mirror of
https://github.com/openai/codex.git
synced 2026-11-17 22:10:37 +00:00
Keep TUI quota state scoped to the active provider (#61977)
## Why Starting or switching chats can carry quota usage, backend banners, and pending recovery from the previous provider, even when both providers report identical account details. ## What changed - Refresh account state when the started or cached thread uses a different provider, and discard inherited quota and backend banner state across provider changes. - Track the provider associated with quota inherited by the task list, where the local default can differ from the previous chat's provider. - Invalidate pending recovery when the provider changes or the chat loses its ChatGPT account, and ignore queued recovery refreshes without a ChatGPT account. - Preserve quota state and pending recovery when opening another chat on the same provider. ## Testing Add regression coverage for provider changes with matching account details, stale recovery replies, cached side chats, and quota and recovery preservation across `/new` and task list transitions. GitOrigin-RevId: f4513ca565f2068489327989ae10b24cada0a9bf
This commit is contained in:
@@ -551,6 +551,7 @@ impl App {
|
||||
self.feedback_audience = bootstrap.feedback_audience;
|
||||
self.chat_widget.requires_openai_auth = bootstrap.requires_openai_auth;
|
||||
self.chat_widget.invalidate_security_setup();
|
||||
self.chat_widget.forget_inherited_quota_provider();
|
||||
self.chat_widget.update_account_state(
|
||||
bootstrap.status_account_display,
|
||||
bootstrap.plan_type,
|
||||
|
||||
@@ -2111,7 +2111,12 @@ impl App {
|
||||
}
|
||||
}
|
||||
AppEvent::RefreshRateLimits { origin } => {
|
||||
self.refresh_rate_limits(app_server, origin);
|
||||
// A queued recovery can outlive the chat's ChatGPT account.
|
||||
if origin != RateLimitRefreshOrigin::Recovery
|
||||
|| self.chat_widget.has_chatgpt_account()
|
||||
{
|
||||
self.refresh_rate_limits(app_server, origin);
|
||||
}
|
||||
}
|
||||
AppEvent::ApplyBackendBannerFallback { thread_id } => {
|
||||
if self.active_thread_id == Some(thread_id)
|
||||
|
||||
@@ -581,9 +581,12 @@ impl App {
|
||||
self.active_thread_id = Some(id);
|
||||
self.active_thread_rx = Some(receiver);
|
||||
self.recap.seed_from_turns(&snapshot.turns, Instant::now());
|
||||
if let Err(err) = self.render_thread_snapshot(
|
||||
tui, app_server, id, snapshot, /*resume_restored_queue*/ false,
|
||||
) {
|
||||
if let Err(err) = self
|
||||
.render_thread_snapshot(
|
||||
tui, app_server, id, snapshot, /*resume_restored_queue*/ false,
|
||||
)
|
||||
.await
|
||||
{
|
||||
if discard_replaced_view_input
|
||||
&& let Err(drain_err) = tui.discard_pending_input_before_interactive_screen()
|
||||
{
|
||||
@@ -647,6 +650,7 @@ impl App {
|
||||
if self.reconnect.presentation == ReconnectPresentation::Overview {
|
||||
self.refresh_agents_overview_threads(app_server);
|
||||
}
|
||||
self.chat_widget.forget_inherited_quota_provider();
|
||||
self.chat_widget.update_account_state(
|
||||
bootstrap.status_account_display,
|
||||
bootstrap.plan_type,
|
||||
|
||||
@@ -564,7 +564,15 @@ impl App {
|
||||
/// Thread switches reconstruct the `ChatWidget`, which loses the `collab_agent_metadata` map.
|
||||
/// This helper copies every known nickname/role from `AgentNavigationState` into the
|
||||
/// replacement widget so that replayed collab items render agent names immediately.
|
||||
pub(super) fn replace_chat_widget(&mut self, mut chat_widget: ChatWidget) {
|
||||
pub(super) fn replace_chat_widget(&mut self, chat_widget: ChatWidget) {
|
||||
self.replace_chat_widget_for_provider(chat_widget, /*thread_provider*/ None);
|
||||
}
|
||||
|
||||
fn replace_chat_widget_for_provider(
|
||||
&mut self,
|
||||
mut chat_widget: ChatWidget,
|
||||
thread_provider: Option<&str>,
|
||||
) {
|
||||
chat_widget.inherit_view_transition_key_guard(&mut self.chat_widget);
|
||||
chat_widget.fork_in_progress = self.chat_widget.fork_in_progress;
|
||||
self.pending_right_click_paste = None;
|
||||
@@ -597,10 +605,24 @@ impl App {
|
||||
chat_widget.windows_sandbox_elevated_setup_complete =
|
||||
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 lost_chatgpt_account =
|
||||
self.chat_widget.has_chatgpt_account() && !chat_widget.has_chatgpt_account();
|
||||
if provider_changed || lost_chatgpt_account {
|
||||
self.rate_limit_hard_stop_generation =
|
||||
self.rate_limit_hard_stop_generation.wrapping_add(1);
|
||||
self.rate_limit_refresh_state.invalidate_recovery();
|
||||
} else if self.rate_limit_refresh_state.has_pending_recovery() {
|
||||
chat_widget.hold_rate_limit_recovery();
|
||||
}
|
||||
if chat_widget.status_account_display() == self.chat_widget.status_account_display()
|
||||
&& chat_widget.has_chatgpt_account() == self.chat_widget.has_chatgpt_account()
|
||||
{
|
||||
chat_widget.inherit_backend_banner_state(&mut self.chat_widget);
|
||||
if !provider_changed {
|
||||
chat_widget.inherit_backend_banner_state(&mut self.chat_widget);
|
||||
}
|
||||
chat_widget.inherit_security_setup(&mut self.chat_widget);
|
||||
}
|
||||
chat_widget
|
||||
@@ -867,7 +889,8 @@ impl App {
|
||||
if is_replay_only && let Some(session) = snapshot.session.as_mut() {
|
||||
session.read_only_history = true;
|
||||
}
|
||||
self.render_thread_snapshot(tui, app_server, thread_id, snapshot, !is_replay_only)?;
|
||||
self.render_thread_snapshot(tui, app_server, thread_id, snapshot, !is_replay_only)
|
||||
.await?;
|
||||
if !is_replay_only
|
||||
&& let Some(message) = self
|
||||
.side_threads
|
||||
@@ -917,10 +940,10 @@ impl App {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn render_thread_snapshot(
|
||||
pub(super) async fn render_thread_snapshot(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &AppServerSession,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
snapshot: ThreadEventSnapshot,
|
||||
resume_restored_queue: bool,
|
||||
@@ -935,12 +958,27 @@ impl App {
|
||||
&& side_parent(thread_id).is_some_and(|parent| {
|
||||
self.chat_widget.thread_id().and_then(side_parent) == Some(parent)
|
||||
});
|
||||
let init = self.chatwidget_init_for_forked_or_resumed_thread(
|
||||
let mut init = self.chatwidget_init_for_forked_or_resumed_thread(
|
||||
tui,
|
||||
self.config.clone(),
|
||||
/*initial_user_message*/ None,
|
||||
);
|
||||
self.replace_chat_widget(ChatWidget::new_with_app_event(init));
|
||||
if let Some(session) = &snapshot.session
|
||||
&& session.model_provider_id != self.chat_widget.quota_provider_id()
|
||||
{
|
||||
let account = app_server
|
||||
.read_thread_account(session)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
self.apply_session_account(&mut init, account);
|
||||
}
|
||||
self.replace_chat_widget_for_provider(
|
||||
ChatWidget::new_with_app_event(init),
|
||||
snapshot
|
||||
.session
|
||||
.as_ref()
|
||||
.map(|session| session.model_provider_id.as_str()),
|
||||
);
|
||||
self.chat_widget
|
||||
.set_task_mentions_enabled(app_server.task_tools_available(thread_id));
|
||||
self.chat_widget
|
||||
@@ -1478,7 +1516,9 @@ impl App {
|
||||
None
|
||||
};
|
||||
let thread_id = started.session.thread_id;
|
||||
let (account, account_error) = if self.model_catalog.provider_may_have_changed() {
|
||||
let (account, account_error) = if self.model_catalog.provider_may_have_changed()
|
||||
|| started.session.model_provider_id != self.chat_widget.quota_provider_id()
|
||||
{
|
||||
match app_server.read_thread_account(&started.session).await {
|
||||
Ok(account) => (Some(account), None),
|
||||
Err(err) => (Some(SessionAccount::default()), Some(err)),
|
||||
@@ -1544,6 +1584,20 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_session_account(
|
||||
&mut self,
|
||||
init: &mut crate::chatwidget::ChatWidgetInit,
|
||||
account: SessionAccount,
|
||||
) {
|
||||
self.account_email_request_id = None;
|
||||
self.feedback_audience = account.feedback_audience();
|
||||
init.has_chatgpt_account = account.has_chatgpt_account();
|
||||
init.has_codex_backend_auth = init.has_chatgpt_account;
|
||||
init.requires_openai_auth = account.requires_openai_auth;
|
||||
init.status_account_display = account.display;
|
||||
init.initial_plan_type = account.plan;
|
||||
}
|
||||
|
||||
async fn replace_chat_widget_with_account(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
@@ -1594,15 +1648,12 @@ impl App {
|
||||
initial_user_message,
|
||||
);
|
||||
if let Some(account) = account {
|
||||
self.account_email_request_id = None;
|
||||
self.feedback_audience = account.feedback_audience();
|
||||
init.has_chatgpt_account = account.has_chatgpt_account();
|
||||
init.has_codex_backend_auth = init.has_chatgpt_account;
|
||||
init.requires_openai_auth = account.requires_openai_auth;
|
||||
init.status_account_display = account.display;
|
||||
init.initial_plan_type = account.plan;
|
||||
self.apply_session_account(&mut init, account);
|
||||
}
|
||||
self.replace_chat_widget(ChatWidget::new_with_app_event(init));
|
||||
self.replace_chat_widget_for_provider(
|
||||
ChatWidget::new_with_app_event(init),
|
||||
Some(&started.session.model_provider_id),
|
||||
);
|
||||
if matches!(
|
||||
presentation,
|
||||
ThreadAttachPresentation::Fresh | ThreadAttachPresentation::FreshWithDraft
|
||||
|
||||
@@ -9915,62 +9915,6 @@ async fn app_server_thread_replacement_clears_previous_transcript_before_replay(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_thread_switch_discards_queued_previous_history() -> Result<()> {
|
||||
let (mut app, mut events, _op_rx) = make_test_app_with_channels().await;
|
||||
app.transcript_cells = vec![plain_line_cell("Previous thread transcript")];
|
||||
app.chat_widget
|
||||
.add_plain_history_lines(vec![Line::from("Previous queued history")]);
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
let next_thread_id = ThreadId::new();
|
||||
app.render_thread_snapshot(
|
||||
&mut tui,
|
||||
&app_server,
|
||||
next_thread_id,
|
||||
ThreadEventSnapshot {
|
||||
delegated_turns: Vec::new(),
|
||||
session: Some(test_thread_session(
|
||||
next_thread_id,
|
||||
test_path_buf("/tmp/next"),
|
||||
)),
|
||||
turns: vec![test_turn(
|
||||
"next-turn",
|
||||
TurnStatus::Completed,
|
||||
vec![ThreadItemPayload::UserMessage {
|
||||
id: "next-user".to_string(),
|
||||
client_id: None,
|
||||
content: vec![AppServerUserInput::Text {
|
||||
text: "Next thread prompt".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
}],
|
||||
)],
|
||||
events: Vec::new(),
|
||||
active_reasoning_item: None,
|
||||
input_state: None,
|
||||
},
|
||||
/*resume_restored_queue*/ false,
|
||||
)?;
|
||||
assert_eq!(app.pending_thread_switch_resets, 1);
|
||||
while let Ok(event) = events.try_recv() {
|
||||
app.handle_event(&mut tui, &mut app_server, event).await?;
|
||||
}
|
||||
assert_eq!(app.pending_thread_switch_resets, 0);
|
||||
let rendered = app
|
||||
.render_transcript_lines_for_reflow(/*width*/ 80)
|
||||
.lines
|
||||
.iter()
|
||||
.map(rendered_line_text)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(!rendered.contains("Previous thread transcript"));
|
||||
assert!(!rendered.contains("Previous queued history"));
|
||||
assert!(rendered.contains("Next thread prompt"));
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rendered_line_text(line: &crate::terminal_hyperlinks::HyperlinkLine) -> String {
|
||||
line.line
|
||||
.spans
|
||||
|
||||
@@ -42,6 +42,70 @@ async fn next_rate_limits_loaded(
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn new_chat_without_a_chatgpt_account_rejects_stale_recovery() -> Result<()> {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
set_chatgpt_auth(&mut app.chat_widget);
|
||||
let provider = app.chat_widget.quota_provider_id().to_owned();
|
||||
let (request_id, hard_stop_generation) = app
|
||||
.rate_limit_refresh_state
|
||||
.start(
|
||||
RateLimitRefreshOrigin::Recovery,
|
||||
&mut app.rate_limit_hard_stop_generation,
|
||||
)
|
||||
.expect("start quota recovery");
|
||||
|
||||
// A saved /provider selection makes /new read the account again.
|
||||
*app.model_catalog.provider_write.lock().await = true;
|
||||
Box::pin(app.start_fresh_session(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
crate::app::session_lifecycle::FreshSessionStart::PreserveCurrentView(None),
|
||||
/*initial_user_message*/ None,
|
||||
/*new_thread_name*/ None,
|
||||
))
|
||||
.await;
|
||||
app.drain_active_thread_events(&mut tui).await?;
|
||||
assert_eq!(app.chat_widget.quota_provider_id(), provider);
|
||||
assert!(!app.chat_widget.has_chatgpt_account());
|
||||
|
||||
// The outgoing chat's limit error can also have queued a refresh just before /new.
|
||||
Box::pin(app.handle_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
AppEvent::RefreshRateLimits {
|
||||
origin: RateLimitRefreshOrigin::Recovery,
|
||||
},
|
||||
))
|
||||
.await?;
|
||||
app.chat_widget.apply_external_edit("continue".into());
|
||||
app.chat_widget
|
||||
.handle_key_event(crossterm::event::KeyCode::Enter.into());
|
||||
assert!(
|
||||
std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(event,
|
||||
AppEvent::CodexOp(Op::UserTurn { items, .. })
|
||||
if matches!(items.as_slice(), [UserInput::Text { text, .. }] if text == "continue")
|
||||
))
|
||||
);
|
||||
Box::pin(app.handle_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
AppEvent::RateLimitsLoaded {
|
||||
request_id,
|
||||
hard_stop_generation,
|
||||
origin: RateLimitRefreshOrigin::Recovery,
|
||||
result: Ok(super::luna_reserve_recovery_tests::reserve_response()),
|
||||
},
|
||||
))
|
||||
.await?;
|
||||
let state = serde_json::to_value(app.chat_widget.statusline_state())?;
|
||||
assert_eq!(state["account"]["rate_limits"], json!([]));
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn luna_reserve_periodic_refresh_adapts_without_an_experiment_banner() -> Result<()> {
|
||||
let backend = MockServer::start().await;
|
||||
|
||||
@@ -19,10 +19,17 @@ 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;
|
||||
crate::chatwidget::tests::helpers::set_fast_mode_test_catalog_for_models(
|
||||
&mut app.chat_widget,
|
||||
"gpt-5.5",
|
||||
"gpt-5.6-terra",
|
||||
);
|
||||
app.model_catalog = app.chat_widget.model_catalog();
|
||||
let home = tempdir()?;
|
||||
app.config.codex_home = home.path().abs();
|
||||
app.config.sqlite = SqliteConfig::new_for_testing(home.path().abs());
|
||||
app.config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File;
|
||||
let mut server_config = app.config.clone();
|
||||
server_config.codex_home = home.path().abs();
|
||||
server_config.sqlite = SqliteConfig::new_for_testing(home.path().abs());
|
||||
server_config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File;
|
||||
app_test_support::write_chatgpt_auth(
|
||||
home.path(),
|
||||
app_test_support::ChatGptAuthFixture::new("test-token")
|
||||
@@ -40,18 +47,61 @@ 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 = 'test-model'\ncli_auth_credentials_store = 'file'\nchatgpt_base_url = {:?}\nmodel_catalog_json = {catalog_path:?}\nfeatures.apps = 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",
|
||||
backend.uri(),
|
||||
),
|
||||
)?;
|
||||
let (mut server, _requests, proxy) = Box::pin(start_recording_app_server(
|
||||
&app.config,
|
||||
/*blocked_thread_list*/ None,
|
||||
/*failed_thread_name*/ None,
|
||||
))
|
||||
.await?;
|
||||
let (mut server, _requests, proxy) =
|
||||
Box::pin(session_lifecycle_requests::start_recording_remote_app_server(&server_config))
|
||||
.await?;
|
||||
app.app_server_target = AppServerTarget::Remote {
|
||||
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", "amazon-bedrock"] {
|
||||
for provider in [
|
||||
"amazon-bedrock",
|
||||
"openai",
|
||||
"alt",
|
||||
"openai",
|
||||
"amazon-bedrock",
|
||||
] {
|
||||
if app.chat_widget.config_ref().model_provider_id == "alt" {
|
||||
// The task list uses the client default, which is also the next provider.
|
||||
Box::pin(app.archive_current_thread(&mut tui, &mut server)).await?;
|
||||
assert!(app.active_thread_id.is_none());
|
||||
app.handle_app_server_event(
|
||||
&server,
|
||||
codex_app_server_client::AppServerEvent::ServerNotification(Box::new(
|
||||
ServerNotification::AccountUpdated(
|
||||
codex_app_server_protocol::AccountUpdatedNotification {
|
||||
auth_mode: Some(codex_app_server_protocol::AuthMode::Chatgpt),
|
||||
plan_type: Some(codex_protocol::account::PlanType::Pro),
|
||||
},
|
||||
),
|
||||
)),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let mut snapshot = super::rate_limits::rate_limit_snapshot(
|
||||
/*used_percent*/ 90, /*rate_limit_reached_type*/ None,
|
||||
/*spend_control_reached*/ None,
|
||||
);
|
||||
snapshot.credits = None;
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(snapshot.clone()));
|
||||
if provider == "alt" {
|
||||
assert!(app.chat_widget.usage_notice(/*width*/ 100).is_some());
|
||||
app.chat_widget
|
||||
.update_backend_banner(&super::backend_banner_fallback_tests::fallback_response());
|
||||
assert!(app.chat_widget.backend_banner_fallback().is_some());
|
||||
}
|
||||
let (request_id, hard_stop_generation) = app
|
||||
.rate_limit_refresh_state
|
||||
.start(
|
||||
RateLimitRefreshOrigin::Recovery,
|
||||
&mut app.rate_limit_hard_stop_generation,
|
||||
)
|
||||
.expect("start quota recovery on the previous provider");
|
||||
crate::config_update::write_config_batch(
|
||||
server.request_handle(),
|
||||
vec![crate::config_update::replace_config_value(
|
||||
@@ -60,7 +110,6 @@ async fn new_session_refreshes_account_for_the_started_provider() -> Result<()>
|
||||
)],
|
||||
)
|
||||
.await?;
|
||||
*app.model_catalog.provider_write.lock().await = true;
|
||||
Box::pin(app.start_fresh_session(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
@@ -69,7 +118,30 @@ async fn new_session_refreshes_account_for_the_started_provider() -> Result<()>
|
||||
/*new_thread_name*/ None,
|
||||
))
|
||||
.await;
|
||||
let chatgpt = provider == "openai";
|
||||
app.drain_active_thread_events(&mut tui).await?;
|
||||
if provider == "alt" {
|
||||
assert!(
|
||||
app.rate_limit_refresh_state
|
||||
.poll_deadline(std::time::Duration::ZERO)
|
||||
.is_some(),
|
||||
"the new provider can poll before the old recovery reply"
|
||||
);
|
||||
app.apply_backend_banner_fallback(&mut server).await;
|
||||
assert_eq!(app.chat_widget.current_model(), "gpt-5.5");
|
||||
assert!(app.chat_widget.usage_notice(/*width*/ 100).is_none());
|
||||
}
|
||||
let state = serde_json::to_value(app.chat_widget.statusline_state())?;
|
||||
assert_eq!(state["account"]["rate_limits"], serde_json::json!([]));
|
||||
let late_read = AppEvent::RateLimitsLoaded {
|
||||
request_id,
|
||||
origin: RateLimitRefreshOrigin::Recovery,
|
||||
hard_stop_generation,
|
||||
result: Ok(super::rate_limits::account_rate_limits_response(snapshot)),
|
||||
};
|
||||
Box::pin(app.handle_event(&mut tui, &mut server, late_read)).await?;
|
||||
let state = serde_json::to_value(app.chat_widget.statusline_state())?;
|
||||
assert_eq!(state["account"]["rate_limits"], serde_json::json!([]));
|
||||
let chatgpt = matches!(provider, "openai" | "alt");
|
||||
assert_eq!(
|
||||
(
|
||||
app.chat_widget.config_ref().model_provider_id.as_str(),
|
||||
@@ -92,6 +164,183 @@ async fn new_session_refreshes_account_for_the_started_provider() -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn new_session_on_same_provider_preserves_quota_and_pending_recovery() -> Result<()> {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
app.config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File;
|
||||
app_test_support::write_chatgpt_auth(
|
||||
app.config.codex_home.as_path(),
|
||||
app_test_support::ChatGptAuthFixture::new("test-token").plan_type("pro"),
|
||||
codex_login::AuthCredentialsStoreMode::File,
|
||||
)
|
||||
.expect("write synthetic auth");
|
||||
let backend = wiremock::MockServer::start().await;
|
||||
std::fs::write(
|
||||
app.config.codex_home.join("config.toml"),
|
||||
format!(
|
||||
"cli_auth_credentials_store = 'file'\nchatgpt_base_url = {:?}\n",
|
||||
backend.uri()
|
||||
),
|
||||
)?;
|
||||
let (mut server, _requests, proxy) =
|
||||
Box::pin(session_lifecycle_requests::start_recording_remote_app_server(&app.config))
|
||||
.await?;
|
||||
let client_home = tempdir()?;
|
||||
std::fs::write(
|
||||
client_home.path().join("config.toml"),
|
||||
"model_provider = 'amazon-bedrock'\n",
|
||||
)?;
|
||||
app.local_settings.codex_home = client_home.path().abs();
|
||||
app.app_server_target = AppServerTarget::Remote {
|
||||
endpoint: crate::resolve_remote_addr("ws://127.0.0.1:4500")?,
|
||||
};
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
*app.model_catalog.provider_write.lock().await = true;
|
||||
Box::pin(app.start_fresh_session(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
FreshSessionStart::PreserveCurrentView(None),
|
||||
/*initial_user_message*/ None,
|
||||
/*new_thread_name*/ None,
|
||||
))
|
||||
.await;
|
||||
app.drain_active_thread_events(&mut tui).await?;
|
||||
assert!(app.chat_widget.has_chatgpt_account());
|
||||
let mut snapshot = super::rate_limits::rate_limit_snapshot(
|
||||
/*used_percent*/ 41, /*rate_limit_reached_type*/ None,
|
||||
/*spend_control_reached*/ None,
|
||||
);
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(snapshot.clone()));
|
||||
app.chat_widget.hold_rate_limit_recovery();
|
||||
let (request_id, hard_stop_generation) = app
|
||||
.rate_limit_refresh_state
|
||||
.start(
|
||||
RateLimitRefreshOrigin::Recovery,
|
||||
&mut app.rate_limit_hard_stop_generation,
|
||||
)
|
||||
.expect("start quota recovery");
|
||||
|
||||
for from_task_list in [false, true] {
|
||||
let previous = app.active_thread_id.expect("active thread");
|
||||
if from_task_list {
|
||||
Box::pin(app.archive_current_thread(&mut tui, &mut server)).await?;
|
||||
assert!(app.active_thread_id.is_none());
|
||||
assert_eq!(
|
||||
app.chat_widget.config_ref().model_provider_id,
|
||||
"amazon-bedrock"
|
||||
);
|
||||
}
|
||||
Box::pin(app.start_fresh_session(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
FreshSessionStart::PreserveCurrentView(None),
|
||||
/*initial_user_message*/ None,
|
||||
/*new_thread_name*/ None,
|
||||
))
|
||||
.await;
|
||||
app.drain_active_thread_events(&mut tui).await?;
|
||||
assert_ne!(
|
||||
app.active_thread_id.expect("/new opened a thread"),
|
||||
previous
|
||||
);
|
||||
assert_eq!(app.chat_widget.config_ref().model_provider_id, "openai");
|
||||
let state = serde_json::to_value(app.chat_widget.statusline_state())?;
|
||||
assert_eq!(
|
||||
state["account"]["rate_limits"][0]["primary_limit"]["used_percent"],
|
||||
41.0
|
||||
);
|
||||
}
|
||||
app.chat_widget.apply_external_edit("after recovery".into());
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
assert_eq!(
|
||||
app.chat_widget.queued_user_message_texts(),
|
||||
["after recovery"]
|
||||
);
|
||||
snapshot.primary.as_mut().unwrap().used_percent = 60;
|
||||
let reply = AppEvent::RateLimitsLoaded {
|
||||
request_id,
|
||||
origin: RateLimitRefreshOrigin::Recovery,
|
||||
hard_stop_generation,
|
||||
result: Ok(super::rate_limits::account_rate_limits_response(snapshot)),
|
||||
};
|
||||
Box::pin(app.handle_event(&mut tui, &mut server, reply)).await?;
|
||||
assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| {
|
||||
matches!(event, AppEvent::CodexOp(Op::UserTurn { items, .. })
|
||||
if matches!(items.as_slice(), [UserInput::Text { text, .. }] if text == "after recovery"))
|
||||
}));
|
||||
let state = serde_json::to_value(app.chat_widget.statusline_state())?;
|
||||
assert_eq!(
|
||||
state["account"]["rate_limits"][0]["primary_limit"]["used_percent"],
|
||||
60.0
|
||||
);
|
||||
server.shutdown().await?;
|
||||
proxy.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn switching_to_a_cached_side_chat_clears_the_previous_providers_quota() -> Result<()> {
|
||||
let mut app = make_test_app().await;
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let started = server.start_thread(&app.config).await?;
|
||||
let parent = started.session.thread_id;
|
||||
app.enqueue_primary_thread_session(started.session, started.turns)
|
||||
.await?;
|
||||
app.drain_active_thread_events(&mut tui).await?;
|
||||
set_chatgpt_auth(&mut app.chat_widget);
|
||||
assert!(app.chat_widget.rate_limit_refresh_interval().is_some());
|
||||
let quota = super::rate_limits::rate_limit_snapshot(
|
||||
/*used_percent*/ 73, /*rate_limit_reached_type*/ None,
|
||||
/*spend_control_reached*/ None,
|
||||
);
|
||||
app.chat_widget.on_rate_limit_snapshot(Some(quota.clone()));
|
||||
let state = serde_json::to_value(app.chat_widget.statusline_state())?;
|
||||
assert_eq!(
|
||||
state["account"]["rate_limits"][0]["primary_limit"]["used_percent"],
|
||||
73.0
|
||||
);
|
||||
let (request_id, hard_stop_generation) = app
|
||||
.rate_limit_refresh_state
|
||||
.start(
|
||||
RateLimitRefreshOrigin::Periodic,
|
||||
&mut app.rate_limit_hard_stop_generation,
|
||||
)
|
||||
.expect("start quota refresh");
|
||||
|
||||
let child = ThreadId::new();
|
||||
let mut session = test_thread_session(child, app.config.cwd.to_path_buf());
|
||||
session.model_provider_id = "amazon-bedrock".into();
|
||||
app.side_threads.insert(child, SideThreadState::new(parent));
|
||||
app.ensure_thread_channel(child)
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.set_session(session, Vec::new());
|
||||
app.select_agent_thread(&mut tui, &mut server, child)
|
||||
.await?;
|
||||
|
||||
Box::pin(app.handle_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
AppEvent::RateLimitsLoaded {
|
||||
request_id,
|
||||
hard_stop_generation,
|
||||
origin: RateLimitRefreshOrigin::Periodic,
|
||||
result: Ok(super::rate_limits::account_rate_limits_response(quota)),
|
||||
},
|
||||
))
|
||||
.await?;
|
||||
let state = serde_json::to_value(app.chat_widget.statusline_state())?;
|
||||
assert_eq!(state["thread"]["model"]["provider"], "amazon-bedrock");
|
||||
assert_eq!(state["account"]["rate_limits"], serde_json::json!([]));
|
||||
assert!(app.chat_widget.rate_limit_refresh_interval().is_none());
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_account_uses_only_a_matching_server_default() -> Result<()> {
|
||||
let (client, mut commands, _events) =
|
||||
@@ -403,10 +652,10 @@ async fn replacement_uses_server_defaults_and_preserves_explicit_launch_settings
|
||||
app.config.codex_home = client_home.path().to_path_buf().abs();
|
||||
app.config.sqlite = SqliteConfig::new_for_testing(client_home.path().abs());
|
||||
app.chat_widget
|
||||
.handle_thread_session_quiet(test_thread_session(
|
||||
ThreadId::new(),
|
||||
client_home.path().to_path_buf(),
|
||||
));
|
||||
.handle_thread_session_quiet(ThreadSessionState {
|
||||
model_provider_id: server_config.model_provider_id.clone(),
|
||||
..test_thread_session(ThreadId::new(), client_home.path().to_path_buf())
|
||||
});
|
||||
match explicit {
|
||||
"model" => app.harness_overrides.model = Some("cli-model".to_string()),
|
||||
"effort" => app.cli_kv_overrides.push((
|
||||
@@ -1396,7 +1645,10 @@ async fn replacement_preserves_remote_launch_paths_and_older_servers() -> Result
|
||||
"model = \"configured-model\"\n",
|
||||
)?;
|
||||
app.enqueue_primary_thread_session(
|
||||
test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf()),
|
||||
ThreadSessionState {
|
||||
model_provider_id: app.config.model_provider_id.clone(),
|
||||
..test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf())
|
||||
},
|
||||
Vec::new(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -12,7 +12,7 @@ use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn rate_limit_snapshot(
|
||||
pub(super) fn rate_limit_snapshot(
|
||||
used_percent: i32,
|
||||
rate_limit_reached_type: Option<RateLimitReachedType>,
|
||||
spend_control_reached: Option<bool>,
|
||||
@@ -39,7 +39,9 @@ fn rate_limit_snapshot(
|
||||
}
|
||||
}
|
||||
|
||||
fn account_rate_limits_response(snapshot: RateLimitSnapshot) -> GetAccountRateLimitsResponse {
|
||||
pub(super) fn account_rate_limits_response(
|
||||
snapshot: RateLimitSnapshot,
|
||||
) -> GetAccountRateLimitsResponse {
|
||||
GetAccountRateLimitsResponse {
|
||||
ordinary_usage_allowed: None,
|
||||
account_id: None,
|
||||
|
||||
@@ -6973,3 +6973,60 @@ async fn provider_error_preserves_partial_history_notice() -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn snapshot_thread_switch_discards_queued_previous_history() -> Result<()> {
|
||||
let (mut app, mut events, _op_rx) = make_test_app_with_channels().await;
|
||||
app.transcript_cells = vec![plain_line_cell("Previous thread transcript")];
|
||||
app.chat_widget
|
||||
.add_plain_history_lines(vec![Line::from("Previous queued history")]);
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
let next_thread_id = ThreadId::new();
|
||||
app.render_thread_snapshot(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
next_thread_id,
|
||||
ThreadEventSnapshot {
|
||||
delegated_turns: Vec::new(),
|
||||
session: Some(test_thread_session(
|
||||
next_thread_id,
|
||||
test_path_buf("/tmp/next"),
|
||||
)),
|
||||
turns: vec![test_turn(
|
||||
"next-turn",
|
||||
TurnStatus::Completed,
|
||||
vec![ThreadItemPayload::UserMessage {
|
||||
id: "next-user".to_string(),
|
||||
client_id: None,
|
||||
content: vec![AppServerUserInput::Text {
|
||||
text: "Next thread prompt".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
}],
|
||||
)],
|
||||
events: Vec::new(),
|
||||
active_reasoning_item: None,
|
||||
input_state: None,
|
||||
},
|
||||
/*resume_restored_queue*/ false,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(app.pending_thread_switch_resets, 1);
|
||||
while let Ok(event) = events.try_recv() {
|
||||
app.handle_event(&mut tui, &mut app_server, event).await?;
|
||||
}
|
||||
assert_eq!(app.pending_thread_switch_resets, 0);
|
||||
let rendered = app
|
||||
.render_transcript_lines_for_reflow(/*width*/ 80)
|
||||
.lines
|
||||
.iter()
|
||||
.map(rendered_line_text)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(!rendered.contains("Previous thread transcript"));
|
||||
assert!(!rendered.contains("Previous queued history"));
|
||||
assert!(rendered.contains("Next thread prompt"));
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -932,11 +932,12 @@ async fn unattended_modals_survive_unfinished_terminal_input() -> Result<()> {
|
||||
crossterm::event::buffer_input(b"\rya")?;
|
||||
app.render_thread_snapshot(
|
||||
&mut tui,
|
||||
&app_server,
|
||||
&mut app_server,
|
||||
thread_id,
|
||||
snapshot,
|
||||
/*resume_restored_queue*/ false,
|
||||
)?;
|
||||
)
|
||||
.await?;
|
||||
assert!(app.chat_widget.has_active_modal());
|
||||
let before = tui.terminal.previous_buffer().clone();
|
||||
let cursor = tui.terminal.last_known_cursor_pos;
|
||||
@@ -1930,12 +1931,12 @@ async fn ignore_same_thread_resume_allows_retrying_read_only_view() -> Result<()
|
||||
history_mode: None,
|
||||
})
|
||||
);
|
||||
let app_server =
|
||||
let mut app_server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
app.render_thread_snapshot(
|
||||
&mut tui,
|
||||
&app_server,
|
||||
&mut app_server,
|
||||
thread_id,
|
||||
ThreadEventSnapshot {
|
||||
delegated_turns: Vec::new(),
|
||||
@@ -1946,7 +1947,8 @@ async fn ignore_same_thread_resume_allows_retrying_read_only_view() -> Result<()
|
||||
input_state: None,
|
||||
},
|
||||
/*resume_restored_queue*/ false,
|
||||
)?;
|
||||
)
|
||||
.await?;
|
||||
assert!(app.chat_widget.is_external_writer_view());
|
||||
assert!(!app.chat_widget.is_task_running_for_test());
|
||||
Ok(())
|
||||
|
||||
@@ -227,11 +227,12 @@ async fn command_start_before_message_completion_does_not_duplicate_preamble() -
|
||||
app.active_thread_rx = Some(receiver);
|
||||
app.render_thread_snapshot(
|
||||
&mut tui,
|
||||
&app_server,
|
||||
&mut app_server,
|
||||
thread_id,
|
||||
snapshot,
|
||||
/*resume_restored_queue*/ false,
|
||||
)?;
|
||||
)
|
||||
.await?;
|
||||
while let Ok(event) = app_events.try_recv() {
|
||||
app.handle_event(&mut tui, &mut app_server, event).await?;
|
||||
}
|
||||
|
||||
@@ -588,6 +588,7 @@ pub(crate) struct ChatWidget {
|
||||
token_usage_pending: bool,
|
||||
// Status and polling use account usage reads; response streams may identify meters differently.
|
||||
rate_limit_snapshots_by_limit_id: BTreeMap<String, RateLimitSnapshotDisplay>,
|
||||
inherited_quota_provider: Option<String>,
|
||||
refreshing_status_outputs: Vec<(u64, StatusHistoryHandle)>,
|
||||
next_status_refresh_request_id: u64,
|
||||
pending_rate_limit_reset_request_id: Option<u64>,
|
||||
|
||||
@@ -298,8 +298,8 @@ impl ChatWidget {
|
||||
self.backend_banner_state = std::mem::take(&mut previous.backend_banner_state);
|
||||
self.luna_reserve_notice_account_id = previous.luna_reserve_notice_account_id.take();
|
||||
self.backend_banner_state.dismissed |= self.reserve_notice_already_shown();
|
||||
// Usage belongs to the account, so switching tasks must not reset the polling cadence
|
||||
// or discard the already-known limits shown by /status.
|
||||
// The task list can use a different local provider from the chat whose quota it inherits.
|
||||
self.inherited_quota_provider = Some(previous.quota_provider_id().to_owned());
|
||||
self.rate_limit_snapshots_by_limit_id =
|
||||
std::mem::take(&mut previous.rate_limit_snapshots_by_limit_id);
|
||||
self.usage_notice_state = std::mem::take(&mut previous.usage_notice_state);
|
||||
|
||||
@@ -160,6 +160,7 @@ impl ChatWidget {
|
||||
token_info: None,
|
||||
token_usage_pending: false,
|
||||
rate_limit_snapshots_by_limit_id: BTreeMap::new(),
|
||||
inherited_quota_provider: None,
|
||||
refreshing_status_outputs: Vec::new(),
|
||||
next_status_refresh_request_id: 0,
|
||||
pending_rate_limit_reset_request_id: None,
|
||||
|
||||
@@ -195,6 +195,19 @@ fn has_usable_workspace_credits(credits: &CreditsSnapshot) -> bool {
|
||||
}
|
||||
|
||||
impl ChatWidget {
|
||||
pub(crate) fn quota_provider_id(&self) -> &str {
|
||||
if self.thread_id().is_none()
|
||||
&& let Some(provider) = &self.inherited_quota_provider
|
||||
{
|
||||
return provider;
|
||||
}
|
||||
&self.config.model_provider_id
|
||||
}
|
||||
|
||||
pub(crate) fn forget_inherited_quota_provider(&mut self) {
|
||||
self.inherited_quota_provider = None;
|
||||
}
|
||||
|
||||
/// Poll more often near exhaustion for every ChatGPT account, independently of experiments.
|
||||
pub(crate) fn rate_limit_refresh_interval(&self) -> Option<std::time::Duration> {
|
||||
if !self.should_prefetch_rate_limits() {
|
||||
|
||||
Reference in New Issue
Block a user