From dc8b6a6a8b9a1e1f0b27f5f4237fb76b00268fe0 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 9 Jun 2026 01:42:25 +0000 Subject: [PATCH] refresh account plan from usage --- .../request_processors/account_processor.rs | 55 +++++--- .../app-server/tests/suite/v2/rate_limits.rs | 132 ++++++++++++++++++ codex-rs/login/src/auth/auth_tests.rs | 87 ++++++++++++ codex-rs/login/src/auth/manager.rs | 76 ++++++++++ codex-rs/model-provider/src/provider.rs | 8 +- codex-rs/tui/src/app/app_server_events.rs | 64 +++++++-- codex-rs/tui/src/app/tests.rs | 90 ++++++++++++ codex-rs/tui/src/chatwidget/rate_limits.rs | 2 - .../tui/src/chatwidget/status_controls.rs | 6 +- .../src/chatwidget/tests/status_and_layout.rs | 31 ++-- .../chatwidget/tests/status_command_tests.rs | 46 +++++- codex-rs/tui/src/status/card.rs | 39 ++++-- 12 files changed, 565 insertions(+), 71 deletions(-) diff --git a/codex-rs/app-server/src/request_processors/account_processor.rs b/codex-rs/app-server/src/request_processors/account_processor.rs index a4bbe42d61..6bd70567fa 100644 --- a/codex-rs/app-server/src/request_processors/account_processor.rs +++ b/codex-rs/app-server/src/request_processors/account_processor.rs @@ -161,10 +161,10 @@ impl AccountRequestProcessor { } fn current_account_updated_notification(&self) -> AccountUpdatedNotification { - let auth = self.auth_manager.auth_cached(); + let (auth, plan_type) = self.auth_manager.auth_cached_with_effective_account_plan(); AccountUpdatedNotification { auth_mode: auth.as_ref().map(CodexAuth::api_auth_mode), - plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type), + plan_type, } } @@ -663,12 +663,13 @@ impl AccountRequestProcessor { Self::maybe_refresh_remote_installed_plugins_cache_for_current_config( &config_manager, &thread_manager, - auth.clone(), + auth, ) .await; + let (auth, plan_type) = auth_manager.auth_cached_with_effective_account_plan(); let payload_v2 = AccountUpdatedNotification { auth_mode: auth.as_ref().map(CodexAuth::api_auth_mode), - plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type), + plan_type, }; outgoing .send_server_notification(ServerNotification::AccountUpdated(payload_v2)) @@ -842,19 +843,27 @@ impl AccountRequestProcessor { async fn get_account_rate_limits_response( &self, ) -> Result { - self.fetch_account_rate_limits() - .await - .map( - |(rate_limits, rate_limits_by_limit_id)| GetAccountRateLimitsResponse { - rate_limits: rate_limits.into(), - rate_limits_by_limit_id: Some( - rate_limits_by_limit_id - .into_iter() - .map(|(limit_id, snapshot)| (limit_id, snapshot.into())) - .collect(), - ), - }, - ) + let (rate_limits, rate_limits_by_limit_id, account_plan_changed) = + self.fetch_account_rate_limits().await?; + let response = GetAccountRateLimitsResponse { + rate_limits: rate_limits.into(), + rate_limits_by_limit_id: Some( + rate_limits_by_limit_id + .into_iter() + .map(|(limit_id, snapshot)| (limit_id, snapshot.into())) + .collect(), + ), + }; + + if account_plan_changed { + self.outgoing + .send_server_notification(ServerNotification::AccountUpdated( + self.current_account_updated_notification(), + )) + .await; + } + + Ok(response) } async fn get_account_token_usage_response( @@ -961,6 +970,7 @@ impl AccountRequestProcessor { ( CoreRateLimitSnapshot, HashMap, + bool, ), JSONRPCErrorError, > { @@ -975,6 +985,7 @@ impl AccountRequestProcessor { "chatgpt authentication required to read rate limits", )); } + let account_id = auth.get_account_id(); let client = BackendClient::from_auth(self.config.chatgpt_base_url.clone(), &auth) .map_err(|err| internal_error(format!("failed to construct backend client: {err}")))?; @@ -1006,8 +1017,16 @@ impl AccountRequestProcessor { .find(|snapshot| snapshot.limit_id.as_deref() == Some("codex")) .cloned() .unwrap_or_else(|| snapshots[0].clone()); + let account_plan_changed = if let (Some(account_id), Some(plan_type)) = + (account_id.as_deref(), primary.plan_type) + { + self.auth_manager + .record_account_plan_type_from_usage(account_id, plan_type) + } else { + false + }; - Ok((primary, rate_limits_by_limit_id)) + Ok((primary, rate_limits_by_limit_id, account_plan_changed)) } } diff --git a/codex-rs/app-server/tests/suite/v2/rate_limits.rs b/codex-rs/app-server/tests/suite/v2/rate_limits.rs index 1bb93db819..3c1f6cf88f 100644 --- a/codex-rs/app-server/tests/suite/v2/rate_limits.rs +++ b/codex-rs/app-server/tests/suite/v2/rate_limits.rs @@ -3,9 +3,14 @@ use app_test_support::ChatGptAuthFixture; use app_test_support::TestAppServer; use app_test_support::to_response; use app_test_support::write_chatgpt_auth; +use codex_app_server_protocol::Account; +use codex_app_server_protocol::AccountUpdatedNotification; use codex_app_server_protocol::AddCreditsNudgeCreditType; use codex_app_server_protocol::AddCreditsNudgeEmailStatus; +use codex_app_server_protocol::AuthMode; +use codex_app_server_protocol::GetAccountParams; use codex_app_server_protocol::GetAccountRateLimitsResponse; +use codex_app_server_protocol::GetAccountResponse; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::LoginAccountResponse; @@ -15,8 +20,10 @@ use codex_app_server_protocol::RateLimitWindow; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SendAddCreditsNudgeEmailParams; use codex_app_server_protocol::SendAddCreditsNudgeEmailResponse; +use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::SpendControlLimitSnapshot; use codex_config::types::AuthCredentialsStoreMode; +use codex_login::load_auth_dot_json; use codex_protocol::account::PlanType as AccountPlanType; use pretty_assertions::assert_eq; use serde_json::json; @@ -263,6 +270,131 @@ async fn get_account_rate_limits_returns_snapshot() -> Result<()> { Ok(()) } +#[tokio::test] +async fn usage_plan_change_updates_account_once_without_persisting_auth() -> Result<()> { + let codex_home = TempDir::new()?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .email("user@example.com") + .plan_type("free"), + AuthCredentialsStoreMode::File, + )?; + let auth_before = load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)? + .expect("auth.json should exist"); + + let server = MockServer::start().await; + write_chatgpt_base_url(codex_home.path(), &server.uri())?; + Mock::given(method("GET")) + .and(path("/api/codex/usage")) + .and(header("authorization", "Bearer chatgpt-token")) + .and(header("chatgpt-account-id", "account-123")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "plan_type": "pro", + }))) + .expect(2) + .mount(&server) + .await; + + let mut mcp = + TestAppServer::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let account_params = GetAccountParams { + refresh_token: false, + }; + let initial_request_id = mcp.send_get_account_request(account_params.clone()).await?; + let initial_response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(initial_request_id)), + ) + .await??; + let initial_account: GetAccountResponse = to_response(initial_response)?; + assert_eq!( + initial_account, + GetAccountResponse { + account: Some(Account::Chatgpt { + email: "user@example.com".to_string(), + plan_type: AccountPlanType::Free, + }), + requires_openai_auth: true, + } + ); + + let rate_limits_request_id = mcp.send_get_account_rate_limits_request().await?; + let rate_limits_response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(rate_limits_request_id)), + ) + .await??; + let rate_limits: GetAccountRateLimitsResponse = to_response(rate_limits_response)?; + assert_eq!( + rate_limits.rate_limits.plan_type, + Some(AccountPlanType::Pro) + ); + + let notification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("account/updated"), + ) + .await??; + let notification: ServerNotification = notification.try_into()?; + let ServerNotification::AccountUpdated(account_updated) = notification else { + panic!("unexpected notification: {notification:?}"); + }; + assert_eq!( + account_updated, + AccountUpdatedNotification { + auth_mode: Some(AuthMode::Chatgpt), + plan_type: Some(AccountPlanType::Pro), + } + ); + + let updated_request_id = mcp.send_get_account_request(account_params).await?; + let updated_response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(updated_request_id)), + ) + .await??; + let updated_account: GetAccountResponse = to_response(updated_response)?; + assert_eq!( + updated_account, + GetAccountResponse { + account: Some(Account::Chatgpt { + email: "user@example.com".to_string(), + plan_type: AccountPlanType::Pro, + }), + requires_openai_auth: true, + } + ); + + let repeated_request_id = mcp.send_get_account_rate_limits_request().await?; + let repeated_response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(repeated_request_id)), + ) + .await??; + let repeated_rate_limits: GetAccountRateLimitsResponse = to_response(repeated_response)?; + assert_eq!( + repeated_rate_limits.rate_limits.plan_type, + Some(AccountPlanType::Pro) + ); + assert!( + !mcp.pending_notification_methods() + .iter() + .any(|method| method == "account/updated"), + "identical usage plan should not emit another account/updated" + ); + + let auth_after = load_auth_dot_json(codex_home.path(), AuthCredentialsStoreMode::File)? + .expect("auth.json should still exist"); + assert_eq!(auth_after, auth_before); + + server.verify().await; + Ok(()) +} + #[tokio::test] async fn send_add_credits_nudge_email_requires_auth() -> Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/login/src/auth/auth_tests.rs b/codex-rs/login/src/auth/auth_tests.rs index e7b5502ebc..75d5adf963 100644 --- a/codex-rs/login/src/auth/auth_tests.rs +++ b/codex-rs/login/src/auth/auth_tests.rs @@ -700,6 +700,39 @@ fn write_auth_file(params: AuthFileParams, codex_home: &Path) -> std::io::Result Ok(fake_jwt) } +async fn test_chatgpt_auth(account_id: &str, plan_type: &str) -> CodexAuth { + let codex_home = tempdir().expect("tempdir"); + let fake_jwt = fake_jwt_for_auth_file_params(&AuthFileParams { + openai_api_key: None, + chatgpt_plan_type: Some(plan_type.to_string()), + chatgpt_account_id: Some(account_id.to_string()), + }) + .expect("encode auth token"); + let auth_json = json!({ + "tokens": { + "id_token": fake_jwt, + "access_token": "test-access-token", + "refresh_token": "test-refresh-token", + "account_id": account_id, + }, + "last_refresh": Utc::now(), + }); + std::fs::write( + get_auth_file(codex_home.path()), + serde_json::to_string_pretty(&auth_json).expect("serialize auth file"), + ) + .expect("write auth file"); + super::load_auth( + codex_home.path(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::File, + /*chatgpt_base_url*/ None, + ) + .await + .expect("load auth") + .expect("auth available") +} + fn fake_jwt_for_auth_file_params(params: &AuthFileParams) -> std::io::Result { #[derive(Serialize)] struct Header { @@ -1376,6 +1409,60 @@ async fn plan_type_maps_known_plan() { pretty_assertions::assert_eq!(auth.account_plan_type(), Some(AccountPlanType::Pro)); } +#[tokio::test] +async fn usage_plan_overrides_token_for_current_account_only() { + let auth = test_chatgpt_auth("account-a", "free").await; + let manager = AuthManager::from_auth_for_testing(auth); + + assert_eq!( + manager.effective_account_plan_type(), + Some(AccountPlanType::Free) + ); + assert!(!manager.record_account_plan_type_from_usage("account-b", AccountPlanType::Pro)); + assert_eq!( + manager.effective_account_plan_type(), + Some(AccountPlanType::Free) + ); + assert!(manager.record_account_plan_type_from_usage("account-a", AccountPlanType::Pro)); + assert_eq!( + manager.effective_account_plan_type(), + Some(AccountPlanType::Pro) + ); +} + +#[tokio::test] +async fn usage_plan_survives_same_account_reload_and_clears_on_account_change() { + let manager = AuthManager::from_auth_for_testing(test_chatgpt_auth("account-a", "free").await); + assert!(manager.record_account_plan_type_from_usage("account-a", AccountPlanType::Pro)); + + manager.set_cached_auth(Some(test_chatgpt_auth("account-a", "plus").await)); + assert_eq!( + manager.effective_account_plan_type(), + Some(AccountPlanType::Pro) + ); + + manager.set_cached_auth(Some(test_chatgpt_auth("account-b", "team").await)); + assert_eq!( + manager.effective_account_plan_type(), + Some(AccountPlanType::Team) + ); + + manager.set_cached_auth(None); + assert_eq!(manager.effective_account_plan_type(), None); +} + +#[tokio::test] +async fn matching_usage_plan_remains_authoritative_after_same_account_reload() { + let manager = AuthManager::from_auth_for_testing(test_chatgpt_auth("account-a", "free").await); + assert!(!manager.record_account_plan_type_from_usage("account-a", AccountPlanType::Free)); + + manager.set_cached_auth(Some(test_chatgpt_auth("account-a", "pro").await)); + assert_eq!( + manager.effective_account_plan_type(), + Some(AccountPlanType::Free) + ); +} + #[tokio::test] #[serial(codex_auth_env)] async fn plan_type_maps_self_serve_business_usage_based_plan() { diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index 9e255a99a3..ce08a7ae63 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -1088,11 +1088,19 @@ impl AuthDotJson { #[derive(Clone)] struct CachedAuth { auth: Option, + /// Latest plan reported by `/usage` for the current ChatGPT account. + usage_account_plan: Option, /// Permanent refresh failure cached for the current auth snapshot so /// later refresh attempts for the same credentials fail fast without network. permanent_refresh_failure: Option, } +#[derive(Clone, Debug)] +struct AccountScopedPlan { + account_id: String, + plan_type: AccountPlanType, +} + #[derive(Clone)] struct AuthScopedRefreshFailure { auth: CodexAuth, @@ -1420,6 +1428,7 @@ impl AuthManager { codex_home, inner: RwLock::new(CachedAuth { auth: managed_auth, + usage_account_plan: None, permanent_refresh_failure: None, }), auth_change_tx, @@ -1436,6 +1445,7 @@ impl AuthManager { pub fn from_auth_for_testing(auth: CodexAuth) -> Arc { let cached = CachedAuth { auth: Some(auth), + usage_account_plan: None, permanent_refresh_failure: None, }; let (auth_change_tx, _auth_change_rx) = watch::channel(0); @@ -1457,6 +1467,7 @@ impl AuthManager { pub fn from_auth_for_testing_with_home(auth: CodexAuth, codex_home: PathBuf) -> Arc { let cached = CachedAuth { auth: Some(auth), + usage_account_plan: None, permanent_refresh_failure: None, }; let (auth_change_tx, _auth_change_rx) = watch::channel(0); @@ -1479,6 +1490,7 @@ impl AuthManager { codex_home: PathBuf::from("non-existent"), inner: RwLock::new(CachedAuth { auth: None, + usage_account_plan: None, permanent_refresh_failure: None, }), auth_change_tx, @@ -1498,6 +1510,65 @@ impl AuthManager { self.inner.read().ok().and_then(|c| c.auth.clone()) } + /// Returns cached auth and its effective account plan from one state snapshot. + pub fn auth_cached_with_effective_account_plan( + &self, + ) -> (Option, Option) { + let Ok(cached) = self.inner.read() else { + return (None, None); + }; + let plan_type = Self::effective_account_plan_type_from_cached(&cached); + (cached.auth.clone(), plan_type) + } + + /// Returns the latest plan reported by `/usage` for the current account, + /// falling back to the plan embedded in the cached auth token. + pub fn effective_account_plan_type(&self) -> Option { + self.inner + .read() + .ok() + .and_then(|cached| Self::effective_account_plan_type_from_cached(&cached)) + } + + /// Records a plan returned by `/usage` only when it belongs to the account + /// that is still current. Returns whether the effective plan changed. + pub fn record_account_plan_type_from_usage( + &self, + account_id: &str, + plan_type: AccountPlanType, + ) -> bool { + let Ok(mut cached) = self.inner.write() else { + return false; + }; + if cached + .auth + .as_ref() + .and_then(CodexAuth::get_account_id) + .as_deref() + != Some(account_id) + { + return false; + } + + let previous = Self::effective_account_plan_type_from_cached(&cached); + cached.usage_account_plan = Some(AccountScopedPlan { + account_id: account_id.to_string(), + plan_type, + }); + previous != Some(plan_type) + } + + fn effective_account_plan_type_from_cached(cached: &CachedAuth) -> Option { + let auth = cached.auth.as_ref()?; + let account_id = auth.get_account_id(); + cached + .usage_account_plan + .as_ref() + .filter(|usage| account_id.as_deref() == Some(usage.account_id.as_str())) + .map(|usage| usage.plan_type) + .or_else(|| auth.account_plan_type()) + } + /// Subscribes to cached auth changes that can affect request recovery. pub fn auth_change_receiver(&self) -> watch::Receiver { self.auth_change_tx.subscribe() @@ -1638,12 +1709,17 @@ impl AuthManager { fn set_cached_auth(&self, new_auth: Option) -> bool { if let Ok(mut guard) = self.inner.write() { let previous = guard.auth.as_ref(); + let previous_account_id = previous.and_then(CodexAuth::get_account_id); + let new_account_id = new_auth.as_ref().and_then(CodexAuth::get_account_id); let changed = !AuthManager::auths_equal(previous, new_auth.as_ref()); let auth_changed_for_refresh = !Self::auths_equal_for_refresh(previous, new_auth.as_ref()); if auth_changed_for_refresh { guard.permanent_refresh_failure = None; } + if previous_account_id != new_account_id { + guard.usage_account_plan = None; + } tracing::info!("Reloaded auth, changed: {changed}"); guard.auth = new_auth; if auth_changed_for_refresh { diff --git a/codex-rs/model-provider/src/provider.rs b/codex-rs/model-provider/src/provider.rs index afd07065d4..e6ede271db 100644 --- a/codex-rs/model-provider/src/provider.rs +++ b/codex-rs/model-provider/src/provider.rs @@ -202,20 +202,20 @@ impl ModelProvider for ConfiguredModelProvider { self.auth_manager .as_ref() .and_then(|auth_manager| { - let auth = auth_manager.auth_cached()?; + let (auth, plan_type) = auth_manager.auth_cached_with_effective_account_plan(); + let auth = auth?; if auth_manager.refresh_failure_for_auth(&auth).is_some() { return None; } - Some(auth) + Some((auth, plan_type)) }) - .map(|auth| match &auth { + .map(|(auth, plan_type)| match &auth { CodexAuth::ApiKey(_) => Ok(ProviderAccount::ApiKey), CodexAuth::Chatgpt(_) | CodexAuth::ChatgptAuthTokens(_) | CodexAuth::AgentIdentity(_) | CodexAuth::PersonalAccessToken(_) => { let email = auth.get_account_email(); - let plan_type = auth.account_plan_type(); match (email, plan_type) { (Some(email), Some(plan_type)) => { diff --git a/codex-rs/tui/src/app/app_server_events.rs b/codex-rs/tui/src/app/app_server_events.rs index 268dbd305b..1c48ee0189 100644 --- a/codex-rs/tui/src/app/app_server_events.rs +++ b/codex-rs/tui/src/app/app_server_events.rs @@ -9,10 +9,18 @@ use crate::app_event::AppEvent; use crate::app_event::ConnectorsSnapshot; use crate::app_server_session::AppServerSession; use crate::app_server_session::status_account_display_from_auth_mode; +use crate::status::StatusAccountDisplay; +use crate::status::plan_type_display_name; use codex_app_server_client::AppServerEvent; +use codex_app_server_protocol::Account; use codex_app_server_protocol::AuthMode; +use codex_app_server_protocol::ClientRequest; +use codex_app_server_protocol::GetAccountParams; +use codex_app_server_protocol::GetAccountResponse; +use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequest; +use uuid::Uuid; impl App { pub(super) fn refresh_mcp_startup_expected_servers_from_config(&mut self) { @@ -80,16 +88,52 @@ impl App { return; } ServerNotification::AccountUpdated(notification) => { - self.chat_widget.update_account_state( - status_account_display_from_auth_mode( - notification.auth_mode, - notification.plan_type, - ), - notification.plan_type, - notification - .auth_mode - .is_some_and(AuthMode::has_chatgpt_account), - ); + let request_id = RequestId::String(format!("account-read-{}", Uuid::new_v4())); + let account: Result = app_server_client + .request_handle() + .request_typed(ClientRequest::GetAccount { + request_id, + params: GetAccountParams { + refresh_token: false, + }, + }) + .await; + match account { + Ok(account) => { + let (display, plan_type, has_chatgpt_account) = match account.account { + Some(Account::ApiKey {}) => { + (Some(StatusAccountDisplay::ApiKey), None, false) + } + Some(Account::Chatgpt { email, plan_type }) => ( + Some(StatusAccountDisplay::ChatGpt { + email: Some(email), + plan: Some(plan_type_display_name(plan_type)), + }), + Some(plan_type), + true, + ), + Some(Account::AmazonBedrock {}) | None => (None, None, false), + }; + self.chat_widget.update_account_state( + display, + plan_type, + has_chatgpt_account, + ); + } + Err(err) => { + tracing::warn!("account/read failed after account/updated: {err}"); + self.chat_widget.update_account_state( + status_account_display_from_auth_mode( + notification.auth_mode, + notification.plan_type, + ), + notification.plan_type, + notification + .auth_mode + .is_some_and(AuthMode::has_chatgpt_account), + ); + } + } return; } ServerNotification::ExternalAgentConfigImportCompleted(_) => { diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 451bfadc1a..7363f35a26 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -23,6 +23,7 @@ use crate::history_cell::UserHistoryCell; use crate::history_cell::new_session_info; use crate::multi_agents::AgentPickerThreadEntry; use assert_matches::assert_matches; +use base64::Engine as _; use crate::app_command::AppCommand as Op; use crate::diff_model::FileChange; @@ -30,6 +31,7 @@ use crate::legacy_core::config::ConfigBuilder; use crate::legacy_core::config::ConfigOverrides; use crate::legacy_core::config::PermissionProfileSnapshot; use crate::legacy_core::config::TerminalResizeReflowMaxRows; +use codex_app_server_protocol::AccountUpdatedNotification; use codex_app_server_protocol::AdditionalFileSystemPermissions; use codex_app_server_protocol::AdditionalNetworkPermissions; use codex_app_server_protocol::AdditionalPermissionProfile; @@ -74,6 +76,7 @@ use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput; use codex_app_server_protocol::UserInput as AppServerUserInput; use codex_app_server_protocol::WarningNotification; +use codex_config::types::AuthCredentialsStoreMode; use codex_otel::SessionTelemetry; use codex_protocol::ThreadId; use codex_protocol::config_types::CollaborationMode; @@ -113,6 +116,37 @@ fn test_absolute_path(path: &str) -> AbsolutePathBuf { AbsolutePathBuf::try_from(PathBuf::from(path)).expect("absolute test path") } +fn write_pro_chatgpt_auth(codex_home: &Path) { + let encode = |value: &serde_json::Value| { + base64::engine::general_purpose::URL_SAFE_NO_PAD + .encode(serde_json::to_vec(value).expect("serialize JWT segment")) + }; + let token = format!( + "{}.{}.sig", + encode(&serde_json::json!({"alg": "none", "typ": "JWT"})), + encode(&serde_json::json!({ + "email": "user@example.com", + "https://api.openai.com/auth": { + "chatgpt_account_id": "workspace-1", + "chatgpt_plan_type": "pro", + }, + })), + ); + let auth = serde_json::json!({ + "tokens": { + "id_token": token, + "access_token": "test-access-token", + "refresh_token": "test-refresh-token", + "account_id": "workspace-1", + }, + }); + std::fs::write( + codex_home.join("auth.json"), + serde_json::to_vec_pretty(&auth).expect("serialize auth.json"), + ) + .expect("write auth.json"); +} + async fn next_thread_settings_updated( app_server: &mut AppServerSession, thread_id: ThreadId, @@ -3352,6 +3386,62 @@ async fn side_thread_snapshot_skips_session_header_preamble() { ); } +#[tokio::test] +async fn account_updated_reads_canonical_account_for_status() { + let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; + while app_event_rx.try_recv().is_ok() {} + app.config.cli_auth_credentials_store_mode = AuthCredentialsStoreMode::File; + write_pro_chatgpt_auth(app.config.codex_home.as_path()); + let app_server = crate::start_embedded_app_server_for_picker(&app.config) + .await + .expect("embedded app server"); + app.chat_widget.update_account_state( + Some(crate::status::StatusAccountDisplay::ChatGpt { + email: Some("user@example.com".to_string()), + plan: Some("Free".to_string()), + }), + Some(codex_protocol::account::PlanType::Free), + /*has_chatgpt_account*/ true, + ); + + app.handle_app_server_event( + &app_server, + codex_app_server_client::AppServerEvent::ServerNotification( + ServerNotification::AccountUpdated(AccountUpdatedNotification { + auth_mode: Some(codex_app_server_protocol::AuthMode::Chatgpt), + plan_type: Some(codex_protocol::account::PlanType::Pro), + }), + ), + ) + .await; + + match app.chat_widget.status_account_display() { + Some(crate::status::StatusAccountDisplay::ChatGpt { email, plan }) => { + assert_eq!(email.as_deref(), Some("user@example.com")); + assert_eq!(plan.as_deref(), Some("Pro")); + } + other => panic!("expected ChatGPT account display, got {other:?}"), + } + assert_eq!( + app.chat_widget.current_plan_type(), + Some(codex_protocol::account::PlanType::Pro) + ); + + app.chat_widget.add_status_output( + /*refreshing_rate_limits*/ false, /*request_id*/ None, + ); + let rendered = match app_event_rx.try_recv() { + Ok(AppEvent::InsertHistoryCell(cell)) => { + lines_to_single_string(&cell.display_lines(/*width*/ 80)) + } + other => panic!("expected status output, got {other:?}"), + }; + assert!( + rendered.contains("user@example.com (Pro)"), + "expected canonical account/read state in /status, got: {rendered}" + ); +} + #[tokio::test] async fn primary_thread_ignores_child_mcp_startup_notifications() { let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; diff --git a/codex-rs/tui/src/chatwidget/rate_limits.rs b/codex-rs/tui/src/chatwidget/rate_limits.rs index efb0b63628..ab538a2c08 100644 --- a/codex-rs/tui/src/chatwidget/rate_limits.rs +++ b/codex-rs/tui/src/chatwidget/rate_limits.rs @@ -201,8 +201,6 @@ impl ChatWidget { } else { None }; - self.plan_type = snapshot.plan_type.or(self.plan_type); - let is_codex_limit = limit_id.eq_ignore_ascii_case("codex"); if is_codex_limit && let Some(rate_limit_reached_type) = snapshot.rate_limit_reached_type diff --git a/codex-rs/tui/src/chatwidget/status_controls.rs b/codex-rs/tui/src/chatwidget/status_controls.rs index d4de738314..f6903add04 100644 --- a/codex-rs/tui/src/chatwidget/status_controls.rs +++ b/codex-rs/tui/src/chatwidget/status_controls.rs @@ -263,7 +263,11 @@ impl ChatWidget { for (pending_request_id, handle) in self.refreshing_status_outputs.drain(..) { if pending_request_id == request_id { updated_any = true; - handle.finish_rate_limit_refresh(rate_limit_snapshots.as_slice(), now); + handle.finish_rate_limit_refresh( + rate_limit_snapshots.as_slice(), + self.plan_type, + now, + ); } else { remaining.push((pending_request_id, handle)); } diff --git a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs index 3d08daa427..4fea08d341 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs @@ -837,8 +837,13 @@ async fn rolling_rate_limit_snapshot_preserves_prior_individual_limit() { } #[tokio::test] -async fn rate_limit_snapshot_updates_and_retains_plan_type() { +async fn rate_limit_snapshots_do_not_override_account_plan() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.update_account_state( + /*status_account_display*/ None, + Some(PlanType::Pro), + /*has_chatgpt_account*/ true, + ); chat.on_rate_limit_snapshot(Some(RateLimitSnapshot { limit_id: None, @@ -855,10 +860,10 @@ async fn rate_limit_snapshot_updates_and_retains_plan_type() { }), credits: None, individual_limit: None, - plan_type: Some(PlanType::Plus), + plan_type: Some(PlanType::Free), rate_limit_reached_type: None, })); - assert_eq!(chat.plan_type, Some(PlanType::Plus)); + assert_eq!(chat.plan_type, Some(PlanType::Pro)); chat.on_rate_limit_snapshot(Some(RateLimitSnapshot { limit_id: None, @@ -875,29 +880,21 @@ async fn rate_limit_snapshot_updates_and_retains_plan_type() { }), credits: None, individual_limit: None, - plan_type: Some(PlanType::Pro), + plan_type: None, rate_limit_reached_type: None, })); assert_eq!(chat.plan_type, Some(PlanType::Pro)); - chat.on_rate_limit_snapshot(Some(RateLimitSnapshot { + chat.on_rolling_rate_limit_snapshot(RateLimitSnapshot { limit_id: None, limit_name: None, - primary: Some(RateLimitWindow { - used_percent: 30, - window_duration_mins: Some(60), - resets_at: Some(456), - }), - secondary: Some(RateLimitWindow { - used_percent: 18, - window_duration_mins: Some(300), - resets_at: Some(567), - }), + primary: None, + secondary: None, credits: None, individual_limit: None, - plan_type: None, + plan_type: Some(PlanType::Free), rate_limit_reached_type: None, - })); + }); assert_eq!(chat.plan_type, Some(PlanType::Pro)); } diff --git a/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs b/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs index c206313549..44de62c794 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs @@ -1,5 +1,7 @@ use super::*; +use crate::status::StatusAccountDisplay; use assert_matches::assert_matches; +use codex_protocol::account::PlanType; #[tokio::test] async fn status_command_renders_immediately_and_refreshes_rate_limits_for_chatgpt_auth() { @@ -28,16 +30,26 @@ async fn status_command_renders_immediately_and_refreshes_rate_limits_for_chatgp } #[tokio::test] -async fn status_command_refresh_updates_cached_limits_for_future_status_outputs() { +async fn status_command_refresh_updates_existing_and_future_status_outputs() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; set_chatgpt_auth(&mut chat); + chat.status_account_display = Some(StatusAccountDisplay::ChatGpt { + email: Some("user@example.com".to_string()), + plan: Some("Free".to_string()), + }); + chat.plan_type = Some(PlanType::Free); chat.dispatch_command(SlashCommand::Status); - match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(_)) => {} + let status_cell = match rx.try_recv() { + Ok(AppEvent::InsertHistoryCell(cell)) => cell, other => panic!("expected status output before refresh request, got {other:?}"), - } + }; + let initial = lines_to_single_string(&status_cell.display_lines(/*width*/ 80)); + assert!( + initial.contains("user@example.com (Free)"), + "expected initial /status output to use the reconciled account plan, got: {initial}" + ); let first_request_id = match rx.try_recv() { Ok(AppEvent::RefreshRateLimits { origin: RateLimitRefreshOrigin::StatusCommand { request_id }, @@ -45,10 +57,30 @@ async fn status_command_refresh_updates_cached_limits_for_future_status_outputs( other => panic!("expected rate-limit refresh request, got {other:?}"), }; - chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 92.0))); + let mut usage_snapshot = snapshot(/*percent*/ 92.0); + usage_snapshot.plan_type = Some(PlanType::Pro); + chat.update_account_state( + Some(StatusAccountDisplay::ChatGpt { + email: Some("user@example.com".to_string()), + plan: Some("Pro".to_string()), + }), + Some(PlanType::Pro), + /*has_chatgpt_account*/ true, + ); + chat.on_rate_limit_snapshot(Some(usage_snapshot)); chat.finish_status_rate_limit_refresh(first_request_id); drain_insert_history(&mut rx); + let refreshed_existing = lines_to_single_string(&status_cell.display_lines(/*width*/ 80)); + assert!( + refreshed_existing.contains("8% left"), + "expected the existing /status output to use refreshed limits, got: {refreshed_existing}" + ); + assert!( + refreshed_existing.contains("user@example.com (Pro)"), + "expected the existing /status output to use the plan from /usage, got: {refreshed_existing}" + ); + chat.dispatch_command(SlashCommand::Status); let refreshed = match rx.try_recv() { Ok(AppEvent::InsertHistoryCell(cell)) => { @@ -60,6 +92,10 @@ async fn status_command_refresh_updates_cached_limits_for_future_status_outputs( refreshed.contains("8% left"), "expected a future /status output to use refreshed cached limits, got: {refreshed}" ); + assert!( + refreshed.contains("user@example.com (Pro)"), + "expected a future /status output to use the plan from /usage, got: {refreshed}" + ); } #[tokio::test] diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index 61ffd3da7d..7aab4956fa 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -38,6 +38,7 @@ use super::helpers::compose_account_display; use super::helpers::compose_model_display; use super::helpers::format_directory_display; use super::helpers::format_tokens_compact; +use super::helpers::plan_type_display_name; use super::rate_limits::RateLimitSnapshotDisplay; use super::rate_limits::StatusRateLimitData; use super::rate_limits::StatusRateLimitRow; @@ -74,6 +75,7 @@ pub(crate) struct StatusTokenUsageData { struct StatusRateLimitState { rate_limits: StatusRateLimitData, refreshing_rate_limits: bool, + plan_type: Option, } #[derive(Debug, Clone)] @@ -85,6 +87,7 @@ impl StatusHistoryHandle { pub(crate) fn finish_rate_limit_refresh( &self, rate_limits: &[RateLimitSnapshotDisplay], + plan_type: Option, now: DateTime, ) { let rate_limits = if rate_limits.len() <= 1 { @@ -99,6 +102,7 @@ impl StatusHistoryHandle { .expect("status history rate-limit state poisoned"); state.rate_limits = rate_limits; state.refreshing_rate_limits = false; + state.plan_type = plan_type.or(state.plan_type); } } @@ -209,7 +213,7 @@ pub(crate) fn new_status_output_with_rate_limits_handle( thread_name: Option, forked_from: Option, rate_limits: &[RateLimitSnapshotDisplay], - _plan_type: Option, + plan_type: Option, now: DateTime, model_name: &str, collaboration_mode: Option<&str>, @@ -229,7 +233,7 @@ pub(crate) fn new_status_output_with_rate_limits_handle( thread_name, forked_from, rate_limits, - _plan_type, + plan_type, now, model_name, collaboration_mode, @@ -257,7 +261,7 @@ impl StatusHistoryCell { thread_name: Option, forked_from: Option, rate_limits: &[RateLimitSnapshotDisplay], - _plan_type: Option, + plan_type: Option, now: DateTime, model_name: &str, collaboration_mode: Option<&str>, @@ -348,6 +352,7 @@ impl StatusHistoryCell { let rate_limit_state = Arc::new(RwLock::new(StatusRateLimitState { rate_limits, refreshing_rate_limits, + plan_type, })); let agents_summary = Arc::new(RwLock::new(agents_summary)); @@ -720,13 +725,24 @@ impl HistoryCell for StatusHistoryCell { return Vec::new(); } + #[expect(clippy::expect_used)] + let rate_limit_state = self + .rate_limit_state + .read() + .expect("status history rate-limit state poisoned"); let account_value = self.account.as_ref().map(|account| match account { - StatusAccountDisplay::ChatGpt { email, plan } => match (email, plan) { - (Some(email), Some(plan)) => format!("{email} ({plan})"), - (Some(email), None) => email.clone(), - (None, Some(plan)) => plan.clone(), - (None, None) => "ChatGPT".to_string(), - }, + StatusAccountDisplay::ChatGpt { email, plan } => { + let plan = rate_limit_state + .plan_type + .map(plan_type_display_name) + .or_else(|| plan.clone()); + match (email, plan) { + (Some(email), Some(plan)) => format!("{email} ({plan})"), + (Some(email), None) => email.clone(), + (None, Some(plan)) => plan, + (None, None) => "ChatGPT".to_string(), + } + } StatusAccountDisplay::ApiKey => { "API key configured (run codex login to use ChatGPT)".to_string() } @@ -739,11 +755,6 @@ impl HistoryCell for StatusHistoryCell { let mut seen: BTreeSet = labels.iter().cloned().collect(); let thread_name = self.thread_name.as_deref().filter(|name| !name.is_empty()); #[expect(clippy::expect_used)] - let rate_limit_state = self - .rate_limit_state - .read() - .expect("status history rate-limit state poisoned"); - #[expect(clippy::expect_used)] let agents_summary = self .agents_summary .read()