Use the current billing plan for TUI thread usage (#61978)

## Why

Account reads can use a cached subscription plan, and rolling quota updates can carry an obsolete plan. This can leave thread usage unavailable or cause `/status` to display costs using the wrong billing model.

## What changed

- Prefer a known plan from a full Codex quota read over the account plan, regardless of reply order. Ignore unknown quota plans and prevent rolling updates from changing the billing plan.
- Preserve quota plan state across chat widget replacement and apply accepted quota reads even after the requesting status card is gone.
- Refresh thread usage availability when the plan changes and pair asynchronous `/status` estimates with the corrected plan, including native dollar usage for `Ent26`.

## Testing

Add regression tests for reply ordering, unknown plans, corrected pending status cards, obsolete rolling updates, and quota replies arriving after widget replacement.

GitOrigin-RevId: 238fadb587fe98cda0eeb5111c1949928acc8153
This commit is contained in:
Joe Savona
2026-11-17 06:32:38 +00:00
committed by copyberry
parent 490394c184
commit 7e59b27667
18 changed files with 269 additions and 52 deletions
+1 -1
View File
@@ -859,7 +859,7 @@ impl App {
feedback: self.feedback.clone(),
is_first_run: false,
status_account_display: self.chat_widget.status_account_display().cloned(),
initial_plan_type: self.chat_widget.current_plan_type(),
initial_plan_type: self.chat_widget.account_plan,
model: Some(self.chat_widget.current_model().to_string()),
startup_tooltip_override: None,
status_line_invalid_items_warned: self.status_line_invalid_items_warned.clone(),
+2 -1
View File
@@ -34,12 +34,13 @@ impl App {
if let Some(Account::Chatgpt {
email,
workspace_name,
..
plan_type,
}) = response.account
{
app_event_tx.send(AppEvent::AccountEmailLoaded {
request_id,
email,
plan_type,
workspace: crate::app_server_session::workspace_display(
workspace_name,
response.workspace_routing,
+8 -3
View File
@@ -1654,10 +1654,10 @@ impl App {
elicitation_target: None,
});
}
AppEvent::AccountEmailLoaded { request_id, email, workspace } => {
AppEvent::AccountEmailLoaded { request_id, email, workspace, plan_type } => {
if self.account_email_request_id == Some(request_id) {
self.account_email_request_id = None;
self.chat_widget.on_account_email_loaded(email, workspace);
self.chat_widget.on_account_email_loaded(email, workspace, plan_type);
}
}
AppEvent::SecuritySetupLoaded { request_id, identity, notice } => {
@@ -2217,7 +2217,12 @@ impl App {
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)
let snapshots = app_server_rate_limit_snapshots(response);
// The account can outlive the popup or chat that requested this read.
for snapshot in &snapshots {
self.chat_widget.observe_quota_plan(snapshot);
}
snapshots
} else {
Vec::new()
};
@@ -87,6 +87,7 @@ async fn new_session_refreshes_account_for_the_started_provider() -> Result<()>
/*spend_control_reached*/ None,
);
snapshot.credits = None;
snapshot.plan_type = Some(codex_protocol::account::PlanType::Business);
app.chat_widget
.on_rate_limit_snapshot(Some(snapshot.clone()));
if provider == "alt" {
+58
View File
@@ -156,6 +156,64 @@ async fn backend_banner_state_survives_widget_replacement() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn accepted_rate_limit_read_updates_billing_after_its_status_card_is_gone() -> Result<()> {
use codex_protocol::account::PlanType;
let (mut app, mut events, _) = make_test_app_with_channels().await;
let mut tui = crate::tui::test_support::make_test_tui()?;
let mut server =
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
let card_id = 1;
app.chat_widget
.add_status_output(/*refreshing_rate_limits*/ true, Some(card_id));
let origin = RateLimitRefreshOrigin::StatusCommand {
request_id: card_id,
};
let (request_id, hard_stop_generation) = app
.rate_limit_refresh_state
.start(origin, &mut app.rate_limit_hard_stop_generation)
.unwrap();
let mut replacement = app.chatwidget_init_for_forked_or_resumed_thread(
&mut tui,
app.config.clone(),
/*initial_user_message*/ None,
);
replacement.has_codex_backend_auth = true;
replacement.initial_plan_type = Some(PlanType::Plus);
replacement.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".into()]);
app.replace_chat_widget(ChatWidget::new_with_app_event(replacement));
let thread = ThreadId::new();
app.enqueue_primary_thread_session(
test_thread_session(thread, app.config.cwd.to_path_buf()),
Vec::new(),
)
.await?;
app.drain_active_thread_events(&mut tui).await?;
while events.try_recv().is_ok() {}
let quota = serde_json::from_value(serde_json::json!({"planType": "business"}))?;
Box::pin(app.handle_event(
&mut tui,
&mut server,
AppEvent::RateLimitsLoaded {
request_id,
origin,
hard_stop_generation,
result: Ok(account_rate_limits_response(quota)),
},
))
.await?;
assert_eq!(
app.chat_widget.current_plan_type(),
Some(PlanType::Business)
);
assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event|
matches!(event, AppEvent::RefreshThreadUsage { thread_id, .. } if thread_id == thread)));
server.shutdown().await?;
Ok(())
}
#[tokio::test]
async fn rolling_workspace_hard_stops_invalidate_older_rate_limit_reads() -> Result<()> {
let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await;
@@ -173,6 +173,7 @@ async fn security_setup_fetch_with_default_features_uses_authenticated_codex_end
request_id: uuid::Uuid::new_v4(),
email: Some("stale@example.com".into()),
workspace: Some("stale-account".into()),
plan_type: codex_protocol::account::PlanType::Plus,
},
)
.await?;
+1
View File
@@ -358,6 +358,7 @@ pub(crate) enum AppEvent {
request_id: uuid::Uuid,
email: Option<String>,
workspace: Option<String>,
plan_type: codex_protocol::account::PlanType,
},
SecuritySetupLoaded {
request_id: uuid::Uuid,
+2
View File
@@ -599,6 +599,8 @@ pub(crate) struct ChatWidget {
pending_rate_limit_reset_hint: Option<PlainHistoryCell>,
available_rate_limit_reset_credits: Option<i64>,
next_rate_limit_reset_request_id: u64,
pub(crate) account_plan: Option<PlanType>,
quota_plan: Option<PlanType>,
plan_type: Option<PlanType>,
codex_rate_limit_reached_type: Option<RateLimitReachedType>,
codex_spend_control_reached: Option<bool>,
@@ -302,6 +302,8 @@ impl ChatWidget {
self.inherited_quota_provider = Some(previous.quota_provider_id().to_owned());
self.rate_limit_snapshots_by_limit_id =
std::mem::take(&mut previous.rate_limit_snapshots_by_limit_id);
self.quota_plan = previous.quota_plan.take();
self.refresh_billing_plan();
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;
@@ -171,6 +171,8 @@ impl ChatWidget {
pending_rate_limit_reset_hint: None,
available_rate_limit_reset_credits: None,
next_rate_limit_reset_request_id: 0,
account_plan: initial_plan_type,
quota_plan: None,
plan_type: initial_plan_type,
codex_rate_limit_reached_type: None,
codex_spend_control_reached: None,
+20 -2
View File
@@ -252,9 +252,27 @@ impl ChatWidget {
}
pub(crate) fn on_rate_limit_snapshot(&mut self, snapshot: Option<RateLimitSnapshot>) {
if let Some(snapshot) = &snapshot {
self.observe_quota_plan(snapshot);
}
self.on_rate_limit_snapshot_from(snapshot, RateLimitSnapshotSource::AccountUsage);
}
pub(crate) fn observe_quota_plan(&mut self, snapshot: &RateLimitSnapshot) {
if snapshot
.limit_id
.as_deref()
.is_none_or(|id| id.eq_ignore_ascii_case("codex"))
&& let Some(plan) = snapshot.plan_type.filter(|plan| *plan != PlanType::Unknown)
{
self.quota_plan = Some(plan);
if self.plan_type != Some(plan) {
self.refresh_billing_plan();
self.refresh_status_surfaces();
}
}
}
pub(crate) fn on_rolling_rate_limit_snapshot(&mut self, snapshot: RateLimitSnapshot) {
if let (Some(previous), Some(current)) = (
self.codex_rate_limit_reached_type,
@@ -302,8 +320,6 @@ impl ChatWidget {
balance: credits.balance.clone(),
});
}
self.plan_type = snapshot.plan_type.or(self.plan_type);
if is_codex_limit
&& (matches!(source, RateLimitSnapshotSource::AccountUsage)
|| snapshot.spend_control_reached.is_some())
@@ -422,6 +438,8 @@ impl ChatWidget {
}
} else {
self.rate_limit_snapshots_by_limit_id.clear();
self.quota_plan = None;
self.refresh_billing_plan();
self.codex_rate_limit_reached_type = None;
self.codex_spend_control_reached = None;
}
+6
View File
@@ -223,6 +223,7 @@ impl ChatWidget {
&mut self,
current_email: Option<String>,
current_workspace: Option<String>,
plan_type: PlanType,
) {
if let Some(StatusAccountDisplay::ChatGpt {
email, workspace, ..
@@ -230,6 +231,9 @@ impl ChatWidget {
{
*email = current_email;
*workspace = current_workspace;
self.account_plan = Some(plan_type);
self.refresh_billing_plan();
self.refresh_status_surfaces();
}
}
@@ -287,6 +291,8 @@ impl ChatWidget {
self.status_line_workspace_messages_disabled = false;
self.clear_thread_usage_state();
self.status_account_display = status_account_display;
self.account_plan = plan_type;
self.quota_plan = None;
self.plan_type = plan_type;
self.has_chatgpt_account = has_chatgpt_account;
if api_key_changed {
+8 -21
View File
@@ -275,7 +275,7 @@ impl ChatWidget {
}
if self.thread_usage_is_available() {
handle.reserve_thread_usage_label_width();
handle.set_thread_usage(self.estimated_thread_usage().cloned());
handle.set_thread_usage(self.estimated_thread_usage().cloned(), self.plan_type);
self.add_to_history(cell);
self.request_thread_usage_for_status(handle.clone());
} else {
@@ -306,38 +306,25 @@ impl ChatWidget {
request_id: u64,
snapshots: Vec<RateLimitSnapshot>,
) {
if !self
let Some(index) = self
.refreshing_status_outputs
.iter()
.any(|(pending_request_id, _)| *pending_request_id == request_id)
{
.position(|(pending_request_id, _)| *pending_request_id == request_id)
else {
return;
}
};
for snapshot in snapshots {
self.on_rate_limit_snapshot(Some(snapshot));
}
let (_, handle) = self.refreshing_status_outputs.swap_remove(index);
let rate_limit_snapshots: Vec<RateLimitSnapshotDisplay> = self
.rate_limit_snapshots_by_limit_id
.values()
.cloned()
.collect();
let now = Local::now();
let mut remaining = Vec::with_capacity(self.refreshing_status_outputs.len());
let mut updated_any = false;
for (pending_request_id, handle) in self.refreshing_status_outputs.drain(..) {
if pending_request_id == request_id {
updated_any = true;
handle.finish_rate_limit_refresh(rate_limit_snapshots.as_slice(), now);
} else {
remaining.push((pending_request_id, handle));
}
}
self.refreshing_status_outputs = remaining;
if updated_any {
self.request_redraw();
}
handle.finish_rate_limit_refresh(&rate_limit_snapshots, Local::now());
self.request_redraw();
}
pub(super) fn open_status_line_setup(&mut self) {
@@ -1333,6 +1333,10 @@ async fn rate_limit_snapshot_updates_and_retains_plan_type() {
rate_limit_reached_type: None,
}));
assert_eq!(chat.plan_type, Some(PlanType::Pro));
let unknown = serde_json::from_value(serde_json::json!({"planType": "unknown"})).unwrap();
chat.on_rate_limit_snapshot(Some(unknown));
assert_eq!(chat.plan_type, Some(PlanType::Pro));
}
#[tokio::test]
+20 -1
View File
@@ -56,6 +56,25 @@ pub(super) struct ThreadUsageState {
}
impl ChatWidget {
pub(super) fn refresh_billing_plan(&mut self) {
// A full quota read reflects the current subscription; account/read can use a cached token.
let plan = self.quota_plan.or(self.account_plan);
if self.plan_type == plan {
return;
}
let previously_available = self.thread_usage_is_available();
self.plan_type = plan;
if !self.thread_usage_is_available() {
self.clear_thread_usage_state();
} else if !previously_available {
// A pending /status can learn that the account is billable from its own quota read.
for (_, handle) in self.refreshing_status_outputs.clone() {
handle.reserve_thread_usage_label_width();
self.request_thread_usage_for_status(handle);
}
}
}
pub(super) fn clear_thread_usage_state(&mut self) {
self.thread_usage = ThreadUsageState::default();
}
@@ -299,7 +318,7 @@ impl ChatWidget {
}
if usage_updated && !self.thread_usage.status_history_handles.is_empty() {
for handle in &self.thread_usage.status_history_handles {
handle.set_thread_usage(self.thread_usage.estimate.clone());
handle.set_thread_usage(self.thread_usage.estimate.clone(), self.plan_type);
}
if self
.thread_usage
@@ -69,6 +69,115 @@ async fn replacement_widget_rejects_a_previous_widgets_read_for_the_same_thread(
assert!(replacement.is_pending_thread_usage(thread, current));
}
#[tokio::test]
async fn billing_prefers_a_known_quota_plan_in_either_reply_order() {
for (account, quota_plan, expected) in [
(PlanType::Plus, PlanType::Business, PlanType::Business),
(PlanType::Unknown, PlanType::Business, PlanType::Business),
(PlanType::Business, PlanType::Unknown, PlanType::Business),
] {
for quota_first in [true, false] {
let (mut chat, ..) = make_chatwidget_manual_with_sender().await;
chat.status_account_display = Some(crate::status::StatusAccountDisplay::ChatGpt {
email: None,
plan: None,
workspace: None,
});
let quota =
serde_json::from_value(serde_json::json!({"planType": quota_plan})).unwrap();
let account_read = |chat: &mut ChatWidget| {
chat.on_account_email_loaded(
/*current_email*/ None, /*current_workspace*/ None, account,
);
};
if quota_first {
chat.on_rate_limit_snapshot(Some(quota));
account_read(&mut chat);
} else {
account_read(&mut chat);
assert_eq!(chat.current_plan_type(), Some(account));
chat.on_rate_limit_snapshot(Some(quota));
}
assert_eq!(chat.current_plan_type(), Some(expected));
}
}
}
#[tokio::test]
async fn pending_status_card_uses_the_corrected_plan_for_its_usage_reply() {
let mut rows = Vec::new();
for original_plan in [PlanType::Business, PlanType::Plus] {
let (mut chat, _, mut events, _) = make_chatwidget_manual_with_sender().await;
let thread = ThreadId::new();
chat.thread_id = Some(thread);
chat.has_codex_backend_auth = true;
chat.plan_type = Some(original_plan);
let status_request = 1;
chat.add_status_output(/*refreshing_rate_limits*/ true, Some(status_request));
let AppEvent::InsertHistoryCell(card) = events.try_recv().unwrap() else {
panic!("expected a /status card");
};
let corrected_ent26 =
serde_json::from_value(serde_json::json!({"planType": PlanType::Ent26})).unwrap();
chat.finish_status_rate_limit_refresh(status_request, vec![corrected_ent26]);
let usage = ThreadUsage {
native_usage_usd_micros: Some(1_800_000),
..thread_usage(
thread,
/*estimated_usage_credits_micros*/ 50_000_000,
Some(2_000_000),
)
};
let request = thread_usage_request_id(&mut events);
assert!(chat.finish_thread_usage_refresh(
thread,
request,
Ok(ThreadUsageOutcome::Available(usage))
));
let row = card
.display_lines(/*width*/ 90)
.into_iter()
.map(|line| line.to_string())
.find(|line| line.contains("Thread usage:"))
.unwrap();
rows.push(format!("{original_plan:?} → Ent26: {}", row.trim()));
}
insta::assert_snapshot!(rows.join("\n"), @r"
Business → Ent26: Thread usage: ~$1.80
Plus → Ent26: Thread usage: ~$1.80
");
}
#[tokio::test]
async fn rolling_quota_cannot_restore_an_obsolete_billing_plan() {
let (mut chat, _, mut events, _) = make_chatwidget_manual_with_sender().await;
let thread = ThreadId::new();
chat.thread_id = Some(thread);
chat.has_codex_backend_auth = true;
chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".into()]);
chat.status_account_display = Some(crate::status::StatusAccountDisplay::ChatGpt {
email: None,
plan: None,
workspace: None,
});
chat.on_account_email_loaded(
/*current_email*/ None,
/*current_workspace*/ None,
PlanType::Business,
);
let pending = thread_usage_request_id(&mut events);
chat.on_account_email_loaded(
/*current_email*/ None,
/*current_workspace*/ None,
PlanType::Plus,
);
let rolling = serde_json::from_value(serde_json::json!({"planType": "business"})).unwrap();
chat.on_rolling_rate_limit_snapshot(rolling);
assert_eq!(chat.current_plan_type(), Some(PlanType::Plus));
assert!(!chat.finish_thread_usage_refresh(thread, pending, Ok(ThreadUsageOutcome::Disabled)));
}
#[test]
fn estimated_cost_formats_dollars_and_sub_cent_values() {
assert_eq!(
+3 -6
View File
@@ -119,8 +119,9 @@ impl StatusHistoryHandle {
pub(crate) fn set_thread_usage(
&self,
estimate: Option<codex_app_server_protocol::ThreadUsage>,
plan: Option<PlanType>,
) {
self.card.thread_usage.set_estimate(estimate);
self.card.thread_usage.set_estimate(estimate, plan);
}
}
@@ -142,7 +143,6 @@ struct StatusHistoryCell {
token_usage: StatusTokenUsageData,
rate_limit_state: Arc<RwLock<StatusRateLimitState>>,
thread_usage: StatusThreadUsage,
plan_type: Option<PlanType>,
}
#[cfg(test)]
@@ -422,7 +422,6 @@ impl StatusHistoryCell {
agents_summary,
rate_limit_state,
thread_usage,
plan_type: _plan_type,
}
}
@@ -897,9 +896,7 @@ impl StatusHistoryCell {
}
lines.extend(self.rate_limit_lines(&rate_limit_state, available_width, &formatter));
let thread_usage_lines = self
.thread_usage
.lines(&formatter, value_width, self.plan_type);
let thread_usage_lines = self.thread_usage.lines(&formatter, value_width);
if !thread_usage_lines.is_empty() {
lines.push(Line::from(Vec::<Span<'static>>::new()));
lines.extend(thread_usage_lines);
+21 -17
View File
@@ -12,7 +12,6 @@ use ratatui::prelude::Line;
use ratatui::style::Stylize;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::Arc;
use std::sync::RwLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
@@ -43,10 +42,16 @@ pub(crate) fn thread_cost_micros(usage: &ThreadUsage, plan_type: Option<PlanType
}
/// Shared state updates a committed `/status` card when its asynchronous estimate arrives.
#[derive(Clone, Debug, Default)]
#[derive(Debug, Default)]
pub(crate) struct StatusThreadUsage {
estimate: Arc<RwLock<Option<ThreadUsage>>>,
reserve_label_width: Arc<AtomicBool>,
billing: RwLock<CardBilling>,
reserve_label_width: AtomicBool,
}
#[derive(Debug, Default)]
struct CardBilling {
estimate: Option<ThreadUsage>,
plan: Option<PlanType>,
}
impl StatusThreadUsage {
@@ -55,13 +60,13 @@ impl StatusThreadUsage {
.store(/*val*/ true, Ordering::Relaxed);
}
pub(crate) fn set_estimate(&self, estimate: Option<ThreadUsage>) {
pub(crate) fn set_estimate(&self, estimate: Option<ThreadUsage>, plan: Option<PlanType>) {
#[expect(clippy::expect_used)]
let mut stored_estimate = self
.estimate
let mut billing = self
.billing
.write()
.expect("status history thread-usage state poisoned");
*stored_estimate = estimate;
*billing = CardBilling { estimate, plan };
}
pub(crate) fn push_labels(&self, labels: &mut Vec<String>, seen: &mut BTreeSet<String>) {
@@ -71,11 +76,11 @@ impl StatusThreadUsage {
push_label(labels, seen, BILLED_TOKENS_LABEL);
}
#[expect(clippy::expect_used)]
let stored_estimate = self
.estimate
let billing = self
.billing
.read()
.expect("status history thread-usage state poisoned");
let Some(estimate) = stored_estimate.as_ref() else {
let Some(estimate) = billing.estimate.as_ref() else {
return;
};
push_label(labels, seen, "Thread usage");
@@ -97,20 +102,19 @@ impl StatusThreadUsage {
&self,
formatter: &FieldFormatter,
value_width: usize,
plan_type: Option<PlanType>,
) -> Vec<Line<'static>> {
#[expect(clippy::expect_used)]
let stored_estimate = self
.estimate
let billing = self
.billing
.read()
.expect("status history thread-usage state poisoned");
let Some(estimate) = stored_estimate.as_ref() else {
let Some(estimate) = billing.estimate.as_ref() else {
return Vec::new();
};
if plan_type == Some(PlanType::Ent26) {
if billing.plan == Some(PlanType::Ent26) {
// Credit-weighted breakdowns do not describe native dollar usage.
return thread_cost_micros(estimate, plan_type)
return thread_cost_micros(estimate, billing.plan)
.and_then(format_estimated_usd_micros)
.map(|cost| vec![formatter.line("Thread usage", vec![cost.into()])])
.unwrap_or_default();