[codex] Render backend-selected near-limit prompts in TUI

This commit is contained in:
James Chu
2026-05-04 23:55:21 -04:00
parent 69afe438db
commit f260fa1ca3
12 changed files with 746 additions and 5 deletions
+6
View File
@@ -406,6 +406,9 @@
"connectors": {
"type": "boolean"
},
"current_usage_limit_nudge": {
"type": "boolean"
},
"default_mode_request_user_input": {
"type": "boolean"
},
@@ -3825,6 +3828,9 @@
"connectors": {
"type": "boolean"
},
"current_usage_limit_nudge": {
"type": "boolean"
},
"default_mode_request_user_input": {
"type": "boolean"
},
+8
View File
@@ -223,6 +223,8 @@ pub enum Feature {
PreventIdleSleep,
/// Enable workspace-specific owner nudge copy and prompts in the TUI.
WorkspaceOwnerUsageNudge,
/// Render backend-selected proactive usage-limit prompts in the TUI.
CurrentUsageLimitNudge,
/// Legacy rollout flag for Responses API WebSocket transport experiments.
ResponsesWebsockets,
/// Legacy rollout flag for Responses API WebSocket transport v2 experiments.
@@ -1070,6 +1072,12 @@ pub const FEATURES: &[FeatureSpec] = &[
stage: Stage::UnderDevelopment,
default_enabled: false,
},
FeatureSpec {
id: Feature::CurrentUsageLimitNudge,
key: "current_usage_limit_nudge",
stage: Stage::Stable,
default_enabled: true,
},
FeatureSpec {
id: Feature::ResponsesWebsockets,
key: "responses_websockets",
+1 -1
View File
@@ -76,7 +76,7 @@ impl App {
}
ServerNotification::AccountRateLimitsUpdated(notification) => {
self.chat_widget
.on_rate_limit_snapshot(Some(notification.rate_limits.clone()));
.on_live_rate_limit_snapshot(notification.rate_limits.clone());
return;
}
ServerNotification::AccountUpdated(notification) => {
+80
View File
@@ -26,6 +26,7 @@ use crate::diff_model::FileChange;
use crate::legacy_core::config::ConfigBuilder;
use crate::legacy_core::config::ConfigOverrides;
use crate::legacy_core::config::TerminalResizeReflowMaxRows;
use codex_app_server_protocol::AccountRateLimitsUpdatedNotification;
use codex_app_server_protocol::AdditionalFileSystemPermissions;
use codex_app_server_protocol::AdditionalNetworkPermissions;
use codex_app_server_protocol::AdditionalPermissionProfile;
@@ -46,6 +47,8 @@ use codex_app_server_protocol::NetworkPolicyRuleAction as AppServerNetworkPolicy
use codex_app_server_protocol::NonSteerableTurnKind as AppServerNonSteerableTurnKind;
use codex_app_server_protocol::PatchChangeKind;
use codex_app_server_protocol::PermissionsRequestApprovalParams;
use codex_app_server_protocol::RateLimitSnapshot;
use codex_app_server_protocol::RateLimitWindow;
use codex_app_server_protocol::RequestId as AppServerRequestId;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ServerRequest;
@@ -63,6 +66,8 @@ use codex_app_server_protocol::TurnCompletedNotification;
use codex_app_server_protocol::TurnError as AppServerTurnError;
use codex_app_server_protocol::TurnStartedNotification;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UsageLimitNudge;
use codex_app_server_protocol::UsageLimitNudgeAction;
use codex_app_server_protocol::UserInput;
use codex_app_server_protocol::UserInput as AppServerUserInput;
use codex_app_server_protocol::WarningNotification;
@@ -140,6 +145,81 @@ async fn stale_rate_limit_refresh_generations_do_not_move_backward() {
assert_eq!(app.latest_applied_rate_limit_refresh_generation, Some(2));
}
fn codex_rate_limit_snapshot(
used_percent: i32,
current_usage_limit_nudge: Option<UsageLimitNudge>,
) -> RateLimitSnapshot {
RateLimitSnapshot {
limit_id: Some("codex".to_string()),
limit_name: None,
primary: Some(RateLimitWindow {
used_percent,
window_duration_mins: Some(60),
resets_at: Some(123),
}),
secondary: None,
credits: None,
plan_type: None,
rate_limit_reached_type: None,
current_usage_limit_nudge,
}
}
#[tokio::test]
async fn stale_rate_limit_refresh_results_are_ignored() {
let mut app = make_test_app().await;
app.handle_rate_limits_loaded(
/*refresh_generation*/ 2,
RateLimitRefreshOrigin::UsageNudgePrefetch,
Ok(vec![codex_rate_limit_snapshot(
/*used_percent*/ 90,
Some(UsageLimitNudge {
threshold: 90,
action: UsageLimitNudgeAction::AddCredits,
}),
)]),
);
app.handle_rate_limits_loaded(
/*refresh_generation*/ 1,
RateLimitRefreshOrigin::UsageNudgePrefetch,
Ok(vec![codex_rate_limit_snapshot(
/*used_percent*/ 90, None,
)]),
);
assert!(
app.chat_widget
.has_active_current_usage_limit_nudge_for_test()
);
}
#[tokio::test]
async fn account_rate_limits_updated_prefetches_authoritative_usage_nudge_snapshot() {
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
while app_event_rx.try_recv().is_ok() {}
let app_server = crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref())
.await
.expect("embedded app server");
app.handle_app_server_event(
&app_server,
codex_app_server_client::AppServerEvent::ServerNotification(
ServerNotification::AccountRateLimitsUpdated(AccountRateLimitsUpdatedNotification {
rate_limits: codex_rate_limit_snapshot(/*used_percent*/ 75, None),
}),
),
)
.await;
assert!(matches!(
app_event_rx.try_recv(),
Ok(AppEvent::RefreshRateLimits {
origin: RateLimitRefreshOrigin::UsageNudgePrefetch,
})
));
}
#[test]
fn startup_waiting_gate_is_only_for_fresh_or_exit_session_selection() {
assert_eq!(
+7 -3
View File
@@ -104,13 +104,17 @@ pub(crate) struct ConnectorsSnapshot {
///
/// A `StartupPrefetch` fires once, concurrently with the rest of TUI init, and
/// only updates the cached snapshots (no status card to finalize). A
/// `StatusCommand` is tied to a specific `/status` invocation and must call
/// `finish_status_rate_limit_refresh` when done so the card stops showing a
/// "refreshing" state.
/// `UsageNudgePrefetch` is triggered from coarse live usage signals so the TUI
/// can fetch the richer backend-authored snapshot once before deciding whether
/// to queue a prompt. A `StatusCommand` is tied to a specific `/status`
/// invocation and must call `finish_status_rate_limit_refresh` when done so
/// the card stops showing a "refreshing" state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RateLimitRefreshOrigin {
/// Eagerly fetched after bootstrap so the first `/status` already has data.
StartupPrefetch,
/// Best-effort near-limit refresh requested from a live usage update.
UsageNudgePrefetch,
/// User-initiated via `/status`; the `request_id` correlates with the
/// status card that should be updated when the fetch completes.
StatusCommand { request_id: u64 },
+129 -1
View File
@@ -122,6 +122,7 @@ use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnCompletedNotification;
use codex_app_server_protocol::TurnPlanStepStatus;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UsageLimitNudge;
use codex_app_server_protocol::UserInput;
use codex_chatgpt::connectors;
use codex_config::ConfigLayerStackOrdering;
@@ -203,6 +204,7 @@ const PLAN_MODE_REASONING_SCOPE_TITLE: &str = "Apply reasoning change";
const PLAN_MODE_REASONING_SCOPE_PLAN_ONLY: &str = "Apply to Plan mode override";
const PLAN_MODE_REASONING_SCOPE_ALL_MODES: &str = "Apply to global default and Plan mode override";
const CONNECTORS_SELECTION_VIEW_ID: &str = "connectors-selection";
const RATE_LIMIT_SWITCH_PROMPT_VIEW_ID: &str = "rate-limit-switch-prompt";
const TUI_STUB_MESSAGE: &str = "Not available in TUI yet.";
/// Choose the keybinding used to edit the most-recently queued message.
@@ -315,7 +317,17 @@ use crate::status_indicator_widget::STATUS_DETAILS_DEFAULT_MAX_LINES;
use crate::status_indicator_widget::StatusDetailsCapitalization;
use crate::text_formatting::truncate_text;
use crate::tui::FrameRequester;
mod current_usage_limit_nudge;
mod goal_status;
#[cfg(test)]
use self::current_usage_limit_nudge::CURRENT_USAGE_LIMIT_NUDGE_URL;
use self::current_usage_limit_nudge::CurrentUsageLimitNudgePromptState;
#[cfg(test)]
use self::current_usage_limit_nudge::UPGRADE_USAGE_LIMIT_NUDGE_URL;
#[cfg(test)]
use self::current_usage_limit_nudge::WORKSPACE_OWNER_USAGE_LIMIT_NUDGE_URL;
use self::current_usage_limit_nudge::prompt_subtitle as current_usage_limit_nudge_prompt_subtitle;
use self::current_usage_limit_nudge::prompt_url as current_usage_limit_nudge_prompt_url;
use self::goal_status::GoalStatusState;
#[cfg(test)]
use self::goal_status::goal_status_indicator_from_app_goal;
@@ -768,6 +780,7 @@ pub(crate) struct ChatWidget {
plan_type: Option<PlanType>,
codex_rate_limit_reached_type: Option<RateLimitReachedType>,
rate_limit_warnings: RateLimitWarningState,
current_usage_limit_nudge_prompt: CurrentUsageLimitNudgePromptState,
rate_limit_switch_prompt: RateLimitSwitchPromptState,
add_credits_nudge_email_in_flight: Option<AddCreditsNudgeCreditType>,
adaptive_chunking: AdaptiveChunkingPolicy,
@@ -2560,7 +2573,8 @@ impl ChatWidget {
if matches!(
self.rate_limit_switch_prompt,
RateLimitSwitchPromptState::Pending
) {
) || self.current_usage_limit_nudge_prompt.has_pending()
{
return;
}
@@ -2827,6 +2841,28 @@ impl ChatWidget {
}
}
pub(crate) fn on_live_rate_limit_snapshot(&mut self, snapshot: RateLimitSnapshot) {
if self.should_prefetch_current_usage_limit_nudge(&snapshot) {
self.app_event_tx.send(AppEvent::RefreshRateLimits {
origin: RateLimitRefreshOrigin::UsageNudgePrefetch,
});
}
self.on_rate_limit_snapshot(Some(snapshot));
}
fn should_prefetch_current_usage_limit_nudge(&mut self, snapshot: &RateLimitSnapshot) -> bool {
let is_codex_limit = snapshot
.limit_id
.as_deref()
.unwrap_or("codex")
.eq_ignore_ascii_case("codex");
is_codex_limit
&& self.current_usage_limit_nudge_enabled()
&& self
.current_usage_limit_nudge_prompt
.should_prefetch(snapshot.primary.as_ref())
}
pub(crate) fn on_rate_limit_snapshot(&mut self, snapshot: Option<RateLimitSnapshot>) {
if let Some(mut snapshot) = snapshot {
let limit_id = snapshot
@@ -2852,6 +2888,17 @@ 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 {
let nudge = if self.current_usage_limit_nudge_enabled() {
snapshot.current_usage_limit_nudge.clone()
} else {
None
};
self.current_usage_limit_nudge_prompt.update(nudge);
}
if self.current_usage_limit_nudge_prompt.is_active() {
self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle;
}
if is_codex_limit
&& let Some(rate_limit_reached_type) = snapshot.rate_limit_reached_type
{
@@ -2900,6 +2947,7 @@ impl ChatWidget {
if high_usage
&& !has_workspace_credits
&& !self.current_usage_limit_nudge_prompt.is_active()
&& !self.rate_limit_switch_prompt_hidden()
&& self.current_model() != NUDGE_MODEL_SLUG
&& !matches!(
@@ -2994,6 +3042,12 @@ impl ChatWidget {
.enabled(Feature::WorkspaceOwnerUsageNudge)
}
fn current_usage_limit_nudge_enabled(&self) -> bool {
self.config
.features
.enabled(Feature::CurrentUsageLimitNudge)
}
fn on_rate_limit_error(&mut self, error_kind: RateLimitErrorKind, message: String) {
if !self.workspace_owner_usage_nudge_enabled() {
self.on_error(message);
@@ -4850,6 +4904,7 @@ impl ChatWidget {
plan_type: initial_plan_type,
codex_rate_limit_reached_type: None,
rate_limit_warnings: RateLimitWarningState::default(),
current_usage_limit_nudge_prompt: CurrentUsageLimitNudgePromptState::default(),
rate_limit_switch_prompt: RateLimitSwitchPromptState::default(),
add_credits_nudge_email_in_flight: None,
adaptive_chunking: AdaptiveChunkingPolicy::default(),
@@ -7146,6 +7201,12 @@ impl ChatWidget {
}
fn maybe_show_pending_rate_limit_prompt(&mut self) {
if self.current_usage_limit_nudge_prompt.is_active() {
self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle;
}
if self.maybe_show_pending_current_usage_limit_nudge_prompt() {
return;
}
if self.rate_limit_switch_prompt_hidden() {
self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle;
return;
@@ -7164,6 +7225,64 @@ impl ChatWidget {
}
}
fn maybe_show_pending_current_usage_limit_nudge_prompt(&mut self) -> bool {
if !self.current_usage_limit_nudge_enabled() {
return false;
}
let Some(nudge) = self.current_usage_limit_nudge_prompt.take_pending() else {
return false;
};
self.open_current_usage_limit_nudge_prompt(nudge);
true
}
fn open_current_usage_limit_nudge_prompt(&mut self, nudge: UsageLimitNudge) {
if !self.bottom_pane.replace_selection_view_if_active(
RATE_LIMIT_SWITCH_PROMPT_VIEW_ID,
self.current_usage_limit_nudge_prompt_params(&nudge),
) {
self.bottom_pane
.show_selection_view(self.current_usage_limit_nudge_prompt_params(&nudge));
}
}
fn current_usage_limit_nudge_prompt_params(
&self,
nudge: &UsageLimitNudge,
) -> SelectionViewParams {
let prompt_url = current_usage_limit_nudge_prompt_url(nudge, self.plan_type).to_string();
let yes_actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
tx.send(AppEvent::OpenUrlInBrowser {
url: prompt_url.clone(),
});
})];
let items = vec![
SelectionItem {
name: "Yes".to_string(),
display_shortcut: Some(key_hint::plain(KeyCode::Char('y'))),
actions: yes_actions,
dismiss_on_select: true,
..Default::default()
},
SelectionItem {
name: "No".to_string(),
display_shortcut: Some(key_hint::plain(KeyCode::Char('n'))),
is_default: true,
dismiss_on_select: true,
..Default::default()
},
];
SelectionViewParams {
title: Some("Approaching usage limit".to_string()),
subtitle: Some(current_usage_limit_nudge_prompt_subtitle(nudge)),
footer_hint: Some(standard_popup_hint_line()),
items,
initial_selected_idx: Some(1),
..Default::default()
}
}
fn open_rate_limit_switch_prompt(&mut self, preset: ModelPreset) {
let switch_model = preset.model;
let switch_model_for_events = switch_model.clone();
@@ -7231,6 +7350,7 @@ impl ChatWidget {
];
self.bottom_pane.show_selection_view(SelectionViewParams {
view_id: Some(RATE_LIMIT_SWITCH_PROMPT_VIEW_ID),
title: Some("Approaching rate limits".to_string()),
subtitle: Some(format!("Switch to {switch_model} for lower credit usage?")),
footer_hint: Some(standard_popup_hint_line()),
@@ -9127,6 +9247,9 @@ impl ChatWidget {
self.turn_sleep_inhibitor
.set_turn_running(self.agent_turn_running);
}
if feature == Feature::CurrentUsageLimitNudge && !enabled {
self.current_usage_limit_nudge_prompt.update(None);
}
#[cfg(target_os = "windows")]
if matches!(
feature,
@@ -9143,6 +9266,11 @@ impl ChatWidget {
enabled
}
#[cfg(test)]
pub(crate) fn has_active_current_usage_limit_nudge_for_test(&self) -> bool {
self.current_usage_limit_nudge_prompt.is_active()
}
pub(crate) fn set_approvals_reviewer(&mut self, policy: ApprovalsReviewer) {
self.config.approvals_reviewer = policy;
}
@@ -0,0 +1,112 @@
use codex_app_server_protocol::RateLimitWindow;
use codex_app_server_protocol::UsageLimitNudge;
use codex_app_server_protocol::UsageLimitNudgeAction;
use codex_protocol::account::PlanType;
pub(super) const CURRENT_USAGE_LIMIT_NUDGE_URL: &str = "https://chatgpt.com/codex/settings/usage";
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)]
struct UsageNudgePrefetchKey {
window_duration_mins: Option<i64>,
resets_at: Option<i64>,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum UsageNudgePrefetchThreshold {
Percent75,
Percent90,
}
impl UsageNudgePrefetchThreshold {
fn from_used_percent(used_percent: i32) -> Option<Self> {
if used_percent >= 90 {
Some(Self::Percent90)
} else if used_percent >= 75 {
Some(Self::Percent75)
} else {
None
}
}
}
#[derive(Default)]
pub(super) struct CurrentUsageLimitNudgePromptState {
active: bool,
pending: Option<UsageLimitNudge>,
has_shown: bool,
last_prefetch: Option<(UsageNudgePrefetchKey, UsageNudgePrefetchThreshold)>,
}
impl CurrentUsageLimitNudgePromptState {
pub(super) fn update(&mut self, nudge: Option<UsageLimitNudge>) {
self.active = nudge.is_some();
self.pending = (!self.has_shown).then_some(nudge).flatten();
}
pub(super) fn take_pending(&mut self) -> Option<UsageLimitNudge> {
let nudge = self.pending.take()?;
self.has_shown = true;
Some(nudge)
}
pub(super) fn is_active(&self) -> bool {
self.active
}
pub(super) fn has_pending(&self) -> bool {
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;
};
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;
}
self.last_prefetch = Some((key, threshold));
true
}
}
pub(super) fn prompt_subtitle(nudge: &UsageLimitNudge) -> String {
let action = match nudge.action {
UsageLimitNudgeAction::AddCredits => "Add credits",
UsageLimitNudgeAction::Upgrade => "Upgrade",
};
format!(
"You're at {}% of your Codex usage limit. {action} now to keep going?",
nudge.threshold
)
}
pub(super) fn prompt_url(nudge: &UsageLimitNudge, plan_type: Option<PlanType>) -> &'static str {
match nudge.action {
UsageLimitNudgeAction::Upgrade => UPGRADE_USAGE_LIMIT_NUDGE_URL,
UsageLimitNudgeAction::AddCredits
if plan_type.is_some_and(PlanType::is_workspace_account) =>
{
WORKSPACE_OWNER_USAGE_LIMIT_NUDGE_URL
}
UsageLimitNudgeAction::AddCredits => CURRENT_USAGE_LIMIT_NUDGE_URL,
}
}
@@ -0,0 +1,35 @@
---
source: tui/src/chatwidget/tests/current_usage_limit_nudge.rs
expression: "rendered_cases.join(\"\\n---\\n\")"
---
Approaching usage limit
You're at 75% of your Codex usage limit. Add credits now to keep going?
1. Yes (y)
› 2. No (default) (n)
Press enter to confirm or esc to go back
---
Approaching usage limit
You're at 75% of your Codex usage limit. Upgrade now to keep going?
1. Yes (y)
› 2. No (default) (n)
Press enter to confirm or esc to go back
---
Approaching usage limit
You're at 90% of your Codex usage limit. Add credits now to keep going?
1. Yes (y)
› 2. No (default) (n)
Press enter to confirm or esc to go back
---
Approaching usage limit
You're at 90% of your Codex usage limit. Upgrade now to keep going?
1. Yes (y)
› 2. No (default) (n)
Press enter to confirm or esc to go back
+4
View File
@@ -8,6 +8,7 @@ pub(super) use super::*;
pub(super) use crate::app_command::AppCommand as Op;
pub(super) use crate::app_event::AppEvent;
pub(super) use crate::app_event::ExitMode;
pub(super) use crate::app_event::RateLimitRefreshOrigin;
#[cfg(not(target_os = "linux"))]
pub(super) use crate::app_event::RealtimeAudioDeviceKind;
pub(super) use crate::app_event_sender::AppEventSender;
@@ -114,6 +115,8 @@ pub(super) use codex_app_server_protocol::TurnCompletedNotification;
pub(super) use codex_app_server_protocol::TurnError as AppServerTurnError;
pub(super) use codex_app_server_protocol::TurnStartedNotification;
pub(super) use codex_app_server_protocol::TurnStatus as AppServerTurnStatus;
pub(super) use codex_app_server_protocol::UsageLimitNudge;
pub(super) use codex_app_server_protocol::UsageLimitNudgeAction;
pub(super) use codex_app_server_protocol::UserInput;
pub(super) use codex_app_server_protocol::UserInput as AppServerUserInput;
pub(super) use codex_app_server_protocol::WarningNotification;
@@ -222,6 +225,7 @@ macro_rules! assert_chatwidget_snapshot {
mod app_server;
mod approval_requests;
mod composer_submission;
mod current_usage_limit_nudge;
mod exec_flow;
mod goal_menu;
mod guardian;
@@ -0,0 +1,324 @@
use super::*;
use pretty_assertions::assert_eq;
fn snapshot_with_nudge(threshold: u8, action: UsageLimitNudgeAction) -> RateLimitSnapshot {
RateLimitSnapshot {
current_usage_limit_nudge: Some(UsageLimitNudge { threshold, action }),
..snapshot(f64::from(threshold))
}
}
fn next_open_url_event(rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>) -> Option<String> {
while let Ok(event) = rx.try_recv() {
if let AppEvent::OpenUrlInBrowser { url } = event {
return Some(url);
}
}
None
}
fn next_rate_limit_refresh_origin(
rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
) -> Option<RateLimitRefreshOrigin> {
while let Ok(event) = rx.try_recv() {
if let AppEvent::RefreshRateLimits { origin } = event {
return Some(origin);
}
}
None
}
#[tokio::test]
async fn proactive_usage_prompt_renders_backend_actions() {
let mut rendered_cases = Vec::new();
for (threshold, action) in [
(75, UsageLimitNudgeAction::AddCredits),
(75, UsageLimitNudgeAction::Upgrade),
(90, UsageLimitNudgeAction::AddCredits),
(90, UsageLimitNudgeAction::Upgrade),
] {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_rate_limit_snapshot(Some(snapshot_with_nudge(threshold, action)));
chat.maybe_show_pending_rate_limit_prompt();
rendered_cases.push(render_bottom_popup(&chat, /*width*/ 88));
}
assert_chatwidget_snapshot!(
"proactive_usage_prompt_variants",
rendered_cases.join("\n---\n")
);
}
#[tokio::test]
async fn proactive_usage_prompt_shows_only_once_per_session() {
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,
)));
assert!(chat.maybe_show_pending_current_usage_limit_nudge_prompt());
chat.on_rate_limit_snapshot(Some(snapshot_with_nudge(
/*threshold*/ 90,
UsageLimitNudgeAction::Upgrade,
)));
assert!(!chat.maybe_show_pending_current_usage_limit_nudge_prompt());
}
#[tokio::test]
async fn proactive_usage_prompt_empty_snapshot_does_not_queue_prompt() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
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;
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 74.0));
assert_eq!(next_rate_limit_refresh_origin(&mut rx), None);
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 75.0));
assert_eq!(
next_rate_limit_refresh_origin(&mut rx),
Some(RateLimitRefreshOrigin::UsageNudgePrefetch)
);
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 80.0));
assert_eq!(next_rate_limit_refresh_origin(&mut rx), None);
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 90.0));
assert_eq!(
next_rate_limit_refresh_origin(&mut rx),
Some(RateLimitRefreshOrigin::UsageNudgePrefetch)
);
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 95.0));
assert_eq!(next_rate_limit_refresh_origin(&mut rx), None);
}
#[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;
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 92.0));
assert_eq!(
next_rate_limit_refresh_origin(&mut rx),
Some(RateLimitRefreshOrigin::UsageNudgePrefetch)
);
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 95.0));
assert_eq!(next_rate_limit_refresh_origin(&mut rx), None);
}
#[tokio::test]
async fn proactive_usage_prompt_prefetches_again_after_primary_window_rolls_over() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
let mut first_window = snapshot(/*percent*/ 75.0);
first_window.primary.as_mut().expect("primary").resets_at = Some(100);
let mut second_window = snapshot(/*percent*/ 75.0);
second_window.primary.as_mut().expect("primary").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;
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 75.0));
assert_eq!(
next_rate_limit_refresh_origin(&mut rx),
Some(RateLimitRefreshOrigin::UsageNudgePrefetch)
);
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 74.0));
assert_eq!(next_rate_limit_refresh_origin(&mut rx), None);
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 80.0));
assert_eq!(next_rate_limit_refresh_origin(&mut rx), None);
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 90.0));
assert_eq!(
next_rate_limit_refresh_origin(&mut rx),
Some(RateLimitRefreshOrigin::UsageNudgePrefetch)
);
}
#[tokio::test]
async fn proactive_usage_prompt_empty_prefetch_result_does_not_queue_prompt() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 75.0));
assert_eq!(
next_rate_limit_refresh_origin(&mut rx),
Some(RateLimitRefreshOrigin::UsageNudgePrefetch)
);
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_yes_opens_expected_destination() {
for (plan_type, action, expected_url) in [
(
None,
UsageLimitNudgeAction::Upgrade,
UPGRADE_USAGE_LIMIT_NUDGE_URL,
),
(
None,
UsageLimitNudgeAction::AddCredits,
CURRENT_USAGE_LIMIT_NUDGE_URL,
),
(
Some(PlanType::SelfServeBusinessUsageBased),
UsageLimitNudgeAction::AddCredits,
WORKSPACE_OWNER_USAGE_LIMIT_NUDGE_URL,
),
] {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.plan_type = plan_type;
chat.on_rate_limit_snapshot(Some(snapshot_with_nudge(/*threshold*/ 90, action)));
chat.maybe_show_pending_rate_limit_prompt();
chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
assert_eq!(next_open_url_event(&mut rx), Some(expected_url.to_string()));
}
}
#[tokio::test]
async fn proactive_usage_prompt_no_dismisses_without_opening_browser() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_rate_limit_snapshot(Some(snapshot_with_nudge(
/*threshold*/ 90,
UsageLimitNudgeAction::Upgrade,
)));
chat.maybe_show_pending_rate_limit_prompt();
chat.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
assert_eq!(next_open_url_event(&mut rx), None);
}
#[tokio::test]
async fn proactive_usage_prompt_waits_for_between_turn_hook() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_live_rate_limit_snapshot(snapshot(/*percent*/ 75.0));
assert_eq!(
next_rate_limit_refresh_origin(&mut rx),
Some(RateLimitRefreshOrigin::UsageNudgePrefetch)
);
chat.on_rate_limit_snapshot(Some(snapshot_with_nudge(
/*threshold*/ 75,
UsageLimitNudgeAction::AddCredits,
)));
let popup = render_bottom_popup(&chat, /*width*/ 88);
assert!(!popup.contains("Approaching usage limit"), "popup: {popup}");
chat.maybe_show_pending_rate_limit_prompt();
assert!(render_bottom_popup(&chat, /*width*/ 88).contains("Approaching usage limit"));
}
#[tokio::test]
async fn proactive_usage_prompt_flag_disabled_skips_prompt_and_keeps_passive_warning() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.set_feature_enabled(Feature::CurrentUsageLimitNudge, /*enabled*/ false);
chat.on_rate_limit_snapshot(Some(snapshot_with_nudge(
/*threshold*/ 90,
UsageLimitNudgeAction::AddCredits,
)));
assert!(!chat.maybe_show_pending_current_usage_limit_nudge_prompt());
let popup = render_bottom_popup(&chat, /*width*/ 88);
assert!(!popup.contains("Approaching usage limit"), "popup: {popup}");
let rendered = drain_insert_history(&mut rx)
.into_iter()
.map(|lines| lines_to_single_string(&lines))
.collect::<String>();
assert!(
rendered.contains("less than 10% of your 1h limit left"),
"rendered: {rendered}"
);
}
#[tokio::test]
async fn proactive_usage_prompt_flag_disable_clears_already_queued_prompt() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_rate_limit_snapshot(Some(snapshot_with_nudge(
/*threshold*/ 90,
UsageLimitNudgeAction::AddCredits,
)));
chat.set_feature_enabled(Feature::CurrentUsageLimitNudge, /*enabled*/ false);
assert!(!chat.maybe_show_pending_current_usage_limit_nudge_prompt());
let popup = render_bottom_popup(&chat, /*width*/ 88);
assert!(!popup.contains("Approaching usage limit"), "popup: {popup}");
}
#[tokio::test]
async fn proactive_usage_prompt_suppresses_later_rate_limit_switch_prompt() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.on_rate_limit_snapshot(Some(snapshot_with_nudge(
/*threshold*/ 90,
UsageLimitNudgeAction::AddCredits,
)));
assert!(matches!(
chat.rate_limit_switch_prompt,
RateLimitSwitchPromptState::Idle
));
chat.maybe_show_pending_rate_limit_prompt();
chat.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
chat.maybe_show_pending_rate_limit_prompt();
let popup = render_bottom_popup(&chat, /*width*/ 88);
assert!(!popup.contains("Approaching rate limits"), "popup: {popup}");
assert!(matches!(
chat.rate_limit_switch_prompt,
RateLimitSwitchPromptState::Idle
));
}
#[tokio::test]
async fn proactive_usage_prompt_replaces_shown_rate_limit_switch_prompt() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.has_chatgpt_account = true;
chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 92.0)));
chat.maybe_show_pending_rate_limit_prompt();
assert!(render_bottom_popup(&chat, /*width*/ 88).contains("Approaching rate limits"));
chat.on_rate_limit_snapshot(Some(snapshot_with_nudge(
/*threshold*/ 90,
UsageLimitNudgeAction::AddCredits,
)));
chat.maybe_show_pending_rate_limit_prompt();
let popup = render_bottom_popup(&chat, /*width*/ 88);
assert!(popup.contains("Approaching usage limit"), "popup: {popup}");
assert!(!popup.contains("Approaching rate limits"), "popup: {popup}");
chat.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
let popup = render_bottom_popup(&chat, /*width*/ 88);
assert!(!popup.contains("Approaching rate limits"), "popup: {popup}");
}
@@ -208,6 +208,7 @@ pub(super) async fn make_chatwidget_manual(
plan_type: None,
codex_rate_limit_reached_type: None,
rate_limit_warnings: RateLimitWarningState::default(),
current_usage_limit_nudge_prompt: CurrentUsageLimitNudgePromptState::default(),
rate_limit_switch_prompt: RateLimitSwitchPromptState::default(),
add_credits_nudge_email_in_flight: None,
adaptive_chunking: crate::streaming::chunking::AdaptiveChunkingPolicy::default(),
@@ -1094,6 +1094,45 @@ async fn plan_implementation_popup_skips_when_rate_limit_prompt_pending() {
);
}
#[tokio::test]
async fn plan_implementation_popup_skips_when_usage_limit_nudge_pending() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.has_chatgpt_account = true;
chat.set_feature_enabled(Feature::CollaborationModes, /*enabled*/ true);
let plan_mask = collaboration_modes::mask_for_kind(chat.model_catalog.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
chat.set_collaboration_mask(plan_mask);
chat.on_task_started();
chat.on_plan_update(UpdatePlanArgs {
explanation: None,
plan: vec![PlanItemArg {
step: "First".to_string(),
status: StepStatus::Pending,
}],
});
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
current_usage_limit_nudge: Some(UsageLimitNudge {
threshold: 90,
action: UsageLimitNudgeAction::AddCredits,
}),
..snapshot(/*percent*/ 92.0)
}));
chat.on_task_complete(
/*last_agent_message*/ None, /*duration_ms*/ None, /*from_replay*/ false,
);
let popup = render_bottom_popup(&chat, /*width*/ 80);
assert!(
popup.contains("Approaching usage limit"),
"expected usage-limit popup, got {popup:?}"
);
assert!(
!popup.contains(PLAN_IMPLEMENTATION_TITLE),
"expected plan popup to be skipped, got {popup:?}"
);
}
#[tokio::test]
async fn plan_completion_restores_status_indicator_after_streaming_plan_output() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;