Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,55 @@
#![cfg(test)]
//! Regression coverage for a key held across the sign-in menus.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn held_enter_requires_a_fresh_confirmation_to_save_a_prefilled_api_key() {
let (mut widget, _home) = tests::widget_forced_chatgpt().await;
widget.auth_config.forced_login_method = None;
let enter = |kind| KeyEvent::new_with_kind(KeyCode::Enter, KeyModifiers::NONE, kind);
widget.handle_key_event(KeyCode::Up.into());
widget.handle_key_event(enter(KeyEventKind::Press));
widget.handle_key_event(enter(KeyEventKind::Repeat));
widget.handle_key_event(enter(KeyEventKind::Press));
widget.handle_key_event(KeyCode::Down.into());
widget.handle_key_event(enter(KeyEventKind::Repeat));
assert_eq!(widget.highlighted_mode, SignInOption::ApiKey);
assert!(matches!(
*widget.sign_in_state.read().unwrap(),
SignInState::PickMode
));
widget.handle_key_event(enter(KeyEventKind::Release));
widget.handle_key_event(enter(KeyEventKind::Press));
{
let mut state = widget.sign_in_state.write().unwrap();
let SignInState::ApiKeyEntry(input) = &mut *state else {
panic!("expected API key entry");
};
input.value = "test-api-key".into();
input.prepopulated_from_env = true;
}
let (request_frame, mut frames) = FrameRequester::test_channel();
widget.request_frame = request_frame;
widget.handle_key_event(enter(KeyEventKind::Press));
widget.handle_key_event(enter(KeyEventKind::Repeat));
widget.handle_key_event(KeyCode::Left.into());
widget.handle_key_event(enter(KeyEventKind::Repeat));
assert_eq!(
frames.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty)
);
widget.handle_key_event(enter(KeyEventKind::Release));
widget.handle_key_event(enter(KeyEventKind::Press));
frames.try_recv().expect("fresh Enter should start saving");
frames.recv().await.expect("API key save should finish");
assert!(matches!(
*widget.sign_in_state.read().unwrap(),
SignInState::ApiKeyConfigured
));
}

View File

@@ -0,0 +1,313 @@
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::LoginAccountParams;
use codex_app_server_protocol::LoginAccountResponse;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Widget;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Wrap;
use uuid::Uuid;
use crate::motion::MotionMode;
use crate::motion::shimmer_text;
use super::AuthModeWidget;
use super::ContinueWithDeviceCodeState;
use super::SignInState;
use super::cancel_login_attempt;
use super::mark_url_hyperlink;
use super::onboarding_request_id;
pub(super) fn start_headless_chatgpt_login(widget: &mut AuthModeWidget) {
let request_id = Uuid::new_v4().to_string();
*widget.sign_in_state.write().unwrap() =
SignInState::ChatGptDeviceCode(ContinueWithDeviceCodeState::pending(request_id.clone()));
widget.request_frame.schedule_frame();
let request_handle = widget.app_server_request_handle.clone();
let sign_in_state = widget.sign_in_state.clone();
let request_frame = widget.request_frame.clone();
let error = widget.error.clone();
tokio::spawn(async move {
match request_handle
.request_typed::<LoginAccountResponse>(ClientRequest::LoginAccount {
request_id: onboarding_request_id(),
params: LoginAccountParams::ChatgptDeviceCode,
})
.await
{
Ok(LoginAccountResponse::ChatgptDeviceCode {
login_id,
verification_url,
user_code,
}) => {
let updated = set_device_code_state_for_active_attempt(
&sign_in_state,
&request_frame,
&request_id,
ContinueWithDeviceCodeState::ready(
request_id.clone(),
login_id.clone(),
verification_url,
user_code,
),
);
if updated {
*error.write().unwrap() = None;
} else {
cancel_login_attempt(&request_handle, login_id).await;
}
}
Ok(other) => {
let _updated = set_device_code_error_for_active_attempt(
&sign_in_state,
&request_frame,
&error,
&request_id,
format!("Unexpected account/login/start response: {other:?}"),
);
}
Err(err) => {
let _updated = set_device_code_error_for_active_attempt(
&sign_in_state,
&request_frame,
&error,
&request_id,
err.to_string(),
);
}
}
});
}
pub(super) fn render_device_code_login(
widget: &AuthModeWidget,
area: Rect,
buf: &mut Buffer,
state: &ContinueWithDeviceCodeState,
) {
let banner = if state.is_showing_copyable_auth() {
"Finish signing in via your browser"
} else {
"Preparing device code login"
};
let mut spans = vec![" ".into()];
if widget.animations_enabled && !widget.animations_suppressed.get() {
widget
.request_frame
.schedule_frame_in(std::time::Duration::from_millis(100));
spans.extend(shimmer_text(banner, MotionMode::Animated));
} else {
spans.push(banner.into());
}
let mut lines = vec![spans.into(), "".into()];
let verification_url = if let (Some(verification_url), Some(user_code)) =
(&state.verification_url, &state.user_code)
{
lines.push(" 1. Open this link in your browser and sign in".into());
lines.push("".into());
lines.push(Line::from(vec![
" ".into(),
verification_url.as_str().cyan().underlined(),
]));
lines.push("".into());
lines.push(
" 2. Enter this one-time code after you are signed in (expires in 15 minutes)".into(),
);
lines.push("".into());
lines.push(Line::from(vec![
" ".into(),
user_code.as_str().cyan().bold(),
]));
lines.push("".into());
lines.push(
" Continue only if you started this login in Codex. If a website or another person gave you this code, cancel."
.dim()
.into(),
);
lines.push("".into());
Some(verification_url.clone())
} else {
lines.push(" Requesting a one-time code...".dim().into());
lines.push("".into());
None
};
lines.push(Line::from(vec![
" Press ".dim(),
widget.cancel_binding().into(),
" to cancel".dim(),
]));
Paragraph::new(lines)
.wrap(Wrap { trim: false })
.render(area, buf);
if let Some(url) = &verification_url {
mark_url_hyperlink(buf, area, url);
}
}
fn device_code_attempt_matches(state: &SignInState, request_id: &str) -> bool {
matches!(
state,
SignInState::ChatGptDeviceCode(state) if state.request_id == request_id
)
}
fn set_device_code_state_for_active_attempt(
sign_in_state: &std::sync::Arc<std::sync::RwLock<SignInState>>,
request_frame: &crate::tui::FrameRequester,
request_id: &str,
next_state: ContinueWithDeviceCodeState,
) -> bool {
let mut guard = sign_in_state.write().unwrap();
if !device_code_attempt_matches(&guard, request_id) {
return false;
}
*guard = SignInState::ChatGptDeviceCode(next_state);
drop(guard);
request_frame.schedule_frame();
true
}
fn set_device_code_error_for_active_attempt(
sign_in_state: &std::sync::Arc<std::sync::RwLock<SignInState>>,
request_frame: &crate::tui::FrameRequester,
error: &std::sync::Arc<std::sync::RwLock<Option<String>>>,
request_id: &str,
message: String,
) -> bool {
let mut guard = sign_in_state.write().unwrap();
if !device_code_attempt_matches(&guard, request_id) {
return false;
}
*guard = SignInState::PickMode;
drop(guard);
*error.write().unwrap() = Some(message);
request_frame.schedule_frame();
true
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use std::sync::RwLock;
fn pending_device_code_state(request_id: &str) -> Arc<RwLock<SignInState>> {
Arc::new(RwLock::new(SignInState::ChatGptDeviceCode(
ContinueWithDeviceCodeState::pending(request_id.to_string()),
)))
}
#[test]
fn device_code_attempt_matches_only_for_matching_request_id() {
let state = SignInState::ChatGptDeviceCode(ContinueWithDeviceCodeState::pending(
"request-1".to_string(),
));
assert_eq!(device_code_attempt_matches(&state, "request-1"), true);
assert_eq!(device_code_attempt_matches(&state, "request-2"), false);
assert_eq!(
device_code_attempt_matches(&SignInState::PickMode, "request-1"),
false
);
}
#[test]
fn set_device_code_state_for_active_attempt_updates_only_when_active() {
let request_frame = crate::tui::FrameRequester::test_dummy();
let sign_in_state = pending_device_code_state("request-1");
assert_eq!(
set_device_code_state_for_active_attempt(
&sign_in_state,
&request_frame,
"request-1",
ContinueWithDeviceCodeState::ready(
"request-1".to_string(),
"login-1".to_string(),
"https://example.com/device".to_string(),
"ABCD-EFGH".to_string(),
),
),
true
);
assert!(matches!(
&*sign_in_state.read().unwrap(),
SignInState::ChatGptDeviceCode(state) if state.login_id() == Some("login-1")
));
let sign_in_state = pending_device_code_state("request-2");
assert_eq!(
set_device_code_state_for_active_attempt(
&sign_in_state,
&request_frame,
"request-1",
ContinueWithDeviceCodeState::ready(
"request-1".to_string(),
"login-1".to_string(),
"https://example.com/device".to_string(),
"ABCD-EFGH".to_string(),
),
),
false
);
assert!(matches!(
&*sign_in_state.read().unwrap(),
SignInState::ChatGptDeviceCode(state) if state.login_id.is_none()
));
}
#[test]
fn set_device_code_error_for_active_attempt_updates_only_when_active() {
let request_frame = crate::tui::FrameRequester::test_dummy();
let error = Arc::new(RwLock::new(None));
let sign_in_state = pending_device_code_state("request-1");
assert_eq!(
set_device_code_error_for_active_attempt(
&sign_in_state,
&request_frame,
&error,
"request-1",
"device code unavailable".to_string(),
),
true
);
assert!(matches!(
&*sign_in_state.read().unwrap(),
SignInState::PickMode
));
assert_eq!(
error.read().unwrap().as_deref(),
Some("device code unavailable")
);
let error = Arc::new(RwLock::new(None));
let sign_in_state = pending_device_code_state("request-2");
assert_eq!(
set_device_code_error_for_active_attempt(
&sign_in_state,
&request_frame,
&error,
"request-1",
"device code unavailable".to_string(),
),
false
);
assert!(matches!(
&*sign_in_state.read().unwrap(),
SignInState::ChatGptDeviceCode(_)
));
assert_eq!(*error.read().unwrap(), None);
}
}

View File

