Rimossi i provider integrati OpenAI, Bedrock e GCP e ogni fallback a OpenAI (B)
Parte "sicurezza" della fase 3 di aKode (e39aae00), senza le funzioni di imeAI:
- via i provider integrati openai, amazon-bedrock, amazon-bedrock-runtime e gcp
(crate model-provider: moduli amazon_bedrock, gcp, chatgpt_base_url; login Bedrock;
onboarding Bedrock/GCP; richieste app-server di setup cloud);
- nessun URL predefinito verso api.openai.com / chatgpt.com: un provider senza
base_url non viene mai contattato; senza model_provider configurato exec e TUI
mostrano come scriverne uno in config.toml (NO_MODEL_PROVIDER_CONFIGURED_ERROR);
- via la skill openai-docs, la sample skill-installer (scaricava da github.com/openai/skills),
request_plugin_install, AppsInstructions, URL predefiniti di realtime e updater;
- test di sicurezza adattati (provider "mock" al posto di quello integrato), non cancellati.
Restano fuori da questo commit (categoria F/D/E, non portate): chiave per provider nel
portachiavi, modelli da /models, unione dei messaggi di sistema, crate web-tools e
SearXNG, header @@ in apply_patch, modello ausiliario, tool function per apply_patch.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -47,10 +47,8 @@ use crate::LoginStatus;
|
||||
use crate::activation_key_guard::ActivationKeyGuard;
|
||||
use crate::key_hint::KeyBinding;
|
||||
use crate::key_hint::KeyBindingListExt;
|
||||
use crate::onboarding::bedrock::BedrockState;
|
||||
use crate::onboarding::gateway::GatewayStep;
|
||||
use crate::onboarding::gateway::USE_CUSTOM_PROVIDER;
|
||||
use crate::onboarding::gcp::GcpState;
|
||||
use crate::onboarding::keys;
|
||||
use crate::onboarding::onboarding_screen::KeyboardHandler;
|
||||
use crate::onboarding::onboarding_screen::StepStateProvider;
|
||||
@@ -74,10 +72,6 @@ pub(crate) enum SignInState {
|
||||
PickMode,
|
||||
ApiKeyEntry(ApiKeyInputState),
|
||||
ApiKeyConfigured,
|
||||
Bedrock(BedrockState),
|
||||
BedrockConfigured,
|
||||
Gcp(GcpState),
|
||||
GcpConfigured,
|
||||
GatewaySelected(String),
|
||||
GatewayOAuth {
|
||||
provider_id: String,
|
||||
@@ -93,8 +87,6 @@ pub(crate) enum SignInState {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum SignInOption {
|
||||
ApiKey,
|
||||
Bedrock,
|
||||
Gcp,
|
||||
Gateway,
|
||||
}
|
||||
|
||||
@@ -119,10 +111,7 @@ impl KeyboardHandler for AuthModeWidget {
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.handle_gcp_key_event(&key_event)
|
||||
|| self.handle_bedrock_key_event(&key_event)
|
||||
|| self.handle_gateway_key_event(key_event)
|
||||
{
|
||||
if self.handle_gateway_key_event(key_event) {
|
||||
return;
|
||||
}
|
||||
if self.handle_api_key_entry_key_event(&key_event) {
|
||||
@@ -178,22 +167,12 @@ impl KeyboardHandler for AuthModeWidget {
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut state = self.sign_in_state.write().unwrap();
|
||||
let input = match &mut *state {
|
||||
SignInState::Bedrock(state) => state.active_input_mut(),
|
||||
SignInState::Gcp(state) => state.active_input_mut(),
|
||||
SignInState::ApiKeyEntry(_) => {
|
||||
drop(state);
|
||||
let _ = self.handle_api_key_entry_paste(pasted);
|
||||
return;
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(input) = input {
|
||||
input.paste(&pasted);
|
||||
self.set_error(/*message*/ None);
|
||||
drop(state);
|
||||
self.request_frame.schedule_frame();
|
||||
let is_api_key_entry = matches!(
|
||||
*self.sign_in_state.read().unwrap(),
|
||||
SignInState::ApiKeyEntry(_)
|
||||
);
|
||||
if is_api_key_entry {
|
||||
let _ = self.handle_api_key_entry_paste(pasted);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -209,8 +188,6 @@ pub(crate) struct AuthModeWidget {
|
||||
pub app_server_target: crate::AppServerTarget,
|
||||
pub app_server_request_handle: AppServerRequestHandle,
|
||||
pub auth_config: AuthConfig,
|
||||
pub bedrock_setup_enabled: bool,
|
||||
pub gcp_setup_enabled: bool,
|
||||
pub gateway_setup_enabled: bool,
|
||||
pub(super) gateway: Option<GatewayStep>,
|
||||
}
|
||||
@@ -231,24 +208,20 @@ impl AuthModeWidget {
|
||||
}
|
||||
self.sign_in_state.read().is_ok_and(|guard| match &*guard {
|
||||
SignInState::ApiKeyEntry(_) => true,
|
||||
SignInState::Bedrock(state) => state.is_text_entry_active(),
|
||||
SignInState::Gcp(state) => state.is_text_entry_active(),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns whether printable quit shortcuts must be treated as text input.
|
||||
///
|
||||
/// OpenAI API-key entry keeps its existing empty-field quit behavior, while
|
||||
/// Cloud setup fields accept printable input from their first character.
|
||||
/// API-key entry keeps its existing empty-field quit behavior, while
|
||||
/// provider setup fields accept printable input from their first character.
|
||||
pub(crate) fn should_suppress_printable_quit(&self) -> bool {
|
||||
if let Some(wizard) = &self.gateway {
|
||||
return wizard.is_text_entry_active();
|
||||
}
|
||||
self.sign_in_state.read().is_ok_and(|guard| match &*guard {
|
||||
SignInState::ApiKeyEntry(state) => !state.value.is_empty(),
|
||||
SignInState::Bedrock(state) => state.is_text_entry_active(),
|
||||
SignInState::Gcp(state) => state.is_text_entry_active(),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
@@ -268,12 +241,6 @@ impl AuthModeWidget {
|
||||
|
||||
fn displayed_sign_in_options(&self) -> Vec<SignInOption> {
|
||||
let mut options = vec![SignInOption::ApiKey];
|
||||
if self.bedrock_setup_enabled {
|
||||
options.push(SignInOption::Bedrock);
|
||||
}
|
||||
if self.gcp_setup_enabled {
|
||||
options.push(SignInOption::Gcp);
|
||||
}
|
||||
if self.gateway_setup_enabled {
|
||||
options.push(SignInOption::Gateway);
|
||||
}
|
||||
@@ -333,22 +300,6 @@ impl AuthModeWidget {
|
||||
self.disallow_api_login();
|
||||
}
|
||||
}
|
||||
SignInOption::Bedrock => {
|
||||
if self.bedrock_setup_enabled && self.is_api_login_allowed() {
|
||||
self.start_bedrock_discovery();
|
||||
} else if !self.is_api_login_allowed() {
|
||||
self.disallow_api_login();
|
||||
}
|
||||
}
|
||||
SignInOption::Gcp => {
|
||||
if self.gcp_setup_enabled && self.is_api_login_allowed() {
|
||||
*self.sign_in_state.write().unwrap() = SignInState::Gcp(GcpState::default());
|
||||
self.set_error(/*message*/ None);
|
||||
self.request_frame.schedule_frame();
|
||||
} else if !self.is_api_login_allowed() {
|
||||
self.disallow_api_login();
|
||||
}
|
||||
}
|
||||
SignInOption::Gateway => {
|
||||
if self.gateway_setup_enabled && self.is_api_login_allowed() {
|
||||
self.start_gateway_picker();
|
||||
@@ -367,12 +318,11 @@ impl AuthModeWidget {
|
||||
}
|
||||
|
||||
fn render_pick_mode(&self, area: Rect, buf: &mut Buffer) {
|
||||
let mut lines: Vec<Line> =
|
||||
if self.bedrock_setup_enabled || self.gcp_setup_enabled || self.gateway_setup_enabled {
|
||||
vec![" Choose how you want to use Codex.".into(), "".into()]
|
||||
} else {
|
||||
vec![" Connect an API key to use Codex.".into(), "".into()]
|
||||
};
|
||||
let mut lines: Vec<Line> = if self.gateway_setup_enabled {
|
||||
vec![" Choose how you want to use Codex.".into(), "".into()]
|
||||
} else {
|
||||
vec![" Connect an API key to use Codex.".into(), "".into()]
|
||||
};
|
||||
|
||||
let options_start = lines.len();
|
||||
let mut compact_options = Vec::new();
|
||||
@@ -416,22 +366,6 @@ impl AuthModeWidget {
|
||||
"Pay for what you use",
|
||||
));
|
||||
}
|
||||
SignInOption::Bedrock => {
|
||||
lines.extend(create_mode_item(
|
||||
idx,
|
||||
option,
|
||||
"Use Amazon Bedrock",
|
||||
"Connect using your AWS credentials",
|
||||
));
|
||||
}
|
||||
SignInOption::Gcp => {
|
||||
lines.extend(create_mode_item(
|
||||
idx,
|
||||
option,
|
||||
"Use Google Cloud Vertex AI",
|
||||
"Connect using your Google Cloud credentials",
|
||||
));
|
||||
}
|
||||
SignInOption::Gateway => {
|
||||
lines.extend(create_mode_item(
|
||||
idx,
|
||||
@@ -697,15 +631,6 @@ impl AuthModeWidget {
|
||||
*error.write().unwrap() = None;
|
||||
*sign_in_state.write().unwrap() = SignInState::ApiKeyConfigured;
|
||||
}
|
||||
Ok(other) => {
|
||||
*error.write().unwrap() = Some(format!(
|
||||
"Unexpected account/login/start response: {other:?}"
|
||||
));
|
||||
*sign_in_state.write().unwrap() = SignInState::ApiKeyEntry(ApiKeyInputState {
|
||||
value: api_key,
|
||||
prepopulated_from_env: false,
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
*error.write().unwrap() = Some(format!("Failed to save API key: {err}"));
|
||||
*sign_in_state.write().unwrap() = SignInState::ApiKeyEntry(ApiKeyInputState {
|
||||
@@ -726,8 +651,6 @@ impl AuthModeWidget {
|
||||
LoginStatus::AuthMode(match auth_mode {
|
||||
ApiAuthMode::ApiKey => AuthMode::ApiKey,
|
||||
ApiAuthMode::Headers => AuthMode::Headers,
|
||||
ApiAuthMode::BedrockApiKey => AuthMode::BedrockApiKey,
|
||||
ApiAuthMode::BedrockAccessKeys => AuthMode::BedrockAccessKeys,
|
||||
})
|
||||
})
|
||||
.unwrap_or(LoginStatus::NotAuthenticated);
|
||||
@@ -740,13 +663,9 @@ impl StepStateProvider for AuthModeWidget {
|
||||
match &*sign_in_state {
|
||||
SignInState::PickMode
|
||||
| SignInState::ApiKeyEntry(_)
|
||||
| SignInState::Bedrock(_)
|
||||
| SignInState::Gcp(_)
|
||||
| SignInState::GatewayOAuth { .. }
|
||||
| SignInState::GatewayOAuthFailed { .. } => StepState::InProgress,
|
||||
SignInState::ApiKeyConfigured
|
||||
| SignInState::BedrockConfigured
|
||||
| SignInState::GcpConfigured
|
||||
| SignInState::GatewaySelected(_)
|
||||
| SignInState::GatewayConfigured => StepState::Complete,
|
||||
}
|
||||
@@ -770,12 +689,6 @@ impl WidgetRef for AuthModeWidget {
|
||||
SignInState::ApiKeyConfigured => {
|
||||
self.render_api_key_configured(area, buf);
|
||||
}
|
||||
SignInState::Bedrock(state) => {
|
||||
state.render(area, buf, self.error_message());
|
||||
}
|
||||
SignInState::Gcp(state) => {
|
||||
state.render(area, buf, self.error_message());
|
||||
}
|
||||
SignInState::GatewayOAuth { url, .. } => {
|
||||
let mut lines = vec![Line::from(
|
||||
"Finish signing in to your gateway in the browser.".bold(),
|
||||
@@ -804,16 +717,6 @@ impl WidgetRef for AuthModeWidget {
|
||||
.wrap(Wrap { trim: false })
|
||||
.render(area, buf);
|
||||
}
|
||||
SignInState::GcpConfigured => {
|
||||
Paragraph::new("✓ Google Cloud Vertex AI configured".green())
|
||||
.wrap(Wrap { trim: false })
|
||||
.render(area, buf);
|
||||
}
|
||||
SignInState::BedrockConfigured => {
|
||||
Paragraph::new("✓ Amazon Bedrock configured".green())
|
||||
.wrap(Wrap { trim: false })
|
||||
.render(area, buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -888,8 +791,6 @@ mod tests {
|
||||
app_server_target: crate::AppServerTarget::Embedded,
|
||||
app_server_request_handle: AppServerRequestHandle::InProcess(client.request_handle()),
|
||||
auth_config,
|
||||
bedrock_setup_enabled: false,
|
||||
gcp_setup_enabled: false,
|
||||
gateway_setup_enabled: false,
|
||||
gateway: None,
|
||||
};
|
||||
@@ -936,7 +837,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bedrock_option_requires_feature_and_api_login_permission() {
|
||||
async fn gateway_option_requires_feature_and_api_login_permission() {
|
||||
let (mut widget, codex_home) = widget_api_login_forbidden().await;
|
||||
widget.auth_config.forced_login_method = None;
|
||||
assert_eq!(
|
||||
@@ -946,7 +847,7 @@ mod tests {
|
||||
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
"model_provider = \"openai\"\n[features]\nbedrock_setup_wizard = true\n",
|
||||
"[features]\ngateway_setup_wizard = true\n",
|
||||
)
|
||||
.unwrap();
|
||||
let config = ConfigBuilder::default()
|
||||
@@ -954,16 +855,16 @@ mod tests {
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
widget.bedrock_setup_enabled = crate::should_show_provider_setup_wizard(
|
||||
widget.gateway_setup_enabled = crate::should_show_provider_setup_wizard(
|
||||
widget.login_status,
|
||||
/*requires_openai_auth*/ true,
|
||||
&config,
|
||||
&widget.app_server_target,
|
||||
Feature::BedrockSetupWizard,
|
||||
Feature::GatewaySetupWizard,
|
||||
);
|
||||
assert_eq!(
|
||||
widget.displayed_sign_in_options(),
|
||||
vec![SignInOption::ApiKey, SignInOption::Bedrock]
|
||||
vec![SignInOption::ApiKey, SignInOption::Gateway]
|
||||
);
|
||||
widget.move_highlight(/*delta*/ 1);
|
||||
|
||||
@@ -988,8 +889,8 @@ mod tests {
|
||||
1. Use an OpenAI API key
|
||||
Pay for what you use
|
||||
|
||||
> 2. Use Amazon Bedrock
|
||||
Connect using your AWS credentials
|
||||
> 2. Use a custom provider or gateway
|
||||
Choose a saved configuration or create a new one
|
||||
|
||||
Press enter to continue
|
||||
"###);
|
||||
@@ -1090,10 +991,6 @@ mod tests {
|
||||
#[cfg(test)]
|
||||
mod activation_key_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gcp_tests.rs"]
|
||||
mod gcp_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gateway_tests.rs"]
|
||||
mod gateway_tests;
|
||||
|
||||
@@ -1,819 +0,0 @@
|
||||
//! 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(), ®ion);
|
||||
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;
|
||||
@@ -1,561 +0,0 @@
|
||||
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")
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -42,8 +42,6 @@ pub(crate) async fn authenticate_gateway(
|
||||
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,
|
||||
|
||||
@@ -33,19 +33,17 @@ fn screen(widget: &AuthModeWidget, height: u16) -> String {
|
||||
async fn select_a_saved_gateway_during_sign_in() -> color_eyre::Result<()> {
|
||||
let (mut widget, home) = super::tests::widget_api_login_forbidden().await;
|
||||
widget.auth_config.forced_login_method = None;
|
||||
widget.bedrock_setup_enabled = true;
|
||||
widget.gcp_setup_enabled = true;
|
||||
widget.gateway_setup_enabled = true;
|
||||
|
||||
insta::assert_snapshot!("gateway_sign_in_menu", screen(&widget, /*height*/ 8));
|
||||
widget.handle_key_event(KeyCode::Char('4').into());
|
||||
widget.handle_key_event(KeyCode::Char('2').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.handle_key_event(KeyCode::Char('2').into());
|
||||
widget.advance_gateway_request().await;
|
||||
let error = screen(&widget, /*height*/ 8);
|
||||
assert!(error.contains("configuration policy"));
|
||||
@@ -61,7 +59,7 @@ base_url = "https://office.example.test/v1"
|
||||
wire_api = "responses"
|
||||
"#,
|
||||
)?;
|
||||
widget.handle_key_event(KeyCode::Char('4').into());
|
||||
widget.handle_key_event(KeyCode::Char('2').into());
|
||||
widget.advance_gateway_request().await;
|
||||
insta::assert_snapshot!("gateway_saved_picker", screen(&widget, /*height*/ 8));
|
||||
widget.handle_key_event(KeyCode::Enter.into());
|
||||
@@ -78,8 +76,6 @@ wire_api = "responses"
|
||||
async fn create_highlights_the_saved_gateway_until_explicitly_selected() -> color_eyre::Result<()> {
|
||||
let (mut widget, home) = super::tests::widget_api_login_forbidden().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,
|
||||
@@ -93,7 +89,7 @@ async fn create_highlights_the_saved_gateway_until_explicitly_selected() -> colo
|
||||
)
|
||||
.await
|
||||
.map_err(color_eyre::Report::msg)?;
|
||||
widget.handle_key_event(KeyCode::Char('4').into());
|
||||
widget.handle_key_event(KeyCode::Char('2').into());
|
||||
widget.advance_gateway_request().await;
|
||||
widget.handle_key_event(KeyCode::Down.into());
|
||||
widget.handle_key_event(KeyCode::Enter.into());
|
||||
@@ -144,7 +140,8 @@ async fn create_highlights_the_saved_gateway_until_explicitly_selected() -> colo
|
||||
let page = list_providers(&widget.app_server_request_handle)
|
||||
.await
|
||||
.map_err(color_eyre::Report::msg)?;
|
||||
assert_eq!(page.default_provider_id, "openai");
|
||||
// aKode has no default provider until one is selected.
|
||||
assert_eq!(page.default_provider_id, "");
|
||||
|
||||
widget.handle_key_event(KeyEvent::new_with_kind(
|
||||
KeyCode::Enter,
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
//! 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
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
#![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_api_login_forbidden().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;
|
||||
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));
|
||||
assert_eq!(widget.highlighted_mode, SignInOption::Gcp);
|
||||
snapshot(&widget, "gcp_sign_in_menu_short", Rect::new(0, 0, 76, 8));
|
||||
let area = Rect::new(0, 0, 76, 12);
|
||||
|
||||
widget.auth_config.forced_login_method = Some(ForcedLoginMethod::Chatgpt);
|
||||
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.handle_key_event(press(KeyCode::Char('3')));
|
||||
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()
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
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_required;
|
||||
pub(crate) use provider_required::model_provider_missing;
|
||||
pub(crate) use provider_required::show_no_model_provider_setup;
|
||||
mod provider_setup;
|
||||
pub(crate) use provider_setup::FieldDisplay;
|
||||
pub(crate) use provider_setup::ProviderInput;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Onboarding screen orchestration and top-level keyboard routing.
|
||||
//!
|
||||
//! The onboarding flow is a small state machine over visible steps
|
||||
//! (welcome/auth/trust/GovCloud). This module decides which step receives key/paste
|
||||
//! (welcome/auth/trust). This module decides which step receives key/paste
|
||||
//! events and enforces flow-level safety rules that cut across individual step
|
||||
//! widgets. Folder-entry consent reuses this same event loop for startup and in-app navigation.
|
||||
//!
|
||||
@@ -41,7 +41,6 @@ use crate::legacy_core::config::Config;
|
||||
use crate::onboarding::auth::AuthModeWidget;
|
||||
use crate::onboarding::auth::SignInOption;
|
||||
use crate::onboarding::auth::SignInState;
|
||||
use crate::onboarding::bedrock::BedrockState;
|
||||
use crate::onboarding::keys;
|
||||
use crate::onboarding::trust_directory::TrustDirectorySelection;
|
||||
use crate::onboarding::trust_directory::TrustDirectoryWidget;
|
||||
@@ -67,10 +66,6 @@ enum Step {
|
||||
Welcome(WelcomeWidget),
|
||||
Auth(AuthModeWidget),
|
||||
TrustDirectory(TrustDirectoryWidget),
|
||||
GovCloudGuidance {
|
||||
state: BedrockState,
|
||||
acknowledged: bool,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) trait KeyboardHandler {
|
||||
@@ -101,8 +96,6 @@ pub(crate) struct OnboardingScreenArgs {
|
||||
pub show_trust_screen: bool,
|
||||
pub remote_project_trust: Option<RemoteProjectTrust>,
|
||||
pub show_login_screen: bool,
|
||||
pub bedrock_setup_enabled: bool,
|
||||
pub gcp_setup_enabled: bool,
|
||||
pub gateway_setup_enabled: bool,
|
||||
pub login_status: LoginStatus,
|
||||
pub app_server_target: crate::AppServerTarget,
|
||||
@@ -131,8 +124,6 @@ impl OnboardingScreen {
|
||||
show_trust_screen,
|
||||
remote_project_trust,
|
||||
show_login_screen,
|
||||
bedrock_setup_enabled,
|
||||
gcp_setup_enabled,
|
||||
gateway_setup_enabled,
|
||||
login_status,
|
||||
app_server_target,
|
||||
@@ -180,8 +171,6 @@ impl OnboardingScreen {
|
||||
app_server_target,
|
||||
app_server_request_handle,
|
||||
auth_config,
|
||||
bedrock_setup_enabled,
|
||||
gcp_setup_enabled,
|
||||
gateway_setup_enabled,
|
||||
gateway: None,
|
||||
}));
|
||||
@@ -285,7 +274,7 @@ impl OnboardingScreen {
|
||||
pub(super) fn auth_widget_mut(&mut self) -> Option<&mut AuthModeWidget> {
|
||||
self.steps.iter_mut().find_map(|step| match step {
|
||||
Step::Auth(widget) => Some(widget),
|
||||
Step::Welcome(_) | Step::TrustDirectory(_) | Step::GovCloudGuidance { .. } => None,
|
||||
Step::Welcome(_) | Step::TrustDirectory(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -326,7 +315,7 @@ impl KeyboardHandler for OnboardingScreen {
|
||||
/// Route key events to onboarding steps while preserving text-entry safety.
|
||||
///
|
||||
/// OpenAI API-key entry suppresses printable quit bindings after typing
|
||||
/// starts, while cloud provider fields suppress them from the first character.
|
||||
/// starts, while provider setup fields suppress them from the first character.
|
||||
/// Control/alt quit chords still work as emergency exits.
|
||||
fn handle_key_event(&mut self, key_event: KeyEvent) {
|
||||
if key_event.kind == KeyEventKind::Release {
|
||||
@@ -344,12 +333,7 @@ impl KeyboardHandler for OnboardingScreen {
|
||||
// If the user cancels the auth menu, exit the app rather than
|
||||
// leave the user at a prompt in an unauthed state.
|
||||
self.should_exit = true;
|
||||
} else if self.is_trust_step_active()
|
||||
|| self
|
||||
.steps
|
||||
.iter()
|
||||
.any(|step| matches!(step, Step::GovCloudGuidance { .. }))
|
||||
{
|
||||
} else if self.is_trust_step_active() {
|
||||
self.should_exit = true;
|
||||
}
|
||||
self.is_done = true;
|
||||
@@ -413,7 +397,7 @@ impl WidgetRef for &OnboardingScreen {
|
||||
for step in self.current_steps() {
|
||||
match step {
|
||||
Step::Welcome(widget) => widget.set_presentation(logo_presentation),
|
||||
Step::Auth(_) | Step::TrustDirectory(_) | Step::GovCloudGuidance { .. } => {}
|
||||
Step::Auth(_) | Step::TrustDirectory(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -487,18 +471,12 @@ impl KeyboardHandler for Step {
|
||||
Step::Welcome(widget) => widget.handle_key_event(key_event),
|
||||
Step::Auth(widget) => widget.handle_key_event(key_event),
|
||||
Step::TrustDirectory(widget) => widget.handle_key_event(key_event),
|
||||
Step::GovCloudGuidance {
|
||||
state,
|
||||
acknowledged,
|
||||
} => {
|
||||
*acknowledged = state.handle_guidance_key_event(&key_event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_paste(&mut self, pasted: String) {
|
||||
match self {
|
||||
Step::Welcome(_) | Step::GovCloudGuidance { .. } => {}
|
||||
Step::Welcome(_) => {}
|
||||
Step::Auth(widget) => widget.handle_paste(pasted),
|
||||
Step::TrustDirectory(widget) => widget.handle_paste(pasted),
|
||||
}
|
||||
@@ -511,13 +489,6 @@ impl StepStateProvider for Step {
|
||||
Step::Welcome(w) => w.get_step_state(),
|
||||
Step::Auth(w) => w.get_step_state(),
|
||||
Step::TrustDirectory(w) => w.get_step_state(),
|
||||
Step::GovCloudGuidance { acknowledged, .. } => {
|
||||
if *acknowledged {
|
||||
StepState::Complete
|
||||
} else {
|
||||
StepState::InProgress
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -534,32 +505,10 @@ impl WidgetRef for Step {
|
||||
Step::TrustDirectory(widget) => {
|
||||
widget.render_ref(area, buf);
|
||||
}
|
||||
Step::GovCloudGuidance { state, .. } => state.render(area, buf, /*error*/ None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn run_gov_cloud_guidance(tui: &mut Tui) -> Result<()> {
|
||||
let screen = OnboardingScreen {
|
||||
request_frame: tui.frame_requester(),
|
||||
steps: vec![Step::GovCloudGuidance {
|
||||
state: BedrockState::guidance(),
|
||||
acknowledged: false,
|
||||
}],
|
||||
remote_trust_key: None,
|
||||
is_done: false,
|
||||
should_exit: false,
|
||||
};
|
||||
let result = run_onboarding_screen(
|
||||
screen, /*app_server_request_handle*/ None, /*app_server*/ None, tui,
|
||||
)
|
||||
.await?;
|
||||
if result.should_exit {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, StartupCancelled).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn run_onboarding_app(
|
||||
args: OnboardingScreenArgs,
|
||||
app_server: Option<&mut AppServerSession>,
|
||||
|
||||
67
codex-rs/tui/src/onboarding/provider_required.rs
Normal file
67
codex-rs/tui/src/onboarding/provider_required.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
//! Startup guidance shown when no model provider is configured.
|
||||
//!
|
||||
//! aKode ships no default provider, so a fresh installation cannot start a model session until
|
||||
//! the user adds one. For now startup prints the setup guidance and exits with an error; a
|
||||
//! first-run onboarding screen can replace [`show_no_model_provider_setup`] later.
|
||||
|
||||
use codex_app_server_client::AppServerRequestHandle;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::ConfigReadParams;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_model_provider_info::NO_MODEL_PROVIDER_CONFIGURED_ERROR;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppExitInfo;
|
||||
use crate::ExitReason;
|
||||
use crate::config_update::EffectiveConfig;
|
||||
use crate::legacy_core::config::Config;
|
||||
use crate::tui::Tui;
|
||||
|
||||
/// Whether neither the local configuration nor the connected app server selects a provider.
|
||||
///
|
||||
/// A connected server can resolve a provider from its own configuration, so a missing local
|
||||
/// provider alone is not enough. When the server cannot answer, startup continues and reports
|
||||
/// any provider error through the normal session path.
|
||||
pub(crate) async fn model_provider_missing(
|
||||
config: &Config,
|
||||
request_handle: AppServerRequestHandle,
|
||||
) -> bool {
|
||||
if config.model_provider_configured() {
|
||||
return false;
|
||||
}
|
||||
let server_config = request_handle
|
||||
.request_typed::<EffectiveConfig>(ClientRequest::ConfigRead {
|
||||
request_id: RequestId::String(format!("tui-provider-check-{}", Uuid::new_v4())),
|
||||
params: ConfigReadParams {
|
||||
include_layers: false,
|
||||
cwd: Some(config.cwd.display().to_string()),
|
||||
},
|
||||
})
|
||||
.await;
|
||||
match server_config {
|
||||
Ok(server_config) => server_config
|
||||
.config
|
||||
.model_provider
|
||||
.as_deref()
|
||||
.is_none_or(|provider| provider.trim().is_empty()),
|
||||
Err(err) => {
|
||||
tracing::warn!(%err, "Failed to read the server's model provider");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Explain how to configure a model provider instead of starting a model session.
|
||||
///
|
||||
/// The returned exit info makes the caller print the guidance and exit with a non-zero status.
|
||||
pub(crate) fn show_no_model_provider_setup(tui: &mut Tui) -> AppExitInfo {
|
||||
let _ = tui.terminal.clear();
|
||||
AppExitInfo {
|
||||
token_usage: crate::token_usage::TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::Fatal(NO_MODEL_PROVIDER_CONFIGURED_ERROR.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,12 @@
|
||||
//! Single-line fields shared by provider settings and the cloud setup wizards.
|
||||
//! Single-line fields shared by provider settings and the gateway setup form.
|
||||
|
||||
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;
|
||||
@@ -25,8 +21,6 @@ pub(crate) struct ProviderInput(Arc<Mutex<TextArea>>);
|
||||
pub(crate) enum FieldDisplay {
|
||||
Focused,
|
||||
Unfocused,
|
||||
FocusedSecret,
|
||||
UnfocusedSecret,
|
||||
}
|
||||
|
||||
impl Default for ProviderInput {
|
||||
@@ -76,7 +70,7 @@ impl ProviderInput {
|
||||
line.push_span(placeholder.to_owned().dim());
|
||||
return line;
|
||||
}
|
||||
let focused = matches!(display, FieldDisplay::Focused | FieldDisplay::FocusedSecret);
|
||||
let focused = matches!(display, FieldDisplay::Focused);
|
||||
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 {
|
||||
@@ -89,14 +83,8 @@ impl ProviderInput {
|
||||
} 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());
|
||||
for (offset, grapheme) in editor.text()[start..].grapheme_indices(true) {
|
||||
let span = Span::raw(grapheme.to_owned());
|
||||
let span = if focused { span.cyan() } else { span };
|
||||
let Some(rest) = remaining.checked_sub(span.width()) else {
|
||||
break;
|
||||
@@ -125,39 +113,3 @@ pub(crate) fn move_provider_field(key: KeyEvent, selected: &mut usize, count: us
|
||||
};
|
||||
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();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
---
|
||||
source: tui/src/onboarding/gateway_tests.rs
|
||||
assertion_line: 40
|
||||
assertion_line: 38
|
||||
expression: "screen(&widget, 8)"
|
||||
---
|
||||
Choose how you want to use Codex.
|
||||
|
||||
> 1. Use an OpenAI API key
|
||||
2. Use Amazon Bedrock
|
||||
3. Use Google Cloud Vertex AI
|
||||
4. Use a custom provider or gateway
|
||||
2. Use a custom provider or gateway
|
||||
Press enter to continue
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
source: tui/src/onboarding/gcp_tests.rs
|
||||
expression: terminal.backend().to_string()
|
||||
---
|
||||
✓ Google Cloud Vertex AI configured
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
source: tui/src/onboarding/gcp_tests.rs
|
||||
expression: terminal.backend().to_string()
|
||||
---
|
||||
> Set up Google Cloud Vertex AI
|
||||
|
||||
Validating credentials and saving configuration…
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,16 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,22 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
source: tui/src/onboarding/gcp_tests.rs
|
||||
assertion_line: 34
|
||||
expression: terminal.backend().to_string()
|
||||
---
|
||||
Choose how you want to use Codex.
|
||||
|
||||
> 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
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
source: tui/src/onboarding/gcp_tests.rs
|
||||
assertion_line: 34
|
||||
expression: terminal.backend().to_string()
|
||||
---
|
||||
Choose how you want to use Codex.
|
||||
|
||||
1. Use an OpenAI API key
|
||||
2. Use Amazon Bedrock
|
||||
> 3. Use Google Cloud Vertex AI
|
||||
Press enter to continue
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
source: tui/src/onboarding/gcp_tests.rs
|
||||
assertion_line: 34
|
||||
expression: terminal.backend().to_string()
|
||||
---
|
||||
Connect an API key to use Codex.
|
||||
|
||||
> 1. Use an OpenAI API key
|
||||
Pay for what you use
|
||||
|
||||
Press enter to continue
|
||||
@@ -1,13 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,10 +0,0 @@
|
||||
---
|
||||
source: tui/src/onboarding/bedrock_tests.rs
|
||||
expression: initial
|
||||
---
|
||||
Using Codex with AWS
|
||||
GovCloud
|
||||
|
||||
You are using Codex with
|
||||
> Acknowledge
|
||||
↑/↓ scroll · enter
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Shared welcome header for the existing sign-in and Bedrock onboarding pickers.
|
||||
//! Shared welcome header for the onboarding sign-in picker.
|
||||
//! The logo occupies a fixed stage so its motion never shifts the choices below it.
|
||||
|
||||
use crossterm::event::KeyEvent;
|
||||
|
||||
Reference in New Issue
Block a user