mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
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:
1 parent
d7f8e48d7d
commit
0a5b999169
21 files changed
+491
-186
No files matched your search
@@ -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.
|
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
|
## Windows sandbox implementation selection
|
||||||
|
|
||||||
|
|||||||
@@ -172,7 +172,38 @@ impl ConfigManager {
|
|||||||
let mut config = Config::rebuild_with_session_layers(
|
let mut config = Config::rebuild_with_session_layers(
|
||||||
session_layers,
|
session_layers,
|
||||||
cwd.to_path_buf(),
|
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?;
|
.await?;
|
||||||
self.apply_runtime_feature_enablement(&mut config);
|
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<()> {
|
async fn provider_requirements_do_not_reload_thread_config() -> Result<()> {
|
||||||
let home = tempdir()?;
|
let home = tempdir()?;
|
||||||
let mut manager = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf());
|
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?;
|
let current = manager.load_latest_config(/*fallback_cwd*/ None).await?;
|
||||||
manager.thread_config_loader = Arc::new(UnavailableThreadConfig);
|
manager.thread_config_loader = Arc::new(UnavailableThreadConfig);
|
||||||
assert!(
|
assert!(
|
||||||
@@ -80,6 +87,13 @@ async fn provider_requirements_do_not_reload_thread_config() -> Result<()> {
|
|||||||
.is_err()
|
.is_err()
|
||||||
);
|
);
|
||||||
manager.check_thread_model_provider(¤t).await?;
|
manager.check_thread_model_provider(¤t).await?;
|
||||||
|
manager.cloud_config_bundle = Arc::new(RwLock::new(
|
||||||
|
CloudConfigBundleFixture::loader_with_enterprise_requirement("model_provider = 'retained'"),
|
||||||
|
));
|
||||||
|
let retained = manager
|
||||||
|
.load_retained_session_config(¤t.config_layer_stack, ¤t.cwd)
|
||||||
|
.await?;
|
||||||
|
assert_eq!(retained.model_provider, current.model_provider);
|
||||||
|
|
||||||
manager.cloud_config_bundle = Arc::new(RwLock::new(
|
manager.cloud_config_bundle = Arc::new(RwLock::new(
|
||||||
CloudConfigBundleFixture::loader_with_enterprise_requirement("model_provider = 'other'"),
|
CloudConfigBundleFixture::loader_with_enterprise_requirement("model_provider = 'other'"),
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ pub(crate) struct MessageProcessor {
|
|||||||
models_refresh_worker: ModelsRefreshWorker,
|
models_refresh_worker: ModelsRefreshWorker,
|
||||||
turn_cost_worker: Option<TurnCostWorker>,
|
turn_cost_worker: Option<TurnCostWorker>,
|
||||||
skills_watcher: Arc<SkillsWatcher>,
|
skills_watcher: Arc<SkillsWatcher>,
|
||||||
account_processor: AccountRequestProcessor,
|
account_processor: Arc<AccountRequestProcessor>,
|
||||||
apps_processor: AppsRequestProcessor,
|
apps_processor: AppsRequestProcessor,
|
||||||
catalog_processor: CatalogRequestProcessor,
|
catalog_processor: CatalogRequestProcessor,
|
||||||
command_exec_processor: CommandExecRequestProcessor,
|
command_exec_processor: CommandExecRequestProcessor,
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ pub(crate) struct AccountRequestProcessor {
|
|||||||
config_manager: ConfigManager,
|
config_manager: ConfigManager,
|
||||||
active_login: Arc<Mutex<Option<ActiveLogin>>>,
|
active_login: Arc<Mutex<Option<ActiveLogin>>>,
|
||||||
workspace_routing: Arc<Mutex<Option<workspace_routing::CachedWorkspaceRouting>>>,
|
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,
|
workspace_routing_shutdown: CancellationToken,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,8 +105,8 @@ impl AccountRequestProcessor {
|
|||||||
outgoing: Arc<OutgoingMessageSender>,
|
outgoing: Arc<OutgoingMessageSender>,
|
||||||
config: Arc<Config>,
|
config: Arc<Config>,
|
||||||
config_manager: ConfigManager,
|
config_manager: ConfigManager,
|
||||||
) -> Self {
|
) -> Arc<Self> {
|
||||||
let processor = Self {
|
let processor = Arc::new(Self {
|
||||||
auth_manager,
|
auth_manager,
|
||||||
thread_manager,
|
thread_manager,
|
||||||
outgoing,
|
outgoing,
|
||||||
@@ -114,16 +114,16 @@ impl AccountRequestProcessor {
|
|||||||
config_manager,
|
config_manager,
|
||||||
active_login: Arc::new(Mutex::new(None)),
|
active_login: Arc::new(Mutex::new(None)),
|
||||||
workspace_routing: 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(),
|
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();
|
let startup = processor.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let _ = startup
|
let _ = startup.read_account(/*request*/ None).await;
|
||||||
.get_account_response(GetAccountParams {
|
|
||||||
refresh_token: false,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
});
|
});
|
||||||
processor
|
processor
|
||||||
}
|
}
|
||||||
@@ -152,15 +152,6 @@ impl AccountRequestProcessor {
|
|||||||
.map(|response| Some(response.into()))
|
.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(
|
pub(crate) async fn get_auth_status(
|
||||||
&self,
|
&self,
|
||||||
params: GetAuthStatusParams,
|
params: GetAuthStatusParams,
|
||||||
@@ -896,14 +887,10 @@ impl AccountRequestProcessor {
|
|||||||
let auth_changes = self.auth_manager.auth_change_state_receiver();
|
let auth_changes = self.auth_manager.auth_change_state_receiver();
|
||||||
let owner_generation = auth_changes.borrow().owner_generation;
|
let owner_generation = auth_changes.borrow().owner_generation;
|
||||||
if payload.success
|
if payload.success
|
||||||
&& let Err(error) = self
|
&& let Err(error) = self.read_account(/*request*/ None).await
|
||||||
.get_account_response(GetAccountParams {
|
|
||||||
refresh_token: false,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
{
|
{
|
||||||
payload.success = false;
|
payload.success = false;
|
||||||
payload.error = Some(error.message);
|
payload.error = Some(error.to_string());
|
||||||
}
|
}
|
||||||
if payload.success && auth_changes.borrow().owner_generation == owner_generation {
|
if payload.success && auth_changes.borrow().owner_generation == owner_generation {
|
||||||
Self::maybe_refresh_plugin_caches_for_current_config(
|
Self::maybe_refresh_plugin_caches_for_current_config(
|
||||||
|
|||||||
+295
-86
@@ -1,19 +1,132 @@
|
|||||||
//! Discovers routing for the selected ChatGPT workspace without crossing auth owners.
|
//! 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.
|
//! 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 super::*;
|
||||||
use codex_app_server_protocol::AccountRoutingOverride;
|
use codex_app_server_protocol::AccountRoutingOverride;
|
||||||
use codex_app_server_protocol::WorkspaceRouting;
|
|
||||||
use codex_backend_client::AccountEntry;
|
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;
|
use url::Url;
|
||||||
|
|
||||||
pub(super) struct CachedWorkspaceRouting {
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub(super) struct WorkspaceRoutingKey {
|
||||||
auth_generation: u64,
|
auth_generation: u64,
|
||||||
|
chatgpt_account_id: String,
|
||||||
effective_chatgpt_base_url: String,
|
effective_chatgpt_base_url: String,
|
||||||
required_chatgpt_base_url: Option<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,
|
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 {
|
impl AccountRequestProcessor {
|
||||||
pub(crate) fn notify_workspace_routing_to_connection(&self, connection_id: ConnectionId) {
|
pub(crate) fn notify_workspace_routing_to_connection(&self, connection_id: ConnectionId) {
|
||||||
let processor = self.clone();
|
let processor = self.clone();
|
||||||
@@ -23,11 +136,7 @@ impl AccountRequestProcessor {
|
|||||||
if auth_changes.borrow().owner_generation != owner_generation {
|
if auth_changes.borrow().owner_generation != owner_generation {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if let Ok(response) = processor
|
if let Ok(response) = processor.read_account(/*request*/ None).await
|
||||||
.get_account_response(GetAccountParams {
|
|
||||||
refresh_token: false,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
&& response.workspace_routing.is_some()
|
&& response.workspace_routing.is_some()
|
||||||
&& auth_changes.borrow().owner_generation == owner_generation
|
&& 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,
|
&self,
|
||||||
params: GetAccountParams,
|
params: GetAccountParams,
|
||||||
) -> Result<GetAccountResponse, JSONRPCErrorError> {
|
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||||
self.refresh_token_if_requested(params.refresh_token).await;
|
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 mut auth_changes = self.auth_manager.auth_change_state_receiver();
|
||||||
let auth_state = *auth_changes.borrow_and_update();
|
let auth_state = *auth_changes.borrow_and_update();
|
||||||
let current_auth_changes = auth_changes.clone();
|
let current_auth_changes = auth_changes.clone();
|
||||||
let read = Box::pin(async {
|
let read = Box::pin(async {
|
||||||
let _fetch_permit = self
|
let load_config = async || {
|
||||||
.workspace_routing_fetch
|
match request.and_then(|request| request.session.as_deref()) {
|
||||||
.acquire()
|
Some(session) => {
|
||||||
|
self.config_manager
|
||||||
|
.load_retained_session_config(&session.config_layer_stack, &session.cwd)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| internal_error("workspace routing discovery cancelled"))?;
|
}
|
||||||
let config = match self
|
None => {
|
||||||
.config_manager
|
self.config_manager
|
||||||
.load_latest_config(/*fallback_cwd*/ None)
|
.load_latest_config(/*fallback_cwd*/ None)
|
||||||
.await
|
.await
|
||||||
{
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let config = match load_config().await {
|
||||||
Ok(config) => config,
|
Ok(config) => config,
|
||||||
Err(_)
|
Err(_)
|
||||||
if !self
|
if !self
|
||||||
@@ -74,7 +220,7 @@ impl AccountRequestProcessor {
|
|||||||
{
|
{
|
||||||
self.config.as_ref().clone()
|
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 auth = self.auth_manager.auth_cached();
|
||||||
let provider = create_model_provider(
|
let provider = create_model_provider(
|
||||||
@@ -83,65 +229,116 @@ impl AccountRequestProcessor {
|
|||||||
);
|
);
|
||||||
let account_state = provider
|
let account_state = provider
|
||||||
.account_state()
|
.account_state()
|
||||||
.map_err(|err| invalid_request(err.to_string()))?;
|
.map_err(AccountReadError::InvalidAccount)?;
|
||||||
let account = account_state.account.map(Account::from);
|
let mut workspace_routing = if let Some((auth, account_id)) = auth
|
||||||
let workspace_routing = if let Some((auth, account_id)) = auth
|
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.filter(|auth| {
|
.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)))
|
.and_then(|auth| auth.get_account_id().map(|account_id| (auth, account_id)))
|
||||||
{
|
{
|
||||||
if account_id.is_empty() {
|
if account_id.is_empty() {
|
||||||
return Err(internal_error(
|
return Err(WorkspaceRoutingError::MissingAccountId.into());
|
||||||
"workspace routing requires a ChatGPT account id",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
let required_chatgpt_base_url = config
|
let required_chatgpt_base_url = config
|
||||||
.config_layer_stack
|
.config_layer_stack
|
||||||
.requirements_toml()
|
.requirements_toml()
|
||||||
.chatgpt_base_url
|
.chatgpt_base_url
|
||||||
.clone();
|
.clone();
|
||||||
let cached = self
|
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
|
||||||
|
.map_err(|_| WorkspaceRoutingError::DiscoveryCancelled)?;
|
||||||
|
let fetched = fetch.routing.lock().await.clone();
|
||||||
|
let cached = match fetched {
|
||||||
|
Some(routing) => Some(routing),
|
||||||
|
None => self
|
||||||
.workspace_routing
|
.workspace_routing
|
||||||
.lock()
|
.lock()
|
||||||
.await
|
.await
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.filter(|cached| {
|
.filter(|cached| cached.key == key)
|
||||||
cached.auth_generation == auth_state.generation
|
.map(|cached| cached.routing.clone()),
|
||||||
&& cached.effective_chatgpt_base_url == config.chatgpt_base_url
|
};
|
||||||
&& cached.required_chatgpt_base_url == required_chatgpt_base_url
|
let routing = if let Some(cached) = cached {
|
||||||
&& cached.routing.chatgpt_account_id == account_id
|
cached
|
||||||
})
|
|
||||||
.map(|cached| cached.routing.clone());
|
|
||||||
if let Some(cached) = cached {
|
|
||||||
Some(cached)
|
|
||||||
} else {
|
} else {
|
||||||
*self.workspace_routing.lock().await = None;
|
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(
|
let client = BackendClient::from_auth(
|
||||||
&config.chatgpt_base_url,
|
&config.chatgpt_base_url,
|
||||||
auth,
|
&discovery_auth,
|
||||||
config.http_client_factory(),
|
config.http_client_factory(),
|
||||||
);
|
);
|
||||||
let response = client
|
match client.get_accounts_check().await {
|
||||||
.get_accounts_check()
|
Ok(response) => break response,
|
||||||
.await
|
Err(error) => {
|
||||||
.map_err(|_| internal_error("workspace routing discovery failed"))?;
|
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
|
let mut accounts = response
|
||||||
.accounts
|
.accounts
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|account| account.id == account_id);
|
.filter(|account| account.id == account_id);
|
||||||
let entry = accounts.next().ok_or_else(|| {
|
let entry = accounts
|
||||||
internal_error("selected workspace missing from routing discovery")
|
.next()
|
||||||
})?;
|
.ok_or(WorkspaceRoutingError::MissingWorkspace)?;
|
||||||
if accounts.next().is_some() {
|
if accounts.next().is_some() {
|
||||||
return Err(internal_error("duplicate workspace in routing discovery"));
|
return Err(WorkspaceRoutingError::DuplicateWorkspace.into());
|
||||||
}
|
}
|
||||||
let latest_config = self
|
let latest_config = load_config()
|
||||||
.config_manager
|
|
||||||
.load_latest_config(/*fallback_cwd*/ None)
|
|
||||||
.await
|
.await
|
||||||
.map_err(|_| internal_error("failed to reload workspace requirements"))?;
|
.map_err(|_| WorkspaceRoutingError::RequirementsReload)?;
|
||||||
if latest_config.chatgpt_base_url != config.chatgpt_base_url
|
if latest_config.chatgpt_base_url != config.chatgpt_base_url
|
||||||
|| latest_config.model_provider != config.model_provider
|
|| latest_config.model_provider != config.model_provider
|
||||||
|| latest_config
|
|| latest_config
|
||||||
@@ -150,9 +347,7 @@ impl AccountRequestProcessor {
|
|||||||
.chatgpt_base_url
|
.chatgpt_base_url
|
||||||
!= required_chatgpt_base_url
|
!= required_chatgpt_base_url
|
||||||
{
|
{
|
||||||
return Err(internal_error(
|
return Err(WorkspaceRoutingError::ConfigurationChanged.into());
|
||||||
"configuration changed during workspace routing discovery; retry account/read",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
let routing = resolve_routing(
|
let routing = resolve_routing(
|
||||||
entry,
|
entry,
|
||||||
@@ -162,44 +357,68 @@ impl AccountRequestProcessor {
|
|||||||
let mut cached = self.workspace_routing.lock().await;
|
let mut cached = self.workspace_routing.lock().await;
|
||||||
if current_auth_changes.borrow().owner_generation != auth_state.owner_generation
|
if current_auth_changes.borrow().owner_generation != auth_state.owner_generation
|
||||||
{
|
{
|
||||||
return Err(internal_error(
|
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||||
"account changed during workspace routing discovery",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
// Same-owner refresh can complete a newer discovery first.
|
||||||
|
if current_auth_changes.borrow().generation == discovery_generation {
|
||||||
*cached = Some(CachedWorkspaceRouting {
|
*cached = Some(CachedWorkspaceRouting {
|
||||||
auth_generation: auth_state.generation,
|
key: WorkspaceRoutingKey {
|
||||||
effective_chatgpt_base_url: config.chatgpt_base_url.clone(),
|
auth_generation: discovery_generation,
|
||||||
required_chatgpt_base_url,
|
..key
|
||||||
|
},
|
||||||
routing: routing.clone(),
|
routing: routing.clone(),
|
||||||
});
|
});
|
||||||
Some(routing)
|
|
||||||
}
|
}
|
||||||
|
routing
|
||||||
|
};
|
||||||
|
*fetch.routing.lock().await = Some(routing.clone());
|
||||||
|
Some(routing)
|
||||||
} else {
|
} else {
|
||||||
*self.workspace_routing.lock().await = None;
|
*self.workspace_routing.lock().await = None;
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
Ok(GetAccountResponse {
|
if let Some(request) = request.filter(|_| workspace_routing.is_some()) {
|
||||||
account,
|
let origin = Url::parse(&request.provider_base_url)
|
||||||
requires_openai_auth: account_state.requires_openai_auth,
|
.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,
|
workspace_routing,
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
let result = tokio::select! {
|
let result = tokio::select! {
|
||||||
biased;
|
biased;
|
||||||
_ = self.workspace_routing_shutdown.cancelled() => {
|
_ = 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) => {
|
_ = 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 = 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 {
|
if auth_changes.borrow().owner_generation != auth_state.owner_generation {
|
||||||
return Err(internal_error(
|
return Err(WorkspaceRoutingError::AccountChanged.into());
|
||||||
"account changed during workspace routing discovery",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
@@ -209,18 +428,14 @@ fn resolve_routing(
|
|||||||
entry: AccountEntry,
|
entry: AccountEntry,
|
||||||
required_chatgpt_base_url: Option<&str>,
|
required_chatgpt_base_url: Option<&str>,
|
||||||
effective_base_url: &str,
|
effective_base_url: &str,
|
||||||
) -> Result<WorkspaceRouting, JSONRPCErrorError> {
|
) -> Result<WorkspaceRouting, AccountReadError> {
|
||||||
let backend = entry
|
let backend = entry
|
||||||
.workspace_backend_origin
|
.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() {
|
let account_routing_override = match entry.account_routing_override.as_deref() {
|
||||||
Some("NO_CONSTRAINT") => AccountRoutingOverride::NoConstraint,
|
Some(value @ ("NO_CONSTRAINT" | "us" | "us_cr")) => value.to_owned(),
|
||||||
Some("us") => AccountRoutingOverride::Us,
|
|
||||||
Some("us_cr") => AccountRoutingOverride::UsCr,
|
|
||||||
_ => {
|
_ => {
|
||||||
return Err(internal_error(
|
return Err(WorkspaceRoutingError::InvalidRoutingOverride.into());
|
||||||
"workspace routing discovery has invalid account routing override",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let required = required_chatgpt_base_url
|
let required = required_chatgpt_base_url
|
||||||
@@ -231,18 +446,14 @@ fn resolve_routing(
|
|||||||
} else {
|
} else {
|
||||||
let url = parse_backend_url(&backend)?;
|
let url = parse_backend_url(&backend)?;
|
||||||
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
|
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
|
||||||
return Err(internal_error(
|
return Err(WorkspaceRoutingError::BackendIsNotOrigin.into());
|
||||||
"workspace routing discovery must return an origin",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
Some(url)
|
Some(url)
|
||||||
};
|
};
|
||||||
let origin = match (required, discovered) {
|
let origin = match (required, discovered) {
|
||||||
(Some(required), Some(discovered)) => {
|
(Some(required), Some(discovered)) => {
|
||||||
if required.origin() != discovered.origin() {
|
if required.origin() != discovered.origin() {
|
||||||
return Err(internal_error(
|
return Err(WorkspaceRoutingError::BackendConflict.into());
|
||||||
"required ChatGPT backend conflicts with workspace routing",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
required.origin()
|
required.origin()
|
||||||
}
|
}
|
||||||
@@ -256,17 +467,15 @@ fn resolve_routing(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_backend_url(value: &str) -> Result<Url, JSONRPCErrorError> {
|
fn parse_backend_url(value: &str) -> Result<Url, AccountReadError> {
|
||||||
let url = Url::parse(value).map_err(|_| internal_error("invalid workspace backend URL"))?;
|
let url = Url::parse(value).map_err(|_| WorkspaceRoutingError::InvalidBackendUrl)?;
|
||||||
if url.scheme() != "https"
|
if url.scheme() != "https"
|
||||||
|| url.host_str().is_none()
|
|| url.host_str().is_none()
|
||||||
|| !url.username().is_empty()
|
|| !url.username().is_empty()
|
||||||
|| url.password().is_some()
|
|| url.password().is_some()
|
||||||
|| value.trim() != value
|
|| value.trim() != value
|
||||||
{
|
{
|
||||||
return Err(internal_error(
|
return Err(WorkspaceRoutingError::InvalidBackendOrigin.into());
|
||||||
"workspace backend must use an HTTPS origin without credentials",
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
Ok(url)
|
Ok(url)
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-16
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use pretty_assertions::assert_eq;
|
use pretty_assertions::assert_eq;
|
||||||
|
use serde_json::Value;
|
||||||
use test_case::test_case;
|
use test_case::test_case;
|
||||||
|
|
||||||
#[test_case(Some("https://gov.chatgpt.com/backend-api/"), "NO_CONSTRAINT", "https://gov.chatgpt.com"; "configured_only")]
|
#[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 {
|
WorkspaceRouting {
|
||||||
chatgpt_account_id: "workspace".into(),
|
chatgpt_account_id: "workspace".into(),
|
||||||
backend_origin: expected.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());
|
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!(null), serde_json::json!("us_cr"), WorkspaceRoutingError::MissingBackendOrigin; "null_origin")]
|
||||||
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(null); "null_routing")]
|
#[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"); "empty_origin")]
|
#[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"); "origin_with_path")]
|
#[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"); "origin_with_query")]
|
#[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"); "origin_with_fragment")]
|
#[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"); "credentials")]
|
#[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"); "insecure_origin")]
|
#[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"); "unknown_routing")]
|
#[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!(""); "empty_routing")]
|
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(""), WorkspaceRoutingError::InvalidRoutingOverride; "empty_routing")]
|
||||||
fn rejects_invalid_discovery(backend: serde_json::Value, routing: serde_json::Value) {
|
fn rejects_invalid_discovery(backend: Value, routing: Value, expected: WorkspaceRoutingError) {
|
||||||
let entry = serde_json::from_value(serde_json::json!({
|
let entry = serde_json::from_value(serde_json::json!({
|
||||||
"id": "workspace", "workspace_backend_origin": backend, "account_routing_override": routing,
|
"id": "workspace", "workspace_backend_origin": backend, "account_routing_override": routing,
|
||||||
}))
|
}))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(
|
assert_eq!(
|
||||||
resolve_routing(
|
resolve_routing(
|
||||||
entry,
|
entry,
|
||||||
/*required_chatgpt_base_url*/ None,
|
/*required_chatgpt_base_url*/ None,
|
||||||
"https://chatgpt.com"
|
"https://chatgpt.com"
|
||||||
)
|
),
|
||||||
.is_err()
|
Err(AccountReadError::Routing(expected))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,7 +78,7 @@ fn unrestricted_discovery_uses_effective_custom_backend() {
|
|||||||
WorkspaceRouting {
|
WorkspaceRouting {
|
||||||
chatgpt_account_id: "workspace".into(),
|
chatgpt_account_id: "workspace".into(),
|
||||||
backend_origin: "https://custom.example:8443".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) {
|
pub async fn mount_workspace_routing(server: &wiremock::MockServer) {
|
||||||
wiremock::Mock::given(wiremock::matchers::method("GET"))
|
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| {
|
.respond_with(|request: &wiremock::Request| {
|
||||||
let account_id = request
|
let account_id = request
|
||||||
.headers
|
.headers
|
||||||
|
|||||||
@@ -615,17 +615,23 @@ async fn mount_disabled_attribution_settings(mock_server: &MockServer) {
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test_case("/v1"; "responses")]
|
||||||
|
#[test_case("/backend-api/codex"; "discovery")]
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
// 401 response triggers account/chatgptAuthTokens/refresh and retries with new tokens.
|
// 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 codex_home = TempDir::new()?;
|
||||||
let mock_server = MockServer::start().await;
|
let mock_server = MockServer::start().await;
|
||||||
|
let backend = MockServer::start().await;
|
||||||
create_config_toml(
|
create_config_toml(
|
||||||
codex_home.path(),
|
codex_home.path(),
|
||||||
CreateConfigTomlParams {
|
CreateConfigTomlParams {
|
||||||
requires_openai_auth: Some(true),
|
model_provider_id: Some("routing".into()),
|
||||||
base_url: Some(format!("{}/v1", mock_server.uri())),
|
extra_provider_config: Some(format!(
|
||||||
chatgpt_base_url: Some(format!("{}/backend-api", mock_server.uri())),
|
"[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()
|
..Default::default()
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
@@ -641,22 +647,33 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
|
|||||||
}));
|
}));
|
||||||
let responses_mock = responses::mount_response_sequence(
|
let responses_mock = responses::mount_response_sequence(
|
||||||
&mock_server,
|
&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;
|
.await;
|
||||||
mount_disabled_attribution_settings(&mock_server).await;
|
mount_disabled_attribution_settings(&backend).await;
|
||||||
|
|
||||||
let initial_access_token = encode_id_token(
|
let initial_access_token = encode_id_token(
|
||||||
&ChatGptIdTokenClaims::new()
|
&ChatGptIdTokenClaims::new()
|
||||||
.email("initial@example.com")
|
.email("initial@example.com")
|
||||||
|
.chatgpt_user_id("user")
|
||||||
.plan_type("pro")
|
.plan_type("pro")
|
||||||
.chatgpt_account_id(WORKSPACE_ID_INITIAL),
|
.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(
|
let refreshed_access_token = encode_id_token(
|
||||||
&ChatGptIdTokenClaims::new()
|
&ChatGptIdTokenClaims::new()
|
||||||
.email("refreshed@example.com")
|
.email("refreshed@example.com")
|
||||||
|
.chatgpt_user_id("user")
|
||||||
.plan_type("pro")
|
.plan_type("pro")
|
||||||
.chatgpt_account_id(WORKSPACE_ID_REFRESHED),
|
.chatgpt_account_id(refreshed_workspace),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let mut mcp = TestAppServer::builder()
|
let mut mcp = TestAppServer::builder()
|
||||||
@@ -691,6 +708,25 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
|
|||||||
let thread: codex_app_server_protocol::ThreadStartResponse =
|
let thread: codex_app_server_protocol::ThreadStartResponse =
|
||||||
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(thread_req)).await??;
|
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
|
let turn_req = mcp
|
||||||
.send_turn_start_request(codex_app_server_protocol::TurnStartParams {
|
.send_turn_start_request(codex_app_server_protocol::TurnStartParams {
|
||||||
thread_id: thread.thread.id,
|
thread_id: thread.thread.id,
|
||||||
@@ -705,7 +741,7 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
|
|||||||
respond_to_refresh_request(
|
respond_to_refresh_request(
|
||||||
&mut mcp,
|
&mut mcp,
|
||||||
&refreshed_access_token,
|
&refreshed_access_token,
|
||||||
WORKSPACE_ID_REFRESHED,
|
refreshed_workspace,
|
||||||
Some("pro"),
|
Some("pro"),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -718,13 +754,9 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> {
|
|||||||
.await??;
|
.await??;
|
||||||
|
|
||||||
let requests = responses_mock.requests();
|
let requests = responses_mock.requests();
|
||||||
assert_eq!(requests.len(), 2);
|
assert_eq!(requests.len(), if model_path == "/v1" { 2 } else { 1 });
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
requests[0].header("authorization"),
|
requests[requests.len() - 1].header("authorization"),
|
||||||
Some(format!("Bearer {initial_access_token}"))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
requests[1].header("authorization"),
|
|
||||||
Some(format!("Bearer {refreshed_access_token}"))
|
Some(format!("Bearer {refreshed_access_token}"))
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -527,6 +527,7 @@ pub(crate) async fn mount_analytics_capture(server: &MockServer, codex_home: &Pa
|
|||||||
AuthCredentialsStoreMode::File,
|
AuthCredentialsStoreMode::File,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
app_test_support::mount_workspace_routing(server).await;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
|
|||||||
hint_text: &str,
|
hint_text: &str,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let server = responses::start_mock_server().await;
|
let server = responses::start_mock_server().await;
|
||||||
|
let backend = responses::start_mock_server().await;
|
||||||
let response_mock = responses::mount_sse_once(
|
let response_mock = responses::mount_sse_once(
|
||||||
&server,
|
&server,
|
||||||
responses::sse(vec![
|
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]}))?,
|
serde_json::to_vec(&json!({"models": [model]}))?,
|
||||||
)?;
|
)?;
|
||||||
MockResponsesConfig::new(&server.uri())
|
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!(
|
.with_root_config(&format!(
|
||||||
"model_catalog_json = {}",
|
"model_catalog_json = {}",
|
||||||
serde_json::to_string(&catalog_path)?
|
serde_json::to_string(&catalog_path)?
|
||||||
@@ -135,7 +136,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
|
|||||||
server.uri(),
|
server.uri(),
|
||||||
))
|
))
|
||||||
.write(codex_home.path())?;
|
.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()
|
let mut app_server = TestAppServer::builder()
|
||||||
.with_codex_home(codex_home.path())
|
.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 {
|
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_type"] == "codex_thread_hint_status"
|
||||||
&& event["event_params"]["thread_id"] == thread.id
|
&& 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 server = responses::start_mock_server().await;
|
||||||
|
let backend = responses::start_mock_server().await;
|
||||||
for (namespace, tool, arguments) in &calls[..9] {
|
for (namespace, tool, arguments) in &calls[..9] {
|
||||||
Mock::given(method("POST"))
|
Mock::given(method("POST"))
|
||||||
.and(path(format!(
|
.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_name("OpenAI")
|
||||||
.with_provider_base_url(&format!("{}/backend-api/codex", server.uri()))
|
.with_provider_base_url(&format!("{}/backend-api/codex", server.uri()))
|
||||||
.with_provider_config("supports_websockets = false\nrequires_openai_auth = true")
|
.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!(
|
.with_root_config(&format!(
|
||||||
"model_catalog_json = {}",
|
"model_catalog_json = {}",
|
||||||
serde_json::to_string(&catalog_path)?
|
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",
|
"[features.token_budget]\nenabled = true\nuse_history_notes_extension = true",
|
||||||
)
|
)
|
||||||
.write(codex_home.path())?;
|
.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()
|
let mut app_server = TestAppServer::builder()
|
||||||
.with_codex_home(codex_home.path())
|
.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() {
|
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_type"] == "codex_control_tool_call_event"
|
||||||
&& event["event_params"]["item_id"] == format!("call-{index}")
|
&& 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_"));
|
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_type"] == "codex_turn_event"
|
||||||
&& event["event_params"]["turn_id"] == completed.turn.id
|
&& event["event_params"]["turn_id"] == completed.turn.id
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -5478,10 +5478,13 @@ async fn rebuild_with_session_layers_refreshes_requirements() -> std::io::Result
|
|||||||
thread_layer_stack,
|
thread_layer_stack,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
let zsh_path = refreshed_config.zsh_path.clone();
|
||||||
let config = Config::rebuild_with_session_layers(
|
let config = Config::rebuild_with_session_layers(
|
||||||
&thread_config.config_layer_stack,
|
&thread_config.config_layer_stack,
|
||||||
thread_config.cwd.to_path_buf(),
|
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?;
|
.await?;
|
||||||
|
|
||||||
@@ -5603,10 +5606,13 @@ async fn rebuild_with_session_layers_refreshes_plugin_derived_mcp_config() -> an
|
|||||||
thread_layer_stack,
|
thread_layer_stack,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
let zsh_path = refreshed_config.zsh_path.clone();
|
||||||
let config = Config::rebuild_with_session_layers(
|
let config = Config::rebuild_with_session_layers(
|
||||||
&thread_config.config_layer_stack,
|
&thread_config.config_layer_stack,
|
||||||
thread_config.cwd.to_path_buf(),
|
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?;
|
.await?;
|
||||||
let plugins_manager =
|
let plugins_manager =
|
||||||
|
|||||||
@@ -1844,22 +1844,16 @@ impl Config {
|
|||||||
pub async fn rebuild_with_session_layers(
|
pub async fn rebuild_with_session_layers(
|
||||||
session_layers: &ConfigLayerStack,
|
session_layers: &ConfigLayerStack,
|
||||||
cwd: PathBuf,
|
cwd: PathBuf,
|
||||||
refreshed_config: &Config,
|
refreshed_layers: &ConfigLayerStack,
|
||||||
|
codex_home: AbsolutePathBuf,
|
||||||
|
default_zsh_path: Option<AbsolutePathBuf>,
|
||||||
) -> std::io::Result<Self> {
|
) -> std::io::Result<Self> {
|
||||||
let config_layer_stack = Self::layer_stack_preserving_session(
|
let config_layer_stack =
|
||||||
session_layers,
|
Self::layer_stack_preserving_session(session_layers, refreshed_layers)?;
|
||||||
&refreshed_config.config_layer_stack,
|
|
||||||
)?;
|
|
||||||
let cfg: ConfigToml = config_layer_stack
|
let cfg: ConfigToml = config_layer_stack
|
||||||
.effective_config()
|
.effective_config()
|
||||||
.try_into()
|
.try_into()
|
||||||
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
|
.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(
|
Self::load_config_with_layer_stack(
|
||||||
LOCAL_FS.as_ref(),
|
LOCAL_FS.as_ref(),
|
||||||
cfg,
|
cfg,
|
||||||
@@ -1868,7 +1862,7 @@ impl Config {
|
|||||||
default_zsh_path,
|
default_zsh_path,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
refreshed_config.codex_home.clone(),
|
codex_home,
|
||||||
config_layer_stack,
|
config_layer_stack,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -181,7 +181,13 @@ X-Managed = "required"
|
|||||||
let rebuilt = Config::rebuild_with_session_layers(
|
let rebuilt = Config::rebuild_with_session_layers(
|
||||||
&overridden.config_layer_stack,
|
&overridden.config_layer_stack,
|
||||||
overridden.cwd.to_path_buf(),
|
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?;
|
.await?;
|
||||||
assert_eq!(rebuilt.model_provider, test.config.model_provider);
|
assert_eq!(rebuilt.model_provider, test.config.model_provider);
|
||||||
|
|||||||
+2
-2
@@ -6,7 +6,7 @@ Scenario: Astra asks who a launch update is for, keeps working, and receives the
|
|||||||
|
|
||||||
## Window 1
|
## Window 1
|
||||||
-- request 1 (request) --
|
-- request 1 (request) --
|
||||||
00:additional_tools/developer (3; hash=d4f3e164a92d9bf1):
|
00:additional_tools/developer (3; hash=9e8e744a3a55a2dd):
|
||||||
- namespace/functions; hash=e7db0a45c4ec3157
|
- namespace/functions; hash=e7db0a45c4ec3157
|
||||||
- custom/exec
|
- custom/exec
|
||||||
- function/wait
|
- 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
|
- function/request_user_input_async
|
||||||
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
||||||
- function/sleep
|
- 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/followup_task
|
||||||
- function/interrupt_agent
|
- function/interrupt_agent
|
||||||
- function/list_agents
|
- function/list_agents
|
||||||
|
|||||||
+2
-2
@@ -16,7 +16,7 @@ Settings:
|
|||||||
text: {"verbosity":"low"}
|
text: {"verbosity":"low"}
|
||||||
tool_choice: "auto"
|
tool_choice: "auto"
|
||||||
-- request 1 (request) --
|
-- request 1 (request) --
|
||||||
00:additional_tools/developer (3; hash=24819537059703a0):
|
00:additional_tools/developer (3; hash=d78b689d87e8c03e):
|
||||||
- namespace/functions; hash=97852c93915dad58
|
- namespace/functions; hash=97852c93915dad58
|
||||||
- custom/exec
|
- custom/exec
|
||||||
- function/wait
|
- function/wait
|
||||||
@@ -24,7 +24,7 @@ Settings:
|
|||||||
- function/request_user_input_async
|
- function/request_user_input_async
|
||||||
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
||||||
- function/sleep
|
- 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/followup_task
|
||||||
- function/interrupt_agent
|
- function/interrupt_agent
|
||||||
- function/list_agents
|
- function/list_agents
|
||||||
|
|||||||
+4
-4
@@ -16,7 +16,7 @@ Settings:
|
|||||||
text: {"verbosity":"low"}
|
text: {"verbosity":"low"}
|
||||||
tool_choice: "auto"
|
tool_choice: "auto"
|
||||||
-- request 1 (turn) --
|
-- request 1 (turn) --
|
||||||
00:additional_tools/developer (3; hash=d4f3e164a92d9bf1):
|
00:additional_tools/developer (3; hash=9e8e744a3a55a2dd):
|
||||||
- namespace/functions; hash=e7db0a45c4ec3157
|
- namespace/functions; hash=e7db0a45c4ec3157
|
||||||
- custom/exec
|
- custom/exec
|
||||||
- function/wait
|
- function/wait
|
||||||
@@ -24,7 +24,7 @@ Settings:
|
|||||||
- function/request_user_input_async
|
- function/request_user_input_async
|
||||||
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
||||||
- function/sleep
|
- 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/followup_task
|
||||||
- function/interrupt_agent
|
- function/interrupt_agent
|
||||||
- function/list_agents
|
- function/list_agents
|
||||||
@@ -190,7 +190,7 @@ Settings:
|
|||||||
## Window 2 (after request 3: input diverged at item 02)
|
## Window 2 (after request 3: input diverged at item 02)
|
||||||
Settings: same as window 1
|
Settings: same as window 1
|
||||||
-- request 4 (turn) --
|
-- request 4 (turn) --
|
||||||
00:additional_tools/developer (3; hash=d4f3e164a92d9bf1):
|
00:additional_tools/developer (3; hash=9e8e744a3a55a2dd):
|
||||||
- namespace/functions; hash=e7db0a45c4ec3157
|
- namespace/functions; hash=e7db0a45c4ec3157
|
||||||
- custom/exec
|
- custom/exec
|
||||||
- function/wait
|
- function/wait
|
||||||
@@ -198,7 +198,7 @@ Settings: same as window 1
|
|||||||
- function/request_user_input_async
|
- function/request_user_input_async
|
||||||
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
||||||
- function/sleep
|
- 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/followup_task
|
||||||
- function/interrupt_agent
|
- function/interrupt_agent
|
||||||
- function/list_agents
|
- function/list_agents
|
||||||
|
|||||||
+4
-4
@@ -16,7 +16,7 @@ Settings:
|
|||||||
text: {"verbosity":"low"}
|
text: {"verbosity":"low"}
|
||||||
tool_choice: "auto"
|
tool_choice: "auto"
|
||||||
-- request 1 (turn) --
|
-- request 1 (turn) --
|
||||||
00:additional_tools/developer (3; hash=d4f3e164a92d9bf1):
|
00:additional_tools/developer (3; hash=9e8e744a3a55a2dd):
|
||||||
- namespace/functions; hash=e7db0a45c4ec3157
|
- namespace/functions; hash=e7db0a45c4ec3157
|
||||||
- custom/exec
|
- custom/exec
|
||||||
- function/wait
|
- function/wait
|
||||||
@@ -24,7 +24,7 @@ Settings:
|
|||||||
- function/request_user_input_async
|
- function/request_user_input_async
|
||||||
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
||||||
- function/sleep
|
- 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/followup_task
|
||||||
- function/interrupt_agent
|
- function/interrupt_agent
|
||||||
- function/list_agents
|
- function/list_agents
|
||||||
@@ -113,7 +113,7 @@ Settings:
|
|||||||
## Window 2 (after request 2: input diverged at item 00)
|
## Window 2 (after request 2: input diverged at item 00)
|
||||||
Settings: same as window 1
|
Settings: same as window 1
|
||||||
-- request 3 (turn) --
|
-- request 3 (turn) --
|
||||||
00:additional_tools/developer (3; hash=61ace4f77de8d87f):
|
00:additional_tools/developer (3; hash=d9bfc9d2033f8c93):
|
||||||
- namespace/functions; hash=8c17932a39355f2d
|
- namespace/functions; hash=8c17932a39355f2d
|
||||||
- custom/exec
|
- custom/exec
|
||||||
- function/wait
|
- function/wait
|
||||||
@@ -121,7 +121,7 @@ Settings: same as window 1
|
|||||||
- function/request_user_input_async
|
- function/request_user_input_async
|
||||||
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
||||||
- function/sleep
|
- 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/followup_task
|
||||||
- function/interrupt_agent
|
- function/interrupt_agent
|
||||||
- function/list_agents
|
- function/list_agents
|
||||||
|
|||||||
+2
-2
@@ -16,7 +16,7 @@ Settings:
|
|||||||
text: {"verbosity":"low"}
|
text: {"verbosity":"low"}
|
||||||
tool_choice: "auto"
|
tool_choice: "auto"
|
||||||
-- request 1 (turn) --
|
-- request 1 (turn) --
|
||||||
00:additional_tools/developer (3; hash=61ace4f77de8d87f):
|
00:additional_tools/developer (3; hash=d9bfc9d2033f8c93):
|
||||||
- namespace/functions; hash=8c17932a39355f2d
|
- namespace/functions; hash=8c17932a39355f2d
|
||||||
- custom/exec
|
- custom/exec
|
||||||
- function/wait
|
- function/wait
|
||||||
@@ -24,7 +24,7 @@ Settings:
|
|||||||
- function/request_user_input_async
|
- function/request_user_input_async
|
||||||
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
||||||
- function/sleep
|
- 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/followup_task
|
||||||
- function/interrupt_agent
|
- function/interrupt_agent
|
||||||
- function/list_agents
|
- function/list_agents
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ use crate::AuthManager;
|
|||||||
use crate::CodexAuth;
|
use crate::CodexAuth;
|
||||||
|
|
||||||
/// A successful discovery for one selected workspace.
|
/// A successful discovery for one selected workspace.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct WorkspaceRouting {
|
pub struct WorkspaceRouting {
|
||||||
pub chatgpt_account_id: String,
|
pub chatgpt_account_id: String,
|
||||||
pub backend_origin: String,
|
pub backend_origin: String,
|
||||||
@@ -44,7 +44,8 @@ pub struct WorkspaceRoutingRequest {
|
|||||||
|
|
||||||
/// Resolves routing through the account owner's cache and requirements loader.
|
/// Resolves routing through the account owner's cache and requirements loader.
|
||||||
/// Returns no routing for independent destinations or no selected workspace.
|
/// 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.
|
/// Implementations must reject failed discovery and changes to the selected account.
|
||||||
pub trait WorkspaceRoutingResolver: Send + Sync {
|
pub trait WorkspaceRoutingResolver: Send + Sync {
|
||||||
fn resolve(
|
fn resolve(
|
||||||
@@ -68,13 +69,15 @@ impl AuthManager {
|
|||||||
let Some(resolver) = self.workspace_routing_resolver.get() else {
|
let Some(resolver) = self.workspace_routing_resolver.get() else {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
let auth_changes = self.auth_change_receiver();
|
let auth_changes = self.auth_change_state_receiver();
|
||||||
let revision = *auth_changes.borrow();
|
let owner_generation = auth_changes.borrow().owner_generation;
|
||||||
let resolver = resolver
|
let resolver = resolver
|
||||||
.upgrade()
|
.upgrade()
|
||||||
.ok_or_else(|| io::Error::other("workspace routing owner is unavailable"))?;
|
.ok_or_else(|| io::Error::other("workspace routing owner is unavailable"))?;
|
||||||
let routing = resolver.resolve(request).await?;
|
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| {
|
|| routing.as_ref().is_some_and(|routing| {
|
||||||
auth.get_account_id().as_deref() != Some(routing.chatgpt_account_id.as_str())
|
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 (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||||
let backend = wiremock::MockServer::start().await;
|
let backend = wiremock::MockServer::start().await;
|
||||||
app.config.chatgpt_base_url = backend.uri();
|
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;
|
app.config.cli_auth_credentials_store_mode = AuthCredentialsStoreMode::File;
|
||||||
write_chatgpt_auth(
|
write_chatgpt_auth(
|
||||||
&app.config.codex_home,
|
&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),
|
(200, false, "gpt-5.6-sol", true, Notice::Limited),
|
||||||
] {
|
] {
|
||||||
backend.reset().await;
|
backend.reset().await;
|
||||||
|
app_test_support::mount_workspace_routing(&backend).await;
|
||||||
let codex_home = app.config.codex_home.clone();
|
let codex_home = app.config.codex_home.clone();
|
||||||
let response = wiremock::ResponseTemplate::new(status)
|
let response = wiremock::ResponseTemplate::new(status)
|
||||||
.set_delay(if model == "gpt-5.6-sol" && enrolled { Duration::from_secs(1) } else { Duration::ZERO })
|
.set_delay(if model == "gpt-5.6-sol" && enrolled { Duration::from_secs(1) } else { Duration::ZERO })
|
||||||
|
|||||||
Reference in new issue
Block a user