mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Keep quota warnings visible in the TUI (#46912)
## Why Quota warnings were hidden from normal transcript rendering, leaving no persistent reminder of remaining usage near the composer. ## What changed - Show the most constrained quota window in the existing composer hint row, using the existing plan-specific warning thresholds. Include remaining usage, reset time, and `/status` when space permits. - Keep the notice visible while typing or running a turn, even with tooltips disabled. Yield to interaction controls and blocking banners, and suppress the notice when usable credits are available. - Preserve quota metadata across sparse updates and thread switches. Require a fresh account usage read to confirm recovery, ignore reads made stale by newer rolling updates, and clear notice state on account changes. - Render quota warning history cells in both transcript modes while retaining warning counts and replay deduplication. ## Testing Add unit, integration, and snapshot coverage for warning thresholds, narrow layouts, unchanged composer geometry, suppression, recovery, overlapping reads, account changes, and native transcript replay. GitOrigin-RevId: e45dc94a6e7a9dad50307840b9fdb15978d053dc
This commit is contained in:
@@ -75,7 +75,7 @@ impl App {
|
||||
/// Recovery requests are coalesced and bounded by the reset-request timeout. The origin
|
||||
/// also identifies command-specific completion work, such as finalizing a `/status` card,
|
||||
/// without confusing sparse inference notifications with authoritative usage responses.
|
||||
pub(super) fn refresh_rate_limits(
|
||||
pub(crate) fn refresh_rate_limits(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
origin: RateLimitRefreshOrigin,
|
||||
@@ -93,6 +93,7 @@ impl App {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.chat_widget.start_usage_notice_read(request_id);
|
||||
let request_handle = app_server.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Stable, contextual discovery in unused composer-gap space.
|
||||
//! Hints change with conversation state, never on a timer, and honor show_tooltips.
|
||||
//! Usage warnings and contextual discovery share the existing composer-gap row.
|
||||
//! Interaction controls take priority; only discovery tips require idle input and show_tooltips.
|
||||
|
||||
use super::*;
|
||||
use crate::history_cell::SessionInfoCell;
|
||||
@@ -10,11 +10,8 @@ use ratatui::style::Styled;
|
||||
use ratatui::text::Line;
|
||||
|
||||
impl App {
|
||||
pub(super) fn composer_tip(&self) -> Option<Line<'static>> {
|
||||
if !self.local_settings.tui.show_tooltips
|
||||
|| !self.chat_widget.composer_is_empty()
|
||||
|| self.chat_widget.is_user_turn_pending_or_running()
|
||||
|| !self.chat_widget.no_modal_or_popup_active()
|
||||
pub(super) fn composer_hint(&self, width: u16) -> Option<Line<'static>> {
|
||||
if !self.chat_widget.no_modal_or_popup_active()
|
||||
|| !self.transcript_view.is_following()
|
||||
|| self.transcript_view.has_active_interaction()
|
||||
|| self.backtrack.primed
|
||||
@@ -22,6 +19,15 @@ impl App {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if let Some(notice) = self.chat_widget.usage_notice(width) {
|
||||
return Some(notice);
|
||||
}
|
||||
if !self.local_settings.tui.show_tooltips
|
||||
|| !self.chat_widget.composer_is_empty()
|
||||
|| self.chat_widget.is_user_turn_pending_or_running()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Cosmetic tip rotation needs cell types, not a scan of every prompt's text.
|
||||
let count = self
|
||||
.transcript_cells
|
||||
|
||||
@@ -1,8 +1,146 @@
|
||||
//! Discovery yields to input and reflects configured shortcuts.
|
||||
//! Composer hints preserve input geometry and yield to interaction controls.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::RateLimitSnapshot;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use codex_app_server_protocol::TurnItemsView;
|
||||
use codex_app_server_protocol::TurnStartedNotification;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn quota(used_percent: i32) -> RateLimitSnapshot {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"primary": {"usedPercent": used_percent, "windowDurationMins": 300},
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_notice_preserves_composer_geometry_and_restores_tip_on_recovery() -> Result<()> {
|
||||
let mut snapshots = Vec::new();
|
||||
for (width, running, used_percent) in [(80, false, 92), (32, true, 101), (18, true, 95)] {
|
||||
let (mut app, mut events, _ops) = crate::app::tests::make_test_app_with_channels().await;
|
||||
app.local_settings.tui.show_tooltips = !running;
|
||||
app.local_settings.tui.animations = false;
|
||||
app.transcript_cells
|
||||
.push(Arc::new(crate::history_cell::PlainHistoryCell::new(vec![
|
||||
"Conversation".into(),
|
||||
])));
|
||||
if running {
|
||||
app.chat_widget.apply_external_edit("draft stays".into());
|
||||
app.chat_widget.handle_server_notification(
|
||||
ServerNotification::TurnStarted(TurnStartedNotification {
|
||||
thread_id: ThreadId::new().to_string(),
|
||||
turn: Turn {
|
||||
id: "turn".into(),
|
||||
items_view: TurnItemsView::Full,
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::InProgress,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
}),
|
||||
/*replay_kind*/ None,
|
||||
);
|
||||
assert!(app.chat_widget.is_user_turn_pending_or_running());
|
||||
}
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
let size = Size::new(width, /*height*/ 10);
|
||||
tui.terminal.resize(size)?;
|
||||
let before = app.render_owned_transcript(&mut tui, size)?;
|
||||
let cursor = tui.terminal.last_known_cursor_pos;
|
||||
let tip = app.composer_hint(width.saturating_sub(/*rhs*/ 2));
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(quota(used_percent)));
|
||||
while let Ok(event) = events.try_recv() {
|
||||
if let AppEvent::InsertHistoryCell(cell) = event {
|
||||
app.insert_history_cell(&mut tui, cell);
|
||||
}
|
||||
}
|
||||
assert_eq!(app.render_owned_transcript(&mut tui, size)?, before);
|
||||
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
|
||||
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
let screen = buffer
|
||||
.content()
|
||||
.chunks(usize::from(buffer.area.width))
|
||||
.map(|row| {
|
||||
row.iter()
|
||||
.map(ratatui::buffer::Cell::symbol)
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_owned()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
snapshots.push(format!("{width} columns, running={running}\n{screen}"));
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(quota(/*used_percent*/ 10)));
|
||||
assert_eq!(app.composer_hint(width.saturating_sub(/*rhs*/ 2)), tip);
|
||||
assert_eq!(app.render_owned_transcript(&mut tui, size)?, before);
|
||||
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
}
|
||||
insta::assert_snapshot!(
|
||||
"composer_usage_notice",
|
||||
crate::chatwidget::tests::helpers::normalize_snapshot_paths(snapshots.join("\n\n")),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_notice_yields_to_interactions_and_blocking_banners() {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
app.local_settings.tui.show_tooltips = true;
|
||||
let tip = app.composer_hint(/*width*/ 80);
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(quota(/*used_percent*/ 92)));
|
||||
let notice = app.composer_hint(/*width*/ 80);
|
||||
assert!(notice.is_some());
|
||||
assert_ne!(notice, tip);
|
||||
app.transcript_view.begin_search();
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), None);
|
||||
app.transcript_view = Default::default();
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), notice);
|
||||
app.chat_widget.open_warnings(&app.transcript_cells);
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), None);
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), notice);
|
||||
|
||||
for (spend_control, reached_type) in [
|
||||
(Some(true), None),
|
||||
(
|
||||
None,
|
||||
Some(codex_app_server_protocol::RateLimitReachedType::RateLimitReached),
|
||||
),
|
||||
] {
|
||||
let mut update = quota(/*used_percent*/ 92);
|
||||
update.spend_control_reached = spend_control;
|
||||
update.rate_limit_reached_type = reached_type;
|
||||
app.chat_widget.on_rate_limit_snapshot(Some(update));
|
||||
assert_eq!(app.chat_widget.usage_notice(/*width*/ 80), None);
|
||||
}
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(quota(/*used_percent*/ 92)));
|
||||
assert_eq!(app.chat_widget.usage_notice(/*width*/ 80), notice);
|
||||
app.chat_widget.update_backend_banner(
|
||||
&serde_json::from_value(serde_json::json!({
|
||||
"rateLimits": quota(/*used_percent*/ 92),
|
||||
"rateLimitUpsell": {
|
||||
"banner_type": "selected_model_limit", "title": "Usage limit reached",
|
||||
"description": "Choose another model.", "ctas": [],
|
||||
},
|
||||
}))
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(app.chat_widget.usage_notice(/*width*/ 80), None);
|
||||
app.chat_widget.clear_backend_banner();
|
||||
assert_eq!(app.chat_widget.usage_notice(/*width*/ 80), notice);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hints_respect_settings_drafts_and_custom_shortcuts() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
@@ -39,13 +177,13 @@ async fn hints_respect_settings_drafts_and_custom_shortcuts() -> Result<()> {
|
||||
crate::chatwidget::tests::helpers::normalize_snapshot_paths(snapshots.join("\n\n")),
|
||||
);
|
||||
app.keymap.app.find_transcript.clear();
|
||||
assert_eq!(app.composer_tip(), None);
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), None);
|
||||
app.transcript_cells.clear();
|
||||
app.chat_widget.apply_external_edit("draft".into());
|
||||
assert_eq!(app.composer_tip(), None);
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), None);
|
||||
app.chat_widget.apply_external_edit(String::new());
|
||||
app.local_settings.tui.show_tooltips = false;
|
||||
assert_eq!(app.composer_tip(), None);
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), None);
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ use codex_app_server_protocol::WindowsSandboxSetupMode;
|
||||
pub(super) const SHUTDOWN_FIRST_EXIT_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 2);
|
||||
|
||||
impl App {
|
||||
pub(super) async fn handle_event(
|
||||
pub(crate) async fn handle_event(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
@@ -1570,6 +1570,7 @@ impl App {
|
||||
let rate_limit_reset_credits = response.rate_limit_reset_credits.clone();
|
||||
let snapshots = if accepted
|
||||
{
|
||||
self.chat_widget.apply_usage_notice_read(request_id);
|
||||
self.chat_widget.update_backend_banner(&response);
|
||||
self.apply_backend_banner_fallback(app_server).await;
|
||||
app_server_rate_limit_snapshots(response)
|
||||
|
||||
@@ -1,10 +1,50 @@
|
||||
//! Native tool completion is emitted once, before output queued behind it.
|
||||
//! Native output preserves ordering, quota warning visibility, and replay consistency.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::DynamicToolCallOutputContentItem;
|
||||
use codex_app_server_protocol::DynamicToolCallStatus;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_warnings_are_emitted_once_and_survive_native_replay() -> Result<()> {
|
||||
for initial_replay in [false, true] {
|
||||
let (mut app, mut events, _ops) = crate::app::tests::make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
if initial_replay {
|
||||
app.begin_initial_history_replay_buffer();
|
||||
}
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::new_warning_event("Hidden diagnostic".into())),
|
||||
);
|
||||
let quota: codex_app_server_protocol::RateLimitSnapshot =
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"primary": {"usedPercent": 80, "windowDurationMins": 300},
|
||||
}))?;
|
||||
for _ in 0..2 {
|
||||
app.chat_widget.on_rate_limit_snapshot(Some(quota.clone()));
|
||||
while let Ok(event) = events.try_recv() {
|
||||
if let AppEvent::InsertHistoryCell(cell) = event {
|
||||
app.insert_history_cell(&mut tui, cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
app.finish_initial_history_replay_buffer(&mut tui);
|
||||
let inserted = tui.pending_history_lines_for_test();
|
||||
insta::allow_duplicates! {
|
||||
insta::assert_snapshot!("native_quota_warning", inserted.iter().map(|line| line.line.to_string()).collect::<Vec<_>>().join("\n"));
|
||||
}
|
||||
assert_eq!(
|
||||
app.render_transcript_lines_for_reflow(/*width*/ 80).lines,
|
||||
inserted
|
||||
);
|
||||
app.flush_native_history(&mut tui);
|
||||
assert_eq!(tui.pending_history_lines_for_test(), inserted);
|
||||
assert_eq!(history_cell::warning_count(&app.transcript_cells), 2);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settled_tool_precedes_queued_output_and_is_not_emitted_twice() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
|
||||
@@ -80,11 +80,11 @@ impl App {
|
||||
"esc latest"
|
||||
};
|
||||
self.sync_owned_transcript(screen_size.width);
|
||||
let composer_tip = self.composer_tip();
|
||||
let transcript_width = self.chat_widget.history_wrap_width(screen_size.width);
|
||||
let composer_hint = self.composer_hint(transcript_width.saturating_sub(/*rhs*/ 2));
|
||||
let mut prompt_footer =
|
||||
self.prompt_navigation_footer(screen_size.width.saturating_sub(/*rhs*/ 2));
|
||||
let chat_widget = &self.chat_widget;
|
||||
let transcript_width = chat_widget.history_wrap_width(screen_size.width);
|
||||
let view = &mut self.transcript_view;
|
||||
let active_key = chat_widget.active_cell_transcript_key();
|
||||
view.sync_history_tail(&self.transcript_cells);
|
||||
@@ -153,7 +153,7 @@ impl App {
|
||||
)
|
||||
});
|
||||
feedback_tick =
|
||||
view.render_composer_gap(follow_area, composer_tip.as_ref(), frame.buffer);
|
||||
view.render_composer_gap(follow_area, composer_hint.as_ref(), frame.buffer);
|
||||
// Rendering resolves whether new activity is still hidden. Paint that result in
|
||||
// this frame so a revision change cannot flash a stale activity hint.
|
||||
let mut footer =
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
---
|
||||
source: tui/src/app/composer_hints_tests.rs
|
||||
assertion_line: 87
|
||||
expression: "crate::chatwidget::tests::helpers::normalize_snapshot_paths(snapshots.join(\"\\n\\n\"))"
|
||||
---
|
||||
80 columns, running=false
|
||||
Conversation
|
||||
|
||||
⚠ Heads up, you have less than 10% of your 5h limit left. Run /status for a
|
||||
breakdown.
|
||||
⚠ 5h limit: 8% left · /status
|
||||
|
||||
› Ask Codex to do anything
|
||||
|
||||
GPT-5.6-Sol default · /tmp/project
|
||||
? for shortcuts ⚠ 1 warning · f2 to view
|
||||
|
||||
32 columns, running=true
|
||||
5% of your 5h limit left.
|
||||
Run /status for a breakdown.
|
||||
⚠ 5h limit: only <1% left
|
||||
• Working (0s • esc to interrup…
|
||||
|
||||
|
||||
› draft stays
|
||||
|
||||
GPT-5.6-Sol default · /tmp/pr…
|
||||
tab to queue message
|
||||
|
||||
18 columns, running=true
|
||||
Run /status for
|
||||
a breakdown.
|
||||
⚠ 5h 5% left
|
||||
• Working (0s • e…
|
||||
|
||||
|
||||
› draft stays
|
||||
|
||||
GPT-5.6-Sol def…
|
||||
tab to queue mes
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/app/native_history_tests.rs
|
||||
assertion_line: 31
|
||||
expression: "inserted.iter().map(|line|\nline.line.to_string()).collect::<Vec<_>>().join(\"\\n\")"
|
||||
---
|
||||
⚠ Heads up, you have less than 25% of your 5h limit left. Run /status for a
|
||||
breakdown.
|
||||
@@ -9,7 +9,7 @@ use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
|
||||
use codex_models_manager::test_support::construct_model_info_offline_for_tests;
|
||||
use codex_models_manager::test_support::get_model_offline_for_tests;
|
||||
|
||||
pub(super) async fn make_test_app() -> App {
|
||||
pub(crate) async fn make_test_app() -> App {
|
||||
let (chat_widget, app_event_tx, _rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||
let config = chat_widget.config_ref().clone();
|
||||
let file_search = FileSearchManager::new(config.cwd.to_path_buf(), app_event_tx.clone());
|
||||
|
||||
@@ -399,6 +399,7 @@ pub(crate) use backend_banners::AutomaticModelSwitchReason;
|
||||
mod protocol;
|
||||
mod protocol_requests;
|
||||
mod rate_limits;
|
||||
mod usage_notice;
|
||||
use self::rate_limits::RateLimitErrorKind;
|
||||
use self::rate_limits::RateLimitSwitchPromptState;
|
||||
use self::rate_limits::RateLimitWarningState;
|
||||
@@ -628,6 +629,7 @@ pub(crate) struct ChatWidget {
|
||||
codex_rate_limit_reached_type: Option<RateLimitReachedType>,
|
||||
codex_spend_control_reached: Option<bool>,
|
||||
rate_limit_warnings: RateLimitWarningState,
|
||||
usage_notice_state: usage_notice::UsageNoticeState,
|
||||
backend_banner_state: backend_banners::BackendBannerState,
|
||||
automatic_model_switch_state: backend_banners::AutomaticModelSwitchState,
|
||||
backend_banner_notice_model: Option<String>,
|
||||
|
||||
@@ -302,6 +302,7 @@ impl ChatWidget {
|
||||
// or discard the already-known limits shown by /status.
|
||||
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);
|
||||
self.codex_rate_limit_reached_type = previous.codex_rate_limit_reached_type;
|
||||
self.codex_spend_control_reached = previous.codex_spend_control_reached;
|
||||
self.backend_banner_state.presented = None;
|
||||
|
||||
@@ -161,6 +161,7 @@ impl ChatWidget {
|
||||
codex_rate_limit_reached_type: None,
|
||||
codex_spend_control_reached: None,
|
||||
rate_limit_warnings: RateLimitWarningState::default(),
|
||||
usage_notice_state: usage_notice::UsageNoticeState::default(),
|
||||
backend_banner_state: backend_banners::BackendBannerState::default(),
|
||||
automatic_model_switch_state: backend_banners::AutomaticModelSwitchState::default(),
|
||||
backend_banner_notice_model: None,
|
||||
|
||||
@@ -50,10 +50,11 @@ impl RateLimitWarningState {
|
||||
&& secondary_used_percent >= RATE_LIMIT_WARNING_THRESHOLDS[self.secondary_index]
|
||||
{
|
||||
let threshold = RATE_LIMIT_WARNING_THRESHOLDS[self.secondary_index];
|
||||
if threshold != 50.0
|
||||
|| (matches!(plan_type, Some(PlanType::Plus | PlanType::Team))
|
||||
&& secondary_window_minutes
|
||||
.is_some_and(|minutes| is_approximate_window(minutes, 5 * 60)))
|
||||
if threshold
|
||||
>= f64::from(usage_notice::warning_threshold(
|
||||
plan_type,
|
||||
secondary_window_minutes,
|
||||
))
|
||||
{
|
||||
highest_secondary = Some(threshold);
|
||||
}
|
||||
@@ -75,10 +76,11 @@ impl RateLimitWarningState {
|
||||
&& primary_used_percent >= RATE_LIMIT_WARNING_THRESHOLDS[self.primary_index]
|
||||
{
|
||||
let threshold = RATE_LIMIT_WARNING_THRESHOLDS[self.primary_index];
|
||||
if threshold != 50.0
|
||||
|| (matches!(plan_type, Some(PlanType::Plus | PlanType::Team))
|
||||
&& primary_window_minutes
|
||||
.is_some_and(|minutes| is_approximate_window(minutes, 5 * 60)))
|
||||
if threshold
|
||||
>= f64::from(usage_notice::warning_threshold(
|
||||
plan_type,
|
||||
primary_window_minutes,
|
||||
))
|
||||
{
|
||||
highest_primary = Some(threshold);
|
||||
}
|
||||
@@ -137,7 +139,7 @@ pub(crate) fn fallback_limit_label(is_secondary: bool) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_approximate_window(minutes: i64, expected_minutes: i64) -> bool {
|
||||
pub(super) fn is_approximate_window(minutes: i64, expected_minutes: i64) -> bool {
|
||||
let minutes = minutes as f64;
|
||||
let expected_minutes = expected_minutes as f64;
|
||||
minutes >= expected_minutes * 0.95 && minutes <= expected_minutes * 1.05
|
||||
@@ -176,7 +178,7 @@ pub(super) fn is_app_server_cyber_policy_error(info: &AppServerCodexErrorInfo) -
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum RateLimitSnapshotSource {
|
||||
pub(super) enum RateLimitSnapshotSource {
|
||||
AccountUsage,
|
||||
RollingUpdate,
|
||||
}
|
||||
@@ -252,11 +254,21 @@ impl ChatWidget {
|
||||
snapshot: Option<RateLimitSnapshot>,
|
||||
source: RateLimitSnapshotSource,
|
||||
) {
|
||||
let usage_notice_blocked = self.codex_rate_limit_reached_type.is_some()
|
||||
|| self.codex_spend_control_reached == Some(true);
|
||||
if let Some(mut snapshot) = snapshot {
|
||||
let limit_id = snapshot
|
||||
.limit_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| "codex".to_string());
|
||||
let is_codex_limit = limit_id.eq_ignore_ascii_case("codex");
|
||||
if is_codex_limit
|
||||
&& self
|
||||
.usage_notice_state
|
||||
.update(&snapshot, source, self.plan_type)
|
||||
{
|
||||
self.request_redraw();
|
||||
}
|
||||
if matches!(source, RateLimitSnapshotSource::RollingUpdate)
|
||||
&& snapshot.credits.is_none()
|
||||
{
|
||||
@@ -272,7 +284,6 @@ 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
|
||||
&& (matches!(source, RateLimitSnapshotSource::AccountUsage)
|
||||
|| snapshot.spend_control_reached.is_some())
|
||||
@@ -375,7 +386,7 @@ impl ChatWidget {
|
||||
|
||||
if !warnings.is_empty() {
|
||||
for warning in warnings {
|
||||
self.add_to_history(history_cell::new_warning_event(warning));
|
||||
self.add_to_history(history_cell::new_usage_warning_event(warning));
|
||||
}
|
||||
self.request_redraw();
|
||||
}
|
||||
@@ -384,6 +395,12 @@ impl ChatWidget {
|
||||
self.codex_rate_limit_reached_type = None;
|
||||
self.codex_spend_control_reached = None;
|
||||
}
|
||||
if usage_notice_blocked
|
||||
!= (self.codex_rate_limit_reached_type.is_some()
|
||||
|| self.codex_spend_control_reached == Some(true))
|
||||
{
|
||||
self.request_redraw();
|
||||
}
|
||||
self.refresh_status_line();
|
||||
}
|
||||
|
||||
|
||||
@@ -211,6 +211,7 @@ impl ChatWidget {
|
||||
self.codex_rate_limit_reached_type = None;
|
||||
self.codex_spend_control_reached = None;
|
||||
self.rate_limit_warnings = RateLimitWarningState::default();
|
||||
self.usage_notice_state = usage_notice::UsageNoticeState::default();
|
||||
self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle;
|
||||
self.bottom_pane
|
||||
.dismiss_view_by_id(RATE_LIMIT_SWITCH_PROMPT_VIEW_ID);
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: tui/src/chatwidget/usage_notice_tests.rs
|
||||
assertion_line: 35
|
||||
expression: "lines.join(\"\\n\")"
|
||||
---
|
||||
47 columns: ⚠ 5h limit: 8% left · resets at 13:00 · /status
|
||||
46 columns: ⚠ 5h limit: 8% left · /status
|
||||
28 columns: ⚠ 5h limit: 8% left
|
||||
18 columns: ⚠ 5h 8% left
|
||||
12 columns: ⚠ 5h 8% left
|
||||
11 columns:
|
||||
@@ -0,0 +1,179 @@
|
||||
//! Account quota state and composer notice, independent of one-time warning history.
|
||||
//! Rolling updates retain metadata; fresh account reads replace windows and confirm recovery.
|
||||
//! Optional details yield to the quota summary when the composer gap is narrow.
|
||||
|
||||
use super::ChatWidget;
|
||||
use super::rate_limits::RateLimitSnapshotSource;
|
||||
use super::rate_limits::is_approximate_window;
|
||||
use super::rate_limits::limit_label_for_window;
|
||||
use crate::footer_hint::first_fitting_line;
|
||||
use chrono::DateTime;
|
||||
use chrono::Local;
|
||||
use codex_app_server_protocol::CreditsSnapshot;
|
||||
use codex_app_server_protocol::RateLimitSnapshot;
|
||||
use codex_app_server_protocol::RateLimitWindow;
|
||||
use codex_protocol::account::PlanType;
|
||||
use ratatui::text::Line;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct UsageNoticeState {
|
||||
primary: Option<RateLimitWindow>,
|
||||
secondary: Option<RateLimitWindow>,
|
||||
plan_type: Option<PlanType>,
|
||||
credits: Option<CreditsSnapshot>,
|
||||
latest_read_id: u64,
|
||||
stale_through: Option<u64>,
|
||||
applying_stale_read: bool,
|
||||
}
|
||||
|
||||
impl UsageNoticeState {
|
||||
fn line(&self, width: u16, now: DateTime<Local>) -> Option<Line<'static>> {
|
||||
let (window, is_secondary) = self.current()?;
|
||||
let label = limit_label_for_window(window.window_duration_mins, is_secondary);
|
||||
// Percentages are rounded by the protocol; 100% alone does not prove a hard stop.
|
||||
let remaining = if window.used_percent >= 100 {
|
||||
"<1%".to_string()
|
||||
} else {
|
||||
format!("{}%", 100 - window.used_percent)
|
||||
};
|
||||
let emphasis = if window.used_percent >= 95 {
|
||||
"only "
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let summary = format!("⚠ {label} limit: {emphasis}{remaining} left");
|
||||
let reset = window
|
||||
.resets_at
|
||||
.and_then(|timestamp| DateTime::from_timestamp(timestamp, /*nsecs*/ 0))
|
||||
.filter(|reset| *reset > now)
|
||||
.map(|reset| {
|
||||
format!(
|
||||
" · resets at {}",
|
||||
crate::status::format_reset_timestamp(reset.with_timezone(&Local), now)
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut style = crate::style::warning_notice_style();
|
||||
if window.used_percent >= 90 {
|
||||
style = style.bold();
|
||||
}
|
||||
let line = first_fitting_line(
|
||||
[
|
||||
format!("{summary}{reset} · /status"),
|
||||
format!("{summary} · /status"),
|
||||
summary,
|
||||
format!("⚠ {label} {remaining} left"),
|
||||
]
|
||||
.map(Line::from),
|
||||
width,
|
||||
);
|
||||
(!line.spans.is_empty()).then_some(line.style(style))
|
||||
}
|
||||
|
||||
pub(super) fn update(
|
||||
&mut self,
|
||||
snapshot: &RateLimitSnapshot,
|
||||
source: RateLimitSnapshotSource,
|
||||
plan_type: Option<PlanType>,
|
||||
) -> bool {
|
||||
if matches!(source, RateLimitSnapshotSource::AccountUsage) && self.applying_stale_read {
|
||||
return false;
|
||||
}
|
||||
let previous = self.current();
|
||||
let rolling = matches!(source, RateLimitSnapshotSource::RollingUpdate);
|
||||
if rolling {
|
||||
self.stale_through = Some(self.latest_read_id);
|
||||
}
|
||||
self.plan_type = snapshot.plan_type.or(self.plan_type).or(plan_type);
|
||||
for (current, incoming) in [
|
||||
(&mut self.primary, &snapshot.primary),
|
||||
(&mut self.secondary, &snapshot.secondary),
|
||||
] {
|
||||
if !rolling {
|
||||
*current = incoming.clone();
|
||||
continue;
|
||||
}
|
||||
let Some(incoming) = incoming else {
|
||||
continue;
|
||||
};
|
||||
let mut window = incoming.clone();
|
||||
if let Some(previous) = current {
|
||||
window.window_duration_mins = window
|
||||
.window_duration_mins
|
||||
.or(previous.window_duration_mins);
|
||||
window.resets_at = window.resets_at.or(previous.resets_at);
|
||||
let threshold = warning_threshold(self.plan_type, window.window_duration_mins);
|
||||
if previous.used_percent >= threshold && window.used_percent < threshold {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
*current = Some(window);
|
||||
}
|
||||
if !rolling || snapshot.credits.is_some() {
|
||||
self.credits = snapshot.credits.clone();
|
||||
}
|
||||
self.current() != previous
|
||||
}
|
||||
|
||||
/// Select the lowest remaining capacity and whether it is the secondary window.
|
||||
pub(super) fn current(&self) -> Option<(RateLimitWindow, bool)> {
|
||||
if self
|
||||
.credits
|
||||
.as_ref()
|
||||
.is_some_and(|credits| credits.unlimited || credits.has_credits)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// max_by_key chooses the last equal entry, giving the primary window priority.
|
||||
[(&self.secondary, true), (&self.primary, false)]
|
||||
.into_iter()
|
||||
.filter_map(|(window, secondary)| Some((window.as_ref()?, secondary)))
|
||||
.filter(|(window, _)| {
|
||||
window.used_percent
|
||||
>= warning_threshold(self.plan_type, window.window_duration_mins)
|
||||
})
|
||||
.max_by_key(|(window, _)| window.used_percent)
|
||||
.map(|(window, secondary)| (window.clone(), secondary))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn warning_threshold(plan_type: Option<PlanType>, window_minutes: Option<i64>) -> i32 {
|
||||
if matches!(plan_type, Some(PlanType::Plus | PlanType::Team))
|
||||
&& window_minutes.is_some_and(|minutes| {
|
||||
is_approximate_window(minutes, /*expected_minutes*/ 5 * 60)
|
||||
})
|
||||
{
|
||||
50
|
||||
} else {
|
||||
75
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatWidget {
|
||||
pub(crate) fn usage_notice(&self, width: u16) -> Option<Line<'static>> {
|
||||
if self.has_applicable_backend_banner()
|
||||
|| self.codex_rate_limit_reached_type.is_some()
|
||||
|| self.codex_spend_control_reached == Some(true)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
self.usage_notice_state.line(width, Local::now())
|
||||
}
|
||||
|
||||
pub(crate) fn start_usage_notice_read(&mut self, request_id: u64) {
|
||||
self.usage_notice_state.latest_read_id = request_id;
|
||||
}
|
||||
|
||||
pub(crate) fn apply_usage_notice_read(&mut self, request_id: u64) {
|
||||
// A newer failed read does not invalidate an older successful one. Only rolling
|
||||
// updates received since that read began make it too old to confirm recovery.
|
||||
self.usage_notice_state.applying_stale_read = self
|
||||
.usage_notice_state
|
||||
.stale_through
|
||||
.is_some_and(|id| request_id <= id);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "usage_notice_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,398 @@
|
||||
//! Quota selection, sparse updates, read ordering, and compact notice formatting.
|
||||
|
||||
use super::*;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_event::RateLimitRefreshOrigin;
|
||||
use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
|
||||
use crate::tui::FrameRequester;
|
||||
use chrono::TimeZone;
|
||||
use codex_app_server_protocol::RateLimitReachedType;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn snapshot(used_percent: i32) -> RateLimitSnapshot {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"primary": {"usedPercent": used_percent, "windowDurationMins": 300, "resetsAt": 1000},
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn notice_time() -> DateTime<Local> {
|
||||
Local
|
||||
.with_ymd_and_hms(
|
||||
/*year*/ 2026, /*month*/ 9, /*day*/ 20, /*hour*/ 12,
|
||||
/*min*/ 0, /*sec*/ 0,
|
||||
)
|
||||
.single()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notice_details_fit_without_truncating_the_warning() {
|
||||
let now = notice_time();
|
||||
let mut state = UsageNoticeState {
|
||||
primary: snapshot(/*used_percent*/ 92).primary,
|
||||
..Default::default()
|
||||
};
|
||||
state.primary.as_mut().unwrap().resets_at =
|
||||
Some((now + chrono::Duration::hours(/*hours*/ 1)).timestamp());
|
||||
let mut lines = Vec::new();
|
||||
for width in [47, 46, 28, 18, 12, 11] {
|
||||
let line = state.line(width, now);
|
||||
assert!(
|
||||
line.as_ref()
|
||||
.is_none_or(|line| line.width() <= usize::from(width))
|
||||
);
|
||||
lines.push(format!("{width} columns: {}", line.unwrap_or_default()));
|
||||
}
|
||||
insta::assert_snapshot!("usage_notice_widths", lines.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notice_shows_only_valid_future_reset_times() {
|
||||
let now = notice_time();
|
||||
let mut state = UsageNoticeState {
|
||||
primary: snapshot(/*used_percent*/ 92).primary,
|
||||
..Default::default()
|
||||
};
|
||||
for (reset, expected) in [
|
||||
(None, ""),
|
||||
(Some(now.timestamp() - 1), ""),
|
||||
(Some(now.timestamp()), ""),
|
||||
(Some(i64::MAX), ""),
|
||||
(
|
||||
Some((now + chrono::Duration::days(/*days*/ 1)).timestamp()),
|
||||
" · resets at 12:00 on 21 Sep",
|
||||
),
|
||||
] {
|
||||
state.primary.as_mut().unwrap().resets_at = reset;
|
||||
assert_eq!(
|
||||
state.line(/*width*/ 80, now),
|
||||
Some(
|
||||
Line::from(format!("⚠ 5h limit: 8% left{expected} · /status"))
|
||||
.style(crate::style::warning_notice_style().bold())
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notice_emphasis_tracks_utilization_without_claiming_a_hard_stop() {
|
||||
for (used, remaining, bold) in [
|
||||
(89, "11%", false),
|
||||
(90, "10%", true),
|
||||
(94, "6%", true),
|
||||
(95, "only 5%", true),
|
||||
(100, "only <1%", true),
|
||||
(101, "only <1%", true),
|
||||
] {
|
||||
let state = UsageNoticeState {
|
||||
primary: snapshot(used).primary,
|
||||
..Default::default()
|
||||
};
|
||||
let style = crate::style::warning_notice_style();
|
||||
assert_eq!(
|
||||
state.line(/*width*/ 80, notice_time()),
|
||||
Some(
|
||||
Line::from(format!("⚠ 5h limit: {remaining} left · /status")).style(if bold {
|
||||
style.bold()
|
||||
} else {
|
||||
style
|
||||
})
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notice_uses_existing_plan_and_window_thresholds() {
|
||||
for (plan, minutes, used, visible) in [
|
||||
(Some(PlanType::Plus), Some(300), 49, false),
|
||||
(Some(PlanType::Plus), Some(300), 50, true),
|
||||
(Some(PlanType::Team), Some(285), 50, true),
|
||||
(Some(PlanType::Plus), Some(1440), 50, false),
|
||||
(Some(PlanType::Plus), None, 50, false),
|
||||
(Some(PlanType::Pro), Some(300), 74, false),
|
||||
(Some(PlanType::Pro), Some(300), 75, true),
|
||||
(None, Some(300), 75, true),
|
||||
] {
|
||||
let mut state = UsageNoticeState::default();
|
||||
let mut update = snapshot(used);
|
||||
update.primary.as_mut().unwrap().window_duration_mins = minutes;
|
||||
state.update(&update, RateLimitSnapshotSource::AccountUsage, plan);
|
||||
assert_eq!(
|
||||
state.current(),
|
||||
visible.then(|| (update.primary.unwrap(), false)),
|
||||
"plan={plan:?}, minutes={minutes:?}, used={used}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn most_constrained_window_wins_with_primary_tie_break() {
|
||||
let mut state = UsageNoticeState::default();
|
||||
let mut update = snapshot(/*used_percent*/ 90);
|
||||
update.secondary = Some(RateLimitWindow {
|
||||
used_percent: 95,
|
||||
window_duration_mins: Some(10080),
|
||||
resets_at: Some(2000),
|
||||
});
|
||||
for primary_used in [90, 95, 100] {
|
||||
update.primary.as_mut().unwrap().used_percent = primary_used;
|
||||
state.update(
|
||||
&update,
|
||||
RateLimitSnapshotSource::AccountUsage,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
let expected = if primary_used < 95 {
|
||||
(update.secondary.clone().unwrap(), true)
|
||||
} else {
|
||||
(update.primary.clone().unwrap(), false)
|
||||
};
|
||||
assert_eq!(state.current(), Some(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_updates_preserve_metadata_until_confirmed_recovery() {
|
||||
let mut state = UsageNoticeState::default();
|
||||
let initial = snapshot(/*used_percent*/ 92);
|
||||
state.update(
|
||||
&initial,
|
||||
RateLimitSnapshotSource::AccountUsage,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
let mut sparse = snapshot(/*used_percent*/ 94);
|
||||
sparse.primary.as_mut().unwrap().window_duration_mins = None;
|
||||
sparse.primary.as_mut().unwrap().resets_at = None;
|
||||
state.update(
|
||||
&sparse,
|
||||
RateLimitSnapshotSource::RollingUpdate,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
let mut expected = initial.primary.unwrap();
|
||||
expected.used_percent = 94;
|
||||
assert_eq!(state.current(), Some((expected.clone(), false)));
|
||||
sparse.primary = None;
|
||||
state.update(
|
||||
&sparse,
|
||||
RateLimitSnapshotSource::RollingUpdate,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
assert_eq!(state.current(), Some((expected.clone(), false)));
|
||||
let healthy = snapshot(/*used_percent*/ 10);
|
||||
state.update(
|
||||
&healthy,
|
||||
RateLimitSnapshotSource::RollingUpdate,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
assert_eq!(state.current(), Some((expected, false)));
|
||||
state.update(
|
||||
&healthy,
|
||||
RateLimitSnapshotSource::AccountUsage,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
assert_eq!(state.current(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authoritative_reads_replace_windows_and_metadata() {
|
||||
let mut state = UsageNoticeState {
|
||||
primary: snapshot(/*used_percent*/ 92).primary,
|
||||
secondary: snapshot(/*used_percent*/ 95).primary,
|
||||
..Default::default()
|
||||
};
|
||||
let mut update = snapshot(/*used_percent*/ 80);
|
||||
update.primary.as_mut().unwrap().window_duration_mins = None;
|
||||
update.primary.as_mut().unwrap().resets_at = None;
|
||||
state.update(
|
||||
&update,
|
||||
RateLimitSnapshotSource::AccountUsage,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
assert_eq!(state.current(), Some((update.primary.unwrap(), false)));
|
||||
let mut empty = snapshot(/*used_percent*/ 0);
|
||||
empty.primary = None;
|
||||
state.update(
|
||||
&empty,
|
||||
RateLimitSnapshotSource::AccountUsage,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
assert_eq!(state.current(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usable_credits_suppress_notices_and_survive_sparse_updates() {
|
||||
for (has_credits, unlimited) in [(true, false), (false, true)] {
|
||||
let mut state = UsageNoticeState::default();
|
||||
let mut funded = snapshot(/*used_percent*/ 92);
|
||||
funded.credits = Some(CreditsSnapshot {
|
||||
has_credits,
|
||||
unlimited,
|
||||
balance: None,
|
||||
});
|
||||
state.update(
|
||||
&funded,
|
||||
RateLimitSnapshotSource::AccountUsage,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
let sparse = snapshot(/*used_percent*/ 96);
|
||||
state.update(
|
||||
&sparse,
|
||||
RateLimitSnapshotSource::RollingUpdate,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
assert_eq!(state.current(), None);
|
||||
state.update(
|
||||
&sparse,
|
||||
RateLimitSnapshotSource::AccountUsage,
|
||||
/*plan_type*/ None,
|
||||
);
|
||||
assert_eq!(state.current(), Some((sparse.primary.unwrap(), false)));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notice_redraws_when_only_limit_blockers_change() {
|
||||
let (frame_requester, mut draw_rx) = FrameRequester::test_channel();
|
||||
let (mut chat, _, _, _) = make_chatwidget_manual_with_sender().await;
|
||||
chat.frame_requester = frame_requester;
|
||||
chat.local_settings.tui.status_line = Some(Vec::new());
|
||||
chat.local_settings.tui.terminal_title = Some(Vec::new());
|
||||
let low = snapshot(/*used_percent*/ 92);
|
||||
chat.on_rate_limit_snapshot(Some(low.clone()));
|
||||
let notice = chat.usage_notice(/*width*/ 80);
|
||||
assert!(notice.is_some());
|
||||
for (limit_id, spend_control_reached, rate_limit_reached_type) in [
|
||||
(None, Some(true), None),
|
||||
(None, None, Some(RateLimitReachedType::RateLimitReached)),
|
||||
(
|
||||
Some("codex_other".to_string()),
|
||||
None,
|
||||
Some(RateLimitReachedType::RateLimitReached),
|
||||
),
|
||||
] {
|
||||
while draw_rx.try_recv().is_ok() {}
|
||||
let mut blocked = low.clone();
|
||||
blocked.limit_id = limit_id;
|
||||
blocked.spend_control_reached = spend_control_reached;
|
||||
blocked.rate_limit_reached_type = rate_limit_reached_type;
|
||||
chat.on_rolling_rate_limit_snapshot(blocked);
|
||||
assert_eq!(chat.usage_notice(/*width*/ 80), None);
|
||||
assert!(draw_rx.try_recv().is_ok());
|
||||
while draw_rx.try_recv().is_ok() {}
|
||||
chat.on_rate_limit_snapshot(/*snapshot*/ None);
|
||||
assert_eq!(chat.usage_notice(/*width*/ 80), notice);
|
||||
assert!(draw_rx.try_recv().is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn overlapping_reads_keep_older_success_when_newer_read_fails() -> color_eyre::Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let low = snapshot(/*used_percent*/ 92);
|
||||
let healthy = snapshot(/*used_percent*/ 10);
|
||||
for (first_id, rolling, update, expected) in [
|
||||
(
|
||||
1,
|
||||
None,
|
||||
low.clone(),
|
||||
Some((low.primary.clone().unwrap(), false)),
|
||||
),
|
||||
(
|
||||
3,
|
||||
Some(low.clone()),
|
||||
healthy.clone(),
|
||||
Some((low.primary.clone().unwrap(), false)),
|
||||
),
|
||||
(5, None, healthy, None),
|
||||
] {
|
||||
for request_id in first_id..=first_id + 1 {
|
||||
app.chat_widget
|
||||
.add_status_output(/*refreshing_rate_limits*/ true, Some(request_id));
|
||||
app.refresh_rate_limits(
|
||||
&session,
|
||||
RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
);
|
||||
}
|
||||
if let Some(rolling) = rolling {
|
||||
app.chat_widget.on_rolling_rate_limit_snapshot(rolling);
|
||||
}
|
||||
let before = app.chat_widget.usage_notice_state.current();
|
||||
for (request_id, result, expected) in [
|
||||
(first_id + 1, Err("transient failure".into()), before),
|
||||
(first_id, Ok(update), expected),
|
||||
] {
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut session,
|
||||
AppEvent::RateLimitsLoaded {
|
||||
request_id,
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
hard_stop_generation: 0,
|
||||
result: result.map(|update| {
|
||||
serde_json::from_value(serde_json::json!({"rateLimits": update})).unwrap()
|
||||
}),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(app.chat_widget.usage_notice_state.current(), expected);
|
||||
}
|
||||
}
|
||||
session.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rolling_updates_invalidate_only_reads_already_started() {
|
||||
let (mut chat, _, _, _) = make_chatwidget_manual_with_sender().await;
|
||||
let mut low = snapshot(/*used_percent*/ 50);
|
||||
low.plan_type = Some(PlanType::Plus);
|
||||
let healthy = snapshot(/*used_percent*/ 10);
|
||||
chat.start_usage_notice_read(/*request_id*/ 1);
|
||||
chat.on_rolling_rate_limit_snapshot(low.clone());
|
||||
chat.start_usage_notice_read(/*request_id*/ 2);
|
||||
chat.start_usage_notice_read(/*request_id*/ 3);
|
||||
// Read 3 fails; read 1 is stale, but read 2 began after the rolling update.
|
||||
chat.apply_usage_notice_read(/*request_id*/ 1);
|
||||
let mut stale = healthy.clone();
|
||||
stale.plan_type = Some(PlanType::Pro);
|
||||
// A legacy response can include the same quota both at the top level and in its map.
|
||||
for _ in 0..2 {
|
||||
chat.on_rate_limit_snapshot(Some(stale.clone()));
|
||||
assert_eq!(
|
||||
chat.usage_notice_state.current(),
|
||||
Some((low.primary.clone().unwrap(), false))
|
||||
);
|
||||
}
|
||||
chat.apply_usage_notice_read(/*request_id*/ 2);
|
||||
chat.on_rate_limit_snapshot(Some(healthy));
|
||||
assert_eq!(chat.usage_notice_state.current(), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notice_follows_threads_and_clears_on_account_change() {
|
||||
let (mut previous, _, _, _) = make_chatwidget_manual_with_sender().await;
|
||||
let low = snapshot(/*used_percent*/ 92);
|
||||
previous.on_rate_limit_snapshot(Some(low.clone()));
|
||||
previous.start_usage_notice_read(/*request_id*/ 1);
|
||||
previous.on_rolling_rate_limit_snapshot(low.clone());
|
||||
let (mut chat, _, _, _) = make_chatwidget_manual_with_sender().await;
|
||||
chat.inherit_backend_banner_state(&mut previous);
|
||||
chat.apply_usage_notice_read(/*request_id*/ 1);
|
||||
chat.on_rate_limit_snapshot(Some(snapshot(/*used_percent*/ 10)));
|
||||
let mut other = snapshot(/*used_percent*/ 99);
|
||||
other.limit_id = Some("codex_other".into());
|
||||
chat.on_rolling_rate_limit_snapshot(other);
|
||||
chat.on_rate_limit_snapshot(/*snapshot*/ None);
|
||||
assert_eq!(
|
||||
chat.usage_notice_state.current(),
|
||||
Some((low.primary.unwrap(), false))
|
||||
);
|
||||
chat.update_account_state(
|
||||
/*status_account_display*/ None, /*plan_type*/ None,
|
||||
/*has_chatgpt_account*/ true, /*has_codex_backend_auth*/ true,
|
||||
);
|
||||
assert_eq!(chat.usage_notice_state.current(), None);
|
||||
}
|
||||
@@ -97,6 +97,7 @@ pub(crate) fn new_warning_event(message: String) -> WarningHistoryCell {
|
||||
let style = crate::style::status_style(crate::style::StatusTone::Attention);
|
||||
WarningHistoryCell {
|
||||
server_version_notice: false,
|
||||
visible_in_transcript: false,
|
||||
key: message.clone(),
|
||||
diagnostic: message.clone(),
|
||||
details: PrefixedWrappedHistoryCell::new(
|
||||
@@ -107,6 +108,13 @@ pub(crate) fn new_warning_event(message: String) -> WarningHistoryCell {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_usage_warning_event(message: String) -> WarningHistoryCell {
|
||||
WarningHistoryCell {
|
||||
visible_in_transcript: true,
|
||||
..new_warning_event(message)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_server_version_warning(
|
||||
notice: crate::status::remote_connection::ServerVersionNotice,
|
||||
) -> WarningHistoryCell {
|
||||
@@ -123,6 +131,7 @@ pub(crate) fn new_server_version_warning(
|
||||
}
|
||||
WarningHistoryCell {
|
||||
server_version_notice: true,
|
||||
visible_in_transcript: false,
|
||||
key,
|
||||
diagnostic: lines
|
||||
.iter()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Retain warning details for the transcript while exposing stable identities to the footer.
|
||||
//! Message identities deduplicate replay; MCP identities count affected servers, not summary rows.
|
||||
//! Quota warnings remain visible in both transcript modes.
|
||||
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -47,6 +48,7 @@ pub(crate) enum WarningKey<'a> {
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct WarningHistoryCell {
|
||||
pub(crate) server_version_notice: bool,
|
||||
pub(super) visible_in_transcript: bool,
|
||||
pub(super) key: String,
|
||||
pub(super) diagnostic: String,
|
||||
pub(super) details: PrefixedWrappedHistoryCell,
|
||||
@@ -54,11 +56,19 @@ pub(crate) struct WarningHistoryCell {
|
||||
|
||||
impl HistoryCell for WarningHistoryCell {
|
||||
fn live_raw_lines(&self) -> Vec<Line<'static>> {
|
||||
Vec::new()
|
||||
if self.visible_in_transcript {
|
||||
self.details.raw_lines()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
|
||||
Vec::new()
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
if self.visible_in_transcript {
|
||||
self.details.display_lines(width)
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
|
||||
@@ -3,6 +3,46 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn usage_warnings_render_in_both_transcripts_including_composites() {
|
||||
let message = "Only 8% of your 5h limit remains. Run /status for details.";
|
||||
let usage = new_usage_warning_event(message.into());
|
||||
let diagnostic = new_warning_event(message.into());
|
||||
let composite = CompositeHistoryCell::new(vec![
|
||||
Box::new(PlainHistoryCell::new(vec!["Earlier output".into()])),
|
||||
Box::new(new_warning_event("Hidden diagnostic".into())),
|
||||
Box::new(new_usage_warning_event(message.into())),
|
||||
]);
|
||||
assert_eq!(usage.warning_entries(), diagnostic.warning_entries());
|
||||
for mode in [HistoryRenderMode::Rich, HistoryRenderMode::Raw] {
|
||||
let visible = usage.display_hyperlink_lines_for_mode(/*width*/ 28, mode);
|
||||
let expected = match mode {
|
||||
HistoryRenderMode::Rich => usage.transcript_hyperlink_lines(/*width*/ 28),
|
||||
HistoryRenderMode::Raw => plain_hyperlink_lines(usage.raw_lines()),
|
||||
};
|
||||
assert_eq!(visible, expected);
|
||||
if matches!(mode, HistoryRenderMode::Rich) {
|
||||
assert_eq!(usage.compact_hyperlink_lines(/*width*/ 28), visible);
|
||||
}
|
||||
assert!(
|
||||
diagnostic
|
||||
.display_hyperlink_lines_for_mode(/*width*/ 28, mode)
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
composite.display_hyperlink_lines_for_mode(/*width*/ 28, mode),
|
||||
[
|
||||
vec![
|
||||
HyperlinkLine::from("Earlier output"),
|
||||
HyperlinkLine::from("")
|
||||
],
|
||||
visible
|
||||
]
|
||||
.concat(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warning_count_deduplicates_messages_mcp_summaries_and_composites() {
|
||||
let cells: Vec<Arc<dyn HistoryCell>> = vec![
|
||||
|
||||
Reference in New Issue
Block a user