Add proactive Codex usage prompt

This commit is contained in:
James Chu
2026-04-27 01:25:40 -04:00
parent 040976b218
commit 9aa3206b11
6 changed files with 347 additions and 0 deletions
+3
View File
@@ -302,6 +302,9 @@ impl App {
AppEvent::OpenUrlInBrowser { url } => {
self.open_url_in_browser(url);
}
AppEvent::AddInfoMessage { message } => {
self.chat_widget.add_info_message(message, /*hint*/ None);
}
AppEvent::RefreshConnectors { force_refetch } => {
self.chat_widget.refresh_connectors(force_refetch);
}
+5
View File
@@ -228,6 +228,11 @@ pub(crate) enum AppEvent {
url: String,
},
/// Add an informational message to the transcript.
AddInfoMessage {
message: String,
},
/// Refresh app connector state and mention bindings.
RefreshConnectors {
force_refetch: bool,
+159
View File
@@ -201,6 +201,7 @@ use codex_protocol::protocol::Op;
use codex_protocol::protocol::PatchApplyBeginEvent;
use codex_protocol::protocol::RateLimitReachedType;
use codex_protocol::protocol::RateLimitSnapshot;
use codex_protocol::protocol::RateLimitWindow;
use codex_protocol::protocol::ReviewRequest;
use codex_protocol::protocol::ReviewTarget;
use codex_protocol::protocol::SkillMetadata as ProtocolSkillMetadata;
@@ -479,6 +480,11 @@ fn is_standard_tool_call(parsed_cmd: &[ParsedCommand]) -> bool {
const RATE_LIMIT_WARNING_THRESHOLDS: [f64; 3] = [75.0, 90.0, 95.0];
const NUDGE_MODEL_SLUG: &str = "gpt-5.4-mini";
const RATE_LIMIT_SWITCH_PROMPT_THRESHOLD: f64 = 90.0;
const PROACTIVE_USAGE_PROMPT_THRESHOLD: f64 = 90.0;
const PROACTIVE_USAGE_PROMPT_USAGE_URL: &str = "https://chatgpt.com/codex/settings/usage?utm_source=codex_cli&utm_medium=cli&utm_campaign=usage_limit_prompt&utm_content=threshold_90";
const PROACTIVE_USAGE_PROMPT_PRO_URL: &str = "https://chatgpt.com/explore/pro?utm_source=codex_cli&utm_medium=cli&utm_campaign=usage_limit_prompt&utm_content=threshold_90";
const PROACTIVE_USAGE_PROMPT_BROWSER_MESSAGE: &str =
"Finish in your browser, then return here to continue.";
const MAX_AGENT_COPY_HISTORY: usize = 32;
#[derive(Debug)]
@@ -552,6 +558,21 @@ impl RateLimitWarningState {
}
}
fn rate_limit_snapshot_crosses_proactive_prompt_threshold(snapshot: &RateLimitSnapshot) -> bool {
snapshot
.primary
.as_ref()
.is_some_and(rate_limit_window_crosses_proactive_prompt_threshold)
|| snapshot
.secondary
.as_ref()
.is_some_and(rate_limit_window_crosses_proactive_prompt_threshold)
}
fn rate_limit_window_crosses_proactive_prompt_threshold(window: &RateLimitWindow) -> bool {
window.used_percent >= PROACTIVE_USAGE_PROMPT_THRESHOLD && window.used_percent < 100.0
}
pub(crate) fn get_limits_duration(windows_minutes: i64) -> String {
const MINUTES_PER_HOUR: i64 = 60;
const MINUTES_PER_DAY: i64 = 24 * MINUTES_PER_HOUR;
@@ -604,6 +625,20 @@ enum RateLimitSwitchPromptState {
Shown,
}
#[derive(Default)]
enum ProactiveUsagePromptState {
#[default]
Idle,
Pending,
Shown,
}
struct ProactiveUsagePromptContent {
action_label: &'static str,
subtitle: &'static str,
url: &'static str,
}
#[derive(Debug, Clone, Default)]
enum ConnectorsCacheState {
#[default]
@@ -811,6 +846,7 @@ pub(crate) struct ChatWidget {
codex_rate_limit_reached_type: Option<RateLimitReachedType>,
rate_limit_warnings: RateLimitWarningState,
rate_limit_switch_prompt: RateLimitSwitchPromptState,
proactive_usage_prompt: ProactiveUsagePromptState,
add_credits_nudge_email_in_flight: Option<AddCreditsNudgeCreditType>,
adaptive_chunking: AdaptiveChunkingPolicy,
// Stream lifecycle controller
@@ -2989,8 +3025,15 @@ impl ChatWidget {
.as_ref()
.map(|credits| credits.has_credits)
.unwrap_or(false);
let proactive_usage_prompt_eligible =
is_codex_limit && self.should_show_proactive_usage_prompt(&snapshot);
if proactive_usage_prompt_eligible {
self.proactive_usage_prompt = ProactiveUsagePromptState::Pending;
}
if high_usage
&& !proactive_usage_prompt_eligible
&& !has_workspace_credits
&& !self.rate_limit_switch_prompt_hidden()
&& self.current_model() != NUDGE_MODEL_SLUG
@@ -5204,6 +5247,7 @@ impl ChatWidget {
codex_rate_limit_reached_type: None,
rate_limit_warnings: RateLimitWarningState::default(),
rate_limit_switch_prompt: RateLimitSwitchPromptState::default(),
proactive_usage_prompt: ProactiveUsagePromptState::default(),
add_credits_nudge_email_in_flight: None,
adaptive_chunking: AdaptiveChunkingPolicy::default(),
stream_controller: None,
@@ -7974,7 +8018,67 @@ impl ChatWidget {
.unwrap_or(false)
}
fn should_show_proactive_usage_prompt(&self, snapshot: &RateLimitSnapshot) -> bool {
if !self.has_chatgpt_account
|| !matches!(self.proactive_usage_prompt, ProactiveUsagePromptState::Idle)
|| !rate_limit_snapshot_crosses_proactive_prompt_threshold(snapshot)
{
return false;
}
let plan_type = snapshot.plan_type.or(self.plan_type);
let paid_personal_user = matches!(
plan_type,
Some(PlanType::Plus | PlanType::Pro | PlanType::ProLite)
);
let workspace_owner = matches!(
snapshot
.rate_limit_reached_type
.or(self.codex_rate_limit_reached_type),
Some(
RateLimitReachedType::WorkspaceOwnerCreditsDepleted
| RateLimitReachedType::WorkspaceOwnerUsageLimitReached
)
);
paid_personal_user || workspace_owner
}
fn proactive_usage_prompt_content(&self) -> Option<ProactiveUsagePromptContent> {
let workspace_owner = matches!(
self.codex_rate_limit_reached_type,
Some(
RateLimitReachedType::WorkspaceOwnerCreditsDepleted
| RateLimitReachedType::WorkspaceOwnerUsageLimitReached
)
);
if workspace_owner {
return Some(ProactiveUsagePromptContent {
action_label: "Review usage options",
subtitle: "You've used at least 90% of your Codex usage limit. Review usage options to keep going?",
url: PROACTIVE_USAGE_PROMPT_USAGE_URL,
});
}
match self.plan_type {
Some(PlanType::Plus) => Some(ProactiveUsagePromptContent {
action_label: "Upgrade now",
subtitle: "You've used at least 90% of your Codex usage limit. Upgrade now to keep going?",
url: PROACTIVE_USAGE_PROMPT_PRO_URL,
}),
Some(PlanType::Pro | PlanType::ProLite) => Some(ProactiveUsagePromptContent {
action_label: "Buy credits",
subtitle: "You've used at least 90% of your Codex usage limit. Buy credits to keep going?",
url: PROACTIVE_USAGE_PROMPT_USAGE_URL,
}),
_ => None,
}
}
fn maybe_show_pending_rate_limit_prompt(&mut self) {
if self.maybe_show_pending_proactive_usage_prompt() {
return;
}
if self.rate_limit_switch_prompt_hidden() {
self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle;
return;
@@ -7993,6 +8097,61 @@ impl ChatWidget {
}
}
fn maybe_show_pending_proactive_usage_prompt(&mut self) -> bool {
if !matches!(
self.proactive_usage_prompt,
ProactiveUsagePromptState::Pending
) {
return false;
}
self.open_proactive_usage_prompt();
self.proactive_usage_prompt = ProactiveUsagePromptState::Shown;
true
}
fn open_proactive_usage_prompt(&mut self) {
let Some(content) = self.proactive_usage_prompt_content() else {
self.proactive_usage_prompt = ProactiveUsagePromptState::Idle;
return;
};
let url = content.url;
let yes_actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
tx.send(AppEvent::OpenUrlInBrowser {
url: url.to_string(),
});
tx.send(AppEvent::AddInfoMessage {
message: PROACTIVE_USAGE_PROMPT_BROWSER_MESSAGE.to_string(),
});
})];
let items = vec![
SelectionItem {
name: content.action_label.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()
},
];
self.bottom_pane.show_selection_view(SelectionViewParams {
title: Some("Approaching usage limit".to_string()),
subtitle: Some(content.subtitle.to_string()),
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();
@@ -0,0 +1,11 @@
---
source: tui/src/chatwidget/tests/status_and_layout.rs
expression: popup
---
Approaching usage limit
You've used at least 90% of your Codex usage limit. Upgrade now to keep going?
1. Upgrade now (y)
› 2. No (default) (n)
Press enter to confirm or esc to go back
@@ -206,6 +206,7 @@ pub(super) async fn make_chatwidget_manual(
codex_rate_limit_reached_type: None,
rate_limit_warnings: RateLimitWarningState::default(),
rate_limit_switch_prompt: RateLimitSwitchPromptState::default(),
proactive_usage_prompt: ProactiveUsagePromptState::default(),
add_credits_nudge_email_in_flight: None,
adaptive_chunking: crate::streaming::chunking::AdaptiveChunkingPolicy::default(),
stream_controller: None,
@@ -541,6 +541,138 @@ async fn rate_limit_switch_prompt_popup_snapshot() {
assert_chatwidget_snapshot!("rate_limit_switch_prompt_popup", popup);
}
#[tokio::test]
async fn proactive_usage_prompt_skips_75_percent() {
let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
chat.has_chatgpt_account = true;
let mut limits = snapshot(/*percent*/ 75.0);
limits.plan_type = Some(PlanType::Plus);
chat.on_rate_limit_snapshot(Some(limits));
assert!(matches!(
chat.proactive_usage_prompt,
ProactiveUsagePromptState::Idle
));
}
#[tokio::test]
async fn proactive_usage_prompt_shows_for_paid_personal_user_at_90_percent() {
let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
chat.has_chatgpt_account = true;
let mut limits = snapshot(/*percent*/ 90.0);
limits.plan_type = Some(PlanType::Plus);
chat.on_rate_limit_snapshot(Some(limits));
assert!(matches!(
chat.proactive_usage_prompt,
ProactiveUsagePromptState::Pending
));
assert!(matches!(
chat.rate_limit_switch_prompt,
RateLimitSwitchPromptState::Idle
));
chat.maybe_show_pending_rate_limit_prompt();
assert!(matches!(
chat.proactive_usage_prompt,
ProactiveUsagePromptState::Shown
));
let popup = render_bottom_popup(&chat, /*width*/ 90);
assert_chatwidget_snapshot!("proactive_usage_prompt", popup);
}
#[tokio::test]
async fn proactive_usage_prompt_yes_opens_usage_url_with_utm_params() {
let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
chat.has_chatgpt_account = true;
let mut limits = snapshot(/*percent*/ 92.0);
limits.plan_type = Some(PlanType::Pro);
chat.on_rate_limit_snapshot(Some(limits));
chat.maybe_show_pending_rate_limit_prompt();
chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
let (url, message) = next_open_url_and_info_message_events(&mut rx);
assert_eq!(url, PROACTIVE_USAGE_PROMPT_USAGE_URL);
assert_eq!(message, PROACTIVE_USAGE_PROMPT_BROWSER_MESSAGE);
}
#[tokio::test]
async fn proactive_usage_prompt_plus_user_opens_upgrade_url_with_utm_params() {
let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
chat.has_chatgpt_account = true;
let mut limits = snapshot(/*percent*/ 92.0);
limits.plan_type = Some(PlanType::Plus);
chat.on_rate_limit_snapshot(Some(limits));
chat.maybe_show_pending_rate_limit_prompt();
chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
let (url, message) = next_open_url_and_info_message_events(&mut rx);
assert_eq!(url, PROACTIVE_USAGE_PROMPT_PRO_URL);
assert_eq!(message, PROACTIVE_USAGE_PROMPT_BROWSER_MESSAGE);
}
#[tokio::test]
async fn proactive_usage_prompt_no_suppresses_repeat_prompts() {
let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await;
chat.has_chatgpt_account = true;
let mut limits = snapshot(/*percent*/ 90.0);
limits.plan_type = Some(PlanType::Plus);
chat.on_rate_limit_snapshot(Some(limits));
chat.maybe_show_pending_rate_limit_prompt();
chat.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
let mut later_limits = snapshot(/*percent*/ 95.0);
later_limits.plan_type = Some(PlanType::Plus);
chat.on_rate_limit_snapshot(Some(later_limits));
chat.maybe_show_pending_rate_limit_prompt();
assert!(matches!(
chat.proactive_usage_prompt,
ProactiveUsagePromptState::Shown
));
assert_no_open_url_or_info_message(&mut rx);
}
#[tokio::test]
async fn proactive_usage_prompt_excludes_workspace_member_without_owner_signal() {
let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
chat.has_chatgpt_account = true;
let mut limits = snapshot(/*percent*/ 90.0);
limits.plan_type = Some(PlanType::Team);
chat.on_rate_limit_snapshot(Some(limits));
assert!(matches!(
chat.proactive_usage_prompt,
ProactiveUsagePromptState::Idle
));
}
#[tokio::test]
async fn proactive_usage_prompt_allows_explicit_workspace_owner_signal() {
let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await;
chat.has_chatgpt_account = true;
let mut limits = snapshot(/*percent*/ 90.0);
limits.plan_type = Some(PlanType::Team);
limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceOwnerUsageLimitReached);
chat.on_rate_limit_snapshot(Some(limits));
assert!(matches!(
chat.proactive_usage_prompt,
ProactiveUsagePromptState::Pending
));
assert!(matches!(
chat.rate_limit_switch_prompt,
RateLimitSwitchPromptState::Idle
));
}
#[tokio::test]
async fn workspace_owner_usage_nudge_flag_disabled_keeps_generic_rate_limit_error() {
{
@@ -891,6 +1023,42 @@ fn next_send_add_credits_nudge_email_event(
panic!("expected SendAddCreditsNudgeEmail app event");
}
fn next_open_url_and_info_message_events(
rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
) -> (String, String) {
let mut url = None;
let mut message = None;
while let Ok(event) = rx.try_recv() {
match event {
AppEvent::OpenUrlInBrowser { url: event_url } => {
url = Some(event_url);
}
AppEvent::AddInfoMessage {
message: event_message,
} => {
message = Some(event_message);
}
_ => {}
}
}
(
url.expect("expected OpenUrlInBrowser app event"),
message.expect("expected AddInfoMessage app event"),
)
}
fn assert_no_open_url_or_info_message(rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>) {
while let Ok(event) = rx.try_recv() {
assert!(
!matches!(
event,
AppEvent::OpenUrlInBrowser { .. } | AppEvent::AddInfoMessage { .. }
),
"unexpected event: {event:?}"
);
}
}
fn assert_no_owner_nudge_or_rate_limit_refresh(
rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
) {