Add an account Summary tab to Analytics (#45769)

## What changed

- Make Summary the initial Analytics tab, showing profile identity, token totals, streaks, activity insights, and most-used plugins and skills.
- Move daily, weekly, and cumulative token activity charts into Summary. Replace the usage menu's separate views with “View analytics”; `/usage weekly` and the other explicit modes open Summary with the requested view, while reopening from the menu retains navigation.
- Load account profiles independently of other reports, preserve missing values separately from zero, and reject responses when the active account changes. Refresh retries profile failures.
- Adapt Summary to narrow terminals and compact large chart totals and axis labels. Show the account email without its ID in the Analytics header.
- Flush queued transcript history before opening an overlay so startup output stays in the transcript.

## Testing

Add profile decoding and account identity tests, Summary layout and navigation snapshots, refresh and cancellation coverage, and regression tests for retained navigation and transcript history when opening Analytics.

GitOrigin-RevId: 6dbe6c4c98209000d8b4bc18a4e01b98fab5991a
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-09-15 19:13:08 +00:00
1 parent 8f0d2459ac
commit 9bd49c9dcc
122 files changed
+3685 -1980

No files matched your search

@@ -30,8 +30,6 @@ use crate::hooks_rpc::write_hook_trust;
use crate::hooks_rpc::write_hook_trusts;
use codex_utils_absolute_path::AbsolutePathBuf;
const TOKEN_ACTIVITY_FETCH_TIMEOUT: std::time::Duration =
std::time::Duration::from_secs(/*secs*/ 15);
pub(super) const THREAD_USAGE_FETCH_TIMEOUT: std::time::Duration =
std::time::Duration::from_secs(/*secs*/ 65);
const RATE_LIMIT_RESET_REQUEST_TIMEOUT: std::time::Duration =
@@ -124,25 +122,6 @@ impl App {
});
}
pub(super) fn refresh_token_activity(
&mut self,
app_server: &AppServerSession,
request_id: u64,
) {
let request_handle = app_server.request_handle();
let app_event_tx = self.app_event_tx.clone();
tokio::spawn(async move {
let result = tokio::time::timeout(
TOKEN_ACTIVITY_FETCH_TIMEOUT,
fetch_account_token_activity(request_handle),
)
.await
.map_err(|_| "account/usage/read timed out in TUI".to_string())
.and_then(|result| result.map_err(|err| err.to_string()));
app_event_tx.send(AppEvent::TokenActivityLoaded { request_id, result });
});
}
pub(super) fn refresh_thread_usage(
&mut self,
app_server: &AppServerSession,
@@ -831,19 +810,6 @@ pub(super) async fn fetch_account_rate_limits(
result.wrap_err("account/rateLimits/read failed in TUI")
}
pub(super) async fn fetch_account_token_activity(
request_handle: AppServerRequestHandle,
) -> Result<codex_app_server_protocol::GetAccountTokenUsageResponse> {
let request_id = RequestId::String(format!("account-token-usage-{}", Uuid::new_v4()));
request_handle
.request_typed(ClientRequest::GetAccountTokenUsage {
request_id,
params: None,
})
.await
.wrap_err("account/usage/read failed in TUI")
}
pub(super) async fn fetch_thread_usage(
request_handle: AppServerRequestHandle,
thread_id: ThreadId,
+4 -24
View File
@@ -1413,9 +1413,6 @@ impl App {
self.refresh_rate_limits(app_server, RateLimitRefreshOrigin::Periodic);
}
}
AppEvent::RefreshTokenActivity { request_id } => {
self.refresh_token_activity(app_server, request_id);
}
AppEvent::RefreshThreadUsage {
thread_id,
request_id,
@@ -1605,16 +1602,15 @@ impl App {
self.chat_widget.finish_rate_limit_recovery();
}
},
AppEvent::OpenTokenActivity => {
self.chat_widget
.add_token_activity_output(crate::chatwidget::TokenActivityView::Daily);
}
AppEvent::OpenAnalytics => {
AppEvent::OpenAnalytics { view: summary_view } => {
tui.enter_alt_screen()?;
let mut view = self.retained_analytics.take().unwrap_or_else(|| {
Box::new(crate::analytics::AnalyticsView::new(self.keymap.list.clone()))
});
view.keymap = self.keymap.list.clone();
if summary_view.is_some() {
view.select_summary(summary_view);
}
view.open(
app_server.request_handle(),
tui.frame_requester(),
@@ -1692,22 +1688,6 @@ impl App {
);
}
}
AppEvent::TokenActivityLoaded { request_id, result } => {
if let Err(err) = &result {
tracing::warn!("account/usage/read failed during TUI refresh: {err}");
}
if self
.chat_widget
.finish_token_activity_refresh(request_id, result)
{
// Commit synchronously so an already queued /clear cannot overtake this card.
// Do not route through ChatWidget::add_to_history: /usage may complete during
// active work, and flushing an in-progress tool cell would corrupt its lifecycle.
// If an answer stream is active, keep the settled card transient until its
// provisional transcript cells have been consolidated.
self.insert_pending_usage_output_if_ready(tui);
}
}
AppEvent::ThreadUsageLoaded {
thread_id,
request_id,
-4
View File
@@ -197,9 +197,6 @@ impl App {
}
fn insert_pending_usage_output(&mut self, tui: &mut tui::Tui) {
if let Some(cell) = self.chat_widget.take_completed_token_activity_output() {
self.insert_history_cell(tui, Box::new(cell));
}
if let Some(cell) = self.chat_widget.take_pending_rate_limit_reset_hint() {
self.insert_history_cell(tui, Box::new(cell));
}
@@ -324,7 +321,6 @@ impl App {
self.deferred_history_lines.clear();
self.has_emitted_history_lines = false;
self.transcript_reflow.clear();
self.chat_widget.clear_pending_token_activity_refreshes();
self.chat_widget.clear_pending_rate_limit_reset_hint();
self.initial_history_replay_buffer = None;
self.scrollback_has_older_history = false;
-32
View File
@@ -8538,38 +8538,6 @@ async fn refreshed_snapshot_session_persists_resumed_turns() {
);
}
#[tokio::test]
async fn late_usage_result_can_follow_finalized_plan() {
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
app.chat_widget
.add_token_activity_output(crate::chatwidget::TokenActivityView::Daily);
let request_id = match app_event_rx.try_recv() {
Ok(AppEvent::RefreshTokenActivity { request_id }) => request_id,
other => panic!("expected token activity refresh request, got {other:?}"),
};
app.chat_widget.note_stream_consolidation_queued();
app.transcript_cells
.push(Arc::new(history_cell::new_proposed_plan_stream(
vec![Line::from("finalized plan")],
/*is_stream_continuation*/ false,
)));
app.chat_widget.note_stream_consolidation_completed();
assert!(
app.chat_widget.finish_token_activity_refresh(
request_id,
Err("token activity unavailable".to_string()),
)
);
assert!(!app.pending_usage_output_insertion_blocked());
assert!(
app.chat_widget
.take_completed_token_activity_output()
.is_some()
);
}
#[tokio::test]
async fn new_session_requests_shutdown_for_previous_conversation() {
Box::pin(async {
@@ -0,0 +1,78 @@
---
source: tui/src/app/tests/transcript_composer.rs
expression: snapshot
---
Analytics · Live account
[7d] 30d · [date range]
1 Summary 2 Total usage history 3 Messages [4 Plugins called] 5 Skills
used 6 Top chats
▎ Plugins called
────────────────────────────────────────────────────────────────────────────
No data reported for this range.
tab/1–6 section · z dashboard · ←/→ day
r 7/30d · R refresh · pgup/pgdn scroll · esc back · q close
Analytics · Live account
[7d] 30d · [date range]
1 Summary 2 Total usage history 3 Messages [4 Plugins called] 5 Skills
used 6 Top chats
▎ Plugins called
────────────────────────────────────────────────────────────────────────────
No data reported for this range.
tab/1–6 section · z dashboard · ←/→ day
r 7/30d · R refresh · pgup/pgdn scroll · esc back · q close
Analytics · Live account
[1 Summary] 2 Total usage history 3 Messages 4 Plugins called 5 Skills
used 6 Top chats
▎ Summary
────────────────────────────────────────────────────────────────────────────
Plus
12.3K — —
Lifetime tokens Peak tokens Longest chat
— —
Current streak Longest streak
Token activity Daily [Weekly] Cumulative
Last 12 months
Token activity history unavailable
Activity insights Most used plugins and skills
tab/1–6 section · z dashboard · ↑/↓ scroll
g view · R refresh · pgup/pgdn scroll · esc back · q close
@@ -47,8 +47,12 @@ async fn analytics_preserves_the_draft_and_retains_the_view_on_reopen() -> Resul
let mut tui = crate::tui::test_support::make_test_tui()?;
app.chat_widget
.apply_external_edit("preserved draft".into());
app.handle_event(&mut tui, &mut app_server, AppEvent::OpenAnalytics)
.await?;
app.handle_event(
&mut tui,
&mut app_server,
AppEvent::OpenAnalytics { view: None },
)
.await?;
for code in [
KeyCode::Char('4'),
KeyCode::Enter,
@@ -62,8 +66,12 @@ async fn analytics_preserves_the_draft_and_retains_the_view_on_reopen() -> Resul
press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('q')).await?;
assert!(app.overlay.is_none());
assert!(app.retained_analytics.is_some());
app.handle_event(&mut tui, &mut app_server, AppEvent::OpenAnalytics)
.await?;
app.handle_event(
&mut tui,
&mut app_server,
AppEvent::OpenAnalytics { view: None },
)
.await?;
assert!(matches!(app.overlay, Some(Overlay::Analytics(_))));
assert!(app.retained_analytics.is_none());
press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('q')).await?;
@@ -74,6 +82,138 @@ async fn analytics_preserves_the_draft_and_retains_the_view_on_reopen() -> Resul
Ok(())
}
#[tokio::test]
async fn analytics_menu_reopen_preserves_navigation_and_explicit_view_selects_summary() -> Result<()>
{
let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await;
let http = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.and(wiremock::matchers::path("/backend-api/wham/accounts/check"))
.and(wiremock::matchers::header(
"chatgpt-account-id",
"test-account",
))
.respond_with(wiremock::ResponseTemplate::new(/*s*/ 200).set_body_json(
serde_json::json!({"accounts": [{"id": "test-account", "plan_type": "plus"}]}),
))
.expect(/*r*/ 3)
.mount(&http)
.await;
wiremock::Mock::given(wiremock::matchers::method("GET"))
.respond_with(
wiremock::ResponseTemplate::new(/*s*/ 200)
.set_body_json(serde_json::json!({"stats":{"lifetime_tokens":12345},"data":[]})),
)
.mount(&http)
.await;
app.config.chatgpt_base_url = format!("{}/backend-api", http.uri());
app.config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File;
app_test_support::write_chatgpt_auth(
&app.config.codex_home,
app_test_support::ChatGptAuthFixture::new("test-access-token")
.account_id("test-account")
.chatgpt_account_id("test-account")
.chatgpt_user_id("test-user")
.plan_type("plus"),
codex_login::AuthCredentialsStoreMode::File,
)
.unwrap();
let mut app_server = start_config_write_test_app_server(&app).await?;
let mut tui = crate::tui::test_support::make_test_tui()?;
let mut screens = Vec::new();
for explicit in [
None,
None,
Some(crate::analytics::TokenActivityView::Weekly),
] {
app.handle_event(
&mut tui,
&mut app_server,
AppEvent::OpenAnalytics { view: explicit },
)
.await?;
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 10), async {
loop {
app.handle_tui_event(&mut tui, &mut app_server, TuiEvent::Draw)
.await?;
let text = buffer_text(crate::custom_terminal::test_support::last_rendered_buffer(
&tui.terminal,
));
if screens.is_empty() && text.contains("Lifetime tokens") {
press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('4')).await?;
continue;
}
if text.contains("Lifetime tokens")
|| text.contains("No activity")
|| text.contains("No data reported")
{
return Ok::<(), color_eyre::Report>(());
}
tokio::time::sleep(std::time::Duration::from_millis(/*millis*/ 5)).await;
}
})
.await??;
let screen = buffer_text(crate::custom_terminal::test_support::last_rendered_buffer(
&tui.terminal,
));
screens.push(screen);
press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('q')).await?;
}
assert_eq!(screens[0], screens[1]);
assert!(screens[1].contains("[4 Plugins called]"));
assert!(screens[2].contains("[1 Summary]"));
assert!(screens[2].contains("[Weekly]"));
let snapshot = screens.join("\n\n");
let snapshot = snapshot
.lines()
.map(|line| {
if line.starts_with(" [7d] 30d · ") {
" [7d] 30d · [date range]"
} else {
line
}
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(snapshot);
Ok(())
}
#[tokio::test]
async fn analytics_keeps_queued_and_late_startup_history_out_of_the_overlay() -> Result<()> {
for alternate_screen in [true, false] {
let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await;
let mut app_server = start_config_write_test_app_server(&app).await?;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_alt_screen_enabled(alternate_screen);
app.insert_history_cell(
&mut tui,
Box::new(PlainHistoryCell::new(vec!["Startup header".into()])),
);
assert!(!tui.pending_history_lines_for_test().is_empty());
app.handle_event(
&mut tui,
&mut app_server,
AppEvent::OpenAnalytics { view: None },
)
.await?;
assert!(tui.pending_history_lines_for_test().is_empty());
app.insert_history_cell(
&mut tui,
Box::new(PlainHistoryCell::new(vec![
"Late startup announcement".into(),
])),
);
assert!(tui.pending_history_lines_for_test().is_empty());
let deferred = app.deferred_history_lines.clone();
assert!(!deferred.is_empty());
press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('q')).await?;
assert_eq!(tui.pending_history_lines_for_test(), deferred);
assert_eq!(app.transcript_cells.len(), 2);
}
Ok(())
}
#[tokio::test]
async fn transcript_flag_off_preserves_viewer_and_backtracking() -> Result<()> {
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;