From 40a6cc1bd48ffc5918968a9294830f144d078ca3 Mon Sep 17 00:00:00 2001 From: James Chu Date: Mon, 4 May 2026 00:38:02 -0400 Subject: [PATCH] [codex] Harden proactive usage nudge refresh flow --- codex-rs/tui/src/app/tests.rs | 34 +++++ codex-rs/tui/src/chatwidget.rs | 20 ++- .../chatwidget/current_usage_limit_nudge.rs | 75 ++++++---- .../tests/current_usage_limit_nudge.rs | 138 ++++++++++++++++++ 4 files changed, 239 insertions(+), 28 deletions(-) diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 60192130a2..b400c4c19e 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -220,6 +220,40 @@ async fn account_rate_limits_updated_prefetches_authoritative_usage_nudge_snapsh )); } +#[tokio::test] +async fn account_rate_limits_updated_does_not_clear_authoritative_usage_nudge_state() { + let mut app = make_test_app().await; + let app_server = crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()) + .await + .expect("embedded app server"); + + app.handle_rate_limits_loaded( + /*refresh_generation*/ 0, + RateLimitRefreshOrigin::UsageNudgePrefetch, + Ok(vec![codex_rate_limit_snapshot( + /*used_percent*/ 75, + Some(UsageLimitNudge { + threshold: 75, + action: UsageLimitNudgeAction::AddCredits, + }), + )]), + ); + app.handle_app_server_event( + &app_server, + codex_app_server_client::AppServerEvent::ServerNotification( + ServerNotification::AccountRateLimitsUpdated(AccountRateLimitsUpdatedNotification { + rate_limits: codex_rate_limit_snapshot(/*used_percent*/ 80, None), + }), + ), + ) + .await; + + assert!( + app.chat_widget + .has_active_current_usage_limit_nudge_for_test() + ); +} + #[test] fn startup_waiting_gate_is_only_for_fresh_or_exit_session_selection() { assert_eq!( diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index d297ded298..788661c6ca 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -478,6 +478,12 @@ struct RateLimitWarningState { primary_index: usize, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum RateLimitSnapshotSource { + LiveUpdate, + AuthoritativeRead, +} + impl RateLimitWarningState { fn take_warnings( &mut self, @@ -2847,7 +2853,7 @@ impl ChatWidget { origin: RateLimitRefreshOrigin::UsageNudgePrefetch, }); } - self.on_rate_limit_snapshot(Some(snapshot)); + self.apply_rate_limit_snapshot(Some(snapshot), RateLimitSnapshotSource::LiveUpdate); } fn should_prefetch_current_usage_limit_nudge(&mut self, snapshot: &RateLimitSnapshot) -> bool { @@ -2860,10 +2866,18 @@ impl ChatWidget { && self.current_usage_limit_nudge_enabled() && self .current_usage_limit_nudge_prompt - .should_prefetch(snapshot.primary.as_ref()) + .should_prefetch(snapshot.primary.as_ref(), snapshot.secondary.as_ref()) } pub(crate) fn on_rate_limit_snapshot(&mut self, snapshot: Option) { + self.apply_rate_limit_snapshot(snapshot, RateLimitSnapshotSource::AuthoritativeRead); + } + + fn apply_rate_limit_snapshot( + &mut self, + snapshot: Option, + source: RateLimitSnapshotSource, + ) { if let Some(mut snapshot) = snapshot { let limit_id = snapshot .limit_id @@ -2888,7 +2902,7 @@ impl ChatWidget { 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 { + if is_codex_limit && matches!(source, RateLimitSnapshotSource::AuthoritativeRead) { let nudge = if self.current_usage_limit_nudge_enabled() { snapshot.current_usage_limit_nudge.clone() } else { diff --git a/codex-rs/tui/src/chatwidget/current_usage_limit_nudge.rs b/codex-rs/tui/src/chatwidget/current_usage_limit_nudge.rs index 2d4bf7b1fa..64f33d662c 100644 --- a/codex-rs/tui/src/chatwidget/current_usage_limit_nudge.rs +++ b/codex-rs/tui/src/chatwidget/current_usage_limit_nudge.rs @@ -7,8 +7,15 @@ pub(super) const CURRENT_USAGE_LIMIT_NUDGE_URL: &str = "https://chatgpt.com/code pub(super) const WORKSPACE_OWNER_USAGE_LIMIT_NUDGE_URL: &str = "https://chatgpt.com/admin/billing"; pub(super) const UPGRADE_USAGE_LIMIT_NUDGE_URL: &str = "https://chatgpt.com/explore/pro"; +#[derive(Clone, Copy, PartialEq, Eq)] +enum UsageNudgePrefetchWindow { + Primary, + Secondary, +} + #[derive(Clone, Copy, PartialEq, Eq)] struct UsageNudgePrefetchKey { + window: UsageNudgePrefetchWindow, window_duration_mins: Option, resets_at: Option, } @@ -36,7 +43,7 @@ pub(super) struct CurrentUsageLimitNudgePromptState { active: bool, pending: Option, has_shown: bool, - last_prefetch: Option<(UsageNudgePrefetchKey, UsageNudgePrefetchThreshold)>, + last_prefetches: Vec<(UsageNudgePrefetchKey, UsageNudgePrefetchThreshold)>, } impl CurrentUsageLimitNudgePromptState { @@ -59,32 +66,50 @@ impl CurrentUsageLimitNudgePromptState { self.pending.is_some() } - pub(super) fn should_prefetch(&mut self, primary: Option<&RateLimitWindow>) -> bool { - let Some(primary) = primary else { - return false; - }; - let Some(threshold) = UsageNudgePrefetchThreshold::from_used_percent(primary.used_percent) - else { - // Keep the per-window watermark across transient downward or sparse - // live updates so stale events cannot re-arm a threshold we already - // refreshed for in this window. - return false; - }; + pub(super) fn should_prefetch( + &mut self, + primary: Option<&RateLimitWindow>, + secondary: Option<&RateLimitWindow>, + ) -> bool { + let mut should_prefetch = false; - let key = UsageNudgePrefetchKey { - window_duration_mins: primary.window_duration_mins, - resets_at: primary.resets_at, - }; - if self - .last_prefetch - .is_some_and(|(last_key, last_threshold)| { - last_key == key && last_threshold >= threshold - }) - { - return false; + for (window_kind, window) in [ + (UsageNudgePrefetchWindow::Primary, primary), + (UsageNudgePrefetchWindow::Secondary, secondary), + ] { + let Some(window) = window else { + continue; + }; + let Some(threshold) = + UsageNudgePrefetchThreshold::from_used_percent(window.used_percent) + else { + // Keep the per-window watermark across transient downward or + // sparse live updates so stale events cannot re-arm a + // threshold we already refreshed for in this window. + continue; + }; + + let key = UsageNudgePrefetchKey { + window: window_kind, + window_duration_mins: window.window_duration_mins, + resets_at: window.resets_at, + }; + if let Some((_, last_threshold)) = self + .last_prefetches + .iter_mut() + .find(|(last_key, _)| *last_key == key) + { + if *last_threshold >= threshold { + continue; + } + *last_threshold = threshold; + } else { + self.last_prefetches.push((key, threshold)); + } + should_prefetch = true; } - self.last_prefetch = Some((key, threshold)); - true + + should_prefetch } } diff --git a/codex-rs/tui/src/chatwidget/tests/current_usage_limit_nudge.rs b/codex-rs/tui/src/chatwidget/tests/current_usage_limit_nudge.rs index b5f5b66ea1..23896d154c 100644 --- a/codex-rs/tui/src/chatwidget/tests/current_usage_limit_nudge.rs +++ b/codex-rs/tui/src/chatwidget/tests/current_usage_limit_nudge.rs @@ -8,6 +8,17 @@ fn snapshot_with_nudge(threshold: u8, action: UsageLimitNudgeAction) -> RateLimi } } +fn snapshot_with_windows(primary_percent: f64, secondary_percent: f64) -> RateLimitSnapshot { + RateLimitSnapshot { + secondary: Some(RateLimitWindow { + used_percent: secondary_percent.round() as i32, + window_duration_mins: Some(300), + resets_at: None, + }), + ..snapshot(primary_percent) + } +} + fn next_open_url_event(rx: &mut tokio::sync::mpsc::UnboundedReceiver) -> Option { while let Ok(event) = rx.try_recv() { if let AppEvent::OpenUrlInBrowser { url } = event { @@ -75,6 +86,32 @@ async fn proactive_usage_prompt_empty_snapshot_does_not_queue_prompt() { assert!(!chat.maybe_show_pending_current_usage_limit_nudge_prompt()); } +#[tokio::test] +async fn proactive_usage_prompt_live_snapshot_does_not_clear_authoritative_pending_nudge() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.on_rate_limit_snapshot(Some(snapshot_with_nudge( + /*threshold*/ 75, + UsageLimitNudgeAction::AddCredits, + ))); + chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 80.0)); + + assert!(chat.maybe_show_pending_current_usage_limit_nudge_prompt()); +} + +#[tokio::test] +async fn proactive_usage_prompt_authoritative_empty_snapshot_clears_pending_nudge() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.on_rate_limit_snapshot(Some(snapshot_with_nudge( + /*threshold*/ 75, + UsageLimitNudgeAction::AddCredits, + ))); + chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 75.0))); + + assert!(!chat.maybe_show_pending_current_usage_limit_nudge_prompt()); +} + #[tokio::test] async fn proactive_usage_prompt_prefetches_snapshot_at_each_live_threshold_crossing() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -101,6 +138,74 @@ async fn proactive_usage_prompt_prefetches_snapshot_at_each_live_threshold_cross assert_eq!(next_rate_limit_refresh_origin(&mut rx), None); } +#[tokio::test] +async fn proactive_usage_prompt_prefetches_snapshot_at_secondary_live_threshold_crossings() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.on_live_rate_limit_snapshot(snapshot_with_windows( + /*primary_percent*/ 50.0, /*secondary_percent*/ 74.0, + )); + assert_eq!(next_rate_limit_refresh_origin(&mut rx), None); + + chat.on_live_rate_limit_snapshot(snapshot_with_windows( + /*primary_percent*/ 50.0, /*secondary_percent*/ 75.0, + )); + assert_eq!( + next_rate_limit_refresh_origin(&mut rx), + Some(RateLimitRefreshOrigin::UsageNudgePrefetch) + ); + + chat.on_live_rate_limit_snapshot(snapshot_with_windows( + /*primary_percent*/ 50.0, /*secondary_percent*/ 80.0, + )); + assert_eq!(next_rate_limit_refresh_origin(&mut rx), None); + + chat.on_live_rate_limit_snapshot(snapshot_with_windows( + /*primary_percent*/ 50.0, /*secondary_percent*/ 90.0, + )); + assert_eq!( + next_rate_limit_refresh_origin(&mut rx), + Some(RateLimitRefreshOrigin::UsageNudgePrefetch) + ); +} + +#[tokio::test] +async fn proactive_usage_prompt_prefetches_each_window_independently() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.on_live_rate_limit_snapshot(snapshot_with_windows( + /*primary_percent*/ 75.0, /*secondary_percent*/ 74.0, + )); + assert_eq!( + next_rate_limit_refresh_origin(&mut rx), + Some(RateLimitRefreshOrigin::UsageNudgePrefetch) + ); + + chat.on_live_rate_limit_snapshot(snapshot_with_windows( + /*primary_percent*/ 80.0, /*secondary_percent*/ 75.0, + )); + assert_eq!( + next_rate_limit_refresh_origin(&mut rx), + Some(RateLimitRefreshOrigin::UsageNudgePrefetch) + ); + + chat.on_live_rate_limit_snapshot(snapshot_with_windows( + /*primary_percent*/ 90.0, /*secondary_percent*/ 80.0, + )); + assert_eq!( + next_rate_limit_refresh_origin(&mut rx), + Some(RateLimitRefreshOrigin::UsageNudgePrefetch) + ); + + chat.on_live_rate_limit_snapshot(snapshot_with_windows( + /*primary_percent*/ 95.0, /*secondary_percent*/ 90.0, + )); + assert_eq!( + next_rate_limit_refresh_origin(&mut rx), + Some(RateLimitRefreshOrigin::UsageNudgePrefetch) + ); +} + #[tokio::test] async fn proactive_usage_prompt_prefetches_once_when_first_live_update_is_above_90() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -136,6 +241,39 @@ async fn proactive_usage_prompt_prefetches_again_after_primary_window_rolls_over ); } +#[tokio::test] +async fn proactive_usage_prompt_prefetches_again_after_secondary_window_rolls_over() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + let mut first_window = snapshot_with_windows( + /*primary_percent*/ 50.0, /*secondary_percent*/ 75.0, + ); + first_window + .secondary + .as_mut() + .expect("secondary") + .resets_at = Some(100); + let mut second_window = snapshot_with_windows( + /*primary_percent*/ 50.0, /*secondary_percent*/ 75.0, + ); + second_window + .secondary + .as_mut() + .expect("secondary") + .resets_at = Some(200); + + chat.on_live_rate_limit_snapshot(first_window); + assert_eq!( + next_rate_limit_refresh_origin(&mut rx), + Some(RateLimitRefreshOrigin::UsageNudgePrefetch) + ); + + chat.on_live_rate_limit_snapshot(second_window); + assert_eq!( + next_rate_limit_refresh_origin(&mut rx), + Some(RateLimitRefreshOrigin::UsageNudgePrefetch) + ); +} + #[tokio::test] async fn proactive_usage_prompt_prefetch_dedupe_survives_same_window_dip() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;