mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Constrain API-key model access programs to server support (#53689)
## Why Servers can advertise cyber access programs without accepting them for API-key accounts. The TUI must account for server support before exposing those programs. ## What changed - Check `features.api_key_cyber_access_programs` at startup and when loading models for API-key accounts, clearing `available_access_programs` when forwarding is unavailable. - Use thread-scoped feature settings after thread creation and honor feature requirements and CLI overrides at startup. - Refresh account-scoped models when switching to or from API-key authentication or changing API-key thread context, clearing cached access programs while the refresh is pending. ## Testing Extend session tests to cover enabled and disabled server settings, CLI overrides, and catalog filtering before and after thread creation. Update account-change tests to handle the model refresh. GitOrigin-RevId: c80de30a0063b84949098d137715d8678bd70587
This commit is contained in:
@@ -17,6 +17,7 @@ use crate::config_update::format_config_error;
|
||||
use crate::external_agent_config_migration::flow::ExternalAgentConfigMigrationFlowOutcome;
|
||||
use crate::pager_overlay::TranscriptHistoryState;
|
||||
use crate::session_resume::cwds_differ;
|
||||
use crate::status::StatusAccountDisplay;
|
||||
use codex_app_server_client::AppServerEvent;
|
||||
use codex_app_server_protocol::ThreadGoalStatus;
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -2228,7 +2229,23 @@ impl App {
|
||||
app_server.fetch_models(request_id, self.app_event_tx.clone());
|
||||
}
|
||||
}
|
||||
AppEvent::ModelsLoaded { request_id, result } => {
|
||||
AppEvent::ModelsLoaded { request_id, result: Ok(models) }
|
||||
if self.chat_widget.model_popup_request_is_current(request_id)
|
||||
&& self.chat_widget.status_account_display() == Some(&StatusAccountDisplay::ApiKey) =>
|
||||
{
|
||||
let checked = app_server.constrain_api_key_models(
|
||||
self.chat_widget.config_ref(),
|
||||
self.chat_widget.thread_id(),
|
||||
/*requirements*/ None,
|
||||
models,
|
||||
);
|
||||
let tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
tx.send(AppEvent::ApiKeyCompatModelsLoaded { request_id, result: Ok(checked.await) });
|
||||
});
|
||||
}
|
||||
AppEvent::ModelsLoaded { request_id, result }
|
||||
| AppEvent::ApiKeyCompatModelsLoaded { request_id, result } => {
|
||||
if self.chat_widget.on_models_loaded(request_id, result) {
|
||||
self.model_catalog = self.chat_widget.model_catalog();
|
||||
app_server.set_available_models(self.model_catalog.try_list_models()?);
|
||||
|
||||
@@ -82,10 +82,11 @@ async fn misalignment_continuation_requires_current_review_and_submits_once() ->
|
||||
);
|
||||
app.chat_widget.open_model_popup();
|
||||
let request_id = std::iter::from_fn(|| rx.try_recv().ok())
|
||||
.find_map(|event| match event {
|
||||
.filter_map(|event| match event {
|
||||
AppEvent::FetchModels { request_id } => Some(request_id),
|
||||
_ => None,
|
||||
})
|
||||
.last()
|
||||
.expect("model catalog request");
|
||||
let mut model = crate::test_support::TEST_MODEL_PRESETS[0].clone();
|
||||
model.model = app.chat_widget.current_model().to_string();
|
||||
|
||||
@@ -206,6 +206,7 @@ async fn daybreak_command_persists_and_confirms_each_selection() -> Result<()> {
|
||||
app.chat_widget
|
||||
.set_feature_enabled(Feature::CliDaybreak, /*enabled*/ true);
|
||||
app.chat_widget.set_daybreak_enabled(/*enabled*/ true);
|
||||
let models = app.chat_widget.model_catalog().models.clone();
|
||||
app.chat_widget.update_account_state(
|
||||
Some(crate::status::StatusAccountDisplay::ApiKey),
|
||||
/*plan_type*/ None,
|
||||
@@ -213,6 +214,14 @@ async fn daybreak_command_persists_and_confirms_each_selection() -> Result<()> {
|
||||
/*has_codex_backend_auth*/ false,
|
||||
);
|
||||
assert!(!app.chat_widget.daybreak_enabled);
|
||||
let request_id = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.filter_map(|event| match event {
|
||||
AppEvent::FetchModels { request_id } => Some(request_id),
|
||||
_ => None,
|
||||
})
|
||||
.last()
|
||||
.expect("account model refresh");
|
||||
assert!(app.chat_widget.on_models_loaded(request_id, Ok(models)));
|
||||
for (cli_daybreak, api_key_cyber_access_programs, enabled) in [
|
||||
(false, false, true),
|
||||
(false, true, true),
|
||||
|
||||
@@ -1325,6 +1325,11 @@ pub(crate) enum AppEvent {
|
||||
request_id: uuid::Uuid,
|
||||
result: Result<Vec<ModelPreset>, String>,
|
||||
},
|
||||
/// Finished the API-key compatibility check; do not check the same catalog again.
|
||||
ApiKeyCompatModelsLoaded {
|
||||
request_id: uuid::Uuid,
|
||||
result: Result<Vec<ModelPreset>, String>,
|
||||
},
|
||||
|
||||
FetchPermissionProfiles {
|
||||
request_id: uuid::Uuid,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! This module owns the typed JSON-RPC calls needed by the TUI and keeps
|
||||
//! request/response plumbing out of `App` and `ChatWidget`.
|
||||
|
||||
mod daybreak_api_key_compat;
|
||||
mod external_agent_config;
|
||||
pub(crate) mod fs;
|
||||
mod history;
|
||||
@@ -335,6 +336,7 @@ pub(crate) struct AppServerSession {
|
||||
thread_settings_update_supported: bool,
|
||||
default_model: Option<String>,
|
||||
available_models: Vec<ModelPreset>,
|
||||
daybreak_api_key_compat: Arc<tokio::sync::Semaphore>,
|
||||
managed_new_thread_defaults: Option<NewThreadModelDefaults>,
|
||||
external_agent_config_import_id: Mutex<Option<String>>,
|
||||
dynamic_tool_mcp: Option<Arc<DynamicToolMcpServer>>,
|
||||
@@ -441,6 +443,7 @@ impl AppServerSession {
|
||||
thread_settings_update_supported: true,
|
||||
default_model: None,
|
||||
available_models: Vec::new(),
|
||||
daybreak_api_key_compat: Arc::new(tokio::sync::Semaphore::new(/*permits*/ 1)),
|
||||
managed_new_thread_defaults: None,
|
||||
external_agent_config_import_id: Mutex::default(),
|
||||
dynamic_tool_mcp: None,
|
||||
@@ -727,6 +730,16 @@ impl AppServerSession {
|
||||
&mut available_models,
|
||||
&requirements,
|
||||
);
|
||||
if matches!(account.account, Some(Account::ApiKey {})) {
|
||||
available_models = self
|
||||
.constrain_api_key_models(
|
||||
config,
|
||||
/*thread_id*/ None,
|
||||
requirements.requirements.as_ref(),
|
||||
available_models,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
self.managed_new_thread_defaults = requirements
|
||||
.requirements
|
||||
.and_then(|requirements| requirements.models)
|
||||
@@ -2618,6 +2631,7 @@ mod tests {
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions;
|
||||
use codex_protocol::openai_models::ModelAccessPrograms;
|
||||
use codex_protocol::openai_models::ModelServiceTier;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
@@ -2625,6 +2639,7 @@ mod tests {
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
@@ -2642,7 +2657,17 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn bootstrap_reuses_prefetched_account_without_another_account_read() -> Result<()> {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let config = build_config(&codex_home).await;
|
||||
let mut config = build_config(&codex_home).await;
|
||||
let mut catalog = codex_models_manager::bundled_models_response()?;
|
||||
for model in &mut catalog.models {
|
||||
model.available_access_programs = Some(ModelAccessPrograms {
|
||||
cyber: vec![
|
||||
CyberAccessProgram::Standard,
|
||||
CyberAccessProgram::DaybreakBlue,
|
||||
],
|
||||
});
|
||||
}
|
||||
config.model_catalog = Some(catalog);
|
||||
let mut app_server = crate::start_embedded_app_server_for_picker(&config).await?;
|
||||
let next_request_id = app_server.next_request_id;
|
||||
let account = GetAccountResponse {
|
||||
@@ -2674,6 +2699,63 @@ mod tests {
|
||||
)
|
||||
);
|
||||
|
||||
// Account-specific catalog filtering at startup and before/after thread creation.
|
||||
let models = bootstrap.available_models;
|
||||
assert!(
|
||||
models
|
||||
.iter()
|
||||
.any(|model| model.available_access_programs.is_some())
|
||||
);
|
||||
let client_home = tempfile::tempdir()?;
|
||||
let key = "features.api_key_cyber_access_programs";
|
||||
for (server_enabled, cli_override, forwarding_enabled) in [
|
||||
(false, None, false),
|
||||
(true, None, true),
|
||||
(false, Some(true), true),
|
||||
(true, Some(false), false),
|
||||
] {
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
format!("[features]\napi_key_cyber_access_programs = {server_enabled}\n"),
|
||||
)?;
|
||||
let client_config = ConfigBuilder::default()
|
||||
.codex_home(client_home.path().to_path_buf())
|
||||
.cli_overrides(
|
||||
cli_override
|
||||
.into_iter()
|
||||
.map(|value| (key.into(), value.into()))
|
||||
.collect(),
|
||||
)
|
||||
.build()
|
||||
.await?;
|
||||
let api_key = app_server
|
||||
.bootstrap_with_account(
|
||||
&client_config,
|
||||
GetAccountResponse {
|
||||
account: Some(Account::ApiKey {}),
|
||||
requires_openai_auth: true,
|
||||
workspace_routing: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut expected = models.clone();
|
||||
if !forwarding_enabled {
|
||||
for model in &mut expected {
|
||||
model.available_access_programs = None;
|
||||
}
|
||||
}
|
||||
assert_eq!(api_key.available_models, expected);
|
||||
let thread = app_server.start_thread(&client_config).await?;
|
||||
let refreshed = app_server
|
||||
.constrain_api_key_models(
|
||||
&client_config,
|
||||
Some(thread.session.thread_id),
|
||||
/*requirements*/ None,
|
||||
models.clone(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(refreshed, expected);
|
||||
}
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Compatibility with servers that advertise cyber programs without accepting them for API keys.
|
||||
//! Remove when supported servers all forward API-key programs. Both callers pass raw catalogs.
|
||||
|
||||
use super::AppServerSession;
|
||||
use super::thread_cwd_from_config;
|
||||
use crate::legacy_core::config::Config;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::ConfigReadParams;
|
||||
use codex_app_server_protocol::ConfigReadResponse;
|
||||
use codex_app_server_protocol::ConfigRequirements;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_config::ConfigLayerSource;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
use std::sync::Arc;
|
||||
|
||||
impl AppServerSession {
|
||||
pub(crate) fn constrain_api_key_models(
|
||||
&self,
|
||||
config: &Config,
|
||||
thread_id: Option<ThreadId>,
|
||||
requirements: Option<&ConfigRequirements>,
|
||||
mut models: Vec<ModelPreset>,
|
||||
) -> impl Future<Output = Vec<ModelPreset>> + Send + 'static {
|
||||
let cli_override = config
|
||||
.config_layer_stack
|
||||
.origins()
|
||||
.get("features.api_key_cyber_access_programs")
|
||||
.is_some_and(|origin| matches!(origin.name, ConfigLayerSource::SessionFlags))
|
||||
.then(|| config.features.enabled(Feature::ApiKeyCyberAccessPrograms));
|
||||
let startup_enabled = requirements
|
||||
.and_then(|r| r.feature_requirements.as_ref())
|
||||
.and_then(|features| features.get(Feature::ApiKeyCyberAccessPrograms.key()))
|
||||
.copied()
|
||||
.or(cli_override);
|
||||
let cwd = thread_cwd_from_config(
|
||||
config,
|
||||
self.thread_params_mode(),
|
||||
self.remote_cwd_override(),
|
||||
);
|
||||
let handle = self.request_handle();
|
||||
let lookup = Arc::clone(&self.daybreak_api_key_compat);
|
||||
async move {
|
||||
// Serialize the reserved ID. This semaphore is never closed.
|
||||
let _permit = lookup.acquire().await;
|
||||
const ID: &str = "tui-daybreak-forwarding";
|
||||
let forwarding_enabled = if let Some(thread_id) = thread_id {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
crate::experimental_features::fetch(handle, Some(thread_id), ID, tx);
|
||||
rx.await.ok().and_then(Result::ok).is_some_and(|features| {
|
||||
features.iter().any(|feature| {
|
||||
feature.name == Feature::ApiKeyCyberAccessPrograms.key() && feature.enabled
|
||||
})
|
||||
})
|
||||
} else if let Some(enabled) = startup_enabled {
|
||||
enabled
|
||||
} else {
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(/*secs*/ 5),
|
||||
handle.request_typed::<ConfigReadResponse>(ClientRequest::ConfigRead {
|
||||
request_id: RequestId::String(ID.into()),
|
||||
params: ConfigReadParams {
|
||||
include_layers: false,
|
||||
cwd,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.and_then(|response| {
|
||||
response
|
||||
.config
|
||||
.additional
|
||||
.get("features")?
|
||||
.get(Feature::ApiKeyCyberAccessPrograms.key())?
|
||||
.as_bool()
|
||||
})
|
||||
.unwrap_or(false)
|
||||
};
|
||||
if !forwarding_enabled {
|
||||
for model in &mut models {
|
||||
model.available_access_programs = None;
|
||||
}
|
||||
}
|
||||
models
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,17 @@ use super::model_popups::MODEL_SELECTION_VIEW_ID;
|
||||
use super::*;
|
||||
|
||||
impl ChatWidget {
|
||||
pub(super) fn refresh_account_scoped_models(&mut self) {
|
||||
if self.status_account_display == Some(StatusAccountDisplay::ApiKey) {
|
||||
for model in &mut Arc::make_mut(&mut self.model_catalog).models {
|
||||
model.available_access_programs = None;
|
||||
}
|
||||
}
|
||||
let request_id = uuid::Uuid::new_v4();
|
||||
self.model_popup_request_id = Some(request_id);
|
||||
self.app_event_tx.send(AppEvent::FetchModels { request_id });
|
||||
}
|
||||
|
||||
fn model_popup_view_id(&self) -> Option<&'static str> {
|
||||
[MODEL_SELECTION_VIEW_ID, ALL_MODELS_SELECTION_VIEW_ID]
|
||||
.into_iter()
|
||||
|
||||
@@ -93,6 +93,12 @@ impl ChatWidget {
|
||||
self.bottom_pane
|
||||
.set_queue_submissions(/*queue_submissions*/ false);
|
||||
if previous_thread_id != self.thread_id {
|
||||
if (previous_thread_id.is_some()
|
||||
|| (self.remote_connection.is_some() && self.config.cwd != session.cwd))
|
||||
&& self.status_account_display == Some(StatusAccountDisplay::ApiKey)
|
||||
{
|
||||
self.refresh_account_scoped_models();
|
||||
}
|
||||
self.backend_banner_notice_model = None;
|
||||
self.automatic_model_switch_state =
|
||||
backend_banners::AutomaticModelSwitchState::default();
|
||||
|
||||
@@ -260,6 +260,8 @@ impl ChatWidget {
|
||||
// Account-update notifications are the identity boundary. The visible account fields can
|
||||
// be identical across two accounts, so always invalidate account-scoped requests and data.
|
||||
self.model_popup_request_id = None;
|
||||
let api_key_changed = self.status_account_display == Some(StatusAccountDisplay::ApiKey)
|
||||
|| status_account_display == Some(StatusAccountDisplay::ApiKey);
|
||||
self.invalidate_permission_discovery();
|
||||
self.permission_discovery = None;
|
||||
self.invalidate_connector_scope();
|
||||
@@ -292,6 +294,9 @@ impl ChatWidget {
|
||||
self.status_account_display = status_account_display;
|
||||
self.plan_type = plan_type;
|
||||
self.has_chatgpt_account = has_chatgpt_account;
|
||||
if api_key_changed {
|
||||
self.refresh_account_scoped_models();
|
||||
}
|
||||
self.set_daybreak_enabled(self.daybreak_enabled);
|
||||
self.has_codex_backend_auth = has_codex_backend_auth;
|
||||
self.bottom_pane
|
||||
|
||||
Reference in New Issue
Block a user