Connect app-server workspace discovery to model request routing (#46281)

## Why

Model requests need the selected workspace's routing constraints before sending content. A missing cached route cannot establish that a custom ChatGPT-auth destination is independent of the workspace.

## What changed

- Register the account processor as the workspace routing resolver for Responses HTTP, compaction, and WebSockets, enabling origin selection and routing headers while preserving API paths and rejecting routed HTTP redirects.
- Share concurrent discovery by auth generation, workspace, and backend configuration. Recover from discovery-time `401` responses while allowing token refreshes for the same auth owner.
- Require successful discovery before classifying custom destinations as independent, and require a new thread when a workspace-bound session's bootstrap origin changes.
- Refresh managed requirements using retained session configuration without fetching thread configuration again. Return typed routing errors without account or backend details.

## Testing

Extend coverage for discovery-time token refresh, retained provider definitions under managed requirements, and specific invalid-routing error categories.

GitOrigin-RevId: 090cda70daa91ee8acfbc973699d028111e54125
This commit is contained in:
acrognale-oai
2026-09-17 19:12:42 +00:00
committed by copyberry
parent d7f8e48d7d
commit 0a5b999169
21 changed files with 505 additions and 200 deletions
+11 -1
View File
@@ -283,7 +283,17 @@ The experimental `account/read.workspaceRouting` response field returns the sele
App-server discovers routing for saved ChatGPT logins at startup and for new logins or workspace switches. After requirements and routing are ready, it sends the existing `account/updated` notification. Newly initialized connections also receive this notification once saved-workspace routing is ready, including when discovery finished before the connection initialized. Clients then reread `configRequirements/read` and `account/read`. Saved ChatGPT credentials without a selected workspace ID retain their account information and return `workspaceRouting: null`; app-server does not guess a workspace from the backend's default account. Discovery failures for a selected workspace, including missing or null fields from older backends, return an `account/read` error. They never produce a successful unrestricted result. A later read retries failed discovery. Logout clears the cached routing, and results from earlier authentication owners are discarded. Token refreshes for the same known user and workspace invalidate cached routing without cancelling discovery or failing sign-in. Configuration is reloaded after discovery; a changed backend, model provider, or required backend rejects the result so the next read discovers against current configuration. Account notifications recheck the auth owner generation after waiting for outbound queue capacity. Superseded sign-in attempts emit a failed `account/login/completed` event instead of silently dropping completion. Notifications remain snapshots: clients reread current account and requirements state rather than treating a queued notification as authorization.
The origin of a required `chatgpt_base_url` must match the discovered origin by scheme, host, and effective port. The base URL's API path is not part of this comparison. Either origin alone is sufficient. If requirements specify no base URL and discovery explicitly returns `NO_CONSTRAINT`, the effective `chatgpt_base_url` supplies the origin, including its existing default. `backendOrigin` is always a resolved origin; `accountRoutingOverride` preserves `NO_CONSTRAINT` when the backend explicitly returns it. Discovering an origin does not change API paths or apply routing headers to requests.
Routing compares origins by scheme, host, and effective port, ignoring API paths. A required
`chatgpt_base_url` must match discovery; if neither provides an origin, `NO_CONSTRAINT` uses the
configured base URL.
Responses HTTP (including compaction) and WebSockets wait for discovery and preserve API paths.
HTTP redirects are rejected. `us` and `us_cr` set `X-OpenAI-Account-Routing-Override`;
`NO_CONSTRAINT` omits it.
API-key and explicitly external-auth providers bypass discovery. Custom ChatGPT-auth destinations
require discovery before being treated as independent. Changing a workspace-bound thread's
bootstrap origin requires a new thread.
## Windows sandbox implementation selection
+32 -1
View File
@@ -172,7 +172,38 @@ impl ConfigManager {
let mut config = Config::rebuild_with_session_layers(
session_layers,
cwd.to_path_buf(),
&refreshed_config,
&refreshed_config.config_layer_stack,
refreshed_config.codex_home.clone(),
refreshed_config
.zsh_path
.clone()
.map(AbsolutePathBuf::try_from)
.transpose()?,
)
.await?;
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
Ok(config)
}
/// Refreshes global settings and managed requirements using already fetched session layers.
pub(crate) async fn load_retained_session_config(
&self,
session_layers: &ConfigLayerStack,
cwd: &Path,
) -> std::io::Result<Config> {
let mut manager = self.clone();
manager.thread_config_loader = Arc::new(codex_config::NoopThreadConfigLoader);
let refreshed_layers = manager
.load_config_layers_for_cwd(AbsolutePathBuf::from_absolute_path(cwd)?)
.await?;
// Merge the retained provider definitions before resolving managed provider selection.
let mut config = Config::rebuild_with_session_layers(
session_layers,
cwd.to_path_buf(),
&refreshed_layers,
AbsolutePathBuf::from_absolute_path(&self.codex_home)?,
/*default_zsh_path*/ None,
)
.await?;
self.apply_runtime_feature_enablement(&mut config);
@@ -71,6 +71,13 @@ impl ThreadConfigLoader for UnavailableThreadConfig {
async fn provider_requirements_do_not_reload_thread_config() -> Result<()> {
let home = tempdir()?;
let mut manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
manager.thread_config_loader = Arc::new(codex_config::StaticThreadConfigLoader::new(vec![
ThreadConfigSource::Session(codex_config::SessionThreadConfig {
model_provider: Some("retained".into()),
model_providers: toml::from_str("[retained]\nname = 'Retained'")?,
..Default::default()
}),
]));
let current = manager.load_latest_config(/*fallback_cwd*/ None).await?;
manager.thread_config_loader = Arc::new(UnavailableThreadConfig);
assert!(
@@ -80,6 +87,13 @@ async fn provider_requirements_do_not_reload_thread_config() -> Result<()> {
.is_err()
);
manager.check_thread_model_provider(&current).await?;
manager.cloud_config_bundle = Arc::new(RwLock::new(
CloudConfigBundleFixture::loader_with_enterprise_requirement("model_provider = 'retained'"),
));
let retained = manager
.load_retained_session_config(&current.config_layer_stack, &current.cwd)
.await?;
assert_eq!(retained.model_provider, current.model_provider);
manager.cloud_config_bundle = Arc::new(RwLock::new(
CloudConfigBundleFixture::loader_with_enterprise_requirement("model_provider = 'other'"),
+1 -1
View File
@@ -144,7 +144,7 @@ pub(crate) struct MessageProcessor {
models_refresh_worker: ModelsRefreshWorker,
turn_cost_worker: Option<TurnCostWorker>,
skills_watcher: Arc<SkillsWatcher>,
account_processor: AccountRequestProcessor,
account_processor: Arc<AccountRequestProcessor>,
apps_processor: AppsRequestProcessor,
catalog_processor: CatalogRequestProcessor,
command_exec_processor: CommandExecRequestProcessor,
@@ -94,7 +94,7 @@ pub(crate) struct AccountRequestProcessor {
config_manager: ConfigManager,
active_login: Arc<Mutex<Option<ActiveLogin>>>,
workspace_routing: Arc<Mutex<Option<workspace_routing::CachedWorkspaceRouting>>>,
workspace_routing_fetch: Arc<Semaphore>,
workspace_routing_fetches: Arc<Mutex<workspace_routing::WorkspaceRoutingFetches>>,
workspace_routing_shutdown: CancellationToken,
}
@@ -105,8 +105,8 @@ impl AccountRequestProcessor {
outgoing: Arc<OutgoingMessageSender>,
config: Arc<Config>,
config_manager: ConfigManager,
) -> Self {
let processor = Self {
) -> Arc<Self> {
let processor = Arc::new(Self {
auth_manager,
thread_manager,
outgoing,
@@ -114,16 +114,16 @@ impl AccountRequestProcessor {
config_manager,
active_login: Arc::new(Mutex::new(None)),
workspace_routing: Arc::new(Mutex::new(None)),
workspace_routing_fetch: Arc::new(Semaphore::new(/*permits*/ 1)),
workspace_routing_fetches: Arc::new(Mutex::new(HashMap::new())),
workspace_routing_shutdown: CancellationToken::new(),
};
});
let resolver: Arc<dyn codex_login::WorkspaceRoutingResolver> = processor.clone();
processor
.auth_manager
.set_workspace_routing_resolver(Arc::downgrade(&resolver));
let startup = processor.clone();
tokio::spawn(async move {
let _ = startup
.get_account_response(GetAccountParams {
refresh_token: false,
})
.await;
let _ = startup.read_account(/*request*/ None).await;
});
processor
}
@@ -152,15 +152,6 @@ impl AccountRequestProcessor {
.map(|response| Some(response.into()))
}
pub(crate) async fn get_account(
&self,
params: GetAccountParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.get_account_response(params)
.await
.map(|response| Some(response.into()))
}
pub(crate) async fn get_auth_status(
&self,
params: GetAuthStatusParams,
@@ -896,14 +887,10 @@ impl AccountRequestProcessor {
let auth_changes = self.auth_manager.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
if payload.success
&& let Err(error) = self
.get_account_response(GetAccountParams {
refresh_token: false,
})
.await
&& let Err(error) = self.read_account(/*request*/ None).await
{
payload.success = false;
payload.error = Some(error.message);
payload.error = Some(error.to_string());
}
if payload.success && auth_changes.borrow().owner_generation == owner_generation {
Self::maybe_refresh_plugin_caches_for_current_config(
@@ -1,19 +1,132 @@
//! Discovers routing for the selected ChatGPT workspace without crossing auth owners.
//! Discovery is coordinated per routing key; a cache miss never proves independence.
//! Credential refreshes invalidate the cache, but do not cancel same-owner discovery.
//! Model sessions retain their original bootstrap scope across configuration changes.
use super::*;
use codex_app_server_protocol::AccountRoutingOverride;
use codex_app_server_protocol::WorkspaceRouting;
use codex_backend_client::AccountEntry;
use codex_login::WorkspaceRouting;
use codex_login::WorkspaceRoutingRequest;
use codex_login::WorkspaceRoutingResolver;
use codex_model_provider::ProviderAccount;
use codex_model_provider::ProviderAccountError;
use codex_model_provider::ProviderAccountState;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Weak;
use tokio::sync::Semaphore;
use url::Url;
pub(super) struct CachedWorkspaceRouting {
#[derive(Clone, PartialEq, Eq, Hash)]
pub(super) struct WorkspaceRoutingKey {
auth_generation: u64,
chatgpt_account_id: String,
effective_chatgpt_base_url: String,
required_chatgpt_base_url: Option<String>,
}
// Results live through same-key waiters, even if another key replaces the cache.
// Weak entries are pruned on the next read after those requests finish.
pub(super) type WorkspaceRoutingFetches = HashMap<WorkspaceRoutingKey, Weak<WorkspaceRoutingFetch>>;
pub(super) struct WorkspaceRoutingFetch {
discovery: Semaphore,
routing: Mutex<Option<WorkspaceRouting>>,
}
pub(super) struct CachedWorkspaceRouting {
key: WorkspaceRoutingKey,
routing: WorkspaceRouting,
}
pub(super) struct AccountRead {
account_state: ProviderAccountState,
pub(super) workspace_routing: Option<WorkspaceRouting>,
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum AccountReadError {
#[error(transparent)]
InvalidAccount(#[from] ProviderAccountError),
#[error(transparent)]
Routing(#[from] WorkspaceRoutingError),
}
/// Routing failure categories carry no account, URL, or backend data.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum WorkspaceRoutingError {
#[error("failed to load workspace requirements")]
RequirementsLoad,
#[error("workspace routing requires a ChatGPT account id")]
MissingAccountId,
#[error("workspace routing discovery cancelled")]
DiscoveryCancelled,
#[error("account changed during workspace routing discovery")]
AccountChanged,
#[error("workspace routing discovery unauthorized (401)")]
DiscoveryUnauthorized,
#[error("workspace routing discovery failed")]
DiscoveryFailed,
#[error("selected workspace missing from routing discovery")]
MissingWorkspace,
#[error("duplicate workspace in routing discovery")]
DuplicateWorkspace,
#[error("failed to reload workspace requirements")]
RequirementsReload,
#[error("configuration changed during workspace routing discovery; retry account/read")]
ConfigurationChanged,
#[error("invalid model provider URL")]
InvalidProviderUrl,
#[error("invalid ChatGPT backend URL")]
InvalidBootstrapUrl,
#[error("invalid session ChatGPT backend URL")]
InvalidSessionBootstrapUrl,
#[error("ChatGPT backend changed; start a new thread before sending more content")]
SessionBackendChanged,
#[error("workspace routing discovery cancelled during shutdown")]
Shutdown,
#[error("workspace routing discovery timed out")]
DiscoveryTimeout,
#[error("workspace routing discovery missing backend origin")]
MissingBackendOrigin,
#[error("workspace routing discovery has invalid account routing override")]
InvalidRoutingOverride,
#[error("workspace routing discovery must return an origin")]
BackendIsNotOrigin,
#[error("required ChatGPT backend conflicts with workspace routing")]
BackendConflict,
#[error("invalid workspace backend URL")]
InvalidBackendUrl,
#[error("workspace backend must use an HTTPS origin without credentials")]
InvalidBackendOrigin,
}
impl WorkspaceRoutingResolver for AccountRequestProcessor {
fn resolve(
&self,
request: WorkspaceRoutingRequest,
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>> {
Box::pin(async move {
self.read_account(Some(&request))
.await
.map(|account| account.workspace_routing)
.map_err(|error| match error {
AccountReadError::InvalidAccount(error) => io::Error::other(error),
AccountReadError::Routing(error) => io::Error::new(
if error == WorkspaceRoutingError::DiscoveryUnauthorized {
io::ErrorKind::PermissionDenied
} else {
io::ErrorKind::Other
},
error,
),
})
})
}
}
impl AccountRequestProcessor {
pub(crate) fn notify_workspace_routing_to_connection(&self, connection_id: ConnectionId) {
let processor = self.clone();
@@ -23,11 +136,7 @@ impl AccountRequestProcessor {
if auth_changes.borrow().owner_generation != owner_generation {
return;
}
if let Ok(response) = processor
.get_account_response(GetAccountParams {
refresh_token: false,
})
.await
if let Ok(response) = processor.read_account(/*request*/ None).await
&& response.workspace_routing.is_some()
&& auth_changes.borrow().owner_generation == owner_generation
{
@@ -45,25 +154,62 @@ impl AccountRequestProcessor {
});
}
pub(super) async fn get_account_response(
pub(crate) async fn get_account(
&self,
params: GetAccountParams,
) -> Result<GetAccountResponse, JSONRPCErrorError> {
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.refresh_token_if_requested(params.refresh_token).await;
let read = self
.read_account(/*request*/ None)
.await
.map_err(|error| match error {
AccountReadError::InvalidAccount(error) => invalid_request(error.to_string()),
AccountReadError::Routing(error) => internal_error(error.to_string()),
})?;
Ok(Some(
GetAccountResponse {
account: read.account_state.account.map(Account::from),
requires_openai_auth: read.account_state.requires_openai_auth,
workspace_routing: read.workspace_routing.map(|routing| {
codex_app_server_protocol::WorkspaceRouting {
chatgpt_account_id: routing.chatgpt_account_id,
backend_origin: routing.backend_origin,
account_routing_override: match routing.account_routing_override.as_str() {
"NO_CONSTRAINT" => AccountRoutingOverride::NoConstraint,
"us" => AccountRoutingOverride::Us,
"us_cr" => AccountRoutingOverride::UsCr,
_ => unreachable!("routing discovery validates the override"),
},
}
}),
}
.into(),
))
}
pub(super) async fn read_account(
&self,
request: Option<&WorkspaceRoutingRequest>,
) -> Result<AccountRead, AccountReadError> {
let mut auth_changes = self.auth_manager.auth_change_state_receiver();
let auth_state = *auth_changes.borrow_and_update();
let current_auth_changes = auth_changes.clone();
let read = Box::pin(async {
let _fetch_permit = self
.workspace_routing_fetch
.acquire()
.await
.map_err(|_| internal_error("workspace routing discovery cancelled"))?;
let config = match self
.config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
{
let load_config = async || {
match request.and_then(|request| request.session.as_deref()) {
Some(session) => {
self.config_manager
.load_retained_session_config(&session.config_layer_stack, &session.cwd)
.await
}
None => {
self.config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
}
}
};
let config = match load_config().await {
Ok(config) => config,
Err(_)
if !self
@@ -74,7 +220,7 @@ impl AccountRequestProcessor {
{
self.config.as_ref().clone()
}
Err(_) => return Err(internal_error("failed to load workspace requirements")),
Err(_) => return Err(WorkspaceRoutingError::RequirementsLoad.into()),
};
let auth = self.auth_manager.auth_cached();
let provider = create_model_provider(
@@ -83,65 +229,116 @@ impl AccountRequestProcessor {
);
let account_state = provider
.account_state()
.map_err(|err| invalid_request(err.to_string()))?;
let account = account_state.account.map(Account::from);
let workspace_routing = if let Some((auth, account_id)) = auth
.map_err(AccountReadError::InvalidAccount)?;
let mut workspace_routing = if let Some((auth, account_id)) = auth
.as_ref()
.filter(|auth| {
auth.is_chatgpt_auth() && matches!(account, Some(Account::Chatgpt { .. }))
auth.is_chatgpt_auth()
&& (request.is_some()
|| matches!(
account_state.account,
Some(ProviderAccount::Chatgpt { .. })
))
})
.and_then(|auth| auth.get_account_id().map(|account_id| (auth, account_id)))
{
if account_id.is_empty() {
return Err(internal_error(
"workspace routing requires a ChatGPT account id",
));
return Err(WorkspaceRoutingError::MissingAccountId.into());
}
let required_chatgpt_base_url = config
.config_layer_stack
.requirements_toml()
.chatgpt_base_url
.clone();
let cached = self
.workspace_routing
.lock()
let key = WorkspaceRoutingKey {
auth_generation: auth_state.generation,
chatgpt_account_id: account_id.clone(),
effective_chatgpt_base_url: config.chatgpt_base_url.clone(),
required_chatgpt_base_url: required_chatgpt_base_url.clone(),
};
let fetch = {
let mut fetches = self.workspace_routing_fetches.lock().await;
fetches.retain(|_, fetch| fetch.strong_count() > 0);
if let Some(fetch) = fetches.get(&key).and_then(Weak::upgrade) {
fetch
} else {
let fetch = Arc::new(WorkspaceRoutingFetch {
discovery: Semaphore::new(/*permits*/ 1),
routing: Mutex::new(/*t*/ None),
});
fetches.insert(key.clone(), Arc::downgrade(&fetch));
fetch
}
};
let _permit = fetch
.discovery
.acquire()
.await
.as_ref()
.filter(|cached| {
cached.auth_generation == auth_state.generation
&& cached.effective_chatgpt_base_url == config.chatgpt_base_url
&& cached.required_chatgpt_base_url == required_chatgpt_base_url
&& cached.routing.chatgpt_account_id == account_id
})
.map(|cached| cached.routing.clone());
if let Some(cached) = cached {
Some(cached)
} else {
*self.workspace_routing.lock().await = None;
let client = BackendClient::from_auth(
&config.chatgpt_base_url,
auth,
config.http_client_factory(),
);
let response = client
.get_accounts_check()
.map_err(|_| WorkspaceRoutingError::DiscoveryCancelled)?;
let fetched = fetch.routing.lock().await.clone();
let cached = match fetched {
Some(routing) => Some(routing),
None => self
.workspace_routing
.lock()
.await
.map_err(|_| internal_error("workspace routing discovery failed"))?;
.as_ref()
.filter(|cached| cached.key == key)
.map(|cached| cached.routing.clone()),
};
let routing = if let Some(cached) = cached {
cached
} else {
let mut recovery = self.auth_manager.unauthorized_recovery();
let mut discovery_auth = auth.clone();
let mut discovery_generation = auth_state.generation;
let response = loop {
let client = BackendClient::from_auth(
&config.chatgpt_base_url,
&discovery_auth,
config.http_client_factory(),
);
match client.get_accounts_check().await {
Ok(response) => break response,
Err(error) => {
let unauthorized = error.is_unauthorized();
if unauthorized
&& recovery.has_next()
&& recovery.next().await.is_ok()
{
let refreshed = *current_auth_changes.borrow();
if refreshed.owner_generation != auth_state.owner_generation {
return Err(WorkspaceRoutingError::AccountChanged.into());
}
discovery_generation = refreshed.generation;
discovery_auth = self
.auth_manager
.auth_cached()
.ok_or(WorkspaceRoutingError::AccountChanged)?;
continue;
}
return Err(if unauthorized {
WorkspaceRoutingError::DiscoveryUnauthorized
} else {
WorkspaceRoutingError::DiscoveryFailed
}
.into());
}
}
};
let mut accounts = response
.accounts
.into_iter()
.filter(|account| account.id == account_id);
let entry = accounts.next().ok_or_else(|| {
internal_error("selected workspace missing from routing discovery")
})?;
let entry = accounts
.next()
.ok_or(WorkspaceRoutingError::MissingWorkspace)?;
if accounts.next().is_some() {
return Err(internal_error("duplicate workspace in routing discovery"));
return Err(WorkspaceRoutingError::DuplicateWorkspace.into());
}
let latest_config = self
.config_manager
.load_latest_config(/*fallback_cwd*/ None)
let latest_config = load_config()
.await
.map_err(|_| internal_error("failed to reload workspace requirements"))?;
.map_err(|_| WorkspaceRoutingError::RequirementsReload)?;
if latest_config.chatgpt_base_url != config.chatgpt_base_url
|| latest_config.model_provider != config.model_provider
|| latest_config
@@ -150,9 +347,7 @@ impl AccountRequestProcessor {
.chatgpt_base_url
!= required_chatgpt_base_url
{
return Err(internal_error(
"configuration changed during workspace routing discovery; retry account/read",
));
return Err(WorkspaceRoutingError::ConfigurationChanged.into());
}
let routing = resolve_routing(
entry,
@@ -162,44 +357,68 @@ impl AccountRequestProcessor {
let mut cached = self.workspace_routing.lock().await;
if current_auth_changes.borrow().owner_generation != auth_state.owner_generation
{
return Err(internal_error(
"account changed during workspace routing discovery",
));
return Err(WorkspaceRoutingError::AccountChanged.into());
}
*cached = Some(CachedWorkspaceRouting {
auth_generation: auth_state.generation,
effective_chatgpt_base_url: config.chatgpt_base_url.clone(),
required_chatgpt_base_url,
routing: routing.clone(),
});
Some(routing)
}
// Same-owner refresh can complete a newer discovery first.
if current_auth_changes.borrow().generation == discovery_generation {
*cached = Some(CachedWorkspaceRouting {
key: WorkspaceRoutingKey {
auth_generation: discovery_generation,
..key
},
routing: routing.clone(),
});
}
routing
};
*fetch.routing.lock().await = Some(routing.clone());
Some(routing)
} else {
*self.workspace_routing.lock().await = None;
None
};
Ok(GetAccountResponse {
account,
requires_openai_auth: account_state.requires_openai_auth,
if let Some(request) = request.filter(|_| workspace_routing.is_some()) {
let origin = Url::parse(&request.provider_base_url)
.map_err(|_| WorkspaceRoutingError::InvalidProviderUrl)?
.origin();
let bootstrap_origin = Url::parse(&config.chatgpt_base_url)
.map_err(|_| WorkspaceRoutingError::InvalidBootstrapUrl)?
.origin();
let session_bootstrap_origin = Url::parse(&request.chatgpt_base_url)
.map_err(|_| WorkspaceRoutingError::InvalidSessionBootstrapUrl)?
.origin();
let selected_backend = workspace_routing
.as_ref()
.is_some_and(|routing| routing.backend_origin == origin.ascii_serialization());
let workspace_bound = request.previously_routed
|| request.provider_base_url == codex_model_provider::CHATGPT_CODEX_BASE_URL
|| origin == session_bootstrap_origin
|| (session_bootstrap_origin == bootstrap_origin && selected_backend);
if !workspace_bound {
workspace_routing = None;
} else if session_bootstrap_origin != bootstrap_origin {
return Err(WorkspaceRoutingError::SessionBackendChanged.into());
}
}
Ok(AccountRead {
account_state,
workspace_routing,
})
});
let result = tokio::select! {
biased;
_ = self.workspace_routing_shutdown.cancelled() => {
return Err(internal_error("workspace routing discovery cancelled during shutdown"));
return Err(WorkspaceRoutingError::Shutdown.into());
}
_ = auth_changes.wait_for(|state| state.owner_generation != auth_state.owner_generation) => {
return Err(internal_error("account changed during workspace routing discovery"));
return Err(WorkspaceRoutingError::AccountChanged.into());
}
result = tokio::time::timeout(Duration::from_secs(/*secs*/ 10), read) => {
result.map_err(|_| internal_error("workspace routing discovery timed out"))?
result.map_err(|_| WorkspaceRoutingError::DiscoveryTimeout)?
}
};
if auth_changes.borrow().owner_generation != auth_state.owner_generation {
return Err(internal_error(
"account changed during workspace routing discovery",
));
return Err(WorkspaceRoutingError::AccountChanged.into());
}
result
}
@@ -209,18 +428,14 @@ fn resolve_routing(
entry: AccountEntry,
required_chatgpt_base_url: Option<&str>,
effective_base_url: &str,
) -> Result<WorkspaceRouting, JSONRPCErrorError> {
) -> Result<WorkspaceRouting, AccountReadError> {
let backend = entry
.workspace_backend_origin
.ok_or_else(|| internal_error("workspace routing discovery missing backend origin"))?;
.ok_or(WorkspaceRoutingError::MissingBackendOrigin)?;
let account_routing_override = match entry.account_routing_override.as_deref() {
Some("NO_CONSTRAINT") => AccountRoutingOverride::NoConstraint,
Some("us") => AccountRoutingOverride::Us,
Some("us_cr") => AccountRoutingOverride::UsCr,
Some(value @ ("NO_CONSTRAINT" | "us" | "us_cr")) => value.to_owned(),
_ => {
return Err(internal_error(
"workspace routing discovery has invalid account routing override",
));
return Err(WorkspaceRoutingError::InvalidRoutingOverride.into());
}
};
let required = required_chatgpt_base_url
@@ -231,18 +446,14 @@ fn resolve_routing(
} else {
let url = parse_backend_url(&backend)?;
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
return Err(internal_error(
"workspace routing discovery must return an origin",
));
return Err(WorkspaceRoutingError::BackendIsNotOrigin.into());
}
Some(url)
};
let origin = match (required, discovered) {
(Some(required), Some(discovered)) => {
if required.origin() != discovered.origin() {
return Err(internal_error(
"required ChatGPT backend conflicts with workspace routing",
));
return Err(WorkspaceRoutingError::BackendConflict.into());
}
required.origin()
}
@@ -256,17 +467,15 @@ fn resolve_routing(
})
}
fn parse_backend_url(value: &str) -> Result<Url, JSONRPCErrorError> {
let url = Url::parse(value).map_err(|_| internal_error("invalid workspace backend URL"))?;
fn parse_backend_url(value: &str) -> Result<Url, AccountReadError> {
let url = Url::parse(value).map_err(|_| WorkspaceRoutingError::InvalidBackendUrl)?;
if url.scheme() != "https"
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| value.trim() != value
{
return Err(internal_error(
"workspace backend must use an HTTPS origin without credentials",
));
return Err(WorkspaceRoutingError::InvalidBackendOrigin.into());
}
Ok(url)
}
@@ -2,6 +2,7 @@
use super::*;
use pretty_assertions::assert_eq;
use serde_json::Value;
use test_case::test_case;
#[test_case(Some("https://gov.chatgpt.com/backend-api/"), "NO_CONSTRAINT", "https://gov.chatgpt.com"; "configured_only")]
@@ -20,7 +21,7 @@ fn resolves_origins(required: Option<&str>, discovered: &str, expected: &str) {
WorkspaceRouting {
chatgpt_account_id: "workspace".into(),
backend_origin: expected.into(),
account_routing_override: AccountRoutingOverride::NoConstraint,
account_routing_override: "NO_CONSTRAINT".into(),
}
);
}
@@ -37,28 +38,28 @@ fn rejects_conflicting_origins(required: &str, discovered: &str) {
assert!(resolve_routing(entry, Some(required), "https://chatgpt.com").is_err());
}
#[test_case(serde_json::json!(null), serde_json::json!("us_cr"); "null_origin")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(null); "null_routing")]
#[test_case(serde_json::json!(""), serde_json::json!("us_cr"); "empty_origin")]
#[test_case(serde_json::json!("https://example.com/backend-api/"), serde_json::json!("us_cr"); "origin_with_path")]
#[test_case(serde_json::json!("https://example.com?query"), serde_json::json!("us_cr"); "origin_with_query")]
#[test_case(serde_json::json!("https://example.com#fragment"), serde_json::json!("us_cr"); "origin_with_fragment")]
#[test_case(serde_json::json!("https://user:pass@example.com"), serde_json::json!("us_cr"); "credentials")]
#[test_case(serde_json::json!("http://example.com"), serde_json::json!("us_cr"); "insecure_origin")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!("unknown"); "unknown_routing")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(""); "empty_routing")]
fn rejects_invalid_discovery(backend: serde_json::Value, routing: serde_json::Value) {
#[test_case(serde_json::json!(null), serde_json::json!("us_cr"), WorkspaceRoutingError::MissingBackendOrigin; "null_origin")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(null), WorkspaceRoutingError::InvalidRoutingOverride; "null_routing")]
#[test_case(serde_json::json!(""), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendUrl; "empty_origin")]
#[test_case(serde_json::json!("https://example.com/backend-api/"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_path")]
#[test_case(serde_json::json!("https://example.com?query"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_query")]
#[test_case(serde_json::json!("https://example.com#fragment"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_fragment")]
#[test_case(serde_json::json!("https://user:pass@example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "credentials")]
#[test_case(serde_json::json!("http://example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "insecure_origin")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!("unknown"), WorkspaceRoutingError::InvalidRoutingOverride; "unknown_routing")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(""), WorkspaceRoutingError::InvalidRoutingOverride; "empty_routing")]
fn rejects_invalid_discovery(backend: Value, routing: Value, expected: WorkspaceRoutingError) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": backend, "account_routing_override": routing,
}))
.unwrap();
assert!(
assert_eq!(
resolve_routing(
entry,
/*required_chatgpt_base_url*/ None,
"https://chatgpt.com"
)
.is_err()
),
Err(AccountReadError::Routing(expected))
);
}
@@ -77,7 +78,7 @@ fn unrestricted_discovery_uses_effective_custom_backend() {
WorkspaceRouting {
chatgpt_account_id: "workspace".into(),
backend_origin: "https://custom.example:8443".into(),
account_routing_override: AccountRoutingOverride::Us,
account_routing_override: "us".into(),
}
);
}
@@ -17,7 +17,9 @@ use serde_json::json;
pub async fn mount_workspace_routing(server: &wiremock::MockServer) {
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/backend-api/wham/accounts/check"))
.and(wiremock::matchers::path_regex(
"^/(backend-api/wham|api/codex)/accounts/check$",
))
.respond_with(|request: &wiremock::Request| {
let account_id = request
.headers
+46 -14
View File
@@ -615,17 +615,23 @@ async fn mount_disabled_attribution_settings(mock_server: &MockServer) {
.await;
}
#[test_case("/v1"; "responses")]
#[test_case("/backend-api/codex"; "discovery")]
#[tokio::test]
// 401 response triggers account/chatgptAuthTokens/refresh and retries with new tokens.
async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
async fn external_auth_refreshes_on_unauthorized(model_path: &str) -> Result<()> {
let codex_home = TempDir::new()?;
let mock_server = MockServer::start().await;
let backend = MockServer::start().await;
create_config_toml(
codex_home.path(),
CreateConfigTomlParams {
requires_openai_auth: Some(true),
base_url: Some(format!("{}/v1", mock_server.uri())),
chatgpt_base_url: Some(format!("{}/backend-api", mock_server.uri())),
model_provider_id: Some("routing".into()),
extra_provider_config: Some(format!(
"[model_providers.routing]\nname = \"OpenAI\"\nrequires_openai_auth = true\nbase_url = \"{}{model_path}\"\nrequest_max_retries = 0\nstream_max_retries = 0\n",
mock_server.uri(),
)),
chatgpt_base_url: Some(format!("{}/backend-api", backend.uri())),
..Default::default()
},
)?;
@@ -641,22 +647,33 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
}));
let responses_mock = responses::mount_response_sequence(
&mock_server,
vec![unauthorized, responses::sse_response(success_sse)],
if model_path == "/v1" {
vec![unauthorized, responses::sse_response(success_sse)]
} else {
vec![responses::sse_response(success_sse)]
},
)
.await;
mount_disabled_attribution_settings(&mock_server).await;
mount_disabled_attribution_settings(&backend).await;
let initial_access_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.email("initial@example.com")
.chatgpt_user_id("user")
.plan_type("pro")
.chatgpt_account_id(WORKSPACE_ID_INITIAL),
)?;
let refreshed_workspace = if model_path == "/v1" {
WORKSPACE_ID_REFRESHED
} else {
WORKSPACE_ID_INITIAL
};
let refreshed_access_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.email("refreshed@example.com")
.chatgpt_user_id("user")
.plan_type("pro")
.chatgpt_account_id(WORKSPACE_ID_REFRESHED),
.chatgpt_account_id(refreshed_workspace),
)?;
let mut mcp = TestAppServer::builder()
@@ -691,6 +708,25 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
let thread: codex_app_server_protocol::ThreadStartResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(thread_req)).await??;
if model_path != "/v1" {
// Force discovery after login cached the same workspace's route.
let config_path = codex_home.path().join("config.toml");
std::fs::write(
&config_path,
std::fs::read_to_string(&config_path)?.replace("/backend-api\"", "/backend-api/\""),
)?;
Mock::given(path("/backend-api/wham/accounts/check"))
.and(header(
"authorization",
format!("Bearer {initial_access_token}"),
))
.respond_with(ResponseTemplate::new(/*s*/ 401))
.with_priority(/*p*/ 1)
.expect(/*r*/ 1)
.mount(&backend)
.await;
}
let turn_req = mcp
.send_turn_start_request(codex_app_server_protocol::TurnStartParams {
thread_id: thread.thread.id,
@@ -705,7 +741,7 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
respond_to_refresh_request(
&mut mcp,
&refreshed_access_token,
WORKSPACE_ID_REFRESHED,
refreshed_workspace,
Some("pro"),
)
.await?;
@@ -718,13 +754,9 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
.await??;
let requests = responses_mock.requests();
assert_eq!(requests.len(), 2);
assert_eq!(requests.len(), if model_path == "/v1" { 2 } else { 1 });
assert_eq!(
requests[0].header("authorization"),
Some(format!("Bearer {initial_access_token}"))
);
assert_eq!(
requests[1].header("authorization"),
requests[requests.len() - 1].header("authorization"),
Some(format!("Bearer {refreshed_access_token}"))
);
@@ -527,6 +527,7 @@ pub(crate) async fn mount_analytics_capture(server: &MockServer, codex_home: &Pa
AuthCredentialsStoreMode::File,
)?;
app_test_support::mount_workspace_routing(server).await;
Ok(())
}
@@ -41,6 +41,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
hint_text: &str,
) -> Result<()> {
let server = responses::start_mock_server().await;
let backend = responses::start_mock_server().await;
let response_mock = responses::mount_sse_once(
&server,
responses::sse(vec![
@@ -121,7 +122,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
serde_json::to_vec(&json!({"models": [model]}))?,
)?;
MockResponsesConfig::new(&server.uri())
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.with_root_config(&format!("chatgpt_base_url = \"{}\"", backend.uri()))
.with_root_config(&format!(
"model_catalog_json = {}",
serde_json::to_string(&catalog_path)?
@@ -135,7 +136,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
server.uri(),
))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
mount_analytics_capture(&backend, codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -225,7 +226,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
}));
if use_history_notes_extension {
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
let event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_thread_hint_status"
&& event["event_params"]["thread_id"] == thread.id
})
@@ -297,6 +298,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
),
];
let server = responses::start_mock_server().await;
let backend = responses::start_mock_server().await;
for (namespace, tool, arguments) in &calls[..9] {
Mock::given(method("POST"))
.and(path(format!(
@@ -347,7 +349,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
.with_provider_name("OpenAI")
.with_provider_base_url(&format!("{}/backend-api/codex", server.uri()))
.with_provider_config("supports_websockets = false\nrequires_openai_auth = true")
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.with_root_config(&format!("chatgpt_base_url = \"{}\"", backend.uri()))
.with_root_config(&format!(
"model_catalog_json = {}",
serde_json::to_string(&catalog_path)?
@@ -356,7 +358,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
"[features.token_budget]\nenabled = true\nuse_history_notes_extension = true",
)
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
mount_analytics_capture(&backend, codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -393,7 +395,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
}
for (index, (namespace, tool, _)) in calls.iter().enumerate() {
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
let event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_control_tool_call_event"
&& event["event_params"]["item_id"] == format!("call-{index}")
})
@@ -419,7 +421,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
);
assert!(!event.to_string().contains("PRIVATE_"));
}
let turn_event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
let turn_event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["turn_id"] == completed.turn.id
})
+8 -2
View File
@@ -5478,10 +5478,13 @@ async fn rebuild_with_session_layers_refreshes_requirements() -> std::io::Result
thread_layer_stack,
)
.await?;
let zsh_path = refreshed_config.zsh_path.clone();
let config = Config::rebuild_with_session_layers(
&thread_config.config_layer_stack,
thread_config.cwd.to_path_buf(),
&refreshed_config,
&refreshed_config.config_layer_stack,
refreshed_config.codex_home.clone(),
zsh_path.map(AbsolutePathBuf::try_from).transpose()?,
)
.await?;
@@ -5603,10 +5606,13 @@ async fn rebuild_with_session_layers_refreshes_plugin_derived_mcp_config() -> an
thread_layer_stack,
)
.await?;
let zsh_path = refreshed_config.zsh_path.clone();
let config = Config::rebuild_with_session_layers(
&thread_config.config_layer_stack,
thread_config.cwd.to_path_buf(),
&refreshed_config,
&refreshed_config.config_layer_stack,
refreshed_config.codex_home.clone(),
zsh_path.map(AbsolutePathBuf::try_from).transpose()?,
)
.await?;
let plugins_manager =
+6 -12
View File
@@ -1844,22 +1844,16 @@ impl Config {
pub async fn rebuild_with_session_layers(
session_layers: &ConfigLayerStack,
cwd: PathBuf,
refreshed_config: &Config,
refreshed_layers: &ConfigLayerStack,
codex_home: AbsolutePathBuf,
default_zsh_path: Option<AbsolutePathBuf>,
) -> std::io::Result<Self> {
let config_layer_stack = Self::layer_stack_preserving_session(
session_layers,
&refreshed_config.config_layer_stack,
)?;
let config_layer_stack =
Self::layer_stack_preserving_session(session_layers, refreshed_layers)?;
let cfg: ConfigToml = config_layer_stack
.effective_config()
.try_into()
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
let default_zsh_path = refreshed_config
.zsh_path
.clone()
.map(AbsolutePathBuf::try_from)
.transpose()?;
Self::load_config_with_layer_stack(
LOCAL_FS.as_ref(),
cfg,
@@ -1868,7 +1862,7 @@ impl Config {
default_zsh_path,
..Default::default()
},
refreshed_config.codex_home.clone(),
codex_home,
config_layer_stack,
)
.await
@@ -181,7 +181,13 @@ X-Managed = "required"
let rebuilt = Config::rebuild_with_session_layers(
&overridden.config_layer_stack,
overridden.cwd.to_path_buf(),
&overridden,
&overridden.config_layer_stack,
overridden.codex_home.clone(),
overridden
.zsh_path
.clone()
.map(codex_utils_absolute_path::AbsolutePathBuf::try_from)
.transpose()?,
)
.await?;
assert_eq!(rebuilt.model_provider, test.config.model_provider);
@@ -6,7 +6,7 @@ Scenario: Astra asks who a launch update is for, keeps working, and receives the
## Window 1
-- request 1 (request) --
00:additional_tools/developer (3; hash=d4f3e164a92d9bf1):
00:additional_tools/developer (3; hash=9e8e744a3a55a2dd):
- namespace/functions; hash=e7db0a45c4ec3157
- custom/exec
- function/wait
@@ -14,7 +14,7 @@ Scenario: Astra asks who a launch update is for, keeps working, and receives the
- function/request_user_input_async
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
- function/sleep
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=43f195d9cc99ee15
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=91f6de0e2773854f
- function/followup_task
- function/interrupt_agent
- function/list_agents
@@ -16,7 +16,7 @@ Settings:
text: {"verbosity":"low"}
tool_choice: "auto"
-- request 1 (request) --
00:additional_tools/developer (3; hash=24819537059703a0):
00:additional_tools/developer (3; hash=d78b689d87e8c03e):
- namespace/functions; hash=97852c93915dad58
- custom/exec
- function/wait
@@ -24,7 +24,7 @@ Settings:
- function/request_user_input_async
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
- function/sleep
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=43f195d9cc99ee15
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=91f6de0e2773854f
- function/followup_task
- function/interrupt_agent
- function/list_agents
@@ -16,7 +16,7 @@ Settings:
text: {"verbosity":"low"}
tool_choice: "auto"
-- request 1 (turn) --
00:additional_tools/developer (3; hash=d4f3e164a92d9bf1):
00:additional_tools/developer (3; hash=9e8e744a3a55a2dd):
- namespace/functions; hash=e7db0a45c4ec3157
- custom/exec
- function/wait
@@ -24,7 +24,7 @@ Settings:
- function/request_user_input_async
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
- function/sleep
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=43f195d9cc99ee15
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=91f6de0e2773854f
- function/followup_task
- function/interrupt_agent
- function/list_agents
@@ -190,7 +190,7 @@ Settings:
## Window 2 (after request 3: input diverged at item 02)
Settings: same as window 1
-- request 4 (turn) --
00:additional_tools/developer (3; hash=d4f3e164a92d9bf1):
00:additional_tools/developer (3; hash=9e8e744a3a55a2dd):
- namespace/functions; hash=e7db0a45c4ec3157
- custom/exec
- function/wait
@@ -198,7 +198,7 @@ Settings: same as window 1
- function/request_user_input_async
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
- function/sleep
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=43f195d9cc99ee15
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=91f6de0e2773854f
- function/followup_task
- function/interrupt_agent
- function/list_agents
@@ -16,7 +16,7 @@ Settings:
text: {"verbosity":"low"}
tool_choice: "auto"
-- request 1 (turn) --
00:additional_tools/developer (3; hash=d4f3e164a92d9bf1):
00:additional_tools/developer (3; hash=9e8e744a3a55a2dd):
- namespace/functions; hash=e7db0a45c4ec3157
- custom/exec
- function/wait
@@ -24,7 +24,7 @@ Settings:
- function/request_user_input_async
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
- function/sleep
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=43f195d9cc99ee15
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=91f6de0e2773854f
- function/followup_task
- function/interrupt_agent
- function/list_agents
@@ -113,7 +113,7 @@ Settings:
## Window 2 (after request 2: input diverged at item 00)
Settings: same as window 1
-- request 3 (turn) --
00:additional_tools/developer (3; hash=61ace4f77de8d87f):
00:additional_tools/developer (3; hash=d9bfc9d2033f8c93):
- namespace/functions; hash=8c17932a39355f2d
- custom/exec
- function/wait
@@ -121,7 +121,7 @@ Settings: same as window 1
- function/request_user_input_async
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
- function/sleep
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=43f195d9cc99ee15
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=91f6de0e2773854f
- function/followup_task
- function/interrupt_agent
- function/list_agents
@@ -16,7 +16,7 @@ Settings:
text: {"verbosity":"low"}
tool_choice: "auto"
-- request 1 (turn) --
00:additional_tools/developer (3; hash=61ace4f77de8d87f):
00:additional_tools/developer (3; hash=d9bfc9d2033f8c93):
- namespace/functions; hash=8c17932a39355f2d
- custom/exec
- function/wait
@@ -24,7 +24,7 @@ Settings:
- function/request_user_input_async
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
- function/sleep
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=43f195d9cc99ee15
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=91f6de0e2773854f
- function/followup_task
- function/interrupt_agent
- function/list_agents
@@ -13,7 +13,7 @@ use crate::AuthManager;
use crate::CodexAuth;
/// A successful discovery for one selected workspace.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceRouting {
pub chatgpt_account_id: String,
pub backend_origin: String,
@@ -44,7 +44,8 @@ pub struct WorkspaceRoutingRequest {
/// Resolves routing through the account owner's cache and requirements loader.
/// Returns no routing for independent destinations or no selected workspace.
/// Destination scope is decided here, before making a discovery request.
/// Custom ChatGPT-auth destinations require successful discovery before independence
/// can be established; a cache miss is not evidence of an independent destination.
/// Implementations must reject failed discovery and changes to the selected account.
pub trait WorkspaceRoutingResolver: Send + Sync {
fn resolve(
@@ -68,13 +69,15 @@ impl AuthManager {
let Some(resolver) = self.workspace_routing_resolver.get() else {
return Ok(None);
};
let auth_changes = self.auth_change_receiver();
let revision = *auth_changes.borrow();
let auth_changes = self.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
let resolver = resolver
.upgrade()
.ok_or_else(|| io::Error::other("workspace routing owner is unavailable"))?;
let routing = resolver.resolve(request).await?;
if *auth_changes.borrow() != revision
// Discovery may recover expired credentials for the same owner. Model
// client setup rebuilds routing and credentials after that revision change.
if auth_changes.borrow().owner_generation != owner_generation
|| routing.as_ref().is_some_and(|routing| {
auth.get_account_id().as_deref() != Some(routing.chatgpt_account_id.as_str())
})
@@ -16,6 +16,12 @@ async fn cyber_refusal_reads_eligibility_without_changing_the_model() -> Result<
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
let backend = wiremock::MockServer::start().await;
app.config.chatgpt_base_url = backend.uri();
// Embedded account discovery reloads the bootstrap URL from disk.
std::fs::write(
app.config.codex_home.join("config.toml"),
format!("chatgpt_base_url = {:?}\n", backend.uri()),
)?;
app_test_support::mount_workspace_routing(&backend).await;
app.config.cli_auth_credentials_store_mode = AuthCredentialsStoreMode::File;
write_chatgpt_auth(
&app.config.codex_home,
@@ -43,6 +49,7 @@ async fn cyber_refusal_reads_eligibility_without_changing_the_model() -> Result<
(200, false, "gpt-5.6-sol", true, Notice::Limited),
] {
backend.reset().await;
app_test_support::mount_workspace_routing(&backend).await;
let codex_home = app.config.codex_home.clone();
let response = wiremock::ResponseTemplate::new(status)
.set_delay(if model == "gpt-5.6-sol" && enrolled { Duration::from_secs(1) } else { Duration::ZERO })