Add Luna Reserve usage fallback to the TUI (#42372)

## Why

When ordinary included usage is exhausted, eligible users need a way to keep working with the backend-provided Luna Reserve quota and return to their previous model once ordinary usage recovers.

## What changed

- Automatically switch eligible TUI tasks to Luna Reserve after an authoritative account usage read, preserving the prior model and reasoning effort per task.
- Restrict model selection while on Reserve to its supported reasoning levels, keep queued turns on the accepted model, and restore the saved model after a fresh read confirms recovery.
- Surface Reserve usage in the composer and `/status`, and expose `normalModelSlug` in app-server rate-limit snapshots so clients can use the associated model's display metadata without changing the request model.
- Poll account limits more frequently near exhaustion and retain compatibility with app servers that only accept the legacy null request parameters.

## Testing

- Added coverage for Reserve entry, queued-turn handling, task reconstruction, recovery authorization, account changes, model selection, usage rendering, and banner dismissal.

GitOrigin-RevId: 46a435e9531051f8cec3f6a46c4b9f7cfa479747
This commit is contained in:
dhruvgupta-oai authored and copyberry committed 2026-09-02 21:50:51 +00:00
1 parent 76f47103fe
commit 5037919777
76 files changed
+1907 -135

No files matched your search

@@ -319,7 +319,10 @@ async fn backend_banner_fallback_candidates_and_notice_follow_selected_model() {
response.rate_limit_upsell.as_mut().unwrap()["fallback_model_slugs"] =
json!(["hidden-model", "test-model-c", "test-model-b"]);
chat.update_backend_banner(&response);
assert_eq!(chat.backend_banner_fallback(), Some(models[2].clone()));
assert_eq!(
chat.backend_banner_fallback().map(|switch| switch.model),
Some(models[2].clone())
);
// A retained ChatGPT login must not change a task whose server does not require auth.
chat.requires_openai_auth = false;
assert_eq!(chat.backend_banner_fallback(), None);
@@ -107,6 +107,7 @@ pub(super) fn snapshot(percent: f64) -> RateLimitSnapshot {
RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: percent.round() as i32,
window_duration_mins: Some(60),
@@ -0,0 +1,254 @@
//! Exercise Reserve picker focus, its status label, and the composer palette across entry and exit.
use super::helpers::normalize_snapshot_paths;
use super::*;
use crate::terminal_palette::with_test_default_colors;
use crate::terminal_probe::DefaultColors;
use pretty_assertions::assert_eq;
use serde_json::json;
fn reserve_snapshot(primary_used: i32, weekly_used: i32) -> RateLimitSnapshot {
RateLimitSnapshot {
limit_id: Some("base_model_inference".into()),
limit_name: Some("gpt-reserve".into()),
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: primary_used,
window_duration_mins: Some(300),
resets_at: None,
}),
secondary: Some(RateLimitWindow {
used_percent: weekly_used,
window_duration_mins: Some(10080),
resets_at: None,
}),
..snapshot(/*percent*/ 0.0)
}
}
#[tokio::test]
async fn luna_reserve_selector_supports_arrows_enter_shortcuts_and_escape_without_losing_draft() {
for (keys, destination) in [
(
vec![KeyCode::Down, KeyCode::Enter],
Some("https://chatgpt.com/?cta_tab=personal&highlight_plan=plus#pricing"),
),
(
vec![KeyCode::Down, KeyCode::Up, KeyCode::Enter],
Some("https://chatgpt.com/codex/settings/usage?credits_modal=true"),
),
(
vec![KeyCode::Char('1')],
Some("https://chatgpt.com/codex/settings/usage?credits_modal=true"),
),
(
vec![KeyCode::Char('2')],
Some("https://chatgpt.com/?cta_tab=personal&highlight_plan=plus#pricing"),
),
(vec![KeyCode::Down, KeyCode::Esc], None),
] {
let (mut chat, mut events, _ops) = make_chatwidget_manual(Some("gpt-reserve")).await;
chat.has_chatgpt_account = true;
chat.apply_external_edit("saved draft".into());
chat.on_rate_limit_snapshot(Some(reserve_snapshot(
/*primary_used*/ 48, /*weekly_used*/ 20,
)));
let response = serde_json::from_value(json!({
"accountId": "account-preview", "rateLimits": {},
"rateLimitUpsell": {
"banner_type": "luna_reserve", "presentation": "dismissible",
"title": "You’re now using Luna, a faster model for simpler tasks.",
"description": "Add credits or upgrade to continue using the most advanced models.",
"ctas": [{"action": "add_credits", "label": "Add credits"},
{"action": "open_pricing_dialog", "label": "Upgrade"}]
}
}))
.unwrap();
chat.update_backend_banner(&response);
let rendered = normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 90));
assert!(
!rendered.contains("saved draft"),
"selector owns input focus"
);
assert!(rendered.contains("esc to continue working"));
while events.try_recv().is_ok() {}
for key in keys {
chat.handle_key_event(KeyEvent::from(key));
if key == KeyCode::Down {
insta::assert_snapshot!(
"luna_reserve_selector_second_choice",
normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 90))
);
}
}
let queued = std::iter::from_fn(|| events.try_recv().ok()).collect::<Vec<_>>();
let urls: Vec<_> = queued
.iter()
.filter_map(|event| match event {
AppEvent::OpenUrlInBrowser { url } => Some(url.as_str()),
_ => None,
})
.collect();
assert_eq!(urls, destination.into_iter().collect::<Vec<_>>());
assert!(
!queued
.iter()
.any(|event| matches!(event, AppEvent::CodexOp(AppCommand::UserTurn { .. })))
);
assert_eq!(chat.composer_text_with_pending(), "saved draft");
// A periodic usage reply must not reopen a selector the user just closed.
chat.update_backend_banner(&response);
let rendered = normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 90));
assert!(!rendered.contains("You’re now using Luna"));
assert!(rendered.contains("saved draft"));
assert!(rendered.contains("Luna Reserve"));
}
}
#[tokio::test]
async fn luna_reserve_status_tracks_the_active_model() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("gpt-5.6-sol")).await;
chat.has_chatgpt_account = true;
chat.on_rate_limit_snapshot(Some(reserve_snapshot(
/*primary_used*/ 25, /*weekly_used*/ 60,
)));
assert!(
!normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 80))
.contains("Luna Reserve")
);
chat.set_model("gpt-reserve");
let rendered = normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 80));
assert!(rendered.contains("Luna Reserve default"));
insta::assert_snapshot!("luna_reserve_usage_wide", rendered);
insta::assert_snapshot!(
"luna_reserve_usage_narrow",
normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 34))
);
chat.set_model("gpt-5.6-sol");
assert!(
!normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 80))
.contains("Luna Reserve")
);
chat.set_model("gpt-reserve");
assert!(
normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 80)).contains("Luna Reserve")
);
}
#[tokio::test]
async fn luna_reserve_usage_survives_banner_dismissal_and_typing_during_a_turn() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("gpt-reserve")).await;
chat.has_chatgpt_account = true;
chat.on_rate_limit_snapshot(Some(reserve_snapshot(
/*primary_used*/ 48, /*weekly_used*/ 20,
)));
let response = codex_app_server_protocol::GetAccountRateLimitsResponse {
ordinary_usage_allowed: Some(false),
account_id: Some("account-preview".into()),
rate_limits: snapshot(/*percent*/ 100.0),
rate_limits_by_limit_id: None,
rate_limit_reset_credits: None,
rate_limit_upsell: Some(json!({
"banner_type": "luna_reserve", "presentation": "dismissible",
"title": "You’re now using Luna, a faster model for simpler tasks.",
"description": "Add credits or upgrade to continue using the most advanced models.",
"ctas": [
{"action": "add_credits", "label": "Add credits"},
{"action": "open_pricing_dialog", "label": "Upgrade"}
]
})),
};
chat.update_backend_banner(&response);
for colors in [
DefaultColors {
fg: (230, 230, 230),
bg: (20, 20, 20),
},
DefaultColors {
fg: (25, 25, 25),
bg: (255, 255, 255),
},
] {
with_test_default_colors(colors, || {
let area = Rect::new(0, 0, 80, chat.bottom_pane.desired_height(/*width*/ 80));
let mut buffer = Buffer::empty(area);
chat.bottom_pane.render(area, &mut buffer);
// Do not rely on the terminal's bold default foreground or dim important copy.
for (y, text) in buffer
.content
.chunks(80)
.enumerate()
.filter_map(|(y, row)| {
let text: String = row.iter().map(ratatui::buffer::Cell::symbol).collect();
(text.contains("You’re now using Luna")
|| text.contains("Add credits or upgrade"))
.then_some((y as u16, text))
})
{
let copy = &buffer[(2, y)];
assert_eq!(copy.fg, crate::terminal_palette::rgb_color(colors.fg));
assert!(
!copy.modifier.contains(ratatui::style::Modifier::DIM),
"{text}"
);
}
});
}
insta::assert_snapshot!(
"luna_reserve_usage_with_upsell",
normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 80))
);
chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(
!normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 80))
.contains("You’re now using Luna")
);
chat.bottom_pane.set_task_running(/*running*/ true);
chat.handle_key_event(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
chat.handle_key_event(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE));
let rendered = normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 80));
assert_eq!(chat.composer_text_with_pending(), "x");
insta::assert_snapshot!("luna_reserve_usage_running", rendered);
}
#[tokio::test]
async fn luna_reserve_prompt_preserves_the_composer_palette_on_exit() {
let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("gpt-reserve")).await;
chat.has_chatgpt_account = true;
chat.on_rate_limit_snapshot(Some(reserve_snapshot(
/*primary_used*/ 25, /*weekly_used*/ 60,
)));
for colors in [
DefaultColors {
fg: (230, 230, 230),
bg: (20, 20, 20),
},
DefaultColors {
fg: (25, 25, 25),
bg: (255, 255, 255),
},
] {
with_test_default_colors(colors, || {
chat.set_model("gpt-reserve");
let area = Rect::new(0, 0, 80, chat.bottom_pane.desired_height(/*width*/ 80));
let mut active = Buffer::empty(area);
chat.bottom_pane.render(area, &mut active);
let cursor = chat.bottom_pane.cursor_pos(area).expect("composer cursor");
let ordinary_style = crate::style::user_message_style();
assert_eq!(active[(0, cursor.1)].bg, ordinary_style.bg.unwrap());
assert_eq!(active[(0, cursor.1)].bg, active[(0, cursor.1 - 1)].bg);
chat.set_model("gpt-5.6-sol");
let area = Rect::new(0, 0, 80, chat.bottom_pane.desired_height(/*width*/ 80));
let mut inactive = Buffer::empty(area);
chat.bottom_pane.render(area, &mut inactive);
let restored_cursor = chat.bottom_pane.cursor_pos(area).expect("composer cursor");
assert_eq!(
inactive[(0, restored_cursor.1)].bg,
ordinary_style.bg.unwrap()
);
assert_eq!(restored_cursor.1, cursor.1);
});
}
}
@@ -1,11 +1,9 @@
---
source: tui/src/chatwidget/tests/backend_banners_tests.rs
assertion_line: 50
expression: "render_bottom_popup(&chat, 70)"
expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 70))"
---
Selected model usage exhausted
Ask your owner for credits or switch to another model.
› 1. Notify owner
Press a number to choose
@@ -0,0 +1,12 @@
---
source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs
expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 90))"
---
You’re now using Luna, a faster model for simpler tasks.
Add credits or upgrade to continue using the most advanced models.
1. Add credits
› 2. Upgrade
3. Continue with Luna Reserve
Press enter to confirm or esc to continue working
@@ -0,0 +1,8 @@
---
source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs
expression: "render_bottom_popup(&chat, 34)"
---
› Ask Codex to do anything
Luna Reserve default · /tmp/pro…
@@ -0,0 +1,10 @@
---
source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs
expression: rendered
---
• Working (0s • esc to interrupt)
› x
tab to queue message 100% context left
@@ -0,0 +1,8 @@
---
source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs
expression: rendered
---
› Ask Codex to do anything
Luna Reserve default · /tmp/project
@@ -0,0 +1,12 @@
---
source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs
expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 80))"
---
You’re now using Luna, a faster model for simpler tasks.
Add credits or upgrade to continue using the most advanced models.
› 1. Add credits
2. Upgrade
3. Continue with Luna Reserve
Press enter to confirm or esc to continue working
@@ -706,6 +706,7 @@ async fn status_line_uses_secondary_fallback_for_unsupported_window() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: None,
secondary: Some(RateLimitWindow {
used_percent: 50,
@@ -732,6 +733,7 @@ async fn status_line_legacy_limit_items_prefer_matching_windows() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 94,
window_duration_mins: Some(7 * 24 * 60),
@@ -766,6 +768,7 @@ async fn status_line_shows_secondary_non_weekly_when_primary_is_weekly() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 94,
window_duration_mins: Some(7 * 24 * 60),
@@ -800,6 +803,7 @@ async fn status_line_five_hour_item_omits_weekly_only_limit() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 9,
window_duration_mins: Some(7 * 24 * 60),
@@ -830,6 +834,7 @@ async fn status_line_single_monthly_primary_omits_weekly_limit_item() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 35,
window_duration_mins: Some(30 * 24 * 60),
@@ -860,6 +865,7 @@ async fn status_line_secondary_only_non_weekly_limit_omits_primary_limit_item()
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: None,
secondary: Some(RateLimitWindow {
used_percent: 35,
@@ -890,7 +896,12 @@ async fn rate_limit_snapshot_keeps_prior_credits_when_missing_from_headers() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
primary: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 10,
window_duration_mins: Some(60),
resets_at: Some(123),
}),
secondary: None,
credits: Some(CreditsSnapshot {
has_credits: true,
@@ -912,6 +923,7 @@ async fn rate_limit_snapshot_keeps_prior_credits_when_missing_from_headers() {
chat.on_rolling_rate_limit_snapshot(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 80,
window_duration_mins: Some(60),
@@ -938,7 +950,7 @@ async fn rate_limit_snapshot_keeps_prior_credits_when_missing_from_headers() {
assert!(!credits.unlimited);
assert_eq!(
display.primary.as_ref().map(|window| window.used_percent),
Some(80.0)
Some(10.0)
);
}
@@ -983,6 +995,7 @@ async fn rate_limit_snapshot_updates_and_retains_plan_type() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 10,
window_duration_mins: Some(60),
@@ -1004,6 +1017,7 @@ async fn rate_limit_snapshot_updates_and_retains_plan_type() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 25,
window_duration_mins: Some(30),
@@ -1025,6 +1039,7 @@ async fn rate_limit_snapshot_updates_and_retains_plan_type() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 30,
window_duration_mins: Some(60),
@@ -1051,6 +1066,7 @@ async fn rate_limit_snapshots_keep_separate_entries_per_limit_id() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: Some("codex".to_string()),
limit_name: Some("codex".to_string()),
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 20,
window_duration_mins: Some(300),
@@ -1071,6 +1087,7 @@ async fn rate_limit_snapshots_keep_separate_entries_per_limit_id() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: Some("codex_other".to_string()),
limit_name: Some("codex_other".to_string()),
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 90,
window_duration_mins: Some(60),
@@ -1126,6 +1143,7 @@ async fn rate_limit_switch_prompt_skips_non_codex_limit() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: Some("codex_other".to_string()),
limit_name: Some("codex_other".to_string()),
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 95,
window_duration_mins: Some(60),
@@ -67,6 +67,7 @@ fn cache_rate_limit_snapshot(chat: &mut ChatWidget) {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 35,
window_duration_mins: Some(30 * 24 * 60),
@@ -353,6 +354,7 @@ async fn status_surface_preview_omits_unavailable_rate_limit_items() {
chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 9,
window_duration_mins: Some(7 * 24 * 60),