mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
feat(tui): reland token activity command (#27925)
## Why [#25345](https://github.com/openai/codex/pull/25345) was approved, green, and squash-merged into its stacked base branch, `fcoury/tokenmaxxing-api`. Four minutes later, that base branch was force-pushed back to an API-only rebased head while preparing [#25344](https://github.com/openai/codex/pull/25344) for `main`. As a result, the squash commit from #25345 was orphaned and the TUI command never reached `main` or a release. This PR relands the orphaned TUI change from [`411410b8`](https://github.com/openai/codex/commit/411410b85c2d8eb050d441f17396c5c4048d866f) on current `main`. ## What changed - Add `/usage`, `/usage daily`, `/usage weekly`, and `/usage cumulative` for account token activity. - Fetch account usage asynchronously through the existing `account/usage/read` app-server RPC. - Render daily, weekly, and cumulative activity with theme-aware terminal palettes and bounded transient cards. - Preserve transcript ordering while assistant streams, history consolidations, active cells, and hooks complete. - Hide `/usage` from completion when backend auth is unavailable while keeping typed-command guidance. - Carry current-main behavior forward for cwd-aware Markdown parsing, Windows Terminal color detection, and personal access token auth. - Clear pending usage cards on thread rollback and delay completed cards until live hook output is committed. - Add focused regression and snapshot coverage for loading, auth errors, invalid views, rollback, hook ordering, layout, and charts. ## Prior review The original implementation was approved by Eric Traut in #25345 after testing multiple themes and light/dark terminals. This PR preserves that reviewed implementation while adapting it to current `main` and adding regression coverage for newer rollback and hook lifecycle behavior. ## Validation - `just test -p codex-tui token_activity palette renderable usage_command` — 37 passed. - Focused rollback, hook-ordering, and error snapshot tests — 4 passed. - `just fix -p codex-tui` — passed. - `UV_CACHE_DIR=/private/tmp/codex-uv-cache just fmt` — passed. - `cargo insta pending-snapshots` — no pending snapshots. - `just test -p codex-tui` — 2,870 passed; two unrelated guardian feature-flag tests failed because their expected `OverrideTurnContext` event was absent: - `update_feature_flags_disabling_guardian_clears_manual_review_policy_without_history` - `update_feature_flags_disabling_guardian_clears_review_policy_and_restores_default` - `just argument-comment-lint` could not complete because the local Bazel LLVM `compiler-rt` repository is missing `include/sanitizer/*.h`. The touched Rust diff was manually inspected and no missing opaque-literal argument comments were found.
This commit is contained in:
1 parent
9e07892253
commit
c884536d84
42 files changed
+2296
-57
No files matched your search
@@ -80,6 +80,15 @@ impl App {
|
||||
return;
|
||||
}
|
||||
ServerNotification::AccountUpdated(notification) => {
|
||||
let has_codex_backend_auth = matches!(
|
||||
notification.auth_mode,
|
||||
Some(
|
||||
AuthMode::Chatgpt
|
||||
| AuthMode::ChatgptAuthTokens
|
||||
| AuthMode::AgentIdentity
|
||||
| AuthMode::PersonalAccessToken
|
||||
)
|
||||
);
|
||||
self.chat_widget.update_account_state(
|
||||
status_account_display_from_auth_mode(
|
||||
notification.auth_mode,
|
||||
@@ -89,6 +98,7 @@ impl App {
|
||||
notification
|
||||
.auth_mode
|
||||
.is_some_and(AuthMode::has_chatgpt_account),
|
||||
has_codex_backend_auth,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,9 @@ 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);
|
||||
|
||||
impl App {
|
||||
pub(super) fn fetch_mcp_inventory(
|
||||
&mut self,
|
||||
@@ -78,6 +81,25 @@ 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 send_add_credits_nudge_email(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
@@ -652,6 +674,19 @@ pub(super) async fn fetch_account_rate_limits(
|
||||
Ok(app_server_rate_limit_snapshots(response))
|
||||
}
|
||||
|
||||
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 send_add_credits_nudge_email(
|
||||
request_handle: AppServerRequestHandle,
|
||||
credit_type: AddCreditsNudgeCreditType,
|
||||
|
||||
@@ -227,27 +227,7 @@ impl App {
|
||||
self.begin_thread_switch_history_replay_buffer();
|
||||
}
|
||||
AppEvent::InsertHistoryCell(cell) => {
|
||||
let cell: Arc<dyn HistoryCell> = cell.into();
|
||||
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
|
||||
t.insert_cell(cell.clone());
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
self.transcript_cells.push(cell.clone());
|
||||
if self.initial_history_replay_buffer.as_ref().is_some() {
|
||||
self.insert_history_cell_lines_with_initial_replay_buffer(
|
||||
tui,
|
||||
cell.as_ref(),
|
||||
self.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width),
|
||||
);
|
||||
} else {
|
||||
self.insert_history_cell_lines(
|
||||
tui,
|
||||
cell.as_ref(),
|
||||
self.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width),
|
||||
);
|
||||
}
|
||||
self.insert_history_cell(tui, cell);
|
||||
}
|
||||
AppEvent::EndInitialHistoryReplayBuffer => {
|
||||
self.finish_initial_history_replay_buffer(tui);
|
||||
@@ -265,10 +245,16 @@ impl App {
|
||||
scrollback_reflow,
|
||||
deferred_history_cell,
|
||||
)?;
|
||||
self.chat_widget.note_stream_consolidation_completed();
|
||||
self.insert_completed_token_activity_output_after_stream_shutdown(tui);
|
||||
}
|
||||
AppEvent::ConsolidateProposedPlan(source) => {
|
||||
if !self.terminal_resize_reflow_enabled() {
|
||||
self.transcript_reflow.clear();
|
||||
if !self.transcript_reflow.history_cell_refresh_requested() {
|
||||
self.transcript_reflow.clear();
|
||||
}
|
||||
self.chat_widget.note_stream_consolidation_completed();
|
||||
self.insert_completed_token_activity_output_after_stream_shutdown(tui);
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
let end = self.transcript_cells.len();
|
||||
@@ -303,6 +289,8 @@ impl App {
|
||||
|
||||
self.maybe_finish_stream_reflow(tui)?;
|
||||
}
|
||||
self.chat_widget.note_stream_consolidation_completed();
|
||||
self.insert_completed_token_activity_output_after_stream_shutdown(tui);
|
||||
}
|
||||
AppEvent::ApplyThreadRollback { num_turns } => {
|
||||
if self.apply_non_pending_thread_rollback(num_turns) {
|
||||
@@ -722,6 +710,9 @@ impl App {
|
||||
AppEvent::RefreshRateLimits { origin } => {
|
||||
self.refresh_rate_limits(app_server, origin);
|
||||
}
|
||||
AppEvent::RefreshTokenActivity { request_id } => {
|
||||
self.refresh_token_activity(app_server, request_id);
|
||||
}
|
||||
AppEvent::OpenThreadGoalMenu { thread_id } => {
|
||||
self.open_thread_goal_menu(app_server, thread_id).await;
|
||||
}
|
||||
@@ -778,6 +769,25 @@ 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_completed_token_activity_output_if_ready(tui);
|
||||
}
|
||||
}
|
||||
AppEvent::CommitCompletedTokenActivityOutput => {
|
||||
self.insert_completed_token_activity_output_after_stream_shutdown(tui);
|
||||
}
|
||||
AppEvent::ConnectorsLoaded { result, is_final } => {
|
||||
self.chat_widget.on_connectors_loaded(result, is_final);
|
||||
}
|
||||
@@ -1966,6 +1976,7 @@ impl App {
|
||||
}
|
||||
self.sync_tui_theme_selection(name);
|
||||
self.refresh_status_line();
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
Err(err) => {
|
||||
self.restore_runtime_theme_from_config();
|
||||
@@ -1978,6 +1989,7 @@ impl App {
|
||||
}
|
||||
AppEvent::SyntaxThemePreviewed => {
|
||||
self.refresh_status_line();
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
AppEvent::OpenKeymapActionMenu { context, action } => {
|
||||
self.chat_widget
|
||||
|
||||
@@ -8,6 +8,62 @@ use super::*;
|
||||
const DESKTOP_THREAD_OPENED_MESSAGE: &str = "Opened this session in Codex Desktop.";
|
||||
|
||||
impl App {
|
||||
pub(super) fn insert_history_cell(&mut self, tui: &mut tui::Tui, cell: Box<dyn HistoryCell>) {
|
||||
let cell: Arc<dyn HistoryCell> = cell.into();
|
||||
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
|
||||
t.insert_cell(cell.clone());
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
self.transcript_cells.push(cell.clone());
|
||||
if self.initial_history_replay_buffer.as_ref().is_some() {
|
||||
self.insert_history_cell_lines_with_initial_replay_buffer(
|
||||
tui,
|
||||
cell.as_ref(),
|
||||
self.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width),
|
||||
);
|
||||
} else {
|
||||
self.insert_history_cell_lines(
|
||||
tui,
|
||||
cell.as_ref(),
|
||||
self.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width),
|
||||
);
|
||||
}
|
||||
// A committed cell can unblock a settled /usage card that was waiting
|
||||
// behind a transient active cell or a provisional stream tail.
|
||||
self.chat_widget
|
||||
.request_completed_token_activity_output_insertion();
|
||||
}
|
||||
|
||||
pub(super) fn insert_completed_token_activity_output_if_ready(&mut self, tui: &mut tui::Tui) {
|
||||
if self.chat_widget.token_activity_history_insertion_blocked()
|
||||
|| self.transcript_cells.last().is_some_and(|cell| {
|
||||
cell.as_any().is::<history_cell::AgentMessageCell>()
|
||||
|| cell.as_any().is::<history_cell::ProposedPlanStreamCell>()
|
||||
})
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.insert_completed_token_activity_output(tui);
|
||||
}
|
||||
|
||||
pub(super) fn insert_completed_token_activity_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));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn insert_completed_token_activity_output_after_stream_shutdown(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
) {
|
||||
if self.chat_widget.token_activity_history_insertion_blocked() {
|
||||
return;
|
||||
}
|
||||
self.insert_completed_token_activity_output(tui);
|
||||
}
|
||||
|
||||
pub(super) fn open_url_in_browser(&mut self, url: String) {
|
||||
if let Err(err) = webbrowser::open(&url) {
|
||||
self.chat_widget
|
||||
@@ -110,6 +166,7 @@ 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.initial_history_replay_buffer = None;
|
||||
self.backtrack = BacktrackState::default();
|
||||
self.backtrack_render_pending = false;
|
||||
|
||||
@@ -264,6 +264,14 @@ impl App {
|
||||
/// transient stream rows.
|
||||
pub(super) fn maybe_finish_stream_reflow(&mut self, tui: &mut tui::Tui) -> Result<()> {
|
||||
if !self.terminal_resize_reflow_enabled() {
|
||||
if self.transcript_reflow.take_stream_finish_reflow_needed() {
|
||||
self.schedule_immediate_history_cell_refresh(tui);
|
||||
self.maybe_run_resize_reflow(tui)?;
|
||||
return Ok(());
|
||||
}
|
||||
if self.transcript_reflow.history_cell_refresh_requested() {
|
||||
return Ok(());
|
||||
}
|
||||
self.transcript_reflow.clear();
|
||||
return Ok(());
|
||||
}
|
||||
@@ -286,6 +294,22 @@ impl App {
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
fn schedule_immediate_history_cell_refresh(&mut self, tui: &mut tui::Tui) {
|
||||
self.transcript_reflow.schedule_history_cell_refresh();
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
pub(crate) fn retry_pending_history_cell_refresh(&self, tui: &mut tui::Tui) {
|
||||
if self.transcript_reflow.history_cell_refresh_requested() {
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn should_handle_draw_pre_render(&self) -> bool {
|
||||
self.terminal_resize_reflow_enabled()
|
||||
|| self.transcript_reflow.history_cell_refresh_requested()
|
||||
}
|
||||
|
||||
/// Force stream-finalized output through the resize reflow path.
|
||||
///
|
||||
/// Proposed plan consolidation uses this stricter path because a completed plan is inserted or
|
||||
@@ -293,7 +317,9 @@ impl App {
|
||||
/// resize, the visible scrollback can keep the pre-consolidation wrapping.
|
||||
pub(super) fn finish_required_stream_reflow(&mut self, tui: &mut tui::Tui) -> Result<()> {
|
||||
if !self.terminal_resize_reflow_enabled() {
|
||||
self.transcript_reflow.clear();
|
||||
if !self.transcript_reflow.history_cell_refresh_requested() {
|
||||
self.transcript_reflow.clear();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.schedule_immediate_resize_reflow(tui);
|
||||
@@ -334,7 +360,10 @@ impl App {
|
||||
} else {
|
||||
frame_requester.schedule_frame_in(TRANSCRIPT_REFLOW_DEBOUNCE);
|
||||
}
|
||||
} else if !self.terminal_resize_reflow_enabled() && width.changed {
|
||||
} else if !self.terminal_resize_reflow_enabled()
|
||||
&& width.changed
|
||||
&& !self.transcript_reflow.history_cell_refresh_requested()
|
||||
{
|
||||
self.transcript_reflow.clear();
|
||||
}
|
||||
}
|
||||
@@ -388,7 +417,9 @@ impl App {
|
||||
/// reuse terminal-wrapped output here would preserve exactly the stale wrapping this feature is
|
||||
/// meant to remove.
|
||||
pub(super) fn maybe_run_resize_reflow(&mut self, tui: &mut tui::Tui) -> Result<()> {
|
||||
if !self.terminal_resize_reflow_enabled() {
|
||||
if !self.terminal_resize_reflow_enabled()
|
||||
&& !self.transcript_reflow.history_cell_refresh_requested()
|
||||
{
|
||||
self.transcript_reflow.clear();
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -326,6 +326,7 @@ async fn enqueue_primary_thread_session_replays_turns_before_initial_prompt_subm
|
||||
),
|
||||
enhanced_keys_supported: false,
|
||||
has_chatgpt_account: false,
|
||||
has_codex_backend_auth: false,
|
||||
model_catalog: app.model_catalog.clone(),
|
||||
feedback: codex_feedback::CodexFeedback::new(),
|
||||
is_first_run: false,
|
||||
@@ -4594,6 +4595,32 @@ async fn height_shrink_schedules_resize_reflow() {
|
||||
assert!(app.transcript_reflow.has_pending_reflow());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_resize_reflow_preserves_pending_history_cell_refresh() {
|
||||
let (mut app, _rx, _op_rx) = make_test_app_with_channels().await;
|
||||
let frame_requester = crate::tui::FrameRequester::test_dummy();
|
||||
app.config
|
||||
.features
|
||||
.set_enabled(Feature::TerminalResizeReflow, /*enabled*/ false)
|
||||
.expect("feature should be configurable");
|
||||
assert!(!app.should_handle_draw_pre_render());
|
||||
app.transcript_reflow.schedule_history_cell_refresh();
|
||||
assert!(app.should_handle_draw_pre_render());
|
||||
|
||||
assert!(!app.handle_draw_size_change(
|
||||
ratatui::layout::Size::new(/*width*/ 118, /*height*/ 35),
|
||||
ratatui::layout::Size::new(/*width*/ 118, /*height*/ 35),
|
||||
&frame_requester,
|
||||
));
|
||||
assert!(app.handle_draw_size_change(
|
||||
ratatui::layout::Size::new(/*width*/ 119, /*height*/ 35),
|
||||
ratatui::layout::Size::new(/*width*/ 118, /*height*/ 35),
|
||||
&frame_requester,
|
||||
));
|
||||
|
||||
assert!(app.transcript_reflow.history_cell_refresh_requested());
|
||||
}
|
||||
|
||||
fn test_turn(turn_id: &str, status: TurnStatus, items: Vec<ThreadItem>) -> Turn {
|
||||
Turn {
|
||||
id: turn_id.to_string(),
|
||||
@@ -5379,6 +5406,7 @@ async fn replace_chat_widget_reseeds_collab_agent_metadata_for_replay() {
|
||||
initial_user_message: None,
|
||||
enhanced_keys_supported: app.enhanced_keys_supported,
|
||||
has_chatgpt_account: app.chat_widget.has_chatgpt_account(),
|
||||
has_codex_backend_auth: app.chat_widget.has_codex_backend_auth(),
|
||||
model_catalog: app.model_catalog.clone(),
|
||||
feedback: app.feedback.clone(),
|
||||
is_first_run: false,
|
||||
@@ -5536,12 +5564,34 @@ async fn queued_rollback_syncs_overlay_and_clears_deferred_history() {
|
||||
app.deferred_history_lines = vec![Line::from("stale buffered line").into()];
|
||||
app.backtrack.overlay_preview_active = true;
|
||||
app.backtrack.nth_user_message = 1;
|
||||
app.chat_widget.update_account_state(
|
||||
/*status_account_display*/ None, /*plan_type*/ None,
|
||||
/*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ true,
|
||||
);
|
||||
app.chat_widget
|
||||
.set_composer_text("/usage".to_string(), Vec::new(), Vec::new());
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
let pending_usage = app
|
||||
.chat_widget
|
||||
.active_cell_transcript_lines(/*width*/ 80)
|
||||
.expect("pending usage transcript");
|
||||
assert!(lines_to_single_string(&pending_usage).contains("Token activity\n Loading..."));
|
||||
|
||||
let changed = app.apply_non_pending_thread_rollback(/*num_turns*/ 1);
|
||||
|
||||
assert!(changed);
|
||||
assert!(app.backtrack_render_pending);
|
||||
assert!(app.deferred_history_lines.is_empty());
|
||||
assert!(
|
||||
app.chat_widget
|
||||
.active_cell_transcript_lines(/*width*/ 80)
|
||||
.is_none_or(|lines| !lines_to_single_string(&lines).contains("Token activity"))
|
||||
);
|
||||
assert_eq!(app.backtrack.nth_user_message, 0);
|
||||
let user_messages: Vec<String> = app
|
||||
.transcript_cells
|
||||
|
||||
Reference in new issue
Block a user