Refresh analytics on identity changes and compact usage menus (#46862)

## Why

Analytics must discard previously loaded reports when account identity checks fail. Usage actions also need to remain readable on narrow terminals and reflect customized list bindings.

## What changed

- Track identity invalidation across analytics reports and refresh the view to clear stale data and reload the account and reports.
- Recheck identity around chat and task loading, including after asynchronous work, before accepting results.
- Shorten `/usage` labels and use picker layouts that hide descriptions when space is limited. Show action-specific `open`, `choose`, and `confirm` hints using the active list keymap.

## Testing

Extend regression coverage for account switches during report loading, clearing and reloading reports, and retrying account discovery with `R`. Add a narrow usage-menu snapshot and update usage and reset-dialog expectations.

GitOrigin-RevId: 0c60a0f930c6b00457aa897711bd5a496c7decde
This commit is contained in:
Eric Traut
2026-09-20 18:17:27 +00:00
committed by copyberry
parent d2d196bd6a
commit 5e5cadad6b
18 changed files with 195 additions and 67 deletions
+6 -4
View File
@@ -44,11 +44,12 @@ pub(super) async fn read(
if !super::models::thread_usage_supported(session.backend.account().plan_type) {
return Ok(None);
}
session.backend.ensure_identity().await?;
live.ensure_identity().await?;
let threads = tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 60), roots(&handle))
.await
.map_err(|_| "Chat listing timed out. Press R to retry.".to_string())??;
session.backend.ensure_identity().await?;
.map_err(|_| "Chat listing timed out. Press R to retry.".to_string());
live.ensure_identity().await?;
let threads = threads??;
if threads.is_empty() {
return Ok(Some(Chats { rows: Vec::new() }));
}
@@ -65,6 +66,7 @@ pub(super) async fn read(
tokio::time::timeout_at(deadline, estimates(session, &pair[..midpoint])),
tokio::time::timeout_at(deadline, estimates(session, &pair[midpoint..])),
);
live.ensure_identity().await?;
for batch in [first, second].into_iter().flatten() {
data.extend(batch?);
}
@@ -72,7 +74,7 @@ pub(super) async fn read(
break;
}
}
session.backend.ensure_identity().await?;
live.ensure_identity().await?;
let mut usage: HashMap<_, _> = data
.into_iter()
.map(|row| (row.thread_id.clone(), row))
+18 -3
View File
@@ -17,6 +17,7 @@ use tokio::sync::Mutex;
use tokio::sync::OnceCell;
pub(super) struct Live {
pub(super) identity_invalidated: std::sync::atomic::AtomicBool,
config: Arc<Config>,
end_date: chrono::NaiveDate,
session: OnceCell<Session>,
@@ -34,6 +35,7 @@ pub(super) struct Session {
impl Live {
pub(super) fn new(config: Arc<Config>, end_date: chrono::NaiveDate) -> Self {
Self {
identity_invalidated: std::sync::atomic::AtomicBool::new(/*v*/ false),
config,
end_date,
session: OnceCell::new(),
@@ -91,6 +93,19 @@ impl Live {
.await
}
/// Every report shares the same privacy boundary, including cached report loads.
pub(super) async fn ensure_identity(&self) -> Result<(), String> {
let identity = match self.session().await {
Ok(session) => session.backend.ensure_identity().await,
Err(error) => Err(error),
};
if identity.is_err() {
self.identity_invalidated
.store(/*val*/ true, std::sync::atomic::Ordering::Relaxed);
}
identity
}
pub(super) async fn plan_history(&self) -> Result<Option<super::plan::Report>, String> {
let session = self.session().await?;
if session.kind != AccountKind::Consumer {
@@ -100,7 +115,7 @@ impl Live {
.backend
.request(|client| async move { client.get_plan_limit_history().await })
.await;
session.backend.ensure_identity().await?;
self.ensure_identity().await?;
history
.map_err(request_error)?
.map(super::plan::Report::parse)
@@ -131,7 +146,7 @@ impl Live {
.and_then(|offset| end.checked_sub_days(chrono::Days::new(u64::from(offset))))
.ok_or("Invalid analytics date range.")?;
let session = self.session().await?;
session.backend.ensure_identity().await?;
self.ensure_identity().await?;
let enterprise_tokens = report == Report::Usage
&& matches!(
session.kind,
@@ -166,7 +181,7 @@ impl Live {
.await
.map(AnalyticsData::from)
};
session.backend.ensure_identity().await?;
self.ensure_identity().await?;
let response = response.map_err(request_error)?;
let history = (|| {
if enterprise_tokens {
+1 -1
View File
@@ -14,7 +14,7 @@ use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
pub(super) fn sign_in(home: &std::path::Path, account: &str, user: &str, plan: &str) {
pub(in crate::analytics) fn sign_in(home: &std::path::Path, account: &str, user: &str, plan: &str) {
let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(
json!({
"exp": 4102444800_i64, "email": "analytics@example.test",
+49 -2
View File
@@ -1,6 +1,7 @@
//! Exercise local Analytics plan discovery and report recovery while connected to an app-server.
use super::tests::live;
use super::tests::sign_in;
use codex_app_server_client::AppServerRequestHandle;
use codex_app_server_client::RemoteAppServerClient;
use codex_app_server_client::RemoteAppServerConnectArgs;
@@ -70,7 +71,7 @@ async fn local_reports_share_an_account_and_recover_profile_errors() {
use crate::analytics::sections::Section;
let http = crate::analytics::test_support::server().await;
let (_home, local) = live(&http, "enterprise").await;
let (home, local) = live(&http, "enterprise").await;
let (client, server) = remote().await;
let failed_profile = Mock::given(method("GET"))
.and(wiremock::matchers::path("/backend-api/wham/profiles/me"))
@@ -129,6 +130,49 @@ async fn local_reports_share_an_account_and_recover_profile_errors() {
"account-a"
);
}
Mock::given(method("GET"))
.and(wiremock::matchers::path("/backend-api/wham/accounts/check"))
.and(header("chatgpt-account-id", "account-b"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"accounts": [{"id": "account-b", "plan_type": "enterprise"}]
})))
.with_priority(/*p*/ 1)
.expect(/*r*/ 1)
.mount(&http)
.await;
sign_in(home.path(), "account-b", "user-b", "enterprise");
assert!(
view.live
.as_ref()
.unwrap()
.history(
super::Report::Usage,
/*days*/ 7,
super::Grouping::Surface
)
.await
.is_err()
);
view.poll_reports();
assert!(matches!(view.account, Load::Loading(_)));
assert!(matches!(view.profile, Load::Unavailable));
assert!(
view.sections
.0
.iter()
.all(|section| matches!(section.history, Load::Unavailable))
);
crate::analytics::test_support::settle(&mut view).await;
assert_eq!(
view.account.ready(),
Some(&codex_protocol::account::PlanType::Enterprise)
);
for section in view.visible_sections() {
if section.report().is_some() {
assert!(view.sections[*section].history.ready().is_some());
}
}
http.verify().await;
view.cancel_loads();
client.shutdown().await.unwrap();
server.await.unwrap();
@@ -184,7 +228,10 @@ async fn account_lookup_failure_recovers_on_refresh_with_the_server_plan() {
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"stats": {}})))
.mount(&http)
.await;
view.refresh();
view.handle_key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Char('R'),
crossterm::event::KeyModifiers::NONE,
));
crate::analytics::test_support::settle(&mut view).await;
assert_eq!(
view.visible_sections(),
+7
View File
@@ -78,6 +78,13 @@ pub(super) enum RangeGroup {
impl AnalyticsView {
pub(super) fn poll_reports(&mut self) {
if self.live.as_ref().is_some_and(|live| {
live.identity_invalidated
.load(std::sync::atomic::Ordering::Relaxed)
}) {
self.refresh();
return;
}
for section in &mut self.sections.0 {
section.history.poll();
}
+1 -1
View File
@@ -22,7 +22,7 @@ impl Live {
.backend
.request(|client| async move { client.get_account_profile().await })
.await;
session.backend.ensure_identity().await?;
self.ensure_identity().await?;
profile.map(Some).map_err(super::client::request_error)
}
}
+8 -5
View File
@@ -45,14 +45,15 @@ pub(super) async fn read(
if session.kind != super::models::AccountKind::Consumer {
return Ok(None);
}
session.backend.ensure_identity().await?;
let mut roots = tokio::time::timeout(
live.ensure_identity().await?;
let roots = tokio::time::timeout(
std::time::Duration::from_secs(/*secs*/ 60),
super::chats::roots(&handle),
)
.await
.map_err(|_| "Chat listing timed out. Press R to retry.".to_string())??;
session.backend.ensure_identity().await?;
.map_err(|_| "Chat listing timed out. Press R to retry.".to_string());
live.ensure_identity().await?;
let mut roots = roots??;
roots.sort_by(|a, b| {
b.updated_at
.cmp(&a.updated_at)
@@ -74,6 +75,7 @@ pub(super) async fn read(
}
}
drop(pending);
live.ensure_identity().await?;
let mut seen = HashSet::new();
let mut batches = Vec::new();
let mut batch = Vec::new();
@@ -114,6 +116,7 @@ pub(super) async fn read(
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(/*secs*/ 25);
while let Ok(Some(result)) = tokio::time::timeout_at(deadline, pending.next()).await {
completed_batches += 1;
live.ensure_identity().await?;
match result {
Ok(response) => {
freshness.push(
@@ -146,7 +149,7 @@ pub(super) async fn read(
freshness.push(/*value*/ None);
}
drop(pending);
session.backend.ensure_identity().await?;
live.ensure_identity().await?;
Ok(Some(Chats {
truncated,
updated_at: if freshness.iter().all(Option::is_some) {
+27 -4
View File
@@ -12,7 +12,13 @@ use wiremock::matchers::path;
#[tokio::test]
async fn consumer_roots_include_paginated_archived_descendants_and_keep_missing_usage() {
for (unsupported, status) in [(false, 200), (true, 200), (false, 404), (false, 503)] {
for (unsupported, status, switch_account) in [
(false, 200, false),
(true, 200, false),
(false, 404, false),
(false, 503, false),
(false, 200, true),
] {
use codex_app_server_client::RemoteAppServerClient;
use codex_app_server_client::RemoteAppServerConnectArgs;
use codex_app_server_client::RemoteAppServerEndpoint;
@@ -20,7 +26,8 @@ async fn consumer_roots_include_paginated_archived_descendants_and_keep_missing_
use tokio_tungstenite::tungstenite::Message;
let server = MockServer::start().await;
let (_home, live) = live(&server, "plus").await;
let (home, live) = live(&server, "plus").await;
let home_path = home.path().to_path_buf();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let websocket_url = format!("ws://{}", listener.local_addr().unwrap());
let rpc = tokio::spawn(async move {
@@ -103,12 +110,29 @@ async fn consumer_roots_include_paginated_archived_descendants_and_keep_missing_
]});
if unsupported { expected["threads"].as_array_mut().unwrap().retain(|thread| thread["thread_id"] == "missing"); }
assert_eq!(body, expected);
if switch_account {
super::super::client::tests::sign_in(&home_path, "account-b", "user-b", "plus");
}
let mut response=json!({"data_as_of":null,"threads":[]});
if !unsupported { response["threads"] = json!([{ "thread_id":"root", "data_status":"partial", "usage_source":"included_plan", "weekly_limit_percent":125, "five_hour_limit_percent":null, "balance_usage_credits":null, "groups":[] }]); }
ResponseTemplate::new(status).set_body_json(response)
}).expect(/*r*/ 1).mount(&server).await;
let handle = AppServerRequestHandle::Remote(remote.request_handle());
let chats = read(handle, Arc::new(live)).await.unwrap().unwrap();
let live = Arc::new(live);
let result = read(handle, Arc::clone(&live)).await;
assert_eq!(rpc.await.unwrap(), if unsupported { 4 } else { 6 });
if switch_account {
assert_eq!(
(
result.is_err(),
live.identity_invalidated
.load(std::sync::atomic::Ordering::Relaxed),
),
(true, true)
);
continue;
}
let chats = result.unwrap().unwrap();
assert_eq!(
(
chats.rows.len(),
@@ -127,6 +151,5 @@ async fn consumer_roots_include_paginated_archived_descendants_and_keep_missing_
}
)
);
assert_eq!(rpc.await.unwrap(), if unsupported { 4 } else { 6 });
}
}
+4 -1
View File
@@ -303,7 +303,10 @@ async fn stale_rate_limit_reads_preserve_newer_workspace_hard_stop_for_every_ori
let popup = render_bottom_popup(&app.chat_widget, /*width*/ 100);
match origin_name {
"usage" => assert!(popup.contains("No usage limit resets available.")),
"usage" => assert!(
popup.contains("Redeem reset None available."),
"expected usage reset availability, got: {popup}"
),
"reset-picker" => {
assert!(popup.contains("You don't have any usage limit resets available."));
}
@@ -9,4 +9,4 @@ expression: "render_bottom_popup(&chat, 80)"
1. Yes, use reset Reset your weekly and 5-hour usage limits.
› 2. No, go back Choose a different reset.
enter select · esc back
enter confirm · esc back
@@ -1,6 +1,5 @@
---
source: tui/src/chatwidget/tests/usage.rs
assertion_line: 429
expression: "render_bottom_popup(&chat, 44)"
---
Usage limit resets
@@ -12,4 +11,4 @@ expression: "render_bottom_popup(&chat, 44)"
2. Full reset Does not expire.
3. Cancel
enter select · esc back
enter choose · esc back
@@ -1,6 +1,5 @@
---
source: tui/src/chatwidget/tests/usage.rs
assertion_line: 409
expression: "states.join(\"\\n---\\n\")"
---
Usage limit resets
@@ -19,7 +18,7 @@ expression: "states.join(\"\\n---\\n\")"
2. Full reset (Weekly + 5 hr) Expires 08:59 on 27 Jun 2026.
3. Cancel
enter select · esc back
enter choose · esc back
---
Usage limit resets
You don't have any usage limit resets available.
@@ -3,10 +3,10 @@ source: tui/src/chatwidget/tests/usage.rs
expression: "render_bottom_popup(&chat, 80)"
---
Usage
View account usage or redeem an earned reset.
Account usage and resets.
› 1. View analytics Browse account usage and activity.
2. Redeem usage limit reset You have 2 usage limit resets available.
› 1. View analytics Usage history.
2. Redeem reset 2 available.
enter select · esc back
enter open · esc back
@@ -1,13 +1,12 @@
---
source: tui/src/chatwidget/tests/usage.rs
assertion_line: 261
expression: "render_bottom_popup(&chat, 80)"
---
Usage
View account usage or redeem an earned reset.
Account usage and resets.
› 1. View analytics Browse account usage and activity.
2. Redeem usage limit reset Check reset availability.
› 1. View analytics Usage history.
2. Redeem reset Check availability.
enter select · esc back
enter open · esc back
@@ -0,0 +1,12 @@
---
source: tui/src/chatwidget/tests/usage.rs
expression: "render_bottom_popup(&chat, 40)"
---
Usage
Account usage and resets.
› 1. View analytics
2. Redeem reset
enter open · esc back
@@ -3,10 +3,10 @@ source: tui/src/chatwidget/tests/usage.rs
expression: "render_bottom_popup(&chat, 80)"
---
Usage
View account usage or redeem an earned reset.
Account usage and resets.
› 1. View analytics Browse account usage and activity.
Redeem usage limit reset No usage limit resets available.
› 1. View analytics Usage history.
Redeem reset None available.
enter select · esc back
enter open · esc back
+7 -3
View File
@@ -128,6 +128,10 @@ async fn usage_command_opens_menu_when_reset_is_available_snapshot() {
"usage_command_menu",
render_bottom_popup(&chat, /*width*/ 80)
);
assert_chatwidget_snapshot!(
"usage_command_menu_narrow",
render_bottom_popup(&chat, /*width*/ 40)
);
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_matches!(rx.try_recv(), Ok(AppEvent::OpenAnalytics { view: None }));
}
@@ -212,7 +216,7 @@ async fn usage_menu_refresh_failure_preserves_disabled_known_zero() {
Err("backend unavailable".to_string()),
);
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("No usage limit resets available."));
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("None available."));
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_matches!(rx.try_recv(), Ok(AppEvent::OpenAnalytics { view: None }));
}
@@ -816,8 +820,8 @@ async fn failed_post_consume_refresh_does_not_keep_stale_reset_count() {
chat.dispatch_command(SlashCommand::Usage);
let rendered = render_bottom_popup(&chat, /*width*/ 80);
assert!(rendered.contains("Check reset availability."));
assert!(!rendered.contains("You have 2 usage limit resets available."));
assert!(rendered.contains("Check availability."));
assert!(!rendered.contains("2 available."));
}
#[tokio::test]
+40 -25
View File
@@ -33,28 +33,22 @@ impl ChatWidget {
let reset_eligible = self.has_chatgpt_account;
let (reset_action_enabled, reset_description) =
match (reset_eligible, self.available_rate_limit_reset_credits) {
(true, Some(available_count)) if available_count > 0 => (
true,
format!(
"You have {available_count} {} available.",
reset_label(available_count)
),
),
(true, None) => (true, "Check reset availability.".to_string()),
(true, Some(_)) | (false, _) => {
(false, "No usage limit resets available.".to_string())
(true, Some(available_count)) if available_count > 0 => {
(true, format!("{available_count} available."))
}
(true, None) => (true, "Check availability.".to_string()),
(true, Some(_)) | (false, _) => (false, "None available.".to_string()),
};
SelectionViewParams {
view_id: Some(USAGE_MENU_VIEW_ID),
title: Some("Usage".to_string()),
subtitle: Some("View account usage or redeem an earned reset.".to_string()),
footer_hint: Some(standard_popup_hint_line()),
subtitle: Some("Account usage and resets.".to_string()),
footer_hint: Some(usage_hint_line(&self.bottom_pane.list_keymap(), "open")),
items: vec![
SelectionItem {
name: "View analytics".to_string(),
description: Some("Browse account usage and activity.".to_string()),
description: Some("Usage history.".to_string()),
actions: vec![Box::new(|tx| {
tx.send(AppEvent::OpenAnalytics { view: None });
})],
@@ -62,7 +56,7 @@ impl ChatWidget {
..Default::default()
},
SelectionItem {
name: "Redeem usage limit reset".to_string(),
name: "Redeem reset".to_string(),
description: Some(reset_description),
is_disabled: !reset_action_enabled,
actions: vec![Box::new(|tx| {
@@ -72,7 +66,7 @@ impl ChatWidget {
..Default::default()
},
],
..Default::default()
..SelectionViewParams::picker()
}
}
@@ -116,7 +110,7 @@ impl ChatWidget {
is_disabled: true,
..Default::default()
}],
..Default::default()
..SelectionViewParams::picker()
});
self.request_redraw();
request_id
@@ -214,10 +208,10 @@ impl ChatWidget {
reset_credits.available_count,
reset_label(reset_credits.available_count)
)),
footer_hint: Some(standard_popup_hint_line()),
footer_hint: Some(usage_hint_line(&self.bottom_pane.list_keymap(), "choose")),
items,
initial_selected_idx: Some(0),
..Default::default()
..SelectionViewParams::picker()
}
}
@@ -250,7 +244,7 @@ impl ChatWidget {
view_id: Some(RATE_LIMIT_RESET_CONFIRMATION_VIEW_ID),
title: Some("Use this reset?".to_string()),
subtitle: Some(subtitle),
footer_hint: Some(standard_popup_hint_line()),
footer_hint: Some(usage_hint_line(&self.bottom_pane.list_keymap(), "confirm")),
items: vec![
SelectionItem {
name: "Yes, use reset".to_string(),
@@ -278,7 +272,7 @@ impl ChatWidget {
on_cancel: Some(Box::new(move |_| {
confirmation_gate.store(true, Ordering::Release);
})),
..Default::default()
..SelectionViewParams::picker()
});
true
}
@@ -303,7 +297,7 @@ impl ChatWidget {
dismiss_on_select: true,
..Default::default()
}],
..Default::default()
..SelectionViewParams::picker()
}
}
@@ -327,7 +321,7 @@ impl ChatWidget {
..Default::default()
},
],
..Default::default()
..SelectionViewParams::picker()
}
}
@@ -351,7 +345,7 @@ impl ChatWidget {
..Default::default()
}],
allow_cancel: false,
..Default::default()
..SelectionViewParams::picker()
});
self.request_redraw();
request_id
@@ -428,7 +422,7 @@ impl ChatWidget {
..Default::default()
},
],
..Default::default()
..SelectionViewParams::picker()
});
false
}
@@ -475,7 +469,7 @@ impl ChatWidget {
..Default::default()
}],
allow_cancel: false,
..Default::default()
..SelectionViewParams::picker()
}
}
@@ -577,6 +571,27 @@ impl ChatWidget {
}
}
/// Keep usage actions readable on narrow terminals and honor customized list bindings.
fn usage_hint_line(
keymap: &crate::keymap::ListKeymap,
accept_label: &'static str,
) -> Line<'static> {
let mut spans = Vec::new();
for (action, label) in [
(crate::keymap::ListAction::Accept, accept_label),
(crate::keymap::ListAction::Cancel, "back"),
] {
if let Some(hint) = keymap.primary_hint(action) {
if !spans.is_empty() {
spans.push(" · ".into());
}
spans.extend(hint.spans());
spans.push(format!(" {label}").into());
}
}
Line::from(spans)
}
fn reset_label(count: i64) -> &'static str {
if count == 1 {
"usage limit reset"