@@ -0,0 +1,819 @@
//! Amazon Bedrock credential setup and the startup GovCloud guidance screen.
use super::auth::AuthModeWidget;
use super::auth::SignInState;
use super::auth::onboarding_request_id;
use super::keys;
use super::provider_setup::FieldDisplay;
use super::provider_setup::ProviderInput;
use super::provider_setup::move_provider_field;
use crate::key_hint::KeyBindingListExt;
use crate::wrapping::word_wrap_lines;
use codex_app_server_client::AppServerRequestHandle;
use codex_app_server_protocol::AwsCredentialType;
use codex_app_server_protocol::BedrockAwsProfile;
use codex_app_server_protocol::BedrockCheckGovCloudRequirementsParams;
use codex_app_server_protocol::BedrockCheckGovCloudRequirementsResponse;
use codex_app_server_protocol::BedrockDiscoverParams;
use codex_app_server_protocol::BedrockDiscoverResponse;
use codex_app_server_protocol::BedrockEnvironmentCredential;
use codex_app_server_protocol::BedrockSetupParams;
use codex_app_server_protocol::BedrockSetupResponse;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::LoginAccountParams;
use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::RequestId;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Widget;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
use std::sync::Arc;
use std::sync::PoisonError;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
const GOV_CLOUD_GUIDANCE_URL: &str =
"https://learn.chatgpt.com/docs/enterprise/govcloud-configuration";
#[derive(Clone)]
pub(super) struct BedrockState {
view: BedrockView,
highlighted: usize,
profiles: Vec<BedrockAwsProfile>,
environment_credentials: Vec<BedrockEnvironmentCredential>,
}
#[derive(Clone)]
enum BedrockView {
Discovering(RequestId),
Methods(BedrockMethodList),
ProfileEntry(ProviderInput),
AccessKeyEntry {
values: [ProviderInput; 3],
selected_field: usize,
},
ApiKeyEntry(ProviderInput),
RegionEntry {
credential: BedrockCredential,
value: ProviderInput,
},
EnvironmentInstructions,
Configuring(RequestId),
// Render-clamped scroll offset shared with the auth widget's cloned state.
GovCloudWarning(Arc<AtomicUsize>),
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum BedrockMethodList {
Detected,
All,
}
#[derive(Clone)]
enum BedrockCredential {
Profile(String),
Environment,
AccessKeys {
access_key_id: String,
secret_access_key: String,
session_token: Option<String>,
},
ApiKey(String),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BedrockMethod {
Profile(usize),
Environment,
OtherMethods,
ManualProfile,
AccessKeys,
EnvironmentInstructions,
ApiKey,
}
enum BedrockAction {
BackToAuth,
Configure(BedrockCredential, String),
}
impl BedrockState {
pub(super) fn guidance() -> Self {
Self {
view: BedrockView::GovCloudWarning(Arc::default()),
highlighted: 0,
profiles: Vec::new(),
environment_credentials: Vec::new(),
}
}
pub(super) fn handle_guidance_key_event(&mut self, key_event: &KeyEvent) -> bool {
let BedrockView::GovCloudWarning(scroll) = &self.view else {
return false;
};
let offset = scroll.load(Ordering::Relaxed);
if keys::MOVE_UP.is_pressed(*key_event) {
scroll.store(offset.saturating_sub(1), Ordering::Relaxed);
} else if keys::MOVE_DOWN.is_pressed(*key_event) {
scroll.store(offset.saturating_add(1), Ordering::Relaxed);
}
key_event.kind == KeyEventKind::Press && keys::CONFIRM.is_pressed(*key_event)
}
fn discovering(request_id: RequestId) -> Self {
Self {
view: BedrockView::Discovering(request_id),
highlighted: 0,
profiles: Vec::new(),
environment_credentials: Vec::new(),
}
}
fn discovered(response: BedrockDiscoverResponse) -> Self {
Self {
view: BedrockView::Methods(BedrockMethodList::Detected),
highlighted: 0,
profiles: response.profiles,
environment_credentials: response.environment_credentials,
}
}
fn methods(&self) -> Vec<BedrockMethod> {
if matches!(self.view, BedrockView::EnvironmentInstructions) {
return vec![BedrockMethod::OtherMethods];
}
let detected = matches!(self.view, BedrockView::Methods(BedrockMethodList::Detected));
if detected && !self.profiles.is_empty() {
let mut methods = (0..self.profiles.len())
.map(BedrockMethod::Profile)
.collect::<Vec<_>>();
if !self.environment_credentials.is_empty() {
methods.push(BedrockMethod::Environment);
}
methods.push(BedrockMethod::OtherMethods);
return methods;
}
if detected && !self.environment_credentials.is_empty() {
return vec![BedrockMethod::Environment, BedrockMethod::OtherMethods];
}
vec![
BedrockMethod::ManualProfile,
BedrockMethod::AccessKeys,
BedrockMethod::EnvironmentInstructions,
BedrockMethod::ApiKey,
]
}
pub(super) fn is_text_entry_active(&self) -> bool {
matches!(
self.view,
BedrockView::ProfileEntry(_)
| BedrockView::AccessKeyEntry { .. }
| BedrockView::ApiKeyEntry(_)
| BedrockView::RegionEntry { .. }
)
}
pub(super) fn is_configuring(&self, id: &RequestId) -> bool {
matches!(&self.view, BedrockView::Configuring(active) if active == id)
}
pub(super) fn active_input_mut(&mut self) -> Option<&mut ProviderInput> {
match &mut self.view {
BedrockView::ProfileEntry(value)
| BedrockView::ApiKeyEntry(value)
| BedrockView::RegionEntry { value, .. } => Some(value),
BedrockView::AccessKeyEntry {
values,
selected_field,
} => Some(&mut values[*selected_field]),
_ => None,
}
}
fn enter_region(&mut self, credential: BedrockCredential, value: &str) {
self.view = BedrockView::RegionEntry {
credential,
value: value.into(),
};
}
fn select_method(&mut self, method: BedrockMethod) -> Option<BedrockAction> {
self.highlighted = 0;
match method {
BedrockMethod::Profile(index) => {
let profile = self.profiles[index].clone();
let credential = BedrockCredential::Profile(profile.name);
if let Some(region) = profile.region {
return Some(BedrockAction::Configure(credential, region));
}
self.enter_region(credential, "");
}
BedrockMethod::Environment => {
let credential = BedrockCredential::Environment;
if let Some(region) = self
.environment_credentials
.iter()
.find_map(|credential| credential.region.clone())
{
return Some(BedrockAction::Configure(credential, region));
}
self.enter_region(credential, "");
}
BedrockMethod::OtherMethods => {
self.view = BedrockView::Methods(BedrockMethodList::All);
}
BedrockMethod::ManualProfile => {
self.view = BedrockView::ProfileEntry(ProviderInput::default());
}
BedrockMethod::AccessKeys => {
self.view = BedrockView::AccessKeyEntry {
values: Default::default(),
selected_field: 0,
};
}
BedrockMethod::EnvironmentInstructions => {
self.view = BedrockView::EnvironmentInstructions;
}
BedrockMethod::ApiKey => {
self.view = BedrockView::ApiKeyEntry(ProviderInput::default());
}
}
None
}
fn handle_key_event(&mut self, key_event: &KeyEvent) -> Option<BedrockAction> {
if keys::CANCEL.is_pressed(*key_event) {
let leave_wizard = matches!(
self.view,
BedrockView::Discovering(_) | BedrockView::Methods(BedrockMethodList::Detected)
);
if leave_wizard {
return Some(BedrockAction::BackToAuth);
}
self.view = BedrockView::Methods(BedrockMethodList::Detected);
self.highlighted = 0;
return None;
}
if matches!(self.view, BedrockView::Configuring(_)) {
return None;
}
if matches!(
self.view,
BedrockView::Methods(_) | BedrockView::EnvironmentInstructions
) {
let methods = self.methods();
if keys::MOVE_UP.is_pressed(*key_event) {
self.highlighted = (self.highlighted + methods.len() - 1) % methods.len();
} else if keys::MOVE_DOWN.is_pressed(*key_event) {
self.highlighted = (self.highlighted + 1) % methods.len();
} else if keys::CONFIRM.is_pressed(*key_event) {
return self.select_method(methods[self.highlighted]);
} else if let KeyCode::Char(digit @ '1'..='9') = key_event.code
&& let Some(method) = methods.get(digit as usize - '1' as usize).copied()
{
return self.select_method(method);
}
return None;
}
if let BedrockView::AccessKeyEntry {
values,
selected_field,
} = &mut self.view
&& move_provider_field(*key_event, selected_field, values.len())
{
return None;
}
if keys::CONFIRM.is_pressed(*key_event) {
return self.confirm_input();
}
if let Some(input) = self.active_input_mut() {
input.input(*key_event);
}
None
}
fn confirm_input(&mut self) -> Option<BedrockAction> {
let credential = match &mut self.view {
BedrockView::ProfileEntry(value) => BedrockCredential::Profile(value.value()?),
BedrockView::ApiKeyEntry(value) => BedrockCredential::ApiKey(value.value()?),
BedrockView::RegionEntry { credential, value } => {
return Some(BedrockAction::Configure(credential.clone(), value.value()?));
}
BedrockView::AccessKeyEntry {
values,
selected_field,
} => {
if *selected_field < 2 {
if values[*selected_field].value().is_some() {
*selected_field += 1;
}
return None;
}
let Some(access_key_id) = values[0].value() else {
*selected_field = 0;
return None;
};
let Some(secret_access_key) = values[1].value() else {
*selected_field = 1;
return None;
};
BedrockCredential::AccessKeys {
access_key_id,
secret_access_key,
session_token: values[2].value(),
}
}
_ => return None,
};
if let BedrockCredential::Profile(profile) = &credential
&& let Some(region) = self.profiles.iter().find_map(|discovered| {
(discovered.name == *profile)
.then(|| discovered.region.clone())
.flatten()
})
{
return Some(BedrockAction::Configure(credential, region));
}
self.enter_region(credential, "");
None
}
pub(super) fn render(&self, area: Rect, buf: &mut Buffer, error: Option<String>) {
if area.width == 0 || area.height == 0 {
return;
}
let mut lines: Vec<Line> = vec![
Line::from(vec!["> ".into(), "Set up Amazon Bedrock".bold()]),
"".into(),
];
let mut footer = Vec::new();
match &self.view {
BedrockView::GovCloudWarning(_) => {
lines = vec!["Using Codex with AWS GovCloud".bold().into(), "".into()];
lines.push(Line::from(vec![
"You are using Codex with AWS GovCloud. Please ensure you or your administrator have read the ".into(),
"application configuration and security guidance"
.cyan()
.underlined(),
" before proceeding.".into(),
]));
footer.push("".into());
footer.push("> Acknowledge".cyan().into());
}
BedrockView::Discovering(_) => {
lines.push(" Checking for existing AWS credentials...".dim().into());
}
BedrockView::Configuring(_) => {
lines.push(" Setting up Amazon Bedrock...".dim().into());
}
BedrockView::Methods(list) => {
if *list == BedrockMethodList::Detected && self.profiles.len() == 1 {
let profile = &self.profiles[0];
lines.push(format!(" AWS profile detected: {}", profile.name).into());
if let Some(region) = &profile.region {
lines.push(format!(" Region: {region}").dim().into());
}
} else if *list == BedrockMethodList::Detected && self.profiles.len() > 1 {
lines.push(" Choose an AWS profile.".into());
} else if *list == BedrockMethodList::Detected
&& !self.environment_credentials.is_empty()
{
lines.push(" AWS credentials detected in the server environment.".into());
} else {
if *list == BedrockMethodList::Detected {
lines.push(" No AWS credentials found.".into());
}
lines.push(" Choose how you authenticate with AWS.".into());
}
lines.push("".into());
self.render_methods(&mut lines);
}
BedrockView::ProfileEntry(value) => {
lines.push(" Enter the name of your AWS profile.".into());
lines.push("".into());
lines.push(value.line(" AWS profile: ", "", FieldDisplay::Focused, area.width));
}
BedrockView::ApiKeyEntry(value) => {
lines.push(" Enter your Amazon Bedrock API key.".into());
lines.push("".into());
lines.push(value.line(
" Bedrock API key: ",
"",
FieldDisplay::FocusedSecret,
area.width,
));
}
BedrockView::RegionEntry { value, .. } => {
lines.push(" Enter the AWS Region to use with Amazon Bedrock.".into());
lines.push("".into());
lines.push(value.line(" AWS Region: ", "", FieldDisplay::Focused, area.width));
}
BedrockView::AccessKeyEntry {
values,
selected_field,
} => {
lines.push(" Enter your AWS access keys.".into());
lines.push("".into());
for (index, label) in [
"AWS access key ID",
"AWS secret access key",
"AWS session token (optional)",
]
.into_iter()
.enumerate()
{
let marker = if index == *selected_field { ">" } else { " " };
let display = match (index == *selected_field, index == 0) {
(true, true) => FieldDisplay::Focused,
(false, true) => FieldDisplay::Unfocused,
(true, false) => FieldDisplay::FocusedSecret,
(false, false) => FieldDisplay::UnfocusedSecret,
};
let line =
values[index].line(&format!("{marker} {label}: "), "", display, area.width);
lines.push(if index == *selected_field {
line.cyan()
} else {
line
});
}
}
BedrockView::EnvironmentInstructions => {
lines.push(
" Export AWS credentials, then run `codex --no-daemon` in that shell.".into(),
);
lines.push("".into());
lines.push(Line::from(vec![
" Setup guide: ".into(),
"https://learn.chatgpt.com/docs/amazon-bedrock"
.cyan()
.underlined(),
]));
lines.push("".into());
self.render_methods(&mut lines);
}
}
if !matches!(self.view, BedrockView::Discovering(_)) {
footer.push("".into());
if !matches!(self.view, BedrockView::Configuring(_)) {
footer.push(Line::from(vec![
" Press ".dim(),
keys::CONFIRM[0].into(),
" to continue".dim(),
]));
}
if !matches!(self.view, BedrockView::GovCloudWarning(_)) {
footer.push(Line::from(vec![
" Press ".dim(),
keys::CANCEL[0].into(),
" to go back".dim(),
]));
}
}
if let Some(error) = error {
footer.push("".into());
footer.push(error.red().into());
}
let mut lines = word_wrap_lines(lines, usize::from(area.width));
let mut footer = word_wrap_lines(footer, usize::from(area.width));
if matches!(self.view, BedrockView::GovCloudWarning(_))
&& lines.len() + footer.len() > usize::from(area.height)
{
footer = vec!["> Acknowledge".cyan().into()];
if area.height > 2 {
footer.push(Line::from(vec![
keys::MOVE_UP[0].into(),
"/".dim(),
keys::MOVE_DOWN[0].into(),
" scroll · ".dim(),
keys::CONFIRM[0].into(),
]));
}
footer = word_wrap_lines(footer, usize::from(area.width));
}
if lines.len() + footer.len() <= usize::from(area.height) || footer.is_empty() {
lines.extend(footer);
Paragraph::new(lines).render(area, buf);
if let BedrockView::GovCloudWarning(scroll) = &self.view {
scroll.store(0, Ordering::Relaxed);
crate::terminal_hyperlinks::mark_underlined_hyperlink(
buf,
area,
GOV_CLOUD_GUIDANCE_URL,
);
}
return;
}
let footer_height = u16::try_from(footer.len())
.unwrap_or(u16::MAX)
.min(area.height.saturating_sub(1));
let content_height = area.height.saturating_sub(footer_height);
let highlighted_row = lines
.iter()
.enumerate()
.skip(1)
.find_map(|(index, line)| {
line.spans
.first()
.is_some_and(|span| span.content.starts_with("> "))
.then_some(index)
})
.unwrap_or_default();
let max_scroll = lines.len().saturating_sub(usize::from(content_height));
let scroll = if let BedrockView::GovCloudWarning(scroll) = &self.view {
let offset = scroll.load(Ordering::Relaxed).min(max_scroll);
scroll.store(offset, Ordering::Relaxed);
offset
} else {
highlighted_row
.saturating_add(2)
.saturating_sub(usize::from(content_height))
.min(max_scroll)
};
let content_area = Rect {
height: content_height,
..area
};
let footer_area = Rect {
y: area.y.saturating_add(content_height),
height: footer_height,
..area
};
Paragraph::new(lines)
.scroll((u16::try_from(scroll).unwrap_or(u16::MAX), 0))
.render(content_area, buf);
Paragraph::new(footer).render(footer_area, buf);
if matches!(self.view, BedrockView::GovCloudWarning(_)) {
crate::terminal_hyperlinks::mark_underlined_hyperlink(
buf,
content_area,
GOV_CLOUD_GUIDANCE_URL,
);
}
}
fn render_methods(&self, lines: &mut Vec<Line<'static>>) {
for (index, method) in self.methods().into_iter().enumerate() {
let (title, description) = match method {
BedrockMethod::Profile(profile_index) => {
let profile = &self.profiles[profile_index];
let title = if self.profiles.len() == 1 {
format!("Continue with {}", profile.name)
} else {
profile.name.clone()
};
let description = if self.profiles.len() == 1 {
"Use your existing AWS credentials".to_string()
} else {
profile.region.clone().unwrap_or_default()
};
(title, description)
}
BedrockMethod::Environment => {
let description = if self.environment_credentials.iter().any(|credential| {
credential.credential_type == AwsCredentialType::BedrockApiKey
}) {
"Use the Bedrock API key from the server environment"
} else {
"Use AWS access keys from the server environment"
};
(
"Continue with detected credentials".to_string(),
description.to_string(),
)
}
BedrockMethod::OtherMethods => (
if matches!(self.view, BedrockView::EnvironmentInstructions) {
"Choose another sign-in method"
} else {
"Other AWS sign-in methods"
}
.to_string(),
if matches!(self.view, BedrockView::EnvironmentInstructions) {
""
} else {
"Use another profile, access keys, environment variables, or a Bedrock API key"
}
.to_string(),
),
BedrockMethod::ManualProfile => (
"AWS profile".to_string(),
"Use AWS SSO or a named profile".to_string(),
),
BedrockMethod::AccessKeys => (
"AWS access keys".to_string(),
"Enter an access key ID and secret access key".to_string(),
),
BedrockMethod::EnvironmentInstructions => (
"Environment variables".to_string(),
"Use AWS credentials exported in your shell".to_string(),
),
BedrockMethod::ApiKey => (
"Bedrock API key".to_string(),
"Enter a Bedrock API key".to_string(),
),
};
let selected = index == self.highlighted;
let marker = if selected { ">" } else { " " };
let title_line = format!("{marker} {}. {title}", index + 1);
lines.push(if selected {
title_line.cyan().into()
} else {
title_line.into()
});
if !description.is_empty()
&& (!matches!(self.view, BedrockView::Methods(BedrockMethodList::Detected))
|| !self.profiles.is_empty()
|| self.environment_credentials.is_empty())
{
lines.push(format!(" {description}").dim().into());
}
lines.push("".into());
}
}
}
pub(crate) async fn check_gov_cloud(request_handle: AppServerRequestHandle) -> bool {
match tokio::time::timeout(
std::time::Duration::from_secs(/*secs*/ 15),
request_handle.request_typed::<BedrockCheckGovCloudRequirementsResponse>(
ClientRequest::BedrockCheckGovCloudRequirements {
request_id: onboarding_request_id(),
params: BedrockCheckGovCloudRequirementsParams {},
},
),
)
.await
{
Ok(Ok(response)) => response.is_gov_cloud,
Ok(Err(_)) | Err(_) => false,
}
}
impl AuthModeWidget {
pub(super) fn start_bedrock_discovery(&mut self) {
let request_id = onboarding_request_id();
*self
.sign_in_state
.write()
.unwrap_or_else(PoisonError::into_inner) =
SignInState::Bedrock(BedrockState::discovering(request_id.clone()));
*self.error.write().unwrap_or_else(PoisonError::into_inner) = None;
self.request_frame.schedule_frame();
let request_handle = self.app_server_request_handle.clone();
let sign_in_state = self.sign_in_state.clone();
let error = self.error.clone();
let request_frame = self.request_frame.clone();
tokio::spawn(async move {
let result = request_handle
.request_typed::<BedrockDiscoverResponse>(ClientRequest::BedrockDiscover {
request_id: request_id.clone(),
params: BedrockDiscoverParams {},
})
.await;
let mut guard = sign_in_state
.write()
.unwrap_or_else(PoisonError::into_inner);
if !matches!(
&*guard,
SignInState::Bedrock(state)
if matches!(&state.view, BedrockView::Discovering(active_request_id)
if *active_request_id == request_id)
) {
return;
}
match result {
Ok(response) => {
*guard = SignInState::Bedrock(BedrockState::discovered(response));
}
Err(err) => {
*guard =
SignInState::Bedrock(BedrockState::discovered(BedrockDiscoverResponse {
profiles: Vec::new(),
environment_credentials: Vec::new(),
}));
*error.write().unwrap_or_else(PoisonError::into_inner) =
Some(format!("Unable to check AWS credentials: {err}"));
}
}
drop(guard);
request_frame.schedule_frame();
});
}
pub(super) fn handle_bedrock_key_event(&mut self, key_event: &KeyEvent) -> bool {
{
let mut guard = self
.sign_in_state
.write()
.unwrap_or_else(PoisonError::into_inner);
let SignInState::Bedrock(state) = &mut *guard else {
return false;
};
*self.error.write().unwrap_or_else(PoisonError::into_inner) = None;
match state.handle_key_event(key_event) {
Some(BedrockAction::BackToAuth) => {
*guard = SignInState::PickMode;
}
Some(BedrockAction::Configure(credential, region)) => {
let fallback = state.clone();
drop(guard);
self.start_bedrock_setup(credential, region, fallback);
}
None => {}
}
}
self.request_frame.schedule_frame();
true
}
fn start_bedrock_setup(
&mut self,
credential: BedrockCredential,
region: String,
mut fallback: BedrockState,
) {
fallback.enter_region(credential.clone(), &region);
let mut configuring = fallback.clone();
let request_id = onboarding_request_id();
configuring.view = BedrockView::Configuring(request_id.clone());
*self
.sign_in_state
.write()
.unwrap_or_else(PoisonError::into_inner) = SignInState::Bedrock(configuring);
let request_handle = self.app_server_request_handle.clone();
let active_request_id = request_id.clone();
let request = async move {
let result = match credential {
BedrockCredential::ApiKey(api_key) => request_handle
.request_typed::<LoginAccountResponse>(ClientRequest::LoginAccount {
request_id,
params: LoginAccountParams::AmazonBedrock { api_key, region },
})
.await
.map_err(|error| error.to_string())
.and_then(|response| match response {
LoginAccountResponse::AmazonBedrock {} => Ok(()),
response => Err(format!(
"Unexpected account/login/start response: {response:?}"
)),
}),
BedrockCredential::Profile(profile) => request_handle
.request_typed::<BedrockSetupResponse>(ClientRequest::BedrockSetup {
request_id,
params: BedrockSetupParams::Profile { profile, region },
})
.await
.map(|_| ())
.map_err(|error| error.to_string()),
BedrockCredential::Environment => request_handle
.request_typed::<BedrockSetupResponse>(ClientRequest::BedrockSetup {
request_id,
params: BedrockSetupParams::Environment { region },
})
.await
.map(|_| ())
.map_err(|error| error.to_string()),
BedrockCredential::AccessKeys {
access_key_id,
secret_access_key,
session_token,
} => request_handle
.request_typed::<LoginAccountResponse>(ClientRequest::LoginAccount {
request_id,
params: LoginAccountParams::AmazonBedrockAccessKeys {
access_key_id,
secret_access_key,
session_token,
region,
},
})
.await
.map_err(|error| error.to_string())
.and_then(|response| match response {
LoginAccountResponse::AmazonBedrock {} => Ok(()),
response => Err(format!(
"Unexpected account/login/start response: {response:?}"
)),
}),
};
result.map_err(|err| format!("Unable to set up Amazon Bedrock: {err}"))
};
self.spawn_provider_setup(active_request_id, SignInState::Bedrock(fallback), request);
}
}
#[cfg(test)]
#[path = "bedrock_tests.rs"]
mod tests;

View File

@@ -0,0 +1,561 @@
use super::*;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
#[test]
fn gov_cloud_guidance_requires_acknowledgement() {
let mut state = BedrockState::guidance();
insta::assert_snapshot!("gov_cloud_warning", render_visible(&state));
assert!(!state.handle_guidance_key_event(&KeyEvent::new_with_kind(
KeyCode::Enter,
KeyModifiers::NONE,
KeyEventKind::Repeat,
)));
assert!(state.handle_guidance_key_event(&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)));
let area = Rect::new(0, 0, 72, 24);
let mut buffer = Buffer::empty(area);
state.render(area, &mut buffer, /*error*/ None);
assert!(
buffer
.content
.iter()
.any(|cell| cell.symbol().contains(GOV_CLOUD_GUIDANCE_URL))
);
}
#[test]
fn gov_cloud_guidance_scrolls_in_short_panes() {
let mut state = BedrockState::guidance();
let area = Rect::new(0, 0, 24, 6);
let initial = render_visible_at(&state, area);
insta::assert_snapshot!("gov_cloud_warning_short", initial);
// Even a one-row disclosure viewport must expose every line and the link.
for height in [6, 2] {
let area = Rect::new(0, 0, 24, height);
let mut seen = String::new();
for _ in 0..20 {
let mut buffer = Buffer::empty(area);
state.render(area, &mut buffer, /*error*/ None);
seen.extend(buffer.content.iter().map(ratatui::buffer::Cell::symbol));
assert!(render_visible_at(&state, area).contains("Acknowledge"));
assert!(
!state.handle_guidance_key_event(&KeyEvent::new(KeyCode::Down, KeyModifiers::NONE))
);
}
assert!(seen.contains("Using Codex with AWS"));
assert!(seen.contains("proceeding."));
assert!(seen.contains(GOV_CLOUD_GUIDANCE_URL));
for _ in 0..20 {
state.handle_guidance_key_event(&KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
render_visible_at(&state, area);
}
assert!(render_visible_at(&state, area).starts_with("Using Codex with AWS"));
}
assert_eq!(render_visible_at(&state, area), initial);
state.handle_guidance_key_event(&KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
render_visible(&state);
assert_eq!(render_visible_at(&state, area), initial);
}
fn render_visible(state: &BedrockState) -> String {
render_visible_at(state, Rect::new(0, 0, 72, 24))
}
fn render_visible_at(state: &BedrockState, area: Rect) -> String {
let mut buffer = Buffer::empty(area);
state.render(area, &mut buffer, /*error*/ None);
let mut rows = (area.top()..area.bottom())
.map(|row| {
(area.left()..area.right())
.map(|column| {
crate::terminal_hyperlinks::strip_osc8(buffer[(column, row)].symbol())
})
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>();
while rows.last().is_some_and(String::is_empty) {
rows.pop();
}
rows.join("\n")
}
#[test]
fn discovery_prioritizes_profiles_and_groups_other_sign_in_methods() {
let discovering = BedrockState::discovering(RequestId::Integer(1));
insta::assert_snapshot!(render_visible(&discovering), @r###"
> Set up Amazon Bedrock
Checking for existing AWS credentials...
"###);
let mut configuring = discovering;
configuring.view = BedrockView::Configuring(RequestId::Integer(2));
insta::assert_snapshot!(render_visible(&configuring), @r###"
> Set up Amazon Bedrock
Setting up Amazon Bedrock...
Press esc to go back
"###);
assert!(
configuring
.handle_key_event(&KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))
.is_none()
);
assert!(matches!(
configuring.view,
BedrockView::Methods(BedrockMethodList::Detected)
));
let profile = BedrockAwsProfile {
name: "engineering".to_string(),
region: Some("us-east-2".to_string()),
};
let environment = BedrockEnvironmentCredential {
credential_type: AwsCredentialType::AccessKeys,
region: Some("us-west-2".to_string()),
};
for (profiles, environment_credentials, expected) in [
(
vec![profile.clone()],
vec![environment.clone()],
vec![
BedrockMethod::Profile(0),
BedrockMethod::Environment,
BedrockMethod::OtherMethods,
],
),
(
vec![
profile.clone(),
BedrockAwsProfile {
name: "production".to_string(),
region: Some("us-west-2".to_string()),
},
],
vec![environment.clone()],
vec![
BedrockMethod::Profile(0),
BedrockMethod::Profile(1),
BedrockMethod::Environment,
BedrockMethod::OtherMethods,
],
),
(
Vec::new(),
vec![environment],
vec![BedrockMethod::Environment, BedrockMethod::OtherMethods],
),
(
Vec::new(),
Vec::new(),
vec![
BedrockMethod::ManualProfile,
BedrockMethod::AccessKeys,
BedrockMethod::EnvironmentInstructions,
BedrockMethod::ApiKey,
],
),
] {
let state = BedrockState::discovered(BedrockDiscoverResponse {
profiles,
environment_credentials,
});
assert_eq!(state.methods(), expected);
}
let mut profile_and_bearer = BedrockState::discovered(BedrockDiscoverResponse {
profiles: vec![profile.clone()],
environment_credentials: vec![BedrockEnvironmentCredential {
credential_type: AwsCredentialType::BedrockApiKey,
region: Some("us-east-2".to_string()),
}],
});
assert_eq!(
profile_and_bearer.methods(),
vec![
BedrockMethod::Profile(0),
BedrockMethod::Environment,
BedrockMethod::OtherMethods,
]
);
insta::assert_snapshot!(render_visible(&profile_and_bearer), @r###"
> Set up Amazon Bedrock
AWS profile detected: engineering
Region: us-east-2
> 1. Continue with engineering
Use your existing AWS credentials
2. Continue with detected credentials
Use the Bedrock API key from the server environment
3. Other AWS sign-in methods
Use another profile, access keys, environment variables, or a
Bedrock API key
Press enter to continue
Press esc to go back
"###);
profile_and_bearer.select_method(BedrockMethod::OtherMethods);
assert_eq!(
profile_and_bearer.methods(),
vec![
BedrockMethod::ManualProfile,
BedrockMethod::AccessKeys,
BedrockMethod::EnvironmentInstructions,
BedrockMethod::ApiKey,
]
);
insta::assert_snapshot!(render_visible(&profile_and_bearer), @r"
> Set up Amazon Bedrock
Choose how you authenticate with AWS.
> 1. AWS profile
Use AWS SSO or a named profile
2. AWS access keys
Enter an access key ID and secret access key
3. Environment variables
Use AWS credentials exported in your shell
4. Bedrock API key
Enter a Bedrock API key
Press enter to continue
Press esc to go back
");
let profile_state = BedrockState::discovered(BedrockDiscoverResponse {
profiles: vec![profile],
environment_credentials: Vec::new(),
});
insta::assert_snapshot!(render_visible(&profile_state), @r###"
> Set up Amazon Bedrock
AWS profile detected: engineering
Region: us-east-2
> 1. Continue with engineering
Use your existing AWS credentials
2. Other AWS sign-in methods
Use another profile, access keys, environment variables, or a
Bedrock API key
Press enter to continue
Press esc to go back
"###);
let multiple_profiles = BedrockState::discovered(BedrockDiscoverResponse {
profiles: vec![
BedrockAwsProfile {
name: "engineering".to_string(),
region: Some("us-east-2".to_string()),
},
BedrockAwsProfile {
name: "production".to_string(),
region: Some("us-west-2".to_string()),
},
],
environment_credentials: Vec::new(),
});
insta::assert_snapshot!(render_visible(&multiple_profiles), @r###"
> Set up Amazon Bedrock
Choose an AWS profile.
> 1. engineering
us-east-2
2. production
us-west-2
3. Other AWS sign-in methods
Use another profile, access keys, environment variables, or a
Bedrock API key
Press enter to continue
Press esc to go back
"###);
let environment_state = BedrockState::discovered(BedrockDiscoverResponse {
profiles: Vec::new(),
environment_credentials: vec![BedrockEnvironmentCredential {
credential_type: AwsCredentialType::AccessKeys,
region: Some("us-west-2".to_string()),
}],
});
insta::assert_snapshot!(render_visible(&environment_state), @r###"
> Set up Amazon Bedrock
AWS credentials detected in the server environment.
> 1. Continue with detected credentials
2. Other AWS sign-in methods
Press enter to continue
Press esc to go back
"###);
let empty_state = BedrockState::discovered(BedrockDiscoverResponse {
profiles: Vec::new(),
environment_credentials: Vec::new(),
});
insta::assert_snapshot!(render_visible(&empty_state), @r"
> Set up Amazon Bedrock
No AWS credentials found.
Choose how you authenticate with AWS.
> 1. AWS profile
Use AWS SSO or a named profile
2. AWS access keys
Enter an access key ID and secret access key
3. Environment variables
Use AWS credentials exported in your shell
4. Bedrock API key
Enter a Bedrock API key
Press enter to continue
Press esc to go back
");
let mut many_profiles = BedrockState::discovered(BedrockDiscoverResponse {
profiles: (0..12)
.map(|index| BedrockAwsProfile {
name: format!("engineering-{index}"),
region: Some("us-east-2".to_string()),
})
.collect(),
environment_credentials: Vec::new(),
});
many_profiles.highlighted = many_profiles.methods().len() - 1;
let area = Rect::new(0, 0, 72, 10);
let mut buffer = Buffer::empty(area);
many_profiles.render(area, &mut buffer, /*error*/ None);
let visible = (area.top()..area.bottom())
.flat_map(|row| (area.left()..area.right()).map(move |column| (column, row)))
.map(|position| buffer[position].symbol())
.collect::<String>();
assert!(visible.contains("Other AWS sign-in methods"));
assert!(visible.contains("Press enter to continue"));
assert!(visible.contains("Press esc to go back"));
let narrow_area = Rect::new(0, 0, 24, 12);
let mut narrow_buffer = Buffer::empty(narrow_area);
empty_state.render(
narrow_area,
&mut narrow_buffer,
Some("AWS credentials unavailable in this terminal".to_string()),
);
let narrow_visible = (narrow_area.top()..narrow_area.bottom())
.map(|row| {
(narrow_area.left()..narrow_area.right())
.map(|column| narrow_buffer[(column, row)].symbol())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n");
assert!(narrow_visible.contains("Press enter to"));
assert!(narrow_visible.contains("continue"));
assert!(narrow_visible.contains("Press esc to go back"));
assert!(narrow_visible.contains("AWS credentials"));
assert!(narrow_visible.contains("unavailable"));
}
#[test]
fn credential_entries_share_region_and_keep_aws_secrets_hidden() {
for (profiles, environment_credentials, method) in [
(
vec![BedrockAwsProfile {
name: "engineering".to_string(),
region: None,
}],
Vec::new(),
BedrockMethod::Profile(0),
),
(
Vec::new(),
vec![BedrockEnvironmentCredential {
credential_type: AwsCredentialType::AccessKeys,
region: None,
}],
BedrockMethod::Environment,
),
] {
let mut state = BedrockState::discovered(BedrockDiscoverResponse {
profiles,
environment_credentials,
});
state.select_method(method);
assert!(matches!(&state.view, BedrockView::RegionEntry { .. }));
assert!(state.is_text_entry_active());
}
let mut access_keys = BedrockState::discovered(BedrockDiscoverResponse {
profiles: Vec::new(),
environment_credentials: Vec::new(),
});
access_keys.view = BedrockView::AccessKeyEntry {
values: [
"AKIAEXAMPLE".into(),
"secret-value".into(),
"session-value".into(),
],
selected_field: 1,
};
let visible = render_visible(&access_keys);
insta::assert_snapshot!(visible, @r###"
> Set up Amazon Bedrock
Enter your AWS access keys.
AWS access key ID: AKIAEXAMPLE
> AWS secret access key: •••••••••••e
AWS session token (optional): •••••••••••••
Press enter to continue
Press esc to go back
"###);
assert!(visible.contains("AKIAEXAMPLE"));
assert!(visible.contains("AWS secret access key: •••••••••••e"));
assert!(!visible.contains("secret-value"));
assert!(!visible.contains("session-value"));
access_keys.handle_key_event(&KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
assert!(render_visible(&access_keys).contains("AWS secret access key: ••••••••••••x"));
access_keys.handle_key_event(&KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
let visible = render_visible(&access_keys);
insta::assert_snapshot!(visible, @r###"
> Set up Amazon Bedrock
Enter your AWS access keys.
AWS access key ID: AKIAEXAMPLE
AWS secret access key: •••••••••••••
> AWS session token (optional): ••••••••••••e
Press enter to continue
Press esc to go back
"###);
assert!(!visible.contains("secret-value"));
assert!(!visible.contains("session-value"));
access_keys.view = BedrockView::ApiKeyEntry("old-key".into());
access_keys.handle_key_event(&KeyEvent::new(KeyCode::Home, KeyModifiers::NONE));
for _ in 0..3 {
access_keys.handle_key_event(&KeyEvent::new(KeyCode::Right, KeyModifiers::NONE));
}
access_keys.handle_key_event(&KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
access_keys.active_input_mut().unwrap().paste("bedrock-api");
assert_eq!(
access_keys.active_input_mut().unwrap().value().as_deref(),
Some("bedrock-api-key")
);
access_keys.handle_key_event(&KeyEvent::new(KeyCode::End, KeyModifiers::NONE));
let visible = render_visible(&access_keys);
insta::assert_snapshot!(visible, @r###"
> Set up Amazon Bedrock
Enter your Amazon Bedrock API key.
Bedrock API key: ••••••••••••••y
Press enter to continue
Press esc to go back
"###);
assert!(!visible.contains("bedrock-api-key"));
access_keys.handle_key_event(&KeyEvent::new(KeyCode::Char('z'), KeyModifiers::NONE));
assert!(render_visible(&access_keys).contains("Bedrock API key: •••••••••••••••z"));
access_keys.view = BedrockView::ProfileEntry("engineering".into());
insta::assert_snapshot!(render_visible(&access_keys), @r###"
> Set up Amazon Bedrock
Enter the name of your AWS profile.
AWS profile: engineering
Press enter to continue
Press esc to go back
"###);
access_keys.enter_region(BedrockCredential::Environment, "us-west-1");
insta::assert_snapshot!(render_visible(&access_keys), @r###"
> Set up Amazon Bedrock
Enter the AWS Region to use with Amazon Bedrock.
AWS Region: us-west-1
Press enter to continue
Press esc to go back
"###);
access_keys.view = BedrockView::EnvironmentInstructions;
insta::assert_snapshot!(render_visible(&access_keys), @r###"
> Set up Amazon Bedrock
Export AWS credentials, then run `codex --no-daemon` in that shell.
Setup guide: https://learn.chatgpt.com/docs/amazon-bedrock
> 1. Choose another sign-in method
Press enter to continue
Press esc to go back
"###);
for view in [
BedrockView::ProfileEntry(ProviderInput::default()),
BedrockView::ApiKeyEntry(ProviderInput::default()),
BedrockView::RegionEntry {
credential: BedrockCredential::Environment,
value: ProviderInput::default(),
},
BedrockView::AccessKeyEntry {
values: Default::default(),
selected_field: 0,
},
] {
access_keys.view = view;
assert!(access_keys.is_text_entry_active());
}
for credential in [
BedrockCredential::Profile("engineering".to_string()),
BedrockCredential::Environment,
BedrockCredential::AccessKeys {
access_key_id: "AKIAEXAMPLE".to_string(),
secret_access_key: "secret-value".to_string(),
session_token: None,
},
BedrockCredential::ApiKey("bedrock-api-key".to_string()),
] {
access_keys.enter_region(credential, "us-west-1");
assert!(matches!(
&access_keys.view,
BedrockView::RegionEntry { value, .. } if value.value().as_deref() == Some("us-west-1")
));
}
}

View File

@@ -0,0 +1,152 @@
//! Folder consent for startup and task navigation.
//! Local daemon resumes recheck folders changed during consent. Remote checks
//! retain their existing explicit-cwd scope until authoritative roots are available.
use super::OnboardingResult;
use super::OnboardingScreen;
use super::Step;
use super::run_onboarding_screen;
use crate::AppServerTarget;
use crate::app_server_session::AppServerSession;
use crate::config_update::ProjectTrustHost;
use crate::config_update::read_remote_project_trust;
use crate::legacy_core::config::Config;
use crate::onboarding::trust_directory::TrustCancelAction;
use crate::onboarding::trust_directory::TrustDirectorySelection;
use crate::onboarding::trust_directory::TrustDirectoryWidget;
use crate::startup_draft::StartupDraftPump;
use crate::tui::Tui;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::Thread;
use codex_app_server_protocol::ThreadReadParams;
use codex_app_server_protocol::ThreadReadResponse;
use codex_protocol::config_types::TrustLevel;
use color_eyre::eyre::Result;
use std::collections::VecDeque;
use std::path::Path;
use uuid::Uuid;
#[derive(Clone, Copy, Default)]
pub(crate) struct DirectoryTrustOptions<'a> {
pub resumed_thread: Option<&'a Thread>,
pub cancel: Option<TrustCancelAction>,
}
pub(crate) async fn check_directory_trust(
tui: &mut Tui,
app_server: &AppServerSession,
config: &Config,
target: &AppServerTarget,
cwd: &Path,
options: DirectoryTrustOptions<'_>,
mut startup_draft: Option<&mut StartupDraftPump>,
) -> Result<OnboardingResult> {
let DirectoryTrustOptions {
resumed_thread,
cancel,
} = options;
let connected = !matches!(target, AppServerTarget::Embedded);
let mut consent = OnboardingResult::default();
// Another client can load the saved task while consent is pending. Check both folders.
let saved_cwd = resumed_thread
.filter(|thread| {
matches!(target, AppServerTarget::LocalDaemon { .. }) && thread.cwd.as_path() != cwd
})
.map(|thread| thread.cwd.as_path());
let mut pending_cwds: VecDeque<_> = std::iter::once(cwd)
.chain(saved_cwd)
.map(Path::to_path_buf)
.collect();
let mut checked_cwds = Vec::new();
while let Some(cwd) = pending_cwds.pop_front() {
if checked_cwds.contains(&cwd) {
continue;
}
checked_cwds.push(cwd.clone());
let cwd = cwd.as_path();
let host = if !target.uses_remote_workspace() {
ProjectTrustHost::Local
} else {
ProjectTrustHost::Remote
};
let lookup = read_remote_project_trust(app_server.request_handle(), cwd, host);
let project = if let Some(draft) = startup_draft.as_deref_mut() {
draft.run_until(tui, lookup).await??
} else {
lookup.await?
};
let Some(project) = project else {
continue;
};
// Remote connections retain the existing behavior for saved untrusted folders.
if target.uses_remote_workspace() && project.trust_level == Some(TrustLevel::Untrusted) {
continue;
}
if cancel == Some(TrustCancelAction::CurrentTask)
&& project.trust_level == Some(TrustLevel::Untrusted)
&& !config.active_project.is_untrusted()
{
color_eyre::eyre::bail!(
"Folder trust changed. Reopen the destination with its restricted settings."
);
}
let remote_trust_key =
connected.then(|| project.trust_target.to_string_lossy().into_owned());
if let Some(draft) = startup_draft.as_deref_mut() {
draft.flush_pending_events(tui).await?;
}
let screen = OnboardingScreen {
request_frame: tui.frame_requester(),
steps: vec![Step::TrustDirectory(TrustDirectoryWidget {
restricted: project.trust_level == Some(TrustLevel::Untrusted),
existing_task: connected && resumed_thread.is_some(),
cancel: cancel.unwrap_or(TrustCancelAction::AgentsOverview),
cwd: project.cwd,
trust_target: project.trust_target,
show_windows_create_sandbox_hint: false,
should_quit: false,
selection: None,
highlighted: TrustDirectorySelection::Trust,
error: None,
})],
remote_trust_key,
is_done: false,
should_exit: false,
};
let result = run_onboarding_screen(
screen,
Some(app_server.request_handle()),
/*app_server*/ None,
tui,
)
.await?;
tui.terminal.clear()?;
tui.frame_requester().schedule_frame();
if result.should_exit {
return Ok(result);
}
consent.directory_trust_persisted |= result.directory_trust_persisted;
if matches!(target, AppServerTarget::LocalDaemon { .. })
&& let Some(thread) = resumed_thread
{
// Another client may have reopened this task in a different folder during consent.
let request_handle = app_server.request_handle();
let recheck = request_handle.request_typed(ClientRequest::ThreadRead {
request_id: RequestId::String(format!("tui-trust-recheck-{}", Uuid::new_v4())),
params: ThreadReadParams {
thread_id: thread.id.clone(),
include_turns: false,
},
});
let latest: ThreadReadResponse = if let Some(draft) = startup_draft.as_deref_mut() {
draft.run_until(tui, recheck).await??
} else {
recheck.await?
};
pending_cwds.push_back(latest.thread.cwd.to_path_buf());
}
}
Ok(consent)
}

View File

@@ -0,0 +1,290 @@
//! Gateway sign-in uses the settings picker and form. Creating a gateway returns to the
//! picker; only explicitly selecting a saved provider completes sign-in.
use super::auth::AuthModeWidget;
use super::auth::SignInState;
use super::keys;
use super::provider_setup::ProviderInput;
use crate::app::provider::CREATE_CUSTOM_PROVIDER;
use crate::app::provider::Draft;
use crate::app::provider::ProviderForm;
use crate::app::provider::provider_item;
use crate::app::provider::rpc;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::BottomPaneView;
use crate::bottom_pane::ListSelectionView;
use crate::bottom_pane::SelectionItem;
use crate::bottom_pane::SelectionViewParams;
use crate::bottom_pane::popup_consts::accept_cancel_hint_line;
use crate::key_hint::KeyBindingListExt;
use crate::keymap::ListAction;
use crate::keymap::RuntimeKeymap;
use crate::render::renderable::Renderable;
use codex_app_server_client::AppServerRequestHandle;
use codex_app_server_protocol::ModelProviderConfigWriteParams;
use codex_app_server_protocol::ModelProviderListResponse;
use codex_app_server_protocol::ProviderSettings;
use codex_app_server_protocol::WriteStatus;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use futures::future::LocalBoxFuture;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Widget;
use tokio::sync::mpsc::unbounded_channel;
pub(super) const USE_CUSTOM_PROVIDER: &str = "Use a custom provider or gateway";
// Requests stay on the onboarding thread so a redraw can stop polling without losing the reply.
pub(super) enum GatewayStep {
Loading(LocalBoxFuture<'static, Self>),
LoadError(Box<ListSelectionView>),
Picking(Box<Picker>),
Editing {
picker: Box<Picker>,
form: Box<ProviderForm>,
},
Saving(LocalBoxFuture<'static, Self>),
Selecting(LocalBoxFuture<'static, Result<String, Self>>),
}
impl GatewayStep {
fn load(handle: AppServerRequestHandle, notice: Option<String>) -> Self {
Self::Loading(Box::pin(async move {
match rpc::list_providers(&handle).await {
Ok(mut page) if page.can_change_default => {
page.data
.retain(|p| matches!(p.settings, ProviderSettings::CustomGateway { .. }));
Self::Picking(Box::new(Picker::new(page, /*selected*/ None, notice)))
}
Ok(_) => Self::load_error(
"The default provider is set by configuration policy or a launch override."
.into(),
),
Err(message) => Self::load_error(message),
}
}))
}
fn load_error(message: String) -> Self {
let (tx, _) = unbounded_channel();
Self::LoadError(Box::new(ListSelectionView::new(
crate::app::provider::load_error(USE_CUSTOM_PROVIDER, message),
AppEventSender::new(tx),
RuntimeKeymap::defaults().list,
)))
}
fn save(
handle: AppServerRequestHandle,
picker: Box<Picker>,
mut form: Box<ProviderForm>,
params: ModelProviderConfigWriteParams,
) -> Self {
GatewayStep::Saving(Box::pin(async move {
match rpc::write_provider(&handle, params).await {
Ok(rpc::ProviderWrite::Saved(provider)) => {
let mut page = picker.page;
let selected = page.data.len();
page.data.push(provider);
GatewayStep::Picking(Box::new(Picker::new(
page,
Some(selected),
/*notice*/ None,
)))
}
Ok(rpc::ProviderWrite::UnconfirmedCreate) => {
GatewayStep::load(handle, Some(rpc::UNCONFIRMED_CREATE.into()))
}
Err(message) => {
form.error = Some(message);
GatewayStep::Editing { picker, form }
}
}
}))
}
pub(super) fn active_input_mut(&mut self) -> Option<&mut ProviderInput> {
match self {
Self::Editing { form, .. } => form.active_input_mut(),
_ => None,
}
}
pub(super) fn is_text_entry_active(&self) -> bool {
matches!(self, Self::Editing { form, .. } if form.active_input().is_some())
}
pub(super) fn render(&self, area: Rect, buf: &mut Buffer) {
match self {
Self::Loading(_) => Widget::render(Line::from("Loading gateways…".dim()), area, buf),
Self::Editing { form, .. } => form.render(area, buf),
Self::Saving(_) | Self::Selecting(_) => {
Widget::render(Line::from("Saving gateway settings…".dim()), area, buf)
}
Self::LoadError(list) => list.render(area, buf),
Self::Picking(picker) => picker.list.render(area, buf),
}
}
}
pub(super) struct Picker {
page: ModelProviderListResponse,
list: ListSelectionView,
}
impl Picker {
fn new(
page: ModelProviderListResponse,
selected: Option<usize>,
notice: Option<String>,
) -> Self {
let mut items: Vec<_> = page
.data
.iter()
.map(|p| provider_item(p, &page.default_provider_id))
.collect();
let keymap = RuntimeKeymap::defaults().list;
let hint = |accept| {
accept_cancel_hint_line(
keymap.primary_hint(ListAction::Accept),
accept,
keymap.primary_hint(ListAction::Cancel),
"to go back",
)
};
items.push(SelectionItem {
name: CREATE_CUSTOM_PROVIDER.into(),
footer_hint: Some(hint("to create")),
..Default::default()
});
// Like the other startup pickers, consume the selection directly before the app event loop exists.
let (tx, _) = unbounded_channel();
let list = ListSelectionView::new(
SelectionViewParams {
title: Some(USE_CUSTOM_PROVIDER.into()),
footer_hint: Some(hint("to use as default")),
footer_note: notice.map(Into::into),
initial_selected_idx: selected,
auto_number_shortcuts: false,
items,
..Default::default()
},
AppEventSender::new(tx),
keymap,
);
Self { page, list }
}
fn activate(self: Box<Self>, index: usize, handle: AppServerRequestHandle) -> GatewayStep {
let Some(provider) = self.page.data.get(index) else {
let form = ProviderForm::new(
Draft::new(/*provider*/ None, &self.page.data),
/*error*/ None,
);
return GatewayStep::Editing {
picker: self,
form: Box::new(form),
};
};
let id = provider.id.clone();
GatewayStep::Selecting(Box::pin(async move {
let message = match rpc::set_default_provider(&handle, &id).await {
Ok(response) => match response.status {
WriteStatus::Ok => return Ok(id),
WriteStatus::OkOverridden => rpc::override_reason(response),
},
Err(err) => err.to_string(),
};
Err(GatewayStep::Picking(Box::new(Picker::new(
self.page,
Some(index),
Some(message),
))))
}))
}
}
impl AuthModeWidget {
pub(super) fn start_gateway_picker(&mut self) {
self.set_error(/*message*/ None);
self.gateway = Some(GatewayStep::load(
self.app_server_request_handle.clone(),
/*notice*/ None,
));
self.request_frame.schedule_frame();
}
pub(super) async fn advance_gateway_request(&mut self) {
self.gateway = match &mut self.gateway {
Some(GatewayStep::Loading(request) | GatewayStep::Saving(request)) => {
Some(request.await)
}
Some(GatewayStep::Selecting(request)) => match request.await {
Ok(id) => {
*self
.sign_in_state
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
SignInState::GatewaySelected(id);
None
}
Err(picker) => Some(picker),
},
None
| Some(
GatewayStep::Picking(_) | GatewayStep::LoadError(_) | GatewayStep::Editing { .. },
) => std::future::pending().await,
};
self.request_frame.schedule_frame();
}
pub(super) fn handle_gateway_key_event(&mut self, key: KeyEvent) -> bool {
let Some(step) = self.gateway.take() else {
return false;
};
self.gateway = match step {
GatewayStep::Loading(_) | GatewayStep::Picking(_) | GatewayStep::LoadError(_)
if keys::CANCEL.is_pressed(key) =>
{
None
}
GatewayStep::Editing { picker, .. } if keys::CANCEL.is_pressed(key) => {
Some(GatewayStep::Picking(picker))
}
GatewayStep::Editing { picker, mut form } => {
if let Some(params) = form.input(key) {
self.guard_activation(key);
let handle = self.app_server_request_handle.clone();
Some(GatewayStep::save(handle, picker, form, params))
} else {
Some(GatewayStep::Editing { picker, form })
}
}
GatewayStep::LoadError(mut view) => {
view.handle_key_event(key);
if view.take_last_selected_index().is_some() {
self.guard_activation(key);
None
} else {
Some(GatewayStep::LoadError(view))
}
}
GatewayStep::Picking(mut picker)
if key.kind == KeyEventKind::Press || !keys::CONFIRM.is_pressed(key) =>
{
picker.list.handle_key_event(key);
if let Some(index) = picker.list.take_last_selected_index() {
self.guard_activation(key);
Some(picker.activate(index, self.app_server_request_handle.clone()))
} else {
Some(GatewayStep::Picking(picker))
}
}
step => Some(step),
};
self.request_frame.schedule_frame();
true
}
}

View File

@@ -0,0 +1,172 @@
//! Finish authentication against the embedded server running the selected gateway.
use super::auth::AuthModeWidget;
use super::auth::SignInState;
use super::auth::onboarding_request_id;
use super::onboarding_screen::OnboardingScreen;
use super::onboarding_screen::OnboardingScreenArgs;
use super::onboarding_screen::run_onboarding_screen;
use crate::AppServerTarget;
use crate::app_server_session::AppServerSession;
use crate::get_login_status;
use crate::legacy_core::config::Config;
use crate::should_show_login_screen;
use crate::startup_draft::StartupCancelled;
use crate::tui::Tui;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::GatewayOAuthCancelResponse;
use codex_app_server_protocol::GatewayOAuthChangedNotification;
use codex_app_server_protocol::GatewayOAuthLoginResponse;
use codex_app_server_protocol::GatewayOAuthReadResponse;
use codex_app_server_protocol::GatewayOAuthStatus;
use codex_protocol::config_types::ForcedLoginMethod;
use color_eyre::Result;
use color_eyre::eyre::OptionExt;
pub(crate) async fn authenticate_gateway(
tui: &mut Tui,
server: &mut AppServerSession,
config: &Config,
) -> Result<()> {
let (login_status, account) = get_login_status(server).await?;
let primary_login = should_show_login_screen(login_status, account.requires_openai_auth);
// Some gateways require both credentials. The primary login must finish first.
for login in [Login::Primary, Login::GatewayOAuth] {
match login {
Login::Primary if !primary_login => continue,
Login::GatewayOAuth if config.model_provider.gateway_oauth.is_none() => continue,
Login::GatewayOAuth | Login::Primary => {}
}
let handle = server.request_handle();
let mut screen = OnboardingScreen::new(
tui,
OnboardingScreenArgs {
show_login_screen: true,
gateway_setup_enabled: false,
gcp_setup_enabled: false,
bedrock_setup_enabled: false,
show_trust_screen: false,
remote_project_trust: None,
login_status,
app_server_target: AppServerTarget::Embedded,
app_server_request_handle: Some(handle.clone()),
config: config.clone(),
},
)
.await;
let widget = screen
.auth_widget_mut()
.ok_or_eyre("The gateway login screen is unavailable.")?;
match login {
Login::Primary
if widget
.auth_config
.is_login_method_allowed(ForcedLoginMethod::Chatgpt) =>
{
widget.start_chatgpt_login();
}
Login::Primary => widget.start_api_key_entry(),
Login::GatewayOAuth => widget.start_gateway_oauth(config.model_provider_id.clone()),
}
if run_onboarding_screen(screen, Some(handle), Some(server), tui)
.await?
.should_exit
{
if matches!(login, Login::GatewayOAuth) {
let _ = server
.request_handle()
.request_typed::<GatewayOAuthCancelResponse>(
ClientRequest::GatewayOAuthCancel {
request_id: onboarding_request_id(),
params: None,
},
)
.await;
}
return Err(
std::io::Error::new(std::io::ErrorKind::Interrupted, StartupCancelled).into(),
);
}
}
Ok(())
}
enum Login {
Primary,
GatewayOAuth,
}
impl AuthModeWidget {
pub(super) fn start_gateway_oauth(&mut self, provider_id: String) {
*self
.sign_in_state
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = SignInState::GatewayOAuth {
provider_id: provider_id.clone(),
url: None,
};
let state = self.sign_in_state.clone();
let frame = self.request_frame.clone();
let handle = self.app_server_request_handle.clone();
tokio::spawn(async move {
let result: Result<()> = async {
let status = handle
.request_typed::<GatewayOAuthReadResponse>(ClientRequest::GatewayOAuthRead {
request_id: onboarding_request_id(),
params: None,
})
.await?;
color_eyre::eyre::ensure!(
status.provider_id == provider_id,
"The selected gateway changed during sign-in."
);
if status.required && status.status != Some(GatewayOAuthStatus::Succeeded) {
handle
.request_typed::<GatewayOAuthLoginResponse>(
ClientRequest::GatewayOAuthLogin {
request_id: onboarding_request_id(),
params: None,
},
)
.await?;
}
Ok(())
}
.await;
*state
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = match result {
Ok(()) => SignInState::GatewayConfigured,
Err(err) => SignInState::GatewayOAuthFailed {
provider_id,
message: err.to_string(),
},
};
frame.schedule_frame();
});
}
pub(super) fn on_gateway_oauth_changed(
&mut self,
notification: GatewayOAuthChangedNotification,
) {
let Some(auth_url) = notification.auth_url else {
return;
};
let mut state = self
.sign_in_state
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let SignInState::GatewayOAuth { provider_id, url } = &mut *state
&& notification.provider_id == *provider_id
&& url.as_ref() != Some(&auth_url)
{
*url = Some(auth_url.clone());
drop(state);
self.request_frame.schedule_frame();
tokio::task::spawn_blocking(move || {
let _ = webbrowser::open(&auth_url);
});
}
}
}

View File

@@ -0,0 +1,196 @@
#![cfg(test)]
use super::*;
use crate::app::provider::rpc::list_providers;
use crate::app::provider::rpc::write_provider;
use codex_app_server_protocol::CustomGatewaySettingsParams;
use codex_app_server_protocol::ProviderSettingsPatch;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use serde_json::json;
fn screen(widget: &AuthModeWidget, height: u16) -> String {
let area = Rect::new(0, 0, 72, height);
let mut terminal = crate::custom_terminal::Terminal::with_options(
crate::test_backend::VT100Backend::new(area.width, area.height),
)
.unwrap();
terminal.set_viewport_area(area);
terminal
.draw(|frame| widget.render_ref(area, frame.buffer_mut()))
.unwrap();
terminal
.backend()
.to_string()
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n")
}
#[tokio::test]
async fn select_a_saved_gateway_during_sign_in() -> color_eyre::Result<()> {
let (mut widget, home) = super::tests::widget_forced_chatgpt().await;
widget.auth_config.forced_login_method = None;
widget.bedrock_setup_enabled = true;
widget.gcp_setup_enabled = true;
widget.gateway_setup_enabled = true;
widget.handle_key_event(KeyCode::Char('3').into());
insta::assert_snapshot!("gateway_sign_in_menu", screen(&widget, /*height*/ 8));
widget.handle_key_event(KeyCode::Char('4').into());
widget.advance_gateway_request().await;
insta::assert_snapshot!("gateway_empty_picker", screen(&widget, /*height*/ 8));
widget.handle_key_event(KeyCode::Esc.into());
let managed = home.path().join("managed_config.toml");
std::fs::write(&managed, "model_provider = 'openai'")?;
widget.handle_key_event(KeyCode::Char('4').into());
widget.advance_gateway_request().await;
let error = screen(&widget, /*height*/ 8);
assert!(error.contains("configuration policy"));
insta::assert_snapshot!("gateway_load_error", error);
widget.handle_key_event(KeyCode::Esc.into());
std::fs::remove_file(managed)?;
std::fs::write(
home.path().join("config.toml"),
r#"
[model_providers.office]
name = "Office"
base_url = "https://office.example.test/v1"
wire_api = "responses"
"#,
)?;
widget.handle_key_event(KeyCode::Char('4').into());
widget.advance_gateway_request().await;
insta::assert_snapshot!("gateway_saved_picker", screen(&widget, /*height*/ 8));
widget.handle_key_event(KeyCode::Enter.into());
widget.advance_gateway_request().await;
assert!(matches!(widget.get_step_state(), StepState::Complete));
insta::assert_snapshot!(screen(&widget, /*height*/ 4), @"✓ Custom provider configured");
let saved: toml::Value =
toml::from_str(&std::fs::read_to_string(home.path().join("config.toml"))?)?;
assert_eq!(saved["model_provider"].as_str(), Some("office"));
Ok(())
}
#[tokio::test]
async fn create_highlights_the_saved_gateway_until_explicitly_selected() -> color_eyre::Result<()> {
let (mut widget, home) = super::tests::widget_forced_chatgpt().await;
widget.auth_config.forced_login_method = None;
widget.bedrock_setup_enabled = true;
widget.gcp_setup_enabled = true;
widget.gateway_setup_enabled = true;
write_provider(
&widget.app_server_request_handle,
codex_app_server_protocol::ModelProviderConfigWriteParams {
settings: ProviderSettingsPatch::CustomGateway(CustomGatewaySettingsParams {
name: Some("Office".into()),
base_url: Some(Some("https://office.example.test/v1".into())),
..Default::default()
}),
},
)
.await
.map_err(color_eyre::Report::msg)?;
widget.handle_key_event(KeyCode::Char('3').into());
widget.handle_key_event(KeyCode::Char('4').into());
widget.advance_gateway_request().await;
widget.handle_key_event(KeyCode::Down.into());
widget.handle_key_event(KeyCode::Enter.into());
insta::assert_snapshot!(screen(&widget, /*height*/ 12), @r"
Create a custom provider or gateway
› Name* Team gateway
Base URL* https://gateway.example/v1
API key variable $TEAM_API_KEY
Save
* Required
Enter the environment variable name on the app server.
tab move · enter next/save · esc back
");
widget.handle_paste("Team gateway".into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_paste("https://team.example.test/v1?".into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_paste("TEAM_KEY-".into());
widget.handle_key_event(KeyCode::Down.into());
insta::assert_snapshot!("gateway_save_focused_short", screen(&widget, /*height*/ 4));
widget.handle_key_event(KeyCode::Enter.into());
insta::assert_snapshot!("gateway_save_error_short", screen(&widget, /*height*/ 4));
widget.handle_key_event(KeyCode::Up.into());
widget.handle_key_event(KeyCode::Backspace.into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_key_event(KeyCode::Enter.into());
widget.advance_gateway_request().await;
insta::assert_snapshot!("gateway_validation_retry", screen(&widget, /*height*/ 8));
// Correct the invalid URL and keep the other fields.
widget.handle_key_event(KeyCode::Up.into());
widget.handle_key_event(KeyCode::Up.into());
widget.handle_key_event(KeyCode::Backspace.into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_key_event(KeyCode::Down.into());
widget.handle_key_event(KeyCode::Enter.into());
widget.advance_gateway_request().await;
assert_eq!(widget.error_message(), None);
widget.handle_key_event(KeyEvent::new_with_kind(
KeyCode::Enter,
KeyModifiers::NONE,
KeyEventKind::Repeat,
));
assert!(matches!(widget.get_step_state(), StepState::InProgress));
insta::assert_snapshot!("gateway_created_picker", screen(&widget, /*height*/ 8));
let page = list_providers(&widget.app_server_request_handle)
.await
.map_err(color_eyre::Report::msg)?;
assert_eq!(page.default_provider_id, "openai");
widget.handle_key_event(KeyEvent::new_with_kind(
KeyCode::Enter,
KeyModifiers::NONE,
KeyEventKind::Release,
));
widget.handle_key_event(KeyCode::Enter.into());
widget.advance_gateway_request().await;
assert!(matches!(widget.get_step_state(), StepState::Complete));
let saved: serde_json::Value =
toml::from_str(&std::fs::read_to_string(home.path().join("config.toml"))?)?;
assert_eq!(
saved,
json!({
"model_provider": "team-gateway",
"model_providers": {
"office": {
"name": "Office",
"base_url": "https://office.example.test/v1",
"wire_api": "responses",
},
"team-gateway": {
"name": "Team gateway",
"base_url": "https://team.example.test/v1",
"env_key": "TEAM_KEY",
"wire_api": "responses",
},
},
})
);
Ok(())
}
#[tokio::test]
async fn gateway_oauth_displays_the_browser_link_and_retry_action() {
let (widget, _home) = super::tests::widget_forced_chatgpt().await;
*widget.sign_in_state.write().unwrap() = SignInState::GatewayOAuth {
provider_id: "office".into(),
url: Some("https://office.example.test/authorize".into()),
};
insta::assert_snapshot!("gateway_oauth_browser", screen(&widget, /*height*/ 4));
*widget.sign_in_state.write().unwrap() = SignInState::GatewayOAuthFailed {
provider_id: "office".into(),
message: "Gateway sign-in expired.".into(),
};
insta::assert_snapshot!("gateway_oauth_failed", screen(&widget, /*height*/ 4));
}

View File

@@ -0,0 +1,204 @@
//! Google Cloud setup collects provider settings and delegates validation and persistence to
//! app-server. Setup stays in progress until the server finishes writing the configuration.
use super::auth::AuthModeWidget;
use super::auth::SignInState;
use super::auth::onboarding_request_id;
use super::keys;
use super::provider_setup::FieldDisplay;
use super::provider_setup::ProviderInput;
use crate::key_hint::KeyBindingListExt;
use crate::wrapping::word_wrap_lines;
use codex_app_server_client::TypedRequestError;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::GcpSetupParams;
use codex_app_server_protocol::GcpSetupResponse;
use codex_app_server_protocol::RequestId;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Widget;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
use std::sync::PoisonError;
#[derive(Clone, Default)]
pub(super) struct GcpState {
view: GcpView,
project_id: ProviderInput,
location: ProviderInput,
credential_file: ProviderInput,
}
#[derive(Clone, Default)]
enum GcpView {
#[default]
Project,
Location,
Credentials,
Configuring(RequestId),
}
impl GcpState {
pub(super) fn is_text_entry_active(&self) -> bool {
!matches!(self.view, GcpView::Configuring(_))
}
pub(super) fn is_configuring(&self, id: &RequestId) -> bool {
matches!(&self.view, GcpView::Configuring(active) if active == id)
}
pub(super) fn active_input_mut(&mut self) -> Option<&mut ProviderInput> {
match self.view {
GcpView::Project => Some(&mut self.project_id),
GcpView::Location => Some(&mut self.location),
GcpView::Credentials => Some(&mut self.credential_file),
GcpView::Configuring(_) => None,
}
}
pub(super) fn render(&self, area: Rect, buf: &mut Buffer, error: Option<String>) {
let mut lines: Vec<Line> = vec!["> Set up Google Cloud Vertex AI".bold().into(), "".into()];
let (guidance, field) = match &self.view {
GcpView::Project => (
"Enter the Google Cloud project ID to use with Vertex AI.",
Some((&self.project_id, " Project ID: ", "my-project")),
),
GcpView::Location => (
"Press Enter to use global, or enter a Vertex AI location.",
Some((&self.location, " Location (optional): ", "global")),
),
GcpView::Credentials => (
"Enter an absolute file path on the host running Codex, or press Enter to use Application Default Credentials (ADC).",
Some((&self.credential_file, " Credential file (optional): ", "")),
),
GcpView::Configuring(_) => ("Validating credentials and saving configuration…", None),
};
lines.push(format!(" {guidance}").into());
if let Some((input, label, placeholder)) = field {
lines.push("".into());
lines.push(input.line(label, placeholder, FieldDisplay::Focused, area.width));
}
if matches!(self.view, GcpView::Credentials) {
lines.push("".into());
lines.push(
" To set up ADC with the Google Cloud CLI, run"
.dim()
.into(),
);
lines.push(" gcloud auth application-default login".cyan().into());
}
let mut footer = if self.is_text_entry_active() {
vec![Line::from(vec![
" ".into(),
keys::CONFIRM[0].into(),
if matches!(self.view, GcpView::Credentials) {
" set up"
} else {
" continue"
}
.dim(),
" · ".dim(),
keys::CANCEL[0].into(),
" back".dim(),
])]
} else {
Vec::new()
};
if let Some(error) = error {
footer.push("".into());
footer.push(error.red().into());
}
let footer = word_wrap_lines(footer, usize::from(area.width));
let footer_height = u16::try_from(footer.len())
.unwrap_or(u16::MAX)
.min(area.height);
Paragraph::new(word_wrap_lines(lines, usize::from(area.width))).render(
Rect {
height: area.height.saturating_sub(footer_height),
..area
},
buf,
);
Paragraph::new(footer).render(
Rect {
y: area.bottom().saturating_sub(footer_height),
height: footer_height,
..area
},
buf,
);
}
}
impl AuthModeWidget {
pub(super) fn handle_gcp_key_event(&mut self, key_event: &KeyEvent) -> bool {
let mut guard = self
.sign_in_state
.write()
.unwrap_or_else(PoisonError::into_inner);
let SignInState::Gcp(state) = &mut *guard else {
return false;
};
// A dispatched setup can persist settings. Do not offer cancellation or allow a
// second submission until its result arrives.
if key_event.kind == KeyEventKind::Release || !state.is_text_entry_active() {
return true;
}
if keys::CANCEL.is_pressed(*key_event) {
match state.view {
GcpView::Project => *guard = SignInState::PickMode,
GcpView::Location => state.view = GcpView::Project,
GcpView::Credentials => state.view = GcpView::Location,
GcpView::Configuring(_) => {}
}
} else if keys::CONFIRM.is_pressed(*key_event) {
if key_event.kind != KeyEventKind::Press {
return true;
}
match state.view {
GcpView::Project if state.project_id.value().is_none() => {
*self.error.write().unwrap_or_else(PoisonError::into_inner) =
Some("Enter a Google Cloud project ID.".to_string());
self.request_frame.schedule_frame();
return true;
}
GcpView::Project => state.view = GcpView::Location,
GcpView::Location => state.view = GcpView::Credentials,
GcpView::Credentials => {
let request_id = onboarding_request_id();
let retry = SignInState::Gcp(state.clone());
state.view = GcpView::Configuring(request_id.clone());
let params = GcpSetupParams {
project_id: state.project_id.value().unwrap_or_default(),
location: state.location.value(),
credential_file: state.credential_file.value(),
};
let request_handle = self.app_server_request_handle.clone();
self.spawn_provider_setup(request_id.clone(), retry, async move {
request_handle
.request_typed::<GcpSetupResponse>(ClientRequest::GcpSetup {
request_id,
params,
})
.await
.map(|_| ())
.map_err(|err| match err {
TypedRequestError::Server { source, .. } => source.message,
err => err.to_string(),
})
});
}
GcpView::Configuring(_) => {}
}
} else if let Some(input) = state.active_input_mut() {
input.input(*key_event);
}
*self.error.write().unwrap_or_else(PoisonError::into_inner) = None;
drop(guard);
self.request_frame.schedule_frame();
true
}
}

View File

@@ -0,0 +1,197 @@
#![cfg(test)]
//! Exercises Google Cloud onboarding through the widget and embedded app-server.
use super::*;
use codex_app_server_protocol::ConfigBatchWriteParams;
use codex_app_server_protocol::ConfigEdit;
use codex_app_server_protocol::ConfigWriteResponse;
use codex_app_server_protocol::MergeStrategy;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use serde_json::json;
#[tokio::test]
async fn gcp_menu_gating_and_setup_flow() {
let (mut widget, home) = super::tests::widget_forced_chatgpt().await;
widget.auth_config.forced_login_method = None;
widget.handle_sign_in_option(SignInOption::Gcp);
assert!(matches!(
&*widget.sign_in_state.read().unwrap(),
SignInState::PickMode
));
let snapshot = |widget: &AuthModeWidget, name: &str, area: Rect| {
let mut terminal = crate::custom_terminal::Terminal::with_options(
crate::test_backend::VT100Backend::new(area.width, area.height),
)
.unwrap();
terminal.set_viewport_area(area);
terminal
.draw(|frame| widget.render_ref(area, frame.buffer_mut()))
.unwrap();
insta::assert_snapshot!(name, terminal.backend().to_string());
};
snapshot(
&widget,
"sign_in_menu_short_without_cloud_wizards",
Rect::new(0, 0, 76, 8),
);
let press = |key| KeyEvent::new(key, KeyModifiers::NONE);
widget.gcp_setup_enabled = true;
widget.handle_key_event(press(KeyCode::Char('3')));
assert_eq!(
widget.displayed_sign_in_options(),
vec![SignInOption::ApiKey, SignInOption::Gcp]
);
widget.bedrock_setup_enabled = true;
widget.handle_key_event(KeyEvent::new_with_kind(
KeyCode::Char('3'),
KeyModifiers::NONE,
KeyEventKind::Repeat,
));
assert_eq!(widget.highlighted_mode, SignInOption::ApiKey);
assert!(matches!(
*widget.sign_in_state.read().unwrap(),
SignInState::PickMode
));
snapshot(&widget, "gcp_sign_in_menu", Rect::new(0, 0, 76, 21));
widget.handle_key_event(press(KeyCode::Up));
snapshot(&widget, "gcp_sign_in_menu_short", Rect::new(0, 0, 76, 8));
widget.handle_key_event(press(KeyCode::Esc));
assert_eq!(widget.highlighted_mode, SignInOption::OtherMethods);
let area = Rect::new(0, 0, 76, 12);
widget.auth_config.forced_login_method = Some(ForcedLoginMethod::Chatgpt);
assert_eq!(
widget.displayed_sign_in_options(),
vec![SignInOption::ChatGpt, SignInOption::DeviceCode]
);
widget.handle_sign_in_option(SignInOption::Gcp);
assert!(matches!(
&*widget.sign_in_state.read().unwrap(),
SignInState::PickMode
));
widget.auth_config.forced_login_method = None;
*widget.sign_in_state.write().unwrap() =
SignInState::ChatGptDeviceCode(ContinueWithDeviceCodeState::pending("login".into()));
widget.handle_key_event(press(KeyCode::Char('3')));
assert!(matches!(
&*widget.sign_in_state.read().unwrap(),
SignInState::ChatGptDeviceCode(_)
));
widget.cancel_active_attempt();
widget.handle_key_event(press(KeyCode::Char('3')));
widget.handle_key_event(press(KeyCode::Char('1')));
widget.handle_key_event(press(KeyCode::Esc));
assert_eq!(widget.highlighted_mode, SignInOption::ApiKey);
widget.handle_key_event(press(KeyCode::Char('3')));
widget.handle_key_event(press(KeyCode::Esc));
assert_eq!(widget.highlighted_mode, SignInOption::Gcp);
widget.handle_key_event(press(KeyCode::Enter));
assert!(widget.is_text_entry_active());
assert!(widget.should_suppress_printable_quit());
widget.handle_key_event(KeyEvent::new_with_kind(
KeyCode::Enter,
KeyModifiers::NONE,
KeyEventKind::Release,
));
widget.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_eq!(
widget.error_message().as_deref(),
Some("Enter a Google Cloud project ID.")
);
widget.handle_key_event(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE));
widget.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
widget.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::SUPER));
widget.handle_key_event(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::SUPER));
widget.handle_paste("test-ject\n".to_string());
for _ in 0..4 {
widget.handle_key_event(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE));
}
widget.handle_paste("pro".to_string());
widget.handle_key_event(KeyEvent::new(
KeyCode::Char('u'),
KeyModifiers::SUPER | KeyModifiers::CONTROL,
));
snapshot(&widget, "gcp_project_entry", area);
widget.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
snapshot(&widget, "gcp_location_entry", area);
// Location accepts text normally, and Esc preserves it for the next visit.
widget.handle_paste("us-central1".to_string());
widget.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
widget.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
widget.handle_key_event(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
widget.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
snapshot(&widget, "gcp_credentials_entry", area);
// A relative credential path fails server validation without requiring real GCP credentials.
widget.handle_paste("relative-adc.json".to_string());
let (request_frame, mut frames) = FrameRequester::test_channel();
widget.request_frame = request_frame;
widget.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(!widget.is_text_entry_active());
widget.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
widget.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(!widget.is_text_entry_active());
snapshot(&widget, "gcp_configuring", area);
while !widget.is_text_entry_active() {
frames.recv().await.unwrap();
}
let error = widget.error_message().unwrap();
assert!(error.contains("absolute"), "{error}");
assert!(!home.path().join("config.toml").exists());
snapshot(&widget, "gcp_setup_error_narrow", Rect::new(0, 0, 40, 18));
// Configure the existing command-auth boundary to avoid invoking gcloud in the test.
let (command, args) = if cfg!(windows) {
("cmd", vec!["/C", "echo setup-token"])
} else {
("echo", vec!["setup-token"])
};
widget
.app_server_request_handle
.request_typed::<ConfigWriteResponse>(ClientRequest::ConfigBatchWrite {
request_id: onboarding_request_id(),
params: ConfigBatchWriteParams {
edits: vec![ConfigEdit {
key_path: "model_providers.gcp.auth".to_string(),
value: json!({"command": command, "args": args, "cwd": home.path()}),
merge_strategy: MergeStrategy::Replace,
}],
file_path: None,
expected_version: None,
reload_user_config: false,
},
})
.await
.unwrap();
widget.handle_key_event(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
widget.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
while matches!(&*widget.sign_in_state.read().unwrap(), SignInState::Gcp(_))
&& widget.error_message().is_none()
{
frames.recv().await.unwrap();
}
assert_eq!(widget.error_message(), None);
assert!(matches!(widget.get_step_state(), StepState::Complete));
snapshot(&widget, "gcp_configured", area);
let config: toml::Value =
toml::from_str(&std::fs::read_to_string(home.path().join("config.toml")).unwrap()).unwrap();
assert_eq!(
config,
toml::Value::try_from(json!({
"model_provider": "gcp",
"model_providers": {"gcp": {
"project_id": "test-project", "location": "global",
"auth": {"command": command, "args": args, "cwd": home.path()},
}},
}))
.unwrap()
);
}

View File

@@ -0,0 +1,41 @@
//! Fixed shortcuts used before users have had a chance to configure Codex.
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use crate::key_hint;
use crate::key_hint::KeyBinding;
pub(crate) const MOVE_UP: [KeyBinding; 2] = [
key_hint::plain(KeyCode::Up),
key_hint::plain(KeyCode::Char('k')),
];
pub(crate) const MOVE_DOWN: [KeyBinding; 2] = [
key_hint::plain(KeyCode::Down),
key_hint::plain(KeyCode::Char('j')),
];
pub(crate) const SELECT_FIRST: [KeyBinding; 2] = [
key_hint::plain(KeyCode::Char('1')),
key_hint::plain(KeyCode::Char('y')),
];
pub(crate) const SELECT_SECOND: [KeyBinding; 2] = [
key_hint::plain(KeyCode::Char('2')),
key_hint::plain(KeyCode::Char('n')),
];
pub(crate) const SELECT_THIRD: [KeyBinding; 1] = [key_hint::plain(KeyCode::Char('3'))];
pub(crate) const SELECT_FOURTH: [KeyBinding; 1] = [key_hint::plain(KeyCode::Char('4'))];
pub(crate) const CONFIRM: [KeyBinding; 1] = [key_hint::plain(KeyCode::Enter)];
pub(crate) const CANCEL: [KeyBinding; 1] = [key_hint::plain(KeyCode::Esc)];
pub(crate) const COPY_LINK: [KeyBinding; 1] = [key_hint::plain(KeyCode::Char('c'))];
pub(crate) const QUIT: [KeyBinding; 3] = [
key_hint::plain(KeyCode::Char('q')),
key_hint::ctrl(KeyCode::Char('c')),
key_hint::ctrl(KeyCode::Char('d')),
];
pub(crate) const TOGGLE_ANIMATION: [KeyBinding; 2] = [
key_hint::ctrl(KeyCode::Char('.')),
KeyBinding::new(
KeyCode::Char('.'),
KeyModifiers::CONTROL.union(KeyModifiers::SHIFT),
),
];

View File

@@ -0,0 +1,18 @@
mod auth;
mod bedrock;
mod gateway;
mod gateway_login;
pub(crate) use gateway_login::authenticate_gateway;
mod gcp;
pub(crate) use bedrock::check_gov_cloud;
mod keys;
pub(crate) mod onboarding_screen;
mod provider_setup;
pub(crate) use provider_setup::FieldDisplay;
pub(crate) use provider_setup::ProviderInput;
pub(crate) use provider_setup::move_provider_field;
mod trust_directory;
pub(crate) use auth::mark_url_hyperlink;
pub(crate) use onboarding_screen::DirectoryTrustOptions;
pub(crate) use trust_directory::TrustCancelAction;
mod welcome;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,163 @@
//! Single-line fields shared by provider settings and the cloud setup wizards.
use super::auth::AuthModeWidget;
use super::auth::SignInState;
use crate::bottom_pane::TextArea;
use codex_app_server_protocol::RequestId;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::text::Span;
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::PoisonError;
use unicode_segmentation::UnicodeSegmentation;
// The sign-in state is shared with request tasks. Each field owns its editing history,
// including killed text, so yanking in another field cannot reveal a credential.
#[derive(Clone)]
pub(crate) struct ProviderInput(Arc<Mutex<TextArea>>);
pub(crate) enum FieldDisplay {
Focused,
Unfocused,
FocusedSecret,
UnfocusedSecret,
}
impl Default for ProviderInput {
fn default() -> Self {
Self::from("")
}
}
impl From<&str> for ProviderInput {
fn from(text: &str) -> Self {
let mut editor = TextArea::new_single_line();
editor.insert_str(text);
Self(Arc::new(Mutex::new(editor)))
}
}
impl ProviderInput {
pub(crate) fn editor(&self) -> MutexGuard<'_, TextArea> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn input(&mut self, event: KeyEvent) {
self.editor().input(event);
}
pub(crate) fn paste(&mut self, pasted: &str) {
let text: String = pasted.chars().filter(|c| !c.is_control()).collect();
self.editor().insert_str(&text);
}
pub(crate) fn value(&self) -> Option<String> {
let editor = self.editor();
let text = editor.text().trim();
(!text.is_empty()).then(|| text.to_owned())
}
pub(crate) fn line(
&self,
label: &str,
placeholder: &str,
display: FieldDisplay,
width: u16,
) -> Line<'static> {
let editor = self.editor();
let mut line = Line::from(label.to_owned());
if editor.text().is_empty() && !placeholder.is_empty() {
line.push_span(placeholder.to_owned().dim());
return line;
}
let focused = matches!(display, FieldDisplay::Focused | FieldDisplay::FocusedSecret);
let field_width = usize::from(width).saturating_sub(line.width());
// When the label occupies a whole row, wrapping moves the value to the next row.
let mut remaining = if field_width == 0 {
usize::from(width)
} else {
field_width
};
let start = if focused {
editor.single_line_viewport(remaining as u16).0
} else {
0
};
let mut content = editor.text()[start..].grapheme_indices(true).peekable();
while let Some((offset, grapheme)) = content.next() {
let cell = match display {
FieldDisplay::Focused | FieldDisplay::Unfocused => grapheme,
FieldDisplay::FocusedSecret if content.peek().is_none() => grapheme,
FieldDisplay::FocusedSecret | FieldDisplay::UnfocusedSecret => "•",
};
let span = Span::raw(cell.to_owned());
let span = if focused { span.cyan() } else { span };
let Some(rest) = remaining.checked_sub(span.width()) else {
break;
};
remaining = rest;
line.push_span(if focused && start + offset == editor.cursor() {
span.reversed()
} else {
span
});
}
if focused && remaining > 0 && editor.cursor() == editor.text().len() {
line.push_span(" ".reversed());
}
line
}
}
/// Cycle focus among the inputs and actions in a provider form.
pub(crate) fn move_provider_field(key: KeyEvent, selected: &mut usize, count: usize) -> bool {
*selected = match (key.code, key.modifiers) {
(KeyCode::Up | KeyCode::BackTab, KeyModifiers::NONE)
| (KeyCode::Tab | KeyCode::BackTab, KeyModifiers::SHIFT) => (*selected + count - 1) % count,
(KeyCode::Down | KeyCode::Tab, KeyModifiers::NONE) => (*selected + 1) % count,
_ => return false,
};
true
}
impl AuthModeWidget {
pub(super) fn spawn_provider_setup(
&self,
request_id: RequestId,
retry: SignInState,
request: impl Future<Output = Result<(), String>> + Send + 'static,
) {
let sign_in_state = self.sign_in_state.clone();
let error = self.error.clone();
let request_frame = self.request_frame.clone();
tokio::spawn(async move {
let result = request.await;
let mut state = sign_in_state
.write()
.unwrap_or_else(PoisonError::into_inner);
let configured = match &*state {
SignInState::Bedrock(bedrock) if bedrock.is_configuring(&request_id) => {
SignInState::BedrockConfigured
}
SignInState::Gcp(gcp) if gcp.is_configuring(&request_id) => {
SignInState::GcpConfigured
}
_ => return,
};
let (next, message) = match result {
Ok(()) => (configured, None),
Err(err) => (retry, Some(err)),
};
*state = next;
*error.write().unwrap_or_else(PoisonError::into_inner) = message;
drop(state);
request_frame.schedule_frame();
});
}
}

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: screen(&widget)
---
Use a custom provider or gateway
○ Office office
› ○ Team gateway team-gateway
Create a custom provider or gateway
Press enter to use as default or esc to go back

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: screen(&widget)
---
Use a custom provider or gateway
› Create a custom provider or gateway
Press enter to create or esc to go back

View File

@@ -0,0 +1,10 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: error
---
Use a custom provider or gateway
The default provider is set by configuration policy or a launch
override.
› 1. Back

View File

@@ -0,0 +1,7 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 4)"
---
Finish signing in to your gateway in the browser.
https://office.example.test/authorize
Press Ctrl+C to quit.

View File

@@ -0,0 +1,6 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 4)"
---
Gateway sign-in expired.
Press Enter to retry or Ctrl+C to quit.

View File

@@ -0,0 +1,8 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 4)"
---
› Save
Enter an environment variable name such as TEAM_API_KEY.
* Required

View File

@@ -0,0 +1,8 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 4)"
---
› Save
* Required
Enter the environment variable name on the app server.

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: screen(&widget)
---
Use a custom provider or gateway
› ○ Office office
Create a custom provider or gateway
Press enter to use as default or esc to go back

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: terminal.backend().to_string()
---
Sign in another way
> 1. Use an OpenAI API key
2. Use Amazon Bedrock
3. Use Google Cloud Vertex AI
4. Use a custom provider or gateway
Press enter to continue
Press esc to go back

View File

@@ -0,0 +1,12 @@
---
source: tui/src/onboarding/gateway_tests.rs
expression: "screen(&widget, 8)"
---
Base URL* https://team.example.test/v1?
API key variable $TEAM_KEY
› Save
Enter an HTTP(S) base URL without credentials, a query, or a fragment.
* Required
Enter the environment variable name on the app server.
tab move · enter next/save · esc back

View File

@@ -0,0 +1,5 @@
---
source: tui/src/onboarding/gcp_tests.rs
expression: terminal.backend().to_string()
---
✓ Google Cloud Vertex AI configured

View File

@@ -0,0 +1,7 @@
---
source: tui/src/onboarding/gcp_tests.rs
expression: terminal.backend().to_string()
---
> Set up Google Cloud Vertex AI
Validating credentials and saving configuration…

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/gcp_tests.rs
expression: terminal.backend().to_string()
---
> Set up Google Cloud Vertex AI
Enter an absolute file path on the host running Codex, or press Enter to
use Application Default Credentials (ADC).
Credential file (optional):
To set up ADC with the Google Cloud CLI, run
gcloud auth application-default login
enter set up · esc back

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/gcp_tests.rs
expression: terminal.backend().to_string()
---
> Set up Google Cloud Vertex AI
Press Enter to use global, or enter a Vertex AI location.
Location (optional): global
enter continue · esc back

View File

@@ -0,0 +1,16 @@
---
source: tui/src/onboarding/gcp_tests.rs
expression: terminal.backend().to_string()
---
> Set up Google Cloud Vertex AI
Enter the Google Cloud project ID to use with Vertex AI.
Project ID: test-project
enter continue · esc back

View File

@@ -0,0 +1,22 @@
---
source: tui/src/onboarding/gcp_tests.rs
expression: terminal.backend().to_string()
---
> Set up Google Cloud Vertex AI
Enter an absolute file path on the
host running Codex, or press Enter to
use Application Default Credentials
(ADC).
Credential file (optional): -adc.json
To set up ADC with the Google Cloud
CLI, run
gcloud auth application-default login
enter set up · esc back
provider credential_file must be an
absolute path

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/gcp_tests.rs
expression: terminal.backend().to_string()
---
Sign in another way
> 1. Use an OpenAI API key
Pay for what you use
2. Use Amazon Bedrock
Connect using your AWS credentials
3. Use Google Cloud Vertex AI
Connect using your Google Cloud credentials
Press enter to continue
Press esc to go back

View File

@@ -0,0 +1,11 @@
---
source: tui/src/onboarding/gcp_tests.rs
expression: terminal.backend().to_string()
---
Sign in another way
1. Use an OpenAI API key
2. Use Amazon Bedrock
> 3. Use Google Cloud Vertex AI
Press enter to continue
Press esc to go back

View File

@@ -0,0 +1,11 @@
---
source: tui/src/onboarding/gcp_tests.rs
expression: terminal.backend().to_string()
---
Sign in with ChatGPT to use Codex as part of your paid plan
or connect an API key for usage-based billing
> 1. Sign in with ChatGPT
2. Sign in with Device Code
3. Sign in another way
Press enter to continue

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/auth.rs
expression: terminal.backend().to_string()
---
> Use your own OpenAI API key for usage-based billing
Paste or type your API key below.
╭API key───────────────────────────────────────────────────────────────────────╮
│Paste or type your API key │
╰──────────────────────────────────────────────────────────────────────────────╯
Press enter to save
Press esc to go back

View File

@@ -0,0 +1,15 @@
---
source: tui/src/onboarding/auth.rs
expression: terminal.backend().to_string()
---
> Use your own OpenAI API key for
usage-based billing
Paste or type your API key below.
╭API key───────────────────────────────╮
│Paste or type your API key │
╰──────────────────────────────────────╯
Press enter to save
Press esc to go back

View File

@@ -0,0 +1,25 @@
---
source: tui/src/onboarding/auth.rs
expression: contents
---
Finish signing in via your browser
If the link doesn't open automatically,
press c to copy it:
https://auth.openai.com/oauth/authorize?re
sponse_type=code&client_id=app_EMoamEEZ73f0C
kXaXp7hrann&redirect_uri=http%3A%2F%2Flocalh
ost%3A1455%2Fauth%2Fcallback&scope=openid%20
profile%20email%20offline_access%20api.conne
ctors.read%20api.connectors.invoke&code_chal
lenge=1YM3Z8QbrLbdt9C3eX3j7UQ4GmFRmKz4OeVYwD
6s5xA&code_challenge_method=S256&id_token_ad
d_organizations=true&codex_cli_simplified_fl
ow=true&state=8cHjQ4nVx2Yp7Lm9Rk3Wf6Ta1Bs5Du
0Ei4Go7Nz2PqM&originator=codex_cli_rs
On a remote or headless machine? Press esc
and choose Sign in with Device Code.
Press esc to cancel

View File

@@ -0,0 +1,13 @@
---
source: tui/src/onboarding/bedrock_tests.rs
expression: render_visible(&state)
---
Using Codex with AWS GovCloud
You are using Codex with AWS GovCloud. Please ensure you or your
administrator have read the application configuration and security
guidance before proceeding.
> Acknowledge
Press enter to continue

View File

@@ -0,0 +1,10 @@
---
source: tui/src/onboarding/bedrock_tests.rs
expression: initial
---
Using Codex with AWS
GovCloud
You are using Codex with
> Acknowledge
↑/↓ scroll · enter

View File

@@ -0,0 +1,18 @@
---
source: tui/src/onboarding/trust_directory.rs
assertion_line: 365
expression: terminal.backend()
---
Folder access
/workspace/project
Trust this folder? Codex can read, edit, and run files here,
subject to your permission settings. Folder settings can run code
automatically, even without a model request. Continue only if you
trust these files. Your trust decision will be saved.
› 1. Trust and continue
2. Keep current directory
enter continue · esc cancel

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project
This existing task may retain settings and history, including
project configuration or hooks loaded while it was trusted. To use
restricted settings, start a new task. The folder's trust setting
will not change.
› 1. Open existing task
2. Back to Agent Command Center
enter continue · esc back

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project/long-nested-folde
r
Config, hooks, and exec policies
from untrusted folders stay
disabled. Trusted project folders
can still contribute settings.
Skills still load, and tools follow
your permission settings. Opening
will not change saved trust.
› 1. Open restricted
2. Back to Agent Command Center
enter continue · esc back

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: "terminal.backend().to_string().replace('\\\\', \"/\")"
---
Folder access
workspace/…/repository
Trust this folder? Codex can read,
edit, and run files here, subject to
your permission settings. Folder
settings can run code automatically,
even without a model request.
Continue only if you trust these
files. Your trust decision will be
saved.
› 1. Trust and continue
2. Quit
enter continue · esc quit

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: "terminal.backend().to_string().replace('\\\\', \"/\")"
---
Folder access
workspace/…/repository/checkout
Note: You’re in a subdirectory of a
Git project. Trusting will apply to
the repository root:
workspace/…/repository
Trust this folder? Codex can read,
edit, and run files here, subject to
your permission settings. Folder
settings can run code automatically,
even without a model request.
Continue only if you trust these
files. Your trust decision will be
saved.
› 1. Trust and continue
2. Quit
enter continue · esc quit

View File

@@ -0,0 +1,20 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: "terminal.backend().to_string().replace('\\\\', \"/\")"
---
Folder access
Note: You’re in a subdirectory of a
Git project. Trusting will apply to
the repository root:
workspace/…/repository
Trust this folder? Codex can read,
edit, and run files here, subject to
your permission settings. Folder
settings can run code automatically,
even without a model request.
Continue only if you trust these
files. Your trust decision will be
saved.
› 1. Trust and continue
2. Quit
enter continue · esc quit

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project
Config, hooks, and exec policies from untrusted folders stay
disabled. Trusted project folders can still contribute settings.
Skills still load, and tools follow your permission settings.
Opening will not change saved trust.
› 1. Open restricted
2. Back to Agent Command Center
enter continue · esc back

View File

@@ -0,0 +1,17 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project
Trust this folder? Codex can read, edit, and run files here,
subject to your permission settings. Folder settings can run code
automatically, even without a model request. Continue only if you
trust these files. Your trust decision will be saved.
› 1. Trust and continue
2. Quit
enter continue and create sandbox · esc quit

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: "terminal.backend().to_string().lines().map(str::trim_end).collect::<Vec<_>>().join(\"\\n\")"
---
Folder access
/srv/remote/project/nested
Note: You’re in a subdirectory of a Git project. Trusting will
apply to the repository root:
/srv/remote/project
Trust this folder? Codex can read, edit, and run files here,
subject to your permission settings. Folder settings can run code
automatically, even without a model request. Continue only if you
trust these files. Your trust decision will be saved.
› 1. Trust and continue
2. Back to Agent Command Center
enter continue · esc back

View File

@@ -0,0 +1,21 @@
---
source: tui/src/onboarding/trust_directory.rs
expression: terminal.backend()
---
Folder access
/workspace/project
Trust this folder? Codex can read, edit, and run files here,
subject to your permission settings. Folder settings can run code
automatically, even without a model request. Continue only if you
trust these files. Your trust decision will be saved.
› 1. Trust and continue
2. Quit
Failed to set trust for /workspace/project: config/batchWrite
failed in TUI: Invalid configuration: features.fast_mode=true is
not supported; allowed set [fast_mode=false]
enter continue · esc quit

View File

@@ -0,0 +1,25 @@
---
source: tui/src/onboarding/welcome.rs
expression: visible.trim_end()
---
⢀⣀⣠⣤⣤⣤⣤⣤⣤⣀⣀
⢀⣤⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⡀
⢀⣠⣾⣿⣿⣿⣿⡿⠟⠛⠋⠉⠉⠙⠛⠛⠿⣿⣿⣿⣿⣿⣷⡄
⣠⣾⣿⣿⣿⠿⠋ ⠉⠛⣿⣿⣿⣿⣷⡀
⣰⣿⣿⣿⡟⠁ ⠹⣿⣿⣿⣿⡄
⣼⣿⣿⣿⠟ ⣀⣤⡀ ⠈⢿⣿⣿⣷⡀
⢠⣿⣿⣿⡟ ⣿⣿⣿⣄ ⠘⣿⣿⣿⣧
⢸⣿⣿⣿⠁ ⠙⣿⣿⣿⣆ ⢿⣿⣿⣿
⢾⣿⣿⣿ ⢸⣿⣿⣿⠆ ⢸⣿⣿⣿⠆
⣾⣿⣿⣿ ⣠⣿⣿⣿⠏ ⢀⣀⣀⣀⣀⣀⣀⡀ ⢸⣿⣿⣿
⠸⣿⣿⣿⡆ ⢰⣿⣿⣿⠇ ⣿⣿⣿⣿⣿⣿⣿⣿⡆ ⢀⣿⣿⣿⡟
⢻⣿⣿⣿⣄ ⠉⠛⠁ ⠙⠛⠛⠛⠛⠛⠛⠋ ⢀⣼⣿⣿⣿⠃
⠈⢻⣿⣿⣿⣦⡀ ⣠⣾⣿⣿⣿⠇
⠻⣿⣿⣿⣿⣤⣀ ⢀⣠⣾⣿⣿⣿⡿⠃
⠈⠻⣿⣿⣿⣿⣷⣶⣤⣄⣀⣀⣀⢀⣀⣠⣤⣴⣿⣿⣿⣿⣿⠛
⠙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠋
⠉⠙⠛⠿⠿⠿⠿⠿⠿⠿⠛⠋⠁
Welcome to Codex, OpenAI's command-line coding agent

View File

@@ -0,0 +1,483 @@
//! Folder trust disclosure with bounded paths, shared picker styling, and protected selection.
use std::path::Path;
use std::path::PathBuf;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Paragraph;
use ratatui::widgets::WidgetRef;
use ratatui::widgets::Wrap;
use crate::bottom_pane::picker_option_row;
use crate::bottom_pane::render_menu_surface;
use crate::key_hint::KeyBindingListExt;
use crate::onboarding::keys;
use crate::onboarding::onboarding_screen::KeyboardHandler;
use crate::onboarding::onboarding_screen::StepStateProvider;
use crate::render::Insets;
use crate::render::renderable::FlexRenderable;
use crate::render::renderable::Renderable;
use crate::render::renderable::RenderableExt as _;
use crate::render::renderable::RenderableItem;
use crate::text_formatting::center_truncate_path;
use super::onboarding_screen::StepState;
pub(crate) struct TrustDirectoryWidget {
pub restricted: bool,
pub existing_task: bool,
pub cancel: TrustCancelAction,
pub cwd: PathBuf,
pub trust_target: PathBuf,
pub show_windows_create_sandbox_hint: bool,
pub should_quit: bool,
pub selection: Option<TrustDirectorySelection>,
pub highlighted: TrustDirectorySelection,
pub error: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TrustCancelAction {
Quit,
AgentsOverview,
CurrentTask,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrustDirectorySelection {
Trust,
Quit,
}
impl WidgetRef for &TrustDirectoryWidget {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
// Measure the mandatory content before giving any rows to variable-length paths.
let mut children = vec![(
0,
Paragraph::new(if self.restricted && self.existing_task {
"This existing task may retain settings \
and history, including project configuration or hooks loaded while it was trusted. \
To use restricted settings, start a new task. The folder's trust setting will not change."
} else if self.restricted {
"Config, hooks, and exec policies from untrusted folders stay disabled. \
Trusted project folders can still contribute settings. Skills still load, \
and tools follow your permission settings. Opening will not change saved trust."
} else {
"Trust this folder? Codex can read, edit, and run files here, subject to \
your permission settings. Folder settings can run code automatically, \
even without a model request. Continue only if you trust these files. \
Your trust decision will be saved."
})
.wrap(Wrap { trim: true })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
)];
children.push((1, RenderableItem::Borrowed(&"")));
let options: Vec<(&str, TrustDirectorySelection)> = vec![
(
if self.restricted && self.existing_task {
"Open existing task"
} else if self.restricted {
"Open restricted"
} else {
"Trust and continue"
},
TrustDirectorySelection::Trust,
),
(
match self.cancel {
TrustCancelAction::Quit => "Quit",
TrustCancelAction::AgentsOverview => "Back to Agent Command Center",
TrustCancelAction::CurrentTask => "Keep current directory",
},
TrustDirectorySelection::Quit,
),
];
for (idx, (text, selection)) in options.iter().enumerate() {
children.push((
0,
picker_option_row(idx, text.to_string(), self.highlighted == *selection).into(),
));
}
children.push((1, RenderableItem::Borrowed(&"")));
if let Some(error) = &self.error {
children.push((
0,
Paragraph::new(error.to_string())
.red()
.wrap(Wrap { trim: true })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
));
children.push((1, RenderableItem::Borrowed(&"")));
}
children.push((
0,
Paragraph::new(Line::from(vec![
keys::CONFIRM[0].into(),
if self.show_windows_create_sandbox_hint && !self.restricted {
" continue and create sandbox".dim()
} else {
" continue".dim()
},
" · ".dim(),
keys::CANCEL[0].into(),
match self.cancel {
TrustCancelAction::Quit => " quit",
TrustCancelAction::AgentsOverview => " back",
TrustCancelAction::CurrentTask => " cancel",
}
.dim(),
]))
.wrap(Wrap { trim: false })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
));
children.push((1, RenderableItem::Borrowed(&"")));
#[allow(clippy::disallowed_methods)]
let git_root_warning = (!self.restricted && self.cwd != self.trust_target).then(|| {
Paragraph::new(
"Note: You’re in a subdirectory of a Git project. Trusting will apply to the repository root:",
)
.yellow()
.wrap(Wrap { trim: true })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2))
});
let reserved_height = children
.iter()
.filter(|(flex, _)| *flex == 0)
.map(|(_, child)| child.desired_height(area.width))
.fold(/*init*/ 1u16, u16::saturating_add)
.saturating_add(git_root_warning.desired_height(area.width));
let path_height = area.height.saturating_sub(reserved_height);
// If only one path row fits, show the repository root receiving trust.
let cwd_height = if git_root_warning.is_some() {
path_height / 2
} else {
path_height
};
let path = |path: &Path, max_height: u16| {
let text = path.display().to_string();
let paragraph = Paragraph::new(text.clone()).wrap(Wrap { trim: false });
let width = area.width.saturating_sub(/*rhs*/ 4);
if paragraph.desired_height(width) <= max_height {
paragraph.dim().inset(Insets::vh(/*v*/ 0, /*h*/ 2))
} else {
// A single line bounds even paths containing embedded newlines.
Line::from(center_truncate_path(&text, usize::from(width)))
.dim()
.inset(Insets::vh(/*v*/ 0, /*h*/ 2))
}
};
let mut column = FlexRenderable::new();
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
column.push(
/*flex*/ 0,
RenderableItem::Owned(Box::new(Line::from(" Folder access".bold()))),
);
if cwd_height > 0 {
column.push(/*flex*/ 0, path(&self.cwd, cwd_height));
}
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
if let Some(warning) = git_root_warning {
column.push(/*flex*/ 0, warning);
let root_height = path_height.saturating_sub(cwd_height);
if root_height > 0 {
column.push(/*flex*/ 0, path(&self.trust_target, root_height));
}
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
}
for (flex, child) in children {
column.push(flex, child);
}
let panel = Rect {
height: column.desired_height(area.width).min(area.height),
..area
};
render_menu_surface(panel, buf);
// The column owns flexible vertical padding; row highlights span the full panel.
column.render(panel, buf);
}
}
impl KeyboardHandler for TrustDirectoryWidget {
fn handle_key_event(&mut self, key_event: KeyEvent) {
if key_event.kind != KeyEventKind::Press {
return;
}
if keys::MOVE_UP.is_pressed(key_event) {
self.highlighted = TrustDirectorySelection::Trust;
} else if keys::MOVE_DOWN.is_pressed(key_event) {
self.highlighted = TrustDirectorySelection::Quit;
} else if keys::SELECT_FIRST.is_pressed(key_event) {
// A terminal response fragment can start with `1`; trust always requires an explicit
// Enter confirmation after the directory prompt is visible.
self.highlighted = TrustDirectorySelection::Trust;
} else if keys::SELECT_SECOND.is_pressed(key_event)
|| keys::QUIT.is_pressed(key_event)
|| keys::CANCEL.is_pressed(key_event)
{
self.handle_quit();
} else if keys::CONFIRM.is_pressed(key_event) {
match self.highlighted {
TrustDirectorySelection::Trust => self.handle_trust(),
TrustDirectorySelection::Quit => self.handle_quit(),
}
}
}
}
impl StepStateProvider for TrustDirectoryWidget {
fn get_step_state(&self) -> StepState {
if self.selection.is_some() || self.should_quit {
StepState::Complete
} else {
StepState::InProgress
}
}
}
impl TrustDirectoryWidget {
fn handle_trust(&mut self) {
self.highlighted = TrustDirectorySelection::Trust;
self.error = None;
self.selection = Some(TrustDirectorySelection::Trust);
}
fn handle_quit(&mut self) {
self.highlighted = TrustDirectorySelection::Quit;
self.should_quit = true;
}
pub fn should_quit(&self) -> bool {
self.should_quit
}
}
#[cfg(test)]
mod tests {
use crate::test_backend::VT100Backend;
use super::*;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use ratatui::Terminal;
use std::path::PathBuf;
fn widget(error: Option<String>) -> TrustDirectoryWidget {
TrustDirectoryWidget {
restricted: false,
existing_task: false,
cancel: TrustCancelAction::Quit,
cwd: PathBuf::from("/workspace/project"),
trust_target: PathBuf::from("/workspace/project"),
show_windows_create_sandbox_hint: false,
should_quit: false,
selection: None,
highlighted: TrustDirectorySelection::Trust,
error,
}
}
#[test]
fn release_event_does_not_change_selection() {
let mut widget = TrustDirectoryWidget {
restricted: false,
existing_task: false,
cancel: TrustCancelAction::Quit,
cwd: PathBuf::from("."),
trust_target: PathBuf::from("."),
show_windows_create_sandbox_hint: false,
should_quit: false,
selection: None,
highlighted: TrustDirectorySelection::Quit,
error: None,
};
let release = KeyEvent {
kind: KeyEventKind::Release,
..KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)
};
widget.handle_key_event(release);
assert_eq!(widget.selection, None);
let repeat =
KeyEvent::new_with_kind(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Repeat);
widget.handle_key_event(repeat);
assert_eq!(widget.selection, None);
let press = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
widget.handle_key_event(press);
assert!(widget.should_quit);
}
#[test]
fn fragmented_terminal_response_cannot_grant_directory_trust() {
let mut widget = widget(/*error*/ None);
widget.highlighted = TrustDirectorySelection::Quit;
// The prefix may have been consumed by the protected-screen input drain, leaving the
// numeric OSC slot as the first key delivered after the trust prompt becomes active.
for character in "10;rgb:ffff/ffff/ffff".chars() {
widget.handle_key_event(KeyEvent::new(KeyCode::Char(character), KeyModifiers::NONE));
}
assert_eq!(widget.selection, None);
assert_eq!(widget.highlighted, TrustDirectorySelection::Trust);
widget.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_eq!(widget.selection, Some(TrustDirectorySelection::Trust));
}
#[test]
fn renders_snapshot_for_git_repo() {
let mut widget = widget(/*error*/ None);
widget.show_windows_create_sandbox_hint = true;
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 14)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(terminal.backend());
}
#[test]
fn directory_change_consent_can_keep_current_directory() {
let mut widget = widget(/*error*/ None);
widget.cancel = TrustCancelAction::CurrentTask;
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 18)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(terminal.backend());
widget.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(widget.should_quit());
}
#[test]
fn renders_snapshot_for_remote_git_subdirectory() {
let widget = TrustDirectoryWidget {
restricted: false,
existing_task: false,
cancel: TrustCancelAction::AgentsOverview,
cwd: PathBuf::from("/srv/remote/project/nested"),
trust_target: PathBuf::from("/srv/remote/project"),
..widget(/*error*/ None)
};
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 18)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(
terminal
.backend()
.to_string()
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n")
);
}
#[test]
fn renders_restricted_folder() {
for existing_task in [false, true] {
let widget = TrustDirectoryWidget {
restricted: true,
existing_task,
cancel: TrustCancelAction::AgentsOverview,
..widget(/*error*/ None)
};
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 18)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
if existing_task {
insta::assert_snapshot!("existing_untrusted_task", terminal.backend());
} else {
insta::assert_snapshot!(terminal.backend());
}
}
}
#[test]
fn renders_snapshot_for_trust_error() {
let widget = widget(Some(
"Failed to set trust for /workspace/project: config/batchWrite failed in TUI: Invalid configuration: features.fast_mode=true is not supported; allowed set [fast_mode=false]"
.to_string(),
));
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 70, /*height*/ 22)).expect("terminal");
terminal
.draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(terminal.backend());
}
#[test]
fn picker_wraps_paths_and_restricted_actions() {
let widget = TrustDirectoryWidget {
restricted: true,
cancel: TrustCancelAction::AgentsOverview,
cwd: PathBuf::from("/workspace/project/long-nested-folder"),
..widget(/*error*/ None)
};
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 40, /*height*/ 24)).expect("terminal");
terminal
.draw(|frame| (&widget).render_ref(frame.area(), frame.buffer_mut()))
.expect("draw");
insta::assert_snapshot!("folder_picker_restricted_40x24", terminal.backend());
}
#[test]
fn long_paths_keep_disclosure_and_choices_visible() {
let trust_target: PathBuf = std::iter::once("workspace")
.chain(std::iter::repeat_n("nested-checkout", /*count*/ 60))
.chain(["repository"])
.collect();
for (subdirectory, height, snapshot) in [
(false, 13, "long_checkout_40x13"),
(true, 17, "long_repository_root_40x17"),
(true, 16, "only_repository_root_fits_40x16"),
] {
let widget = TrustDirectoryWidget {
cwd: if subdirectory {
trust_target.join("checkout")
} else {
trust_target.clone()
},
trust_target: trust_target.clone(),
..widget(/*error*/ None)
};
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 40, height)).expect("terminal");
terminal
.draw(|frame| (&widget).render_ref(frame.area(), frame.buffer_mut()))
.expect("draw");
insta::assert_snapshot!(snapshot, terminal.backend().to_string().replace('\\', "/"));
}
}
}

View File

@@ -0,0 +1,222 @@
//! Shared welcome header for the existing sign-in and Bedrock onboarding pickers.
//! The logo occupies a fixed stage so its motion never shifts the choices below it.
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Widget;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Clear;
use ratatui::widgets::Paragraph;
use ratatui::widgets::WidgetRef;
use ratatui::widgets::Wrap;
use std::cell::Cell;
use std::cell::RefCell;
use crate::empty_state_animation::EmptyStateAnimation;
use crate::empty_state_animation::Presentation;
use crate::key_hint::KeyBindingListExt;
use crate::onboarding::keys;
use crate::onboarding::onboarding_screen::KeyboardHandler;
use crate::onboarding::onboarding_screen::StepStateProvider;
use crate::tui::FrameRequester;
use super::onboarding_screen::StepState;
const MIN_ANIMATION_HEIGHT: u16 = 41;
const MIN_ANIMATION_WIDTH: u16 = 64;
const ANIMATION_WIDTH: u16 = 60;
const ANIMATION_HEIGHT: u16 = 21;
pub(crate) struct WelcomeWidget {
pub is_logged_in: bool,
animation: RefCell<EmptyStateAnimation>,
request_frame: FrameRequester,
animations_enabled: bool,
presentation: Cell<Presentation>,
focused: Cell<bool>,
layout_area: Cell<Option<Rect>>,
}
impl KeyboardHandler for WelcomeWidget {
/// Replay the welcome animation when the existing logo shortcut fires.
///
/// The key list includes compatibility variants for terminals that report
/// modifier bits differently.
fn handle_key_event(&mut self, key_event: KeyEvent) {
if !self.animations_enabled {
return;
}
if key_event.kind == KeyEventKind::Press && keys::TOGGLE_ANIMATION.is_pressed(key_event) {
self.animation.get_mut().start_fresh();
self.request_frame.schedule_frame();
}
}
}
impl WelcomeWidget {
pub(crate) fn new(
is_logged_in: bool,
request_frame: FrameRequester,
animations_enabled: bool,
) -> Self {
let mut animation = EmptyStateAnimation::default();
animation.start_fresh();
Self {
is_logged_in,
animation: RefCell::new(animation),
request_frame,
animations_enabled,
presentation: Cell::new(Presentation::Animated),
focused: Cell::new(/*value*/ true),
layout_area: Cell::new(None),
}
}
pub(crate) fn update_layout_area(&self, area: Rect) {
self.layout_area.set(Some(area));
}
pub(crate) fn set_presentation(&self, presentation: Presentation) {
if presentation == Presentation::Hidden {
self.animation.borrow_mut().pause_clock();
}
self.presentation.set(presentation);
}
pub(crate) fn set_focused(&self, focused: bool) {
self.focused.set(focused);
}
}
impl WidgetRef for &WelcomeWidget {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
Clear.render(area, buf);
let layout_area = self.layout_area.get().unwrap_or(area);
// Skip the animation entirely when the viewport is too small so we don't clip frames.
let show_animation = self.animations_enabled
&& self.presentation.get() != Presentation::Hidden
&& layout_area.height >= MIN_ANIMATION_HEIGHT
&& layout_area.width >= MIN_ANIMATION_WIDTH;
let presentation = if !show_animation {
Presentation::Hidden
} else if !self.focused.get() {
Presentation::Faded
} else {
self.presentation.get()
};
let stage = Rect::new(area.x, area.y, ANIMATION_WIDTH, ANIMATION_HEIGHT);
if let Some(delay) = self
.animation
.borrow_mut()
.render_in(stage, buf, presentation)
{
self.request_frame.schedule_frame_in(delay);
}
let logo_rows = if show_animation {
ANIMATION_HEIGHT + 1
} else {
0
};
let mut lines: Vec<Line> = vec![Line::default(); usize::from(logo_rows)];
lines.push(Line::from(vec![
" ".into(),
"Welcome to ".into(),
"Codex".bold(),
", OpenAI's command-line coding agent".into(),
]));
Paragraph::new(lines)
.wrap(Wrap { trim: false })
.render(area, buf);
}
}
impl StepStateProvider for WelcomeWidget {
fn get_step_state(&self) -> StepState {
match self.is_logged_in {
true => StepState::Hidden,
false => StepState::Complete,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
fn row_containing(buf: &Buffer, needle: &str) -> Option<u16> {
(0..buf.area.height).find(|&y| {
let mut row = String::new();
for x in 0..buf.area.width {
row.push_str(buf[(x, y)].symbol());
}
row.contains(needle)
})
}
#[test]
fn welcome_renders_animation_on_first_draw() {
let widget = WelcomeWidget::new(
/*is_logged_in*/ false,
FrameRequester::test_dummy(),
/*animations_enabled*/ true,
);
let area = Rect::new(0, 0, MIN_ANIMATION_WIDTH, MIN_ANIMATION_HEIGHT);
let mut buf = Buffer::empty(area);
(&widget).render_ref(area, &mut buf);
let welcome_row = row_containing(&buf, "Welcome");
assert_eq!(welcome_row, Some(ANIMATION_HEIGHT + 1));
widget.set_focused(/*focused*/ false);
(&widget).render_ref(area, &mut buf);
assert_eq!(row_containing(&buf, "Welcome"), welcome_row);
}
#[test]
fn welcome_skips_animation_below_height_breakpoint() {
let widget = WelcomeWidget::new(
/*is_logged_in*/ false,
FrameRequester::test_dummy(),
/*animations_enabled*/ true,
);
let area = Rect::new(0, 0, MIN_ANIMATION_WIDTH, MIN_ANIMATION_HEIGHT - 1);
let mut buf = Buffer::empty(area);
(&widget).render_ref(area, &mut buf);
let welcome_row = row_containing(&buf, "Welcome");
assert_eq!(welcome_row, Some(0));
}
#[test]
fn welcome_logo_layout() {
let (width, height) = (160, 48);
let widget = WelcomeWidget::new(
/*is_logged_in*/ false,
FrameRequester::test_dummy(),
/*animations_enabled*/ true,
);
// The first focused draw shows the intact logo at exactly zero elapsed time.
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let mut buf = Buffer::empty(area);
(&widget).render_ref(area, &mut buf);
let visible = (0..height)
.map(|y| {
(0..width)
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
.trim_end()
.to_owned()
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(format!("welcome_logo_{width}x{height}"), visible.trim_end());
}
}