diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs index 0c4e827187..f4f0b5c86e 100644 --- a/codex-rs/tui/src/app/config_persistence.rs +++ b/codex-rs/tui/src/app/config_persistence.rs @@ -6,6 +6,7 @@ use super::*; use codex_config::ConfigLayerSource; +use futures::TryFutureExt; async fn build_config_on_runtime_worker( builder: ConfigBuilder, @@ -127,11 +128,21 @@ impl App { .harness_overrides(overrides) .loader_overrides(self.loader_overrides.clone()) .cloud_config_bundle(self.cloud_config_bundle.clone()); + // Reloading client preferences must not replace the remote server's provider definitions. + let remote_providers = target + .uses_remote_workspace() + .then(|| base.model_providers.clone()); build_config_on_runtime_worker( builder, base.application_network_policy.clone(), format!("Failed to rebuild config for cwd {cwd_display}"), ) + .map_ok(move |mut config| { + if let Some(providers) = remote_providers { + config.model_providers = providers; + } + config + }) } #[cfg(test)] diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 99d80527b1..7ac5fc0219 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -2341,7 +2341,7 @@ impl App { match result { Ok(response) => { let rate_limit_reset_credits = response.rate_limit_reset_credits.clone(); - let snapshots = if accepted + let snapshots = if accepted && self.chat_widget.uses_account_quota() { self.chat_widget.apply_usage_notice_read(request_id); self.chat_widget.update_backend_banner(&response); diff --git a/codex-rs/tui/src/app/new_session.rs b/codex-rs/tui/src/app/new_session.rs index 9d10cb39d8..b46d3a9831 100644 --- a/codex-rs/tui/src/app/new_session.rs +++ b/codex-rs/tui/src/app/new_session.rs @@ -39,6 +39,13 @@ pub(super) fn overlay_reasoning_summary( if !has_launch_setting(config, cli_kv_overrides, "model_reasoning_summary") { config.model_reasoning_summary = defaults.model_reasoning_summary; } + overlay_model_providers(config, defaults); +} + +pub(super) fn overlay_model_providers( + config: &mut Config, + defaults: &codex_app_server_protocol::Config, +) { if let Some(providers) = defaults .additional .get("model_providers") diff --git a/codex-rs/tui/src/app/resume_preparation.rs b/codex-rs/tui/src/app/resume_preparation.rs index 6cc5d8f81c..a7f00d5295 100644 --- a/codex-rs/tui/src/app/resume_preparation.rs +++ b/codex-rs/tui/src/app/resume_preparation.rs @@ -553,6 +553,25 @@ impl App { return Err(AppRunControl::Continue); } }; + let provider = &resumed.session.model_provider_id; + if !restored_blank_session + && app_server.thread_params_mode() == crate::ThreadParamsMode::Remote + && !codex_model_provider_info::built_in_model_providers(/*openai_base_url*/ None) + .contains_key(provider) + { + // The server may have changed credentials under the same ID since the last chat. + // Without a current definition, this chat can only use turn-derived quota. + resume_config.model_providers.remove(provider); + if let Ok(defaults) = crate::config_update::read_effective_config_with_optional_layers( + &app_server.request_handle(), + resumed.session.cwd.inferred_native_path_string(), + /*include_layers*/ false, + ) + .await + { + super::new_session::overlay_model_providers(&mut resume_config, &defaults.config); + } + } Ok(PreparedResume { backend_id: app_server.backend_id(), config: resume_config, diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 2d22e654fd..8134b0e713 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -652,8 +652,11 @@ impl App { self.chat_widget.windows_sandbox_elevated_setup_complete; } // Different providers can report identical account details. - let provider_changed = thread_provider - .is_some_and(|provider| provider != self.chat_widget.quota_provider_id()); + let provider_changed = thread_provider.is_some_and(|provider| { + provider != self.chat_widget.quota_provider_id() + || chat_widget.config_ref().model_providers.get(provider) + != self.chat_widget.config_ref().model_providers.get(provider) + }); let lost_chatgpt_account = self.chat_widget.has_chatgpt_account() && !chat_widget.has_chatgpt_account(); if provider_changed || lost_chatgpt_account { diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index 6b44313ab5..e64650b5cb 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -1369,6 +1369,8 @@ See the Codex keymap documentation for supported actions and examples." app.app_event_tx.clone(), app.chat_widget.security_setup_request_id, ); + } + if app.chat_widget.should_prefetch_rate_limits() { let reset_hint_request_id = app.chat_widget.start_rate_limit_reset_startup_check(); app.refresh_rate_limits( &app_server, diff --git a/codex-rs/tui/src/app/tests/backend_banner_recovery_tests.rs b/codex-rs/tui/src/app/tests/backend_banner_recovery_tests.rs index fd6112680b..47f3f6898a 100644 --- a/codex-rs/tui/src/app/tests/backend_banner_recovery_tests.rs +++ b/codex-rs/tui/src/app/tests/backend_banner_recovery_tests.rs @@ -26,7 +26,19 @@ fn response_with_banner() -> GetAccountRateLimitsResponse { })).unwrap() } -async fn next_rate_limits_loaded( +pub(super) fn mock_account_usage(used: u32) -> Mock { + Mock::given(method("GET")) + .and(path("/api/codex/usage")) + .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ + "account_id": "workspace-a", "user_id": "user-a", "plan_type": "plus", + "rate_limit": {"allowed": true, "limit_reached": false, + "primary_window": {"used_percent": used, "limit_window_seconds": 18000, + "reset_after_seconds": 1800, "reset_at": 2000000000}}, + "rate_limit_reset_credits": {"available_count": 1} + }))) +} + +pub(super) async fn next_rate_limits_loaded( events: &mut tokio::sync::mpsc::UnboundedReceiver, ) -> Result { Ok( @@ -135,15 +147,7 @@ async fn luna_reserve_periodic_refresh_adapts_without_an_experiment_banner() -> let mut tui = crate::tui::test_support::make_test_tui()?; for (used, seconds) in [(10, 60), (75, 30), (90, 15), (99, 5), (20, 60)] { backend.reset().await; - Mock::given(method("GET")) - .and(path("/api/codex/usage")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "account_id": "workspace-a", "user_id": "user-a", "plan_type": "plus", - "rate_limit": {"allowed": true, "limit_reached": false, - "primary_window": {"used_percent": used, "limit_window_seconds": 18000, - "reset_after_seconds": 1800, "reset_at": 2000000000}}, - "rate_limit_reset_credits": {"available_count": 1} - }))) + mock_account_usage(used) .expect(/*r*/ 1) .mount(&backend) .await; diff --git a/codex-rs/tui/src/app/tests/new_session_tests.rs b/codex-rs/tui/src/app/tests/new_session_tests.rs index 7d8e0cc373..98c4068f7b 100644 --- a/codex-rs/tui/src/app/tests/new_session_tests.rs +++ b/codex-rs/tui/src/app/tests/new_session_tests.rs @@ -17,8 +17,8 @@ use crossterm::event::KeyModifiers; use pretty_assertions::assert_eq; #[tokio::test] -async fn new_session_refreshes_account_for_the_started_provider() -> Result<()> { - let (mut app, _events, _ops) = make_test_app_with_channels().await; +async fn new_and_resumed_sessions_use_quota_for_the_active_provider() -> Result<()> { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; crate::chatwidget::tests::helpers::set_fast_mode_test_catalog_for_models( &mut app.chat_widget, "gpt-5.5", @@ -47,7 +47,7 @@ async fn new_session_refreshes_account_for_the_started_provider() -> Result<()> std::fs::write( home.path().join("config.toml"), format!( - "model_provider = 'amazon-bedrock'\nmodel = 'gpt-5.5'\ncli_auth_credentials_store = 'file'\nchatgpt_base_url = {:?}\nmodel_catalog_json = {catalog_path:?}\nfeatures.apps = true\n\n[model_providers.alt]\nname = 'Alt'\nwire_api = 'responses'\nrequires_openai_auth = true\n", + "model_provider = 'amazon-bedrock'\nmodel = 'gpt-5.5'\ncli_auth_credentials_store = 'file'\nchatgpt_base_url = {:?}\nmodel_catalog_json = {catalog_path:?}\nfeatures.apps = true\n\n[model_providers.alt]\nname = 'Alt'\nwire_api = 'responses'\nrequires_openai_auth = true\n\n[model_providers.custom]\nname = 'Custom'\nrequires_openai_auth = false\n", backend.uri(), ), )?; @@ -58,12 +58,25 @@ async fn new_session_refreshes_account_for_the_started_provider() -> Result<()> endpoint: crate::resolve_remote_addr("ws://127.0.0.1:4500")?, }; let mut tui = crate::tui::test_support::make_test_tui()?; - for provider in [ - "amazon-bedrock", - "openai", - "alt", - "openai", - "amazon-bedrock", + super::backend_banner_recovery_tests::mock_account_usage(/*used*/ 91) + .expect(/*r*/ 5) + .mount(&backend) + .await; + for (provider, saved_providers) in [ + ("amazon-bedrock", &[][..]), + ("openai", &[]), + ("alt", &[]), + ( + "openai", + &[ + ("custom", false), + ("alt", true), + ("alt", false), + ("openai", true), + ], + ), + ("amazon-bedrock", &[]), + ("custom", &[("openai", true)]), ] { if app.chat_widget.config_ref().model_provider_id == "alt" { // The task list uses the client default, which is also the next provider. @@ -160,6 +173,44 @@ async fn new_session_refreshes_account_for_the_started_provider() -> Result<()> chatgpt.then_some(codex_protocol::account::PlanType::Pro) ) ); + // Resume saved chats without changing the server default or its login. + for &(provider, shares_quota) in saved_providers { + if provider == "alt" && !shares_quota { + crate::config_update::write_config_batch( + server.request_handle(), + vec![crate::config_update::replace_config_value( + "model_providers.alt.requires_openai_auth", + false.into(), + )], + ) + .await?; + } + server_config.model_provider_id = provider.into(); + let id = + create_history_rollout(&server_config, ThreadHistoryMode::Legacy, "Saved chat")?; + let resume = AppEvent::ResumeSessionByIdOrName(id.to_string()); + Box::pin(app.handle_event(&mut tui, &mut server, resume)).await?; + app.drain_active_thread_events(&mut tui).await?; + assert_eq!(app.chat_widget.quota_provider_id(), provider); + assert_eq!(app.chat_widget.has_chatgpt_account(), chatgpt); + assert_eq!( + app.chat_widget.rate_limit_refresh_interval().is_some(), + chatgpt && shares_quota + ); + + // An explicit /usage read can complete even when automatic polling is off. + let origin = RateLimitRefreshOrigin::ResetPicker { + request_id: app.chat_widget.show_rate_limit_reset_loading_popup(), + }; + app.refresh_rate_limits(&server, origin); + let read = + super::backend_banner_recovery_tests::next_rate_limits_loaded(&mut events).await?; + Box::pin(app.handle_event(&mut tui, &mut server, read)).await?; + assert_eq!( + app.chat_widget.usage_notice(/*width*/ 100).is_some(), + shares_quota + ); + } } server.shutdown().await?; proxy.await??; diff --git a/codex-rs/tui/src/app/tests/rate_limits.rs b/codex-rs/tui/src/app/tests/rate_limits.rs index 6b886f2a2e..785de67fdb 100644 --- a/codex-rs/tui/src/app/tests/rate_limits.rs +++ b/codex-rs/tui/src/app/tests/rate_limits.rs @@ -184,11 +184,10 @@ async fn accepted_rate_limit_read_updates_billing_after_its_status_card_is_gone( replacement.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".into()]); app.replace_chat_widget(ChatWidget::new_with_app_event(replacement)); let thread = ThreadId::new(); - app.enqueue_primary_thread_session( - test_thread_session(thread, app.config.cwd.to_path_buf()), - Vec::new(), - ) - .await?; + let mut session = test_thread_session(thread, app.config.cwd.to_path_buf()); + session.model_provider_id = "openai".into(); + app.enqueue_primary_thread_session(session, Vec::new()) + .await?; app.drain_active_thread_events(&mut tui).await?; while events.try_recv().is_ok() {} diff --git a/codex-rs/tui/src/chatwidget/rate_limits.rs b/codex-rs/tui/src/chatwidget/rate_limits.rs index 5d400eaa04..3b431f95f3 100644 --- a/codex-rs/tui/src/chatwidget/rate_limits.rs +++ b/codex-rs/tui/src/chatwidget/rate_limits.rs @@ -5,6 +5,7 @@ pub(super) const WORKSPACE_NUDGE_VIEW_ID: &str = "workspace-usage-nudge"; use crate::bottom_pane::ActionableBanner; use crate::model_catalog::LUNA_RESERVE_MODEL; use codex_app_server_protocol::CodexErrorInfo as AppServerCodexErrorInfo; +use codex_model_provider_info::OPENAI_PROVIDER_ID; use uuid::Uuid; pub(super) struct PendingCreditsNudge { @@ -65,7 +66,7 @@ impl RateLimitWarningState { limit_label_for_window(secondary_window_minutes, /*is_secondary*/ true); let remaining_percent = 100.0 - threshold; warnings.push(format!( - "Heads up, you have less than {remaining_percent:.0}% of your {limit_label} limit left. Run /status for a breakdown." + "Heads up, you have less than {remaining_percent:.0}% of your {limit_label} limit left." )); } } @@ -91,7 +92,7 @@ impl RateLimitWarningState { limit_label_for_window(primary_window_minutes, /*is_secondary*/ false); let remaining_percent = 100.0 - threshold; warnings.push(format!( - "Heads up, you have less than {remaining_percent:.0}% of your {limit_label} limit left. Run /status for a breakdown." + "Heads up, you have less than {remaining_percent:.0}% of your {limit_label} limit left." )); } } @@ -193,6 +194,7 @@ pub(super) fn is_app_server_cyber_policy_error(info: &AppServerCodexErrorInfo) - pub(super) enum RateLimitSnapshotSource { AccountUsage, RollingUpdate, + ProviderTurn, } fn has_usable_workspace_credits(credits: &CreditsSnapshot) -> bool { @@ -289,7 +291,12 @@ impl ChatWidget { self.clear_backend_banner(); } // Rolling app-server notifications are sparse. Preserve metadata learned from the full read. - self.on_rate_limit_snapshot_from(Some(snapshot), RateLimitSnapshotSource::RollingUpdate); + let source = if self.uses_account_quota() { + RateLimitSnapshotSource::RollingUpdate + } else { + RateLimitSnapshotSource::ProviderTurn + }; + self.on_rate_limit_snapshot_from(Some(snapshot), source); } fn on_rate_limit_snapshot_from( @@ -408,6 +415,7 @@ impl ChatWidget { if used_percent.is_some_and(|used| used >= RATE_LIMIT_SWITCH_PROMPT_THRESHOLD) && should_warn_about_rate_limit_usage + && self.quota_provider_id() == OPENAI_PROVIDER_ID && !self.rate_limit_switch_prompt_hidden() && self.current_model() != NUDGE_MODEL_SLUG && matches!( @@ -436,7 +444,10 @@ impl ChatWidget { } if !warnings.is_empty() { - for warning in warnings { + for mut warning in warnings { + if !matches!(source, RateLimitSnapshotSource::ProviderTurn) { + warning.push_str(" Run /status for a breakdown."); + } self.add_to_history(history_cell::new_visible_warning_event(warning)); } self.request_redraw(); @@ -457,9 +468,20 @@ impl ChatWidget { self.refresh_status_line(); } - #[cfg_attr(not(test), allow(dead_code))] - pub(super) fn should_prefetch_rate_limits(&self) -> bool { - self.requires_openai_auth && self.has_chatgpt_account + pub(crate) fn uses_account_quota(&self) -> bool { + if self.thread_params_mode == crate::ThreadParamsMode::Cloud { + return self.requires_openai_auth; + } + // The server authenticated the quota read, but its default provider may differ + // from the one serving this thread. + self.config + .model_providers + .get(self.quota_provider_id()) + .is_some_and(codex_model_provider::provider_uses_first_party_auth_path) + } + + pub(crate) fn should_prefetch_rate_limits(&self) -> bool { + self.requires_openai_auth && self.has_chatgpt_account && self.uses_account_quota() } fn lower_cost_preset(&self) -> Option { 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 521c505082..0e57864746 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs @@ -840,18 +840,10 @@ async fn rate_limit_warnings_emit_thresholds() { assert_eq!( warnings, vec![ - String::from( - "Heads up, you have less than 25% of your 5h limit left. Run /status for a breakdown." - ), - String::from( - "Heads up, you have less than 25% of your weekly limit left. Run /status for a breakdown.", - ), - String::from( - "Heads up, you have less than 5% of your 5h limit left. Run /status for a breakdown." - ), - String::from( - "Heads up, you have less than 5% of your weekly limit left. Run /status for a breakdown.", - ), + String::from("Heads up, you have less than 25% of your 5h limit left."), + String::from("Heads up, you have less than 25% of your weekly limit left.",), + String::from("Heads up, you have less than 5% of your 5h limit left."), + String::from("Heads up, you have less than 5% of your weekly limit left.",), ], "expected one warning per limit for the highest crossed threshold" ); @@ -918,7 +910,7 @@ async fn test_rate_limit_warnings_monthly() { assert_eq!( warnings, vec![String::from( - "Heads up, you have less than 25% of your monthly limit left. Run /status for a breakdown.", + "Heads up, you have less than 25% of your monthly limit left.", ),], "expected one warning per limit for the highest crossed threshold" ); @@ -947,12 +939,8 @@ async fn test_rate_limit_warnings_use_generic_fallback_labels() { /*primary_window_minutes*/ None, ), vec![ - String::from( - "Heads up, you have less than 25% of your secondary usage limit left. Run /status for a breakdown.", - ), - String::from( - "Heads up, you have less than 25% of your usage limit left. Run /status for a breakdown.", - ), + String::from("Heads up, you have less than 25% of your secondary usage limit left.",), + String::from("Heads up, you have less than 25% of your usage limit left.",), ], ); } @@ -970,7 +958,7 @@ async fn test_rate_limit_warnings_use_secondary_fallback_for_unsupported_window( /*primary_window_minutes*/ None, ), vec![String::from( - "Heads up, you have less than 25% of your secondary usage limit left. Run /status for a breakdown.", + "Heads up, you have less than 25% of your secondary usage limit left.", )], ); } @@ -1430,6 +1418,39 @@ async fn rate_limit_switch_prompt_skips_when_on_lower_cost_model() { )); } +#[tokio::test] +async fn custom_provider_warns_from_turn_without_rate_limit_switch_prompt() { + let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await; + chat.config.model_provider_id = "custom".into(); + chat.requires_openai_auth = false; + let mut usage = snapshot(/*percent*/ 96.0); + usage.primary.as_mut().unwrap().window_duration_mins = Some(10080); + chat.on_rolling_rate_limit_snapshot(usage.clone()); + + let warnings = drain_insert_history_transcript(&mut rx); + insta::assert_snapshot!(lines_to_single_string(&warnings.concat()), @r" + ⚠ Heads up, you have less than 5% of your weekly limit left. + "); + assert!(matches!( + chat.rate_limit_switch_prompt, + RateLimitSwitchPromptState::Idle + )); + let notice = chat.usage_notice(/*width*/ 160).unwrap().to_string(); + insta::assert_snapshot!(notice, @"⚠ weekly limit: only 4% left"); + + let mut sparse = snapshot(/*percent*/ 10.0); + sparse.secondary = sparse.primary.take(); + chat.on_rolling_rate_limit_snapshot(sparse); + assert_eq!( + chat.usage_notice(/*width*/ 160).unwrap().to_string(), + notice + ); + + usage.primary.as_mut().unwrap().used_percent = 10; + chat.on_rolling_rate_limit_snapshot(usage); + assert!(chat.usage_notice(/*width*/ 160).is_none()); +} + #[tokio::test] async fn rate_limit_switch_prompt_skips_non_codex_limit() { let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await; diff --git a/codex-rs/tui/src/chatwidget/usage_notice.rs b/codex-rs/tui/src/chatwidget/usage_notice.rs index 698a3e2bcc..28ddf71ed3 100644 --- a/codex-rs/tui/src/chatwidget/usage_notice.rs +++ b/codex-rs/tui/src/chatwidget/usage_notice.rs @@ -1,5 +1,5 @@ //! Account quota state and composer notice, independent of one-time warning history. -//! Rolling updates retain metadata; fresh account reads replace windows and confirm recovery. +//! Sparse turns retain omitted windows. For independent providers they also confirm recovery. //! Details target half the composer gap; the shortest notice may use its full width. use super::ChatWidget; @@ -22,6 +22,7 @@ pub(super) struct UsageNoticeState { secondary: Option, plan_type: Option, credits: Option, + turn_only: bool, latest_read_id: u64, stale_through: Option, pub(super) applying_stale_read: bool, @@ -72,10 +73,11 @@ impl UsageNoticeState { let notice_width = (usize::from(width) / 2) .max(compact.width()) .min(usize::from(width)) as u16; + let hint = if self.turn_only { "" } else { " · /status" }; let line = first_fitting_line( [ - Line::from(format!("{summary}{reset} · /status")), - Line::from(format!("{summary} · /status")), + Line::from(format!("{summary}{reset}{hint}")), + Line::from(format!("{summary}{hint}")), Line::from(summary), compact, ], @@ -94,7 +96,8 @@ impl UsageNoticeState { return false; } let previous = self.current(); - let rolling = matches!(source, RateLimitSnapshotSource::RollingUpdate); + self.turn_only = matches!(source, RateLimitSnapshotSource::ProviderTurn); + let rolling = !matches!(source, RateLimitSnapshotSource::AccountUsage); if rolling { self.stale_through = Some(self.latest_read_id); } @@ -117,7 +120,10 @@ impl UsageNoticeState { .or(previous.window_duration_mins); window.resets_at = window.resets_at.or(previous.resets_at); let threshold = warning_threshold(self.plan_type, window.window_duration_mins); - if previous.used_percent >= threshold && window.used_percent < threshold { + if !self.turn_only + && previous.used_percent >= threshold + && window.used_percent < threshold + { continue; } }