From 0de669e9ceaf79d0683133a71a8265bba539d057 Mon Sep 17 00:00:00 2001 From: Andrea Date: Mon, 9 Nov 2026 14:41:15 +0100 Subject: [PATCH] README: aKode (stato del lavoro, build, configurazione endpoint locale, licenza) --- README.md | 130 +- .../core-plugins/src/remote/share/checkout.rs | 472 ------- codex-rs/core-plugins/src/remote_bundle.rs | 995 --------------- codex-rs/tui/src/analytics.rs | 536 -------- .../tui/src/analytics/account_layout_tests.rs | 477 ------- .../tui/src/analytics/account_plan_tests.rs | 167 --- codex-rs/tui/src/analytics/activity_chart.rs | 319 ----- .../src/analytics/activity_chart/palette.rs | 151 --- .../analytics/activity_chart/palette_tests.rs | 143 --- ...e_uses_effective_terminal_color_level.snap | 10 - .../tui/src/analytics/activity_chart_tests.rs | 239 ---- codex-rs/tui/src/analytics/chart.rs | 353 ------ codex-rs/tui/src/analytics/chat_panel.rs | 325 ----- .../tui/src/analytics/chat_panel_tests.rs | 212 ---- codex-rs/tui/src/analytics/chats.rs | 200 --- codex-rs/tui/src/analytics/chats_tests.rs | 180 --- codex-rs/tui/src/analytics/chrome.rs | 180 --- codex-rs/tui/src/analytics/client.rs | 291 ----- codex-rs/tui/src/analytics/client_tests.rs | 858 ------------- codex-rs/tui/src/analytics/compact_tests.rs | 45 - .../tui/src/analytics/connection_tests.rs | 260 ---- .../src/analytics/consumer_refresh_tests.rs | 138 -- codex-rs/tui/src/analytics/controls.rs | 292 ----- codex-rs/tui/src/analytics/dashboard.rs | 221 ---- codex-rs/tui/src/analytics/dashboard_tests.rs | 99 -- codex-rs/tui/src/analytics/data.rs | 210 --- codex-rs/tui/src/analytics/data_tests.rs | 132 -- codex-rs/tui/src/analytics/hints.rs | 111 -- codex-rs/tui/src/analytics/models.rs | 100 -- codex-rs/tui/src/analytics/mouse.rs | 55 - codex-rs/tui/src/analytics/mouse_tests.rs | 171 --- .../tui/src/analytics/navigation_tests.rs | 326 ----- codex-rs/tui/src/analytics/normalize.rs | 364 ------ codex-rs/tui/src/analytics/normalize_tests.rs | 358 ------ codex-rs/tui/src/analytics/panels.rs | 70 - codex-rs/tui/src/analytics/plan.rs | 121 -- codex-rs/tui/src/analytics/plan_panel.rs | 255 ---- codex-rs/tui/src/analytics/plan_tests.rs | 362 ------ codex-rs/tui/src/analytics/plot.rs | 176 --- .../tui/src/analytics/plot/annotations.rs | 213 ---- codex-rs/tui/src/analytics/plot/layout.rs | 55 - codex-rs/tui/src/analytics/plot/painting.rs | 132 -- codex-rs/tui/src/analytics/plot_tests.rs | 535 -------- .../src/analytics/profile_identity_tests.rs | 28 - codex-rs/tui/src/analytics/recovery_tests.rs | 76 -- codex-rs/tui/src/analytics/redesign_tests.rs | 99 -- codex-rs/tui/src/analytics/render.rs | 230 ---- codex-rs/tui/src/analytics/report_data.rs | 289 ----- .../tui/src/analytics/report_data_tests.rs | 84 -- .../tui/src/analytics/runtime_auth_tests.rs | 241 ---- codex-rs/tui/src/analytics/sections.rs | 305 ----- ...ible_and_closing_aborts_pending_loads.snap | 28 - ...s_unknowns_and_resets_on_new_snapshot.snap | 65 - ..._plan__tests__plan_clocks_twelve_hour.snap | 15 - ...e_empty_and_zero_history_are_distinct.snap | 31 - ...dates_render_the_full_other_remainder.snap | 42 - ...row_charts_keep_the_selection_visible.snap | 105 -- ...height_totals_remain_separate_numbers.snap | 30 - ...ong_range_charts_never_truncate_dates.snap | 102 -- ..._axes_are_hidden_instead_of_truncated.snap | 138 -- ...idpoint_and_descend_from_the_baseline.snap | 49 - ...t_keeps_the_authoritative_daily_total.snap | 30 - ...lytics__plot__tests__seven_day_totals.snap | 37 - ...ytics__plot__tests__signed_chart_dark.snap | 42 - ...tics__plot__tests__signed_chart_light.snap | 42 - ...their_series_color_beside_a_large_day.snap | 68 - ..._credit_history_uses_a_readable_scale.snap | 28 - ...down_ranks_nonzero_groups_and_reflows.snap | 102 -- ...l_indent_and_counts_missing_estimates.snap | 34 - ...er_refresh__consumer_chat_all_metrics.snap | 34 - ...align_and_keep_stable_summary_heights.snap | 117 -- ..._wide_reports_put_details_beside_plot.snap | 64 - ...r_metadata_keeps_utc_across_renderers.snap | 8 - ...alytics__tests__redesign__narrow_help.snap | 20 - ...ixed_and_expose_data_on_small_screens.snap | 37 - ...s__summary__summary_cumulative_narrow.snap | 64 - ...s__tests__summary__summary_daily_wide.snap | 48 - ...tics__tests__summary__summary_partial.snap | 44 - codex-rs/tui/src/analytics/styles.rs | 48 - codex-rs/tui/src/analytics/styles_tests.rs | 185 --- codex-rs/tui/src/analytics/summary.rs | 76 -- codex-rs/tui/src/analytics/summary_panel.rs | 337 ----- codex-rs/tui/src/analytics/summary_tests.rs | 147 --- codex-rs/tui/src/analytics/task_panel.rs | 399 ------ codex-rs/tui/src/analytics/tasks.rs | 248 ---- codex-rs/tui/src/analytics/tasks_tests.rs | 156 --- codex-rs/tui/src/analytics/test_fixtures.rs | 242 ---- codex-rs/tui/src/analytics/test_support.rs | 76 -- codex-rs/tui/src/analytics/tokens.rs | 135 -- codex-rs/tui/src/analytics/tokens_tests.rs | 131 -- codex-rs/tui/src/analytics/tool_panel.rs | 26 - .../tui/src/analytics/tool_panel_tests.rs | 97 -- codex-rs/tui/src/analytics_tests.rs | 667 ---------- codex-rs/tui/src/app/agents_overview_usage.rs | 205 --- .../src/app/agents_overview_usage_tests.rs | 281 ---- .../tui/src/app/backend_banner_fallback.rs | 122 -- codex-rs/tui/src/app/rate_limit_refresh.rs | 131 -- .../tests/backend_banner_fallback_tests.rs | 505 -------- .../tests/backend_banner_recovery_tests.rs | 567 --------- .../app/tests/backend_banner_startup_tests.rs | 95 -- .../app/tests/luna_reserve_recovery_tests.rs | 384 ------ codex-rs/tui/src/app/tests/rate_limits.rs | 563 -------- codex-rs/tui/src/app/tests/thread_usage.rs | 356 ------ codex-rs/tui/src/backend_banners.rs | 77 -- codex-rs/tui/src/backend_banners/actions.rs | 87 -- codex-rs/tui/src/backend_banners/render.rs | 79 -- codex-rs/tui/src/backend_banners_tests.rs | 57 - .../tui/src/chatwidget/backend_banners.rs | 523 -------- .../tui/src/chatwidget/luna_reserve_model.rs | 67 - .../tui/src/chatwidget/luna_reserve_return.rs | 48 - codex-rs/tui/src/chatwidget/reset_credits.rs | 79 -- .../chatwidget/tests/backend_banners_tests.rs | 438 ------- .../tests/luna_reserve_usage_tests.rs | 254 ---- .../tests/rate_limit_recovery_tests.rs | 65 - codex-rs/tui/src/chatwidget/tests/usage.rs | 1127 ----------------- codex-rs/tui/src/chatwidget/thread_usage.rs | 432 ------- .../tui/src/chatwidget/thread_usage_tests.rs | 1060 ---------------- codex-rs/tui/src/chatwidget/usage.rs | 601 --------- codex-rs/tui/src/status/thread_usage.rs | 356 ------ codex-rs/tui/src/status/thread_usage_tests.rs | 70 - codex-rs/tui/src/workspace_messages.rs | 29 - codex-rs/tui/src/workspace_messages_tests.rs | 51 - 122 files changed, 68 insertions(+), 25426 deletions(-) delete mode 100644 codex-rs/core-plugins/src/remote/share/checkout.rs delete mode 100644 codex-rs/core-plugins/src/remote_bundle.rs delete mode 100644 codex-rs/tui/src/analytics.rs delete mode 100644 codex-rs/tui/src/analytics/account_layout_tests.rs delete mode 100644 codex-rs/tui/src/analytics/account_plan_tests.rs delete mode 100644 codex-rs/tui/src/analytics/activity_chart.rs delete mode 100644 codex-rs/tui/src/analytics/activity_chart/palette.rs delete mode 100644 codex-rs/tui/src/analytics/activity_chart/palette_tests.rs delete mode 100644 codex-rs/tui/src/analytics/activity_chart/snapshots/codex_tui__analytics__activity_chart__palette__tests__current_palette_uses_effective_terminal_color_level.snap delete mode 100644 codex-rs/tui/src/analytics/activity_chart_tests.rs delete mode 100644 codex-rs/tui/src/analytics/chart.rs delete mode 100644 codex-rs/tui/src/analytics/chat_panel.rs delete mode 100644 codex-rs/tui/src/analytics/chat_panel_tests.rs delete mode 100644 codex-rs/tui/src/analytics/chats.rs delete mode 100644 codex-rs/tui/src/analytics/chats_tests.rs delete mode 100644 codex-rs/tui/src/analytics/chrome.rs delete mode 100644 codex-rs/tui/src/analytics/client.rs delete mode 100644 codex-rs/tui/src/analytics/client_tests.rs delete mode 100644 codex-rs/tui/src/analytics/compact_tests.rs delete mode 100644 codex-rs/tui/src/analytics/connection_tests.rs delete mode 100644 codex-rs/tui/src/analytics/consumer_refresh_tests.rs delete mode 100644 codex-rs/tui/src/analytics/controls.rs delete mode 100644 codex-rs/tui/src/analytics/dashboard.rs delete mode 100644 codex-rs/tui/src/analytics/dashboard_tests.rs delete mode 100644 codex-rs/tui/src/analytics/data.rs delete mode 100644 codex-rs/tui/src/analytics/data_tests.rs delete mode 100644 codex-rs/tui/src/analytics/hints.rs delete mode 100644 codex-rs/tui/src/analytics/models.rs delete mode 100644 codex-rs/tui/src/analytics/mouse.rs delete mode 100644 codex-rs/tui/src/analytics/mouse_tests.rs delete mode 100644 codex-rs/tui/src/analytics/navigation_tests.rs delete mode 100644 codex-rs/tui/src/analytics/normalize.rs delete mode 100644 codex-rs/tui/src/analytics/normalize_tests.rs delete mode 100644 codex-rs/tui/src/analytics/panels.rs delete mode 100644 codex-rs/tui/src/analytics/plan.rs delete mode 100644 codex-rs/tui/src/analytics/plan_panel.rs delete mode 100644 codex-rs/tui/src/analytics/plan_tests.rs delete mode 100644 codex-rs/tui/src/analytics/plot.rs delete mode 100644 codex-rs/tui/src/analytics/plot/annotations.rs delete mode 100644 codex-rs/tui/src/analytics/plot/layout.rs delete mode 100644 codex-rs/tui/src/analytics/plot/painting.rs delete mode 100644 codex-rs/tui/src/analytics/plot_tests.rs delete mode 100644 codex-rs/tui/src/analytics/profile_identity_tests.rs delete mode 100644 codex-rs/tui/src/analytics/recovery_tests.rs delete mode 100644 codex-rs/tui/src/analytics/redesign_tests.rs delete mode 100644 codex-rs/tui/src/analytics/render.rs delete mode 100644 codex-rs/tui/src/analytics/report_data.rs delete mode 100644 codex-rs/tui/src/analytics/report_data_tests.rs delete mode 100644 codex-rs/tui/src/analytics/runtime_auth_tests.rs delete mode 100644 codex-rs/tui/src/analytics/sections.rs delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__client__tests__live_account_identity_is_visible_and_closing_aborts_pending_loads.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__period_navigation_preserves_unknowns_and_resets_on_new_snapshot.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__plan_clocks_twelve_hour.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__unavailable_empty_and_zero_history_are_distinct.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__duplicate_message_dates_render_the_full_other_remainder.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__missing_zero_and_narrow_charts_keep_the_selection_visible.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__narrow_equal_height_totals_remain_separate_numbers.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__narrow_long_range_charts_never_truncate_dates.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__oversized_axes_are_hidden_instead_of_truncated.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__partial_cells_use_the_midpoint_and_descend_from_the_baseline.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__selected_callout_keeps_the_authoritative_daily_total.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__seven_day_totals.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__signed_chart_dark.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__signed_chart_light.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__tiny_segments_keep_their_series_color_beside_a_large_day.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__zero_credit_history_uses_a_readable_scale.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__chats_table__chats_breakdown_ranks_nonzero_groups_and_reflows.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__chats_table__chats_long_title_keeps_detail_indent_and_counts_missing_estimates.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__consumer_refresh__consumer_chat_all_metrics.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__dashboard__dashboard_cards_align_and_keep_stable_summary_heights.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__recovery__tall_reports_use_available_height_and_wide_reports_put_details_beside_plot.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__recovery__twelve_hour_metadata_keeps_utc_across_renderers.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__redesign__narrow_help.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__redesign__reports_keep_tabs_fixed_and_expose_data_on_small_screens.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_cumulative_narrow.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_daily_wide.snap delete mode 100644 codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_partial.snap delete mode 100644 codex-rs/tui/src/analytics/styles.rs delete mode 100644 codex-rs/tui/src/analytics/styles_tests.rs delete mode 100644 codex-rs/tui/src/analytics/summary.rs delete mode 100644 codex-rs/tui/src/analytics/summary_panel.rs delete mode 100644 codex-rs/tui/src/analytics/summary_tests.rs delete mode 100644 codex-rs/tui/src/analytics/task_panel.rs delete mode 100644 codex-rs/tui/src/analytics/tasks.rs delete mode 100644 codex-rs/tui/src/analytics/tasks_tests.rs delete mode 100644 codex-rs/tui/src/analytics/test_fixtures.rs delete mode 100644 codex-rs/tui/src/analytics/test_support.rs delete mode 100644 codex-rs/tui/src/analytics/tokens.rs delete mode 100644 codex-rs/tui/src/analytics/tokens_tests.rs delete mode 100644 codex-rs/tui/src/analytics/tool_panel.rs delete mode 100644 codex-rs/tui/src/analytics/tool_panel_tests.rs delete mode 100644 codex-rs/tui/src/analytics_tests.rs delete mode 100644 codex-rs/tui/src/app/agents_overview_usage.rs delete mode 100644 codex-rs/tui/src/app/agents_overview_usage_tests.rs delete mode 100644 codex-rs/tui/src/app/backend_banner_fallback.rs delete mode 100644 codex-rs/tui/src/app/rate_limit_refresh.rs delete mode 100644 codex-rs/tui/src/app/tests/backend_banner_fallback_tests.rs delete mode 100644 codex-rs/tui/src/app/tests/backend_banner_recovery_tests.rs delete mode 100644 codex-rs/tui/src/app/tests/backend_banner_startup_tests.rs delete mode 100644 codex-rs/tui/src/app/tests/luna_reserve_recovery_tests.rs delete mode 100644 codex-rs/tui/src/app/tests/rate_limits.rs delete mode 100644 codex-rs/tui/src/app/tests/thread_usage.rs delete mode 100644 codex-rs/tui/src/backend_banners.rs delete mode 100644 codex-rs/tui/src/backend_banners/actions.rs delete mode 100644 codex-rs/tui/src/backend_banners/render.rs delete mode 100644 codex-rs/tui/src/backend_banners_tests.rs delete mode 100644 codex-rs/tui/src/chatwidget/backend_banners.rs delete mode 100644 codex-rs/tui/src/chatwidget/luna_reserve_model.rs delete mode 100644 codex-rs/tui/src/chatwidget/luna_reserve_return.rs delete mode 100644 codex-rs/tui/src/chatwidget/reset_credits.rs delete mode 100644 codex-rs/tui/src/chatwidget/tests/backend_banners_tests.rs delete mode 100644 codex-rs/tui/src/chatwidget/tests/luna_reserve_usage_tests.rs delete mode 100644 codex-rs/tui/src/chatwidget/tests/rate_limit_recovery_tests.rs delete mode 100644 codex-rs/tui/src/chatwidget/tests/usage.rs delete mode 100644 codex-rs/tui/src/chatwidget/thread_usage.rs delete mode 100644 codex-rs/tui/src/chatwidget/thread_usage_tests.rs delete mode 100644 codex-rs/tui/src/chatwidget/usage.rs delete mode 100644 codex-rs/tui/src/status/thread_usage.rs delete mode 100644 codex-rs/tui/src/status/thread_usage_tests.rs delete mode 100644 codex-rs/tui/src/workspace_messages.rs delete mode 100644 codex-rs/tui/src/workspace_messages_tests.rs diff --git a/README.md b/README.md index 06b02fce..5dbbec95 100644 --- a/README.md +++ b/README.md @@ -1,81 +1,87 @@ -

Codex CLI is a coding agent from OpenAI that runs locally on your computer. -

- Codex CLI splash -

-
-If you want Codex in your code editor (VS Code, Cursor, Windsurf), install in your IDE. -
If you want the desktop app experience, run codex app or visit the Codex App page. -
If you are looking for the cloud-based agent from OpenAI, Codex Web, go to chatgpt.com/codex.

+# aKode + +**aKode** è un agente di coding da terminale, privato e a uso personale, che lavora **solo con modelli scelti da te**: il tuo server locale o qualsiasi endpoint compatibile con OpenAI. Non contatta mai OpenAI o ChatGPT. + +È un fork di [OpenAI Codex CLI](https://github.com/openai/codex) (Apache-2.0). Da Codex eredita l'interfaccia a terminale, l'esecuzione dei comandi in sandbox, la modifica dei file con patch, MCP, skill, plugin locali e la modalità non interattiva `exec`. Ha però tolto tutto ciò che dipende dai servizi di OpenAI. + +> **Uso privato.** Questo repository (`git.difonzo.net/andrea/aKode`) non è distribuito né pubblicato. --- -## Quickstart +## Stato del lavoro -### Installing and running Codex CLI +| Fase | Contenuto | Stato | +|---|---|---| +| 1 | Telemetria e chiamate automatiche: Statsig, analytics, invio a Sentry, controllo aggiornamenti, suggerimento del giorno, sincronizzazione plugin OpenAI, CDN dei pets, CIMD `chatgpt.com` | ✅ | +| 2a | Funzioni periferiche ChatGPT: `cloud`, `apply`, `app`, `remote-control`, proxy Responses verso OpenAI, decisions di guardian, sonde di `doctor` verso OpenAI. Il vocale non ha più fallback verso OpenAI | ✅ | +| 2b-1 | Backend ChatGPT: utilizzo, limiti e crediti, configurazione cloud, app e connettori ChatGPT, plugin remoti, upload di file, attribuzione git remota | 🟡 in corso | +| 2b-2 | Login ChatGPT/OAuth, identità agente, token personali: resta solo l'autenticazione con chiave API | ⏳ | +| 3 | Provider: nessun default OpenAI; Ollama, LM Studio ed endpoint personalizzati; elenco modelli letto dal server; unione dei messaggi di sistema per i modelli locali | ⏳ | +| 4 | Primo avvio: una schermata per URL, chiave API e modello, con test della connessione | ⏳ | +| 5 | Rebranding completo: comando `akode`, `~/.akode`, variabili `AKODE_*`, crate `akode-*` | ⏳ | +| 6 | Verifica finale e installatore locale | ⏳ | -Run the following on Mac or Linux to install Codex CLI: +Finché la fase 5 non è completa, il binario, la cartella di configurazione e le variabili d'ambiente usano ancora i nomi di Codex: `codex`, `~/.codex`, `CODEX_*`. -```shell -curl -fsSL https://chatgpt.com/codex/install.sh | sh +--- + +## Requisiti + +- macOS (Apple Silicon) o Linux. +- Rust tramite `rustup`: la toolchain richiesta (`codex-rs/rust-toolchain.toml`) viene installata automaticamente. +- `git`. +- Un endpoint LLM che supporti la **Responses API** (`POST /v1/responses`). Codex/aKode non usa più `/chat/completions`. + +## Compilazione + +```bash +cd codex-rs + +# build leggera: meno spazio su disco, niente debuginfo +export CARGO_NET_GIT_FETCH_WITH_CLI=true +export CARGO_PROFILE_DEV_DEBUG=0 +export CARGO_INCREMENTAL=0 + +cargo build -p codex-cli --bin codex # debug +cargo build -p codex-cli --bin codex --release # release ``` -Run the following on Windows to install Codex CLI: +Per i test serve uno stack più grande: `export RUST_MIN_STACK=8388608`. Testa un crate alla volta (`cargo test -p --lib`). La cartella `codex-rs/target` può superare i 50 GB: cancellala quando non serve. -```shell -powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex" +## Configurazione di un modello + +In `~/.codex/config.toml` (dopo la fase 5 diventerà `~/.akode/config.toml`): + +```toml +model_provider = "imeai" +model = "qwen3.6-35b-a3b" +model_context_window = 131072 + +[model_providers.imeai] +name = "imeAI (Qwen3.6 su ik_llama.cpp)" +base_url = "http://192.168.40.25:8080/v1" +env_key = "IMEAI_API_KEY" # la chiave si legge da questa variabile d'ambiente +wire_api = "responses" ``` -The standalone installers download from `https://releases.openai.com/codex` by default and fall back to GitHub Releases if a metadata or asset download is unavailable. To force GitHub Releases, set `CODEX_INSTALLER_USE_RELEASES_OPENAI_COM` to `false` (`0` and `no` are also accepted): - -```shell -curl -fsSL https://chatgpt.com/codex/install.sh | CODEX_INSTALLER_USE_RELEASES_OPENAI_COM=false sh +```bash +export IMEAI_API_KEY="..." # chiave del server +codex exec "descrivi questo progetto" ``` -```powershell -$env:CODEX_INSTALLER_USE_RELEASES_OPENAI_COM='false'; irm https://chatgpt.com/codex/install.ps1 | iex -``` +**Server llama.cpp / ik_llama.cpp con Qwen3.x:** aKode invia più messaggi di sistema/developer. Il template originale di Qwen li rifiuta ("System message must be at the beginning"), quindi va usato un template che li accetti (`--chat-template-file`). Il server imeAI usa `/etc/llama/qwen36-multisys.jinja`. Con la fase 3 aKode li unirà da solo. -Codex CLI can also be installed via the following package managers: +**Interfaccia interattiva:** in questa fase la TUI richiede un'installazione impacchettata. Lanciata da `target/` funziona solo `codex exec`, oppure `codex --no-daemon`. L'installatore locale arriva con la fase 6. -```shell -# Install using npm -npm install -g @openai/codex -``` +--- -```shell -# Install using Homebrew -brew install --cask codex -``` +## Cosa è stato tolto rispetto a Codex -Then simply run `codex` to get started. +- **Telemetria e analytics:** nessun invio. L'export OpenTelemetry funziona solo se lo configuri tu esplicitamente. +- **Login e servizi ChatGPT:** niente login con l'account ChatGPT, niente attività cloud, app, connettori, plugin remoti, utilizzo e crediti, configurazione gestita dal cloud. +- **Rete in automatico:** nessun controllo aggiornamenti, annuncio, download di asset o sincronizzazione di plugin all'avvio. +- **Feedback:** nessun upload a Sentry; resta solo il salvataggio locale. -
-You can also go to the latest GitHub Release and download the appropriate binary for your platform. +## Licenza -Each GitHub Release contains many executables, but in practice, you likely want one of these: - -- macOS - - Apple Silicon/arm64: `codex-aarch64-apple-darwin.tar.gz` - - x86_64 (older Mac hardware): `codex-x86_64-apple-darwin.tar.gz` -- Linux - - x86_64: `codex-x86_64-unknown-linux-musl.tar.gz` - - arm64: `codex-aarch64-unknown-linux-musl.tar.gz` - -Each archive contains a single entry with the platform baked into the name (e.g., `codex-x86_64-unknown-linux-musl`), so you likely want to rename it to `codex` after extracting it. - -
- -### Using Codex with your ChatGPT plan - -Run `codex` and select **Sign in with ChatGPT**. We recommend signing into your ChatGPT account to use Codex as part of your Plus, Pro, Business, Edu, or Enterprise plan. [Learn more about what's included in your ChatGPT plan](https://help.openai.com/en/articles/11369540-codex-in-chatgpt). - -You can also use Codex with an API key, but this requires [additional setup](https://developers.openai.com/codex/auth#sign-in-with-an-api-key). - -## Docs - -- [**Codex Documentation**](https://developers.openai.com/codex) -- [**Contributing**](./docs/contributing.md) -- [**Installing & building**](./docs/install.md) -- [**Open source fund**](./docs/open-source-fund.md) - -This repository is licensed under the [Apache-2.0 License](LICENSE). +aKode deriva da OpenAI Codex CLI ed è rilasciato sotto la stessa [licenza Apache-2.0](LICENSE); vedi anche [NOTICE](NOTICE). Il codice è stato modificato in modo esteso: la cronologia git del repository documenta ogni modifica rispetto al commit di base `7874033`. "OpenAI" e "Codex" sono marchi dei rispettivi proprietari. aKode non è affiliato né approvato da OpenAI. diff --git a/codex-rs/core-plugins/src/remote/share/checkout.rs b/codex-rs/core-plugins/src/remote/share/checkout.rs deleted file mode 100644 index 223c667b..00000000 --- a/codex-rs/core-plugins/src/remote/share/checkout.rs +++ /dev/null @@ -1,472 +0,0 @@ -use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME; -use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME; -use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME; -use super::super::RemotePluginCatalogError; -use super::super::RemotePluginServiceConfig; -use super::local_paths; -use codex_app_server_protocol::PluginAuthPolicy; -use codex_app_server_protocol::PluginInstallPolicy; -use codex_login::CodexAuth; -use codex_plugin::PluginId; -use codex_plugin::validate_plugin_segment; -use codex_utils_absolute_path::AbsolutePathBuf; -use serde_json::Value as JsonValue; -use serde_json::json; -use std::collections::BTreeMap; -use std::fs; -use std::io; -use std::io::Write; -use std::path::Component; -use std::path::Path; - -const PERSONAL_MARKETPLACE_NAME: &str = "codex-curated"; -const PERSONAL_MARKETPLACE_DISPLAY_NAME: &str = "Personal"; -const PERSONAL_MARKETPLACE_RELATIVE_PATH: &str = ".agents/plugins/marketplace.json"; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RemotePluginShareCheckoutResult { - pub remote_plugin_id: String, - pub plugin_id: String, - pub plugin_name: String, - pub plugin_path: AbsolutePathBuf, - pub marketplace_name: String, - pub marketplace_path: AbsolutePathBuf, - pub remote_version: Option, -} - -pub async fn checkout_remote_plugin_share( - config: &RemotePluginServiceConfig, - auth: Option<&CodexAuth>, - codex_home: &Path, - remote_plugin_id: &str, -) -> Result { - let config = &config.for_current_account(); - let detail = super::super::fetch_remote_plugin_detail_with_download_urls( - config, - auth, - REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME, - remote_plugin_id, - ) - .await?; - let plugin_name = detail.summary.name.clone(); - let remote_version = detail.release_version.clone(); - validate_plugin_segment(&plugin_name, "plugin name").map_err(|reason| { - RemotePluginCatalogError::UnexpectedResponse(format!( - "remote plugin `{remote_plugin_id}` returned invalid plugin name: {reason}" - )) - })?; - if !is_checkout_supported_share_marketplace(&detail.marketplace_name) - || detail.summary.share_context.is_none() - { - return Err(RemotePluginCatalogError::PluginShareCheckoutNotAvailable { - remote_plugin_id: remote_plugin_id.to_string(), - }); - } - - let home = crate::marketplace::home_dir().ok_or_else(|| { - RemotePluginCatalogError::UnexpectedResponse( - "could not determine home directory for personal plugin marketplace".to_string(), - ) - })?; - let home = AbsolutePathBuf::try_from(home).map_err(|err| { - RemotePluginCatalogError::UnexpectedResponse(format!( - "failed to resolve home directory for personal plugin marketplace: {err}" - )) - })?; - - let local_paths = load_share_local_paths_for_checkout(codex_home)?; - let (local_plugin_path, already_checked_out) = - editable_plugin_path_for_checkout(&home, &plugin_name, remote_plugin_id, &local_paths)?; - - let mut created_checkout_path = false; - if !already_checked_out { - let bundle = crate::remote_bundle::validate_remote_plugin_bundle( - remote_plugin_id, - &detail.marketplace_name, - &plugin_name, - detail.release_version.as_deref(), - detail.bundle_download_url.as_deref(), - /*app_manifest*/ None, - ) - .map_err(|err| { - RemotePluginCatalogError::UnexpectedResponse(format!( - "failed to prepare remote plugin bundle checkout: {err}" - )) - })?; - crate::remote_bundle::download_and_extract_remote_plugin_bundle_to_path( - config, - bundle, - local_plugin_path.clone(), - ) - .await - .map_err(|err| { - RemotePluginCatalogError::UnexpectedResponse(format!( - "failed to check out remote plugin bundle: {err}" - )) - })?; - created_checkout_path = true; - } - - let marketplace = match update_personal_marketplace( - &home, - &plugin_name, - &local_plugin_path, - detail.summary.install_policy, - detail.summary.auth_policy, - detail - .summary - .interface - .as_ref() - .and_then(|interface| interface.category.clone()), - ) { - Ok(marketplace) => marketplace, - Err(err) => { - return Err(clean_up_created_checkout_path( - created_checkout_path, - &local_plugin_path, - err, - )); - } - }; - - if let Err(err) = local_paths::record_plugin_share_local_path( - codex_home, - remote_plugin_id, - local_plugin_path.clone(), - ) { - let err = RemotePluginCatalogError::UnexpectedResponse(format!( - "failed to record plugin share local path mapping: {err}" - )); - return Err(clean_up_created_checkout_path( - created_checkout_path, - &local_plugin_path, - err, - )); - } - - let plugin_id = PluginId::new(plugin_name.clone(), marketplace.name.clone()) - .map_err(|err| { - RemotePluginCatalogError::UnexpectedResponse(format!( - "failed to build checked out plugin id: {err}" - )) - })? - .as_key(); - - Ok(RemotePluginShareCheckoutResult { - remote_plugin_id: remote_plugin_id.to_string(), - plugin_id, - plugin_name, - plugin_path: local_plugin_path, - marketplace_name: marketplace.name, - marketplace_path: marketplace.path, - remote_version, - }) -} - -fn is_checkout_supported_share_marketplace(marketplace_name: &str) -> bool { - matches!( - marketplace_name, - REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME - | REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME - | REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME - ) -} - -fn load_share_local_paths_for_checkout( - codex_home: &Path, -) -> Result, RemotePluginCatalogError> { - match local_paths::load_plugin_share_local_paths(codex_home) { - Ok(paths) => Ok(paths), - Err(err) if err.kind() == io::ErrorKind::InvalidData => Ok(BTreeMap::new()), - Err(err) => Err(RemotePluginCatalogError::UnexpectedResponse(format!( - "failed to load plugin share local path mapping: {err}" - ))), - } -} - -fn editable_plugin_path_for_checkout( - home: &AbsolutePathBuf, - plugin_name: &str, - remote_plugin_id: &str, - local_paths: &BTreeMap, -) -> Result<(AbsolutePathBuf, bool), RemotePluginCatalogError> { - if let Some(existing_path) = local_paths.get(remote_plugin_id) - && existing_path.as_path().exists() - { - ensure_path_can_be_listed_in_personal_marketplace(home, existing_path)?; - return Ok((existing_path.clone(), true)); - } - - let local_plugin_path = local_paths - .get(remote_plugin_id) - .cloned() - .unwrap_or_else(|| home.join("plugins").join(plugin_name)); - ensure_path_can_be_listed_in_personal_marketplace(home, &local_plugin_path)?; - - if local_plugin_path.as_path().exists() { - return Err(RemotePluginCatalogError::InvalidPluginPath { - path: local_plugin_path.to_path_buf(), - reason: format!( - "cannot check out remote plugin `{remote_plugin_id}` because the local plugin path already exists" - ), - }); - } - - Ok((local_plugin_path, false)) -} - -fn clean_up_created_checkout_path( - created_checkout_path: bool, - local_plugin_path: &AbsolutePathBuf, - original_err: RemotePluginCatalogError, -) -> RemotePluginCatalogError { - if !created_checkout_path { - return original_err; - } - - match remove_created_checkout_path(local_plugin_path) { - Ok(()) => original_err, - Err(cleanup_err) => RemotePluginCatalogError::UnexpectedResponse(format!( - "{original_err}; additionally failed to clean up checked out plugin path `{}`: {cleanup_err}", - local_plugin_path.display() - )), - } -} - -fn remove_created_checkout_path(local_plugin_path: &AbsolutePathBuf) -> io::Result<()> { - if local_plugin_path.as_path().is_dir() { - fs::remove_dir_all(local_plugin_path.as_path()) - } else { - fs::remove_file(local_plugin_path.as_path()) - } -} - -fn ensure_path_can_be_listed_in_personal_marketplace( - home: &AbsolutePathBuf, - path: &AbsolutePathBuf, -) -> Result<(), RemotePluginCatalogError> { - personal_marketplace_relative_plugin_path(home, path).map(|_| ()) -} - -struct PersonalMarketplaceUpdate { - name: String, - path: AbsolutePathBuf, -} - -fn update_personal_marketplace( - home: &AbsolutePathBuf, - plugin_name: &str, - local_plugin_path: &AbsolutePathBuf, - install_policy: PluginInstallPolicy, - auth_policy: PluginAuthPolicy, - category: Option, -) -> Result { - let marketplace_path = home.join(PERSONAL_MARKETPLACE_RELATIVE_PATH); - let relative_plugin_path = personal_marketplace_relative_plugin_path(home, local_plugin_path)?; - let mut marketplace = read_or_create_personal_marketplace(marketplace_path.as_path())?; - let Some(marketplace_object) = marketplace.as_object_mut() else { - return Err(invalid_marketplace_file( - marketplace_path.as_path(), - "personal marketplace file must contain a JSON object", - )); - }; - let marketplace_name = marketplace_object - .entry("name") - .or_insert_with(|| json!(PERSONAL_MARKETPLACE_NAME)) - .as_str() - .ok_or_else(|| { - invalid_marketplace_file( - marketplace_path.as_path(), - "marketplace name must be a string", - ) - })? - .to_string(); - validate_plugin_segment(&marketplace_name, "marketplace name").map_err(|reason| { - invalid_marketplace_file( - marketplace_path.as_path(), - &format!("marketplace name is invalid: {reason}"), - ) - })?; - - let plugins = marketplace_object - .entry("plugins") - .or_insert_with(|| json!([])) - .as_array_mut() - .ok_or_else(|| { - invalid_marketplace_file( - marketplace_path.as_path(), - "marketplace plugins must be an array", - ) - })?; - - let new_entry = personal_marketplace_plugin_entry( - plugin_name, - &relative_plugin_path, - install_policy, - auth_policy, - category, - ); - - if let Some(existing_entry) = plugins - .iter_mut() - .find(|entry| entry.get("name").and_then(JsonValue::as_str) == Some(plugin_name)) - { - let existing_path = existing_entry - .get("source") - .and_then(|source| source.get("path")) - .and_then(JsonValue::as_str); - if existing_path != Some(relative_plugin_path.as_str()) { - return Err(invalid_marketplace_file( - marketplace_path.as_path(), - &format!( - "marketplace already contains plugin `{plugin_name}` with a different source path" - ), - )); - } - *existing_entry = new_entry; - } else { - plugins.push(new_entry); - } - - let contents = serde_json::to_string_pretty(&marketplace) - .map_err(|err| RemotePluginCatalogError::UnexpectedResponse(err.to_string()))?; - write_json_atomically(marketplace_path.as_path(), &format!("{contents}\n")).map_err(|err| { - RemotePluginCatalogError::UnexpectedResponse(format!( - "failed to update personal plugin marketplace: {err}" - )) - })?; - - Ok(PersonalMarketplaceUpdate { - name: marketplace_name, - path: marketplace_path, - }) -} - -fn read_or_create_personal_marketplace( - marketplace_path: &Path, -) -> Result { - match std::fs::read_to_string(marketplace_path) { - Ok(contents) => serde_json::from_str(&contents).map_err(|err| { - invalid_marketplace_file( - marketplace_path, - &format!("failed to parse personal marketplace file: {err}"), - ) - }), - Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(json!({ - "name": PERSONAL_MARKETPLACE_NAME, - "interface": { - "displayName": PERSONAL_MARKETPLACE_DISPLAY_NAME, - }, - "plugins": [], - })), - Err(err) => Err(RemotePluginCatalogError::UnexpectedResponse(format!( - "failed to read personal plugin marketplace: {err}" - ))), - } -} - -fn personal_marketplace_plugin_entry( - plugin_name: &str, - relative_plugin_path: &str, - install_policy: PluginInstallPolicy, - auth_policy: PluginAuthPolicy, - category: Option, -) -> JsonValue { - let mut entry = json!({ - "name": plugin_name, - "source": { - "source": "local", - "path": relative_plugin_path, - }, - "policy": { - "installation": plugin_install_policy_value(install_policy), - "authentication": plugin_auth_policy_value(auth_policy), - }, - }); - if let Some(category) = category - && !category.trim().is_empty() - && let Some(object) = entry.as_object_mut() - { - object.insert("category".to_string(), json!(category)); - } - entry -} - -fn plugin_install_policy_value(policy: PluginInstallPolicy) -> &'static str { - match policy { - PluginInstallPolicy::NotAvailable => "NOT_AVAILABLE", - PluginInstallPolicy::Available => "AVAILABLE", - PluginInstallPolicy::InstalledByDefault => "INSTALLED_BY_DEFAULT", - } -} - -fn plugin_auth_policy_value(policy: PluginAuthPolicy) -> &'static str { - match policy { - PluginAuthPolicy::OnInstall => "ON_INSTALL", - PluginAuthPolicy::OnUse => "ON_USE", - } -} - -fn personal_marketplace_relative_plugin_path( - home: &AbsolutePathBuf, - local_plugin_path: &AbsolutePathBuf, -) -> Result { - let relative = local_plugin_path - .as_path() - .strip_prefix(home.as_path()) - .map_err(|_| RemotePluginCatalogError::InvalidPluginPath { - path: local_plugin_path.to_path_buf(), - reason: "local plugin path must be inside the home directory to be listed in the personal marketplace".to_string(), - })?; - let mut segments = Vec::new(); - for component in relative.components() { - match component { - Component::Normal(segment) => { - let segment = segment.to_str().ok_or_else(|| { - RemotePluginCatalogError::InvalidPluginPath { - path: local_plugin_path.to_path_buf(), - reason: "local plugin path contains non-UTF-8 segments".to_string(), - } - })?; - segments.push(segment.to_string()); - } - Component::CurDir => {} - Component::ParentDir | Component::RootDir | Component::Prefix(_) => { - return Err(RemotePluginCatalogError::InvalidPluginPath { - path: local_plugin_path.to_path_buf(), - reason: - "local plugin path cannot be represented as a personal marketplace path" - .to_string(), - }); - } - } - } - if segments.is_empty() { - return Err(RemotePluginCatalogError::InvalidPluginPath { - path: local_plugin_path.to_path_buf(), - reason: "local plugin path must not be the home directory".to_string(), - }); - } - Ok(format!("./{}", segments.join("/"))) -} - -fn invalid_marketplace_file(path: &Path, message: &str) -> RemotePluginCatalogError { - RemotePluginCatalogError::InvalidPluginPath { - path: path.to_path_buf(), - reason: message.to_string(), - } -} - -fn write_json_atomically(write_path: &Path, contents: &str) -> io::Result<()> { - let parent = write_path.parent().ok_or_else(|| { - io::Error::new( - io::ErrorKind::InvalidInput, - format!("path {} has no parent directory", write_path.display()), - ) - })?; - std::fs::create_dir_all(parent)?; - let mut tmp = tempfile::NamedTempFile::new_in(parent)?; - tmp.write_all(contents.as_bytes())?; - tmp.persist(write_path).map_err(|err| err.error)?; - Ok(()) -} diff --git a/codex-rs/core-plugins/src/remote_bundle.rs b/codex-rs/core-plugins/src/remote_bundle.rs deleted file mode 100644 index 8cf9ad2b..00000000 --- a/codex-rs/core-plugins/src/remote_bundle.rs +++ /dev/null @@ -1,995 +0,0 @@ -use crate::error_subtype::http_status_sub_error_type; -use crate::plugin_bundle_archive::PluginBundleUnpackError; -use crate::plugin_bundle_archive::unpack_plugin_bundle_tar_gz; -use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME; -use crate::remote::RemotePluginServiceConfig; -use crate::store::PluginInstallResult; -use crate::store::PluginStore; -use crate::store::PluginStoreError; -use crate::store::error_context_sub_error_type; -use crate::store::validate_plugin_version_segment; -use codex_http_client::RouteAwareRequestError; -use codex_plugin::PluginId; -use codex_plugin::PluginIdError; -use codex_utils_absolute_path::AbsolutePathBuf; -use codex_utils_plugins::AGENT_PLUGIN_MANIFEST_RELATIVE_PATH; -use codex_utils_plugins::AgentPluginSchemaStatus; -use codex_utils_plugins::agent_plugin_schema_status; -use codex_utils_plugins::find_plugin_manifest_path; -use http::StatusCode; -use serde_json::Value as JsonValue; -use std::fs; -use std::io; -use std::path::Path; -use std::path::PathBuf; -use url::Host; -use url::Url; - -const REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024; -const REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES: u64 = 512 * 1024 * 1024; -const REMOTE_PLUGIN_INSTALL_STAGING_DIR: &str = "plugins/.remote-plugin-install-staging"; -#[cfg(debug_assertions)] -const TEST_ALLOW_LOOPBACK_HTTP_REMOTE_PLUGIN_BUNDLES_ENV: &str = - "CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS"; - -#[derive(Clone)] -pub struct ValidatedRemotePluginBundle { - pub plugin_id: PluginId, - pub plugin_version: String, - remote_plugin_id: String, - app_manifest: Option, - bundle_download_url: String, -} - -impl std::fmt::Debug for ValidatedRemotePluginBundle { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter - .debug_struct("ValidatedRemotePluginBundle") - .field("plugin_id", &self.plugin_id) - .field("plugin_version", &self.plugin_version) - .field("remote_plugin_id", &self.remote_plugin_id) - .finish_non_exhaustive() - } -} - -#[derive(Debug, thiserror::Error)] -pub enum RemotePluginBundleInstallError { - #[error("remote plugin bundles are not available in aKode")] - Unavailable, - - #[error("backend did not return a release version for remote plugin `{remote_plugin_id}`")] - MissingReleaseVersion { remote_plugin_id: String }, - - #[error( - "backend returned an invalid release version for remote plugin `{remote_plugin_id}`: {message}" - )] - InvalidReleaseVersion { - remote_plugin_id: String, - message: String, - }, - - #[error("backend did not return a download URL for remote plugin `{remote_plugin_id}`")] - MissingBundleDownloadUrl { remote_plugin_id: String }, - - #[error( - "backend returned an invalid download URL for remote plugin `{remote_plugin_id}`: {source}" - )] - InvalidBundleDownloadUrl { - remote_plugin_id: String, - #[source] - source: url::ParseError, - }, - - #[error( - "backend returned an unsupported download URL scheme for remote plugin `{remote_plugin_id}`: {scheme}" - )] - UnsupportedBundleDownloadUrlScheme { - remote_plugin_id: String, - scheme: String, - }, - - #[error( - "backend returned an invalid local plugin id for remote plugin `{remote_plugin_id}`: {source}" - )] - InvalidPluginId { - remote_plugin_id: String, - #[source] - source: PluginIdError, - }, - - #[error("failed to send remote plugin bundle download request to {host}: {source}")] - DownloadRequest { - host: String, - #[source] - source: RouteAwareRequestError, - }, - - #[error("remote plugin bundle download from {host} failed with status {status}: {body}")] - DownloadStatus { - host: String, - status: StatusCode, - body: String, - }, - - #[error("failed to read remote plugin bundle download response from {host}: {source}")] - DownloadBody { - host: String, - #[source] - source: codex_http_client::HttpError, - }, - - #[error("remote plugin bundle download from {host} exceeded maximum size of {max_bytes} bytes")] - DownloadTooLarge { host: String, max_bytes: u64 }, - - #[error( - "remote plugin bundle download from {host} resolved to unsupported URL scheme {scheme}" - )] - UnsupportedBundleDownloadFinalUrl { host: String, scheme: String }, - - #[error( - "remote plugin bundle extracted size would be {bytes} bytes, exceeding the maximum total size of {max_bytes} bytes" - )] - ExtractedBundleTooLarge { bytes: u64, max_bytes: u64 }, - - #[error("{context}: {source}")] - Io { - context: &'static str, - #[source] - source: io::Error, - }, - - #[error("{0}")] - InvalidBundle(String), - - #[error("{0}")] - Store(#[from] PluginStoreError), -} - -impl RemotePluginBundleInstallError { - fn io(context: &'static str, source: io::Error) -> Self { - Self::Io { context, source } - } - - pub fn sub_error_type(&self) -> Option { - match self { - Self::Io { context, .. } => Some(error_context_sub_error_type(context)), - Self::Store(err) => err.sub_error_type(), - Self::DownloadStatus { status, .. } => { - Some(http_status_sub_error_type(*status).to_string()) - } - Self::Unavailable - | Self::MissingReleaseVersion { .. } - | Self::InvalidReleaseVersion { .. } - | Self::MissingBundleDownloadUrl { .. } - | Self::InvalidBundleDownloadUrl { .. } - | Self::UnsupportedBundleDownloadUrlScheme { .. } - | Self::InvalidPluginId { .. } - | Self::DownloadRequest { .. } - | Self::DownloadBody { .. } - | Self::DownloadTooLarge { .. } - | Self::UnsupportedBundleDownloadFinalUrl { .. } - | Self::ExtractedBundleTooLarge { .. } - | Self::InvalidBundle(_) => None, - } - } -} - -pub fn validate_remote_plugin_bundle( - remote_plugin_id: &str, - remote_marketplace_name: &str, - plugin_name: &str, - release_version: Option<&str>, - bundle_download_url: Option<&str>, - app_manifest: Option, -) -> Result { - let plugin_id = PluginId::new(plugin_name.to_string(), remote_marketplace_name.to_string()) - .map_err(|source| RemotePluginBundleInstallError::InvalidPluginId { - remote_plugin_id: remote_plugin_id.to_string(), - source, - })?; - let plugin_version = release_version - .map(str::trim) - .filter(|version| !version.is_empty()) - .ok_or_else(|| RemotePluginBundleInstallError::MissingReleaseVersion { - remote_plugin_id: remote_plugin_id.to_string(), - })? - .to_string(); - validate_plugin_version_segment(&plugin_version).map_err(|message| { - RemotePluginBundleInstallError::InvalidReleaseVersion { - remote_plugin_id: remote_plugin_id.to_string(), - message, - } - })?; - let bundle_download_url = bundle_download_url - .map(str::trim) - .filter(|url| !url.is_empty()) - .ok_or_else( - || RemotePluginBundleInstallError::MissingBundleDownloadUrl { - remote_plugin_id: remote_plugin_id.to_string(), - }, - )? - .to_string(); - let parsed_bundle_url = Url::parse(&bundle_download_url).map_err(|source| { - RemotePluginBundleInstallError::InvalidBundleDownloadUrl { - remote_plugin_id: remote_plugin_id.to_string(), - source, - } - })?; - if !is_allowed_bundle_download_url( - &parsed_bundle_url, - allow_test_loopback_http_bundle_downloads(), - ) { - return Err( - RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme { - remote_plugin_id: remote_plugin_id.to_string(), - scheme: parsed_bundle_url.scheme().to_string(), - }, - ); - } - - Ok(ValidatedRemotePluginBundle { - plugin_id, - plugin_version, - remote_plugin_id: remote_plugin_id.to_string(), - app_manifest, - bundle_download_url, - }) -} - -fn allow_test_loopback_http_bundle_downloads() -> bool { - #[cfg(debug_assertions)] - { - if let Ok(value) = std::env::var(TEST_ALLOW_LOOPBACK_HTTP_REMOTE_PLUGIN_BUNDLES_ENV) { - return value == "1"; - } - } - - false -} - -fn is_allowed_bundle_download_url(url: &Url, allow_loopback_http: bool) -> bool { - match url.scheme() { - "https" => true, - "http" => allow_loopback_http && is_loopback_url(url), - _ => false, - } -} - -fn is_loopback_url(url: &Url) -> bool { - match url.host() { - Some(Host::Ipv4(addr)) => addr.is_loopback(), - Some(Host::Ipv6(addr)) => addr.is_loopback(), - Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), - None => false, - } -} - -pub async fn download_and_install_remote_plugin_bundle( - config: &RemotePluginServiceConfig, - codex_home: PathBuf, - bundle: ValidatedRemotePluginBundle, -) -> Result { - let bundle_bytes = download_remote_plugin_bundle(config, &bundle).await?; - tokio::task::spawn_blocking(move || { - install_remote_plugin_bundle(codex_home, bundle, bundle_bytes) - }) - .await - .map_err(|err| { - RemotePluginBundleInstallError::InvalidBundle(format!( - "failed to join remote plugin bundle install task: {err}" - )) - })? -} - -pub(crate) async fn download_and_extract_remote_plugin_bundle_to_path( - config: &RemotePluginServiceConfig, - bundle: ValidatedRemotePluginBundle, - destination: AbsolutePathBuf, -) -> Result { - let bundle_bytes = download_remote_plugin_bundle(config, &bundle).await?; - tokio::task::spawn_blocking(move || { - extract_remote_plugin_bundle_to_path(bundle, bundle_bytes, destination) - }) - .await - .map_err(|err| { - RemotePluginBundleInstallError::InvalidBundle(format!( - "failed to join remote plugin bundle extraction task: {err}" - )) - })? -} - -pub(crate) async fn download_remote_plugin_bundle( - config: &RemotePluginServiceConfig, - bundle: &ValidatedRemotePluginBundle, -) -> Result, RemotePluginBundleInstallError> { - download_remote_plugin_bundle_with_limit( - config, - &bundle.bundle_download_url, - /*max_bytes*/ REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES, - ) - .await -} - -async fn download_remote_plugin_bundle_with_limit( - config: &RemotePluginServiceConfig, - bundle_download_url: &str, - max_bytes: u64, -) -> Result, RemotePluginBundleInstallError> { - let _ = (config, bundle_download_url, max_bytes); - Err(RemotePluginBundleInstallError::Unavailable) -} - -pub(crate) fn install_remote_plugin_bundle( - codex_home: PathBuf, - bundle: ValidatedRemotePluginBundle, - bundle_bytes: Vec, -) -> Result { - let staging_root = codex_home.join(REMOTE_PLUGIN_INSTALL_STAGING_DIR); - fs::create_dir_all(&staging_root).map_err(|source| { - RemotePluginBundleInstallError::io( - "failed to create remote plugin bundle staging directory", - source, - ) - })?; - let extract_dir = tempfile::Builder::new() - .prefix("remote-plugin-bundle-") - .tempdir_in(&staging_root) - .map_err(|source| { - RemotePluginBundleInstallError::io( - "failed to create remote plugin bundle extraction directory", - source, - ) - })?; - - extract_plugin_bundle_tar_gz(&bundle_bytes, extract_dir.path())?; - let plugin_root = find_extracted_plugin_root(extract_dir.path())?; - prepare_extracted_remote_plugin_root(&plugin_root, &bundle)?; - let plugin_root = AbsolutePathBuf::try_from(plugin_root).map_err(|err| { - RemotePluginBundleInstallError::InvalidBundle(format!( - "failed to resolve extracted remote plugin bundle root: {err}" - )) - })?; - - let store = PluginStore::try_new(codex_home)?; - let remote_plugin_id = bundle.remote_plugin_id; - let result = store - .install_with_version(plugin_root, bundle.plugin_id, bundle.plugin_version) - .map_err(RemotePluginBundleInstallError::from)?; - store.write_remote_plugin_id(&result.plugin_id, &remote_plugin_id)?; - Ok(result) -} - -fn extract_remote_plugin_bundle_to_path( - bundle: ValidatedRemotePluginBundle, - bundle_bytes: Vec, - destination: AbsolutePathBuf, -) -> Result { - if destination.as_path().exists() { - return Err(RemotePluginBundleInstallError::InvalidBundle(format!( - "plugin checkout destination already exists: {}", - destination.display() - ))); - } - - let parent = destination.as_path().parent().ok_or_else(|| { - RemotePluginBundleInstallError::InvalidBundle(format!( - "plugin checkout destination has no parent: {}", - destination.display() - )) - })?; - fs::create_dir_all(parent).map_err(|source| { - RemotePluginBundleInstallError::io("failed to create plugin checkout directory", source) - })?; - - let extract_dir = tempfile::Builder::new() - .prefix("remote-plugin-checkout-") - .tempdir_in(parent) - .map_err(|source| { - RemotePluginBundleInstallError::io( - "failed to create remote plugin bundle extraction directory", - source, - ) - })?; - - extract_plugin_bundle_tar_gz(&bundle_bytes, extract_dir.path())?; - let plugin_root = find_extracted_plugin_root(extract_dir.path())?; - let manifest = crate::manifest::load_plugin_manifest(&plugin_root).ok_or_else(|| { - RemotePluginBundleInstallError::InvalidBundle( - "remote plugin bundle did not contain a valid plugin.json".to_string(), - ) - })?; - if manifest.name != bundle.plugin_id.plugin_name { - return Err(RemotePluginBundleInstallError::InvalidBundle(format!( - "plugin.json name `{}` does not match remote plugin name `{}`", - manifest.name, bundle.plugin_id.plugin_name - ))); - } - - let staged_path = extract_dir.keep(); - fs::rename(&staged_path, destination.as_path()).map_err(|source| { - RemotePluginBundleInstallError::io( - "failed to activate checked out plugin directory", - source, - ) - })?; - - Ok(destination) -} - -fn prepare_extracted_remote_plugin_root( - plugin_root: &Path, - bundle: &ValidatedRemotePluginBundle, -) -> Result<(), RemotePluginBundleInstallError> { - if bundle.plugin_id.marketplace_name != REMOTE_GLOBAL_MARKETPLACE_NAME { - return Ok(()); - } - - overwrite_plugin_manifest_version(plugin_root, &bundle.plugin_version)?; - if let Some(app_manifest) = &bundle.app_manifest { - overwrite_plugin_app_manifest(plugin_root, app_manifest)?; - } - Ok(()) -} - -fn overwrite_plugin_manifest_version( - plugin_root: &Path, - plugin_version: &str, -) -> Result<(), RemotePluginBundleInstallError> { - let manifest_path = find_plugin_manifest_path(plugin_root).ok_or_else(|| { - RemotePluginBundleInstallError::InvalidBundle( - "remote plugin bundle did not contain a valid plugin.json".to_string(), - ) - })?; - let contents = fs::read_to_string(&manifest_path).map_err(|source| { - RemotePluginBundleInstallError::io("failed to read remote plugin manifest", source) - })?; - if manifest_path == plugin_root.join(AGENT_PLUGIN_MANIFEST_RELATIVE_PATH) - && agent_plugin_schema_status(&contents) == AgentPluginSchemaStatus::Supported - { - return Ok(()); - } - let mut manifest: JsonValue = serde_json::from_str(&contents).map_err(|err| { - RemotePluginBundleInstallError::InvalidBundle(format!( - "failed to parse remote plugin manifest: {err}" - )) - })?; - let Some(manifest_object) = manifest.as_object_mut() else { - return Err(RemotePluginBundleInstallError::InvalidBundle( - "remote plugin manifest must be a JSON object".to_string(), - )); - }; - manifest_object.insert( - "version".to_string(), - JsonValue::String(plugin_version.to_string()), - ); - write_json_file( - &manifest_path, - &manifest, - "failed to write remote plugin manifest", - ) -} - -fn overwrite_plugin_app_manifest( - plugin_root: &Path, - app_manifest: &JsonValue, -) -> Result<(), RemotePluginBundleInstallError> { - let app_manifest_path = crate::manifest::load_plugin_manifest(plugin_root) - .and_then(|manifest| manifest.paths.apps.map(|path| path.to_path_buf())) - .unwrap_or_else(|| plugin_root.join(".app.json")); - write_json_file( - &app_manifest_path, - app_manifest, - "failed to write remote plugin app manifest", - ) -} - -fn write_json_file( - path: &Path, - value: &JsonValue, - context: &'static str, -) -> Result<(), RemotePluginBundleInstallError> { - let parent = path.parent().ok_or_else(|| { - RemotePluginBundleInstallError::InvalidBundle(format!( - "remote plugin output path has no parent: {}", - path.display() - )) - })?; - fs::create_dir_all(parent) - .map_err(|source| RemotePluginBundleInstallError::io(context, source))?; - let mut contents = serde_json::to_vec_pretty(value).map_err(|err| { - RemotePluginBundleInstallError::InvalidBundle(format!( - "failed to serialize remote plugin JSON override: {err}" - )) - })?; - contents.push(b'\n'); - fs::write(path, contents).map_err(|source| RemotePluginBundleInstallError::io(context, source)) -} - -fn extract_plugin_bundle_tar_gz( - bytes: &[u8], - destination: &Path, -) -> Result<(), RemotePluginBundleInstallError> { - extract_plugin_bundle_tar_gz_with_limits( - bytes, - destination, - REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES, - ) -} - -fn extract_plugin_bundle_tar_gz_with_limits( - bytes: &[u8], - destination: &Path, - max_total_bytes: u64, -) -> Result<(), RemotePluginBundleInstallError> { - unpack_plugin_bundle_tar_gz(bytes, destination, max_total_bytes).map_err(|err| match err { - PluginBundleUnpackError::ExtractedBundleTooLarge { bytes, max_bytes } => { - RemotePluginBundleInstallError::ExtractedBundleTooLarge { bytes, max_bytes } - } - PluginBundleUnpackError::Io { context, source } => { - RemotePluginBundleInstallError::io(context, source) - } - PluginBundleUnpackError::InvalidBundle(message) => { - RemotePluginBundleInstallError::InvalidBundle(message) - } - }) -} - -fn find_extracted_plugin_root( - extraction_root: &Path, -) -> Result { - if is_standard_plugin_root(extraction_root) { - return Ok(extraction_root.to_path_buf()); - } - - Err(RemotePluginBundleInstallError::InvalidBundle( - "remote plugin bundle did not contain a standard plugin root with plugin.json".to_string(), - )) -} - -fn is_standard_plugin_root(path: &Path) -> bool { - find_plugin_manifest_path(path).is_some() -} - -#[cfg(test)] -mod tests { - use super::*; - use flate2::Compression; - use flate2::write::GzEncoder; - use pretty_assertions::assert_eq; - use std::io::Write; - use tempfile::tempdir; - - const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000"; - - #[test] - fn remote_version_normalization_preserves_portable_root_manifest() { - let temp_dir = tempdir().expect("tempdir"); - let manifest_path = temp_dir.path().join("plugin.json"); - let original = r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"portable","version":"release-2026-07"}"#; - fs::write(&manifest_path, original).expect("write portable manifest"); - - overwrite_plugin_manifest_version(temp_dir.path(), "1.2.3") - .expect("prepare portable remote plugin"); - - assert_eq!( - fs::read_to_string(manifest_path).expect("read portable manifest"), - original - ); - } - - #[test] - fn validate_remote_plugin_bundle_uses_detail_name_for_local_plugin_id() { - let bundle = validate_remote_plugin_bundle( - REMOTE_PLUGIN_ID, - "openai-curated-remote", - "linear", - Some("1.2.3"), - Some("https://example.com/linear.tar.gz?sig=signed-token"), - /*app_manifest*/ None, - ) - .expect("valid install plan"); - - assert_eq!(bundle.plugin_id.plugin_name, "linear"); - assert_eq!(bundle.plugin_id.marketplace_name, "openai-curated-remote"); - assert_eq!(bundle.plugin_version, "1.2.3"); - assert_eq!( - bundle.bundle_download_url.as_str(), - "https://example.com/linear.tar.gz?sig=signed-token" - ); - assert!(!format!("{bundle:?}").contains("signed-token")); - } - - #[test] - fn validate_remote_plugin_bundle_rejects_missing_release_version() { - let err = validate_remote_plugin_bundle( - REMOTE_PLUGIN_ID, - "openai-curated-remote", - "linear", - /*release_version*/ None, - Some("https://example.com/linear.tar.gz"), - /*app_manifest*/ None, - ) - .expect_err("missing release version should be rejected"); - - assert!(matches!( - err, - RemotePluginBundleInstallError::MissingReleaseVersion { .. } - )); - } - - #[test] - fn validate_remote_plugin_bundle_rejects_invalid_release_version() { - let err = validate_remote_plugin_bundle( - REMOTE_PLUGIN_ID, - "openai-curated-remote", - "linear", - Some("../1.2.3"), - Some("https://example.com/linear.tar.gz"), - /*app_manifest*/ None, - ) - .expect_err("invalid release version should be rejected"); - - assert!(matches!( - err, - RemotePluginBundleInstallError::InvalidReleaseVersion { .. } - )); - } - - #[test] - fn validate_remote_plugin_bundle_rejects_missing_download_url() { - let err = validate_remote_plugin_bundle( - REMOTE_PLUGIN_ID, - "openai-curated-remote", - "linear", - Some("1.2.3"), - /*bundle_download_url*/ None, - /*app_manifest*/ None, - ) - .expect_err("missing bundle download URL should be rejected"); - - assert!(matches!( - err, - RemotePluginBundleInstallError::MissingBundleDownloadUrl { .. } - )); - } - - #[test] - fn validate_remote_plugin_bundle_rejects_unsupported_download_url_scheme() { - let err = validate_remote_plugin_bundle( - REMOTE_PLUGIN_ID, - "openai-curated-remote", - "linear", - Some("1.2.3"), - Some("http://example.com/linear.tar.gz"), - /*app_manifest*/ None, - ) - .expect_err("plain HTTP URLs should be rejected before cloud install"); - - assert!(matches!( - err, - RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme { .. } - )); - } - - #[test] - fn install_rejects_invalid_tar_gz_bundle() { - let codex_home = tempdir().expect("tempdir"); - let bundle = valid_remote_plugin_bundle(); - - let err = install_remote_plugin_bundle( - codex_home.path().to_path_buf(), - bundle, - b"not a tar.gz".to_vec(), - ) - .expect_err("invalid tar.gz should be rejected"); - - assert!(format!("{err}").contains("failed to read plugin bundle tar")); - } - - #[test] - fn install_rejects_bundle_without_standard_plugin_root() { - let codex_home = tempdir().expect("tempdir"); - let bundle = valid_remote_plugin_bundle(); - - let err = install_remote_plugin_bundle( - codex_home.path().to_path_buf(), - bundle, - tar_gz_bytes(&[("README.md", b"missing plugin manifest", /*mode*/ 0o644)]), - ) - .expect_err("bundle without plugin root should be rejected"); - - assert!( - format!("{err}").contains("did not contain a standard plugin root with plugin.json") - ); - } - - #[test] - fn install_persists_remote_plugin_install_metadata() { - let codex_home = tempdir().expect("tempdir"); - let bundle = valid_remote_plugin_bundle(); - - let result = install_remote_plugin_bundle( - codex_home.path().to_path_buf(), - bundle, - tar_gz_bytes(&[( - ".codex-plugin/plugin.json", - br#"{"name":"linear","version":"1.2.3"}"#, - /*mode*/ 0o644, - )]), - ) - .expect("install bundle"); - let store = PluginStore::new(codex_home.path().to_path_buf()); - - assert_eq!( - store.remote_plugin_id(&result.plugin_id).unwrap(), - Some(REMOTE_PLUGIN_ID.to_string()) - ); - let metadata_path = store - .plugin_base_root(&result.plugin_id) - .join(".codex-remote-plugin-install.json"); - assert_eq!( - serde_json::from_str::( - &std::fs::read_to_string(metadata_path.as_path()) - .expect("read remote plugin install metadata") - ) - .expect("parse remote plugin install metadata"), - serde_json::json!({ - "schema_version": 1, - "remote_plugin_id": REMOTE_PLUGIN_ID, - }) - ); - } - - #[test] - fn install_preserves_non_global_bundle_manifest_metadata() { - let codex_home = tempdir().expect("tempdir"); - let bundle = validate_remote_plugin_bundle( - REMOTE_PLUGIN_ID, - "workspace-shared-with-me", - "linear", - Some("backend-version"), - Some("https://example.com/linear.tar.gz"), - Some(serde_json::json!({ - "apps": { - "remote": { - "id": "remote-app" - } - } - })), - ) - .expect("valid install plan"); - - let result = install_remote_plugin_bundle( - codex_home.path().to_path_buf(), - bundle, - tar_gz_bytes(&[ - ( - ".codex-plugin/plugin.json", - br#"{"name":"linear","version":"bundle-version"}"#, - /*mode*/ 0o644, - ), - ( - ".app.json", - br#"{"apps":{"bundled":{"id":"bundled-app"}}}"#, - /*mode*/ 0o644, - ), - ]), - ) - .expect("install bundle"); - - assert_eq!(result.plugin_version, "backend-version"); - let installed_manifest: JsonValue = serde_json::from_str( - &std::fs::read_to_string( - result - .installed_path - .join(".codex-plugin/plugin.json") - .as_path(), - ) - .expect("read installed plugin manifest"), - ) - .expect("parse installed plugin manifest"); - assert_eq!( - installed_manifest, - serde_json::json!({ - "name": "linear", - "version": "bundle-version", - }) - ); - let installed_app_manifest: JsonValue = serde_json::from_str( - &std::fs::read_to_string(result.installed_path.join(".app.json").as_path()) - .expect("read installed app manifest"), - ) - .expect("parse installed app manifest"); - assert_eq!( - installed_app_manifest, - serde_json::json!({ - "apps": { - "bundled": { - "id": "bundled-app", - }, - }, - }) - ); - } - - #[test] - fn find_extracted_plugin_root_uses_local_manifest_discovery() { - let extraction_root = tempdir().expect("tempdir"); - std::fs::create_dir_all(extraction_root.path().join(".codex-plugin")) - .expect("create manifest dir"); - std::fs::write( - extraction_root.path().join(".codex-plugin/plugin.json"), - r#"{"name":"linear"}"#, - ) - .expect("write manifest"); - - assert_eq!( - find_extracted_plugin_root(extraction_root.path()).expect("plugin root"), - extraction_root.path() - ); - } - - #[test] - fn find_extracted_plugin_root_rejects_nested_plugin_root() { - let extraction_root = tempdir().expect("tempdir"); - let plugin_root = extraction_root.path().join("linear"); - std::fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create manifest dir"); - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"linear"}"#, - ) - .expect("write manifest"); - - let err = find_extracted_plugin_root(extraction_root.path()) - .expect_err("nested plugin root should be rejected"); - - assert!( - format!("{err}").contains("did not contain a standard plugin root with plugin.json") - ); - } - - #[test] - fn extraction_rejects_tar_path_traversal() { - let destination = tempdir().expect("tempdir"); - let err = extract_plugin_bundle_tar_gz( - &tar_gz_bytes_with_raw_path("../evil.txt", b"evil", /*mode*/ 0o644), - destination.path(), - ) - .expect_err("tar path traversal should be rejected"); - - assert!(format!("{err}").contains("escapes extraction root")); - } - - #[test] - fn extraction_rejects_total_size_over_limit() { - let destination = tempdir().expect("tempdir"); - let err = extract_plugin_bundle_tar_gz_with_limits( - &tar_gz_bytes(&[ - ("a.txt", b"1234", /*mode*/ 0o644), - ("b.txt", b"5678", /*mode*/ 0o644), - ]), - destination.path(), - /*max_total_bytes*/ 6, - ) - .expect_err("oversized extracted bundle should be rejected"); - - assert!(matches!( - err, - RemotePluginBundleInstallError::ExtractedBundleTooLarge { .. } - )); - } - - #[test] - fn extraction_supports_gnu_long_name_entries() { - let destination = tempdir().expect("tempdir"); - let long_path = format!("{}/file.txt", ["segment"; 40].join("/")); - - extract_plugin_bundle_tar_gz( - &tar_gz_bytes(&[(long_path.as_str(), b"long", /*mode*/ 0o644)]), - destination.path(), - ) - .expect("extract bundle with GNU long name entry"); - - assert_eq!( - std::fs::read(destination.path().join(long_path)).expect("read extracted file"), - b"long" - ); - } - - #[cfg(unix)] - #[test] - fn extraction_preserves_executable_permissions() { - use std::os::unix::fs::PermissionsExt; - - let destination = tempdir().expect("tempdir"); - extract_plugin_bundle_tar_gz( - &tar_gz_bytes(&[ - ( - ".codex-plugin/plugin.json", - b"{\"name\":\"linear\"}", - /*mode*/ 0o644, - ), - ("bin/helper", b"#!/bin/sh\n", /*mode*/ 0o755), - ]), - destination.path(), - ) - .expect("extract bundle"); - - let mode = std::fs::metadata(destination.path().join("bin/helper")) - .expect("helper metadata") - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o755); - } - - fn valid_remote_plugin_bundle() -> ValidatedRemotePluginBundle { - validate_remote_plugin_bundle( - REMOTE_PLUGIN_ID, - "openai-curated-remote", - "linear", - Some("1.2.3"), - Some("https://example.com/linear.tar.gz"), - /*app_manifest*/ None, - ) - .expect("valid install plan") - } - - fn tar_gz_bytes(entries: &[(&str, &[u8], u32)]) -> Vec { - let encoder = GzEncoder::new(Vec::new(), Compression::default()); - let mut tar = tar::Builder::new(encoder); - for (path, contents, mode) in entries { - append_tar_entry(&mut tar, tar::EntryType::Regular, path, contents, *mode); - } - finish_tar_gz(tar) - } - - fn tar_gz_bytes_with_raw_path(path: &str, contents: &[u8], mode: u32) -> Vec { - let mut header = tar::Header::new_gnu(); - header.set_entry_type(tar::EntryType::Regular); - header.set_size(contents.len() as u64); - header.set_mode(mode); - header.as_mut_bytes()[..path.len()].copy_from_slice(path.as_bytes()); - header.set_cksum(); - - let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); - encoder - .write_all(header.as_bytes()) - .expect("write tar header"); - encoder.write_all(contents).expect("write tar contents"); - let padding = (512 - (contents.len() % 512)) % 512; - encoder - .write_all(&vec![0; padding]) - .expect("write tar padding"); - encoder.write_all(&[0; 1024]).expect("write tar terminator"); - encoder.finish().expect("finish gzip") - } - - fn append_tar_entry( - tar: &mut tar::Builder, - entry_type: tar::EntryType, - path: &str, - contents: &[u8], - mode: u32, - ) { - let mut header = tar::Header::new_gnu(); - header.set_entry_type(entry_type); - header.set_size(contents.len() as u64); - header.set_mode(mode); - header.set_cksum(); - if let Err(error) = tar.append_data(&mut header, path, contents) { - panic!("failed to append tar test data: {error}"); - } - } - - fn finish_tar_gz(tar: tar::Builder>>) -> Vec { - let encoder = match tar.into_inner() { - Ok(encoder) => encoder, - Err(error) => panic!("failed to finish tar test data: {error}"), - }; - match encoder.finish() { - Ok(bytes) => bytes, - Err(error) => panic!("failed to finish gzip test data: {error}"), - } - } -} diff --git a/codex-rs/tui/src/analytics.rs b/codex-rs/tui/src/analytics.rs deleted file mode 100644 index fe83268a..00000000 --- a/codex-rs/tui/src/analytics.rs +++ /dev/null @@ -1,536 +0,0 @@ -//! Authenticated account analytics dashboard. -//! Stable report tabs share bounded account loads, selection, and inline details. - -mod activity_chart; -mod chart; -mod summary; -mod summary_panel; -pub(crate) use activity_chart::TokenActivityView; -mod chat_panel; -mod chats; -mod chrome; -mod client; -mod controls; -mod dashboard; -mod data; -#[cfg(test)] -#[path = "analytics/test_fixtures.rs"] -mod fixture; -mod hints; -mod models; -mod mouse; -mod normalize; -mod panels; -mod plan; -mod plan_panel; -mod plot; -mod render; -mod report_data; -mod sections; -mod styles; -mod task_panel; -mod tasks; -#[cfg(test)] -#[path = "analytics/test_support.rs"] -mod test_support; -mod tokens; -mod tool_panel; - -#[cfg(test)] -#[path = "analytics_tests.rs"] -mod tests; - -use crate::key_hint; -use crate::keymap::ListAction; -use crate::keymap::ListKeymap; -use crate::tui; -use crate::tui::FrameRequester; -use crate::tui::TuiEvent; -use codex_app_server_client::AppServerRequestHandle; -use crossterm::event::KeyCode; -use crossterm::event::KeyEvent; -use crossterm::event::KeyEventKind; -use crossterm::event::MouseButton; -use crossterm::event::MouseEventKind; -use data::Load; -use sections::Section; -use sections::SectionState; -use sections::SectionStates; - -pub(crate) struct AnalyticsView { - clock_format: crate::clock_format::ClockFormat, - model_names: std::collections::HashMap, - sections: SectionStates, - chats: Load, - tasks: Load, - chat_metric: usize, - profile: Load, - plan: plan::State, - show_zero_credit_groups: bool, - account: Load, - reports_started: bool, - connection: Option<( - std::sync::Arc, - AppServerRequestHandle, - FrameRequester, - )>, - live: Option>, - pub(crate) keymap: ListKeymap, - section: Section, - show_help: bool, - zoomed: bool, - dashboard_scroll: usize, - body_area: ratatui::layout::Rect, - report_area: ratatui::layout::Rect, - tab_hits: Vec<(Section, ratatui::layout::Rect)>, - control_hits: Vec<(controls::Control, ratatui::layout::Rect)>, - mouse_context: Option<(Section, bool, bool)>, - max_scroll: usize, - selection_visible: bool, - help_scroll: usize, - follow_selection: bool, - viewport_height: usize, - ranges: [usize; 3], - end_date: chrono::NaiveDate, - token_model: Option, - pub(crate) is_done: bool, -} - -impl AnalyticsView { - pub(crate) fn new(keymap: ListKeymap) -> Self { - let mut view = Self { - clock_format: crate::clock_format::ClockFormat::system(), - model_names: std::collections::HashMap::new(), - sections: SectionStates(std::array::from_fn(|_| SectionState::default())), - chats: Load::Unavailable, - tasks: Load::Unavailable, - chat_metric: 0, - profile: Load::Unavailable, - plan: plan::State::default(), - show_zero_credit_groups: false, - account: Load::Unavailable, - reports_started: false, - connection: None, - live: None, - keymap, - section: Section::Summary, - show_help: false, - zoomed: true, - dashboard_scroll: 0, - body_area: ratatui::layout::Rect::default(), - report_area: ratatui::layout::Rect::default(), - tab_hits: Vec::new(), - control_hits: Vec::new(), - mouse_context: None, - max_scroll: 0, - selection_visible: false, - help_scroll: 0, - follow_selection: true, - viewport_height: 1, - ranges: [0; 3], - end_date: chrono::Utc::now().date_naive(), - token_model: None, - is_done: false, - }; - view.sections[Section::Usage].group = 1; - view.sections[Section::Plan].group = 1; - view.sections[Section::Chats].cursor = 0; - view.sections[Section::Activity].group = 2; - view.refresh(); - view - } - - pub(crate) fn open( - &mut self, - handle: AppServerRequestHandle, - frame: FrameRequester, - models: Vec, - config: std::sync::Arc, - ) { - self.model_names = models - .into_iter() - .map(|model| (model.model, model.display_name)) - .collect(); - self.plan.enabled = config - .features - .enabled(codex_features::Feature::AnalyticsPlanHistory); - self.connection = Some((config, handle, frame)); - self.is_done = false; - self.show_help = false; - self.refresh(); - } - - pub(crate) fn refresh(&mut self) { - self.invalidate_mouse_targets(); - self.end_date = chrono::Utc::now().date_naive(); - self.live = self.connection.as_ref().map(|(config, _, _)| { - std::sync::Arc::new(client::Live::new( - std::sync::Arc::clone(config), - self.end_date, - )) - }); - for section in &mut self.sections.0 { - section.history = Load::Unavailable; - } - self.sections[Section::Chats].detail = None; - self.chats = Load::Unavailable; - self.tasks = Load::Unavailable; - self.profile = Load::Unavailable; - self.plan.report = Load::Unavailable; - self.reports_started = false; - self.token_model = None; - self.account = if let (Some((_, _, frame)), Some(live)) = (&self.connection, &self.live) { - let live = std::sync::Arc::clone(live); - Load::start( - async move { - live.session().await.map(|session| { - Some( - session - .backend - .account() - .plan_type - .unwrap_or(codex_protocol::account::PlanType::Unknown), - ) - }) - }, - frame.clone(), - ) - } else { - Load::Unavailable - }; - self.start_reports(); - } - - /// Abort work when closing or invalidating a retained view; reopening starts fresh requests. - pub(crate) fn cancel_loads(&mut self) { - self.invalidate_mouse_targets(); - for section in &mut self.sections.0 { - section.history = Load::Unavailable; - } - self.chats = Load::Unavailable; - self.tasks = Load::Unavailable; - self.profile = Load::Unavailable; - self.plan.report = Load::Unavailable; - self.account = Load::Unavailable; - self.live = None; - self.connection = None; - } - - fn load_report(&mut self, section: Section) { - let Some(report) = section.report() else { - return; - }; - let group = self.sections[section].group; - let range = self.ranges[self.range_group(section) as usize]; - self.sections[section].history = - if let (Some((_, _, frame)), Some(live)) = (&self.connection, &self.live) { - let live = std::sync::Arc::clone(live); - let days = if range == 0 { 7 } else { 30 }; - let model = self.token_model.clone(); - Load::start( - async move { - if let Some(model) = model - .as_deref() - .filter(|_| report == models::AccountAnalyticsReport::Usage) - { - live.filtered_history(report, days, data::GROUPINGS[group], Some(model)) - .await - } else { - live.history(report, days, data::GROUPINGS[group]).await - } - }, - frame.clone(), - ) - } else { - Load::Unavailable - }; - } - - fn group_options(&self) -> &[usize] { - if self.visible_sections().is_empty() { - return &[]; - } - match self.section { - Section::Summary => &[0, 1, 2], - Section::Plan => &[1, 2, 0, 3], - Section::Usage if self.business() => &[6, 2], - Section::Usage if self.consumer_attribution() => &[1, 2, 0, 3], - Section::Usage => &[0, 2], - Section::Credits => self.live.as_ref().map_or(&[0], |live| live.credit_groups()), - Section::Activity => &[2, 0], - Section::Plugins | Section::Skills | Section::Chats => &[], - } - } - - fn consumer_attribution(&self) -> bool { - !self.business() - && self - .live - .as_ref() - .is_none_or(|live| live.attributed_usage()) - } - - fn model_name<'a>(&'a self, model: &'a str) -> &'a str { - self.model_names - .get(model) - .filter(|name| !name.is_empty()) - .map(String::as_str) - .unwrap_or(model) - } - - fn row_count(&self) -> usize { - if self.section == Section::Chats && !self.business() { - self.tasks - .ready() - .map_or(/*default*/ 0, |chats| chats.rows.len()) - } else if self.section == Section::Chats { - self.chats - .ready() - .map_or(/*default*/ 0, |chats| chats.rows.len()) - } else if self.ranges[self.range_group(self.section) as usize] == 0 { - 7 - } else { - 30 - } - } - - fn handle_key(&mut self, key: KeyEvent) { - if key.kind == KeyEventKind::Release { - return; - } - if key_hint::plain(KeyCode::Char('q')).is_press(key) - || key_hint::ctrl(KeyCode::Char('c')).is_press(key) - { - self.is_done = true; - return; - } - let action = if key_hint::plain(KeyCode::Char(' ')).is_press(key) { - Some(ListAction::Accept) - } else { - self.keymap.action_for(key).or_else(|| { - if !key.modifiers.is_empty() { - return None; - } - // Keep explicit bindings first and honor remapped or unbound arrows. - let code = match key.code { - KeyCode::Char('h') => KeyCode::Left, - KeyCode::Char('l') => KeyCode::Right, - _ => return None, - }; - self.keymap.action_for(KeyEvent { code, ..key }) - }) - }; - - self.follow_selection = matches!( - action, - Some( - ListAction::Accept - | ListAction::Cancel - | ListAction::MoveLeft - | ListAction::MoveRight - | ListAction::MoveUp - | ListAction::MoveDown - | ListAction::JumpTop - | ListAction::JumpBottom - ) - ); - if self.help_shortcut_available() - && (key_hint::plain(KeyCode::Char('?')).is_press(key) - || key_hint::shift(KeyCode::Char('?')).is_press(key)) - { - self.show_help = !self.show_help; - self.help_scroll = 0; - self.follow_selection = false; - return; - } - if self.show_help && action == Some(ListAction::Cancel) { - self.show_help = false; - self.follow_selection = false; - return; - } - if self.show_help { - self.summary_action(action); - return; - } - if key_hint::plain(KeyCode::Char('z')).is_press(key) - && self.control_available(controls::Control::Dashboard) - { - self.activate_control(controls::Control::Dashboard); - return; - } - if !self.zoomed && action == Some(ListAction::Accept) { - self.toggle_dashboard(); - return; - } - if key_hint::plain(KeyCode::Char('R')).is_press(key) { - self.refresh(); - return; - } - if self.control_available(controls::Control::ZeroCreditGroups) - && key_hint::plain(KeyCode::Char('a')).is_press(key) - { - self.activate_control(controls::Control::ZeroCreditGroups); - return; - } - if self.control_available(controls::Control::Model) - && key_hint::plain(KeyCode::Char('m')).is_press(key) - { - self.activate_control(controls::Control::Model); - return; - } - if key_hint::plain(KeyCode::Char('r')).is_press(key) - && self.control_available(controls::Control::Range) - { - self.activate_control(controls::Control::Range); - return; - } - if key_hint::plain(KeyCode::Char('g')).is_press(key) - && self.control_available(controls::Control::Group) - { - self.activate_control(controls::Control::Group); - return; - } - let visible = self.visible_sections(); - if visible.is_empty() { - self.is_done |= action == Some(ListAction::Cancel); - return; - } - let current = visible - .iter() - .position(|section| *section == self.section) - .unwrap_or_default(); - let target = match key.code { - KeyCode::Char(n @ '1'..='7') if key.modifiers.is_empty() => { - visible.get(n as usize - '1' as usize).copied() - } - KeyCode::Tab => Some(visible[(current + 1) % visible.len()]), - KeyCode::BackTab => Some(visible[(current + visible.len() - 1) % visible.len()]), - _ => None, - }; - if let Some(section) = target { - self.select_section(section); - return; - } - if !self.zoomed && action == Some(ListAction::Cancel) { - self.is_done = true; - return; - } - if self.section == Section::Summary { - self.summary_action(action); - return; - } - if self.section == Section::Plan { - self.plan_action(action); - return; - } - if self.control_available(controls::Control::TaskMetric) - && key_hint::plain(KeyCode::Char('s')).is_press(key) - { - self.activate_control(controls::Control::TaskMetric); - return; - } - if matches!( - self.section, - Section::Plugins | Section::Activity | Section::Skills - ) && action == Some(ListAction::Accept) - && !self.day_has_details(self.section, self.sections[self.section].cursor) - { - return; - } - if self.section == Section::Chats - && matches!(action, Some(ListAction::Accept | ListAction::MoveRight)) - && !self.chat_has_details() - { - return; - } - let chart = self.section != Section::Chats; - let count = self.row_count().max(/*other*/ 1); - let mut scroll_offset = self.scroll_offset(); - let SectionState { - cursor, - detail, - follow_selection_on_focus, - .. - } = &mut self.sections[self.section]; - let previous_cursor = *cursor; - match action { - Some(ListAction::MoveUp) => *cursor = cursor.saturating_sub(/*rhs*/ 1), - Some(ListAction::MoveDown) => *cursor = (*cursor + 1).min(count - 1), - Some(ListAction::MoveLeft) if chart => *cursor = cursor.saturating_sub(/*rhs*/ 1), - Some(ListAction::MoveRight) if chart => *cursor = (*cursor + 1).min(count - 1), - Some(ListAction::JumpTop) => *cursor = 0, - Some(ListAction::JumpBottom) => *cursor = count - 1, - Some(ListAction::Accept | ListAction::MoveRight) => { - *detail = if *detail == Some(*cursor) { - None - } else { - Some(*cursor) - }; - } - Some(ListAction::MoveLeft) => *detail = None, - Some(ListAction::Cancel) => { - self.is_done |= detail.take().is_none(); - } - Some(ListAction::PageDown) => { - scroll_offset += self.viewport_height; - self.follow_selection = false; - } - Some(ListAction::PageUp) => { - scroll_offset = scroll_offset.saturating_sub(self.viewport_height); - self.follow_selection = false; - } - None => {} - } - if chart && detail.is_some() { - *detail = Some(*cursor); - } else if !chart && *cursor != previous_cursor { - *detail = None; - } - *follow_selection_on_focus |= !self.zoomed && *cursor != previous_cursor; - *self.scroll_offset_mut() = scroll_offset; - } - - pub(crate) fn handle_event( - &mut self, - tui: &mut tui::Tui, - event: TuiEvent, - ) -> std::io::Result<()> { - match event { - TuiEvent::Key(key) => { - self.handle_key(key); - if self.is_done { - for section in &mut self.sections.0 { - if matches!(section.history, Load::Loading(_)) { - section.history = Load::Unavailable; - } - } - self.chats = Load::Unavailable; - self.tasks = Load::Unavailable; - self.profile = Load::Unavailable; - self.plan.report = Load::Unavailable; - self.account = Load::Unavailable; - self.connection = None; - } - tui.frame_requester().schedule_frame(); - } - TuiEvent::Mouse(mouse) - if matches!( - mouse.kind, - MouseEventKind::Down(MouseButton::Left) - | MouseEventKind::ScrollUp - | MouseEventKind::ScrollDown - ) => - { - self.handle_mouse(mouse); - tui.frame_requester().schedule_frame(); - } - TuiEvent::Draw | TuiEvent::Resume | TuiEvent::Resize(_) | TuiEvent::FocusGained => { - // Rendering follows a selection on resize only when it was visible before - // reflow. Preserve an intentional reading position away from that selection. - tui.draw(u16::MAX, |frame| self.render(frame.area(), frame.buffer))?; - } - _ => {} - } - Ok(()) - } -} diff --git a/codex-rs/tui/src/analytics/account_layout_tests.rs b/codex-rs/tui/src/analytics/account_layout_tests.rs deleted file mode 100644 index aec8e865..00000000 --- a/codex-rs/tui/src/analytics/account_layout_tests.rs +++ /dev/null @@ -1,477 +0,0 @@ -//! Account layouts, authenticated report loading, independent ranges, and model filters. -use super::*; -use codex_config::types::KeybindingSpec; -use codex_config::types::KeybindingsSpec; -use codex_config::types::TuiKeymap; -use pretty_assertions::assert_eq; - -use crate::analytics::sections::Section; -#[test] -fn account_layouts_show_reports_and_wrap_navigation() { - for (kind, expected) in [ - ( - models::AccountKind::Consumer, - vec![ - Section::Summary, - Section::Usage, - Section::Activity, - Section::Plugins, - Section::Skills, - Section::Chats, - ], - ), - ( - models::AccountKind::Enterprise, - vec![ - Section::Summary, - Section::Credits, - Section::Usage, - Section::Plugins, - Section::Skills, - Section::Chats, - ], - ), - ] { - let mut view = fixture::view(kind); - for (index, section) in expected.iter().enumerate() { - press( - &mut view, - KeyCode::Char(char::from_digit(index as u32 + 1, /*radix*/ 10).unwrap()), - ); - assert_eq!(view.section, *section); - } - press(&mut view, KeyCode::Tab); - assert_eq!(view.section, expected[0]); - press(&mut view, KeyCode::BackTab); - assert_eq!(view.section, *expected.last().unwrap()); - } -} - -#[tokio::test] -async fn changing_ranges_and_grouping_preserves_other_reports_and_focus() { - let server = test_support::server().await; - let (_home, _app_server, mut view) = client::tests::connected_view(&server, "plus").await; - test_support::settle(&mut view).await; - view.section = Section::Usage; - press(&mut view, KeyCode::Left); - press(&mut view, KeyCode::Enter); - press(&mut view, KeyCode::Char('r')); - test_support::settle(&mut view).await; - press(&mut view, KeyCode::Char('g')); - test_support::settle(&mut view).await; - assert_eq!( - ( - view.ranges, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections[Section::Usage].detail, - view.sections[Section::Usage].group - ), - ([1, 0, 0], [28, 6, 6, 0, 6, 6, 6, 6], Some(28), 2) - ); - let context = ( - view.ranges, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections.0.each_ref().map(|state| state.detail), - view.sections.0.each_ref().map(|state| state.group), - ); - screen(&mut view, /*width*/ 58, /*height*/ 25); - assert_eq!( - ( - view.ranges, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections.0.each_ref().map(|state| state.detail), - view.sections.0.each_ref().map(|state| state.group) - ), - context - ); - press(&mut view, KeyCode::Char('3')); - press(&mut view, KeyCode::Char('r')); - test_support::settle(&mut view).await; - assert_eq!(view.ranges, [1, 1, 0]); - assert_eq!( - view.sections - .0 - .each_ref() - .map(|state| state.history.ready().map(|history| history.data.len())), - [Some(30), Some(7), None, None, Some(30), Some(7), None, None] - ); - let server = test_support::server().await; - let (_business_home, _business_server, mut view) = - client::tests::connected_view(&server, "business").await; - test_support::settle(&mut view).await; - view.ranges = [1, 1, 0]; - view.load_report(Section::Usage); - press(&mut view, KeyCode::Char('2')); - press(&mut view, KeyCode::Char('r')); - test_support::settle(&mut view).await; - assert_eq!(view.ranges, [0, 1, 0]); - assert_eq!( - view.sections - .0 - .each_ref() - .map(|state| state.history.ready().map(|history| history.data.len())), - [Some(30), Some(7), Some(7), None, None, Some(7), None, None] - ); -} - -#[tokio::test] -async fn business_tokens_filter_models() { - let server = test_support::server().await; - let (_home, _app_server, mut view) = client::tests::connected_view(&server, "business").await; - test_support::settle(&mut view).await; - view.end_date = fixture::END_DATE; - fixture::seed_reports(&mut view); - press(&mut view, KeyCode::Char('3')); - let all = screen(&mut view, /*width*/ 100, /*height*/ 30); - assert!(all.contains("All models") && all.contains("Cached input")); - press(&mut view, KeyCode::Char('m')); - test_support::settle(&mut view).await; - assert_eq!( - view.sections[Section::Usage] - .history - .ready() - .unwrap() - .data - .iter() - .map(|day| day.total) - .sum::(), - 420.0 - ); - fixture::seed_reports(&mut view); - assert_eq!(view.token_model.as_deref(), Some("GPT-5.5")); - screen(&mut view, /*width*/ 100, /*height*/ 30); - let (_, target) = view - .control_hits - .iter() - .find(|(control, _)| *control == crate::analytics::controls::Control::Model) - .unwrap(); - view.handle_mouse(crossterm::event::MouseEvent { - kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left), - column: target.x, - row: target.y, - modifiers: KeyModifiers::NONE, - }); - test_support::settle(&mut view).await; - fixture::seed_reports(&mut view); - assert_eq!(view.token_model, None); -} - -#[tokio::test] -async fn account_pending_and_error_do_not_start_reports() { - let mut view = AnalyticsView::new(RuntimeKeymap::defaults().list); - let (send, receive) = tokio::sync::oneshot::channel(); - view.account = Load::start( - async move { receive.await.unwrap() }, - FrameRequester::test_dummy(), - ); - screen(&mut view, /*width*/ 80, /*height*/ 24); - assert!( - view.sections - .0 - .iter() - .all(|state| matches!(state.history, Load::Unavailable)) - ); - send.send(Err("Sign in again to view Analytics.".to_string())) - .unwrap(); - tokio::task::yield_now().await; - let error = screen(&mut view, /*width*/ 80, /*height*/ 24); - assert!(error.contains("Sign in again")); - assert!( - view.sections - .0 - .iter() - .all(|state| matches!(state.history, Load::Unavailable)) - ); -} - -#[tokio::test] -async fn account_reports_request_only_eligible_endpoints_and_refresh() { - for (plan, usage, activity) in [ - ( - "plus", - "usage/daily-token-usage-breakdown", - "analytics/daily-workspace-usage-counts", - ), - ( - "business", - "usage/daily-workspace-user-token-usage-breakdown", - "usage/daily-workspace-user-credit-usage", - ), - ] { - let server = test_support::server().await; - wiremock::Mock::given(wiremock::matchers::method("GET")) - .and(wiremock::matchers::path("/backend-api/wham/profiles/me")) - .respond_with( - wiremock::ResponseTemplate::new(/*s*/ 200) - .set_body_json(serde_json::json!({"stats":{}})), - ) - .mount(&server) - .await; - let (_home, _app_server, mut view) = client::tests::connected_view(&server, plan).await; - test_support::settle(&mut view).await; - let mut expected = [ - "accounts/check", - usage, - activity, - "analytics/daily-plugin-usage-metrics", - "analytics/daily-skill-usage-metrics", - "profiles/me", - ] - .map(|endpoint| format!("/backend-api/wham/{endpoint}")); - expected.sort(); - let mut paths = server - .received_requests() - .await - .unwrap() - .into_iter() - .filter(|request| request.url.path().starts_with("/backend-api/wham/")) - .map(|request| request.url.path().to_string()) - .collect::>(); - paths.sort(); - assert_eq!(paths, expected); - let ready = view - .sections - .0 - .each_ref() - .map(|state| state.history.ready().is_some()); - assert_eq!( - ready, - if plan == "plus" { - [true, true, false, false, true, true, false, false] - } else { - [true, true, true, false, false, true, false, false] - } - ); - press(&mut view, KeyCode::Char('R')); - test_support::settle(&mut view).await; - assert_eq!( - view.sections - .0 - .each_ref() - .map(|state| state.history.ready().is_some()), - ready - ); - assert_eq!( - server - .received_requests() - .await - .unwrap() - .iter() - .filter(|request| request.url.path().starts_with("/backend-api/wham/")) - .count(), - 12 - ); - view.cancel_loads(); - } -} - -#[tokio::test] -async fn grouping_cycle_uses_current_server_capabilities() { - let server = test_support::server().await; - let (_home, _app_server, mut view) = client::tests::connected_view(&server, "plus").await; - view.section = Section::Usage; - view.account = Load::Ready(codex_protocol::account::PlanType::Plus); - view.sections[Section::Usage].group = 3; - view.start_reports(); - test_support::settle(&mut view).await; - assert_eq!( - (view.group_options(), view.sections[Section::Usage].group), - (&[0, 2][..], 0) - ); - press(&mut view, KeyCode::Char('g')); - assert_eq!(view.sections[Section::Usage].group, 2); - press(&mut view, KeyCode::Char('g')); - assert_eq!(view.sections[Section::Usage].group, 0); -} - -#[test] -fn ungrouped_sections_preserve_configured_g_jump_top() { - let mut config = TuiKeymap::default(); - config.list.jump_top = Some(KeybindingsSpec::One(KeybindingSpec("g".into()))); - let keymap = RuntimeKeymap::from_config(&config).expect("valid list keymap"); - let mut view = fixture::view(models::AccountKind::Enterprise); - view.keymap = keymap.list; - for section in [ - Section::Chats, - Section::Plugins, - Section::Skills, - Section::Credits, - ] { - view.section = section; - press(&mut view, KeyCode::End); - assert!(view.sections[section].cursor > 0, "{section:?}"); - press(&mut view, KeyCode::Char('g')); - assert_eq!(view.sections[section].cursor, 0, "{section:?}"); - } -} - -#[test] -fn business_chats_display_only_supplied_dollars() { - let mut view = fixture::view(models::AccountKind::Enterprise); - let chats = match &mut view.chats { - Load::Ready(chats) => chats, - _ => panic!("fixture chats"), - }; - for chat in &mut chats.rows { - if let Some(usage) = &mut chat.usage { - usage.estimated_usage_usd_micros = None; - } - } - press(&mut view, KeyCode::Char('6')); - assert!(!screen(&mut view, /*width*/ 100, /*height*/ 30).contains("Est. $ spent")); - if let Load::Ready(chats) = &mut view.chats { - chats.rows[0] - .usage - .as_mut() - .unwrap() - .estimated_usage_usd_micros = Some(123_450_000); - } - let dollars = screen(&mut view, /*width*/ 100, /*height*/ 30); - assert!(dollars.contains("$123.45") && dollars.contains("Est. $ spent")); - assert!(screen(&mut view, /*width*/ 42, /*height*/ 30).contains("$123.45")); -} - -#[tokio::test] -async fn unsupported_workspace_plans_hide_top_chats_and_skip_loading() { - for plan in [ - "team", - "self_serve_business_prolite", - "self_serve_business_usage_based", - "enterprise", - "ent26", - "edu", - "edu_plus", - "edu_pro", - ] { - let server = test_support::server().await; - let (_home, _app_server, mut view) = client::tests::connected_view(&server, plan).await; - test_support::settle(&mut view).await; - assert_eq!( - view.visible_sections(), - &[ - Section::Summary, - Section::Credits, - Section::Usage, - Section::Plugins, - Section::Skills - ], - "{plan}" - ); - assert!(matches!(view.chats, Load::Unavailable), "{plan}"); - let selected = view.section; - press(&mut view, KeyCode::Char('6')); - assert_eq!(view.section, selected); - } - for plan in [ - "business", - "enterprise_cbp_usage_based", - "enterprise_cbp_automation", - ] { - let server = test_support::server().await; - let (_home, _app_server, mut view) = client::tests::connected_view(&server, plan).await; - test_support::settle(&mut view).await; - assert!(view.visible_sections().contains(&Section::Chats), "{plan}"); - press(&mut view, KeyCode::Char('6')); - assert_eq!(view.section, Section::Chats); - } -} - -#[tokio::test] -async fn unknown_plan_keeps_summary_available_without_billing_reports() { - let server = test_support::server().await; - wiremock::Mock::given(wiremock::matchers::method("GET")) - .and(wiremock::matchers::path("/backend-api/wham/profiles/me")) - .respond_with( - wiremock::ResponseTemplate::new(/*s*/ 200) - .set_body_json(serde_json::json!({"stats":{"lifetime_tokens":12345}})), - ) - .expect(/*r*/ 1) - .mount(&server) - .await; - let (_home, _app_server, mut view) = - client::tests::connected_view(&server, "future-plan").await; - test_support::settle(&mut view).await; - assert_eq!(view.visible_sections(), &[Section::Summary]); - assert_eq!( - view.profile.ready().unwrap().stats.tokens.lifetime_tokens, - Some(12345) - ); - assert!( - view.sections - .0 - .iter() - .all(|section| matches!(section.history, Load::Unavailable)) - ); - let paths = server - .received_requests() - .await - .unwrap() - .into_iter() - .filter(|request| request.url.path().starts_with("/backend-api/wham/")) - .map(|request| request.url.path().to_owned()) - .collect::>(); - assert_eq!( - paths, - [ - "/backend-api/wham/accounts/check", - "/backend-api/wham/profiles/me" - ] - ); -} - -#[test] -fn navigation_keeps_its_row_when_sections_change() { - for width in [64, 120] { - let mut view = fixture::view(models::AccountKind::Consumer); - let mut positions = Vec::new(); - for section in [ - Section::Summary, - Section::Usage, - Section::Chats, - Section::Summary, - ] { - view.section = section; - let rendered = screen(&mut view, width, /*height*/ 40); - positions.push( - rendered - .lines() - .position(|line| line.contains("Overview") && line.contains("Usage")) - .unwrap(), - ); - } - assert_eq!(positions, vec![positions[0]; 4]); - } -} - -#[test] -fn taller_report_reveals_more_legend_rows_and_keeps_timestamp_in_controls() { - let mut view = fixture::view(models::AccountKind::Consumer); - view.section = Section::Usage; - let mut history = fixture::history(/*report*/ 0, /*range*/ 0, /*group*/ 1); - history.updated_at = Some(1_788_364_800); - for day in &mut history.data { - day.values = (0..10) - .map(|index| models::AccountAnalyticsValue { - key: format!("feature-{index}"), - label: format!("Feature {}", index + 1), - value: day.total / 10.0, - }) - .collect(); - } - view.sections[Section::Usage].history = data::Load::Ready(history); - let short = screen(&mut view, /*width*/ 120, /*height*/ 30); - let tall = screen(&mut view, /*width*/ 120, /*height*/ 60); - assert!( - tall.lines().filter(|line| line.contains('●')).count() - > short.lines().filter(|line| line.contains('●')).count() - ); - assert!( - tall.lines() - .take(usize::from(view.body_area.y)) - .any(|line| line.contains("Updated")) - ); - for width in [24, 40, 64] { - let narrow = screen(&mut view, width, /*height*/ 60); - assert!(narrow.lines().nth(/*n*/ 3).unwrap().contains("7d/30d")); - } -} diff --git a/codex-rs/tui/src/analytics/account_plan_tests.rs b/codex-rs/tui/src/analytics/account_plan_tests.rs deleted file mode 100644 index 8795e2e9..00000000 --- a/codex-rs/tui/src/analytics/account_plan_tests.rs +++ /dev/null @@ -1,167 +0,0 @@ -//! Server plan discovery survives stale token claims and remains bound to the local identity. - -use super::tests::live; -use super::tests::sign_in; -use super::*; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -#[tokio::test] -async fn refresh_uses_server_plan_and_routes_with_unchanged_local_credentials() { - let server = MockServer::start().await; - let (_home, client) = live(&server, "plus").await; - let reads = Arc::new(AtomicUsize::new(/*v*/ 0)); - let plan_reads = Arc::clone(&reads); - Mock::given(method("GET")) - .and(path("/backend-api/wham/accounts/check")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(move |_: &wiremock::Request| { - let plan = if plan_reads.fetch_add(/*val*/ 1, Ordering::SeqCst) == 0 { - "team" - } else { - "enterprise" - }; - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "accounts": [ - {"id": "other-account", "plan_type": "free"}, - {"id": "account-a", "plan_type": plan} - ], - "account_ordering": ["other-account", "account-a"] - })) - }) - .with_priority(/*p*/ 1) - .expect(/*r*/ 2) - .mount(&server) - .await; - for endpoint in [ - "/backend-api/wham/usage/daily-workspace-user-token-usage-breakdown", - "/backend-api/wham/usage/daily-workspace-user-credit-usage", - ] { - Mock::given(method("GET")) - .and(path(endpoint)) - .and(header("chatgpt-account-id", "account-a")) - .respond_with( - ResponseTemplate::new(/*s*/ 200) - .set_body_json(json!({"breakdown": "product", "series": [], "data": []})), - ) - .expect(/*r*/ 1) - .mount(&server) - .await; - } - let first = client - .history(Report::Credits, /*days*/ 7, Grouping::Surface) - .await - .unwrap(); - assert_eq!(client.session().await.unwrap().kind, AccountKind::Business); - assert_eq!( - client - .history(Report::Credits, /*days*/ 7, Grouping::Surface) - .await - .unwrap(), - first - ); - assert_eq!(reads.load(Ordering::SeqCst), 1); - let refreshed = Live::new(Arc::clone(&client.config), client.end_date); - refreshed - .history(Report::Credits, /*days*/ 7, Grouping::Surface) - .await - .unwrap(); - assert_eq!( - refreshed.session().await.unwrap().kind, - AccountKind::Enterprise - ); - server.verify().await; -} - -#[tokio::test] -async fn account_plan_lookup_recovers_from_unauthorized() { - let server = MockServer::start().await; - let (_home, client) = live(&server, "plus").await; - let reads = AtomicUsize::new(/*v*/ 0); - Mock::given(method("GET")) - .and(path("/backend-api/wham/accounts/check")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(move |_: &wiremock::Request| { - if reads.fetch_add(/*val*/ 1, Ordering::SeqCst) == 0 { - ResponseTemplate::new(/*s*/ 401) - } else { - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "accounts": {"account-a": {"account": { - "account_id": "account-a", "plan_type": "enterprise" - }}}, - "account_ordering": ["account-a"] - })) - } - }) - .with_priority(/*p*/ 1) - .expect(/*r*/ 2) - .mount(&server) - .await; - assert_eq!( - client.session().await.unwrap().kind, - AccountKind::Enterprise - ); - server.verify().await; -} - -#[tokio::test] -async fn failed_plan_discovery_can_retry_without_using_token_plan() { - for response in [ - ResponseTemplate::new(/*s*/ 503), - ResponseTemplate::new(/*s*/ 200).set_body_string("invalid account response"), - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"accounts": [{"id": "account-a"}]})), - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "accounts": [{"id": "other-account", "plan_type": "enterprise"}] - })), - ] { - let server = MockServer::start().await; - let (_home, client) = live(&server, "plus").await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/accounts/check")) - .respond_with(response) - .with_priority(/*p*/ 1) - .expect(/*r*/ 1) - .up_to_n_times(/*n*/ 1) - .mount(&server) - .await; - assert_eq!( - client.session().await.err().unwrap(), - "Couldn't load account plan. Press R to retry Analytics." - ); - assert_eq!(client.session().await.unwrap().kind, AccountKind::Consumer); - server.verify().await; - } -} - -#[tokio::test] -async fn account_plan_lookup_rejects_account_and_user_switches() { - for (account, user) in [("account-b", "user-a"), ("account-a", "user-b")] { - let server = MockServer::start().await; - let (home, client) = live(&server, "plus").await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/accounts/check")) - .respond_with(move |_: &wiremock::Request| { - sign_in(home.path(), account, user, "plus"); - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "accounts": [{"id": "account-a", "plan_type": "enterprise"}] - })) - }) - .with_priority(/*p*/ 1) - .expect(/*r*/ 1) - .mount(&server) - .await; - assert_eq!( - client.session().await.err().unwrap(), - "Account changed. Press R to refresh Analytics." - ); - server.verify().await; - } -} diff --git a/codex-rs/tui/src/analytics/activity_chart.rs b/codex-rs/tui/src/analytics/activity_chart.rs deleted file mode 100644 index 8bfb704b..00000000 --- a/codex-rs/tui/src/analytics/activity_chart.rs +++ /dev/null @@ -1,319 +0,0 @@ -//! Calendar and weekly token charts for the account Summary. Bucketing is independent of view state. - -mod palette; - -use std::collections::BTreeMap; - -use chrono::Datelike; -use chrono::Duration; -use chrono::NaiveDate; -use ratatui::style::Style; -use ratatui::style::Stylize; -use ratatui::text::Line; -use ratatui::text::Span; - -use crate::render::highlight::foreground_style_for_scopes; -use palette::TokenActivityPalette; - -const WEEK_COUNT: usize = 52; -const DAY_COUNT: usize = 7; -const CELL_COUNT: usize = WEEK_COUNT * DAY_COUNT; -const CHART_LEFT_WIDTH: usize = 4; - -/// Selects the aggregation represented by the token activity chart. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum TokenActivityView { - Daily, - Weekly, - Cumulative, -} - -impl TokenActivityView { - /// Parses the optional `/usage` argument into a supported chart view. - /// - /// An empty argument selects Daily when a mode is requested. The bare `/usage` - /// command opens its menu. Returning `None` lets the slash-command dispatcher - /// report unsupported arguments instead of silently choosing a view. - pub(crate) fn parse(value: &str) -> Option { - match value.trim().to_ascii_lowercase().as_str() { - "" | "day" | "daily" => Some(Self::Daily), - "week" | "weekly" => Some(Self::Weekly), - "cumulative" => Some(Self::Cumulative), - _ => None, - } - } - - pub(crate) fn label(self) -> &'static str { - match self { - Self::Daily => "Daily", - Self::Weekly => "Weekly", - Self::Cumulative => "Cumulative", - } - } -} - -pub(super) fn chart_lines( - view: TokenActivityView, - buckets: &[codex_backend_client::TokenUsageProfileDailyBucket], - today: NaiveDate, - width: u16, -) -> Vec> { - let mut lines = Vec::new(); - let values = daily_values(buckets, today); - let shown_columns = shown_columns(width); - if shown_columns == 0 { - lines.push(" Widen terminal to show activity graph".dim().into()); - return lines; - } - - let palette = TokenActivityPalette::current(); - let levels = levels_for_view(&values, view); - let first_column = WEEK_COUNT - shown_columns; - lines.push(month_labels(today, first_column, shown_columns)); - for row in 0..DAY_COUNT { - let mut spans = vec![weekday_label(view, row)]; - for column in first_column..WEEK_COUNT { - if column > first_column { - spans.push(" ".into()); - } - let index = column * DAY_COUNT + row; - if view == TokenActivityView::Daily - && cell_date(today, index).is_some_and(|date| date > today) - { - spans.push(" ".into()); - } else { - let style = if view == TokenActivityView::Daily { - palette.for_level(levels[index]) - } else { - palette.for_bar_level(levels[index]) - }; - spans.push(Span::styled(palette.glyph(view, levels[index]), style)); - } - } - lines.push(spans.into()); - } - // Separate the calendar from the legend/footer below. - lines.push(Line::default()); - match view { - TokenActivityView::Daily => lines.push(legend_line(&palette)), - TokenActivityView::Weekly | TokenActivityView::Cumulative => { - lines.push(bar_caption(view, &values)) - } - } - lines -} - -fn shown_columns(width: u16) -> usize { - (usize::from(width) - .saturating_sub(CHART_LEFT_WIDTH) - .saturating_add(/*rhs*/ 1) - / 2) - .min(WEEK_COUNT) -} - -fn numeric_style() -> Style { - foreground_style_for_scopes(&["constant.numeric", "constant"]) - .unwrap_or_else(|| Style::default().green()) -} - -fn label_style() -> Style { - foreground_style_for_scopes(&["comment"]).unwrap_or_else(|| Style::default().dim()) -} - -fn weekday_label(view: TokenActivityView, row: usize) -> Span<'static> { - if view != TokenActivityView::Daily { - // Bar views fill from the bottom (row 6) upward, so the gutter doubles - // as a coarse Y-axis: peak at the top, baseline at the bottom. - return Span::styled( - match row { - 0 => "max ", - 6 => " 0 ", - _ => " ", - }, - label_style(), - ); - } - Span::styled( - match row { - 0 => " Su ", - 1 => " Mo ", - 2 => " Tu ", - 3 => " We ", - 4 => " Th ", - 5 => " Fr ", - 6 => " Sa ", - _ => " ", - }, - label_style(), - ) -} - -fn legend_line(palette: &TokenActivityPalette) -> Line<'static> { - let mut spans = vec![Span::styled(" Less ", label_style())]; - for level in 0..=4 { - if level > 0 { - spans.push(" ".into()); - } - spans.push(Span::styled( - palette.glyph(TokenActivityView::Daily, level), - palette.for_level(level), - )); - } - spans.push(Span::styled(" More", label_style())); - spans.into() -} - -/// Caption for the bar-chart views, where the 5-step daily legend would be -/// misleading. States what each bar represents and the peak it is scaled to. -fn bar_caption(view: TokenActivityView, values: &[i64]) -> Line<'static> { - let weeks = weekly_totals(values); - let (lead, peak) = match view { - TokenActivityView::Weekly => ( - "Each column = 1 week · tallest ", - weeks.iter().copied().max().unwrap_or(/*default*/ 0), - ), - TokenActivityView::Cumulative => ( - "Running total · top ", - weeks - .iter() - .fold(/*init*/ 0_i64, |sum, value| sum.saturating_add(*value)), - ), - TokenActivityView::Daily => ("", 0), - }; - if peak <= 0 { - return Span::styled(" No token activity in the last 12 months", label_style()).into(); - } - vec![ - Span::styled(format!(" {lead}"), label_style()), - Span::styled(super::data::compact_amount(peak as f64), numeric_style()), - ] - .into() -} - -fn month_labels(today: NaiveDate, first_column: usize, shown_columns: usize) -> Line<'static> { - let mut cells = vec![' '; shown_columns * 2 - 1]; - let start = chart_start(today); - let mut last_end = 0; - for column in first_column..WEEK_COUNT { - let date = start + Duration::days((column * DAY_COUNT) as i64); - if date.day() > 7 { - continue; - } - let label = date.format("%b").to_string(); - let offset = (column - first_column) * 2; - if offset < last_end || offset + label.len() > cells.len() { - continue; - } - for (index, ch) in label.chars().enumerate() { - cells[offset + index] = ch; - } - last_end = offset + label.len() + 1; - } - vec![ - " ".into(), - Span::styled(cells.into_iter().collect::(), label_style()), - ] - .into() -} - -/// Normalizes backend daily buckets into the fixed 52-week display window. -/// -/// The returned vector is ordered by chart cell, starting with the oldest Sunday. -/// Invalid, out-of-window, and future dates are ignored. Duplicate dates are -/// accumulated and negative token values do not reduce activity. -fn daily_values( - buckets: &[codex_backend_client::TokenUsageProfileDailyBucket], - today: NaiveDate, -) -> Vec { - let start = chart_start(today); - let end = start + Duration::days(CELL_COUNT as i64); - let mut by_date = BTreeMap::new(); - for bucket in buckets { - let Ok(date) = NaiveDate::parse_from_str(&bucket.start_date, "%Y-%m-%d") else { - continue; - }; - if date < start || date >= end || date > today { - continue; - } - let value: &mut i64 = by_date.entry(date).or_insert(/*default*/ 0); - *value = value.saturating_add(bucket.tokens.max(/*other*/ 0)); - } - (0..CELL_COUNT) - .map(|offset| { - by_date - .get(&(start + Duration::days(offset as i64))) - .copied() - .unwrap_or(/*default*/ 0) - }) - .collect() -} - -fn levels_for_view(values: &[i64], view: TokenActivityView) -> Vec { - match view { - TokenActivityView::Daily => graded_levels(values), - TokenActivityView::Weekly => bar_levels(&weekly_totals(values)), - TokenActivityView::Cumulative => { - let cumulative = weekly_totals(values) - .into_iter() - .scan(/*initial_state*/ 0, |sum, value| { - *sum = i64::saturating_add(*sum, value); - Some(*sum) - }) - .collect::>(); - bar_levels(&cumulative) - } - } -} - -fn graded_levels(values: &[i64]) -> Vec { - let max = values.iter().copied().max().unwrap_or(/*default*/ 0); - values - .iter() - .map(|value| match (*value, max) { - (0, _) | (_, 0) => 0, - (value, max) if i128::from(value) * 4 > i128::from(max) * 3 => 4, - (value, max) if i128::from(value) * 2 > i128::from(max) => 3, - (value, max) if i128::from(value) * 4 > i128::from(max) => 2, - _ => 1, - }) - .collect() -} - -fn weekly_totals(values: &[i64]) -> Vec { - values - .chunks(DAY_COUNT) - .map(|week| { - week.iter() - .fold(/*init*/ 0_i64, |sum, value| sum.saturating_add(*value)) - }) - .collect() -} - -fn bar_levels(totals: &[i64]) -> Vec { - let max = totals.iter().copied().max().unwrap_or(/*default*/ 0); - totals - .iter() - .flat_map(|value| { - let height = if *value <= 0 || max <= 0 { - 0 - } else { - ((i128::from(*value) * DAY_COUNT as i128 + i128::from(max) - 1) / i128::from(max)) - as usize - }; - (0..DAY_COUNT).map(move |row| if DAY_COUNT - row <= height { 4 } else { 0 }) - }) - .collect() -} - -fn chart_start(today: NaiveDate) -> NaiveDate { - let week_start = today - Duration::days(i64::from(today.weekday().num_days_from_sunday())); - week_start - Duration::weeks((WEEK_COUNT - 1) as i64) -} - -fn cell_date(today: NaiveDate, index: usize) -> Option { - chart_start(today).checked_add_signed(Duration::days(index as i64)) -} - -#[cfg(test)] -#[path = "activity_chart_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/activity_chart/palette.rs b/codex-rs/tui/src/analytics/activity_chart/palette.rs deleted file mode 100644 index 5ac415d5..00000000 --- a/codex-rs/tui/src/analytics/activity_chart/palette.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! Builds terminal-aware styles and glyph choices for token activity charts. -//! -//! The palette adapts theme colors to the active terminal color level while -//! keeping chart-specific glyph policy local to the token activity renderer. - -use ratatui::style::Color; -use ratatui::style::Style; - -use super::TokenActivityView; -use crate::color::blend; -use crate::render::highlight::foreground_style_for_scopes; -use crate::style::accent_style; -use crate::terminal_palette::StdoutColorLevel; -use crate::terminal_palette::best_color_for_level; -use crate::terminal_palette::default_bg; -use crate::terminal_palette::default_fg; -use crate::terminal_palette::effective_stdout_color_level; - -// In low-color terminals we distinguish empty vs active cells by glyph (a -// width-matched filled/hollow pair). In truecolor terminals the grid uses a -// single glyph and lets color carry the intensity (GitHub-style), which keeps -// the grid perfectly aligned and free of texture noise. -const EMPTY_CELL_GLYPH: &str = "□"; -const ACTIVE_CELL_GLYPH: &str = "■"; -const BAR_CELL_GLYPH: &str = "█"; - -/// Stores the terminal-specific styles and glyph strategy for token activity cells. -pub(super) struct TokenActivityPalette { - styles: [Style; 5], - bar_style: Style, - /// True when the terminal supports a truecolor gradient, so the grid can - /// encode intensity purely by color and render every cell with a single - /// glyph. False on low-color terminals, where we fall back to a - /// filled/hollow glyph pair so empty and active cells stay distinguishable. - uses_color: bool, -} - -impl TokenActivityPalette { - pub(super) fn current() -> Self { - Self::from_parts( - default_fg(), - default_bg(), - effective_stdout_color_level(), - theme_activity_style(), - ) - } - - fn from_parts( - default_fg: Option<(u8, u8, u8)>, - default_bg: Option<(u8, u8, u8)>, - color_level: StdoutColorLevel, - active_style: Style, - ) -> Self { - let fallback_palette = || Self::fallback(active_style); - let (Some(fg), Some(bg), Some(anchor)) = - (default_fg, default_bg, activity_anchor_rgb(active_style)) - else { - return fallback_palette(); - }; - if matches!( - color_level, - StdoutColorLevel::Ansi16 | StdoutColorLevel::Unknown - ) { - return fallback_palette(); - } - - let empty_alpha = if crate::color::is_light(bg) { - 0.18 - } else { - 0.14 - }; - let alphas = [empty_alpha, 0.22, 0.42, 0.68, 1.00]; - let styles = std::array::from_fn(|index| { - let color = if index == 0 { - blend(fg, bg, alphas[index]) - } else { - blend(anchor, bg, alphas[index]) - }; - Style::default().fg(best_color_for_level(color, color_level)) - }); - let bar_style = Style::default().fg(best_color_for_level( - blend(anchor, bg, /*alpha*/ 0.78), - color_level, - )); - Self { - styles, - bar_style, - uses_color: true, - } - } - - fn fallback(active_style: Style) -> Self { - let empty_style = Style::default().dim(); - Self { - styles: [ - empty_style, - active_style, - active_style, - active_style, - active_style, - ], - bar_style: active_style, - uses_color: false, - } - } - - pub(super) fn for_level(&self, level: usize) -> Style { - self.styles[level.min(/*other*/ 4)] - } - - pub(super) fn for_bar_level(&self, level: usize) -> Style { - if level == 0 { - self.for_level(/*level*/ 0) - } else { - self.bar_style - } - } - - /// The glyph for a cell at `level`. Daily truecolor renders every visible - /// cell with the same square glyph and lets color carry the intensity; in - /// low-color we use the hollow glyph for empty cells so they remain visible - /// without a color gradient. Bar views use full blocks for filled height and - /// spaces for empty height so the silhouette reads as a column chart. - pub(super) fn glyph(&self, view: TokenActivityView, level: usize) -> &'static str { - if view != TokenActivityView::Daily { - return if level == 0 { " " } else { BAR_CELL_GLYPH }; - } - if self.uses_color || level > 0 { - ACTIVE_CELL_GLYPH - } else { - EMPTY_CELL_GLYPH - } - } -} - -fn theme_activity_style() -> Style { - foreground_style_for_scopes(&["entity.name.type", "support.type", "variable"]) - .unwrap_or_else(accent_style) - .bold() -} - -fn activity_anchor_rgb(style: Style) -> Option<(u8, u8, u8)> { - match style.fg? { - Color::Rgb(r, g, b) => Some((r, g, b)), - _ => None, - } -} - -#[cfg(test)] -#[path = "palette_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/activity_chart/palette_tests.rs b/codex-rs/tui/src/analytics/activity_chart/palette_tests.rs deleted file mode 100644 index e46bd0ad..00000000 --- a/codex-rs/tui/src/analytics/activity_chart/palette_tests.rs +++ /dev/null @@ -1,143 +0,0 @@ -use super::*; -use crate::terminal_palette::rgb_color; -use pretty_assertions::assert_eq; -use ratatui::style::Modifier; - -#[test] -fn current_palette_uses_effective_terminal_color_level() { - let theme = - crate::render::highlight::resolve_theme_by_name("ada", /*codex_home*/ None).unwrap(); - crate::render::highlight::set_syntax_theme(theme); - crate::terminal_palette::with_test_default_colors( - crate::terminal_probe::DefaultColors { - fg: (240, 240, 240), - bg: (0, 0, 0), - }, - || { - let palette = TokenActivityPalette::current(); - assert!(palette.uses_color); - let legend = (0..5) - .map(|level| { - format!( - "{} {:?}", - palette.glyph(TokenActivityView::Daily, level), - palette.for_level(level).fg, - ) - }) - .collect::>() - .join("\n"); - insta::assert_snapshot!(legend); - }, - ); -} - -#[test] -fn truecolor_palette_blends_theme_accent_against_dark_background() { - let default_fg = Some((240, 240, 240)); - let default_bg = Some((0, 0, 0)); - let active_style = Style::default().fg(rgb_color((100, 200, 50))).bold(); - let palette = TokenActivityPalette::from_parts( - default_fg, - default_bg, - StdoutColorLevel::TrueColor, - active_style, - ); - - assert_eq!( - palette.for_level(/*level*/ 0).fg, - Some(rgb_color((33, 33, 33))) - ); - assert_eq!( - palette.for_level(/*level*/ 1).fg, - Some(rgb_color((22, 44, 11))) - ); - assert_eq!( - palette.for_level(/*level*/ 4).fg, - Some(rgb_color((100, 200, 50))) - ); - assert_eq!( - palette.for_bar_level(/*level*/ 4).fg, - Some(rgb_color((78, 156, 39))) - ); - assert!(palette.uses_color); -} - -#[test] -fn truecolor_palette_blends_empty_cell_for_light_background() { - let default_fg = Some((0, 0, 0)); - let default_bg = Some((255, 255, 255)); - let active_style = Style::default().fg(rgb_color((0, 95, 135))).bold(); - let palette = TokenActivityPalette::from_parts( - default_fg, - default_bg, - StdoutColorLevel::TrueColor, - active_style, - ); - - assert_eq!( - palette.for_level(/*level*/ 0).fg, - Some(rgb_color((209, 209, 209))) - ); - assert_eq!( - palette.for_level(/*level*/ 4).fg, - Some(rgb_color((0, 95, 135))) - ); - assert!(palette.uses_color); -} - -#[test] -fn ansi16_palette_uses_theme_accent_without_green_fallback() { - let default_fg = Some((240, 240, 240)); - let default_bg = Some((0, 0, 0)); - let active_style = Style::default().fg(Color::Magenta).bold(); - let palette = TokenActivityPalette::from_parts( - default_fg, - default_bg, - StdoutColorLevel::Ansi16, - active_style, - ); - - assert_eq!(palette.for_level(/*level*/ 0), Style::default().dim()); - assert_eq!(palette.for_level(/*level*/ 1), active_style); - assert_eq!(palette.for_bar_level(/*level*/ 4), active_style); - assert!(!palette.uses_color); -} - -#[test] -fn non_rgb_theme_accent_remains_active_fallback() { - let default_fg = Some((240, 240, 240)); - let default_bg = Some((0, 0, 0)); - let active_style = Style::default().fg(Color::Cyan).bold(); - let palette = TokenActivityPalette::from_parts( - default_fg, - default_bg, - StdoutColorLevel::TrueColor, - active_style, - ); - - assert_eq!(palette.for_level(/*level*/ 1), active_style); - assert!( - palette - .for_level(/*level*/ 1) - .add_modifier - .contains(Modifier::BOLD) - ); - assert!(!palette.uses_color); -} - -#[test] -fn missing_terminal_colors_use_theme_accent_fallback() { - let default_fg = None; - let default_bg = Some((0, 0, 0)); - let active_style = Style::default().fg(Color::Blue).bold(); - let palette = TokenActivityPalette::from_parts( - default_fg, - default_bg, - StdoutColorLevel::TrueColor, - active_style, - ); - - assert_eq!(palette.for_level(/*level*/ 0), Style::default().dim()); - assert_eq!(palette.for_level(/*level*/ 4), active_style); - assert!(!palette.uses_color); -} diff --git a/codex-rs/tui/src/analytics/activity_chart/snapshots/codex_tui__analytics__activity_chart__palette__tests__current_palette_uses_effective_terminal_color_level.snap b/codex-rs/tui/src/analytics/activity_chart/snapshots/codex_tui__analytics__activity_chart__palette__tests__current_palette_uses_effective_terminal_color_level.snap deleted file mode 100644 index bd5ed35e..00000000 --- a/codex-rs/tui/src/analytics/activity_chart/snapshots/codex_tui__analytics__activity_chart__palette__tests__current_palette_uses_effective_terminal_color_level.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: tui/src/analytics/activity_chart/palette_tests.rs -assertion_line: 29 -expression: legend ---- -■ Some(Rgb(33, 33, 33)) -■ Some(Rgb(20, 47, 56)) -■ Some(Rgb(39, 90, 107)) -■ Some(Rgb(64, 146, 173)) -■ Some(Rgb(95, 215, 255)) diff --git a/codex-rs/tui/src/analytics/activity_chart_tests.rs b/codex-rs/tui/src/analytics/activity_chart_tests.rs deleted file mode 100644 index 35faaa7c..00000000 --- a/codex-rs/tui/src/analytics/activity_chart_tests.rs +++ /dev/null @@ -1,239 +0,0 @@ -//! Calendar, aggregation, and chart rendering regressions. -use super::*; -use codex_backend_client::TokenUsageProfileDailyBucket as AccountTokenUsageDailyBucket; -use insta::assert_snapshot; -use pretty_assertions::assert_eq; - -fn graph_width(width: u16) -> u16 { - if width == u16::MAX { - return width; - } - (CHART_LEFT_WIDTH + shown_columns(width) * 2 - 1) as u16 -} - -#[test] -fn duplicate_dates_sum_and_negative_values_clamp() { - let today = - NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date"); - let buckets = vec![ - AccountTokenUsageDailyBucket { - start_date: "2026-05-29".to_string(), - tokens: 10, - }, - AccountTokenUsageDailyBucket { - start_date: "2026-05-29".to_string(), - tokens: 5, - }, - AccountTokenUsageDailyBucket { - start_date: "2026-05-28".to_string(), - tokens: -4, - }, - ]; - - let values = daily_values(&buckets, today); - - assert_eq!(values.iter().sum::(), 15); -} - -#[test] -fn bar_levels_fill_from_bottom() { - let levels = bar_levels(&[0, 10]); - - assert_eq!(&levels[..DAY_COUNT], &[0; DAY_COUNT]); - assert_eq!(&levels[DAY_COUNT..], &[4; DAY_COUNT]); -} - -#[test] -fn token_activity_view_aliases_parse() { - assert_eq!(TokenActivityView::parse(""), Some(TokenActivityView::Daily)); - assert_eq!( - TokenActivityView::parse("day"), - Some(TokenActivityView::Daily) - ); - assert_eq!( - TokenActivityView::parse("week"), - Some(TokenActivityView::Weekly) - ); - assert_eq!( - TokenActivityView::parse("cumulative"), - Some(TokenActivityView::Cumulative) - ); - assert_eq!(TokenActivityView::parse("year"), None); -} - -#[test] -fn daily_graph_snapshot_uses_distinct_empty_and_active_cells() { - let today = - NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date"); - let buckets = vec![ - AccountTokenUsageDailyBucket { - start_date: "2026-05-25".to_string(), - tokens: 1, - }, - AccountTokenUsageDailyBucket { - start_date: "2026-05-29".to_string(), - tokens: 4, - }, - ]; - - let rendered = chart_lines(TokenActivityView::Daily, &buckets, today, /*width*/ 22) - .into_iter() - .map(|line| line.to_string().trim_end().to_string()) - .collect::>() - .join("\n"); - - assert_snapshot!(rendered, @r" - Apr May - Su □ □ □ □ □ □ □ □ □ - Mo □ □ □ □ □ □ □ □ ■ - Tu □ □ □ □ □ □ □ □ □ - We □ □ □ □ □ □ □ □ □ - Th □ □ □ □ □ □ □ □ □ - Fr □ □ □ □ □ □ □ □ ■ - Sa □ □ □ □ □ □ □ □ - - Less □ ■ ■ ■ ■ More - "); -} - -#[test] -fn daily_graph_snapshot_stays_left_aligned_in_wide_terminal() { - assert_eq!(graph_width(/*width*/ 160), 107); - assert_eq!(graph_width(/*width*/ u16::MAX), u16::MAX); - - let today = - NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date"); - let lines = chart_lines(TokenActivityView::Daily, &[], today, /*width*/ 160); - let rendered = [&lines[0], &lines[1], lines.last().expect("legend line")] - .into_iter() - .map(|line| line.to_string().trim_end().to_string()) - .collect::>() - .join("\n"); - - assert_snapshot!(rendered, @" - Jun Jul Aug Sep Oct Nov Dec Jan Feb Mar Apr May - Su □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ - Less □ ■ ■ ■ ■ More - "); -} - -#[test] -fn weekly_graph_snapshot_renders_bar_chart_and_caption() { - let today = - NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date"); - let buckets = vec![ - AccountTokenUsageDailyBucket { - start_date: "2026-05-11".to_string(), - tokens: 3, - }, - AccountTokenUsageDailyBucket { - start_date: "2026-05-18".to_string(), - tokens: 6, - }, - AccountTokenUsageDailyBucket { - start_date: "2026-05-25".to_string(), - tokens: 9, - }, - ]; - - let rendered = chart_lines( - TokenActivityView::Weekly, - &buckets, - today, - /*width*/ 22, - ) - .into_iter() - .map(|line| line.to_string().trim_end().to_string()) - .collect::>() - .join("\n"); - - assert_snapshot!(rendered, @" - Apr May - max █ - █ - █ █ - █ █ - █ █ █ - █ █ █ - 0 █ █ █ - - Each column = 1 week · tallest 9 - "); -} - -#[test] -fn cumulative_graph_snapshot_renders_running_total_bar_chart_and_caption() { - let today = - NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date"); - let buckets = vec![ - AccountTokenUsageDailyBucket { - start_date: "2026-05-11".to_string(), - tokens: 3, - }, - AccountTokenUsageDailyBucket { - start_date: "2026-05-18".to_string(), - tokens: 6, - }, - AccountTokenUsageDailyBucket { - start_date: "2026-05-25".to_string(), - tokens: 9, - }, - ]; - - let rendered = chart_lines( - TokenActivityView::Cumulative, - &buckets, - today, - /*width*/ 22, - ) - .into_iter() - .map(|line| line.to_string().trim_end().to_string()) - .collect::>() - .join("\n"); - - assert_snapshot!(rendered, @" - Apr May - max █ - █ - █ - █ █ - █ █ - █ █ █ - 0 █ █ █ - - Running total · top 18 - "); -} - -#[test] -fn year_window_ignores_other_dates_and_saturates_extreme_totals() { - let today: NaiveDate = "2026-09-09".parse().unwrap(); - let buckets = [ - ("2025-01-01", 100), - ("2026-09-10", 100), - ("invalid", 100), - ("2026-09-08", i64::MAX), - ("2026-09-08", i64::MAX), - ("2026-09-09", i64::MAX), - ] - .map(|(date, tokens)| AccountTokenUsageDailyBucket { - start_date: date.into(), - tokens, - }); - let values = daily_values(&buckets, today); - let mut expected = vec![0; CELL_COUNT]; - let index = (today - chart_start(today)).num_days() as usize; - expected[index - 1] = i64::MAX; - expected[index] = i64::MAX; - assert_eq!(values, expected); - for view in [ - TokenActivityView::Daily, - TokenActivityView::Weekly, - TokenActivityView::Cumulative, - ] { - let levels = levels_for_view(&values, view); - assert!(levels.iter().all(|level| *level <= 4)); - assert!(levels.contains(&4)); - assert!(!chart_lines(view, &buckets, today, /*width*/ 110).is_empty()); - } -} diff --git a/codex-rs/tui/src/analytics/chart.rs b/codex-rs/tui/src/analytics/chart.rs deleted file mode 100644 index b4ffd4f2..00000000 --- a/codex-rs/tui/src/analytics/chart.rs +++ /dev/null @@ -1,353 +0,0 @@ -//! Daily history with a stable chart and a compact, separated breakdown table. -//! Chart series rank by the full range; table rows rank by the selected day and retain series colors. -//! Wide focused reports place their breakdown beside the plot; narrow reports stack it. -//! Missing and zero days retain the same row count; only viewport changes and explicit expansion change height. - -use super::AnalyticsView; -use super::data; -use super::plot; -use super::render::categories; -use super::render::columns; -use super::styles::number; -use super::styles::secondary_style; -use super::styles::series_colors; -use crate::analytics::models::AccountAnalyticsUnit; -use crate::analytics::models::AccountAnalyticsValue; -use crate::analytics::sections::Section; -use crate::line_truncation::truncate_line_with_ellipsis_if_overflow; -use ratatui::style::Styled; -use ratatui::style::Stylize; -use ratatui::text::Line; - -impl AnalyticsView { - pub(super) fn day_has_details(&self, section: Section, day_index: usize) -> bool { - let Some(history) = self.sections[section].history.ready() else { - return false; - }; - let date = self - .section_date_range(section) - .start() - .iter_days() - .nth(day_index); - history.data.iter().any(|day| { - date.is_some_and(|date| day.date == date) - && day.values.iter().any(|value| value.value != 0.0) - }) - } - - pub(super) fn history_lines( - &self, - section: Section, - width: usize, - height: usize, - ) -> plot::Chart { - let state = &self.sections[section].history; - let Some(history) = state.ready() else { - return plot::Chart { - lines: state - .message() - .into_iter() - .map(|message| message.to_string().set_style(secondary_style()).into()) - .collect(), - bands: 0, - }; - }; - if history.data.is_empty() { - return plot::Chart { - lines: vec![ - "No data reported for this range." - .set_style(secondary_style()) - .into(), - ], - bands: 0, - }; - } - let range = self.section_date_range(section); - // At most 30 daily slots; index by date if report ranges grow. - let days = range - .start() - .iter_days() - .take_while(|date| date <= range.end()) - .map(|date| { - let day = history.data.iter().find(|day| day.date == date); - (date, day) - }) - .collect::>(); - let cursor = self.sections[section].cursor.min(days.len() - 1); - let selected_date = days[cursor].0.format("%b %-d").to_string(); - let day = days[cursor].1; - let expanded = self.zoomed && self.sections[section].detail.is_some(); - let colors = series_colors(); - let mut categories = categories(history); - if matches!(section, Section::Plugins | Section::Skills) { - for category in &mut categories { - category.label = super::tool_panel::tool_name(&category.label); - } - } - if self.sections[section].group == 2 { - for category in &mut categories { - category.label = self.model_name(&category.label).to_string(); - } - } - let unit = match section { - Section::Usage if history.unit == AccountAnalyticsUnit::Tokens => "tokens", - Section::Summary => "tokens", - Section::Activity => "messages", - Section::Plugins => "calls", - Section::Skills => "uses", - Section::Usage | Section::Credits | Section::Chats | Section::Plan => "credits", - }; - let empty_breakdown = matches!( - section, - Section::Plugins | Section::Activity | Section::Skills - ) && day.is_none_or(|day| { - day.total == 0.0 && day.values.iter().all(|value| value.value == 0.0) - }); - let relative = history.unit == AccountAnalyticsUnit::RelativeUsage; - let format_amount = if history.unit == AccountAnalyticsUnit::Credits { - data::credit_amount - } else { - data::amount - }; - let total: f64 = history.data.iter().map(|day| day.total).sum(); - let formatted_total = if total.abs() >= 1_000.0 { - data::compact_amount(total) - } else { - format_amount(total) - }; - let mut lines = vec![if relative { - "Total usage · relative units" - .set_style(secondary_style()) - .into() - } else { - number(format!( - "{} {}{unit}", - formatted_total, - if section == Section::Activity { - "reported " - } else { - "" - } - )) - .into() - }]; - if section == Section::Usage && !self.business() && self.zoomed { - lines.push( - "Approximate · may be delayed up to 6 hours" - .set_style(secondary_style()) - .into(), - ); - } - if self.sections[section].group == 3 { - lines.push( - "All usage by how each turn started" - .set_style(secondary_style()) - .into(), - ); - } - let has_activity = history - .data - .iter() - .any(|day| day.total != 0.0 || day.values.iter().any(|value| value.value != 0.0)); - let side_by_side = self.zoomed && width >= 140 && height > 0; - let plot_width = if side_by_side { width - 48 } else { width }; - let mut bands = 0; - if has_activity && height > 0 { - let chart = plot::chart(&days, &categories, cursor, plot_width, height, history.unit); - bands = chart.bands; - lines.extend(chart.lines); - } else if !has_activity { - lines.push( - if matches!( - section, - Section::Plugins | Section::Activity | Section::Skills - ) { - format!("No {unit} reported in this range.") - .set_style(secondary_style()) - .into() - } else { - "No activity reported in this range." - .set_style(secondary_style()) - .into() - }, - ); - } - - let chart_end = lines.len(); - let table_width = if side_by_side { - 44 - } else { - width.min(/*other*/ 56) - }; - lines.push(Line::default()); - if self.zoomed { - lines.push("─".repeat(table_width).dim().into()); - } - let table_start = lines.len(); - let summary = match day { - None => " · Not reported".set_style(secondary_style()), - Some(day) if day.total == 0.0 && day.values.iter().all(|value| value.value == 0.0) => { - " · No activity (0)".set_style(secondary_style()) - } - Some(day) if relative => number(format!(" · {} usage units", data::amount(day.total))), - Some(day) => number(format!( - " · {} {unit}", - if expanded { - day.total.to_string() - } else { - format_amount(day.total) - } - )), - }; - lines.push(truncate_line_with_ellipsis_if_overflow( - vec![selected_date.clone().bold(), summary].into(), - table_width, - )); - if self.zoomed { - lines.push(columns( - match section { - Section::Plugins => "Plugin", - Section::Skills => "Skill", - Section::Chats => "Chat", - Section::Summary - | Section::Usage - | Section::Credits - | Section::Activity - | Section::Plan => self.group_label(section, self.sections[section].group), - } - .bold() - .into(), - if history.unit == AccountAnalyticsUnit::Tokens { - "Tokens" - } else if section == Section::Usage { - "Share" - } else if section == Section::Activity { - "Messages" - } else if section == Section::Plugins { - "Calls" - } else if section == Section::Skills { - "Uses" - } else { - "Credits" - } - .bold() - .into(), - table_width, - )); - } - let mut values = categories - .iter() - .enumerate() - .map(|(index, category)| { - ( - index, - AccountAnalyticsValue { - value: day - .and_then(|day| { - day.values.iter().find(|value| value.key == category.key) - }) - .map_or(/*default*/ 0.0, |value| value.value), - ..category.clone() - }, - ) - }) - .collect::>(); - values.sort_by(|(_, a), (_, b)| b.value.abs().total_cmp(&a.value.abs())); - let row_budget = if self.zoomed { - (self.viewport_height / 4).max(/*other*/ 4) - } else { - 4 - }; - let remainder = if !expanded && values.len() > row_budget { - let remaining = values.split_off(row_budget - 1); - Some(( - format!("{} more", remaining.len()), - remaining.iter().map(|(_, value)| value.value).sum::(), - )) - } else { - None - }; - let rows = values - .iter() - .map(|(index, value)| { - ( - Line::from(vec![ - "● ".fg(colors[(*index).min(/*other*/ 3)]), - value.label.clone().into(), - ]), - value.value, - ) - }) - .chain( - remainder.map(|(label, value)| (Line::from(vec!["… ".dim(), label.dim()]), value)), - ); - for (label, value) in rows.take(if self.zoomed { usize::MAX } else { 2 }) { - let amount = match day { - None => "—".into(), - Some(day) - if section == Section::Usage - && history.unit != AccountAnalyticsUnit::Tokens => - { - format!( - "{:.1}%", - if day.total == 0.0 { - 0.0 - } else { - value / day.total * 100.0 - } - ) - } - Some(_) if expanded => value.to_string(), - Some(_) => format_amount(value), - }; - lines.push(columns( - truncate_line_with_ellipsis_if_overflow( - label, - table_width.saturating_sub(amount.len() + 2), - ), - if day.is_none() || value == 0.0 { - amount.dim() - } else { - amount.into() - } - .into(), - table_width, - )); - } - if empty_breakdown { - // Preserve the measured table allocation when the selected day has no breakdown. - let table_end = lines.len(); - lines.truncate(table_start); - lines.push(truncate_line_with_ellipsis_if_overflow( - if day.is_none() { - format!("Data not reported for {selected_date}.") - } else { - format!("No {unit} reported for {selected_date}.") - } - .set_style(secondary_style()) - .into(), - table_width, - )); - lines.resize(table_end, Line::default()); - } - if !self.zoomed - && let Some(updated) = history - .updated_at - .and_then(|value| chrono::DateTime::from_timestamp(value, /*nsecs*/ 0)) - { - lines.push( - format!( - "Updated {} UTC", - updated.format(self.clock_format.date_time_format()) - ) - .set_style(secondary_style()) - .into(), - ); - } - if side_by_side { - let table = lines.split_off(chart_end); - lines = super::render::join_columns(&lines, &table[1..], plot_width); - } - plot::Chart { lines, bands } - } -} diff --git a/codex-rs/tui/src/analytics/chat_panel.rs b/codex-rs/tui/src/analytics/chat_panel.rs deleted file mode 100644 index 133ff6b5..00000000 --- a/codex-rs/tui/src/analytics/chat_panel.rs +++ /dev/null @@ -1,325 +0,0 @@ -//! Bounded chat tables with inline credit breakdowns and a viewport-sized row window. -//! Zero-credit groups are optional; missing dimensions and signed adjustments stay distinct. - -use super::AnalyticsView; -use super::data; -use super::render::columns; -use super::styles::number; -use super::styles::secondary_style; -use crate::analytics::sections::Section; -use crate::line_truncation::truncate_line_with_ellipsis_if_overflow; -use crate::style::accent_style; -use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_lines; -use ratatui::style::Styled; -use ratatui::style::Stylize; -use ratatui::text::Line; -use std::ops::Range; - -impl AnalyticsView { - pub(super) fn chat_lines(&self, width: usize) -> (Vec>, Range) { - let row_width = width.clamp(/*min*/ 1, /*max*/ 97); - let width = row_width.saturating_sub(/*rhs*/ 1).max(/*other*/ 1); - let wrap = |lines: Vec>| word_wrap_lines(lines, RtOptions::new(width)); - let mut lines = wrap(vec![ - "Active in past 30 days · sorted by lifetime credits" - .set_style(secondary_style()) - .into(), - ]); - if let Some(message) = self.chats.message() { - lines.extend(wrap(vec![ - message.to_string().set_style(secondary_style()).into(), - ])); - } - let Some(chats) = self.chats.ready() else { - return (lines, 0..1); - }; - if chats.rows.is_empty() { - lines.extend(wrap(vec![ - "No recent local chats.".set_style(secondary_style()).into(), - ])); - return (lines, 0..1); - } - let missing = chats.rows.iter().filter(|row| row.usage.is_none()).count(); - if missing > 0 { - lines.extend(wrap(vec![ - format!( - "{missing} chat estimate{} unavailable", - if missing == 1 { "" } else { "s" } - ) - .set_style(secondary_style()) - .into(), - ])); - } - lines.push(Line::default()); - let show_usd = chats.rows.iter().any(|chat| { - chat.usage - .as_ref() - .is_some_and(|usage| usage.estimated_usage_usd_micros.is_some()) - }); - let stacked_amounts = show_usd && width < 70; - lines.extend(wrap(vec![columns( - " Chat".bold().into(), - if stacked_amounts { - "Est. $ / credits" - } else if show_usd { - "Est. $ spent Lifetime credits" - } else { - "Lifetime credits" - } - .bold() - .into(), - width, - )])); - let rows = chats - .rows - .iter() - .enumerate() - .map(|(index, chat)| { - let selected = - self.section == Section::Chats && index == self.sections[Section::Chats].cursor; - let amount = chat.usage.as_ref().map_or_else( - || "—".into(), - |usage| data::credits(usage.estimated_usage_credits_micros), - ); - let amount = if show_usd { - let usd = chat - .usage - .as_ref() - .and_then(|usage| usage.estimated_usage_usd_micros) - .map(|micros| format!("${:.2}", micros as f64 / 1_000_000.0)) - .unwrap_or_else(|| "—".into()); - format!("{usd:>12} {amount:>16}") - } else { - amount - }; - let label = format!( - "{} {}", - if selected { "›" } else { " " }, - chat.display_title() - ); - let label: Line<'static> = if selected { - label.set_style(accent_style()).into() - } else { - label.into() - }; - let label_width = if stacked_amounts { - width - } else { - width.saturating_sub(amount.len() + 1) - }; - let truncated = label.width() > label_width; - let mut row = if stacked_amounts { - vec![ - truncate_line_with_ellipsis_if_overflow(label, label_width), - format!(" {}", amount.trim()).into(), - ] - } else { - vec![columns( - truncate_line_with_ellipsis_if_overflow(label, label_width), - if chat.usage.is_none() { - amount.set_style(secondary_style()).into() - } else if selected { - number(amount).into() - } else { - amount.into() - }, - width, - )] - }; - let header_len = row.len(); - if self.sections[Section::Chats].detail == Some(index) - && let Some(usage) = &chat.usage - { - row.push( - format!(" {}", "─".repeat(width.saturating_sub(/*rhs*/ 2))) - .dim() - .into(), - ); - if truncated { - row.extend(word_wrap_lines( - [chat.display_title().to_string().bold()], - RtOptions::new(width) - .initial_indent(" ".into()) - .subsequent_indent(" ".into()), - )); - } - let zeros = usage - .groups - .iter() - .filter(|group| group.estimated_usage_credits_micros == 0) - .count(); - let mut groups = usage - .groups - .iter() - .filter(|group| { - self.show_zero_credit_groups - || group.estimated_usage_credits_micros != 0 - }) - .collect::>(); - groups.sort_by_key(|group| { - std::cmp::Reverse(group.estimated_usage_credits_micros) - }); - // On narrow terminals, retain every dimension on a second line. - let table = width >= 70; - if !groups.is_empty() { - row.push(columns( - if table { - format!( - " {: width { - row.push(label); - " ".into() - } else { - label - } - }; - row.push(columns(label, amount.into(), width)); - if !table { - row.push( - format!(" {effort} · {speed}") - .set_style(secondary_style()) - .into(), - ); - } - } - if usage.groups.is_empty() { - row.push( - " Breakdown unavailable" - .set_style(secondary_style()) - .into(), - ); - } - if zeros > 0 { - row.push( - format!( - " {zeros} zero-credit {}{} · a {}", - if zeros == 1 { "group" } else { "groups" }, - if self.show_zero_credit_groups { - "" - } else { - " hidden" - }, - if self.show_zero_credit_groups { - "hide zeros" - } else { - "show all" - }, - ) - .set_style(secondary_style()) - .into(), - ); - } - row.push(Line::default()); - } - let details = row.split_off(header_len); - let mut row = wrap(row); - // Wrap first: wrapping trims the highlighted trailing blank otherwise. - if selected { - for line in &mut row { - super::styles::select_row(line, row_width); - } - } - row.extend(wrap(details)); - row - }) - .collect::>(); - let coverage = wrap(vec![ - "Local chats · excludes archived chats and subagent usage" - .set_style(secondary_style()) - .into(), - ]); - self.chat_window(lines, rows, coverage, width) - } - - pub(super) fn chat_window( - &self, - mut lines: Vec>, - rows: Vec>>, - coverage: Vec>, - width: usize, - ) -> (Vec>, Range) { - let wrap = |lines: Vec>| word_wrap_lines(lines, RtOptions::new(width)); - let count = rows.len(); - let range_height = wrap(vec![ - format!("Showing {count}–{count} of {count} chats").into(), - ]) - .len(); - // Measure wrapped details before choosing neighbors so the range describes the rendered rows. - let budget = self - .viewport_height - .saturating_sub(lines.len() + coverage.len() + range_height + 2); - let row_limit = count; - let cursor = self.sections[Section::Chats].cursor.min(count - 1); - let mut first = cursor; - let mut end = cursor + 1; - let mut used = rows[cursor].len(); - while first > 0 && end - first < row_limit && used + rows[first - 1].len() <= budget { - first -= 1; - used += rows[first].len(); - } - while end < count && end - first < row_limit && used + rows[end].len() <= budget { - used += rows[end].len(); - end += 1; - } - let mut selection = 0..1; - for (index, row) in rows.into_iter().enumerate().take(end).skip(first) { - if index == cursor { - selection = lines.len()..lines.len() + row.len(); - } - lines.extend(row); - } - lines.push(Line::default()); - lines.extend(wrap(vec![ - format!("Showing {}–{end} of {count} chats", first + 1) - .set_style(secondary_style()) - .into(), - ])); - lines.extend(coverage); - (lines, selection) - } -} diff --git a/codex-rs/tui/src/analytics/chat_panel_tests.rs b/codex-rs/tui/src/analytics/chat_panel_tests.rs deleted file mode 100644 index ff50868b..00000000 --- a/codex-rs/tui/src/analytics/chat_panel_tests.rs +++ /dev/null @@ -1,212 +0,0 @@ -//! Chat list coverage, responsive expansion, and controls for fixed-period data. - -use super::*; -use pretty_assertions::assert_eq; - -#[test] -fn chats_range_controls_and_visible_rows() { - let mut view = fixture::view(models::AccountKind::Enterprise); - let mut chats = fixture::chats(); - let usage = chats.rows[0].usage.clone(); - chats.rows = (1..=30) - .map(|index| chats::Chat { - title: format!("Chat {index:02}"), - usage: usage.clone(), - }) - .collect(); - view.chats = Load::Ready(chats); - press(&mut view, KeyCode::Char('6')); - let before = ( - view.ranges, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections.0.each_ref().map(|state| state.detail), - ); - press(&mut view, KeyCode::Char('r')); - assert_eq!( - ( - view.ranges, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections.0.each_ref().map(|state| state.detail) - ), - before - ); - for key in [KeyCode::Home, KeyCode::End, KeyCode::Enter] { - press(&mut view, key); - let output = screen(&mut view, /*width*/ 110, /*height*/ 24); - assert!(!output.contains("7d") && !output.contains("r 7/30d")); - let visible = (1..=30) - .filter(|index| output.contains(&format!("Chat {index:02}"))) - .collect::>(); - assert!(output.contains(&format!( - "Showing {}–{} of 30 chats", - visible.first().unwrap(), - visible.last().unwrap() - ))); - } - press(&mut view, KeyCode::Char('r')); - assert_eq!(view.ranges, [0; 3]); - press(&mut view, KeyCode::Char('2')); - press(&mut view, KeyCode::Char('r')); - assert_eq!(view.ranges[view.range_group(Section::Credits) as usize], 1); - assert!(screen(&mut view, /*width*/ 110, /*height*/ 24).contains("r 7d/30d")); -} - -#[test] -fn chats_breakdown_ranks_nonzero_groups_and_reflows() { - let mut view = fixture::view(models::AccountKind::Enterprise); - let mut chats = fixture::chats(); - let usage = chats.rows[0].usage.as_mut().unwrap(); - let seed = usage.groups[0].clone(); - usage.groups = [ - ("Zero model", 0), - ("Small model", 215_610_920), - ("Top model", 19_134_430_635), - ("Refund model", -4), - ] - .map( - |(model, credits)| codex_backend_client::ThreadUsageBreakdownGroup { - model: Some(model.into()), - speed: (credits != 19_134_430_635).then(|| "standard".into()), - estimated_usage_credits_micros: credits, - ..seed.clone() - }, - ) - .to_vec(); - usage.estimated_usage_credits_micros = usage - .groups - .iter() - .map(|group| group.estimated_usage_credits_micros) - .sum(); - view.chats = Load::Ready(chats); - press(&mut view, KeyCode::Char('6')); - press(&mut view, KeyCode::Enter); - let mut screens = Vec::new(); - for width in [110, 58] { - view.follow_selection = true; - let output = screen(&mut view, width, /*height*/ 32); - assert!(output.find("Top model").unwrap() < output.find("Small model").unwrap()); - assert!(output.find("Small model").unwrap() < output.find("Refund model").unwrap()); - assert!(!output.contains("Zero model")); - assert!(output.contains("-0.000004") && output.contains("Not reported")); - assert!(output.contains("19,350.04") && output.contains("19,134.43")); - assert!(output.contains("1 zero-credit group hidden · a show all")); - assert!(output.contains("Refactor billing usage")); - screens.push(output); - } - press(&mut view, KeyCode::Char('a')); - let expanded = screen(&mut view, /*width*/ 110, /*height*/ 32); - assert!(expanded.contains("Zero model") && expanded.contains("a hide zeros")); - screens.push(expanded); - press(&mut view, KeyCode::Char('a')); - assert!(!view.show_zero_credit_groups); - let wide = view.chat_lines(/*width*/ 220).0; - // The content stays within 96 columns, plus one highlighted trailing blank. - assert!(wide.iter().all(|line| line.width() <= 97)); - insta::assert_snapshot!(screens.join("\n")); -} - -#[test] -fn chats_long_title_keeps_detail_indent_and_counts_missing_estimates() { - let mut view = fixture::view(models::AccountKind::Enterprise); - let mut chats = fixture::chats(); - chats.rows[0].title = "Create a comprehensive list of areas to investigate across the runtime and describe how each area affects performance in a long conversation".into(); - chats.rows[1].usage = None; - chats.rows[2].usage = None; - view.chats = Load::Ready(chats); - press(&mut view, KeyCode::Char('6')); - press(&mut view, KeyCode::Enter); - let output = screen(&mut view, /*width*/ 110, /*height*/ 30); - assert!(output.contains("2 chat estimates unavailable")); - insta::assert_snapshot!(output); -} - -#[tokio::test] -async fn unavailable_chats_do_not_open_invisible_details() { - for key in [KeyCode::Enter, KeyCode::Right] { - for state in 0..5 { - let mut view = fixture::view(models::AccountKind::Enterprise); - view.section = Section::Chats; - view.chats = match state { - 0 => Load::Unavailable, - 1 => Load::Error("Temporary failure".into()), - 2 => Load::Ready(chats::Chats::default()), - 3 => Load::Ready(chats::Chats { - rows: vec![chats::Chat { - title: "Another workspace's private title".into(), - usage: None, - }], - }), - _ => Load::start(std::future::pending(), FrameRequester::test_dummy()), - }; - press(&mut view, key); - assert_eq!(view.sections[Section::Chats].detail, None); - press(&mut view, KeyCode::Esc); - assert!(view.is_done); - } - } -} - -#[test] -fn unavailable_chat_titles_are_hidden_in_panel_and_overview() { - let mut view = fixture::view(models::AccountKind::Enterprise); - view.section = Section::Chats; - view.chats = Load::Ready(chats::Chats { - rows: vec![chats::Chat { - title: "Another workspace's private title".into(), - usage: None, - }], - }); - - view.follow_selection = true; - let output = screen(&mut view, /*width*/ 110, /*height*/ 28); - assert!(!output.contains("Another workspace's private title")); - assert!(output.contains("Chat usage unavailable")); -} - -#[test] -fn moving_chat_selection_collapses_details_before_they_leave_the_viewport() { - for (start, key) in [ - (0, KeyCode::Down), - (1, KeyCode::Up), - (0, KeyCode::End), - (2, KeyCode::Home), - ] { - let mut view = fixture::view(models::AccountKind::Enterprise); - view.section = Section::Chats; - view.sections[Section::Chats].cursor = start; - press(&mut view, KeyCode::Enter); - assert_eq!(view.sections[Section::Chats].detail, Some(start)); - press(&mut view, key); - assert_eq!(view.sections[Section::Chats].detail, None); - press(&mut view, KeyCode::Esc); - assert!(view.is_done); - } -} - -#[test] -fn chat_help_and_zero_credit_action_follow_account_and_detail_state() { - for kind in [models::AccountKind::Consumer, models::AccountKind::Business] { - let mut view = fixture::view(kind); - fixture::seed_reports(&mut view); - view.section = Section::Chats; - view.sections[Section::Chats].detail = Some(0); - let help = view - .help_lines(/*width*/ 100) - .iter() - .map(ToString::to_string) - .collect::>() - .join("\n"); - let business = kind == models::AccountKind::Business; - assert_eq!(help.contains("a · show zero-credit"), business); - assert_eq!(help.contains("s · change chat sort metric"), !business); - press(&mut view, KeyCode::Char('a')); - assert_eq!(view.show_zero_credit_groups, business); - view.sections[Section::Chats].detail = None; - assert!( - !view - .help_lines(/*width*/ 100) - .iter() - .any(|line| line.to_string().contains("a · show zero-credit")) - ); - } -} diff --git a/codex-rs/tui/src/analytics/chats.rs b/codex-rs/tui/src/analytics/chats.rs deleted file mode 100644 index f9dd8c68..00000000 --- a/codex-rs/tui/src/analytics/chats.rs +++ /dev/null @@ -1,200 +0,0 @@ -//! Discover recent local roots and load business chat credit estimates. - -use super::client::Live; -use super::client::Session; -use super::data; -use codex_app_server_client::AppServerRequestHandle; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SortDirection; -use codex_app_server_protocol::ThreadListParams; -use codex_app_server_protocol::ThreadListResponse; -use codex_app_server_protocol::ThreadSortKey; -use codex_backend_client::ThreadUsage; -use std::collections::HashMap; -use std::collections::HashSet; -use std::sync::Arc; - -pub(super) struct Chat { - pub title: String, - pub usage: Option, -} - -impl Chat { - /// Local history can span accounts; expose titles only with a returned account estimate. - pub(super) fn display_title(&self) -> &str { - if self.usage.is_some() { - &self.title - } else { - "Chat usage unavailable" - } - } -} - -#[derive(Default)] -pub(super) struct Chats { - pub rows: Vec, -} - -pub(super) async fn read( - handle: AppServerRequestHandle, - live: Arc, -) -> Result, String> { - let session = live.session().await?; - if !super::models::thread_usage_supported(session.backend.account().plan_type) { - return Ok(None); - } - 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()); - live.ensure_identity().await?; - let threads = threads??; - if threads.is_empty() { - return Ok(Some(Chats { rows: Vec::new() })); - } - let ids = threads - .iter() - .map(|thread| thread.id.as_str()) - .collect::>(); - // Repairing local history has its own budget; it must not consume estimate time. - let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(/*secs*/ 25); - let mut data = Vec::new(); - for pair in ids.chunks(/*chunk_size*/ 200) { - let midpoint = pair.len().min(/*other*/ 100); - let (first, second) = tokio::join!( - 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?); - } - if tokio::time::Instant::now() >= deadline { - break; - } - } - live.ensure_identity().await?; - let mut usage: HashMap<_, _> = data - .into_iter() - .map(|row| (row.thread_id.clone(), row)) - .collect(); - let mut rows = threads - .into_iter() - .map(|thread| Chat { - usage: usage.remove(&thread.id), - title: thread - .name - .filter(|name| !name.trim().is_empty()) - .unwrap_or_else(|| { - if thread.preview.trim().is_empty() { - "Untitled chat".into() - } else { - thread.preview - } - }), - }) - .collect::>(); - rows.sort_by_key(|row| { - std::cmp::Reverse( - row.usage - .as_ref() - .map(|usage| usage.estimated_usage_credits_micros), - ) - }); - Ok(Some(Chats { rows })) -} - -/// Recent local roots are shared by consumer task and business credit reporting. -pub(super) async fn roots( - handle: &AppServerRequestHandle, -) -> Result, String> { - let cutoff = chrono::Utc::now().timestamp() - 30 * 24 * 60 * 60; - let mut threads = Vec::new(); - let mut cursor = None; - let mut seen_cursors = HashSet::new(); - loop { - let page: ThreadListResponse = handle - .request_typed(ClientRequest::ThreadList { - request_id: RequestId::String(uuid::Uuid::new_v4().to_string()), - params: ThreadListParams { - cursor, - ..list_params() - }, - }) - .await - .map_err(data::error)?; - let reached_cutoff = page.data.iter().any(|thread| thread.updated_at < cutoff); - threads.extend(page.data.into_iter().filter(|thread| { - thread.updated_at >= cutoff && !thread.ephemeral && thread.parent_thread_id.is_none() - })); - match page.next_cursor { - Some(next) if !seen_cursors.insert(next.clone()) => { - return Err("Chat listing repeated a cursor. Press R to retry.".into()); - } - Some(next) if !reached_cutoff => cursor = Some(next), - _ => break, - } - } - // Keep repeated rows from overlapping pages out of the backend's distinct-ID batches. - let mut seen_ids = HashSet::new(); - threads.retain(|thread| seen_ids.insert(thread.id.clone())); - Ok(threads) -} - -pub(super) fn list_params() -> ThreadListParams { - ThreadListParams { - current_account_only: true, - excluded_thread_ids: None, - attached_to_thread_id: None, - limit: Some(100), - sort_key: Some(ThreadSortKey::UpdatedAt), - sort_direction: Some(SortDirection::Desc), - model_providers: Some(Vec::new()), - source_kinds: None, - originators: None, - archived: Some(false), - cursor: None, - section_id: None, - project_id: None, - cwd: None, - use_state_db_only: false, - search_term: None, - parent_thread_id: None, - ancestor_thread_id: None, - } -} - -/// Isolate unavailable estimates within the existing concurrency slot; keep healthy rows. -async fn estimates(session: &Session, ids: &[&str]) -> Result, String> { - let mut pending = if ids.is_empty() { - Vec::new() - } else { - vec![ids] - }; - let mut rows = Vec::new(); - // At most 15 requests per batch; leave remaining estimates unavailable during an outage. - for _ in 0..15 { - let Some(ids) = pending.pop() else { break }; - match session - .backend - .request(|client| async move { client.get_threads_usage(ids).await }) - .await - { - Ok(batch) => rows.extend(batch), - Err(error) if error.status().is_some_and(|status| status.as_u16() == 503) => { - if ids.len() > 1 { - let midpoint = ids.len().div_ceil(/*rhs*/ 2); - pending.push(&ids[midpoint..]); - pending.push(&ids[..midpoint]); - } - } - Err(error) => return Err(super::client::request_error(error)), - } - } - Ok(rows) -} - -#[cfg(test)] -#[path = "chats_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/chats_tests.rs b/codex-rs/tui/src/analytics/chats_tests.rs deleted file mode 100644 index c852cbc7..00000000 --- a/codex-rs/tui/src/analytics/chats_tests.rs +++ /dev/null @@ -1,180 +0,0 @@ -//! Verify bounded chat discovery, account eligibility, and partial estimate handling. - -use super::super::client::tests::live; -use super::*; -use pretty_assertions::assert_eq; -use serde_json::json; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; - -#[tokio::test] -async fn incomplete_chat_batches_retain_available_estimates_without_inventing_zeroes() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "enterprise_cbp_usage_based").await; - Mock::given(method("POST")).and(path("/backend-api/wham/usage/thread_usage/query")) - .respond_with(|request: &wiremock::Request| { - let body: serde_json::Value = request.body_json().unwrap(); - let ids = body["thread_ids"].as_array().unwrap(); - if ids.len() > 1 || ids[0] == "incomplete" { - ResponseTemplate::new(/*s*/ 503).set_body_json(json!({"detail": "Thread usage is temporarily unavailable."})) - } else { - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"threads": [{ - "thread_id": ids[0], "estimated_usage_credits_micros": if ids[0] == "missing" { None } else { Some(1250000) }, - "estimated_usage_usd_micros": null, "groups": null, - }]})) - } - }).expect(/*r*/ 5).mount(&server).await; - let session = live.session().await.unwrap(); - assert_eq!( - estimates(session, &["available", "incomplete", "missing"]) - .await - .unwrap(), - vec![ThreadUsage { - thread_id: "available".into(), - estimated_usage_credits_micros: 1250000, - estimated_usage_usd_micros: None, - native_usage_usd_micros: None, - groups: Vec::new(), - }] - ); -} - -#[tokio::test] -async fn slow_repairing_chat_listing_keeps_estimate_budget_and_ranks_across_pages() { - use codex_app_server_client::RemoteAppServerClient; - use codex_app_server_client::RemoteAppServerConnectArgs; - use codex_app_server_client::RemoteAppServerEndpoint; - use futures::SinkExt; - use futures::StreamExt; - use tokio_tungstenite::tungstenite::Message; - - let server = MockServer::start().await; - let (_home, live) = live(&server, "enterprise_cbp_usage_based").await; - 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 { - let (stream, _) = listener.accept().await.unwrap(); - let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap(); - let mut pages = Vec::new(); - while let Some(Ok(Message::Text(text))) = socket.next().await { - let request: serde_json::Value = serde_json::from_str(&text).unwrap(); - let result = match request["method"].as_str() { - Some("initialize") => { - json!({"userAgent": "analytics-test", "codexHome": "/unused"}) - } - Some("thread/list") => { - let params = &request["params"]; - pages.push(json!([ - params["cursor"], - params["limit"], - params["useStateDbOnly"].as_bool().unwrap_or_default(), - params["modelProviders"] - ])); - if pages.len() == 1 { - // Simulate repair exceeding the HTTP estimate budget without a wall-clock wait. - tokio::time::pause(); - tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 26)).await; - tokio::time::resume(); - } - let range = if pages.len() == 1 { 0..100 } else { 100..101 }; - let data = range.map(|index| json!({ - "id": format!("chat-{index}"), "sessionId": format!("chat-{index}"), - "preview": "", "name": format!("Chat {index}"), "ephemeral": false, - "modelProvider": "openai", "createdAt": 0, - "updatedAt": chrono::Utc::now().timestamp(), "status": {"type": "idle"}, - "cwd": std::env::temp_dir(), "cliVersion": "test", "source": "cli", "turns": [], - })).collect::>(); - json!({"data": data, "nextCursor": if pages.len() == 1 { Some("next") } else { None }}) - } - _ => continue, - }; - socket - .send(Message::Text( - json!({"jsonrpc": "2.0", "id": request["id"], "result": result}) - .to_string() - .into(), - )) - .await - .unwrap(); - if pages.len() == 2 { - break; - } - } - pages - }); - let remote = RemoteAppServerClient::connect(RemoteAppServerConnectArgs { - required_human_approval: true, - endpoint: RemoteAppServerEndpoint::WebSocket { - websocket_url, - auth_token: None, - }, - client_name: "analytics-test".into(), - client_version: "test".into(), - experimental_api: false, - mcp_server_openai_form_elicitation: false, - opt_out_notification_methods: Vec::new(), - channel_capacity: 16, - }) - .await - .unwrap(); - Mock::given(method("POST")).and(path("/backend-api/wham/usage/thread_usage/query")) - .respond_with(|request: &wiremock::Request| { - let body: serde_json::Value = request.body_json().unwrap(); - let ids = body["thread_ids"].as_array().unwrap(); - assert!(ids.len() <= 100); - if ids.iter().any(|id| id == "chat-35") { - return ResponseTemplate::new(/*s*/ 503) - .set_body_json(json!({"detail": "Thread usage is temporarily unavailable."})); - } - let threads = ids.iter().map(|id| json!({ - "thread_id": id, - "estimated_usage_credits_micros": id.as_str().unwrap().strip_prefix("chat-").unwrap().parse::().unwrap(), - })).collect::>(); - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"threads": threads})) - }).expect(/*r*/ 2..=16).mount(&server).await; - let chats = read( - AppServerRequestHandle::Remote(remote.request_handle()), - Arc::new(live), - ) - .await - .unwrap() - .unwrap(); - assert_eq!( - ( - chats.rows.len(), - chats.rows[0].title.as_str(), - chats.rows.last().unwrap().title.as_str(), - chats.rows.last().unwrap().usage.clone() - ), - (101, "Chat 100", "Chat 35", None) - ); - assert_eq!( - rpc.await.unwrap(), - vec![ - json!([null, 100, false, []]), - json!(["next", 100, false, []]) - ] - ); -} - -#[tokio::test] -async fn unavailable_chat_batches_bound_requests_during_an_outage() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "enterprise_cbp_usage_based").await; - Mock::given(method("POST")) - .respond_with(ResponseTemplate::new(/*s*/ 503)) - .expect(/*r*/ 15) - .mount(&server) - .await; - let ids = (0..100).map(|i| format!("chat-{i}")).collect::>(); - let ids = ids.iter().map(String::as_str).collect::>(); - assert_eq!( - estimates(live.session().await.unwrap(), &ids) - .await - .unwrap(), - Vec::::new() - ); -} diff --git a/codex-rs/tui/src/analytics/chrome.rs b/codex-rs/tui/src/analytics/chrome.rs deleted file mode 100644 index b30f8de2..00000000 --- a/codex-rs/tui/src/analytics/chrome.rs +++ /dev/null @@ -1,180 +0,0 @@ -//! Report navigation and bounded keyboard/mouse help for the full-screen usage view. -//! Each report retains its own reading position; help never replaces its selection or draft. - -use super::AnalyticsView; -use super::controls::Control; -use super::sections::Section; -use crate::keymap::ListAction; -use ratatui::text::Line; - -impl AnalyticsView { - pub(super) fn tab_label(&self, section: Section) -> &'static str { - match section { - Section::Summary => "Overview", - Section::Usage if self.business() => "Tokens", - Section::Usage => "Usage", - Section::Credits => "Credits", - Section::Activity => "Messages", - Section::Plugins => "Plugins", - Section::Skills => "Skills", - Section::Chats => "Chats", - Section::Plan => "Plan", - } - } - - /// Each surface owns its reading position; switching surfaces never copies it. - pub(super) fn scroll_offset(&self) -> usize { - if self.show_help { - self.help_scroll - } else if self.zoomed { - self.sections[self.section].scroll_offset - } else { - self.dashboard_scroll - } - } - - pub(super) fn scroll_offset_mut(&mut self) -> &mut usize { - if self.show_help { - &mut self.help_scroll - } else if self.zoomed { - &mut self.sections[self.section].scroll_offset - } else { - &mut self.dashboard_scroll - } - } - - pub(super) fn toggle_dashboard(&mut self) { - self.zoomed = !self.zoomed; - self.follow_selection = !self.zoomed; - } - - pub(super) fn select_section(&mut self, section: Section) { - if section != self.section { - self.section = section; - self.follow_selection = !self.zoomed; - self.show_help = false; - } - } - - pub(super) fn chat_has_details(&self) -> bool { - let cursor = self.sections[Section::Chats].cursor; - if self.business() { - self.chats - .ready() - .and_then(|chats| chats.rows.get(cursor)) - .and_then(|chat| chat.usage.as_ref()) - .is_some() - } else { - self.task_rows() - .get(cursor) - .and_then(|chat| super::task_panel::available(chat)) - .is_some() - } - } - - pub(super) fn hint(&self, action: ListAction) -> String { - self.keymap - .primary_hint(action) - .map(crate::key_hint::ShortcutHint::display_label) - .unwrap_or_default() - } - - pub(super) fn help_shortcut_available(&self) -> bool { - [ - crossterm::event::KeyModifiers::NONE, - crossterm::event::KeyModifiers::SHIFT, - ] - .into_iter() - .all(|modifiers| { - self.keymap - .action_for(crossterm::event::KeyEvent::new( - crossterm::event::KeyCode::Char('?'), - modifiers, - )) - .is_none() - }) - } - - pub(super) fn help_lines(&self, width: usize) -> Vec> { - let mut controls = vec![ - format!( - "Tab / {} · next / previous report", - crate::key_hint::shift(crossterm::event::KeyCode::Tab).display_label() - ), - format!( - "1–{} · open a report directly", - self.visible_sections().len() - ), - format!( - "{} / {} · select chart day or plan window", - self.hint(ListAction::MoveLeft), - self.hint(ListAction::MoveRight) - ), - format!( - "{} / {} · select chat or plan period; scroll Overview", - self.hint(ListAction::MoveUp), - self.hint(ListAction::MoveDown) - ), - format!( - "{} · expand or collapse details", - self.hint(ListAction::Accept) - ), - format!( - "{} / {} · scroll report", - self.hint(ListAction::PageUp), - self.hint(ListAction::PageDown) - ), - "In alternate screen: mouse wheel · scroll; click tabs or report controls".into(), - ]; - if self.control_available(Control::Range) { - controls.push("r · switch between 7 and 30 days".into()); - } - if self.control_available(Control::Group) { - controls.push("g · change grouping / Overview aggregation".into()); - } - if self.control_available(Control::Model) { - controls.push("m · cycle model filter".into()); - } - if self.control_available(Control::TaskMetric) { - controls.push("s · change chat sort metric".into()); - } - if self.control_available(Control::ZeroCreditGroups) { - controls.push("a · show zero-credit groups in expanded details".into()); - } - controls.extend([ - "R · refresh all reports".into(), - format!( - "z · dashboard / focused report; {} · focus dashboard card", - self.hint(ListAction::Accept) - ), - format!( - "{} · back; q / {} · close usage", - self.hint(ListAction::Cancel), - crate::key_hint::ctrl(crossterm::event::KeyCode::Char('c')).display_label() - ), - ]); - if self.help_shortcut_available() { - controls.insert(controls.len() - 1, "? · toggle this help".into()); - } - if let Some(updated) = self.sections[self.section] - .history - .ready() - .and_then(|report| report.updated_at) - .and_then(|timestamp| chrono::DateTime::from_timestamp(timestamp, /*nsecs*/ 0)) - { - controls.push(format!( - "Report updated {} UTC", - updated.format(self.clock_format.date_time_format()) - )); - } - controls - .into_iter() - .flat_map(|line| { - textwrap::wrap(&line, width) - .into_iter() - .map(|line| Line::from(line.into_owned())) - .collect::>() - }) - .collect() - } -} diff --git a/codex-rs/tui/src/analytics/client.rs b/codex-rs/tui/src/analytics/client.rs deleted file mode 100644 index 0a7a7614..00000000 --- a/codex-rs/tui/src/analytics/client.rs +++ /dev/null @@ -1,291 +0,0 @@ -//! Local account report loading with backend-owned authentication and identity checks. -//! Cached responses belong to one local account and user, independently of the connected server. -//! Every report uses the view's captured end date until refresh replaces the session. - -use super::models::AccountAnalyticsGrouping as Grouping; -use super::models::AccountAnalyticsReport as Report; -use super::models::AccountKind; -use super::report_data::AnalyticsData; -use crate::legacy_core::config::Config; -use codex_backend_client::AnalyticsReport; -use codex_backend_client::AnalyticsSession; -use codex_backend_client::RequestError; -use codex_features::Feature; -use codex_protocol::account::PlanType; -use std::collections::HashMap; -use std::sync::Arc; -use tokio::sync::Mutex; -use tokio::sync::OnceCell; - -pub(super) struct Live { - pub(super) identity_invalidated: std::sync::atomic::AtomicBool, - config: Arc, - end_date: chrono::NaiveDate, - session: OnceCell, - token_models: std::sync::RwLock>, - attributed_usage: std::sync::atomic::AtomicBool, -} - -pub(super) struct Session { - pub(super) kind: AccountKind, - pub(super) backend: AnalyticsSession, - credit_groups: Vec, - cache: Mutex>, -} - -impl Live { - pub(super) fn new(config: Arc, end_date: chrono::NaiveDate) -> Self { - Self { - identity_invalidated: std::sync::atomic::AtomicBool::new(/*v*/ false), - config, - end_date, - session: OnceCell::new(), - token_models: std::sync::RwLock::new(Vec::new()), - attributed_usage: std::sync::atomic::AtomicBool::new(/*v*/ true), - } - } - - pub(super) fn account_label(&self) -> Option { - let session = self.session.get()?; - session.backend.account().email.clone() - } - - pub(super) fn credit_groups(&self) -> &[usize] { - self.session - .get() - .map_or(&[0], |session| &session.credit_groups) - } - - pub(super) fn attributed_usage(&self) -> bool { - self.attributed_usage - .load(std::sync::atomic::Ordering::Relaxed) - } - - pub(super) fn token_models(&self) -> Vec { - self.token_models - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - } - - pub(super) async fn session(&self) -> Result<&Session, String> { - self.session - .get_or_try_init(|| async { - let session = AnalyticsSession::from_config( - self.config.as_ref(), - self.config.http_client_factory(), - self.config - .features - .enabled(Feature::RuntimeAgentInstances) - .then_some(self.config.runtime_auth_mode), - ) - .await?; - let credit_groups = Grouping::credit_groupings(session.account().plan_type) - .iter() - .filter_map(|group| { - super::data::GROUPINGS - .iter() - .position(|candidate| candidate == group) - }) - .collect(); - Ok(Session { - kind: AccountKind::from(session.account().plan_type), - credit_groups, - backend: session, - cache: Mutex::new(HashMap::new()), - }) - }) - .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, String> { - let session = self.session().await?; - if session.kind != AccountKind::Consumer { - return Ok(None); - } - let history = session - .backend - .request(|client| async move { client.get_plan_limit_history().await }) - .await; - self.ensure_identity().await?; - history - .map_err(request_error)? - .map(super::plan::Report::parse) - .transpose() - .map(Option::flatten) - } - - pub(super) async fn history( - &self, - report: Report, - days: u32, - grouping: Grouping, - ) -> Result, String> { - self.filtered_history(report, days, grouping, /*model_filter*/ None) - .await - } - - pub(super) async fn filtered_history( - &self, - report: Report, - days: u32, - grouping: Grouping, - model_filter: Option<&str>, - ) -> Result, String> { - let end = self.end_date; - let start = days - .checked_sub(/*rhs*/ 1) - .and_then(|offset| end.checked_sub_days(chrono::Days::new(u64::from(offset)))) - .ok_or("Invalid analytics date range.")?; - let session = self.session().await?; - self.ensure_identity().await?; - let enterprise_tokens = report == Report::Usage - && matches!( - session.kind, - AccountKind::Enterprise | AccountKind::Business - ); - let grouping = - if enterprise_tokens && !matches!(grouping, Grouping::Model | Grouping::TokenType) { - Grouping::TokenType - } else { - grouping - }; - let route = - route(report, grouping, session.backend.account().plan_type).ok_or_else(|| { - "This credit breakdown is not supported for this account type.".to_string() - })?; - // Credit events have no range parameters. Other grouping changes reuse the same payload. - let key = if route == AnalyticsReport::Credits { - (route, String::new(), String::new()) - } else { - (route, start.to_string(), end.to_string()) - }; - let cached = session.cache.lock().await.get(&key).cloned(); - let response = if let Some(response) = cached { - Ok(response) - } else { - session - .backend - .request(|client| { - let (_, start, end) = key.clone(); - async move { client.get_account_analytics(route, &start, &end).await } - }) - .await - .map(AnalyticsData::from) - }; - self.ensure_identity().await?; - let response = response.map_err(request_error)?; - let history = (|| { - if enterprise_tokens { - let models = super::tokens::history(response.clone(), Grouping::Model, start, end)?; - *self - .token_models - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner) = - super::render::categories(&models) - .into_iter() - .map(|model| model.key) - .collect(); - super::tokens::filtered_history( - response.clone(), - grouping, - start, - end, - model_filter, - ) - .map(Some) - } else { - let grouping = if report == Report::Usage { - let attributed = - super::normalize::has_complete_attribution(&response, start, end)?; - self.attributed_usage - .store(attributed, std::sync::atomic::Ordering::Relaxed); - if !attributed && matches!(grouping, Grouping::Feature | Grouping::TaskStart) { - Grouping::Surface - } else { - grouping - } - } else { - grouping - }; - super::normalize::history(response.clone(), report, grouping, start, end) - } - })(); - let mut cache = session.cache.lock().await; - if history.is_ok() { - cache.insert(key, response); - } else { - cache.remove(&key); - } - history - } -} - -// Account type selects billing semantics, never activity-report eligibility. -fn route(report: Report, grouping: Grouping, plan: Option) -> Option { - let kind = AccountKind::from(plan); - let enterprise = kind == AccountKind::Enterprise; - Some(match report { - Report::Usage if enterprise => AnalyticsReport::EnterpriseTokens, - Report::Usage if kind == AccountKind::Business => AnalyticsReport::WorkspaceCredits, - Report::Usage => AnalyticsReport::Usage, - Report::Messages => AnalyticsReport::Messages, - Report::Credits if !Grouping::credit_groupings(plan).contains(&grouping) => return None, - Report::Credits if enterprise => AnalyticsReport::EnterpriseCredits { - breakdown: match grouping { - Grouping::Surface => "product", - Grouping::Model => "model", - Grouping::Speed => "speed", - Grouping::Reasoning => "reasoning_effort", - Grouping::Feature | Grouping::TaskStart | Grouping::TokenType => return None, - }, - }, - Report::Credits if kind == AccountKind::Business => AnalyticsReport::WorkspaceCredits, - Report::Credits => AnalyticsReport::Credits, - Report::Plugins => AnalyticsReport::Plugins { - limit: if enterprise { 8 } else { 10 }, - }, - Report::Skills => AnalyticsReport::Skills { - limit: if enterprise { 6 } else { 10 }, - }, - }) -} - -pub(super) fn request_error(error: RequestError) -> String { - match error.status().map(|status| status.as_u16()) { - Some(401) => "Sign in again to load this report.", - Some(403) => "Access denied for this report.", - Some(404) => "This report endpoint is unavailable. Press R to retry.", - _ => "Report request failed. Press R to retry.", - } - .into() -} - -#[cfg(test)] -#[path = "client_tests.rs"] -pub(super) mod tests; - -#[cfg(test)] -#[path = "connection_tests.rs"] -mod connection_tests; - -#[cfg(test)] -#[path = "account_plan_tests.rs"] -mod account_plan_tests; - -#[cfg(test)] -#[path = "runtime_auth_tests.rs"] -mod runtime_auth_tests; diff --git a/codex-rs/tui/src/analytics/client_tests.rs b/codex-rs/tui/src/analytics/client_tests.rs deleted file mode 100644 index 680ab13f..00000000 --- a/codex-rs/tui/src/analytics/client_tests.rs +++ /dev/null @@ -1,858 +0,0 @@ -//! Account-scoped authentication and request identity regression coverage. - -use super::*; -use crate::analytics::sections::Section; -use crate::legacy_core::config::ConfigBuilder; -use base64::Engine; -use codex_config::LoaderOverrides; -use pretty_assertions::assert_eq; -use serde_json::json; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; - -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", - "https://api.openai.com/auth": { - "chatgpt_account_id": account, "chatgpt_user_id": user, "chatgpt_plan_type": plan, - }, - }) - .to_string(), - ); - let token = format!("e30.{claims}.test"); - let auth = serde_json::from_value(json!({ - "auth_mode": "chatgpt", "tokens": {"id_token": token, "access_token": token, - "refresh_token": "test-refresh", "account_id": account}, - "last_refresh": chrono::Utc::now(), - })) - .unwrap(); - codex_login::save_auth( - home, - &auth, - codex_login::AuthCredentialsStoreMode::File, - codex_login::AuthKeyringBackendKind::default(), - ) - .unwrap(); -} - -pub(in crate::analytics) async fn live( - server: &MockServer, - plan: &str, -) -> (tempfile::TempDir, Live) { - let home = tempfile::tempdir().unwrap(); - let mut config = ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .loader_overrides(LoaderOverrides::without_managed_config_for_tests()) - .build() - .await - .unwrap(); - config.chatgpt_base_url = format!("{}/backend-api", server.uri()); - config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File; - sign_in(home.path(), "account-a", "user-a", plan); - Mock::given(method("GET")) - .and(path("/backend-api/wham/accounts/check")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "accounts": [{"id": "account-a", "plan_type": plan}], - "account_ordering": ["account-a"] - }))) - .with_priority(/*p*/ 2) - .mount(server) - .await; - ( - home, - Live::new(Arc::new(config), "2026-01-15".parse().unwrap()), - ) -} - -async fn report_requests(server: &MockServer) -> Vec { - server - .received_requests() - .await - .unwrap() - .into_iter() - .filter(|request| request.url.path() != "/backend-api/wham/accounts/check") - .collect() -} - -#[tokio::test] -async fn analytics_rejects_identity_changes_during_requests() { - let server = MockServer::start().await; - let (home, live) = live(&server, "business").await; - let session = live.session().await.unwrap(); - let authenticated = &session.backend; - let result = authenticated - .request(|_| async { - sign_in(home.path(), "account-b", "user-a", "business"); - Ok(123) - }) - .await; - assert_eq!( - result.unwrap_err().to_string(), - "Account changed. Press R to refresh Analytics." - ); - assert!(report_requests(&server).await.is_empty()); -} - -#[tokio::test] -async fn analytics_rejects_account_and_user_changes_before_requests() { - for (account, user) in [("account-b", "user-a"), ("account-a", "user-b")] { - let server = MockServer::start().await; - let (home, live) = live(&server, "plus").await; - let session = live.session().await.unwrap(); - let authenticated = &session.backend; - sign_in(home.path(), account, user, "plus"); - let requested = std::cell::Cell::new(/*value*/ false); - let result = authenticated - .request(|_| async { - requested.set(/*val*/ true); - Ok(()) - }) - .await; - assert!(!requested.get()); - assert_eq!( - result.unwrap_err().to_string(), - "Account changed. Press R to refresh Analytics." - ); - } -} - -#[tokio::test] -async fn analytics_requires_local_chatgpt_authentication() { - for auth in [None, Some(json!({"OPENAI_API_KEY": "sk-test-only"}))] { - let server = MockServer::start().await; - let (home, live) = live(&server, "plus").await; - let path = home.path().join("auth.json"); - match auth { - Some(auth) => std::fs::write(path, serde_json::to_vec(&auth).unwrap()).unwrap(), - None => std::fs::remove_file(path).unwrap(), - } - assert_eq!( - live.session().await.err(), - Some("Sign in locally with ChatGPT to view Analytics.".to_string()) - ); - assert!(report_requests(&server).await.is_empty()); - } -} - -#[tokio::test] -async fn analytics_requests_use_reloaded_credentials_for_the_same_identity() { - let server = MockServer::start().await; - let (home, live) = live(&server, "plus").await; - let session = live.session().await.unwrap(); - let authenticated = &session.backend; - assert_eq!( - live.account_label().as_deref(), - Some("analytics@example.test") - ); - let auth_path = home.path().join("auth.json"); - let mut auth: serde_json::Value = - serde_json::from_slice(&std::fs::read(&auth_path).unwrap()).unwrap(); - auth["tokens"]["access_token"] = json!("refreshed-access-token"); - std::fs::write(auth_path, serde_json::to_vec(&auth).unwrap()).unwrap(); - Mock::given(method("GET")) - .and(path("/backend-api/wham/usage/daily-token-usage-breakdown")) - .and(header("chatgpt-account-id", "account-a")) - .and(header("authorization", "Bearer refreshed-access-token")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": []}))) - .expect(/*r*/ 1) - .mount(&server) - .await; - let result = authenticated - .request(|client| async move { - client - .get_account_analytics( - codex_backend_client::AnalyticsReport::Usage, - "2026-09-01", - "2026-09-07", - ) - .await - }) - .await - .unwrap(); - assert_eq!( - result, - codex_backend_client::AnalyticsResponse::Usage( - codex_backend_client::analytics_models::DailyProductSurfaceUsageResponse::default() - ) - ); - server.verify().await; -} - -#[tokio::test] -async fn analytics_retries_unauthorized_requests_after_credentials_reload() { - let server = MockServer::start().await; - let (home, live) = live(&server, "plus").await; - let session = live.session().await.unwrap(); - let authenticated = &session.backend; - let auth_path = home.path().join("auth.json"); - let mut auth: serde_json::Value = - serde_json::from_slice(&std::fs::read(&auth_path).unwrap()).unwrap(); - let original_token = auth["tokens"]["access_token"].as_str().unwrap().to_owned(); - auth["tokens"]["access_token"] = json!("recovered-access-token"); - let updated_auth = serde_json::to_vec(&auth).unwrap(); - Mock::given(method("GET")) - .and(header("authorization", format!("Bearer {original_token}"))) - .respond_with(move |_: &wiremock::Request| { - std::fs::write(&auth_path, &updated_auth).unwrap(); - ResponseTemplate::new(/*s*/ 401) - }) - .expect(/*r*/ 1) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(header("authorization", "Bearer recovered-access-token")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": []}))) - .expect(/*r*/ 1) - .mount(&server) - .await; - let result = authenticated - .request(|client| async move { - client - .get_account_analytics( - codex_backend_client::AnalyticsReport::Usage, - "2026-09-01", - "2026-09-07", - ) - .await - }) - .await - .unwrap(); - assert_eq!( - result, - codex_backend_client::AnalyticsResponse::Usage( - codex_backend_client::analytics_models::DailyProductSurfaceUsageResponse::default() - ) - ); - server.verify().await; -} - -#[tokio::test] -async fn analytics_retries_session_initialization_after_sign_in() { - let server = MockServer::start().await; - let (home, live) = live(&server, "plus").await; - std::fs::remove_file(home.path().join("auth.json")).unwrap(); - assert!(live.session().await.is_err()); - sign_in(home.path(), "account-a", "user-a", "plus"); - assert_eq!( - live.session().await.unwrap().backend.account().id, - "account-a" - ); -} - -#[tokio::test] -async fn analytics_matches_app_account_routes_and_parameters() { - let server = MockServer::start().await; - for (plan, report, grouping, endpoint, extra) in [ - ( - "plus", - Report::Usage, - Grouping::Model, - "usage/daily-token-usage-breakdown", - vec![("group_by", "day")], - ), - ( - "business", - Report::Usage, - Grouping::TokenType, - "usage/daily-workspace-user-token-usage-breakdown", - vec![ - ("group_by", "day"), - ("breakdown_by", "model"), - ("modes", "codex"), - ("modes", "work"), - ], - ), - ( - "business", - Report::Messages, - Grouping::Model, - "analytics/daily-workspace-usage-counts", - vec![("group_by", "day"), ("workspace_user", "true")], - ), - ( - "unknown", - Report::Usage, - Grouping::Surface, - "usage/daily-token-usage-breakdown", - vec![("group_by", "day")], - ), - ( - "unknown", - Report::Messages, - Grouping::Model, - "analytics/daily-workspace-usage-counts", - vec![("group_by", "day"), ("workspace_user", "true")], - ), - ( - "unknown", - Report::Plugins, - Grouping::Feature, - "analytics/daily-plugin-usage-metrics", - vec![ - ("group_by", "day"), - ("workspace_user", "true"), - ("top_plugin_limit", "10"), - ], - ), - ( - "unknown", - Report::Skills, - Grouping::Feature, - "analytics/daily-skill-usage-metrics", - vec![ - ("group_by", "day"), - ("workspace_user", "true"), - ("top_skill_limit", "10"), - ], - ), - ( - "edu", - Report::Credits, - Grouping::Model, - "usage/daily-workspace-user-credit-usage", - vec![("breakdown", "model")], - ), - ( - "plus", - Report::Credits, - Grouping::Surface, - "usage/credit-usage-events", - vec![], - ), - ( - "team", - Report::Usage, - Grouping::Model, - "usage/daily-workspace-user-token-usage-breakdown", - vec![("group_by", "day")], - ), - ( - "sci_plus", - Report::Usage, - Grouping::Model, - "usage/daily-workspace-user-token-usage-breakdown", - vec![("group_by", "day")], - ), - ( - "team", - Report::Credits, - Grouping::Speed, - "usage/daily-workspace-user-token-usage-breakdown", - vec![("group_by", "day")], - ), - ( - "business", - Report::Credits, - Grouping::Reasoning, - "usage/daily-workspace-user-credit-usage", - vec![("breakdown", "reasoning_effort")], - ), - ( - "plus", - Report::Messages, - Grouping::Model, - "analytics/daily-workspace-usage-counts", - vec![("group_by", "day"), ("workspace_user", "true")], - ), - ( - "plus", - Report::Plugins, - Grouping::Feature, - "analytics/daily-plugin-usage-metrics", - vec![ - ("group_by", "day"), - ("workspace_user", "true"), - ("top_plugin_limit", "10"), - ], - ), - ( - "business", - Report::Plugins, - Grouping::Feature, - "analytics/daily-plugin-usage-metrics", - vec![ - ("group_by", "day"), - ("workspace_user", "true"), - ("top_plugin_limit", "8"), - ], - ), - ( - "business", - Report::Skills, - Grouping::Feature, - "analytics/daily-skill-usage-metrics", - vec![ - ("group_by", "day"), - ("workspace_user", "true"), - ("top_skill_limit", "6"), - ], - ), - ] { - server.reset().await; - let (_home, live) = live(&server, plan).await; - let today = live.end_date; - let start = (today - chrono::Days::new(/*num*/ 6)).to_string(); - let response = if endpoint == "usage/daily-workspace-user-credit-usage" { - let breakdown = extra.iter().find(|(key, _)| *key == "breakdown").unwrap().1; - json!({"data": [], "series": [], "breakdown": breakdown}) - } else { - json!({"data": []}) - }; - Mock::given(method("GET")) - .and(path(format!("/backend-api/wham/{endpoint}"))) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(response)) - .expect(/*r*/ 1) - .mount(&server) - .await; - assert!( - live.history(report, /*days*/ 7, grouping) - .await - .unwrap() - .is_some() - ); - let requests = report_requests(&server).await; - let mut actual = requests[0] - .url - .query_pairs() - .map(|(key, value)| (key.into_owned(), value.into_owned())) - .collect::>(); - let mut expected = extra - .into_iter() - .map(|(key, value)| (key.to_string(), value.to_string())) - .collect::>(); - if endpoint != "usage/credit-usage-events" { - expected.push(("start_date".into(), start.clone())); - expected.push(("end_date".into(), today.to_string())); - } - actual.sort(); - expected.sort(); - assert_eq!(actual, expected); - assert!(requests[0].headers.get("authorization").is_some()); - } -} - -#[tokio::test] -async fn analytics_uses_api_response_for_usage_and_turns_availability() { - let server = MockServer::start().await; - for report in [Report::Usage, Report::Messages] { - for status in [403, 404] { - server.reset().await; - let (_home, live) = live(&server, "business").await; - Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(status)) - .expect(/*r*/ 1) - .mount(&server) - .await; - assert_eq!( - live.history(report, /*days*/ 7, Grouping::Surface) - .await - .unwrap_err(), - if status == 403 { - "Access denied for this report." - } else { - "This report endpoint is unavailable. Press R to retry." - } - ); - server.verify().await; - } - } -} - -#[tokio::test] -async fn analytics_reuses_payload_for_grouping_and_rejects_account_changes() { - let server = MockServer::start().await; - let (home, live) = live(&server, "team").await; - let today = live.end_date.to_string(); - Mock::given(method("GET")) - .and(path( - "/backend-api/wham/usage/daily-workspace-user-token-usage-breakdown", - )) - .respond_with( - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": [{ - "date": today, "product_surface_usage_values": {}, "premium_usage_values": { - "credit_usage_credits": {"cli": 12.5}, "total_usage_credits": {}, - "uncached_text_input_tokens_by_surface": {}, "cached_text_input_tokens_by_surface": {}, - "text_output_tokens_by_surface": {}, "text_total_tokens_by_surface": {} - }, - "models": [{"model": "model-a", "credits": 12.5, "speed": "fast", "on_demand_credits": 12.5}] - }]})), - ) - .expect(/*r*/ 1) - .mount(&server) - .await; - let surface = live - .history(Report::Credits, /*days*/ 7, Grouping::Surface) - .await - .unwrap() - .unwrap(); - let model = live - .history(Report::Credits, /*days*/ 7, Grouping::Model) - .await - .unwrap() - .unwrap(); - assert_eq!( - ( - surface.data.last().unwrap().total, - model.data.last().unwrap().total - ), - (12.5, 12.5) - ); - sign_in(home.path(), "account-a", "user-b", "team"); - assert_eq!( - live.history(Report::Credits, /*days*/ 7, Grouping::Model) - .await - .unwrap_err(), - "Account changed. Press R to refresh Analytics." - ); -} - -#[tokio::test] -async fn token_model_filter_reuses_the_account_scoped_response() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "business").await; - let today = live.end_date.to_string(); - Mock::given(method("GET")) - .and(path("/backend-api/wham/usage/daily-workspace-user-token-usage-breakdown")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data":[{ - "date":today, "product_surface_usage_values": {}, "groups":[ - {"dimensions":{"model":"alpha"}, "credits": 0, "uncached_text_input_tokens":10,"cached_text_input_tokens":20,"text_output_tokens":30}, - {"dimensions":{"model":"beta"}, "credits": 0, "uncached_text_input_tokens":100,"cached_text_input_tokens":200,"text_output_tokens":300} - ] - }]}))) - .expect(/*r*/ 1).mount(&server).await; - let all = live - .history(Report::Usage, /*days*/ 7, Grouping::TokenType) - .await - .unwrap() - .unwrap(); - let alpha = live - .filtered_history( - Report::Usage, - /*days*/ 7, - Grouping::TokenType, - Some("alpha"), - ) - .await - .unwrap() - .unwrap(); - let beta = live - .filtered_history( - Report::Usage, - /*days*/ 7, - Grouping::TokenType, - Some("beta"), - ) - .await - .unwrap() - .unwrap(); - assert_eq!( - (all.data[0].total, alpha.data[0].total, beta.data[0].total), - (660.0, 60.0, 600.0) - ); - assert_eq!( - live.token_models(), - vec!["beta".to_string(), "alpha".to_string()] - ); - assert_eq!(report_requests(&server).await.len(), 1); -} - -#[tokio::test] -async fn legacy_usage_falls_back_to_surface_for_attribution_only_groupings() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "plus").await; - let today = live.end_date.to_string(); - Mock::given(method("GET")) - .respond_with( - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": [{ - "date": today, "product_surface_usage_values": {"cli": 12.5} - }]})), - ) - .expect(/*r*/ 1) - .mount(&server) - .await; - let surface = live - .history(Report::Usage, /*days*/ 7, Grouping::Surface) - .await - .unwrap(); - for grouping in [Grouping::Feature, Grouping::TaskStart] { - let history = live - .history(Report::Usage, /*days*/ 7, grouping) - .await - .unwrap(); - assert_eq!((live.attributed_usage(), history), (false, surface.clone())); - } - server.verify().await; -} - -#[tokio::test] -async fn invalid_ranges_fail_without_requesting_reports() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "plus").await; - for days in [0, u32::MAX] { - assert_eq!( - live.history(Report::Usage, days, Grouping::Surface) - .await - .unwrap_err(), - "Invalid analytics date range." - ); - } - assert!(report_requests(&server).await.is_empty()); -} - -#[tokio::test] -async fn unknown_plan_exposes_no_credit_breakdowns() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "unknown").await; - live.session().await.unwrap(); - assert!(live.credit_groups().is_empty()); - assert!( - live.history(Report::Credits, /*days*/ 7, Grouping::Surface) - .await - .is_err() - ); - assert!(report_requests(&server).await.is_empty()); -} - -#[tokio::test] -async fn in_flight_account_switch_retains_refresh_guidance() { - let server = MockServer::start().await; - let (home, live) = live(&server, "plus").await; - let home_path = home.path().to_path_buf(); - Mock::given(method("GET")) - .respond_with(move |_: &wiremock::Request| { - sign_in(&home_path, "account-b", "user-a", "plus"); - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": []})) - }) - .expect(/*r*/ 1) - .mount(&server) - .await; - assert_eq!( - live.history(Report::Usage, /*days*/ 7, Grouping::Surface) - .await - .unwrap_err(), - "Account changed. Press R to refresh Analytics." - ); - server.verify().await; -} - -#[tokio::test] -async fn missing_breakdowns_remain_unavailable() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "plus").await; - let today = live.end_date.to_string(); - Mock::given(method("GET")) - .respond_with( - ResponseTemplate::new(/*s*/ 200).set_body_json( - json!({"data": [{"date": today, "product_surface_usage_values": {}}]}), - ), - ) - .expect(/*r*/ 1) - .mount(&server) - .await; - assert_eq!( - live.history(Report::Usage, /*days*/ 7, Grouping::Model) - .await, - Ok(None) - ); - server.verify().await; -} - -#[tokio::test] -async fn out_of_range_legacy_rows_do_not_disable_attribution() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "plus").await; - let today = live.end_date.to_string(); - Mock::given(method("GET")) - .respond_with( - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": [ - {"date": "2000-01-01", "product_surface_usage_values": {}}, - {"date": today, "product_surface_usage_values": {}, "attribution": [{"thread_source": "user", "turn_trigger": "composer", "model": "example", "surface": "cli", "value": 12.0}]} - ]})), - ) - .expect(/*r*/ 1) - .mount(&server) - .await; - let history = live - .history(Report::Usage, /*days*/ 7, Grouping::Feature) - .await - .unwrap() - .unwrap(); - assert_eq!( - history.data, - vec![super::super::models::AccountAnalyticsDay { - date: live.end_date, - total: 12.0, - values: vec![super::super::models::AccountAnalyticsValue { - key: "user".into(), - label: "Tasks".into(), - value: 12.0, - }], - }] - ); - assert!(live.attributed_usage()); -} - -#[tokio::test] -async fn invalid_reports_can_retry_without_recreating_the_session() { - for plan in ["plus", "business"] { - let server = MockServer::start().await; - let (_home, live) = live(&server, plan).await; - let requests = Arc::new(std::sync::atomic::AtomicUsize::new(/*v*/ 0)); - let count = Arc::clone(&requests); - Mock::given(method("GET")) - .respond_with(move |_: &wiremock::Request| { - let body = if count.fetch_add(/*val*/ 1, std::sync::atomic::Ordering::SeqCst) == 0 { - json!({"data": [{"date": "invalid"}]}) - } else { - json!({"data": []}) - }; - ResponseTemplate::new(/*s*/ 200).set_body_json(body) - }) - .expect(/*r*/ 2) - .mount(&server) - .await; - assert!( - live.history(Report::Usage, /*days*/ 7, Grouping::Surface) - .await - .is_err() - ); - assert!( - live.history(Report::Usage, /*days*/ 7, Grouping::Surface) - .await - .is_ok() - ); - assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 2); - server.verify().await; - } -} - -#[tokio::test] -async fn invalid_cached_breakdowns_are_evicted_before_retry() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "plus").await; - let today = live.end_date.to_string(); - let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(/*v*/ 0)); - let count = Arc::clone(&attempts); - Mock::given(method("GET")) - .respond_with(move |_: &wiremock::Request| { - let model = if count.fetch_add(/*val*/ 1, std::sync::atomic::Ordering::SeqCst) == 0 { - json!({"model": "alpha", "credits": -1}) - } else { - json!({"model": "alpha", "credits": 12}) - }; - ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": [{ - "date": today, "product_surface_usage_values": {"cli": 12}, "models": [model] - }]})) - }) - .expect(/*r*/ 2) - .mount(&server) - .await; - live.history(Report::Usage, /*days*/ 7, Grouping::Surface) - .await - .unwrap(); - assert!( - live.history(Report::Usage, /*days*/ 7, Grouping::Model) - .await - .is_err() - ); - assert!( - live.history(Report::Usage, /*days*/ 7, Grouping::Model) - .await - .unwrap() - .is_some() - ); - assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 2); - server.verify().await; -} - -pub(in crate::analytics) async fn connected_view( - server: &MockServer, - plan: &str, -) -> ( - tempfile::TempDir, - crate::AppServerSession, - crate::analytics::AnalyticsView, -) { - let (home, live) = live(server, plan).await; - let config = Arc::clone(&live.config); - let app_server = crate::start_embedded_app_server_for_picker(&config) - .await - .unwrap(); - let mut view = - crate::analytics::AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list); - view.open( - app_server.request_handle(), - crate::tui::FrameRequester::test_dummy(), - Vec::new(), - config, - ); - (home, app_server, view) -} - -#[tokio::test] -async fn live_account_identity_is_visible_and_closing_aborts_pending_loads() { - let server = MockServer::start().await; - let (_home, live) = live(&server, "plus").await; - live.session().await.unwrap(); - let mut view = - crate::analytics::AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list); - view.live = Some(Arc::new(live)); - view.sections[Section::Usage].history = - super::super::data::Load::Error("Couldn't load usage. Press R to retry.".into()); - let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new( - /*width*/ 100, /*height*/ 24, - )) - .unwrap(); - terminal - .draw(|frame| view.render(frame.area(), frame.buffer_mut())) - .unwrap(); - insta::assert_snapshot!(terminal.backend().to_string()); - let (draw_tx, _) = tokio::sync::broadcast::channel(/*capacity*/ 1); - let (cancelled_tx, cancelled_rx) = tokio::sync::oneshot::channel::<()>(); - view.sections[Section::Usage].history = super::super::data::Load::start( - async move { - let _cancelled = cancelled_tx; - std::future::pending().await - }, - crate::tui::FrameRequester::new(draw_tx), - ); - view.cancel_loads(); - assert!(cancelled_rx.await.is_err()); -} - -#[tokio::test] -async fn plan_history_rejects_account_change_during_response() { - let server = MockServer::start().await; - for status in [200, 404, 503] { - server.reset().await; - let (home, live) = live(&server, "plus").await; - let home_path = home.path().to_path_buf(); - Mock::given(method("GET")) - .and(path("/backend-api/wham/usage/plan_limit_history")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(move |_: &wiremock::Request| { - sign_in(&home_path, "account-a", "user-b", "plus"); - ResponseTemplate::new(status).set_body_json(json!({ - "data_as_of":"2026-09-02T00:00:00Z", "coverage_start":null, - "coverage_complete":true, "periods":[] - })) - }) - .expect(/*r*/ 1) - .mount(&server) - .await; - assert_eq!( - live.plan_history().await.err().unwrap(), - "Account changed. Press R to refresh Analytics." - ); - } -} - -#[path = "profile_identity_tests.rs"] -mod profile_identity; diff --git a/codex-rs/tui/src/analytics/compact_tests.rs b/codex-rs/tui/src/analytics/compact_tests.rs deleted file mode 100644 index fcc91f98..00000000 --- a/codex-rs/tui/src/analytics/compact_tests.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! Large report totals and axes stay compact while selected-day details retain precision. -use super::*; - -#[test] -fn report_headlines_and_axes_compact_large_values() { - for (section, unit, total, headline) in [ - ( - Section::Usage, - models::AccountAnalyticsUnit::Tokens, - 12_280_365_226.0, - "12.3B tokens", - ), - ( - Section::Plugins, - models::AccountAnalyticsUnit::Count, - 9_749.0, - "9.7K calls", - ), - ( - Section::Skills, - models::AccountAnalyticsUnit::Count, - 2_901.0, - "2.9K uses", - ), - ] { - let mut view = fixture::view(models::AccountKind::Enterprise); - view.section = section; - view.sections[section].history = Load::Ready(models::AccountAnalyticsHistory { - unit, - updated_at: None, - data: vec![models::AccountAnalyticsDay { - date: view.end_date, - total, - values: vec![models::AccountAnalyticsValue { - key: "test".into(), - label: "Example".into(), - value: total, - }], - }], - }); - let rendered = screen(&mut view, /*width*/ 100, /*height*/ 30); - assert!(rendered.contains(headline)); - assert!(rendered.contains(&data::amount(total))); - } -} diff --git a/codex-rs/tui/src/analytics/connection_tests.rs b/codex-rs/tui/src/analytics/connection_tests.rs deleted file mode 100644 index b09c1c55..00000000 --- a/codex-rs/tui/src/analytics/connection_tests.rs +++ /dev/null @@ -1,260 +0,0 @@ -//! 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; -use codex_app_server_client::RemoteAppServerEndpoint; -use futures::SinkExt; -use futures::StreamExt; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use tokio::net::TcpListener; -use tokio::net::TcpStream; -use tokio_tungstenite::WebSocketStream; -use tokio_tungstenite::tungstenite::Message; -use wiremock::Mock; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; - -async fn read(socket: &mut WebSocketStream) -> Value { - let frame = socket.next().await.unwrap().unwrap(); - serde_json::from_str(frame.to_text().unwrap()).unwrap() -} - -async fn remote() -> (RemoteAppServerClient, tokio::task::JoinHandle<()>) { - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (stream, _) = listener.accept().await.unwrap(); - let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap(); - let initialize = read(&mut socket).await; - assert_eq!(initialize["method"], "initialize"); - socket - .send(Message::Text( - json!({"id": initialize["id"], "result": { - "userAgent": "analytics-test", "codexHome": "/server/.codex", - }}) - .to_string() - .into(), - )) - .await - .unwrap(); - assert_eq!(read(&mut socket).await["method"], "initialized"); - // Analytics uses the local account without requesting connected-server account data. - assert!(socket.next().await.unwrap().unwrap().is_close()); - }); - let client = RemoteAppServerClient::connect(RemoteAppServerConnectArgs { - required_human_approval: true, - endpoint: RemoteAppServerEndpoint::WebSocket { - websocket_url: format!("ws://{address}"), - auth_token: None, - }, - client_name: "analytics-test".into(), - client_version: "0.0.0-test".into(), - experimental_api: true, - mcp_server_openai_form_elicitation: false, - opt_out_notification_methods: Vec::new(), - channel_capacity: 8, - }) - .await - .unwrap(); - (client, server) -} - -#[tokio::test] -async fn local_reports_share_an_account_and_recover_profile_errors() { - use crate::analytics::AnalyticsView; - use crate::analytics::data::Load; - use crate::analytics::sections::Section; - - let http = crate::analytics::test_support::server().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")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(ResponseTemplate::new(/*s*/ 503)) - .expect(/*r*/ 1) - .mount_as_scoped(&http) - .await; - let mut view = AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list); - view.open( - AppServerRequestHandle::Remote(client.request_handle()), - crate::tui::FrameRequester::test_dummy(), - Vec::new(), - std::sync::Arc::clone(&local.config), - ); - crate::analytics::test_support::settle(&mut view).await; - assert_eq!( - view.visible_sections(), - &[ - Section::Summary, - Section::Credits, - Section::Usage, - Section::Plugins, - Section::Skills, - ] - ); - assert!(matches!(view.profile, Load::Error(_))); - for section in view.visible_sections() { - if section.report().is_some() { - assert!(view.sections[*section].history.ready().is_some()); - } - } - drop(failed_profile); - - let profile = json!({ - "profile":{"display_name":"Local account","username":"local-user"}, - "stats":{"lifetime_tokens":12345,"peak_daily_tokens":12345, - "daily_usage_buckets":[{"start_date":"2026-09-09","tokens":12345}]} - }); - Mock::given(method("GET")) - .and(wiremock::matchers::path("/backend-api/wham/profiles/me")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(profile.clone())) - .expect(/*r*/ 1) - .mount(&http) - .await; - view.refresh(); - crate::analytics::test_support::settle(&mut view).await; - assert_eq!( - view.profile.ready(), - Some(&serde_json::from_value(profile).unwrap()) - ); - for request in http.received_requests().await.unwrap() { - assert_eq!( - request.headers.get("chatgpt-account-id").unwrap(), - "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(); -} - -#[tokio::test] -async fn account_lookup_failure_recovers_on_refresh_with_the_server_plan() { - use crate::analytics::AnalyticsView; - use crate::analytics::data::Load; - use crate::analytics::sections::Section; - - let http = crate::analytics::test_support::server().await; - let (_home, local) = live(&http, "plus").await; - let (client, server) = remote().await; - Mock::given(method("GET")) - .and(wiremock::matchers::path("/backend-api/wham/accounts/check")) - .respond_with(ResponseTemplate::new(/*s*/ 503)) - .with_priority(/*p*/ 1) - .expect(/*r*/ 1) - .up_to_n_times(/*n*/ 1) - .mount(&http) - .await; - let mut view = AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list); - view.open( - AppServerRequestHandle::Remote(client.request_handle()), - crate::tui::FrameRequester::test_dummy(), - Vec::new(), - std::sync::Arc::clone(&local.config), - ); - crate::analytics::test_support::settle(&mut view).await; - assert!(matches!(view.account, Load::Error(_))); - assert_eq!( - http.received_requests() - .await - .unwrap() - .iter() - .map(|request| request.url.path()) - .collect::>(), - ["/backend-api/wham/accounts/check"] - ); - Mock::given(method("GET")) - .and(wiremock::matchers::path("/backend-api/wham/accounts/check")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "accounts": [{"id": "account-a", "plan_type": "enterprise"}] - }))) - .with_priority(/*p*/ 1) - .expect(/*r*/ 1) - .mount(&http) - .await; - Mock::given(method("GET")) - .and(wiremock::matchers::path("/backend-api/wham/profiles/me")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"stats": {}}))) - .mount(&http) - .await; - 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(), - &[ - Section::Summary, - Section::Credits, - Section::Usage, - Section::Plugins, - Section::Skills, - ] - ); - 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(); -} diff --git a/codex-rs/tui/src/analytics/consumer_refresh_tests.rs b/codex-rs/tui/src/analytics/consumer_refresh_tests.rs deleted file mode 100644 index 1ac1782e..00000000 --- a/codex-rs/tui/src/analytics/consumer_refresh_tests.rs +++ /dev/null @@ -1,138 +0,0 @@ -//! Consumer chat columns follow reported metrics without substituting billing estimates. -use super::*; -use crate::analytics::tasks::Chat; -use crate::analytics::tasks::Chats; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[test] -fn consumer_chats_keep_missing_rows_and_only_offer_known_metrics() { - let mut view = fixture::view(models::AccountKind::Consumer); - view.section = Section::Chats; - view.tasks = Load::Ready(Chats { - rows: vec![ - Chat { title: "Private title from another account".into(), task: None }, - Chat { title: "Unverified backend row".into(), task: Some(serde_json::from_value(json!({ - "thread_id":"unavailable", "data_status":"unavailable", "usage_source":"unknown", - "weekly_limit_percent":null,"five_hour_limit_percent":null,"balance_usage_credits":null,"groups":[] - })).unwrap()) }, - Chat { title: "Refunded task".into(), task: Some(serde_json::from_value(json!({ - "thread_id":"refund", "data_status":"partial", "usage_source":"credits", - "weekly_limit_percent":null,"five_hour_limit_percent":null,"balance_usage_credits":"-0.000004","groups":[{ - "product_experience":"codex", "model":"gpt-5.5", "reasoning_effort":"high", "speed":"fast", - "weekly_limit_percent":null,"five_hour_limit_percent":null,"balance_usage_credits":"-0.000004" - }] - })).unwrap()) }, - ], ..Chats::default() - }); - assert_eq!(view.task_metrics(), vec![2]); - assert_eq!( - view.task_rows() - .iter() - .map(|row| row.title.as_str()) - .collect::>(), - vec![ - "Refunded task", - "Private title from another account", - "Unverified backend row" - ] - ); - press(&mut view, KeyCode::Down); - press(&mut view, KeyCode::Enter); - assert_eq!(view.sections[Section::Chats].detail, None); - let hidden = screen(&mut view, /*width*/ 90, /*height*/ 30); - assert!(!hidden.contains("Private title") && !hidden.contains("Unverified backend row")); - press(&mut view, KeyCode::Up); - press(&mut view, KeyCode::Enter); - assert!(screen(&mut view, /*width*/ 90, /*height*/ 30).contains("-0.000004")); - let chats = match &mut view.tasks { - Load::Ready(chats) => chats, - _ => unreachable!(), - }; - chats.rows[2] - .task - .as_mut() - .unwrap() - .amounts - .five_hour_limit_percent = Some(0.0); - chats.rows[2] - .task - .as_mut() - .unwrap() - .amounts - .weekly_limit_percent = Some(125.0); - chats.rows.push(Chat { - title: "Plan-covered task".into(), - task: Some(serde_json::from_value(json!({ - "thread_id":"plan", "data_status":"available", "usage_source":"included_plan", - "weekly_limit_percent":12.1,"five_hour_limit_percent":null,"balance_usage_credits":"0E-10","groups":[] - })).unwrap()), - }); - for (raw, expected) in [ - ("0E-10", "0.00"), - ("0.0000000000", "0.00"), - ("-0e+10", "0.00"), - ("1e-1000", "1e-1000"), - ("-1e-1000", "-1e-1000"), - ("1e1000", "1e1000"), - ("12.3", "12.30"), - ("12.3400000000", "12.34"), - ("12.346", "12.35"), - ("2.675", "2.68"), - ("-2.675", "-2.68"), - ("1.005", "1.01"), - ("1.0049999999", "1.00"), - ("9.999", "10.00"), - ("0012.3", "12.30"), - ("1.23e2", "123.00"), - ("1234e-2", "12.34"), - ("9007199254740993", "9007199254740993"), - ("999999999999999999", "999999999999999999"), - ("141436", "141,436.00"), - ("0.01", "0.01"), - ("-0.000004", "-0.000004"), - ("1e-7", "1e-7"), - ] { - let amounts = serde_json::from_value(json!({"balance_usage_credits":raw})).unwrap(); - assert_eq!(task_panel::amount(Some(&amounts), /*metric*/ 2), expected); - } - assert_eq!(view.task_metrics(), vec![0, 1, 2]); - insta::assert_snapshot!( - "consumer_chat_all_metrics", - screen(&mut view, /*width*/ 110, /*height*/ 30) - ); - press(&mut view, KeyCode::Char('s')); - assert_eq!(view.task_metric(), 1); -} - -#[test] -fn consumer_chats_show_all_rows_and_collapse_details_before_closing() { - let mut view = fixture::view(models::AccountKind::Consumer); - view.section = Section::Chats; - view.tasks = Load::Ready(Chats { - rows: (0..6).map(|index| Chat { - title: format!("Task {index}"), - task: Some(serde_json::from_value(json!({ - "thread_id":format!("task-{index}"), "data_status":"available", "usage_source":"credits", - "balance_usage_credits":index.to_string(), "groups":[] - })).unwrap()), - }).collect(), - ..Chats::default() - }); - screen(&mut view, /*width*/ 120, /*height*/ 42); - press(&mut view, KeyCode::End); - press(&mut view, KeyCode::Enter); - assert_eq!(view.sections[Section::Chats].detail, Some(5)); - let content = view - .task_lines(/*width*/ 70) - .0 - .iter() - .map(|line| line.to_string().trim_end().to_owned()) - .collect::>() - .join("\n"); - assert!(content.contains("Task 5") && content.contains("Task 0")); - press(&mut view, KeyCode::Esc); - assert!(!view.is_done); - press(&mut view, KeyCode::Esc); - assert!(view.is_done); -} diff --git a/codex-rs/tui/src/analytics/controls.rs b/codex-rs/tui/src/analytics/controls.rs deleted file mode 100644 index c56f9efc..00000000 --- a/codex-rs/tui/src/analytics/controls.rs +++ /dev/null @@ -1,292 +0,0 @@ -//! Visible report controls and update times. Mouse targets and keyboard shortcuts invoke the same semantic actions. -//! Their reserved rows depend only on terminal width, so loading never shifts the report body. - -use super::AnalyticsView; -use super::sections::Section; -use super::styles::secondary_style; -use crate::key_hint; -use crate::line_truncation::truncate_line_with_ellipsis_if_overflow as truncate; -use crate::style::accent_style; -use chrono::Datelike; -use crossterm::event::KeyCode; -use ratatui::buffer::Buffer; -use ratatui::layout::Rect; -use ratatui::style::Styled; -use ratatui::style::Stylize; -use ratatui::text::Line; -use ratatui::widgets::Widget; - -/// A mouse action is independent of a user's remapped or disabled arrow bindings. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Control { - Range, - Group, - Model, - TaskMetric, - Dashboard, - PlanWindow, - ZeroCreditGroups, -} - -impl AnalyticsView { - /// Share action eligibility between painted controls, keyboard dispatch and help. - pub(super) fn control_available(&self, control: Control) -> bool { - if self.visible_sections().is_empty() { - return false; - } - match control { - Control::Range => self.section.report().is_some(), - Control::Group => self.group_options().len() > 1, - Control::Model => self.section == Section::Usage && self.business(), - Control::TaskMetric => self.section == Section::Chats && !self.business(), - Control::Dashboard => true, - Control::PlanWindow => self.section == Section::Plan, - Control::ZeroCreditGroups => { - self.section == Section::Chats - && self.business() - && self.sections[Section::Chats].detail.is_some() - } - } - } - - /// Apply a visible report action without synthesizing a remappable keyboard event. - pub(super) fn activate_control(&mut self, control: Control) { - if !self.control_available(control) { - return; - } - // Labels can change width; wait for their new painted positions before another click. - self.invalidate_mouse_targets(); - match control { - Control::ZeroCreditGroups => { - self.show_zero_credit_groups = !self.show_zero_credit_groups - } - Control::Range => self.change_range(), - Control::Dashboard => self.toggle_dashboard(), - Control::PlanWindow => { - self.plan_action(Some(crate::keymap::ListAction::MoveRight)); - self.follow_selection = true; - } - Control::Model => { - let models = self - .live - .as_ref() - .map_or_else(Vec::new, |live| live.token_models()); - self.token_model = match self - .token_model - .as_ref() - .and_then(|model| models.iter().position(|candidate| candidate == model)) - { - Some(index) => models.get(index + 1).cloned(), - None => models.first().cloned(), - }; - self.load_report(Section::Usage); - } - Control::Group => { - let options = self.group_options(); - let next = options - .iter() - .position(|group| *group == self.sections[self.section].group) - .map_or(/*default*/ 0, |index| (index + 1) % options.len()); - self.sections[self.section].group = options[next]; - self.load_report(self.section); - } - Control::TaskMetric => { - let metrics = self.task_metrics(); - let index = metrics - .iter() - .position(|metric| *metric == self.task_metric()) - .unwrap_or_default(); - self.chat_metric = metrics[(index + 1) % metrics.len()]; - self.sections[Section::Chats].detail = None; - } - } - } - - pub(super) fn render_controls(&mut self, area: Rect, buf: &mut Buffer) { - self.control_hits.clear(); - if area.is_empty() { - return; - } - if self.show_help { - "Usage shortcuts".bold().render(area, buf); - return; - } - if self.visible_sections().is_empty() { - return; - } - let width = usize::from(area.width); - let mut rows = vec![Vec::new(), Vec::new()]; - let report = self.control_available(Control::Range); - if report { - let range = self.ranges[self.range_group(self.section) as usize]; - let dates = self.section_date_range(self.section); - let interval = if dates.start().year() != dates.end().year() && width < 50 { - format!( - "{}–{}", - dates.start().format("%m/%d/%Y"), - dates.end().format("%m/%d/%Y") - ) - } else if dates.start().year() == dates.end().year() { - format!( - "{}–{}", - dates.start().format("%b %-d"), - dates.end().format("%b %-d, %Y") - ) - } else { - format!( - "{}–{}", - dates.start().format("%b %-d, %Y"), - dates.end().format("%b %-d, %Y") - ) - }; - rows[0].push(( - Control::Range, - Line::from(vec![ - key_hint::plain(KeyCode::Char('r')).into(), - " ".dim(), - if range == 0 { - "7d".set_style(accent_style()).bold() - } else { - "7d".dim() - }, - "/".dim(), - if range == 1 { - "30d".set_style(accent_style()).bold() - } else { - "30d".dim() - }, - format!(" · {interval}").into(), - ]), - )); - } - let option_row = usize::from(width < 100 && report); - if self.control_available(Control::Group) { - rows[option_row].push(( - Control::Group, - Line::from(vec![ - key_hint::plain(KeyCode::Char('g')).into(), - " ".dim(), - self.group_label(self.section, self.sections[self.section].group) - .to_owned() - .into(), - ]), - )); - } - if self.control_available(Control::Model) { - rows[option_row].push(( - Control::Model, - Line::from(vec![ - key_hint::plain(KeyCode::Char('m')).into(), - " ".dim(), - self.token_model - .clone() - .unwrap_or_else(|| "All models".into()) - .into(), - ]), - )); - } - if self.control_available(Control::TaskMetric) { - rows[0].push(( - Control::TaskMetric, - Line::from(vec![ - key_hint::plain(KeyCode::Char('s')).into(), - " sort: ".dim(), - super::task_panel::METRICS[self.task_metric()].into(), - ]), - )); - } - if self.control_available(Control::PlanWindow) { - let row = usize::from(width < 100); - let hints = [ - crate::keymap::ListAction::MoveLeft, - crate::keymap::ListAction::MoveRight, - ] - .into_iter() - .filter_map(|action| self.keymap.primary_hint(action)) - .map(key_hint::ShortcutHint::display_label) - .collect::>() - .join("/"); - let mut plan_window = Line::default(); - if !hints.is_empty() { - plan_window.spans = key_hint::key_label_spans(&format!("{hints} ")); - } - plan_window.spans.extend([ - if self.plan.window == 0 { - "5-hour".set_style(accent_style()).bold() - } else { - "5-hour".dim() - }, - " / ".dim(), - if self.plan.window == 1 { - "Weekly".set_style(accent_style()).bold() - } else { - "Weekly".dim() - }, - ]); - rows[row].push((Control::PlanWindow, plan_window)); - } - if !self.zoomed { - let mut dashboard = Line::from("Dashboard".bold()); - if let Some(hint) = self.keymap.primary_hint(crate::keymap::ListAction::Accept) { - dashboard.spans.push(" · ".dim()); - dashboard.spans.extend(hint.spans()); - dashboard.spans.push(" focus".dim()); - } - rows[0].insert(/*index*/ 0, (Control::Dashboard, dashboard)); - } - for (row, controls) in rows - .into_iter() - .enumerate() - .take(usize::from(area.height.saturating_sub(/*rhs*/ 1))) - { - let mut x = area.x; - for (key, line) in controls { - if x > area.x { - " · ".dim().render( - Rect::new( - x, - area.y + row as u16, - area.right().saturating_sub(x).min(/*other*/ 3), - /*height*/ 1, - ), - buf, - ); - x = x.saturating_add(/*rhs*/ 3); - } - let remaining = area.right().saturating_sub(x); - if remaining == 0 { - break; - } - let line = truncate(line, usize::from(remaining)); - let hit = Rect::new( - x, - area.y + row as u16, - line.width() as u16, - /*height*/ 1, - ); - line.render(hit, buf); - if !hit.is_empty() { - self.control_hits.push((key, hit)); - } - x = hit.right(); - } - } - let updated = self.sections[self.section] - .history - .ready() - .and_then(|report| report.updated_at) - .and_then(|value| chrono::DateTime::from_timestamp(value, /*nsecs*/ 0)); - let metadata = updated - .map(|updated| { - format!( - "Updated · {} UTC", - updated.format(self.clock_format.date_time_format()) - ) - }) - .unwrap_or_default(); - truncate(metadata.set_style(secondary_style()).into(), width).render( - Rect::new(area.x, area.bottom() - 1, area.width, /*height*/ 1), - buf, - ); - } -} diff --git a/codex-rs/tui/src/analytics/dashboard.rs b/codex-rs/tui/src/analytics/dashboard.rs deleted file mode 100644 index 94201765..00000000 --- a/codex-rs/tui/src/analytics/dashboard.rs +++ /dev/null @@ -1,221 +0,0 @@ -//! Bordered, aligned overview cards. Detailed reports remain in maximized mode. -//! Card heights depend on the viewport, never on the selected day or load state. - -use super::AnalyticsView; -use super::data; -use super::render::columns; -use super::render::join_columns; -use super::styles::number; -use super::styles::secondary_style; -use crate::analytics::sections::Section; -use crate::line_truncation::truncate_line_with_ellipsis_if_overflow as truncate; -use crate::style::accent_style; -use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_lines; -use ratatui::style::Styled; -use ratatui::style::Stylize; -use ratatui::text::Line; -use std::ops::Range; - -impl AnalyticsView { - pub(super) fn dashboard_lines( - &self, - width: usize, - height: usize, - ) -> (Vec>, Range) { - let count = if width >= 104 { 2 } else { 1 }; - let card_width = if count == 2 { (width - 4) / 2 } else { width }; - let visible = self.visible_sections(); - let rows = visible.len().div_ceil(count).max(/*other*/ 1); - let card_height = - (height.saturating_sub(/*rhs*/ 2) / rows).clamp(/*min*/ 16, /*max*/ 24); - let inner_width = card_width.saturating_sub(/*rhs*/ 4).max(/*other*/ 1); - let inner_height = card_height - 4; - let mut lines = Vec::new(); - let mut selected = 0..0; - for (row, chunk) in visible.chunks(count).enumerate() { - let mut cards = Vec::new(); - for (column, section) in chunk.iter().copied().enumerate() { - let focused = self.section == section; - let border = if focused { - accent_style() - } else { - secondary_style().dim() - }; - let mut content = Vec::new(); - if !matches!(section, Section::Chats | Section::Plan | Section::Summary) { - content.push( - format!( - "{}d{}", - if self.ranges[self.range_group(section) as usize] == 0 { - 7 - } else { - 30 - }, - if section == Section::Usage && self.business() { - format!( - " · {}", - self.token_model.as_deref().unwrap_or("All models") - ) - } else { - String::new() - } - ) - .set_style(secondary_style()) - .into(), - ); - } - if matches!( - section, - Section::Usage | Section::Credits | Section::Activity | Section::Plan - ) { - content.push( - format!( - "By {}", - self.group_label(section, self.sections[section].group) - .to_lowercase() - ) - .set_style(secondary_style()) - .into(), - ); - } - match section { - Section::Summary => content.extend(self.summary_lines(inner_width)), - Section::Usage - | Section::Plugins - | Section::Credits - | Section::Activity - | Section::Skills => content.extend( - self.history_lines( - section, - inner_width, - inner_height.saturating_sub(/*rhs*/ 13).max(/*other*/ 1), - ) - .lines, - ), - Section::Plan => content.extend(self.plan_lines(inner_width).0), - Section::Chats if !self.business() => { - content.extend(self.task_lines(inner_width).0) - } - Section::Chats => { - content.push( - "30d active · lifetime credits" - .set_style(secondary_style()) - .into(), - ); - content.push(Line::default()); - if let Some(chats) = self.chats.ready() { - if chats.rows.is_empty() { - content.push( - "No recent local chats.".set_style(secondary_style()).into(), - ); - } - for chat in chats.rows.iter().take(/*n*/ 5) { - let amount = chat - .usage - .as_ref() - .map(|usage| { - data::credits(usage.estimated_usage_credits_micros) - }) - .unwrap_or_else(|| "—".into()); - content.push(columns( - truncate( - chat.display_title().to_string().into(), - inner_width.saturating_sub(amount.len() + 1), - ), - number(amount).into(), - inner_width, - )); - } - content.push(Line::default()); - content.push( - "Local chats · excludes subagents" - .set_style(secondary_style()) - .into(), - ); - if chats.rows.iter().any(|chat| chat.usage.is_none()) { - content.push( - "Some estimates unavailable" - .set_style(secondary_style()) - .into(), - ); - } - } else if let Some(message) = self.chats.message() { - content.push(message.to_string().set_style(secondary_style()).into()); - } - } - } - let mut content = word_wrap_lines(content, RtOptions::new(inner_width)); - if content.len() > inner_height { - content.truncate(inner_height); - content[inner_height - 1] = - "… z to maximize".set_style(secondary_style()).into(); - } - content.resize(inner_height, Line::default()); - let label = format!(" {} {} ", row * count + column + 1, self.tab_label(section)); - let title = truncate( - Line::from(vec![ - " ".into(), - if focused { - "▸".set_style(accent_style()) - } else { - " ".into() - }, - if focused { - label.bold() - } else { - label.set_style(secondary_style()) - }, - ]), - card_width.saturating_sub(/*rhs*/ 3), - ); - let mut top = vec!["╭─".set_style(border)]; - top.extend(title.spans.iter().cloned()); - top.push( - "─" - .repeat(card_width.saturating_sub(title.width() + 3)) - .set_style(border), - ); - top.push("╮".set_style(border)); - let blank = columns( - "│".set_style(border).into(), - "│".set_style(border).into(), - card_width, - ); - let mut card = vec![Line::from(top), blank.clone()]; - card.extend(content.into_iter().map(|line| { - let line = truncate(line, inner_width); - let padding = card_width.saturating_sub(line.width() + 3); - let mut padded = vec!["│".set_style(border), " ".into()]; - padded.extend(line.spans); - padded.push(" ".repeat(padding).into()); - padded.push("│".set_style(border)); - Line::from(padded) - })); - card.push(blank); - card.push( - format!("╰{}╯", "─".repeat(card_width.saturating_sub(/*rhs*/ 2))) - .set_style(border) - .into(), - ); - cards.push( - card.into_iter() - .map(|line| truncate(line, card_width)) - .collect::>(), - ); - } - if chunk.contains(&self.section) { - selected = lines.len()..lines.len() + card_height; - } - lines.extend(if cards.len() == 2 { - join_columns(&cards[0], &cards[1], card_width) - } else { - cards.remove(/*index*/ 0) - }); - if (row + 1) * count < visible.len() { - lines.push(Line::default()); - } - } - (lines, selected) - } -} diff --git a/codex-rs/tui/src/analytics/dashboard_tests.rs b/codex-rs/tui/src/analytics/dashboard_tests.rs deleted file mode 100644 index fe0c47e6..00000000 --- a/codex-rs/tui/src/analytics/dashboard_tests.rs +++ /dev/null @@ -1,99 +0,0 @@ -//! Overview cards retain alignment and geometry while selection and report states change. -use super::*; -use crate::style::accent_style; -use pretty_assertions::assert_eq; -use ratatui::style::Modifier; - -use crate::analytics::sections::Section; -#[test] -fn dashboard_focus_uses_marker_and_default_foreground_title() { - let mut view = fixture::view(models::AccountKind::Consumer); - view.zoomed = false; - for section in [Section::Usage, Section::Activity] { - view.section = section; - let (lines, _) = view.dashboard_lines(/*width*/ 140, /*height*/ 56); - let title = lines - .iter() - .find(|line| line.spans.iter().any(|span| span.content == "▸")) - .unwrap(); - let marker = title.spans.iter().find(|span| span.content == "▸").unwrap(); - assert_eq!(marker.style, accent_style()); - let focused_title = title - .spans - .iter() - .find(|span| span.content.contains(view.tab_label(section))) - .unwrap(); - assert_eq!(focused_title.style.fg, None); - assert!(focused_title.style.add_modifier.contains(Modifier::BOLD)); - assert_eq!(title.to_string().matches('▸').count(), 1); - } -} - -#[test] -fn dashboard_cards_align_and_keep_stable_summary_heights() { - let mut view = fixture::view(models::AccountKind::Consumer); - press(&mut view, KeyCode::Char('z')); - let wide = screen(&mut view, /*width*/ 144, /*height*/ 64); - for (left, right) in [ - ("1 Overview", "2 Usage"), - ("3 Messages", "4 Plugins"), - ("5 Skills", "6 Chats"), - ] { - assert!( - wide.lines() - .any(|line| line.contains(left) && line.contains(right)) - ); - } - assert!(!wide.contains("Coverage from")); - let before = view.dashboard_lines(/*width*/ 140, /*height*/ 56); - press(&mut view, KeyCode::Left); - view.sections[Section::Plugins].history = Load::Error("Access denied for this report.".into()); - let after = view.dashboard_lines(/*width*/ 140, /*height*/ 56); - assert_eq!((before.0.len(), before.1), (after.0.len(), after.1)); - let edges = |lines: &[ratatui::text::Line<'_>]| { - lines - .iter() - .enumerate() - .filter(|(_, line)| line.to_string().starts_with(['╭', '╰'])) - .map(|(index, _)| index) - .collect::>() - }; - assert_eq!(edges(&before.0), edges(&after.0)); - for width in [1, 4, 40, 100, 140] { - assert!( - view.dashboard_lines(width, /*height*/ 56) - .0 - .iter() - .all(|line| line.width() <= width) - ); - } - let narrow = screen(&mut view, /*width*/ 72, /*height*/ 48); - assert!(narrow.contains("1 Overview")); - let context = ( - view.section, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections.0.each_ref().map(|state| state.group), - ); - press(&mut view, KeyCode::Enter); - assert!(view.zoomed); - assert_eq!( - context, - ( - view.section, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections.0.each_ref().map(|state| state.group) - ) - ); - insta::assert_snapshot!(format!("{wide}\n{narrow}")); -} - -#[test] -fn overview_closes_on_escape_with_retained_day_details() { - let mut view = fixture::view(models::AccountKind::Consumer); - press(&mut view, KeyCode::Enter); - assert_eq!(view.sections[Section::Usage].detail, Some(6)); - press(&mut view, KeyCode::Char('z')); - assert!(!view.zoomed); - press(&mut view, KeyCode::Esc); - assert!(view.is_done); -} diff --git a/codex-rs/tui/src/analytics/data.rs b/codex-rs/tui/src/analytics/data.rs deleted file mode 100644 index 76065d60..00000000 --- a/codex-rs/tui/src/analytics/data.rs +++ /dev/null @@ -1,210 +0,0 @@ -//! Report loading and grouping metadata for the account dashboard. -//! Replacing a pending load aborts it; its response cannot populate a newer range or account. - -use super::models::AccountAnalyticsGrouping as Grouping; -use crate::tui::FrameRequester; -use futures::FutureExt; -use std::panic::AssertUnwindSafe; -use tokio::sync::oneshot; -use tokio::task::JoinHandle; - -pub(super) const GROUPINGS: [Grouping; 7] = [ - Grouping::Surface, - Grouping::Feature, - Grouping::Model, - Grouping::TaskStart, - Grouping::Speed, - Grouping::Reasoning, - Grouping::TokenType, -]; - -pub(super) const GROUP_LABELS: [&str; 7] = [ - "Surface", - "Feature", - "Model", - "Turn start", - "Speed", - "Reasoning", - "Token type", -]; - -pub(super) struct Pending { - receiver: oneshot::Receiver, String>>, - task: JoinHandle<()>, -} - -impl Drop for Pending { - fn drop(&mut self) { - self.task.abort(); - } -} - -pub(super) enum Load { - Loading(Pending), - Ready(T), - Unavailable, - Error(String), -} - -impl Load { - pub(super) fn start( - future: impl std::future::Future, String>> + Send + 'static, - frame: FrameRequester, - ) -> Self { - Self::start_with_timeout(future, frame, std::time::Duration::from_secs(/*secs*/ 30)) - } - - pub(super) fn start_with_timeout( - future: impl std::future::Future, String>> + Send + 'static, - frame: FrameRequester, - timeout: std::time::Duration, - ) -> Self { - let (sender, receiver) = oneshot::channel(); - let task = - tokio::spawn(async move { - let result = - match tokio::time::timeout(timeout, AssertUnwindSafe(future).catch_unwind()) - .await - { - Ok(Ok(result)) => result, - Ok(Err(_)) => Err("Request interrupted. Press R to retry.".into()), - Err(_) => Err("Request timed out. Press R to retry.".into()), - }; - let _ = sender.send(result); - frame.schedule_frame(); - }); - Self::Loading(Pending { receiver, task }) - } - - pub(super) fn poll(&mut self) { - if let Self::Loading(pending) = self { - *self = match pending.receiver.try_recv() { - Ok(Ok(Some(data))) => Self::Ready(data), - Ok(Ok(None)) => Self::Unavailable, - Ok(Err(message)) => Self::Error(message), - Err(oneshot::error::TryRecvError::Closed) => { - Self::Error("Request interrupted. Press R to retry.".into()) - } - Err(oneshot::error::TryRecvError::Empty) => return, - }; - } - } - - pub(super) fn ready(&self) -> Option<&T> { - if let Self::Ready(value) = self { - Some(value) - } else { - None - } - } - - pub(super) fn message(&self) -> Option<&str> { - match self { - Self::Ready(_) => None, - Self::Loading(_) => Some("Loading…"), - Self::Unavailable => Some("No history has been reported."), - Self::Error(message) => Some(message), - } - } -} - -/// Keep untyped server and transport diagnostics out of account reports. -pub(super) fn error(_error: codex_app_server_client::TypedRequestError) -> String { - "Couldn't load analytics. Press R to retry.".into() -} - -/// Keep tiny refunds visible while avoiding noise on ordinary credit amounts. -pub(super) fn amount(value: f64) -> String { - if value == 0.0 { - return "0".into(); - } - if value.abs() < 0.000001 { - return format!("{value:.2e}"); - } - let rounded = if value.abs() < 0.01 { - format!("{value:.6}") - } else { - format!("{value:.2}") - }; - let (whole, fraction) = rounded.split_once('.').unwrap_or((&rounded, "")); - let mut grouped = String::new(); - for (index, ch) in whole.chars().enumerate() { - if index > 0 - && ch.is_ascii_digit() - && (whole.len() - index).is_multiple_of(/*rhs*/ 3) - && !grouped.ends_with('-') - { - grouped.push(','); - } - grouped.push(ch); - } - let fraction = fraction.trim_end_matches('0'); - if !fraction.is_empty() { - grouped.push('.'); - grouped.push_str(fraction); - } - grouped -} - -/// Compact headline and axis labels to one decimal, preserving small signed adjustments. -pub(super) fn compact_amount(value: f64) -> String { - if value.abs() < 1_000.0 || !value.is_finite() { - return amount(value); - } - let units = ["K", "M", "B", "T"]; - let mut scaled = value / 1_000.0; - let mut unit = 0; - // Promote before rounding would produce a label such as 1000K. - while scaled.abs() >= 999.95 && unit + 1 < units.len() { - scaled /= 1_000.0; - unit += 1; - } - let rounded = format!("{:.1}", (scaled * 10.0).round() / 10.0); - format!( - "{}{}", - rounded.trim_end_matches('0').trim_end_matches('.'), - units[unit] - ) -} - -/// Align ordinary credit amounts to two decimals without hiding tiny adjustments. -pub(super) fn credit_amount(value: f64) -> String { - let formatted = amount(value); - if value != 0.0 && value.abs() < 0.01 { - return formatted; - } - match formatted.split_once('.') { - None => format!("{formatted}.00"), - Some((_, fraction)) if fraction.len() == 1 => format!("{formatted}0"), - Some(_) => formatted, - } -} - -pub(super) fn credits(micros: i64) -> String { - let magnitude = micros.unsigned_abs(); - if magnitude > 0 && magnitude < 10_000 { - let fractional = format!("{magnitude:06}"); - return format!( - "{}0.{}", - if micros < 0 { "-" } else { "" }, - fractional.trim_end_matches('0') - ); - } - let cents = (magnitude + 5_000) / 10_000; - let mut whole = (cents / 100).to_string(); - let digits = whole.len(); - for index in (1..digits).rev() { - if (digits - index).is_multiple_of(/*rhs*/ 3) { - whole.insert(index, ','); - } - } - format!( - "{}{whole}.{:02}", - if micros < 0 { "-" } else { "" }, - cents % 100 - ) -} - -#[cfg(test)] -#[path = "data_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/data_tests.rs b/codex-rs/tui/src/analytics/data_tests.rs deleted file mode 100644 index 133f5444..00000000 --- a/codex-rs/tui/src/analytics/data_tests.rs +++ /dev/null @@ -1,132 +0,0 @@ -//! Loading transitions and cancellation when a view replaces pending work. - -use super::*; -use pretty_assertions::assert_eq; - -#[tokio::test] -async fn completed_loads_publish_data_unavailability_and_errors() { - for (result, expected) in [ - (Ok(Some(7)), (Some(7), None)), - (Ok(None), (None, Some("No history has been reported."))), - ( - Err("temporary failure".to_string()), - (None, Some("temporary failure")), - ), - ] { - let mut load = Load::start(async move { result }, FrameRequester::test_dummy()); - let Load::Loading(pending) = &mut load else { - unreachable!() - }; - (&mut pending.task).await.unwrap(); - load.poll(); - assert_eq!((load.ready().copied(), load.message()), expected); - } -} - -#[tokio::test] -async fn replacing_a_pending_load_cancels_its_request() { - let (cancelled_tx, cancelled_rx) = oneshot::channel::<()>(); - let load = Load::<()>::start( - async move { - let _cancelled = cancelled_tx; - std::future::pending().await - }, - FrameRequester::test_dummy(), - ); - tokio::task::yield_now().await; - drop(load); - assert!(cancelled_rx.await.is_err()); -} - -#[tokio::test] -async fn panicking_loads_request_a_frame_and_report_interruption() { - let (draw, mut frames) = tokio::sync::broadcast::channel(/*capacity*/ 1); - let frame = FrameRequester::new(draw); - let mut load = Load::<()>::start(async { panic!("report task failed") }, frame.clone()); - let Load::Loading(pending) = &mut load else { - unreachable!() - }; - let _ = (&mut pending.task).await; - tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 1), frames.recv()) - .await - .unwrap() - .unwrap(); - load.poll(); - assert_eq!( - load.message(), - Some("Request interrupted. Press R to retry.") - ); -} - -#[test] -fn rpc_errors_do_not_expose_server_diagnostics() { - let error = codex_app_server_client::TypedRequestError::Server { - method: "thread/list".into(), - source: codex_app_server_protocol::JSONRPCErrorError { - code: -32603, - message: "Failed opening /private/workspace: token=secret".into(), - data: Some(serde_json::json!({"credential": "secret"})), - }, - }; - assert_eq!( - super::error(error), - "Couldn't load analytics. Press R to retry." - ); -} - -#[tokio::test(start_paused = true)] -async fn extended_chat_load_budget_still_times_out_and_can_be_cancelled() { - let (cancelled_tx, cancelled_rx) = oneshot::channel::<()>(); - let mut load = Load::<()>::start_with_timeout( - async move { - let _cancelled = cancelled_tx; - std::future::pending().await - }, - FrameRequester::test_dummy(), - std::time::Duration::from_secs(/*secs*/ 90), - ); - tokio::task::yield_now().await; - tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 31)).await; - load.poll(); - assert!(matches!(load, Load::Loading(_))); - tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 60)).await; - assert!(cancelled_rx.await.is_err()); - load.poll(); - assert_eq!(load.message(), Some("Request timed out. Press R to retry.")); -} - -#[test] -fn compact_counts_round_promote_units_and_preserve_small_adjustments() { - let values = [ - 0.0, - 959.0, - 1_000.0, - 9_749.0, - 2_901.0, - 12_280_365_226.0, - 142_300_000_000.0, - 999_999.0, - 999_999_999.0, - -1_250.0, - -0.000004, - 1_200_000_000_000.0, - ]; - assert_eq!( - values.map(compact_amount), - [ - "0", - "959", - "1K", - "9.7K", - "2.9K", - "12.3B", - "142.3B", - "1M", - "1B", - "-1.3K", - "-0.000004", - "1.2T" - ] - .map(str::to_string) - ); -} diff --git a/codex-rs/tui/src/analytics/hints.rs b/codex-rs/tui/src/analytics/hints.rs deleted file mode 100644 index f84e4720..00000000 --- a/codex-rs/tui/src/analytics/hints.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Two fixed hint rows keep report actions visible without changing chart geometry. - -use super::AnalyticsView; -use super::sections::Section; -use crate::key_hint::key_label_spans; -use crate::keymap::ListAction; -use ratatui::style::Stylize; -use ratatui::text::Line; - -impl AnalyticsView { - pub(super) fn footer_lines(&self, width: usize, scrollable: bool) -> Vec> { - let pair = |a, b| format!("{}/{}", self.hint(a), self.hint(b)); - let mut actions = Vec::new(); - if self.show_help { - actions.push((self.hint(ListAction::Cancel), "back")); - } else if !self.zoomed { - actions.push((self.hint(ListAction::Accept), "focus")); - actions.push(("tab".into(), "card")); - } else { - match self.section { - Section::Summary => {} - Section::Plan => { - actions.push((pair(ListAction::MoveUp, ListAction::MoveDown), "period")); - } - Section::Chats => { - actions.push((pair(ListAction::MoveUp, ListAction::MoveDown), "row")); - } - Section::Usage - | Section::Credits - | Section::Activity - | Section::Plugins - | Section::Skills => { - actions.push((pair(ListAction::MoveLeft, ListAction::MoveRight), "day")); - } - } - let plan_details = self.section == Section::Plan - && self - .plan - .report - .ready() - .and_then(|report| { - report.periods[self.plan.window].get(self.plan.cursor[self.plan.window]) - }) - .is_some(); - if plan_details - || self.day_has_details(self.section, self.sections[self.section].cursor) - || (self.section == Section::Chats && self.chat_has_details()) - { - actions.push((self.hint(ListAction::Accept), "details")); - } - } - if scrollable { - actions.push((pair(ListAction::PageUp, ListAction::PageDown), "scroll")); - } - if !self.show_help { - actions.push((self.hint(ListAction::Cancel), "back")); - } - let mut navigation = if self.show_help { - vec![("?".into(), "close help")] - } else if self.visible_sections().is_empty() { - vec![("R".into(), "retry")] - } else { - vec![ - ( - if width >= 80 { - format!("tab/1–{}", self.visible_sections().len()) - } else { - "tab".into() - }, - "report", - ), - ( - "z".into(), - if !self.zoomed { - "focus" - } else if width < 50 { - "all" - } else { - "dashboard" - }, - ), - ("?".into(), if width < 50 { "" } else { "help" }), - ("R".into(), "refresh"), - ] - }; - if !self.help_shortcut_available() { - navigation.retain(|(key, _)| key != "?"); - } - [actions, navigation] - .into_iter() - .map(|hints| { - let mut line = Line::default(); - for (key, label) in hints { - if key.is_empty() { - continue; - } - let separator = if line.spans.is_empty() { "" } else { " · " }; - let mut part = Line::from(separator.dim()); - part.spans.extend(key_label_spans(&key)); - if !label.is_empty() { - part.spans.push(format!(" {label}").dim()); - } - if line.width() + part.width() <= width { - line.spans.extend(part.spans); - } - } - line - }) - .collect() - } -} diff --git a/codex-rs/tui/src/analytics/models.rs b/codex-rs/tui/src/analytics/models.rs deleted file mode 100644 index 2cab6892..00000000 --- a/codex-rs/tui/src/analytics/models.rs +++ /dev/null @@ -1,100 +0,0 @@ -//! Private analytics display types, independent of the app-server wire protocol. - -use codex_protocol::account::PlanType; - -/// Billing families match the App's consumer, business, and workspace scopes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum AccountKind { - Consumer, - Business, - Enterprise, - Unknown, -} - -impl From> for AccountKind { - fn from(plan: Option) -> Self { - match plan { - None | Some(PlanType::Unknown) => Self::Unknown, - Some(PlanType::Sci | PlanType::SciPlus) => Self::Business, - Some(plan) if plan.is_team_like() => Self::Business, - Some(plan) if plan.is_workspace_account() => Self::Enterprise, - Some(_) => Self::Consumer, - } - } -} - -/// Match the existing CLI thread-usage capability without widening other workspace reports. -pub(super) fn thread_usage_supported(plan: Option) -> bool { - matches!( - plan, - Some( - PlanType::Business - | PlanType::EnterpriseCbpUsageBased - | PlanType::EnterpriseCbpAutomation - ) - ) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum AccountAnalyticsReport { - Usage, - Credits, - Messages, - Plugins, - Skills, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum AccountAnalyticsGrouping { - Feature, - Model, - Surface, - TaskStart, - Speed, - Reasoning, - TokenType, -} - -impl AccountAnalyticsGrouping { - /// Credit breakdowns supported by the account's billing report. - pub(crate) fn credit_groupings(plan: Option) -> &'static [Self] { - match AccountKind::from(plan) { - AccountKind::Business => &[Self::Surface, Self::Model, Self::Speed], - AccountKind::Enterprise => &[Self::Surface, Self::Model, Self::Speed, Self::Reasoning], - AccountKind::Consumer => &[Self::Surface], - AccountKind::Unknown => &[], - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum AccountAnalyticsUnit { - RelativeUsage, - Credits, - Count, - Tokens, -} - -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct AccountAnalyticsHistory { - pub(crate) unit: AccountAnalyticsUnit, - /// Source freshness in Unix seconds, when provided. Not a completeness watermark. - pub(crate) updated_at: Option, - pub(crate) data: Vec, -} - -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct AccountAnalyticsDay { - /// Source reporting date; display formatting belongs to the UI. - pub(crate) date: chrono::NaiveDate, - /// Full daily denominator, including non-task usage when grouped by task start. - pub(crate) total: f64, - pub(crate) values: Vec, -} - -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct AccountAnalyticsValue { - pub(crate) key: String, - pub(crate) label: String, - pub(crate) value: f64, -} diff --git a/codex-rs/tui/src/analytics/mouse.rs b/codex-rs/tui/src/analytics/mouse.rs deleted file mode 100644 index f288211c..00000000 --- a/codex-rs/tui/src/analytics/mouse.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Mouse actions use the most recently painted Usage layout and semantic report controls. -//! Wheel input belongs only to the body, with bounded independent report/help/dashboard offsets. - -use super::AnalyticsView; -use crossterm::event::MouseButton; -use crossterm::event::MouseEvent; -use crossterm::event::MouseEventKind; -use ratatui::layout::Position; - -impl AnalyticsView { - pub(super) fn invalidate_mouse_targets(&mut self) { - self.mouse_context = None; - self.tab_hits.clear(); - self.control_hits.clear(); - } - - pub(super) fn handle_mouse(&mut self, event: MouseEvent) { - // A report/help/dashboard transition can happen before its scheduled redraw. Old - // rectangles must not activate controls belonging to the surface being replaced. - if self.mouse_context != Some((self.section, self.show_help, self.zoomed)) { - return; - } - let point = Position::new(event.column, event.row); - match event.kind { - MouseEventKind::ScrollDown | MouseEventKind::ScrollUp - if self.body_area.contains(point) => - { - let offset = self.scroll_offset().min(self.max_scroll); - *self.scroll_offset_mut() = match event.kind { - MouseEventKind::ScrollDown => { - offset.saturating_add(/*rhs*/ 3).min(self.max_scroll) - } - _ => offset.saturating_sub(/*rhs*/ 3), - }; - self.follow_selection = false; - } - MouseEventKind::Down(MouseButton::Left) => { - if let Some((section, _)) = - self.tab_hits.iter().find(|(_, rect)| rect.contains(point)) - { - self.select_section(*section); - } else if let Some((control, _)) = self - .control_hits - .iter() - .find(|(_, rect)| rect.contains(point)) - { - let control = *control; - self.follow_selection = false; - self.activate_control(control); - } - } - _ => {} - } - } -} diff --git a/codex-rs/tui/src/analytics/mouse_tests.rs b/codex-rs/tui/src/analytics/mouse_tests.rs deleted file mode 100644 index 09fd7063..00000000 --- a/codex-rs/tui/src/analytics/mouse_tests.rs +++ /dev/null @@ -1,171 +0,0 @@ -//! Mouse routing, painted control bounds, and scrolling across retained report surfaces. - -use super::*; -use crate::analytics::controls::Control; -use codex_config::types::KeybindingSpec; -use codex_config::types::KeybindingsSpec; -use codex_config::types::TuiKeymap; -use crossterm::event::MouseButton; -use crossterm::event::MouseEvent; -use crossterm::event::MouseEventKind; -use pretty_assertions::assert_eq; -use ratatui::layout::Rect; - -fn mouse_at(view: &mut AnalyticsView, kind: MouseEventKind, area: Rect) { - view.handle_mouse(MouseEvent { - kind, - column: area.x, - row: area.y, - modifiers: KeyModifiers::NONE, - }); -} - -#[tokio::test] -async fn mouse_routing_keeps_clipped_tabs_and_refresh_targets_account_scoped() { - let mut view = fixture::view(models::AccountKind::Consumer); - screen(&mut view, /*width*/ 100, /*height*/ 24); - let (_, tab) = view - .tab_hits - .iter() - .find(|(section, _)| *section == Section::Plugins) - .unwrap(); - let mut tui = crate::tui::test_support::make_test_tui().unwrap(); - view.handle_event( - &mut tui, - TuiEvent::Mouse(MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: tab.x, - row: tab.y, - modifiers: KeyModifiers::NONE, - }), - ) - .unwrap(); - assert_eq!(view.section, Section::Plugins); - screen(&mut view, /*width*/ 20, /*height*/ 12); - let (_, tab) = view.tab_hits[0]; - mouse_at(&mut view, MouseEventKind::Down(MouseButton::Left), tab); - assert_eq!(view.section, Section::Plugins); - - screen(&mut view, /*width*/ 100, /*height*/ 24); - let targets = view.control_hits.clone(); - assert!(!targets.is_empty()); - let before = (view.section, view.ranges); - press(&mut view, KeyCode::Char('R')); - for (_, rect) in targets { - mouse_at(&mut view, MouseEventKind::Down(MouseButton::Left), rect); - } - assert_eq!((view.section, view.ranges), before); - assert!(matches!(view.account, Load::Unavailable)); -} - -#[test] -fn clipped_controls_ignore_remapped_keys_and_obsolete_frames() { - let mut config = TuiKeymap::default(); - config.list.cancel = Some(KeybindingsSpec::One(KeybindingSpec("r".into()))); - config.list.accept = Some(KeybindingsSpec::Many(Vec::new())); - config.list.move_left = Some(KeybindingsSpec::Many(Vec::new())); - config.list.move_right = Some(KeybindingsSpec::Many(Vec::new())); - let mut view = fixture::view(models::AccountKind::Consumer); - view.keymap = RuntimeKeymap::from_config(&config).unwrap().list; - screen(&mut view, /*width*/ 100, /*height*/ 24); - let (_, range) = *view - .control_hits - .iter() - .find(|(control, _)| *control == Control::Range) - .unwrap(); - mouse_at(&mut view, MouseEventKind::Down(MouseButton::Left), range); - assert_eq!( - ( - view.ranges[view.range_group(Section::Usage) as usize], - view.is_done - ), - (1, false) - ); - - press(&mut view, KeyCode::Char('z')); - screen(&mut view, /*width*/ 100, /*height*/ 24); - let (_, dashboard) = *view - .control_hits - .iter() - .find(|(control, _)| *control == Control::Dashboard) - .unwrap(); - mouse_at( - &mut view, - MouseEventKind::Down(MouseButton::Left), - dashboard, - ); - assert!(view.zoomed); - - view.plan.enabled = true; - view.select_section(Section::Plan); - view.plan.cursor = [2, 4]; - let retained = view.plan.cursor; - for width in [58, 14] { - view.plan.window = 0; - screen(&mut view, width, /*height*/ 20); - let (_, hit) = *view - .control_hits - .iter() - .find(|(control, _)| *control == Control::PlanWindow) - .unwrap(); - mouse_at( - &mut view, - MouseEventKind::Down(MouseButton::Left), - Rect { - x: hit.right(), - ..hit - }, - ); - assert_eq!(view.plan.window, 0); - let last_painted = Rect { - x: hit.right() - 1, - ..hit - }; - mouse_at( - &mut view, - MouseEventKind::Down(MouseButton::Left), - last_painted, - ); - assert_eq!( - (view.plan.window, view.plan.cursor, view.is_done), - (1, retained, false) - ); - mouse_at( - &mut view, - MouseEventKind::Down(MouseButton::Left), - last_painted, - ); - assert_eq!(view.plan.window, 1); - } -} - -#[test] -fn wheel_scrolls_only_the_painted_body_within_its_bounds() { - let mut view = fixture::view(models::AccountKind::Consumer); - view.follow_selection = false; - screen(&mut view, /*width*/ 58, /*height*/ 12); - assert!(view.max_scroll > 3); - let body = view.body_area; - let tab = view.tab_hits[0].1; - mouse_at(&mut view, MouseEventKind::ScrollDown, tab); - assert_eq!(view.scroll_offset(), 0); - mouse_at(&mut view, MouseEventKind::ScrollDown, body); - assert_eq!(view.scroll_offset(), 3); - *view.scroll_offset_mut() = view.max_scroll; - mouse_at(&mut view, MouseEventKind::ScrollDown, body); - assert_eq!(view.scroll_offset(), view.max_scroll); - mouse_at(&mut view, MouseEventKind::ScrollUp, body); - assert_eq!(view.scroll_offset(), view.max_scroll - 3); - assert!(!view.follow_selection); - let reading = view.scroll_offset(); - - press(&mut view, KeyCode::Char('?')); - mouse_at(&mut view, MouseEventKind::ScrollDown, body); - assert_eq!(view.scroll_offset(), 0); - screen(&mut view, /*width*/ 58, /*height*/ 12); - let help_body = view.body_area; - mouse_at(&mut view, MouseEventKind::ScrollDown, help_body); - assert_eq!(view.scroll_offset(), 3); - press(&mut view, KeyCode::Esc); - assert_eq!(view.scroll_offset(), reading); -} diff --git a/codex-rs/tui/src/analytics/navigation_tests.rs b/codex-rs/tui/src/analytics/navigation_tests.rs deleted file mode 100644 index 75ae8954..00000000 --- a/codex-rs/tui/src/analytics/navigation_tests.rs +++ /dev/null @@ -1,326 +0,0 @@ -//! Vim navigation aliases share arrow behavior while preserving configured bindings. - -use super::*; -use crate::analytics::models::AccountKind; -use codex_config::types::KeybindingSpec; -use codex_config::types::KeybindingsSpec; -use codex_config::types::TuiKeymap; -use pretty_assertions::assert_eq; -use serde_json::json; - -fn navigate(views: &mut [AnalyticsView; 2], keys: &[(char, KeyCode)], size: (u16, u16)) -> String { - let mut output = String::new(); - for &(alias, arrow) in keys { - press(&mut views[0], KeyCode::Char(alias)); - press(&mut views[1], arrow); - output = screen(&mut views[0], size.0, size.1); - assert_eq!(output, screen(&mut views[1], size.0, size.1), "{alias}"); - } - output -} - -#[test] -fn vim_chart_navigation_matches_arrows_in_focused_and_dashboard_views() { - for (kind, section) in [ - (AccountKind::Consumer, Section::Usage), - (AccountKind::Consumer, Section::Activity), - (AccountKind::Consumer, Section::Plugins), - (AccountKind::Consumer, Section::Skills), - (AccountKind::Business, Section::Usage), - (AccountKind::Business, Section::Credits), - ] { - for zoomed in [true, false] { - let mut views = [fixture::view(kind), fixture::view(kind)]; - for view in &mut views { - view.section = section; - view.zoomed = zoomed; - view.sections[section].cursor = 3; - view.sections[section].detail = Some(3); - } - navigate( - &mut views, - &[ - ('h', KeyCode::Left), - ('h', KeyCode::Left), - ('l', KeyCode::Right), - ('j', KeyCode::Down), - ('k', KeyCode::Up), - ], - /*size*/ (96, 32), - ); - assert_eq!( - ( - views[0].section, - views[0].sections[section].cursor, - views[0].sections[section].detail - ), - (section, 2, Some(2)) - ); - } - } -} - -#[test] -fn vim_plan_navigation_preserves_independent_windows_and_collapses_old_details() { - let mut views = [ - fixture::view(AccountKind::Consumer), - fixture::view(AccountKind::Consumer), - ]; - for view in &mut views { - let as_of = "2026-09-02T12:00:00Z" - .parse::>() - .unwrap(); - view.plan.enabled = true; - view.plan.report = Load::Ready(plan::Report { - as_of, - coverage_start: None, - coverage_complete: true, - approximate: false, - periods: std::array::from_fn(|window| { - let length = if window == 0 { - chrono::Duration::hours(/*hours*/ 5) - } else { - chrono::Duration::days(/*days*/ 7) - }; - (0..2) - .map(|index| plan::Period { - id: format!("{window}-{index}"), - start: as_of - length * index, - end: as_of - length * index + length, - complete: true, - used: Some(2500.0), - breakdowns: None, - }) - .collect() - }), - }); - view.plan.poll(); - view.plan.expanded = [Some("0-0".into()), Some("1-0".into())]; - view.section = Section::Plan; - } - navigate( - &mut views, - &[ - ('l', KeyCode::Right), - ('j', KeyCode::Down), - ('k', KeyCode::Up), - ('h', KeyCode::Left), - ('j', KeyCode::Down), - ], - /*size*/ (120, 30), - ); - assert_eq!( - ( - views[0].plan.window, - views[0].plan.cursor, - &views[0].plan.expanded - ), - (0, [1, 0], &[None, None]) - ); -} - -#[test] -fn vim_summary_navigation_scrolls_like_arrows() { - let mut views = [ - fixture::view(AccountKind::Consumer), - fixture::view(AccountKind::Consumer), - ]; - for view in &mut views { - view.section = Section::Summary; - view.profile = Load::Ready( - serde_json::from_value(json!({ - "stats": {"lifetime_tokens": 123, "daily_usage_buckets": [ - {"start_date": "2026-09-02", "tokens": 123} - ]} - })) - .unwrap(), - ); - assert!(screen(view, /*width*/ 64, /*height*/ 18).contains("scroll")); - } - navigate( - &mut views, - &[ - ('h', KeyCode::Left), - ('l', KeyCode::Right), - ('j', KeyCode::Down), - ('j', KeyCode::Down), - ('k', KeyCode::Up), - ], - /*size*/ (64, 18), - ); - assert_eq!(views[0].scroll_offset(), 1); -} - -#[test] -fn vim_chat_navigation_expands_collapses_and_moves_like_arrows() { - for kind in [AccountKind::Consumer, AccountKind::Business] { - let mut views = [fixture::view(kind), fixture::view(kind)]; - for view in &mut views { - view.section = Section::Chats; - if kind == AccountKind::Consumer { - view.tasks = Load::Ready(tasks::Chats { - rows: (0..2) - .map(|index| tasks::Chat { - title: format!("Example chat {index}"), - task: Some( - serde_json::from_value(json!({ - "thread_id": format!("chat-{index}"), - "data_status": "available", "usage_source": "accounting", - "weekly_limit_percent": 20 - index, - "five_hour_limit_percent": null, "balance_usage_credits": null, - "groups": [] - })) - .unwrap(), - ), - }) - .collect(), - ..tasks::Chats::default() - }); - } - } - navigate( - &mut views, - &[ - ('l', KeyCode::Right), - ('h', KeyCode::Left), - ('l', KeyCode::Right), - ('j', KeyCode::Down), - ('l', KeyCode::Right), - ('k', KeyCode::Up), - ], - /*size*/ (96, 32), - ); - assert_eq!( - ( - views[0].sections[Section::Chats].cursor, - views[0].sections[Section::Chats].detail - ), - (0, None) - ); - } -} - -#[test] -fn configured_dashboard_accept_precedes_report_shortcuts() { - for binding in ["r", "g", "m", "R", "tab", "1"] { - let mut config = TuiKeymap::default(); - config.list.accept = Some(KeybindingsSpec::One(KeybindingSpec(binding.into()))); - let mut view = fixture::view(AccountKind::Business); - view.keymap = RuntimeKeymap::from_config(&config).unwrap().list; - view.section = Section::Usage; - view.zoomed = false; - let previous = ( - view.section, - view.ranges, - view.sections[Section::Usage].group, - ); - let key = if binding == "tab" { - KeyCode::Tab - } else { - KeyCode::Char(binding.chars().next().unwrap()) - }; - press(&mut view, key); - assert_eq!( - ( - view.zoomed, - view.section, - view.ranges, - view.sections[Section::Usage].group - ), - (true, previous.0, previous.1, previous.2), - "{binding}" - ); - } -} - -#[test] -fn configured_question_mark_keeps_its_action_and_hides_help_hint() { - for (binding, modifiers) in [("?", KeyModifiers::NONE), ("shift-?", KeyModifiers::SHIFT)] { - let mut config = TuiKeymap::default(); - config.list.cancel = Some(KeybindingsSpec::One(KeybindingSpec(binding.into()))); - let mut view = fixture::view(AccountKind::Consumer); - view.keymap = RuntimeKeymap::from_config(&config).unwrap().list; - let footer = view.footer_lines(/*width*/ 120, /*scrollable*/ false); - assert!( - !footer - .iter() - .any(|line| line.to_string().contains("? help")) - ); - assert!( - !view - .help_lines(/*width*/ 120) - .iter() - .any(|line| line.to_string().contains("toggle this help")) - ); - view.handle_key(KeyEvent::new(KeyCode::Char('?'), modifiers)); - assert_eq!((view.is_done, view.show_help), (true, false)); - } -} - -#[test] -fn configured_vim_keys_win_over_horizontal_aliases() { - let mut config = TuiKeymap::default(); - config.list.jump_top = Some(KeybindingsSpec::Many(vec![ - KeybindingSpec("h".into()), - KeybindingSpec("l".into()), - ])); - let mut view = fixture::view(AccountKind::Consumer); - view.keymap = RuntimeKeymap::from_config(&config).unwrap().list; - for alias in ['h', 'l'] { - view.sections[Section::Usage].cursor = 3; - press(&mut view, KeyCode::Char(alias)); - assert_eq!(view.sections[Section::Usage].cursor, 0); - } -} - -#[test] -fn vim_aliases_respect_removed_and_remapped_arrows() { - let mut config = TuiKeymap::default(); - config.list.move_left = Some(KeybindingsSpec::Many(Vec::new())); - config.list.move_right = Some(KeybindingsSpec::Many(Vec::new())); - config.list.move_up = Some(KeybindingsSpec::One(KeybindingSpec("up".into()))); - config.list.move_down = Some(KeybindingsSpec::One(KeybindingSpec("down".into()))); - let mut view = fixture::view(AccountKind::Consumer); - view.keymap = RuntimeKeymap::from_config(&config).unwrap().list; - view.sections[Section::Usage].cursor = 3; - for alias in ['h', 'j', 'k', 'l'] { - press(&mut view, KeyCode::Char(alias)); - assert_eq!(view.sections[Section::Usage].cursor, 3); - } - - config.list.move_up = Some(KeybindingsSpec::One(KeybindingSpec("right".into()))); - config.list.move_down = Some(KeybindingsSpec::One(KeybindingSpec("left".into()))); - view.keymap = RuntimeKeymap::from_config(&config).unwrap().list; - press(&mut view, KeyCode::Char('h')); - assert_eq!(view.sections[Section::Usage].cursor, 4); - press(&mut view, KeyCode::Char('l')); - assert_eq!(view.sections[Section::Usage].cursor, 3); -} - -#[test] -fn horizontal_aliases_ignore_modifiers_and_release_but_accept_repeat() { - let mut view = fixture::view(AccountKind::Consumer); - view.sections[Section::Usage].cursor = 3; - for alias in ['h', 'l'] { - for modifiers in [ - KeyModifiers::ALT, - KeyModifiers::SHIFT, - KeyModifiers::CONTROL | KeyModifiers::ALT, - ] { - view.handle_key(KeyEvent::new(KeyCode::Char(alias), modifiers)); - assert_eq!(view.sections[Section::Usage].cursor, 3); - } - view.handle_key(KeyEvent { - kind: KeyEventKind::Release, - ..KeyEvent::new(KeyCode::Char(alias), KeyModifiers::NONE) - }); - assert_eq!(view.sections[Section::Usage].cursor, 3); - } - for (alias, cursor) in [('h', 2), ('l', 3)] { - view.handle_key(KeyEvent { - kind: KeyEventKind::Repeat, - ..KeyEvent::new(KeyCode::Char(alias), KeyModifiers::NONE) - }); - assert_eq!(view.sections[Section::Usage].cursor, cursor); - } -} diff --git a/codex-rs/tui/src/analytics/normalize.rs b/codex-rs/tui/src/analytics/normalize.rs deleted file mode 100644 index 0dad8d7e..00000000 --- a/codex-rs/tui/src/analytics/normalize.rs +++ /dev/null @@ -1,364 +0,0 @@ -//! Converts backend reports into display data while preserving missing values and full denominators. - -use super::models::AccountAnalyticsGrouping as Grouping; -use super::models::AccountAnalyticsReport as Report; -use super::models::*; -use super::report_data::AnalyticsData; -use chrono::DateTime; -use chrono::NaiveDate; -use std::collections::BTreeMap; - -/// Out-of-range legacy rows do not change attribution semantics for the requested period. -pub(super) fn has_complete_attribution( - response: &AnalyticsData, - start: NaiveDate, - end: NaiveDate, -) -> Result { - response - .data - .iter() - .try_fold(/*init*/ true, |complete, record| { - let date = NaiveDate::parse_from_str( - record.date.get(..10).unwrap_or(&record.date), - "%Y-%m-%d", - ) - .map_err(|_| String::from("Analytics returned an invalid date."))?; - Ok(complete && (date < start || date > end || record.attribution.is_some())) - }) -} - -pub(super) fn history( - response: AnalyticsData, - report: Report, - grouping: Grouping, - start: NaiveDate, - end: NaiveDate, -) -> Result, String> { - if report == Report::Messages { - match grouping { - Grouping::Model | Grouping::Surface => {} - Grouping::Feature - | Grouping::TaskStart - | Grouping::Speed - | Grouping::Reasoning - | Grouping::TokenType => { - return Err(String::from("Unsupported message count grouping.")); - } - } - } - let attributed = has_complete_attribution(&response, start, end)?; - let series = response.series.as_ref(); - let mut days: BTreeMap)> = BTreeMap::new(); - for record in response.data { - let date = - NaiveDate::parse_from_str(record.date.get(..10).unwrap_or(&record.date), "%Y-%m-%d") - .map_err(|_| String::from("Analytics returned an invalid date."))?; - if date < start || date > end { - continue; - } - let (total, values) = days.entry(date).or_default(); - match report { - Report::Usage => { - let daily = if attributed { - None - } else { - match grouping { - Grouping::Surface => record.product_surface_usage_values, - Grouping::Model => record - .models - .map(|models| -> Result<_, String> { - let mut values = BTreeMap::new(); - for model in models { - let amount = model - .credits - .ok_or("Plan usage amount was not reported.")?; - *values.entry(model.model).or_insert(/*default*/ 0.0) += amount; - } - Ok(values) - }) - .transpose()?, - _ => None, - } - }; - if let Some(daily) = daily { - for (key, amount) in daily { - if !amount.is_finite() || amount < 0.0 { - return Err(String::from("Analytics returned an invalid amount.")); - } - let key = if grouping == Grouping::Surface { - if key.starts_with("work_") { - "work" - } else { - "codex" - } - .to_string() - } else if key.eq_ignore_ascii_case("other") { - "other".to_string() - } else { - key - }; - *total += amount; - *values.entry(key).or_default() += amount; - } - } else if let Some(attribution) = record.attribution.filter(|_| attributed) { - for entry in attribution { - if !entry.value.is_finite() || entry.value < 0.0 { - return Err(String::from("Analytics returned an invalid amount.")); - } - *total += entry.value; - let key = match grouping { - Grouping::Feature => entry.thread_source, - Grouping::Model => entry.model, - Grouping::Surface => entry.surface, - Grouping::TaskStart => { - entry.turn_trigger.map(|trigger| format!("start-{trigger}")) - } - Grouping::Speed | Grouping::Reasoning | Grouping::TokenType => { - return Err(String::from("unsupported analytics grouping")); - } - } - .unwrap_or_else(|| "unknown".to_string()); - *values.entry(key).or_default() += entry.value; - } - } else { - return Ok(None); - } - } - - Report::Credits => { - if series.is_some() { - let Some(credits) = record.values else { - return Ok(None); - }; - for (key, amount) in credits { - *values.entry(key).or_default() += amount; - *total += amount; - } - } else if matches!(grouping, Grouping::Model | Grouping::Speed) { - let Some(models) = record.models else { - return Ok(None); - }; - for model in models { - let amount = model.on_demand_credits.unwrap_or(/*default*/ 0.0); - let key = if grouping == Grouping::Speed { - model.speed.unwrap_or_else(|| "unknown".to_string()) - } else { - model.model - }; - *values.entry(key).or_default() += amount; - *total += amount; - } - } else if let Some(premium) = record.premium_usage_values { - for (surface, amount) in premium.credit_usage_credits { - if !amount.is_finite() { - return Err(String::from("Analytics returned an invalid amount.")); - } - *values.entry(surface).or_default() += amount; - *total += amount; - } - } else if let (Some(amount), Some(surface)) = - (record.credit_amount, record.product_surface) - { - *values.entry(surface).or_default() += amount; - *total += amount; - } else { - return Ok(None); - } - } - Report::Messages => { - let authoritative = record - .totals - .ok_or_else(|| String::from("Message count is unavailable."))? - .turns; - if !authoritative.is_finite() || authoritative < 0.0 { - return Err(String::from("Analytics returned an invalid amount.")); - } - let mut record_values = BTreeMap::::new(); - if grouping == Grouping::Model { - for model in record.models.unwrap_or_default() { - let key = if model.model.eq_ignore_ascii_case("codex-auto-review") - || model.model.eq_ignore_ascii_case("other") - { - "other".to_string() - } else { - model.model - }; - let count = model - .turns - .ok_or_else(|| String::from("Turn count is unavailable."))?; - if !count.is_finite() || count < 0.0 { - return Err(String::from("Analytics returned an invalid amount.")); - } - *record_values.entry(key).or_default() += count; - } - } else { - for client in record.clients.unwrap_or_default() { - if !client.turns.is_finite() || client.turns < 0.0 { - return Err(String::from("Analytics returned an invalid amount.")); - } - let key = match client.client_id.as_str() { - "CODEX_CLI" => "cli", - "CODEX_IDE_VSCODE" => "vscode", - "CODEX_WEB" => "web", - "CODEX_DESKTOP_APP" | "CODEX_WORK_DESKTOP" => "desktop_app", - "CODEX_WORK_WEB" => "work_web", - "CODEX_WORK_MOBILE" => "mobile", - "CODEX_GITHUB" => "github_code_review", - _ => "other", - }; - *record_values.entry(key.to_string()).or_default() += client.turns; - } - } - let remainder = - (authoritative - record_values.values().sum::()).max(/*other*/ 0.0); - if remainder > 0.0 { - *record_values.entry("other".to_string()).or_default() += remainder; - } - for (key, count) in record_values { - *values.entry(key).or_default() += count; - } - *total += authoritative; - } - Report::Plugins | Report::Skills => { - let overviews = if report == Report::Skills { - record.skill_usage_overviews - } else { - record.plugin_usage_overviews - } - .ok_or_else(|| String::from("Tool activity is unavailable."))?; - for tool in overviews { - if !tool.invocation_counts.is_finite() || tool.invocation_counts < 0.0 { - return Err(String::from("Analytics returned an invalid amount.")); - } - *values.entry(tool.display_name).or_default() += tool.invocation_counts; - *total += tool.invocation_counts; - } - } - } - if !total.is_finite() - || values - .values() - .any(|value| !value.is_finite() || (report != Report::Credits && *value < 0.0)) - { - return Err(String::from("Analytics returned an invalid amount.")); - } - } - if report == Report::Usage - && !attributed - && grouping == Grouping::Model - && response.units.as_deref() != Some("credits") - { - let mut totals = BTreeMap::::new(); - for (_, values) in days.values() { - for (key, value) in values { - *totals.entry(key.clone()).or_default() += value; - } - } - let total: f64 = totals.values().sum(); - for (_, values) in days.values_mut() { - let mut other = 0.0; - values.retain(|key, value| { - let amount = totals[key]; - if key.eq_ignore_ascii_case("other") || (amount > 0.0 && amount < total * 0.01) { - other += *value; - false - } else { - true - } - }); - if other > 0.0 { - values.insert("other".to_string(), other); - } - } - } - if report == Report::Credits { - for date in start.iter_days().take_while(|date| *date <= end) { - days.entry(date).or_default(); - } - } - Ok(Some(AccountAnalyticsHistory { - unit: match report { - Report::Usage if !attributed && response.units.as_deref() == Some("credits") => { - AccountAnalyticsUnit::Credits - } - Report::Usage => AccountAnalyticsUnit::RelativeUsage, - Report::Credits => AccountAnalyticsUnit::Credits, - Report::Messages | Report::Plugins | Report::Skills => AccountAnalyticsUnit::Count, - }, - updated_at: response - .data_freshness_ts - .as_deref() - .and_then(|timestamp| DateTime::parse_from_rfc3339(timestamp).ok()) - .map(|timestamp| timestamp.timestamp()), - data: days - .into_iter() - .map(|(date, (total, values))| AccountAnalyticsDay { - date, - total, - values: values - .into_iter() - .map(|(key, value)| AccountAnalyticsValue { - label: series - .and_then(|series| series.iter().find(|series| series.key == key)) - .map(|series| series.label.clone()) - .unwrap_or_else(|| label(&key).to_string()), - key, - value, - }) - .collect(), - }) - .collect(), - })) -} - -pub(super) fn label(key: &str) -> &str { - match key { - "user" => "Tasks", - "subagent" => "Subagents", - "image_generation" => "Image generation", - "automation" => "Automations", - "guardian_review" => "Auto review", - "guardian_classifier" => "Auto review classifier", - "thread_title" => "Thread title", - "system" => "System", - "automated_review" => "Auto review", - "agent_identity" => "Workspace agents", - "memory_consolidation" => "Memory consolidation", - "cli" => "CLI", - "desktop_app" => "Desktop app", - "vscode" => "VS Code", - "web" => "Web", - "work_web" => "Work web", - "work_desktop" => "Work desktop", - "work_mobile" => "Work mobile", - "mobile" => "Mobile", - "slack" => "Slack", - "linear" => "Linear", - "jetbrains" => "JetBrains", - "sdk" => "SDK", - "exec" => "Exec", - "github" => "GitHub", - "codex" => "Codex", - "work" => "Work", - "code_review" | "github_code_review" => "Code review", - "start-user" | "start-composer" => "User messages", - "start-goal" => "Goals", - "start-composer_queue" => "Queued messages", - "start-composer_queue_run_now" => "Queued messages run now", - "start-automation_cron_scheduled" => "Scheduled automations", - "start-automation_cron_run_now" => "Automations run now", - "start-automation_heartbeat_scheduled" => "Scheduled follow-ups", - "start-automation_heartbeat_run_now" => "Follow-ups run now", - "start-app_tool_create_thread" => "Agent-created tasks", - "start-app_tool_send_message" => "Agent follow-ups", - "unknown" | "start-unknown" => "Unknown", - "fast" => "Fast", - "standard" => "Standard", - "other" | "start-other" => "Other", - _ => key, - } -} - -#[cfg(test)] -#[path = "normalize_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/normalize_tests.rs b/codex-rs/tui/src/analytics/normalize_tests.rs deleted file mode 100644 index 140166f9..00000000 --- a/codex-rs/tui/src/analytics/normalize_tests.rs +++ /dev/null @@ -1,358 +0,0 @@ -//! Regression coverage for daily report normalization and billing semantics. - -use super::*; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[test] -fn turn_start_includes_all_features_and_missing_attribution_is_unavailable() { - let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap(); - let response = serde_json::from_value(json!({"data": [{"date": "2026-01-09", "attribution": [ - {"thread_source": "user", "turn_trigger": "composer", "value": 30}, - {"thread_source": "subagent", "value": 70} - ]}]})) - .unwrap(); - assert_eq!( - history(response, Report::Usage, Grouping::TaskStart, date, date).unwrap(), - Some(AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::RelativeUsage, - updated_at: None, - data: vec![AccountAnalyticsDay { - date: "2026-01-09".parse().unwrap(), - total: 100.0, - values: vec![ - AccountAnalyticsValue { - key: "start-composer".to_string(), - label: "User messages".to_string(), - value: 30.0 - }, - AccountAnalyticsValue { - key: "unknown".to_string(), - label: "Unknown".to_string(), - value: 70.0 - } - ], - }], - }) - ); - let response = serde_json::from_value(json!({"data": [{"date": "2026-01-09"}]})).unwrap(); - assert_eq!( - history(response, Report::Usage, Grouping::Feature, date, date).unwrap(), - None - ); -} - -#[test] -fn signed_credits_keep_daily_activity_when_the_period_nets_to_zero() { - let start = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 8).unwrap(); - let end = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap(); - let response = serde_json::from_value(json!({"data": [ - {"date": "2026-01-08", "product_surface": "cli", "credit_amount": 0.004}, - {"date": "2026-01-09", "product_surface": "desktop_app", "credit_amount": -0.004} - ]})) - .unwrap(); - assert_eq!( - history(response, Report::Credits, Grouping::Surface, start, end).unwrap(), - Some(AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::Credits, - updated_at: None, - data: [ - ("2026-01-08", 0.004, "cli", "CLI"), - ("2026-01-09", -0.004, "desktop_app", "Desktop app") - ] - .into_iter() - .map(|(date, amount, key, label)| AccountAnalyticsDay { - date: date.parse().unwrap(), - total: amount, - values: vec![AccountAnalyticsValue { - key: key.to_string(), - label: label.to_string(), - value: amount - }], - }) - .collect(), - }) - ); -} - -#[test] -fn message_surfaces_include_both_desktop_clients_and_unmapped_counts() { - let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap(); - let response = serde_json::from_value( - json!({"data": [{"date": "2026-01-09", "totals": {"turns": 10}, "clients": [ - {"client_id": "CODEX_DESKTOP_APP", "turns": 2}, - {"client_id": "CODEX_WORK_DESKTOP", "turns": 3}, - {"client_id": "new_client", "turns": 1} - ]}]}), - ) - .unwrap(); - assert_eq!( - history(response, Report::Messages, Grouping::Surface, date, date) - .unwrap() - .unwrap() - .data, - vec![AccountAnalyticsDay { - date: "2026-01-09".parse().unwrap(), - total: 10.0, - values: vec![ - AccountAnalyticsValue { - key: "desktop_app".to_string(), - label: "Desktop app".to_string(), - value: 5.0 - }, - AccountAnalyticsValue { - key: "other".to_string(), - label: "Other".to_string(), - value: 5.0 - }, - ], - }] - ); -} - -#[test] -fn enterprise_credit_series_keep_labels_signed_values_and_freshness() { - let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap(); - let response = serde_json::from_value(json!({ - "series": [{"key": "medium", "label": "Medium", "total": 12.5}, {"key": "high", "label": "High", "total": -0.004}], - "data_freshness_ts": "2026-01-09T10:00:00Z", - "data": [{"date": "2026-01-09", "values": {"medium": 12.5, "high": -0.004}}] - })).unwrap(); - assert_eq!( - history(response, Report::Credits, Grouping::Reasoning, date, date).unwrap(), - Some(AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::Credits, - updated_at: Some(1767952800), - data: vec![AccountAnalyticsDay { - date, - total: 12.496, - values: vec![ - AccountAnalyticsValue { - key: "high".into(), - label: "High".into(), - value: -0.004 - }, - AccountAnalyticsValue { - key: "medium".into(), - label: "Medium".into(), - value: 12.5 - } - ], - }], - }) - ); -} - -#[test] -fn credit_timestamps_and_legacy_model_usage_follow_app_fallbacks() { - let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap(); - let credits = serde_json::from_value(json!({"data": [{"date": "2026-01-09T05:00:00Z", "product_surface": "cli", "credit_amount": 12.5}]})).unwrap(); - let usage = serde_json::from_value(json!({"data": [{"date": "2026-01-09", "models": [{"model": "model-a", "credits": 12.5}]}]})).unwrap(); - let credits = history(credits, Report::Credits, Grouping::Surface, date, date) - .unwrap() - .unwrap(); - let usage = history(usage, Report::Usage, Grouping::Model, date, date) - .unwrap() - .unwrap(); - assert_eq!( - ( - credits.data[0].total, - usage.data[0].total, - usage.data[0].values[0].key.as_str() - ), - (12.5, 12.5, "model-a") - ); -} - -#[test] -fn count_reports_preserve_explicit_zero_and_omit_unreported_days() { - let start = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 8).unwrap(); - let end = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 10).unwrap(); - for (report, field) in [ - (Report::Messages, "totals"), - (Report::Plugins, "plugin_usage_overviews"), - (Report::Skills, "skill_usage_overviews"), - ] { - let value = if report == Report::Messages { - json!({"turns": 0}) - } else { - json!([]) - }; - let response = - serde_json::from_value(json!({"data": [{"date": "2026-01-08", (field): value}]})) - .unwrap(); - assert_eq!( - history(response, report, Grouping::Surface, start, end).unwrap(), - Some(AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::Count, - updated_at: None, - data: vec![AccountAnalyticsDay { - date: start, - total: 0.0, - values: Vec::new() - }], - }) - ); - } -} - -#[test] -fn legacy_consumer_history_keeps_daily_products_and_models() { - let date = "2026-09-01".parse().unwrap(); - let response: AnalyticsData = serde_json::from_value(json!({"units":"relative", "data":[{ - "date":"2026-09-01", - "product_surface_usage_values":{"work_desktop":12,"work_web":8,"cli":30,"desktop_app":50}, - "models":[{"model":"major","credits":98.5},{"model":"one-percent","credits":1},{"model":"tiny","credits":0.3},{"model":"OTHER","credits":0.2}] - }]})).unwrap(); - for (grouping, expected) in [ - ( - Grouping::Surface, - vec![("codex", "Codex", 80.0), ("work", "Work", 20.0)], - ), - ( - Grouping::Model, - vec![ - ("major", "major", 98.5), - ("one-percent", "one-percent", 1.0), - ("other", "Other", 0.5), - ], - ), - ] { - assert_eq!( - history(response.clone(), Report::Usage, grouping, date, date).unwrap(), - Some(AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::RelativeUsage, - updated_at: None, - data: vec![AccountAnalyticsDay { - date, - total: 100.0, - values: expected - .into_iter() - .map(|(key, label, value)| AccountAnalyticsValue { - key: key.into(), - label: label.into(), - value - }) - .collect() - }], - }) - ); - } - let mut credits = response; - credits.units = Some("credits".into()); - let model = history(credits, Report::Usage, Grouping::Model, date, date) - .unwrap() - .unwrap(); - assert_eq!( - (model.unit, model.data[0].values.len()), - (AccountAnalyticsUnit::Credits, 4) - ); -} - -#[test] -fn complete_attribution_wins_consistently_and_incomplete_attribution_is_not_mixed() { - let date = "2026-09-01".parse().unwrap(); - let response: AnalyticsData = serde_json::from_value(json!({"units":"credits", "data":[{ - "date":"2026-09-01", "product_surface_usage_values":{"cli":999}, - "models":[{"model":"legacy","credits":999}], - "attribution":[ - {"thread_source":"user","turn_trigger":"composer","surface":"desktop_app","model":"alpha","value":30}, - {"thread_source":"subagent","turn_trigger":"goal","surface":"cli","model":"tiny","value":0.1} - ] - }]})).unwrap(); - for grouping in [ - Grouping::Feature, - Grouping::Model, - Grouping::Surface, - Grouping::TaskStart, - ] { - let normalized = history(response.clone(), Report::Usage, grouping, date, date) - .unwrap() - .unwrap(); - assert_eq!( - ( - normalized.unit, - normalized.data[0].total, - normalized.data[0].values.len() - ), - (AccountAnalyticsUnit::RelativeUsage, 30.1, 2) - ); - } - let incomplete = serde_json::from_value(json!({"data":[ - {"date":"2026-09-01", "attribution":[]}, {"date":"2026-09-02"} - ]})) - .unwrap(); - assert_eq!( - history( - incomplete, - Report::Usage, - Grouping::Feature, - date, - "2026-09-02".parse().unwrap() - ) - .unwrap(), - None - ); -} - -#[test] -fn duplicate_message_dates_preserve_each_records_other_remainder() { - let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap(); - for grouping in [Grouping::Model, Grouping::Surface] { - let response = serde_json::from_value(json!({"data": [ - {"date": "2026-01-09", "totals": {"turns": 10}, "models": [{"model": "example", "turns": 8}], "clients": [{"client_id": "CODEX_CLI", "turns": 8}]}, - {"date": "2026-01-09", "totals": {"turns": 10}, "models": [{"model": "example", "turns": 8}], "clients": [{"client_id": "CODEX_CLI", "turns": 8}]} - ]})).unwrap(); - let (key, label) = if grouping == Grouping::Model { - ("example", "example") - } else { - ("cli", "CLI") - }; - assert_eq!( - history(response, Report::Messages, grouping, date, date).unwrap(), - Some(AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::Count, - updated_at: None, - data: vec![AccountAnalyticsDay { - date, - total: 20.0, - values: vec![ - AccountAnalyticsValue { - key: key.into(), - label: label.into(), - value: 16.0 - }, - AccountAnalyticsValue { - key: "other".into(), - label: "Other".into(), - value: 4.0 - }, - ] - }], - }) - ); - } -} - -#[test] -fn unsupported_message_groupings_fail_even_without_records() { - let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap(); - for grouping in [ - Grouping::Feature, - Grouping::TaskStart, - Grouping::Speed, - Grouping::Reasoning, - Grouping::TokenType, - ] { - for data in [ - json!([]), - json!([{"date": "2026-01-09", "totals": {"turns": 10}, "clients": []}]), - ] { - let response = serde_json::from_value(json!({"data": data})).unwrap(); - assert_eq!( - history(response, Report::Messages, grouping, date, date), - Err("Unsupported message count grouping.".into()) - ); - } - } -} diff --git a/codex-rs/tui/src/analytics/panels.rs b/codex-rs/tui/src/analytics/panels.rs deleted file mode 100644 index 53629f3b..00000000 --- a/codex-rs/tui/src/analytics/panels.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! Responsive panels with consistent category colors and signed daily amounts. - -use super::AnalyticsView; -use crate::analytics::sections::Section; -use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_lines; -use ratatui::text::Line; -use std::ops::Range; - -/// Panel content and measured geometry shared by layout and scrolling. -pub(super) struct Panel { - pub(super) lines: Vec>, - pub(super) selection: Range, - pub(super) chart_bands: usize, -} - -impl AnalyticsView { - pub(super) fn panel(&self, section: Section, width: usize, chart_height: usize) -> Panel { - let mut lines = Vec::new(); - let selection; - let mut chart_bands = 0; - - if section == Section::Summary { - selection = 0..1; - lines.extend(self.summary_lines(width)); - } else if section == Section::Plan { - let (plan, detail) = self.plan_lines(width); - selection = lines.len() + detail.start..lines.len() + detail.end; - lines.extend(plan); - } else if section == Section::Chats { - let (chats, detail) = if self.business() { - self.chat_lines(width) - } else { - self.task_lines(width) - }; - selection = lines.len() + detail.start..lines.len() + detail.end; - lines.extend(chats); - } else { - let history = self.history_lines(section, width, chart_height); - chart_bands = history.bands; - lines.extend(history.lines); - selection = 0..lines.len(); - } - - let mut wrapped = Vec::new(); - let mut wrapped_selection = 0..0; - for (index, line) in lines.into_iter().enumerate() { - if index == selection.start { - wrapped_selection.start = wrapped.len(); - } - if line.style.bg.is_some() && line.width() <= width { - // Keep highlighted padding on selected rows that already fit the panel. - wrapped.push(line); - } else { - wrapped.extend(word_wrap_lines( - [line], - RtOptions::new(width.max(/*other*/ 1)), - )); - } - if index + 1 == selection.end { - wrapped_selection.end = wrapped.len(); - } - } - Panel { - lines: wrapped, - selection: wrapped_selection, - chart_bands, - } - } -} diff --git a/codex-rs/tui/src/analytics/plan.rs b/codex-rs/tui/src/analytics/plan.rs deleted file mode 100644 index d4d9d1ec..00000000 --- a/codex-rs/tui/src/analytics/plan.rs +++ /dev/null @@ -1,121 +0,0 @@ -//! Historical allowance snapshots, separate from daily usage and current chat allowances. -//! Period IDs are snapshot-scoped; unknown accounting is never converted to zero. -use super::data::Load; -use chrono::DateTime; -use chrono::Utc; -use codex_backend_client::PlanLimitBreakdown; -use codex_backend_client::PlanLimitHistory; - -pub(super) struct Period { - pub id: String, - pub start: DateTime, - pub end: DateTime, - pub complete: bool, - pub used: Option, - pub breakdowns: Option>, -} - -pub(super) struct Report { - pub as_of: DateTime, - pub coverage_start: Option>, - pub coverage_complete: bool, - pub approximate: bool, - pub periods: [Vec; 2], -} - -impl Report { - pub(super) fn parse(history: PlanLimitHistory) -> Result, String> { - let parse = |value: &str| { - DateTime::parse_from_rfc3339(value) - .map(|date| date.with_timezone(&Utc)) - .map_err(|_| "Invalid plan history timestamp.".to_string()) - }; - let Some(as_of) = history.data_as_of.as_deref().map(parse).transpose()? else { - return Ok(None); - }; - let mut periods = [Vec::new(), Vec::new()]; - let mut ids = std::collections::HashSet::new(); - if history.periods.len() > 1_000 { - return Err("Plan history contains too many periods.".into()); - } - for period in history.periods { - let window = match period.window_minutes { - 300 => 0, - 10080 => 1, - _ => return Err("Unsupported plan history window.".into()), - }; - let start = parse(&period.starts_at)?; - let end = parse(&period.ends_at)?; - if start >= end - || !ids.insert(period.id.clone()) - || period - .used_basis_points - .is_some_and(|amount| !amount.is_finite()) - || period - .breakdowns - .iter() - .flatten() - .flat_map(|group| &group.rows) - .any(|row| !row.basis_points.is_finite()) - { - return Err("Invalid plan history period.".into()); - } - periods[window].push(Period { - id: period.id, - start, - end, - complete: period.accounting_complete, - used: period.used_basis_points, - breakdowns: period.breakdowns, - }); - } - for window in &mut periods { - window.sort_by_key(|period| std::cmp::Reverse(period.start)); - } - Ok(Some(Self { - as_of, - coverage_start: history.coverage_start.as_deref().map(parse).transpose()?, - coverage_complete: history.coverage_complete, - approximate: history.approximate, - periods, - })) - } -} - -pub(super) struct State { - pub enabled: bool, - pub report: Load, - pub window: usize, - pub cursor: [usize; 2], - pub expanded: [Option; 2], - snapshot: Option>, -} - -impl Default for State { - fn default() -> Self { - Self { - enabled: false, - report: Load::Unavailable, - window: 0, - cursor: [0; 2], - expanded: [None, None], - snapshot: None, - } - } -} - -impl State { - pub(super) fn poll(&mut self) { - self.report.poll(); - let snapshot = self.report.ready().map(|report| report.as_of); - if snapshot != self.snapshot { - self.snapshot = snapshot; - self.cursor = [0; 2]; - self.expanded = [None, None]; - } - } -} - -#[cfg(test)] -#[path = "plan_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/plan_panel.rs b/codex-rs/tui/src/analytics/plan_panel.rs deleted file mode 100644 index 74b45aa4..00000000 --- a/codex-rs/tui/src/analytics/plan_panel.rs +++ /dev/null @@ -1,255 +0,0 @@ -//! Five-hour and weekly period tables share grouping, with independent row expansion. -use super::AnalyticsView; -use super::data; -use super::plan; -use super::render::columns; -use super::render::join_columns; -use super::sections::Section; -use super::styles::secondary_style; -use crate::keymap::ListAction; -use codex_backend_client::PlanLimitDimension; -use ratatui::style::Styled; -use ratatui::style::Stylize; -use ratatui::text::Line; -use std::ops::Range; - -impl AnalyticsView { - pub(super) fn plan_action(&mut self, action: Option) { - let window = self.plan.window; - let periods = self - .plan - .report - .ready() - .map(|report| &report.periods[window]); - let count = periods.map_or(/*default*/ 0, Vec::len); - let mut scroll_offset = self.scroll_offset(); - let cursor = &mut self.plan.cursor[window]; - let previous_cursor = *cursor; - match action { - Some(ListAction::MoveLeft | ListAction::MoveRight) => self.plan.window ^= 1, - Some(ListAction::MoveUp) => *cursor = cursor.saturating_sub(/*rhs*/ 1), - Some(ListAction::MoveDown) => { - *cursor = (*cursor + 1).min(count.saturating_sub(/*rhs*/ 1)) - } - Some(ListAction::JumpTop) => *cursor = 0, - Some(ListAction::JumpBottom) => *cursor = count.saturating_sub(/*rhs*/ 1), - Some(ListAction::Accept) => { - if let Some(period) = periods.and_then(|periods| periods.get(*cursor)) { - self.plan.expanded[window] = - if self.plan.expanded[window].as_ref() == Some(&period.id) { - None - } else { - Some(period.id.clone()) - }; - } - } - Some(ListAction::Cancel) => { - self.is_done |= self.plan.expanded[window].take().is_none(); - } - Some(ListAction::PageDown) => { - scroll_offset += self.viewport_height; - self.follow_selection = false; - } - Some(ListAction::PageUp) => { - scroll_offset = scroll_offset.saturating_sub(self.viewport_height); - self.follow_selection = false; - } - None => {} - } - if *cursor != previous_cursor { - self.plan.expanded[window] = None; - } - self.sections[Section::Plan].follow_selection_on_focus |= - !self.zoomed && (self.plan.window != window || *cursor != previous_cursor); - *self.scroll_offset_mut() = scroll_offset; - } - - pub(super) fn plan_lines(&self, width: usize) -> (Vec>, Range) { - let side_by_side = width >= 100; - let table_width = if side_by_side { (width - 4) / 2 } else { width }; - let group = self.sections[Section::Plan].group; - let dimension = match group { - 1 => PlanLimitDimension::ThreadSource, - 2 => PlanLimitDimension::Model, - 3 => PlanLimitDimension::TurnTrigger, - _ => PlanLimitDimension::Surface, - }; - let mut tables = Vec::new(); - let mut selections = Vec::new(); - for (window, title) in ["5-hour limits", "Weekly limits"].into_iter().enumerate() { - let heading = format!( - "{} {title}", - if self.plan.window == window { - "›" - } else { - " " - } - ); - let mut lines = vec![heading.bold().into(), Line::default()]; - let mut selection = 0..2; - if let Some(report) = self.plan.report.ready() { - if report.periods[window].is_empty() { - lines.push( - if report.coverage_complete { - "No limit periods in this date range" - } else { - "Limit history isn't available yet" - } - .set_style(secondary_style()) - .into(), - ); - } - for (index, period) in report.periods[window] - .iter() - .take(if self.zoomed { usize::MAX } else { 1 }) - .enumerate() - { - let start = lines.len(); - let selected = self.plan.cursor[window] == index; - let label = format!( - "{} {} – {}{}", - if selected { "›" } else { " " }, - period.start.format(self.clock_format.date_time_format()), - period.end.format(self.clock_format.date_time_format()), - if period.start <= report.as_of && period.end > report.as_of { - " *" - } else { - "" - } - ); - let amount = period - .used - .map(|value| format!("{}%", data::amount(value / 100.0))) - .unwrap_or_else(|| "Not available".into()); - let mut row = columns(label.into(), amount.into(), table_width); - if selected && self.plan.window == window { - super::styles::select_row(&mut row, table_width); - } - lines.push(row); - if self.zoomed && self.plan.expanded[window].as_ref() == Some(&period.id) { - if !period.complete { - lines.push( - " Some usage is unavailable; this period may be incomplete" - .dim() - .into(), - ); - } - if let Some(breakdown) = period.breakdowns.as_ref().and_then(|groups| { - groups.iter().find(|group| group.dimension == dimension) - }) { - for row in &breakdown.rows { - let key = if dimension == PlanLimitDimension::TurnTrigger { - format!("start-{}", row.key) - } else { - row.key.clone() - }; - let label = if dimension == PlanLimitDimension::Model { - self.model_name(&key) - } else { - super::normalize::label(&key) - }; - lines.push(columns( - format!(" {label}").into(), - format!("{}%", data::amount(row.basis_points / 100.0)).into(), - table_width, - )); - } - } else { - lines.push(" Breakdown isn't available for this period".dim().into()); - } - } - if selected { - selection = start..lines.len(); - } - } - } else { - lines.push( - match &self.plan.report { - data::Load::Unavailable => "Limit history isn't available yet", - state => state - .message() - .unwrap_or("Limit history isn't available yet"), - } - .to_string() - .set_style(secondary_style()) - .into(), - ); - } - // Wrap each column before joining so long timestamps never collide with its neighbor. - let mut wrapped = Vec::new(); - let mut wrapped_selection = 0..0; - for (index, line) in lines.into_iter().enumerate() { - if index == selection.start { - wrapped_selection.start = wrapped.len(); - } - wrapped.extend(crate::wrapping::word_wrap_lines( - [line], - crate::wrapping::RtOptions::new(table_width.max(/*other*/ 1)), - )); - if index + 1 == selection.end { - wrapped_selection.end = wrapped.len(); - } - } - tables.push(wrapped); - selections.push(wrapped_selection); - } - let mut selection = selections[self.plan.window].clone(); - let mut lines = if side_by_side { - join_columns(&tables[0], &tables[1], table_width) - } else { - if self.plan.window == 1 { - selection = - selection.start + tables[0].len() + 1..selection.end + tables[0].len() + 1; - } - let mut lines = std::mem::take(&mut tables[0]); - lines.push(Line::default()); - lines.append(&mut tables[1]); - lines - }; - if group == 3 { - lines.push( - "By turn start includes Tasks only; percentages use the full period limit" - .dim() - .into(), - ); - } - if let Some(plan::Report { - as_of, - coverage_start, - coverage_complete, - approximate, - .. - }) = self.plan.report.ready() - { - if !*coverage_complete { - lines.push("Some periods aren't available yet".dim().into()); - } - lines.push( - format!( - "Usage as of {} UTC · * current at last update", - as_of.format(self.clock_format.date_time_format()) - ) - .dim() - .into(), - ); - if let Some(start) = coverage_start { - lines.push( - format!( - "Available since {} UTC", - start.format(self.clock_format.date_time_format()) - ) - .dim() - .into(), - ); - } - if *approximate { - lines.push( - "Amounts and period boundaries are approximate; recent activity may be delayed" - .dim() - .into(), - ); - } - } - (lines, selection) - } -} diff --git a/codex-rs/tui/src/analytics/plan_tests.rs b/codex-rs/tui/src/analytics/plan_tests.rs deleted file mode 100644 index 9b0260c8..00000000 --- a/codex-rs/tui/src/analytics/plan_tests.rs +++ /dev/null @@ -1,362 +0,0 @@ -//! Snapshot semantics and independent plan-period navigation without a live billing service. -use super::*; -use crate::analytics::AnalyticsView; -use crate::analytics::fixture; -use crate::analytics::models::AccountKind; -use crate::analytics::sections::Section; -use crossterm::event::KeyCode; -use crossterm::event::KeyEvent; -use crossterm::event::KeyModifiers; -use pretty_assertions::assert_eq; -use serde_json::json; - -fn response() -> PlanLimitHistory { - serde_json::from_value(json!({ - "data_as_of":"2026-09-02T12:00:00Z", "coverage_start":"2026-09-01T00:00:00Z", - "coverage_complete":false, "boundary_tolerance_seconds":60, - "periods":[ - {"id":"five", "window_minutes":300,"plan_type":"plus", - "starts_at":"2026-09-02T10:00:00Z","ends_at":"2026-09-02T15:00:00Z", - "accounting_complete":false,"used_basis_points":12500, - "breakdowns":[ - {"dimension":"future_dimension","rows":[{"key":"future","basis_points":500}]}, - {"dimension":"thread_source","rows":[{"key":"user","basis_points":12500}]}]}, - {"id":"weekly", "window_minutes":10080,"plan_type":"plus", - "starts_at":"2026-09-01T00:00:00Z","ends_at":"2026-09-08T00:00:00Z", - "accounting_complete":true,"used_basis_points":null,"breakdowns":null} - ] - })) - .unwrap() -} - -#[tokio::test] -async fn resize_keeps_visible_weekly_selection_and_respects_manual_scroll() { - let mut history = response(); - for index in 0..12 { - let mut period = history.periods[0].clone(); - period.id = format!("five-{index}"); - history.periods.push(period); - } - let mut view = fixture::view(AccountKind::Consumer); - view.plan.enabled = true; - view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap()); - view.plan.poll(); - view.section = Section::Plan; - view.zoomed = false; - view.plan.expanded[0] = Some("five".into()); - let dashboard = view.dashboard_lines(/*width*/ 120, /*height*/ 60).0; - assert!( - dashboard - .iter() - .any(|line| line.to_string().contains("Weekly limits")) - ); - view.zoomed = true; - view.plan.expanded[0] = None; - let render = |view: &mut AnalyticsView, width, height| { - let mut terminal = - ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height)).unwrap(); - terminal - .draw(|frame| view.render(frame.area(), frame.buffer_mut())) - .unwrap(); - terminal.backend().to_string() - }; - render(&mut view, /*width*/ 80, /*height*/ 24); - for code in [KeyCode::Char('z'), KeyCode::Right] { - view.handle_key(KeyEvent::new(code, KeyModifiers::NONE)); - render(&mut view, /*width*/ 80, /*height*/ 24); - } - view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert!(render(&mut view, /*width*/ 80, /*height*/ 24).contains("Sep 1 00:00 – Sep 8 00:00")); - render(&mut view, /*width*/ 120, /*height*/ 36); - view.handle_key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)); - render(&mut view, /*width*/ 40, /*height*/ 16); - view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - let narrow = render(&mut view, /*width*/ 40, /*height*/ 16); - assert!(view.scroll_offset() > 0); - assert!(narrow.contains("Sep 1 00:00 – Sep 8 00:00")); - assert!(narrow.contains("↑/↓ period · enter details")); - view.handle_key(KeyEvent::new(KeyCode::PageUp, KeyModifiers::NONE)); - render(&mut view, /*width*/ 40, /*height*/ 16); - let reading_position = view.scroll_offset(); - assert!(!view.selection_visible); - for code in [KeyCode::Char('z'), KeyCode::Enter] { - view.handle_key(KeyEvent::new(code, KeyModifiers::NONE)); - render(&mut view, /*width*/ 40, /*height*/ 16); - } - assert_eq!(view.scroll_offset(), reading_position); - view.handle_key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)); - render(&mut view, /*width*/ 50, /*height*/ 16); - view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - render(&mut view, /*width*/ 50, /*height*/ 16); - assert_eq!(view.scroll_offset(), reading_position); - let mut tui = crate::tui::test_support::make_test_tui().unwrap(); - let event = crate::tui::TuiEvent::Resize(ratatui::layout::Size { - width: 55, - height: 16, - }); - tui.screen_size_for_event(&event).unwrap(); - view.handle_event(&mut tui, event).unwrap(); - assert_eq!(view.scroll_offset(), reading_position); - - let mut history = response(); - let breakdown = &mut history.periods[0].breakdowns.as_mut().unwrap()[1]; - breakdown.rows = vec![breakdown.rows[0].clone(); 20]; - view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap()); - view.plan.poll(); - view.plan.window = 0; - view.sections[Section::Plan].group = 1; - view.plan.expanded[0] = Some("five".into()); - view.follow_selection = true; - render(&mut view, /*width*/ 58, /*height*/ 16); - view.handle_key(KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE)); - render(&mut view, /*width*/ 58, /*height*/ 16); - let reading_position = view.scroll_offset(); - assert!(reading_position > 0); - render(&mut view, /*width*/ 60, /*height*/ 16); - assert_eq!(view.scroll_offset(), reading_position); -} - -#[test] -fn period_navigation_preserves_unknowns_and_resets_on_new_snapshot() { - let mut view = fixture::view(AccountKind::Consumer); - view.plan.enabled = true; - view.plan.report = Load::Ready(Report::parse(response()).unwrap().unwrap()); - view.plan.poll(); - view.section = Section::Plan; - view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - view.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); - view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!( - view.plan.expanded, - [Some("five".into()), Some("weekly".into())] - ); - let mut output = Vec::new(); - for width in [120, 58] { - let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new( - width, /*height*/ 30, - )) - .unwrap(); - terminal - .draw(|frame| view.render(frame.area(), frame.buffer_mut())) - .unwrap(); - output.push(terminal.backend().to_string()); - } - insta::assert_snapshot!(output.join("\n")); - let mut next = response(); - next.data_as_of = Some("2026-09-02T13:00:00Z".into()); - view.plan.report = Load::Ready(Report::parse(next).unwrap().unwrap()); - view.plan.poll(); - assert_eq!( - (view.plan.cursor, view.plan.expanded), - ([0, 0], [None, None]) - ); -} - -#[test] -fn unavailable_empty_and_zero_history_are_distinct() { - let mut view = fixture::view(AccountKind::Consumer); - view.plan.enabled = true; - view.section = Section::Plan; - let mut states = Vec::new(); - states.push( - view.plan_lines(/*width*/ 100) - .0 - .iter() - .map(ToString::to_string) - .collect::>() - .join("\n"), - ); - let mut history = response(); - history.coverage_complete = true; - history.periods.clear(); - view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap()); - states.push( - view.plan_lines(/*width*/ 100) - .0 - .iter() - .map(ToString::to_string) - .collect::>() - .join("\n"), - ); - let mut history = response(); - history.periods[0].used_basis_points = Some(0.0); - view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap()); - states.push( - view.plan_lines(/*width*/ 100) - .0 - .iter() - .map(ToString::to_string) - .collect::>() - .join("\n"), - ); - let mut future = response(); - future.periods[0].starts_at = "2026-09-02T13:00:00Z".into(); - view.plan.report = Load::Ready(Report::parse(future).unwrap().unwrap()); - states.push( - view.plan_lines(/*width*/ 100) - .0 - .iter() - .map(ToString::to_string) - .collect::>() - .join("\n"), - ); - let snapshot = states.join("\n\n"); - let snapshot = snapshot - .lines() - .map(str::trim_end) - .collect::>() - .join("\n"); - insta::assert_snapshot!(snapshot); - let mut missing = response(); - missing.data_as_of = None; - assert!(Report::parse(missing).unwrap().is_none()); -} - -#[tokio::test] -async fn plan_gate_prevents_requests_and_unavailable_plan_does_not_block_other_reports() { - use crate::analytics::client; - use crate::analytics::test_support; - use wiremock::Mock; - use wiremock::ResponseTemplate; - use wiremock::matchers::path; - let server = test_support::server().await; - let (_home, _server, mut view) = client::tests::connected_view(&server, "plus").await; - test_support::settle(&mut view).await; - assert!( - !server - .received_requests() - .await - .unwrap() - .iter() - .any(|request| request.url.path().ends_with("plan_limit_history")) - ); - assert!(!view.visible_sections().contains(&Section::Plan)); - Mock::given(path("/backend-api/wham/usage/plan_limit_history")) - .respond_with(ResponseTemplate::new(/*s*/ 404)) - .with_priority(/*p*/ 1) - .expect(/*r*/ 1) - .mount(&server) - .await; - let (mut config, handle, frame) = view.connection.clone().unwrap(); - std::sync::Arc::make_mut(&mut config) - .features - .enable(codex_features::Feature::AnalyticsPlanHistory) - .unwrap(); - view.open(handle, frame, Vec::new(), config); - test_support::settle(&mut view).await; - assert!(matches!(view.plan.report, Load::Unavailable)); - assert!(view.sections[Section::Usage].history.ready().is_some()); - assert!(view.visible_sections().contains(&Section::Plan)); - // Closing cancels the pending plan task along with the other account-owned work. - let (sender, receiver) = tokio::sync::oneshot::channel::<()>(); - view.plan.report = Load::start( - async move { - let _sender = sender; - std::future::pending().await - }, - crate::tui::FrameRequester::test_dummy(), - ); - view.cancel_loads(); - assert!(receiver.await.is_err()); - server.verify().await; - let server = test_support::server().await; - let (_home, _server, mut business) = client::tests::connected_view(&server, "business").await; - let (mut config, handle, frame) = business.connection.clone().unwrap(); - std::sync::Arc::make_mut(&mut config) - .features - .enable(codex_features::Feature::AnalyticsPlanHistory) - .unwrap(); - business.open(handle, frame, Vec::new(), config); - test_support::settle(&mut business).await; - assert!(!business.visible_sections().contains(&Section::Plan)); - assert!(matches!(business.plan.report, Load::Unavailable)); - server.verify().await; -} - -#[test] -fn plan_escape_collapses_details_before_closing() { - let mut view = fixture::view(AccountKind::Consumer); - view.plan.enabled = true; - view.plan.report = Load::Ready(Report::parse(response()).unwrap().unwrap()); - view.plan.poll(); - view.section = Section::Plan; - view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!(!view.is_done); - view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!(view.is_done); -} - -#[test] -fn moving_period_selection_collapses_its_previous_details() { - let mut history = response(); - let mut older = history.periods[0].clone(); - older.starts_at = "2026-09-02T05:00:00Z".into(); - older.ends_at = "2026-09-02T10:00:00Z".into(); - for index in 0..13 { - older.id = format!("older-five-{index}"); - history.periods.push(older.clone()); - } - let mut view = fixture::view(AccountKind::Consumer); - view.plan.enabled = true; - view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap()); - view.plan.poll(); - view.section = Section::Plan; - view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - view.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - assert_eq!( - (&view.plan.cursor, &view.plan.expanded), - (&[1, 0], &[None, None]) - ); - let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new( - /*width*/ 80, /*height*/ 24, - )) - .unwrap(); - for code in [KeyCode::Right, KeyCode::Tab, KeyCode::BackTab] { - view.handle_key(KeyEvent::new(code, KeyModifiers::NONE)); - terminal - .draw(|frame| view.render(frame.area(), frame.buffer_mut())) - .unwrap(); - if view.section == Section::Plan { - assert!( - terminal - .backend() - .to_string() - .contains("Sep 1 00:00 – Sep 8 00:00") - ); - } - } -} - -#[test] -fn invalid_history_returns_safe_errors() { - for invalid in 0..5 { - let mut history = response(); - match invalid { - 0 => history.periods[0].starts_at = "private wire value".into(), - 1 => history.periods[0].ends_at = history.periods[0].starts_at.clone(), - 2 => history.periods.push(history.periods[0].clone()), - 3 => history.periods[0].window_minutes = 1, - _ => history.periods[0].used_basis_points = Some(f64::INFINITY), - } - let error = Report::parse(history).err().unwrap(); - assert!(!error.contains("private wire value")); - } -} - -#[test] -fn plan_clocks_follow_preference_and_keep_utc() { - let mut view = fixture::view(AccountKind::Consumer); - view.clock_format = crate::clock_format::ClockFormat::TwelveHour; - view.plan.enabled = true; - view.section = Section::Plan; - view.plan.report = Load::Ready(Report::parse(response()).unwrap().unwrap()); - let rendered = view - .plan_lines(/*width*/ 80) - .0 - .iter() - .map(ToString::to_string) - .collect::>() - .join("\n"); - insta::assert_snapshot!("plan_clocks_twelve_hour", rendered); -} diff --git a/codex-rs/tui/src/analytics/plot.rs b/codex-rs/tui/src/analytics/plot.rs deleted file mode 100644 index e9f0357a..00000000 --- a/codex-rs/tui/src/analytics/plot.rs +++ /dev/null @@ -1,176 +0,0 @@ -//! Daily stacked bars with fixed calendar ticks, a selection cursor, and an anchored value. -//! Relative usage retains the server's scale; signed credits keep both bands. - -mod annotations; -mod layout; -mod painting; - -use self::layout::Layout; -use self::painting::Band; -use super::data; -use super::data::compact_amount as tick; -use super::render::parts; -use crate::analytics::models::AccountAnalyticsDay; -use crate::analytics::models::AccountAnalyticsUnit; -use crate::analytics::models::AccountAnalyticsValue; -use chrono::NaiveDate; -use ratatui::buffer::Buffer; -use ratatui::layout::Rect; -use ratatui::text::Line; -use ratatui::text::Span; -use unicode_width::UnicodeWidthStr; - -/// Share the chart's scale with the selected-day summary, including signed values. -pub(super) fn peak( - days: &[(NaiveDate, Option<&AccountAnalyticsDay>)], - categories: &[AccountAnalyticsValue], -) -> f64 { - days.iter() - .filter_map(|(_, day)| *day) - .map(|day| { - parts(&day.values, categories) - .iter() - .map(|value| value.abs()) - .sum::() - .max(day.total.abs()) - }) - .fold(/*init*/ 0.0, f64::max) -} - -/// Two readable intervals cover the range; counts never use fractional ticks. -pub(super) fn axis_max(peak: f64, unit: AccountAnalyticsUnit) -> f64 { - if peak == 0.0 { - return if matches!( - unit, - AccountAnalyticsUnit::Count | AccountAnalyticsUnit::Tokens - ) { - 2.0 - } else { - 1.0 - }; - } - let step = if matches!( - unit, - AccountAnalyticsUnit::Count | AccountAnalyticsUnit::Tokens - ) { - (peak / 2.0).max(/*other*/ 1.0) - } else { - peak / 2.0 - }; - let magnitude = 10.0_f64.powf(step.log10().floor()); - let normalized = step / magnitude; - let multiple = [1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 7.5, 10.0] - .into_iter() - .find(|multiple| { - *multiple >= normalized - && (!matches!( - unit, - AccountAnalyticsUnit::Count | AccountAnalyticsUnit::Tokens - ) || (multiple * magnitude).fract() == 0.0) - }) - .unwrap_or(/*default*/ 10.0); - let ceiling = multiple * magnitude * 2.0; - if ceiling.is_finite() && ceiling >= peak { - ceiling - } else { - peak - } -} - -/// Rendered chart geometry exposes its positive and optional negative value bands. -#[derive(Default)] -pub(super) struct Chart { - pub(super) lines: Vec>, - pub(super) bands: usize, -} - -/// Render a calendar selection; the cursor must index days and dimensions fit the terminal. -pub(super) fn chart( - days: &[(NaiveDate, Option<&AccountAnalyticsDay>)], - categories: &[AccountAnalyticsValue], - cursor: usize, - width: usize, - height: usize, - unit: AccountAnalyticsUnit, -) -> Chart { - if days.is_empty() || width == 0 { - return Chart::default(); - } - let values = days - .iter() - .map(|(_, day)| { - day.map_or( - /*default*/ [0.0; 4], - |day| parts(&day.values, categories), - ) - }) - .collect::>(); - let bands = if values.iter().flatten().any(|value| *value < 0.0) { - &[Band::Positive, Band::Negative][..] - } else { - &[Band::Positive][..] - }; - let peak = axis_max(peak(days, categories), unit); - let label_width = tick(peak).width().max(tick(peak / 2.0).width()) + bands.len() - 1 + 2; - let layout = Layout::new(days.len(), cursor, width, height, label_width, bands); - let renderer = Renderer { - days, - values, - cursor, - peak, - unit, - bands, - layout, - }; - let mut buf = Buffer::empty(Rect::new( - /*x*/ 0, - /*y*/ 0, - width as u16, - (layout.marker_row + 2) as u16, - )); - renderer.paint_bars(&mut buf); - renderer.annotate_missing(&mut buf); - renderer.paint_axis(&mut buf); - renderer.annotate_selection(&mut buf); - renderer.annotate_calendar(&mut buf); - let lines = buf - .content - .chunks(width) - .map(|row| { - Line::from( - row.iter() - .map(|cell| Span::styled(cell.symbol().to_owned(), cell.style())) - .collect::>(), - ) - }) - .collect(); - Chart { - lines, - bands: bands.len(), - } -} - -/// Shared inputs for painting and annotations; all phases use the same calendar geometry. -struct Renderer<'a> { - days: &'a [(NaiveDate, Option<&'a AccountAnalyticsDay>)], - values: Vec<[f64; 4]>, - cursor: usize, - peak: f64, - unit: AccountAnalyticsUnit, - bands: &'static [Band], - layout: Layout, -} - -fn amount(value: f64, unit: AccountAnalyticsUnit) -> String { - match unit { - AccountAnalyticsUnit::RelativeUsage => data::amount(value), - AccountAnalyticsUnit::Count | AccountAnalyticsUnit::Tokens => { - data::compact_amount(value.round()) - } - AccountAnalyticsUnit::Credits => data::credit_amount(value), - } -} - -#[cfg(test)] -#[path = "plot_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/plot/annotations.rs b/codex-rs/tui/src/analytics/plot/annotations.rs deleted file mode 100644 index 0ebd2639..00000000 --- a/codex-rs/tui/src/analytics/plot/annotations.rs +++ /dev/null @@ -1,213 +0,0 @@ -//! Missing-day markers, daily-value callouts, and stable calendar labels. - -use super::Renderer; -use super::amount; -use super::layout::Layout; -use super::painting::Band; -use crate::analytics::styles::secondary_style; -use crate::color::is_light; -use crate::style::accent_style; -use crate::terminal_palette::default_bg; -use ratatui::buffer::Buffer; -use ratatui::style::Style; -use ratatui::style::Styled; -use ratatui::style::Stylize; -use ratatui::text::Line; -use unicode_width::UnicodeWidthStr; - -impl Renderer<'_> { - pub(super) fn annotate_missing(&self, buf: &mut Buffer) { - let Layout { - count, - height, - start, - .. - } = self.layout; - for (index, parts) in self.values[start..start + count].iter().enumerate() { - // The selected zero/missing value gets its own callout below; avoid repeating it. - if start + index != self.cursor { - let marker = match self.days[start + index].1 { - None => Some('—'), - Some(day) if day.total == 0.0 && parts.iter().all(|value| *value == 0.0) => { - Some('0') - } - Some(_) => None, - }; - if let Some(marker) = marker { - buf[(self.layout.center(index) as u16, height as u16)] - .set_char(marker) - .set_style(Style::default().dim()); - } - } - } - } - - pub(super) fn annotate_selection(&self, buf: &mut Buffer) { - let Layout { - axis_width, - baseline, - height, - marker_row, - plot_width, - start, - width, - .. - } = self.layout; - // Give the selected value first choice of space; the other labels never overwrite it. - for index in - std::iter::once(self.cursor).chain((start..start + self.layout.count).filter(|index| { - self.days.len() <= 7 - && *index != self.cursor - && self.days[*index].1.is_some_and(|day| { - day.total != 0.0 || self.values[*index].iter().any(|value| *value != 0.0) - }) - })) - { - let total = self.days[index].1.map_or(/*default*/ 0.0, |day| day.total); - let label = self.days[index] - .1 - .map_or_else(|| "—".into(), |_| amount(total, self.unit)); - // A partial number can mean a different amount; leave the cursor when the value cannot fit. - if label.width() > plot_width { - continue; - } - let x = self.layout.center(index - start); - let label_width = label.width(); - let label_x = x - .saturating_sub(label_width / 2) - .clamp(axis_width, width - label_width); - let occupied = label_x.saturating_sub(/*rhs*/ 1).max(axis_width) - ..(label_x + label_width + 1).min(width); - let below = total < 0.0; - let band = if below { - Band::Negative - } else { - Band::Positive - }; - let extent = self.values[index] - .iter() - .map(|value| band.amount(*value)) - .sum::(); - let rows = ((extent * height as f64 / self.peak).ceil() as usize).min(height); - let cap = if below { - baseline + rows - } else { - baseline - rows - }; - let mut label_y = if below { - cap + 1 - } else { - cap.saturating_sub(/*rhs*/ 1) - }; - // Keep the callout close without painting over a neighboring bar. A guide connects any gap. - while occupied - .clone() - .any(|col| buf[(col as u16, label_y as u16)].symbol() != " ") - { - if below && label_y + 1 < marker_row { - label_y += 1; - } else if !below && label_y > 0 { - label_y -= 1; - } else { - break; - } - } - if occupied - .clone() - .any(|col| buf[(col as u16, label_y as u16)].symbol() != " ") - { - continue; - } - // Use white on dark backgrounds and the terminal foreground on light backgrounds. - let style = if index == self.cursor { - let selected = Style::default().bold().not_dim(); - if default_bg().is_some_and(is_light) { - selected - } else { - selected.white() - } - } else { - Style::default().dim() - }; - let guide = if below { - cap + 1..label_y - } else { - label_y + 1..cap - }; - for y in guide { - let cell = &mut buf[(x as u16, y as u16)]; - if cell.symbol() == " " { - cell.set_char('┊').set_style(style); - } - } - buf.set_line( - label_x as u16, - label_y as u16, - &Line::from(label.set_style(style)), - label_width as u16, - ); - } - let x = self.layout.center(self.cursor - start); - buf[(x as u16, marker_row as u16)] - .set_char('▲') - .set_style(accent_style()); - } - - pub(super) fn annotate_calendar(&self, buf: &mut Buffer) { - let Layout { - axis_width, - count, - marker_row, - plot_width, - start, - width, - .. - } = self.layout; - // Calendar ticks depend only on the range/width, never on the current selection. - let mut occupied = vec![false; width]; - // Give the two range endpoints priority over intermediate weekly ticks. - for index in std::iter::once(/*value*/ 0).chain((1..count).rev()) { - if self.days.len() > 7 - && !(start + index).is_multiple_of(/*rhs*/ 7) - && index + 1 != count - { - continue; - } - let format = if self.days.len() <= 7 && plot_width / count < 7 { - "%-d" - } else { - "%b %-d" - }; - let mut label = self.days[start + index].0.format(format).to_string(); - if label.width() > plot_width { - label = self.days[start + index].0.format("%-d").to_string(); - } - if label.width() > plot_width { - continue; - } - let offset = self - .layout - .center(index) - .saturating_sub(label.len() / 2) - .clamp(axis_width, width - label.len()); - if occupied[offset.saturating_sub(/*rhs*/ 1)..(offset + label.len() + 1).min(width)] - .iter() - .any(|used| *used) - { - continue; - } - occupied[offset..offset + label.len()].fill(/*value*/ true); - let label = if start + index == self.cursor { - label.set_style(accent_style()).underlined() - } else { - label.set_style(secondary_style()) - }; - buf.set_line( - offset as u16, - (marker_row + 1) as u16, - &Line::from(label), - (width - offset) as u16, - ); - } - } -} diff --git a/codex-rs/tui/src/analytics/plot/layout.rs b/codex-rs/tui/src/analytics/plot/layout.rs deleted file mode 100644 index e3d8a9e2..00000000 --- a/codex-rs/tui/src/analytics/plot/layout.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Calendar viewport and shared coordinates for bars, axes, and annotations. - -use super::painting::Band; - -#[derive(Clone, Copy)] -pub(super) struct Layout { - pub(super) width: usize, - pub(super) height: usize, - pub(super) axis_width: usize, - pub(super) plot_width: usize, - pub(super) count: usize, - pub(super) start: usize, - pub(super) baseline: usize, - pub(super) marker_row: usize, -} - -impl Layout { - pub(super) fn new( - day_count: usize, - cursor: usize, - width: usize, - height: usize, - label_width: usize, - bands: &[Band], - ) -> Self { - // Hide the axis when a complete label would crowd out the bars. - let axis_width = if width >= 30 && label_width <= width / 3 { - label_width - } else { - 0 - }; - let plot_width = width - axis_width; - let count = day_count.min(plot_width); - let start = cursor.saturating_sub(count - 1).min(day_count - count); - let baseline = height + 1; - let marker_row = baseline + if bands.len() == 2 { height + 2 } else { 1 }; - Self { - width, - height, - axis_width, - plot_width, - count, - start, - baseline, - marker_row, - } - } - - pub(super) fn center(self, index: usize) -> usize { - self.axis_width - + (index * self.plot_width / self.count + (index + 1) * self.plot_width / self.count - - 1) - / 2 - } -} diff --git a/codex-rs/tui/src/analytics/plot/painting.rs b/codex-rs/tui/src/analytics/plot/painting.rs deleted file mode 100644 index 03f6633c..00000000 --- a/codex-rs/tui/src/analytics/plot/painting.rs +++ /dev/null @@ -1,132 +0,0 @@ -//! Paint signed bar cells and numeric axes using the shared layout and scale. - -use super::Renderer; -use super::layout::Layout; -use super::tick; -use crate::analytics::styles::secondary_style; -use crate::analytics::styles::series_colors; -use ratatui::buffer::Buffer; -use ratatui::style::Style; -use ratatui::style::Styled; -use ratatui::text::Line; - -/// A signed stack grows away from the baseline; amounts are nonnegative within each band. -#[derive(Clone, Copy)] -pub(super) enum Band { - Positive, - Negative, -} - -impl Band { - pub(super) fn amount(self, value: f64) -> f64 { - match self { - Self::Positive => value, - Self::Negative => -value, - } - .max(/*other*/ 0.0) - } - - fn row_y(self, baseline: usize, row: usize) -> usize { - match self { - Self::Positive => baseline - row - 1, - Self::Negative => baseline + row + 1, - } - } - - fn partial_glyph(self, level: usize) -> char { - // Reversing the complementary lower block paints a top-anchored partial refund. - let index = match self { - Self::Negative if level < 8 => 8 - level, - Self::Positive | Self::Negative => level, - }; - [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'][index] - } -} - -impl Renderer<'_> { - pub(super) fn paint_bars(&self, buf: &mut Buffer) { - let Layout { - axis_width, - baseline, - count, - height, - plot_width, - start, - .. - } = self.layout; - let colors = series_colors(); - for (index, parts) in self.values[start..start + count].iter().enumerate() { - let left = axis_width + index * plot_width / count; - let step = (index + 1) * plot_width / count - index * plot_width / count; - let bar_width = (step * 2 / 3).clamp(/*min*/ 1, /*max*/ 12); - let x = left + (step - bar_width) / 2; - for band in self.bands { - let plotted = parts.iter().map(|value| band.amount(*value)).sum::(); - let scaled = ((plotted * (height * 8) as f64 / self.peak) as usize) - .max(usize::from(plotted > 0.0)); - for row in 0..height { - let level = scaled.saturating_sub(row * 8).min(/*other*/ 8); - if level == 0 { - continue; - } - let reverse = matches!(band, Band::Negative) && level < 8; - let glyph = band.partial_glyph(level); - let bottom = (row * 8) as f64 * self.peak / (height * 8) as f64; - let top = - ((row * 8 + level) as f64 * self.peak / (height * 8) as f64).min(plotted); - let sample = bottom + (top - bottom) / 2.0; - let mut cumulative = 0.0; - let color = parts - .iter() - .position(|value| { - cumulative += band.amount(*value); - sample < cumulative - }) - .unwrap_or(/*default*/ 3); - let y = band.row_y(baseline, row); - for col in x..x + bar_width { - let cell = &mut buf[(col as u16, y as u16)]; - cell.set_char(glyph).set_fg(colors[color]); - if reverse { - cell.set_style(Style::default().reversed()); - } - } - } - } - } - } - - pub(super) fn paint_axis(&self, buf: &mut Buffer) { - let Layout { - axis_width, - baseline, - height, - width, - .. - } = self.layout; - for x in axis_width..width { - buf[(x as u16, baseline as u16)] - .set_char('─') - .set_style(Style::default().dim()); - } - if axis_width > 0 { - let mut ticks = vec![(1, self.peak), (baseline, 0.0)]; - if height >= 4 { - ticks.push((1 + height / 2, self.peak / 2.0)); - } - if self.bands.len() == 2 { - ticks.push((baseline + height, -self.peak)); - } - for (y, value) in ticks { - let label = tick(value); - let x = axis_width.saturating_sub(label.len() + 1); - buf.set_line( - x as u16, - y as u16, - &Line::from(label.set_style(secondary_style())), - axis_width as u16, - ); - } - } - } -} diff --git a/codex-rs/tui/src/analytics/plot_tests.rs b/codex-rs/tui/src/analytics/plot_tests.rs deleted file mode 100644 index b78a6ebe..00000000 --- a/codex-rs/tui/src/analytics/plot_tests.rs +++ /dev/null @@ -1,535 +0,0 @@ -//! Chart scales, signed bands, missing days, narrow viewports, and terminal palettes. - -use super::*; -use crate::analytics::models::AccountAnalyticsHistory; -use crate::analytics::render::categories; -use crate::analytics::styles::series_colors; -use crate::terminal_palette::with_test_default_colors; -use crate::terminal_probe::DefaultColors; -use pretty_assertions::assert_eq; - -fn value(key: &str, value: f64) -> AccountAnalyticsValue { - AccountAnalyticsValue { - key: key.into(), - label: key.into(), - value, - } -} - -fn display(chart: &Chart) -> String { - let text = chart - .lines - .iter() - .map(|line| line.to_string().trim_end().to_owned()) - .collect::>() - .join("\n"); - let mut palette = Vec::new(); - let mut rows = Vec::new(); - for (row, line) in chart.lines.iter().enumerate() { - let mut previous = None; - let mut runs = Vec::new(); - let mut column = 0; - for span in &line.spans { - let style = format!("{:?}", span.style); - let index = palette - .iter() - .position(|candidate| *candidate == style) - .unwrap_or_else(|| { - palette.push(style); - palette.len() - 1 - }); - if previous != Some(index) { - runs.push(format!("{column}:{index}")); - previous = Some(index); - } - column += span.width(); - } - rows.push(format!("{row}: {}", runs.join(" "))); - } - let palette = palette - .iter() - .enumerate() - .map(|(index, style)| format!("{index}: {style}")) - .collect::>() - .join("\n"); - format!( - "{text}\n\nPalette:\n{palette}\nRows (column:palette):\n{}", - rows.join("\n") - ) -} - -#[test] -fn numeric_axes_use_readable_intervals() { - use AccountAnalyticsUnit::Count; - use AccountAnalyticsUnit::Credits; - use AccountAnalyticsUnit::RelativeUsage; - use AccountAnalyticsUnit::Tokens; - let cases = [ - (82.0, Count, 100.0), - (4_400.0, Credits, 5_000.0), - (4_999.0, Credits, 5_000.0), - (5_001.0, Credits, 6_000.0), - (49.0, Count, 50.0), - (1.0, Count, 2.0), - (3.0, Count, 4.0), - (1_337.0, Credits, 1_500.0), - (0.07, Credits, 0.08), - (0.000004, Credits, 0.000004), - (82.0, RelativeUsage, 100.0), - (1.0, Tokens, 2.0), - ]; - assert_eq!( - cases.map(|(peak, unit, _)| axis_max(peak, unit)), - cases.map(|(_, _, expected)| expected) - ); -} - -#[test] -fn stacked_parts_keep_the_remainder_and_full_denominator() { - let values = vec![ - value("a", /*value*/ 4.0), - value("b", /*value*/ 2.0), - value("c", /*value*/ 1.0), - value("d", /*value*/ 6.0), - value("e", /*value*/ -1.0), - ]; - let categories = vec![values[1].clone(), values[0].clone(), values[2].clone()]; - assert_eq!(parts(&values, &categories), [2.0, 4.0, 1.0, 5.0]); - let day = AccountAnalyticsDay { - date: "2026-01-15".parse().unwrap(), - total: 20.0, - values, - }; - let date = day.date; - assert_eq!(peak(&[(date, Some(&day))], &categories), 20.0); - let refund = AccountAnalyticsDay { - total: -1.0, - values: vec![value("a", /*value*/ 4.0), value("b", /*value*/ -5.0)], - ..day - }; - assert_eq!(peak(&[(date, Some(&refund))], &categories), 9.0); -} - -#[test] -fn signed_chart_on_light_terminal() { - signed_chart( - "light", - DefaultColors { - fg: (0, 0, 0), - bg: (255, 255, 255), - }, - ); -} - -#[test] -fn signed_chart_on_dark_terminal() { - signed_chart( - "dark", - DefaultColors { - fg: (230, 230, 230), - bg: (16, 16, 16), - }, - ); -} - -fn signed_chart(theme: &str, colors: DefaultColors) { - let history = AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::Credits, - updated_at: None, - data: vec![ - AccountAnalyticsDay { - date: "2026-01-13".parse().unwrap(), - total: 8.0, - values: vec![value("a", /*value*/ 10.0), value("b", /*value*/ -2.0)], - }, - AccountAnalyticsDay { - date: "2026-01-14".parse().unwrap(), - total: -3.0, - values: vec![value("a", /*value*/ 1.0), value("b", /*value*/ -4.0)], - }, - AccountAnalyticsDay { - date: "2026-01-15".parse().unwrap(), - total: 0.0, - values: vec![value("a", /*value*/ 3.0), value("b", /*value*/ -3.0)], - }, - ], - }; - let days = history - .data - .iter() - .map(|day| (day.date, Some(day))) - .collect::>(); - let categories = categories(&history); - with_test_default_colors(colors, || { - let rendered = chart( - &days, - &categories, - /*cursor*/ 1, - /*width*/ 44, - /*height*/ 4, - history.unit, - ); - assert_eq!(rendered.bands, 2); - insta::assert_snapshot!(format!("signed_chart_{theme}"), display(&rendered)); - }); -} - -#[test] -fn missing_zero_and_narrow_charts_keep_the_selection_visible() { - let zero = AccountAnalyticsDay { - date: "2026-01-14".parse().unwrap(), - total: 0.0, - values: vec![value("a", /*value*/ 0.0)], - }; - let used = AccountAnalyticsDay { - date: "2026-01-15".parse().unwrap(), - total: 5.0, - values: vec![value("a", /*value*/ 5.0)], - }; - let days = [ - ("2026-01-13".parse().unwrap(), None), - (zero.date, Some(&zero)), - (used.date, Some(&used)), - ]; - with_test_default_colors( - DefaultColors { - fg: (230, 230, 230), - bg: (16, 16, 16), - }, - || { - let mut snapshots = Vec::new(); - for (width, cursor) in [(36, 0), (36, 1), (8, 2), (1, 2)] { - let rendered = chart( - &days, - &used.values, - cursor, - width, - /*height*/ 3, - AccountAnalyticsUnit::Count, - ); - assert_eq!(rendered.bands, 1); - assert!(rendered.lines.iter().all(|line| line.width() <= width)); - assert_eq!( - rendered - .lines - .iter() - .flat_map(|line| &line.spans) - .filter(|span| span.content == "▲") - .count(), - 1 - ); - if cursor == 0 { - let dash = rendered - .lines - .iter() - .find_map(|line| line.to_string().find('—')); - let cursor = rendered - .lines - .iter() - .find_map(|line| line.to_string().find('▲')); - assert_eq!(dash, cursor); - } - snapshots.push(format!( - "width={width}, cursor={cursor}\n{}", - display(&rendered) - )); - } - insta::assert_snapshot!(snapshots.join("\n\n")); - }, - ); -} - -#[test] -fn zero_credit_history_uses_a_readable_scale() { - let history = crate::analytics::normalize::history( - serde_json::from_str(r#"{"data":[]}"#).unwrap(), - crate::analytics::models::AccountAnalyticsReport::Credits, - crate::analytics::models::AccountAnalyticsGrouping::Surface, - "2026-01-09".parse().unwrap(), - "2026-01-15".parse().unwrap(), - ) - .unwrap() - .unwrap(); - let days = history - .data - .iter() - .map(|day| (day.date, Some(day))) - .collect::>(); - let rendered = chart( - &days, - &[], - /*cursor*/ 6, - /*width*/ 44, - /*height*/ 4, - history.unit, - ); - assert_eq!(axis_max(peak(&days, &[]), history.unit), 1.0); - insta::assert_snapshot!(display(&rendered)); -} - -#[test] -fn partial_cells_use_the_midpoint_and_descend_from_the_baseline() { - let categories = vec![value("a", /*value*/ 0.8), value("b", /*value*/ 0.95)]; - let mut snapshots = Vec::new(); - for sign in [1.0, -1.0] { - let day = AccountAnalyticsDay { - date: "2026-01-14".parse().unwrap(), - total: 1.75 * sign, - values: categories - .iter() - .map(|value| AccountAnalyticsValue { - value: value.value * sign, - ..value.clone() - }) - .collect(), - }; - let days = [ - (day.date, Some(&day)), - ("2026-01-15".parse().unwrap(), None), - ]; - let rendered = chart( - &days, - &categories, - /*cursor*/ 1, - /*width*/ 12, - /*height*/ 1, - AccountAnalyticsUnit::Credits, - ); - let cell = &rendered.lines[if sign > 0.0 { 1 } else { 3 }].spans[1]; - assert_eq!(cell.style.fg, Some(series_colors()[1])); - assert_eq!(cell.content.as_ref(), if sign > 0.0 { "▇" } else { "▁" }); - assert_eq!( - cell.style - .add_modifier - .contains(ratatui::style::Modifier::REVERSED), - sign < 0.0 - ); - snapshots.push(format!("sign={sign}\n{}", display(&rendered))); - } - insta::assert_snapshot!(snapshots.join("\n\n")); -} - -#[test] -fn oversized_axes_are_hidden_instead_of_truncated() { - let mut snapshots = Vec::new(); - for (width, total) in [ - (8, 100_000_000.0), - (30, 100_000_000.0), - (35, 100_000_000.0), - (44, 100_000_000.0), - (30, 1e30), - ] { - let day = AccountAnalyticsDay { - date: "2026-01-15".parse().unwrap(), - total, - values: vec![value("a", total)], - }; - let days = [(day.date, Some(&day))]; - - let rendered = chart( - &days, - &day.values, - /*cursor*/ 0, - width, - /*height*/ 4, - AccountAnalyticsUnit::Tokens, - ); - let baseline = rendered.lines[5].to_string(); - assert_eq!(baseline.starts_with('─'), width < 30 || total == 1e30); - if width == 8 { - assert!(rendered.lines[0].to_string().contains("100M")); - } - snapshots.push(format!("width={width}\n{}", display(&rendered))); - } - insta::assert_snapshot!(snapshots.join("\n\n")); -} - -#[test] -fn selected_callout_keeps_the_authoritative_daily_total() { - let day = AccountAnalyticsDay { - date: "2026-01-15".parse().unwrap(), - total: 20.0, - values: vec![value("a", /*value*/ 8.0), value("b", /*value*/ 4.0)], - }; - let days = [(day.date, Some(&day))]; - let rendered = chart( - &days, - &day.values, - /*cursor*/ 0, - /*width*/ 44, - /*height*/ 4, - AccountAnalyticsUnit::Credits, - ); - assert!(display(&rendered).contains("20.00")); - assert!(!display(&rendered).contains("12.00")); - insta::assert_snapshot!(display(&rendered)); -} - -#[test] -fn narrow_long_range_charts_never_truncate_dates() { - let start: NaiveDate = "2026-01-01".parse().unwrap(); - let history = start - .iter_days() - .take(/*n*/ 30) - .map(|date| AccountAnalyticsDay { - date, - total: 1.0, - values: vec![value("a", /*value*/ 1.0)], - }) - .collect::>(); - let days = history - .iter() - .map(|day| (day.date, Some(day))) - .collect::>(); - let mut snapshots = Vec::new(); - for (width, expected) in [(1, ""), (2, "15"), (5, "15"), (6, "Jan 15")] { - let rendered = chart( - &days, - &history[0].values, - /*cursor*/ 14, - width, - /*height*/ 3, - AccountAnalyticsUnit::Count, - ); - assert_eq!(rendered.lines.last().unwrap().to_string().trim(), expected); - snapshots.push(format!("width={width}\n{}", display(&rendered))); - } - insta::assert_snapshot!(snapshots.join("\n\n")); -} - -#[test] -fn tiny_segments_keep_their_series_color_beside_a_large_day() { - let large = AccountAnalyticsDay { - date: "2026-01-14".parse().unwrap(), - total: 100.0, - values: vec![value("a", /*value*/ 100.0)], - }; - let mut snapshots = Vec::new(); - for sign in [1.0, -1.0] { - let tiny = AccountAnalyticsDay { - date: "2026-01-15".parse().unwrap(), - total: 0.01 * sign, - values: vec![value("a", 0.01 * sign)], - }; - let days = [(large.date, Some(&large)), (tiny.date, Some(&tiny))]; - let rendered = chart( - &days, - &large.values, - /*cursor*/ 0, - /*width*/ 44, - /*height*/ 4, - AccountAnalyticsUnit::Credits, - ); - let glyph = if sign > 0.0 { "▁" } else { "▇" }; - let cells = rendered - .lines - .iter() - .flat_map(|line| &line.spans) - .filter(|span| span.content == glyph) - .collect::>(); - assert!(!cells.is_empty()); - assert!( - cells - .iter() - .all(|cell| cell.style.fg == Some(series_colors()[0])) - ); - snapshots.push(format!("sign={sign}\n{}", display(&rendered))); - } - insta::assert_snapshot!(snapshots.join("\n\n")); -} - -#[test] -fn duplicate_message_dates_render_the_full_other_remainder() { - use crate::analytics::models::AccountAnalyticsGrouping; - use crate::analytics::models::AccountAnalyticsReport; - let date = "2026-01-15".parse().unwrap(); - let response = serde_json::from_value(serde_json::json!({"data": [ - {"date": "2026-01-15", "totals": {"turns": 10}, "clients": [{"client_id": "CODEX_CLI", "turns": 8}]}, - {"date": "2026-01-15", "totals": {"turns": 10}, "clients": [{"client_id": "CODEX_CLI", "turns": 8}]} - ]})).unwrap(); - let history = crate::analytics::normalize::history( - response, - AccountAnalyticsReport::Messages, - AccountAnalyticsGrouping::Surface, - date, - date, - ) - .unwrap() - .unwrap(); - let day = &history.data[0]; - let rendered = chart( - &[(date, Some(day))], - &day.values, - /*cursor*/ 0, - /*width*/ 44, - /*height*/ 10, - AccountAnalyticsUnit::Count, - ); - insta::assert_snapshot!(display(&rendered)); -} - -#[test] -fn seven_day_totals_render_without_selecting_each_bar() { - let start: NaiveDate = "2026-01-01".parse().unwrap(); - let rows = (0..7) - .map(|index| AccountAnalyticsDay { - date: start + chrono::Duration::days(index), - total: 111.0 + index as f64 * 100.0, - values: vec![value("a", 111.0 + index as f64 * 100.0)], - }) - .collect::>(); - let days = rows - .iter() - .map(|day| (day.date, Some(day))) - .collect::>(); - let rendered = chart( - &days, - &rows[0].values, - /*cursor*/ 3, - /*width*/ 100, - /*height*/ 8, - AccountAnalyticsUnit::Count, - ); - let text = display(&rendered); - for day in &rows { - assert!(text.contains(&day.total.to_string())); - } - insta::assert_snapshot!("seven_day_totals", text); -} - -#[test] -fn narrow_equal_height_totals_remain_separate_numbers() { - let start: NaiveDate = "2026-01-01".parse().unwrap(); - let rows = (0..7) - .map(|index| AccountAnalyticsDay { - date: start + chrono::Duration::days(index), - total: 111.0, - values: vec![value("a", /*value*/ 111.0)], - }) - .collect::>(); - let days = rows - .iter() - .map(|day| (day.date, Some(day))) - .collect::>(); - let mut screens = Vec::new(); - for width in [21, 28, 35] { - let rendered = chart( - &days, - &rows[0].values, - /*cursor*/ 3, - width, - /*height*/ 4, - AccountAnalyticsUnit::Count, - ); - let text = rendered - .lines - .iter() - .map(|line| line.to_string().trim_end().to_owned()) - .collect::>() - .join("\n"); - assert!(text.contains("111")); - assert!(!text.contains("111111")); - screens.push(text); - } - insta::assert_snapshot!(screens.join("\n\n")); -} diff --git a/codex-rs/tui/src/analytics/profile_identity_tests.rs b/codex-rs/tui/src/analytics/profile_identity_tests.rs deleted file mode 100644 index 0b5c0430..00000000 --- a/codex-rs/tui/src/analytics/profile_identity_tests.rs +++ /dev/null @@ -1,28 +0,0 @@ -//! In-flight profile responses cannot expose data after the active account changes. -use super::*; -use pretty_assertions::assert_eq; - -#[tokio::test] -async fn profile_rejects_account_change_during_success_or_error_response() { - let server = MockServer::start().await; - for status in [200, 404, 503] { - server.reset().await; - let (home, live) = live(&server, "plus").await; - let home_path = home.path().to_path_buf(); - Mock::given(method("GET")) - .and(path("/backend-api/wham/profiles/me")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(move |_: &wiremock::Request| { - sign_in(&home_path, "account-a", "user-b", "plus"); - ResponseTemplate::new(status) - .set_body_json(json!({"stats":{"lifetime_tokens":123}})) - }) - .expect(/*r*/ 1) - .mount(&server) - .await; - assert_eq!( - live.profile().await.err().unwrap(), - "Account changed. Press R to refresh Analytics." - ); - } -} diff --git a/codex-rs/tui/src/analytics/recovery_tests.rs b/codex-rs/tui/src/analytics/recovery_tests.rs deleted file mode 100644 index 76bf3744..00000000 --- a/codex-rs/tui/src/analytics/recovery_tests.rs +++ /dev/null @@ -1,76 +0,0 @@ -//! Restored dashboard, visible controls, and responsive report regression coverage. - -use super::*; - -#[test] -fn report_controls_show_dates_and_update_time() { - let mut view = fixture::view(models::AccountKind::Business); - view.section = Section::Usage; - view.sections[Section::Usage].group = 6; - fixture::seed_reports(&mut view); - view.end_date = "2027-01-02".parse().unwrap(); - let output = screen(&mut view, /*width*/ 40, /*height*/ 16); - assert!(output.contains("12/27/2026–01/02/2027")); - assert!(output.contains("g Token type · m All models")); - assert!(output.contains("Updated · Sep 2 16:00 UTC")); -} - -#[test] -fn twelve_hour_metadata_keeps_utc_across_renderers() { - let mut view = fixture::view(models::AccountKind::Business); - view.clock_format = crate::clock_format::ClockFormat::TwelveHour; - view.section = Section::Usage; - let controls = screen(&mut view, /*width*/ 40, /*height*/ 16); - view.zoomed = false; - view.tasks = Load::Ready(tasks::Chats { - rows: vec![tasks::Chat { - title: "Clock fixture".into(), - task: None, - }], - updated_at: Some("2026-09-02T16:00:00Z".parse().unwrap()), - ..tasks::Chats::default() - }); - let mut output = controls - .lines() - .filter(|line| line.contains("Updated")) - .map(str::to_owned) - .collect::>(); - for lines in [ - view.history_lines(Section::Usage, /*width*/ 40, /*height*/ 16) - .lines, - view.help_lines(/*width*/ 40), - view.task_lines(/*width*/ 80).0, - ] { - output.extend( - lines - .iter() - .map(ToString::to_string) - .filter(|line| line.contains("Updated") || line.contains("Report updated")), - ); - } - insta::assert_snapshot!(output.join("\n")); -} - -#[test] -fn tall_reports_use_available_height_and_wide_reports_put_details_beside_plot() { - for (width, height) in [(80, 60), (180, 60)] { - let mut view = fixture::view(models::AccountKind::Business); - view.section = Section::Usage; - let output = screen(&mut view, width, height); - let plot_rows = output.lines().filter(|line| line.contains('█')).count(); - assert!( - plot_rows > 14, - "only {plot_rows} plot rows at {width} columns" - ); - assert!(output.contains("731,000 tokens")); - assert!(!output.contains("scroll")); - if width == 180 { - assert!( - output - .lines() - .any(|line| line.contains("4.4M tokens") && line.contains('─')) - ); - insta::assert_snapshot!(output); - } - } -} diff --git a/codex-rs/tui/src/analytics/redesign_tests.rs b/codex-rs/tui/src/analytics/redesign_tests.rs deleted file mode 100644 index 9029ef87..00000000 --- a/codex-rs/tui/src/analytics/redesign_tests.rs +++ /dev/null @@ -1,99 +0,0 @@ -//! Responsive navigation and report loading regression coverage. -use super::*; -use pretty_assertions::assert_eq; - -#[test] -fn reports_keep_tabs_fixed_and_expose_data_on_small_screens() { - for (width, height) in [(120, 36), (80, 24), (40, 16)] { - let mut view = fixture::view(models::AccountKind::Business); - view.section = Section::Usage; - let tokens = screen(&mut view, width, height); - assert!(tokens.contains("tokens")); - assert!(tokens.contains("Sep 2")); - let tabs = tokens.lines().take(3).collect::>(); - view.sections[Section::Usage].history = Load::Error("Couldn't load tokens.".into()); - let failed = screen(&mut view, width, height); - assert_eq!(tabs, failed.lines().take(3).collect::>()); - assert!(failed.contains("Couldn't load tokens.")); - if width == 40 { - insta::assert_snapshot!(format!("{tokens}\n{failed}")); - } - } -} - -#[test] -fn keyboard_tabs_and_help_preserve_report_reading_position() { - let mut view = fixture::view(models::AccountKind::Business); - view.section = Section::Usage; - view.sections[Section::Usage].detail = Some(6); - screen(&mut view, /*width*/ 80, /*height*/ 16); - press(&mut view, KeyCode::PageDown); - screen(&mut view, /*width*/ 80, /*height*/ 16); - let offset = view.scroll_offset(); - press(&mut view, KeyCode::BackTab); - assert_eq!(view.section, Section::Credits); - screen(&mut view, /*width*/ 80, /*height*/ 16); - press(&mut view, KeyCode::PageDown); - screen(&mut view, /*width*/ 80, /*height*/ 16); - press(&mut view, KeyCode::Tab); - assert_eq!( - ( - view.section, - view.scroll_offset(), - view.sections[Section::Usage].detail - ), - (Section::Usage, offset, Some(6)) - ); - view.handle_key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::SHIFT)); - let help = screen(&mut view, /*width*/ 40, /*height*/ 16); - assert!(help.contains("Usage shortcuts")); - assert!(help.lines().nth_back(/*n*/ 1).unwrap().contains("scroll")); - assert!(!help.lines().last().unwrap().contains("tab report")); - insta::assert_snapshot!("narrow_help", help); - press(&mut view, KeyCode::PageDown); - screen(&mut view, /*width*/ 40, /*height*/ 16); - assert!(view.scroll_offset() > 0); - press(&mut view, KeyCode::Esc); - assert_eq!( - (view.show_help, view.is_done, view.scroll_offset()), - (false, false, offset) - ); - press(&mut view, KeyCode::Char('?')); - assert_eq!(view.scroll_offset(), 0); - press(&mut view, KeyCode::Char('?')); - assert_eq!(view.scroll_offset(), offset); - press(&mut view, KeyCode::Char('z')); - screen(&mut view, /*width*/ 80, /*height*/ 16); - let dashboard_offset = view.scroll_offset(); - press(&mut view, KeyCode::Char('?')); - press(&mut view, KeyCode::Esc); - assert_eq!( - (view.zoomed, view.scroll_offset()), - (false, dashboard_offset) - ); - press(&mut view, KeyCode::Enter); - screen(&mut view, /*width*/ 80, /*height*/ 16); - assert_eq!( - ( - view.zoomed, - view.scroll_offset(), - view.sections[Section::Usage].detail - ), - (true, offset, Some(6)) - ); -} - -#[test] -fn dashboard_navigation_scrolls_to_selected_card() { - let mut view = fixture::view(models::AccountKind::Consumer); - press(&mut view, KeyCode::Char('z')); - screen(&mut view, /*width*/ 80, /*height*/ 24); - press(&mut view, KeyCode::Char('6')); - let output = screen(&mut view, /*width*/ 80, /*height*/ 24); - assert!(view.scroll_offset() > 0); - assert!( - output - .lines() - .any(|line| line.contains('▸') && line.contains("Chats")) - ); -} diff --git a/codex-rs/tui/src/analytics/render.rs b/codex-rs/tui/src/analytics/render.rs deleted file mode 100644 index 7ed4b0ee..00000000 --- a/codex-rs/tui/src/analytics/render.rs +++ /dev/null @@ -1,230 +0,0 @@ -//! Fixed analytics navigation and responsive report space. -//! Tabs and hints never wrap or move when a report loads, changes range, or becomes empty. - -use super::AnalyticsView; -use super::styles::secondary_style; -use crate::analytics::models::AccountAnalyticsHistory; -use crate::analytics::models::AccountAnalyticsValue; -use ratatui::buffer::Buffer; -use ratatui::layout::Constraint; -use ratatui::layout::Layout; -use ratatui::layout::Rect; -use ratatui::style::Styled; -use ratatui::style::Stylize; -use ratatui::text::Line; -use ratatui::widgets::Paragraph; -use ratatui::widgets::Widget; -use std::collections::BTreeMap; - -pub(super) fn columns(left: Line<'static>, right: Line<'static>, width: usize) -> Line<'static> { - let padding = width - .saturating_sub(left.width() + right.width()) - .max(/*other*/ 1); - let mut spans = left.spans; - spans.push(" ".repeat(padding).into()); - spans.extend(right.spans); - Line::from(spans) -} - -/// Join independently stacked panels without leaving holes below shorter sections. -pub(super) fn join_columns( - left: &[Line<'static>], - right: &[Line<'static>], - column_width: usize, -) -> Vec> { - (0..left.len().max(right.len())) - .map(|row| { - let left = left.get(row).cloned().unwrap_or_default(); - let mut line = columns(left, Line::default(), column_width + 4); - if let Some(right) = right.get(row) { - line.spans.extend(right.spans.iter().cloned()); - } - line - }) - .collect() -} - -pub(super) fn categories(history: &AccountAnalyticsHistory) -> Vec { - let mut totals = BTreeMap::::new(); - for value in history.data.iter().flat_map(|day| &day.values) { - totals - .entry(value.key.clone()) - .or_insert_with(|| AccountAnalyticsValue { - value: 0.0, - ..value.clone() - }) - .value += value.value; - } - let mut values = totals.into_values().collect::>(); - values.sort_by(|a, b| { - b.value - .abs() - .total_cmp(&a.value.abs()) - .then_with(|| a.key.cmp(&b.key)) - }); - values -} - -/// The last plotted category collects all remaining values without renormalizing them. -pub(super) fn parts( - values: &[AccountAnalyticsValue], - categories: &[AccountAnalyticsValue], -) -> [f64; 4] { - let mut parts = [0.0; 4]; - for value in values { - let index = categories - .iter() - .take(/*n*/ 3) - .position(|category| category.key == value.key) - .unwrap_or(/*default*/ 3); - parts[index] += value.value; - } - parts -} - -impl AnalyticsView { - pub(super) fn render(&mut self, area: Rect, buf: &mut Buffer) { - self.poll_reports(); - let inset = u16::from(area.width > 2); - let inner = Rect { - x: area.x + inset, - width: area.width.saturating_sub(inset * 2), - ..area - }; - let width = usize::from(inner.width).max(/*other*/ 1); - let [title, tabs, rule, controls, body, hints] = Layout::vertical([ - Constraint::Length(1), - Constraint::Length(1), - Constraint::Length(1), - Constraint::Length(if width >= 100 { 2 } else { 3 }), - Constraint::Min(1), - Constraint::Length(2), - ]) - .areas(inner); - let account = self.live.as_ref().and_then(|live| live.account_label()); - let plan = self - .account - .ready() - .map(|plan| crate::subscription::SubscriptionDisplay::Analytics.label(*plan)); - let heading = Line::from(vec![ - plan.map(|plan| format!("Usage · {plan}")) - .unwrap_or_else(|| "Usage".into()) - .bold(), - account - .map(|account| format!(" · {account}")) - .unwrap_or_default() - .set_style(secondary_style()), - ]); - crate::line_truncation::truncate_line_with_ellipsis_if_overflow(heading, width) - .render(title, buf); - let visible = self.visible_sections(); - let labels = visible - .iter() - .enumerate() - .map(|(index, section)| { - if width >= 80 { - format!("{} {}", index + 1, self.tab_label(*section)) - } else { - self.tab_label(*section).to_owned() - } - }) - .collect::>(); - let selected = visible - .iter() - .position(|section| *section == self.section) - .unwrap_or_default(); - self.tab_hits = crate::bottom_pane::render_filled_tab_bar( - &labels.iter().map(String::as_str).collect::>(), - selected, - tabs, - buf, - ) - .into_iter() - .map(|(index, rect)| (visible[index], rect)) - .collect(); - // Keep a visible selection on screen across reflow, while retaining intentional - // reading positions when the user has scrolled away from that selection. - if !self.show_help && self.report_area != body && self.selection_visible { - self.follow_selection = true; - } - self.body_area = body; - Line::from("─".repeat(width)).dim().render(rule, buf); - self.render_controls(controls, buf); - self.viewport_height = usize::from(body.height).max(/*other*/ 1); - let (lines, selection) = if self.show_help { - (self.help_lines(width), 0..1) - } else if visible.is_empty() { - let message = self - .account - .message() - .unwrap_or("Analytics is not available for this account type."); - ( - textwrap::wrap(message, width) - .into_iter() - .map(|line| Line::from(line.into_owned())) - .collect(), - 0..1, - ) - } else if !self.zoomed { - self.dashboard_lines(width, self.viewport_height) - } else { - let mut height = (self.viewport_height / 3).clamp(/*min*/ 2, /*max*/ 10); - if body.height < 15 || width < 50 { - height = 0; - } - let mut panel = self.panel(self.section, width, height); - if panel.chart_bands > 0 { - let overhead = panel.lines.len().saturating_sub(height * panel.chart_bands); - let available = self.viewport_height.saturating_sub(overhead) / panel.chart_bands; - height = available.max(/*other*/ 2); - panel = self.panel(self.section, width, height); - } - if self.section == super::sections::Section::Summary && self.profile.ready().is_some() { - let padding = self.viewport_height.saturating_sub(panel.lines.len()) / 2; - panel - .lines - .splice(0..0, std::iter::repeat_n(Line::default(), padding)); - } - (panel.lines, panel.selection) - }; - if self.zoomed && !self.show_help { - self.follow_selection |= - std::mem::take(&mut self.sections[self.section].follow_selection_on_focus); - } - let mut scroll_offset = self.scroll_offset(); - if self.follow_selection { - if selection.start < scroll_offset { - scroll_offset = selection.start; - } else { - let end = selection.start + selection.len().min(self.viewport_height); - if end > scroll_offset + self.viewport_height { - scroll_offset = end - self.viewport_height; - } - } - } - let scrollable = lines.len() > self.viewport_height; - self.max_scroll = lines.len().saturating_sub(self.viewport_height); - scroll_offset = scroll_offset.min(self.max_scroll); - *self.scroll_offset_mut() = scroll_offset; - self.follow_selection = false; - if !self.show_help { - self.report_area = body; - self.selection_visible = (!self.zoomed - || matches!( - self.section, - super::sections::Section::Chats | super::sections::Section::Plan - )) - && selection.start < scroll_offset + self.viewport_height - && selection.start >= scroll_offset; - } - Paragraph::new(lines) - .scroll( - /*offset*/ (scroll_offset.min(usize::from(u16::MAX)) as u16, 0), - ) - .render(body, buf); - self.mouse_context = Some((self.section, self.show_help, self.zoomed)); - Paragraph::new(self.footer_lines(width, scrollable)) - .style(secondary_style()) - .render(hints, buf); - } -} diff --git a/codex-rs/tui/src/analytics/report_data.rs b/codex-rs/tui/src/analytics/report_data.rs deleted file mode 100644 index 0e22d112..00000000 --- a/codex-rs/tui/src/analytics/report_data.rs +++ /dev/null @@ -1,289 +0,0 @@ -//! Projects endpoint-specific backend models into inputs for display normalization. -//! This representation is never used to deserialize HTTP responses. -//! Optional fields select the inputs used by each report; missing backend values stay missing. - -use codex_backend_client::AnalyticsResponse; -use codex_backend_client::analytics_models as backend; - -/// Report values projected for normalization after endpoint-specific decoding. -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct AnalyticsData { - pub(super) data: Vec, - pub(super) units: Option, - pub(super) data_freshness_ts: Option, - pub(super) series: Option>, -} - -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct AnalyticsSeries { - pub(super) key: String, - pub(super) label: String, -} - -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct AnalyticsRecord { - pub(super) date: String, - pub(super) values: Option>, - pub(super) product_surface_usage_values: Option>, - pub(super) premium_usage_values: Option, - pub(super) attribution: Option>, - pub(super) credit_amount: Option, - pub(super) product_surface: Option, - pub(super) totals: Option, - pub(super) models: Option>, - pub(super) groups: Option>, - pub(super) clients: Option>, - pub(super) plugin_usage_overviews: Option>, - pub(super) skill_usage_overviews: Option>, -} - -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct PremiumUsage { - pub(super) credit_usage_credits: std::collections::BTreeMap, -} - -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct UsageAttribution { - pub(super) thread_source: Option, - pub(super) turn_trigger: Option, - pub(super) model: Option, - pub(super) surface: Option, - pub(super) value: f64, -} - -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct AnalyticsCount { - pub(super) turns: f64, -} - -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct AnalyticsModel { - pub(super) model: String, - pub(super) credits: Option, - pub(super) uncached_text_input_tokens: Option, - pub(super) cached_text_input_tokens: Option, - pub(super) text_output_tokens: Option, - pub(super) text_total_tokens: Option, - pub(super) turns: Option, - pub(super) on_demand_credits: Option, - pub(super) speed: Option, -} - -/// Enterprise model groups carry text token counts independently of billing amounts. -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct AnalyticsTokenGroup { - pub(super) dimensions: std::collections::BTreeMap, - #[cfg_attr(test, serde(default))] - pub(super) is_other: bool, - pub(super) uncached_text_input_tokens: Option, - pub(super) cached_text_input_tokens: Option, - pub(super) text_output_tokens: Option, -} - -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct AnalyticsClient { - pub(super) client_id: String, - pub(super) turns: f64, -} - -#[derive(Clone, Debug, Default)] -#[cfg_attr(test, derive(serde::Deserialize))] -pub(super) struct AnalyticsTool { - pub(super) display_name: String, - pub(super) invocation_counts: f64, -} - -impl From for AnalyticsData { - fn from(response: AnalyticsResponse) -> Self { - match response { - AnalyticsResponse::Usage(response) => Self { - units: response.units, - data_freshness_ts: response.data_freshness_ts, - data: response - .data - .into_iter() - .map(|record| AnalyticsRecord { - date: record.date, - product_surface_usage_values: Some(record.product_surface_usage_values), - premium_usage_values: record.premium_usage_values.map(|value| { - PremiumUsage { - credit_usage_credits: value.credit_usage_credits, - } - }), - attribution: record.attribution.map(|values| { - values - .into_iter() - .map(|value| UsageAttribution { - thread_source: Some(value.thread_source), - turn_trigger: Some(value.turn_trigger), - model: Some(value.model), - surface: Some(value.surface), - value: value.value, - }) - .collect() - }), - models: record - .models - .map(|values| values.into_iter().map(AnalyticsModel::from).collect()), - groups: record.groups.map(|values| { - values - .into_iter() - .map(|value| AnalyticsTokenGroup { - dimensions: value.dimensions, - is_other: value.is_other.unwrap_or(/*default*/ false), - uncached_text_input_tokens: value - .uncached_text_input_tokens - .map(|count| count as f64), - cached_text_input_tokens: value - .cached_text_input_tokens - .map(|count| count as f64), - text_output_tokens: value - .text_output_tokens - .map(|count| count as f64), - }) - .collect() - }), - ..Default::default() - }) - .collect(), - ..Default::default() - }, - AnalyticsResponse::Credits(response) => Self { - data: response - .data - .into_iter() - .map(|record| AnalyticsRecord { - date: record.date, - credit_amount: Some(record.credit_amount), - product_surface: Some(record.product_surface), - ..Default::default() - }) - .collect(), - ..Default::default() - }, - AnalyticsResponse::EnterpriseCredits(response) => Self { - data_freshness_ts: response.data_freshness_ts, - series: Some( - response - .series - .into_iter() - .map(|value| AnalyticsSeries { - key: value.key, - label: value.label, - }) - .collect(), - ), - data: response - .data - .into_iter() - .map(|record| AnalyticsRecord { - date: record.date, - values: Some(record.values), - ..Default::default() - }) - .collect(), - ..Default::default() - }, - AnalyticsResponse::Messages(response) => Self { - data: response - .data - .into_iter() - .map(|record| AnalyticsRecord { - date: record.date, - totals: Some(AnalyticsCount { - turns: record.totals.turns as f64, - }), - clients: Some( - record - .clients - .into_iter() - .map(|value| AnalyticsClient { - client_id: value.client_id, - turns: value.turns as f64, - }) - .collect(), - ), - models: record - .models - .map(|values| values.into_iter().map(AnalyticsModel::from).collect()), - ..Default::default() - }) - .collect(), - ..Default::default() - }, - AnalyticsResponse::Plugins(response) => Self { - data_freshness_ts: response.data_freshness_ts, - data: response - .data - .into_iter() - .map(|record| AnalyticsRecord { - date: record.date, - plugin_usage_overviews: Some( - record - .plugin_usage_overviews - .into_iter() - .map(|value| AnalyticsTool { - display_name: value.display_name, - invocation_counts: value.invocation_counts as f64, - }) - .collect(), - ), - ..Default::default() - }) - .collect(), - ..Default::default() - }, - AnalyticsResponse::Skills(response) => Self { - data_freshness_ts: response.data_freshness_ts, - data: response - .data - .into_iter() - .map(|record| AnalyticsRecord { - date: record.date, - skill_usage_overviews: Some( - record - .skill_usage_overviews - .into_iter() - .map(|value| AnalyticsTool { - display_name: value.display_name, - invocation_counts: value.invocation_counts as f64, - }) - .collect(), - ), - ..Default::default() - }) - .collect(), - ..Default::default() - }, - } - } -} - -impl From for AnalyticsModel { - fn from(value: backend::ModelUsage) -> Self { - Self { - model: value.model, - credits: Some(value.credits), - uncached_text_input_tokens: value.uncached_text_input_tokens.map(|count| count as f64), - cached_text_input_tokens: value.cached_text_input_tokens.map(|count| count as f64), - text_output_tokens: value.text_output_tokens.map(|count| count as f64), - text_total_tokens: value.text_total_tokens.map(|count| count as f64), - turns: value.turns.map(|count| count as f64), - on_demand_credits: value.on_demand_credits, - speed: value.speed, - } - } -} - -#[cfg(test)] -#[path = "report_data_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/report_data_tests.rs b/codex-rs/tui/src/analytics/report_data_tests.rs deleted file mode 100644 index 237a8e00..00000000 --- a/codex-rs/tui/src/analytics/report_data_tests.rs +++ /dev/null @@ -1,84 +0,0 @@ -use super::*; -use pretty_assertions::assert_eq; - -#[test] -fn typed_usage_preserves_missing_counts_and_supplied_zero() { - let input = backend::DailyProductSurfaceUsageResponse { - data: vec![backend::DailyProductSurfaceUsage { - date: "2026-01-09".into(), - models: Some(vec![backend::ModelUsage { - model: "example".into(), - credits: 1.5, - cached_text_input_tokens: Some(0), - text_output_tokens: Some(42), - ..Default::default() - }]), - ..Default::default() - }], - ..Default::default() - }; - let actual = AnalyticsData::from(AnalyticsResponse::Usage(input)); - let model = &actual.data[0].models.as_ref().unwrap()[0]; - assert_eq!( - ( - model.credits, - model.uncached_text_input_tokens, - model.cached_text_input_tokens, - model.text_output_tokens - ), - (Some(1.5), None, Some(0.0), Some(42.0)) - ); -} - -#[test] -fn typed_message_records_keep_independent_daily_remainders() { - use super::super::models::*; - let date = "2026-01-09".parse().unwrap(); - let row = backend::DailyWorkspaceUsageCount { - date: "2026-01-09".into(), - totals: backend::WorkspaceUsageCount { - turns: 10, - ..Default::default() - }, - clients: vec![backend::ClientWorkspaceUsageCount { - client_id: "CODEX_CLI".into(), - turns: 8, - ..Default::default() - }], - ..Default::default() - }; - let response = AnalyticsResponse::Messages(backend::DailyWorkspaceUsageCountResponse { - data: vec![row.clone(), row], - ..Default::default() - }); - assert_eq!( - super::super::normalize::history( - response.into(), - AccountAnalyticsReport::Messages, - AccountAnalyticsGrouping::Surface, - date, - date - ) - .unwrap(), - Some(AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::Count, - updated_at: None, - data: vec![AccountAnalyticsDay { - date, - total: 20.0, - values: vec![ - AccountAnalyticsValue { - key: "cli".into(), - label: "CLI".into(), - value: 16.0 - }, - AccountAnalyticsValue { - key: "other".into(), - label: "Other".into(), - value: 4.0 - }, - ] - }], - }) - ); -} diff --git a/codex-rs/tui/src/analytics/runtime_auth_tests.rs b/codex-rs/tui/src/analytics/runtime_auth_tests.rs deleted file mode 100644 index 8c41c38b..00000000 --- a/codex-rs/tui/src/analytics/runtime_auth_tests.rs +++ /dev/null @@ -1,241 +0,0 @@ -//! Exercise Analytics construction and reauthentication through production HTTPS routes. - -#![cfg(test)] - -use super::Live; -use super::tests::sign_in; -use crate::legacy_core::config::ConfigBuilder; -use anyhow::Context; -use anyhow::Result; -use base64::Engine; -use codex_backend_client::AnalyticsReport; -use codex_backend_client::AnalyticsResponse; -use codex_config::LoaderOverrides; -use codex_features::Feature; -use codex_features::RuntimeAuthMode; -use codex_protocol::account::PlanType; -use core_test_support::runtime_auth::PROBE_SERVER; -use core_test_support::runtime_auth::run_harness_through_proxy; -use core_test_support::skip_if_no_network; -use pretty_assertions::assert_eq; -use serde_json::Value; -use serde_json::json; -use std::collections::BTreeSet; -use std::sync::Arc; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; - -async fn runtime_client( - base_url: &str, - mode: RuntimeAuthMode, -) -> Result<(tempfile::TempDir, Live)> { - let home = tempfile::tempdir()?; - let mut config = ConfigBuilder::default() - .codex_home(home.path().to_path_buf()) - .loader_overrides(LoaderOverrides::without_managed_config_for_tests()) - .build() - .await?; - config.chatgpt_base_url = base_url.to_string(); - config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File; - config.features.enable(Feature::RuntimeAgentInstances)?; - config.runtime_auth_mode = mode; - sign_in(home.path(), "account-a", "user-a", "plus"); - Ok((home, Live::new(Arc::new(config), "2026-01-15".parse()?))) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "aKode: runtime registration with auth.openai.com is disabled"] -async fn analytics_runtime_covers_regional_account_and_report_requests() -> Result<()> { - skip_if_no_network!(Ok(())); - let bases = [ - "https://chatgpt.com/backend-api", - "https://us.chatgpt.com/backend-api", - "https://chatgpt-staging.com/backend-api", - "https://us.chatgpt-staging.com/backend-api", - ]; - let modes = [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly]; - if std::env::var(PROBE_SERVER).is_ok() { - for base in bases { - for mode in modes { - let (_home, live) = runtime_client(base, mode).await?; - let session = live - .session() - .await - .map_err(anyhow::Error::msg) - .with_context(|| format!("{base} {mode:?}"))?; - assert_eq!(session.backend.account().plan_type, Some(PlanType::Pro)); - let response = session - .backend - .request(|client| async move { - client - .get_account_analytics( - AnalyticsReport::Usage, - "2026-01-01", - "2026-01-15", - ) - .await - }) - .await?; - assert_eq!( - response, - AnalyticsResponse::Usage( - codex_backend_client::analytics_models::DailyProductSurfaceUsageResponse::default(), - ), - ); - } - } - return Ok(()); - } - - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "runtime_agent_instance_id": "runtime-analytics", "agent_host_id": "host-a", - "actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "account-a"}, - }))) - .expect(/*r*/ 8) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/accounts/check")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "accounts": [{"id": "account-a", "plan_type": "pro"}], - "account_ordering": ["account-a"], - }))) - .expect(/*r*/ 8) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/wham/usage/daily-token-usage-breakdown")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": []}))) - .expect(/*r*/ 8) - .mount(&server) - .await; - run_harness_through_proxy( - &server, - "analytics::client::runtime_auth_tests::analytics_runtime_covers_regional_account_and_report_requests", - /*realtime_target*/ None, - ).await?; - server.verify().await; - let requests = server - .received_requests() - .await - .context("captured requests")?; - assert_eq!(requests.len(), 24); - let mut proofs = BTreeSet::new(); - for (index, requests) in requests.as_chunks::<3>().0.iter().enumerate() { - let base = bases[index / modes.len()]; - let mode = modes[index % modes.len()]; - let registration = &requests[0]; - assert_eq!(registration.url.path(), "/agent/register"); - assert_eq!( - registration.headers["host"], - if base.contains("staging") { - "auth.api.openai.org" - } else { - "auth.openai.com" - }, - ); - let body: Value = registration.body_json()?; - let credential = body["actor_auth"]["credential"] - .as_str() - .context("actor credential")?; - for request in &requests[1..] { - assert_eq!( - request.headers["host"], - base.strip_prefix("https://") - .expect("HTTPS test URL") - .strip_suffix("/backend-api") - .expect("test API path"), - ); - assert_eq!(request.headers["chatgpt-account-id"], "account-a"); - let authorization = request.headers["authorization"].to_str()?; - let proof = match mode { - RuntimeAuthMode::DualHeader => { - assert_eq!(authorization, format!("Bearer {credential}")); - request.headers["x-openai-agent-assertion"].to_str()? - } - RuntimeAuthMode::AssertionOnly => { - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - authorization - .strip_prefix("AgentAssertion ") - .context("runtime authorization")? - } - }; - assert!( - proofs.insert(proof.to_owned()), - "every request needs a fresh assertion" - ); - let payload = proof - .strip_prefix("1.") - .context("runtime assertion version")? - .split('.') - .nth(/*n*/ 1) - .context("assertion payload")?; - let claims: Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload)?, - )?; - assert_eq!(claims["runtime_agent_instance"], "runtime-analytics"); - } - } - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "aKode: runtime registration with auth.openai.com is disabled"] -async fn analytics_runtime_bootstrap_preserves_sign_in_guidance() -> Result<()> { - skip_if_no_network!(Ok(())); - if std::env::var(PROBE_SERVER).is_ok() { - let (_home, live) = runtime_client( - "https://chatgpt.com/backend-api", - RuntimeAuthMode::DualHeader, - ) - .await?; - assert_eq!( - live.session().await.err().as_deref(), - Some("Sign in again to load Analytics."), - ); - return Ok(()); - } - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/agent/register")) - .respond_with(ResponseTemplate::new(/*s*/ 401).set_body_json(json!({ - "error": {"code": "token_expired"}, - }))) - .mount(&server) - .await; - Mock::given(method("POST")) - .and(path("/oauth/token")) - .respond_with(ResponseTemplate::new(/*s*/ 401).set_body_json(json!({ - "error": {"code": "refresh_token_expired"}, - }))) - .expect(/*r*/ 1) - .mount(&server) - .await; - run_harness_through_proxy( - &server, - "analytics::client::runtime_auth_tests::analytics_runtime_bootstrap_preserves_sign_in_guidance", - /*realtime_target*/ None, - ).await?; - server.verify().await; - let requests = server - .received_requests() - .await - .context("captured requests")?; - assert!( - requests - .iter() - .any(|request| request.url.path() == "/agent/register") - ); - assert!( - requests - .iter() - .all(|request| { matches!(request.url.path(), "/agent/register" | "/oauth/token") }) - ); - Ok(()) -} diff --git a/codex-rs/tui/src/analytics/sections.rs b/codex-rs/tui/src/analytics/sections.rs deleted file mode 100644 index e2d9e202..00000000 --- a/codex-rs/tui/src/analytics/sections.rs +++ /dev/null @@ -1,305 +0,0 @@ -//! Account-specific section order, request eligibility, and independent report ranges. -//! Resolving the account precedes report loading; reopening drops all account-owned data. - -use super::AnalyticsView; -use super::chats; -use super::data::Load; -use super::models::AccountKind; - -/// Stable identities preserve selections while account layouts change their order. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum Section { - Usage, - Plugins, - Credits, - Chats, - Activity, - Skills, - Plan, - Summary, -} - -impl Section { - pub(super) fn report(self) -> Option { - use super::models::AccountAnalyticsReport as Report; - match self { - Self::Usage => Some(Report::Usage), - Self::Plugins => Some(Report::Plugins), - Self::Credits => Some(Report::Credits), - Self::Chats | Self::Plan | Self::Summary => None, - Self::Activity => Some(Report::Messages), - Self::Skills => Some(Report::Skills), - } - } -} - -/// Section-only indexing keeps report identity separate from array positions. -pub(super) struct SectionStates(pub(super) [SectionState; 8]); - -impl std::ops::Index
for SectionStates { - type Output = SectionState; - fn index(&self, section: Section) -> &Self::Output { - &self.0[section as usize] - } -} - -impl std::ops::IndexMut
for SectionStates { - fn index_mut(&mut self, section: Section) -> &mut Self::Output { - &mut self.0[section as usize] - } -} - -/// A report and its selection are replaced independently of the other sections. -pub(super) struct SectionState { - pub(super) history: Load, - pub(super) cursor: usize, - pub(super) detail: Option, - pub(super) group: usize, - pub(super) scroll_offset: usize, - pub(super) follow_selection_on_focus: bool, -} - -impl Default for SectionState { - fn default() -> Self { - Self { - history: Load::Unavailable, - cursor: 6, - detail: None, - group: 0, - scroll_offset: 0, - follow_selection_on_focus: false, - } - } -} - -/// Usage, product activity, and tools each share one range across their related sections. -#[derive(Clone, Copy, PartialEq, Eq)] -pub(super) enum RangeGroup { - Usage, - Activity, - Tools, -} - -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(); - } - self.chats.poll(); - self.tasks.poll(); - self.profile.poll(); - self.plan.poll(); - self.account.poll(); - self.start_reports(); - if !self.business() - && !self.consumer_attribution() - && ![0, 2].contains(&self.sections[Section::Usage].group) - { - self.sections[Section::Usage].group = 0; - } - if let Some(chats) = self.tasks.ready() { - self.sections[Section::Chats].cursor = self.sections[Section::Chats] - .cursor - .min(chats.rows.len().saturating_sub(/*rhs*/ 1)); - } - if let Some(chats) = self.chats.ready() { - self.sections[Section::Chats].cursor = self.sections[Section::Chats] - .cursor - .min(chats.rows.len().saturating_sub(/*rhs*/ 1)); - } - } - - pub(super) fn range_group(&self, section: Section) -> RangeGroup { - match section { - Section::Usage if self.business() => RangeGroup::Activity, - Section::Usage - | Section::Credits - | Section::Chats - | Section::Plan - | Section::Summary => RangeGroup::Usage, - Section::Activity => RangeGroup::Activity, - Section::Plugins | Section::Skills => RangeGroup::Tools, - } - } - - pub(super) fn group_label(&self, section: Section, group: usize) -> &'static str { - if section == Section::Summary { - return super::summary::VIEWS[group].label(); - } - if group == 0 - && (section == Section::Credits - || (section == Section::Usage && !self.consumer_attribution())) - { - "Product" - } else { - super::data::GROUP_LABELS[group] - } - } - - fn account_kind(&self) -> Option { - self.account - .ready() - .copied() - .map(|plan| AccountKind::from(Some(plan))) - } - - pub(super) fn business(&self) -> bool { - matches!( - self.account_kind(), - Some(AccountKind::Business | AccountKind::Enterprise) - ) - } - - pub(super) fn visible_sections(&self) -> &'static [Section] { - match self.account_kind() { - Some(AccountKind::Consumer) if self.plan.enabled => &[ - Section::Summary, - Section::Usage, - Section::Plan, - Section::Activity, - Section::Plugins, - Section::Skills, - Section::Chats, - ], - Some(AccountKind::Consumer) => &[ - Section::Summary, - Section::Usage, - Section::Activity, - Section::Plugins, - Section::Skills, - Section::Chats, - ], - Some(AccountKind::Business | AccountKind::Enterprise) - if super::models::thread_usage_supported(self.account.ready().copied()) => - { - &[ - Section::Summary, - Section::Credits, - Section::Usage, - Section::Plugins, - Section::Skills, - Section::Chats, - ] - } - Some(AccountKind::Business | AccountKind::Enterprise) => &[ - Section::Summary, - Section::Credits, - Section::Usage, - Section::Plugins, - Section::Skills, - ], - Some(AccountKind::Unknown) => &[Section::Summary], - None => &[], - } - } - - pub(super) fn start_reports(&mut self) { - if self.reports_started || self.account.ready().is_none() { - return; - } - self.reports_started = true; - let visible = self.visible_sections(); - let Some(first) = visible.first() else { - return; - }; - if !visible.contains(&self.section) { - self.section = *first; - } - let usage_groups: &[usize] = if self.business() { - &[6, 2] - } else { - &[1, 2, 0, 3] - }; - if !usage_groups.contains(&self.sections[Section::Usage].group) { - self.sections[Section::Usage].group = - if matches!(self.account_kind(), Some(AccountKind::Business)) { - 2 - } else { - usage_groups[0] - }; - } - if visible.contains(&Section::Credits) - && let Some(live) = &self.live - && !live - .credit_groups() - .contains(&self.sections[Section::Credits].group) - { - self.sections[Section::Credits].group = live.credit_groups()[0]; - } - self.load_summary(); - for section in visible { - if section.report().is_some() { - self.load_report(*section); - } - } - if visible.contains(&Section::Plan) - && let (Some((_, _, frame)), Some(live)) = (&self.connection, &self.live) - { - let live = std::sync::Arc::clone(live); - self.plan.report = Load::start(async move { live.plan_history().await }, frame.clone()); - } - if visible.contains(&Section::Chats) && !self.business() { - if let (Some((_, handle, frame)), Some(live)) = (&self.connection, &self.live) { - self.tasks = Load::start_with_timeout( - super::tasks::read(handle.clone(), std::sync::Arc::clone(live)), - frame.clone(), - std::time::Duration::from_secs(/*secs*/ 120), - ); - } - } else if visible.contains(&Section::Chats) { - self.chats = - if let (Some((_, handle, frame)), Some(live)) = (&self.connection, &self.live) { - Load::start_with_timeout( - chats::read(handle.clone(), std::sync::Arc::clone(live)), - frame.clone(), - std::time::Duration::from_secs(/*secs*/ 90), - ) - } else { - Load::Unavailable - }; - } - } - - pub(super) fn section_date_range( - &self, - section: Section, - ) -> std::ops::RangeInclusive { - let end = self.end_date; - let range = self.ranges[self.range_group(section) as usize]; - (end - chrono::Days::new(if range == 0 { 6 } else { 29 }))..=end - } - - pub(super) fn change_range(&mut self) { - let index = self.range_group(self.section); - self.ranges[index as usize] ^= 1; - for section in self.visible_sections() { - if matches!(section, Section::Chats | Section::Plan | Section::Summary) - || self.range_group(*section) != index - { - continue; - } - self.sections[*section].cursor = if self.ranges[index as usize] == 1 { - self.sections[*section].cursor + 23 - } else { - self.sections[*section].cursor.saturating_sub(/*rhs*/ 23) - }; - self.sections[*section].detail = self.sections[*section].detail.and_then(|day| { - if self.ranges[index as usize] == 1 { - Some(day + 23) - } else { - day.checked_sub(/*rhs*/ 23) - } - }); - if section.report().is_some() { - self.load_report(*section); - } - } - } -} diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__client__tests__live_account_identity_is_visible_and_closing_aborts_pending_loads.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__client__tests__live_account_identity_is_visible_and_closing_aborts_pending_loads.snap deleted file mode 100644 index f50ca2a4..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__client__tests__live_account_identity_is_visible_and_closing_aborts_pending_loads.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: tui/src/analytics/client_tests.rs -expression: terminal.backend().to_string() ---- -" Usage · analytics@example.test " -" " -" ────────────────────────────────────────────────────────────────────────────────────────────────── " -" " -" " -" " -" No history has been reported. " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" esc back " -" R retry " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__period_navigation_preserves_unknowns_and_resets_on_new_snapshot.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__period_navigation_preserves_unknowns_and_resets_on_new_snapshot.snap deleted file mode 100644 index 381a05e7..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__period_navigation_preserves_unknowns_and_resets_on_new_snapshot.snap +++ /dev/null @@ -1,65 +0,0 @@ ---- -source: tui/src/analytics/plan_tests.rs -expression: "output.join(\"\\n\")" ---- -" Usage · Plus " -" 1 Overview 2 Usage 3 Plan 4 Messages 5 Plugins 6 Skills 7 Chats " -" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" g Feature · ←/→ 5-hour / Weekly " -" " -" 5-hour limits › Weekly limits " -" " -" › Sep 2 10:00 – Sep 2 15:00 * 125% › Sep 1 00:00 – Sep 8 00:00 * Not available " -" Some usage is unavailable; this period may be Breakdown isn't available for this period " -" incomplete " -" Tasks 125% " -" Some periods aren't available yet " -" Usage as of Sep 2 12:00 UTC · * current at last update " -" Available since Sep 1 00:00 UTC " -" Amounts and period boundaries are approximate; recent activity may be delayed " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" ↑/↓ period · enter details · esc back " -" tab/1–7 report · z dashboard · ? help · R refresh " - -" Usage · Plus " -" Overview Usage Plan Messages Plugins › " -" ──────────────────────────────────────────────────────── " -" g Feature " -" ←/→ 5-hour / Weekly " -" " -" 5-hour limits " -" " -" › Sep 2 10:00 – Sep 2 15:00 * 125% " -" Some usage is unavailable; this period may be " -" incomplete " -" Tasks 125% " -" " -" › Weekly limits " -" " -" › Sep 1 00:00 – Sep 8 00:00 * Not available " -" Breakdown isn't available for this period " -" Some periods aren't available yet " -" Usage as of Sep 2 12:00 UTC · * current at last update " -" Available since Sep 1 00:00 UTC " -" Amounts and period boundaries are approximate; recent " -" activity may be delayed " -" " -" " -" " -" " -" " -" " -" ↑/↓ period · enter details · esc back " -" tab report · z dashboard · ? help · R refresh " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__plan_clocks_twelve_hour.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__plan_clocks_twelve_hour.snap deleted file mode 100644 index 3722278f..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__plan_clocks_twelve_hour.snap +++ /dev/null @@ -1,15 +0,0 @@ ---- -source: tui/src/analytics/plan_tests.rs -expression: rendered ---- -› 5-hour limits - -› Sep 2 10:00 AM – Sep 2 3:00 PM * 125% - - Weekly limits - -› Sep 1 12:00 AM – Sep 8 12:00 AM * Not available -Some periods aren't available yet -Usage as of Sep 2 12:00 PM UTC · * current at last update -Available since Sep 1 12:00 AM UTC -Amounts and period boundaries are approximate; recent activity may be delayed diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__unavailable_empty_and_zero_history_are_distinct.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__unavailable_empty_and_zero_history_are_distinct.snap deleted file mode 100644 index 18e7fda2..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plan__tests__unavailable_empty_and_zero_history_are_distinct.snap +++ /dev/null @@ -1,31 +0,0 @@ ---- -source: tui/src/analytics/plan_tests.rs -assertion_line: 105 -expression: snapshot ---- -› 5-hour limits Weekly limits - -Limit history isn't available yet Limit history isn't available yet - -› 5-hour limits Weekly limits - -No limit periods in this date range No limit periods in this date range -Usage as of Sep 2 12:00 UTC · * current at last update -Available since Sep 1 00:00 UTC -Amounts and period boundaries are approximate; recent activity may be delayed - -› 5-hour limits Weekly limits - -› Sep 2 10:00 – Sep 2 15:00 * 0% › Sep 1 00:00 – Sep 8 00:00 * Not available -Some periods aren't available yet -Usage as of Sep 2 12:00 UTC · * current at last update -Available since Sep 1 00:00 UTC -Amounts and period boundaries are approximate; recent activity may be delayed - -› 5-hour limits Weekly limits - -› Sep 2 13:00 – Sep 2 15:00 125% › Sep 1 00:00 – Sep 8 00:00 * Not available -Some periods aren't available yet -Usage as of Sep 2 12:00 UTC · * current at last update -Available since Sep 1 00:00 UTC -Amounts and period boundaries are approximate; recent activity may be delayed diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__duplicate_message_dates_render_the_full_other_remainder.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__duplicate_message_dates_render_the_full_other_remainder.snap deleted file mode 100644 index e50c24e2..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__duplicate_message_dates_render_the_full_other_remainder.snap +++ /dev/null @@ -1,42 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: display(&rendered) ---- - 20 - 20 ████████████ - ████████████ - ████████████ - ████████████ - ████████████ - 10 ████████████ - ████████████ - ████████████ - ████████████ - ████████████ - 0 ──────────────────────────────────────── - ▲ - Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -6: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 22:1 24:0 -1: 0:0 1:2 3:0 18:3 30:0 -2: 0:0 18:3 30:0 -3: 0:0 18:4 30:0 -4: 0:0 18:4 30:0 -5: 0:0 18:4 30:0 -6: 0:0 1:2 3:0 18:4 30:0 -7: 0:0 18:4 30:0 -8: 0:0 18:4 30:0 -9: 0:0 18:4 30:0 -10: 0:0 18:4 30:0 -11: 0:0 2:2 3:0 4:2 -12: 0:0 23:5 24:0 -13: 0:0 20:6 26:0 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__missing_zero_and_narrow_charts_keep_the_selection_visible.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__missing_zero_and_narrow_charts_keep_the_selection_visible.snap deleted file mode 100644 index a0dd98e2..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__missing_zero_and_narrow_charts_keep_the_selection_visible.snap +++ /dev/null @@ -1,105 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: "snapshots.join(\"\\n\\n\")" ---- -width=36, cursor=0 - 5 - 6 ▄▄▄▄▄▄▄ - ███████ - — 0 ███████ - 0 ───────────────────────────────── - ▲ - Jan 13 Jan 14 Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -2: Style::new().fg(Color::Rgb(165, 165, 165)).bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold() -6: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 30:1 31:0 -1: 0:0 1:2 2:0 27:3 34:0 -2: 0:0 27:3 34:0 -3: 0:0 8:4 9:0 19:1 20:0 27:3 34:0 -4: 0:0 1:2 2:0 3:1 -5: 0:0 8:5 9:0 -6: 0:0 5:6 11:0 16:2 22:0 27:2 33:0 - -width=36, cursor=1 - 5 - 6 ▄▄▄▄▄▄▄ - ███████ - — 0 ███████ - 0 ───────────────────────────────── - ▲ - Jan 13 Jan 14 Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -2: Style::new().fg(Color::Rgb(165, 165, 165)).bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold() -6: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 30:1 31:0 -1: 0:0 1:2 2:0 27:3 34:0 -2: 0:0 27:3 34:0 -3: 0:0 8:1 9:0 19:4 20:0 27:3 34:0 -4: 0:0 1:2 2:0 3:1 -5: 0:0 19:5 20:0 -6: 0:0 5:2 11:0 16:6 22:0 27:2 33:0 - -width=8, cursor=2 - 5 - ▄▄ - ██ -— 0 ██ -──────── - ▲ -13 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -4: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Rgb(165, 165, 165)).bg(Color::Reset).underline_color(Color::Reset) -6: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 6:1 7:0 -1: 0:0 5:2 7:0 -2: 0:0 5:2 7:0 -3: 0:3 1:0 3:3 4:0 5:2 7:0 -4: 0:3 -5: 0:0 6:4 7:0 -6: 0:5 2:0 5:6 7:0 - -width=1, cursor=2 -5 -▄ -█ -█ -─ -▲ - - -Palette: -0: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -1: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -Rows (column:palette): -0: 0:0 -1: 0:1 -2: 0:1 -3: 0:1 -4: 0:2 -5: 0:3 -6: 0:4 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__narrow_equal_height_totals_remain_separate_numbers.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__narrow_equal_height_totals_remain_separate_numbers.snap deleted file mode 100644 index 1508a355..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__narrow_equal_height_totals_remain_separate_numbers.snap +++ /dev/null @@ -1,30 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: "screens.join(\"\\n\\n\")" ---- - 111 111 111 -111 ┊ 111 ┊ 111 ┊ -▇▇ ▇▇ ▇▇ ▇▇ ▇▇ ▇▇ ▇▇ -██ ██ ██ ██ ██ ██ ██ -██ ██ ██ ██ ██ ██ ██ -───────────────────── - ▲ - 1 2 3 4 5 6 7 - - -111 111 111 111 111 111 111 - ▇▇ ▇▇ ▇▇ ▇▇ ▇▇ ▇▇ ▇▇ - ██ ██ ██ ██ ██ ██ ██ - ██ ██ ██ ██ ██ ██ ██ -──────────────────────────── - ▲ - 1 2 3 4 5 6 7 - - - 150 111 111 111 111 111 111 111 - ▇▇ ▇▇ ▇▇ ▇▇▇ ▇▇ ▇▇ ▇▇▇ - 75 ██ ██ ██ ███ ██ ██ ███ - ██ ██ ██ ███ ██ ██ ███ - 0 ────────────────────────────── - ▲ - 1 2 3 4 5 6 7 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__narrow_long_range_charts_never_truncate_dates.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__narrow_long_range_charts_never_truncate_dates.snap deleted file mode 100644 index 7a25e248..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__narrow_long_range_charts_never_truncate_dates.snap +++ /dev/null @@ -1,102 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: "snapshots.join(\"\\n\\n\")" ---- -width=1 - -1 -▄ -█ -─ -▲ - - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -Rows (column:palette): -0: 0:0 -1: 0:1 -2: 0:2 -3: 0:2 -4: 0:3 -5: 0:4 -6: 0:0 - -width=2 - - 1 -▄▄ -██ -── - ▲ -15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 -1: 0:0 1:1 -2: 0:2 -3: 0:2 -4: 0:3 -5: 0:0 1:4 -6: 0:5 - -width=5 - - 1 -▄▄▄▄▄ -█████ -───── - ▲ - 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 -1: 0:0 4:1 -2: 0:2 -3: 0:2 -4: 0:3 -5: 0:0 4:4 -6: 0:0 3:5 - -width=6 - - 1 -▄▄▄▄▄▄ -██████ -────── - ▲ -Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 -1: 0:0 5:1 -2: 0:2 -3: 0:2 -4: 0:3 -5: 0:0 5:4 -6: 0:5 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__oversized_axes_are_hidden_instead_of_truncated.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__oversized_axes_are_hidden_instead_of_truncated.snap deleted file mode 100644 index fd6afa47..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__oversized_axes_are_hidden_instead_of_truncated.snap +++ /dev/null @@ -1,138 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: "snapshots.join(\"\\n\\n\")" ---- -width=8 - 100M - █████ - █████ - █████ - █████ -──────── - ▲ -Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 1:1 5:0 -1: 0:0 1:2 6:0 -2: 0:0 1:2 6:0 -3: 0:0 1:2 6:0 -4: 0:0 1:2 6:0 -5: 0:3 -6: 0:0 3:4 4:0 -7: 0:5 6:0 - -width=30 - 100M - 100M ████████████ - ████████████ - 50M ████████████ - ████████████ - 0 ──────────────────────── - ▲ - Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 15:1 19:0 -1: 0:0 1:2 5:0 12:3 24:0 -2: 0:0 12:3 24:0 -3: 0:0 2:2 5:0 12:3 24:0 -4: 0:0 12:3 24:0 -5: 0:0 4:2 5:0 6:2 -6: 0:0 17:4 18:0 -7: 0:0 14:5 20:0 - -width=35 - 100M - 100M ████████████ - ████████████ - 50M ████████████ - ████████████ - 0 ───────────────────────────── - ▲ - Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 18:1 22:0 -1: 0:0 1:2 5:0 14:3 26:0 -2: 0:0 14:3 26:0 -3: 0:0 2:2 5:0 14:3 26:0 -4: 0:0 14:3 26:0 -5: 0:0 4:2 5:0 6:2 -6: 0:0 20:4 21:0 -7: 0:0 17:5 23:0 - -width=44 - 100M - 100M ████████████ - ████████████ - 50M ████████████ - ████████████ - 0 ────────────────────────────────────── - ▲ - Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 22:1 26:0 -1: 0:0 1:2 5:0 19:3 31:0 -2: 0:0 19:3 31:0 -3: 0:0 2:2 5:0 19:3 31:0 -4: 0:0 19:3 31:0 -5: 0:0 4:2 5:0 6:2 -6: 0:0 24:4 25:0 -7: 0:0 21:5 27:0 - -width=30 - - 1000000000000000000T - ▅▅▅▅▅▅▅▅▅▅▅▅ - ████████████ - ████████████ -────────────────────────────── - ▲ - Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 -1: 0:0 4:1 24:0 -2: 0:0 9:2 21:0 -3: 0:0 9:2 21:0 -4: 0:0 9:2 21:0 -5: 0:3 -6: 0:0 14:4 15:0 -7: 0:0 11:5 17:0 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__partial_cells_use_the_midpoint_and_descend_from_the_baseline.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__partial_cells_use_the_midpoint_and_descend_from_the_baseline.snap deleted file mode 100644 index 7370a839..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__partial_cells_use_the_midpoint_and_descend_from_the_baseline.snap +++ /dev/null @@ -1,49 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: "snapshots.join(\"\\n\\n\")" ---- -sign=1 -1.75 - ▇▇▇▇ — -──────────── - ▲ - 14 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -2: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 4:1 -1: 0:1 1:2 5:1 8:3 9:1 -2: 0:0 -3: 0:1 8:4 9:1 -4: 0:1 1:0 3:1 7:5 9:1 - -sign=-1 - - — -──────────── - ▁▁▁▁ --1.75 - ▲ - 14 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset).reversed() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 -1: 0:0 8:1 9:0 -2: 0:2 -3: 0:0 1:3 5:0 -4: 0:2 5:0 -5: 0:0 8:4 9:0 -6: 0:0 1:2 3:0 7:5 9:0 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__selected_callout_keeps_the_authoritative_daily_total.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__selected_callout_keeps_the_authoritative_daily_total.snap deleted file mode 100644 index 8b6deef6..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__selected_callout_keeps_the_authoritative_daily_total.snap +++ /dev/null @@ -1,30 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: display(&rendered) ---- - - 20 20.00 - ▃▃▃▃▃▃▃▃▃▃▃▃ - 10 ████████████ - ████████████ - 0 ──────────────────────────────────────── - ▲ - Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -2: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -3: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -6: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 -1: 0:0 1:1 3:0 21:2 26:0 -2: 0:0 18:3 30:0 -3: 0:0 1:1 3:0 18:4 30:0 -4: 0:0 18:4 30:0 -5: 0:0 2:1 3:0 4:1 -6: 0:0 23:5 24:0 -7: 0:0 20:6 26:0 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__seven_day_totals.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__seven_day_totals.snap deleted file mode 100644 index 74c241a4..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__seven_day_totals.snap +++ /dev/null @@ -1,37 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: text ---- - 711 - 800 611 - 511 █████████ - 411 █████████ █████████ - 311 ████████ █████████ █████████ - 400 211 █████████ ████████ █████████ █████████ - 111 ████████ █████████ ████████ █████████ █████████ - █████████ ████████ █████████ ████████ █████████ █████████ - ████████ █████████ ████████ █████████ ████████ █████████ █████████ - 0 ─────────────────────────────────────────────────────────────────────────────────────────────── - ▲ - Jan 1 Jan 2 Jan 3 Jan 4 Jan 5 Jan 6 Jan 7 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -3: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 91:1 94:0 -1: 0:0 1:1 4:0 77:1 80:0 -2: 0:0 64:1 67:0 88:2 97:0 -3: 0:0 50:3 53:0 74:2 83:0 88:2 97:0 -4: 0:0 37:1 40:0 61:2 69:0 74:2 83:0 88:2 97:0 -5: 0:0 1:1 4:0 23:1 26:0 47:2 56:0 61:2 69:0 74:2 83:0 88:2 97:0 -6: 0:0 10:1 13:0 34:2 42:0 47:2 56:0 61:2 69:0 74:2 83:0 88:2 97:0 -7: 0:0 20:2 29:0 34:2 42:0 47:2 56:0 61:2 69:0 74:2 83:0 88:2 97:0 -8: 0:0 7:2 15:0 20:2 29:0 34:2 42:0 47:2 56:0 61:2 69:0 74:2 83:0 88:2 97:0 -9: 0:0 3:1 4:0 5:1 -10: 0:0 51:4 52:0 -11: 0:0 9:1 14:0 22:1 27:0 36:1 41:0 49:5 54:0 63:1 68:0 76:1 81:0 90:1 95:0 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__signed_chart_dark.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__signed_chart_dark.snap deleted file mode 100644 index a76a24d0..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__signed_chart_dark.snap +++ /dev/null @@ -1,42 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: display(&rendered) ---- - - 15 8.00 - ▅▅▅▅▅▅▅▅ - 7.5 ████████ 0.00 - ████████ ▂▂▂▂▂▂▂▂ ▆▆▆▆▆▆▆▆ - 0 ────────────────────────────────────── - ▄▄▄▄▄▄▄▄ ████████ ▂▂▂▂▂▂▂▂ - - -3.00 - -15 - - ▲ - Jan 13 Jan 14 Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().fg(Color::Rgb(165, 165, 165)).bg(Color::Reset).underline_color(Color::Reset) -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset).reversed() -5: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset) -6: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -7: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold() -8: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 -1: 0:0 3:1 5:0 9:2 13:0 -2: 0:0 8:3 16:0 -3: 0:0 2:1 5:0 8:3 16:0 35:2 39:0 -4: 0:0 8:3 16:0 20:3 28:0 33:3 41:0 -5: 0:0 4:1 5:0 6:2 -6: 0:0 8:4 16:0 20:5 28:0 33:4 41:0 -7: 0:0 -8: 0:0 22:6 27:0 -9: 0:0 2:1 5:0 -10: 0:0 -11: 0:0 24:7 25:0 -12: 0:0 8:1 14:0 21:8 27:0 34:1 40:0 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__signed_chart_light.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__signed_chart_light.snap deleted file mode 100644 index 10525e14..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__signed_chart_light.snap +++ /dev/null @@ -1,42 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: display(&rendered) ---- - - 15 8.00 - ▅▅▅▅▅▅▅▅ - 7.5 ████████ 0.00 - ████████ ▂▂▂▂▂▂▂▂ ▆▆▆▆▆▆▆▆ - 0 ────────────────────────────────────── - ▄▄▄▄▄▄▄▄ ████████ ▂▂▂▂▂▂▂▂ - - -3.00 - -15 - - ▲ - Jan 13 Jan 14 Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().fg(Color::Rgb(76, 76, 76)).bg(Color::Reset).underline_color(Color::Reset) -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset).reversed() -5: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset) -6: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -7: Style::new().fg(Color::Rgb(28, 100, 200)).bg(Color::Reset).underline_color(Color::Reset).bold() -8: Style::new().fg(Color::Rgb(28, 100, 200)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 -1: 0:0 3:1 5:0 9:2 13:0 -2: 0:0 8:3 16:0 -3: 0:0 2:1 5:0 8:3 16:0 35:2 39:0 -4: 0:0 8:3 16:0 20:3 28:0 33:3 41:0 -5: 0:0 4:1 5:0 6:2 -6: 0:0 8:4 16:0 20:5 28:0 33:4 41:0 -7: 0:0 -8: 0:0 22:6 27:0 -9: 0:0 2:1 5:0 -10: 0:0 -11: 0:0 24:7 25:0 -12: 0:0 8:1 14:0 21:8 27:0 34:1 40:0 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__tiny_segments_keep_their_series_color_beside_a_large_day.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__tiny_segments_keep_their_series_color_beside_a_large_day.snap deleted file mode 100644 index 87340fc9..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__tiny_segments_keep_their_series_color_beside_a_large_day.snap +++ /dev/null @@ -1,68 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: "snapshots.join(\"\\n\\n\")" ---- -sign=1 - 100.00 - 100 ████████████ - ████████████ - 50 ████████████ 0.01 - ████████████ ▁▁▁▁▁▁▁▁▁▁▁▁ - 0 ─────────────────────────────────────── - ▲ - Jan 14 Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 11:1 17:0 -1: 0:0 1:2 4:0 8:3 20:0 -2: 0:0 8:3 20:0 -3: 0:0 2:2 4:0 8:3 20:0 31:2 35:0 -4: 0:0 8:3 20:0 28:3 40:0 -5: 0:0 3:2 4:0 5:2 -6: 0:0 14:4 15:0 -7: 0:0 11:5 17:0 30:2 36:0 - -sign=-1 - 100.00 - 100 ████████████ - ████████████ - 50 ████████████ - ████████████ - 0 ────────────────────────────────────── - ▇▇▇▇▇▇▇▇▇▇▇▇ - -0.01 - - -100 - - ▲ - Jan 14 Jan 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset) -4: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset).reversed() -5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -6: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 12:1 18:0 -1: 0:0 2:2 5:0 9:3 21:0 -2: 0:0 9:3 21:0 -3: 0:0 3:2 5:0 9:3 21:0 -4: 0:0 9:3 21:0 -5: 0:0 4:2 5:0 6:2 -6: 0:0 28:4 40:0 -7: 0:0 32:2 37:0 -8: 0:0 -9: 0:0 1:2 5:0 -10: 0:0 -11: 0:0 15:5 16:0 -12: 0:0 12:6 18:0 31:2 37:0 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__zero_credit_history_uses_a_readable_scale.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__zero_credit_history_uses_a_readable_scale.snap deleted file mode 100644 index 85b4bef1..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__plot__tests__zero_credit_history_uses_a_readable_scale.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: tui/src/analytics/plot_tests.rs -expression: display(&rendered) ---- - - 1 - - 0.5 - 0 0 0 0 0 0 0.00 - 0 ─────────────────────────────────────── - ▲ - 9 10 11 12 13 14 15 - -Palette: -0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset) -1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim() -2: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold() -3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold() -4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined() -Rows (column:palette): -0: 0:0 -1: 0:0 3:1 4:0 -2: 0:0 -3: 0:0 1:1 4:0 -4: 0:0 7:1 8:0 12:1 13:0 18:1 19:0 23:1 24:0 29:1 30:0 34:1 35:0 38:2 42:0 -5: 0:0 3:1 4:0 5:1 -6: 0:0 40:3 41:0 -7: 0:0 7:1 8:0 11:1 13:0 17:1 19:0 22:1 24:0 28:1 30:0 33:1 35:0 39:4 41:0 diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__chats_table__chats_breakdown_ranks_nonzero_groups_and_reflows.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__chats_table__chats_breakdown_ranks_nonzero_groups_and_reflows.snap deleted file mode 100644 index 4f36dbb6..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__chats_table__chats_breakdown_ranks_nonzero_groups_and_reflows.snap +++ /dev/null @@ -1,102 +0,0 @@ ---- -source: tui/src/analytics/chat_panel_tests.rs -expression: "screens.join(\"\\n\")" ---- -" Usage · Enterprise " -" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills 6 Chats " -" ──────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" " -" " -" Active in past 30 days · sorted by lifetime credits " -" " -" Chat Lifetime credits " -" › Q3 planning analysis 19,350.04 " -" ────────────────────────────────────────────────────────────────────────────────────────────── " -" Model Effort Speed Credits " -" Top model high Not reported 19,134.43 " -" Small model high standard 215.61 " -" Refund model high standard -0.000004 " -" 1 zero-credit group hidden · a show all " -" " -" Refactor billing usage 113.00 " -" Other usage 109.00 " -" Launch readiness review 85.00 " -" Plan the week 0.00 " -" " -" Showing 1–5 of 5 chats " -" Local chats · excludes archived chats and subagent usage " -" " -" " -" " -" " -" " -" " -" " -" ↑/↓ row · enter details · esc back " -" tab/1–6 report · z dashboard · ? help · R refresh " - -" Usage · Enterprise " -" Overview Credits Tokens Plugins Skills Chats " -" ──────────────────────────────────────────────────────── " -" " -" " -" " -" Active in past 30 days · sorted by lifetime credits " -" " -" Chat Lifetime credits " -" › Q3 planning analysis 19,350.04 " -" ───────────────────────────────────────────────────── " -" Model / effort / speed Credits " -" Top model 19,134.43 " -" high · Not reported " -" Small model 215.61 " -" high · standard " -" Refund model -0.000004 " -" high · standard " -" 1 zero-credit group hidden · a show all " -" " -" Refactor billing usage 113.00 " -" Other usage 109.00 " -" Launch readiness review 85.00 " -" Plan the week 0.00 " -" " -" Showing 1–5 of 5 chats " -" Local chats · excludes archived chats and subagent " -" usage " -" " -" " -" ↑/↓ row · enter details · esc back " -" tab report · z dashboard · ? help · R refresh " - -" Usage · Enterprise " -" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills 6 Chats " -" ──────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" " -" " -" Active in past 30 days · sorted by lifetime credits " -" " -" Chat Lifetime credits " -" › Q3 planning analysis 19,350.04 " -" ────────────────────────────────────────────────────────────────────────────────────────────── " -" Model Effort Speed Credits " -" Top model high Not reported 19,134.43 " -" Small model high standard 215.61 " -" Zero model high standard 0.00 " -" Refund model high standard -0.000004 " -" 1 zero-credit group · a hide zeros " -" " -" Refactor billing usage 113.00 " -" Other usage 109.00 " -" Launch readiness review 85.00 " -" Plan the week 0.00 " -" " -" Showing 1–5 of 5 chats " -" Local chats · excludes archived chats and subagent usage " -" " -" " -" " -" " -" " -" " -" ↑/↓ row · enter details · esc back " -" tab/1–6 report · z dashboard · ? help · R refresh " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__chats_table__chats_long_title_keeps_detail_indent_and_counts_missing_estimates.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__chats_table__chats_long_title_keeps_detail_indent_and_counts_missing_estimates.snap deleted file mode 100644 index ed139c20..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__chats_table__chats_long_title_keeps_detail_indent_and_counts_missing_estimates.snap +++ /dev/null @@ -1,34 +0,0 @@ ---- -source: tui/src/analytics/chat_panel_tests.rs -expression: output ---- -" Usage · Enterprise " -" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills 6 Chats " -" ──────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" " -" " -" Active in past 30 days · sorted by lifetime credits " -" 2 chat estimates unavailable " -" " -" Chat Lifetime credits " -" › Create a comprehensive list of areas to investigate across the runtime and describe ho… 120.00 " -" ────────────────────────────────────────────────────────────────────────────────────────────── " -" Create a comprehensive list of areas to investigate across the runtime and describe how each " -" area affects performance in a long conversation " -" Model Effort Speed Credits " -" GPT-5.6-Sol high standard 120.00 " -" " -" Chat usage unavailable — " -" Chat usage unavailable — " -" Launch readiness review 85.00 " -" Plan the week 0.00 " -" " -" Showing 1–5 of 5 chats " -" Local chats · excludes archived chats and subagent usage " -" " -" " -" " -" " -" " -" ↑/↓ row · enter details · esc back " -" tab/1–6 report · z dashboard · ? help · R refresh " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__consumer_refresh__consumer_chat_all_metrics.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__consumer_refresh__consumer_chat_all_metrics.snap deleted file mode 100644 index 9a4263d3..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__consumer_refresh__consumer_chat_all_metrics.snap +++ /dev/null @@ -1,34 +0,0 @@ ---- -source: tui/src/analytics/consumer_refresh_tests.rs -expression: "screen(&mut view, 110, 30)" ---- -" Usage · Plus " -" 1 Overview 2 Usage 3 Messages 4 Plugins 5 Skills 6 Chats " -" ──────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" s sort: Weekly % " -" " -" Usage estimates · active in past 30 days · sorted by Weekly % " -" Recorded usage / current full limit · may exceed 100% " -" Partial ranking · 1 partial · 2 unavailable " -" " -" Chat Weekly % 5-hour % Balance credits " -" › Refunded task · partial 125.0% 0.0% -0.000004 " -" ─────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" Refunded task " -" Weekly % 125.0% " -" 5-hour % 0.0% " -" Balance credits -0.000004 " -" " -" Model / effort / speed Weekly % " -" gpt-5.5 — " -" high · fast · codex " -" " -" Plan-covered task 12.1% — 0.00 " -" Chat usage unavailable — — — " -" Chat usage unavailable — — — " -" " -" Showing 1–4 of 4 chats " -" Local chats · includes discovered descendants · excludes archived roots " -" " -" ↑/↓ row · enter details · esc back " -" tab/1–6 report · z dashboard · ? help · R refresh " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__dashboard__dashboard_cards_align_and_keep_stable_summary_heights.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__dashboard__dashboard_cards_align_and_keep_stable_summary_heights.snap deleted file mode 100644 index 15642b79..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__dashboard__dashboard_cards_align_and_keep_stable_summary_heights.snap +++ /dev/null @@ -1,117 +0,0 @@ ---- -source: tui/src/analytics/dashboard_tests.rs -expression: "format!(\"{wide}\\n{narrow}\")" ---- -" Usage · Plus " -" 1 Overview 2 Usage 3 Messages 4 Plugins 5 Skills 6 Chats " -" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" Dashboard · enter focus · r 7d/30d · Aug 27–Sep 2, 2026 · g Feature " -" " -" ╭─ 1 Overview ────────────────────────────────────────────────────╮ ╭─ ▸ 2 Usage ───────────────────────────────────────────────────────╮ " -" │ │ │ │ " -" │ No history has been reported. │ │ 7d │ " -" │ │ │ By feature │ " -" │ │ │ Total usage · relative units │ " -" │ │ │ 20 73 64 91 81 100 86 │ " -" │ │ │ 100 ▁▁▁▁▁ ▅▅▅▅▅▅ ▅▅▅▅▅ ▇▇▇▇▇▇ ▆▆▆▆▆ ██████ ▆▆▆▆▆▆ │ " -" │ │ │ 0 ──────────────────────────────────────────────────────────── │ " -" │ │ │ ▲ │ " -" │ │ │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ " -" │ │ │ │ " -" │ │ │ Sep 2 · 86 usage units │ " -" │ │ │ ● Tasks 64.0% │ " -" │ │ │ ● Code review 14.0% │ " -" │ │ │ │ " -" │ │ │ │ " -" │ │ │ │ " -" ╰───────────────────────────────────────────────────────────────────╯ ╰───────────────────────────────────────────────────────────────────╯ " -" " -" ╭─ 3 Messages ────────────────────────────────────────────────────╮ ╭─ 4 Plugins ─────────────────────────────────────────────────────╮ " -" │ │ │ │ " -" │ 7d │ │ 7d │ " -" │ By model │ │ 186 calls │ " -" │ 574 reported messages │ │ 34 23 29 26 22 23 29 │ " -" │ 62 83 107 75 59 85 103 │ │ 40 ▆▆▆▆▆ ▄▄▄▄▄▄ ▅▅▅▅▅▅ ▅▅▅▅▅ ▄▄▄▄▄▄ ▄▄▄▄▄▄ ▅▅▅▅▅▅ │ " -" │ 150 ▃▃▃▃▃ ▄▄▄▄▄▄ ▅▅▅▅▅ ▄▄▄▄▄▄ ▃▃▃▃▃ ▄▄▄▄▄▄ ▅▅▅▅▅▅ │ │ 0 ───────────────────────────────────────────────────────────── │ " -" │ 0 ──────────────────────────────────────────────────────────── │ │ ▲ │ " -" │ ▲ │ │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ " -" │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ │ │ " -" │ │ │ Sep 2 · 29 calls │ " -" │ Sep 2 · 103 messages │ │ ● Slack 10 │ " -" │ ● GPT-5.6-Sol 61 │ │ ● Figma 10 │ " -" │ ● GPT-5.6-Terra 25 │ │ │ " -" │ │ │ │ " -" │ │ │ │ " -" │ │ │ │ " -" ╰───────────────────────────────────────────────────────────────────╯ ╰───────────────────────────────────────────────────────────────────╯ " -" " -" ╭─ 5 Skills ──────────────────────────────────────────────────────╮ ╭─ 6 Chats ───────────────────────────────────────────────────────╮ " -" │ │ │ │ " -" │ 7d │ │ No history has been reported. │ " -" │ 54 uses │ │ │ " -" │ 8 6 9 8 7 5 11 │ │ │ " -" │ 20 ▃▃▃▃▃ ▂▂▂▂▂▂ ▃▃▃▃▃▃ ▃▃▃▃▃ ▂▂▂▂▂▂ ▂▂▂▂▂▂ ▄▄▄▄▄▄ │ │ │ " -" │ 0 ───────────────────────────────────────────────────────────── │ │ │ " -" │ ▲ │ │ │ " -" │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ │ │ " -" │ │ │ │ " -" │ Sep 2 · 11 uses │ │ │ " -" │ ● Testing 4 │ │ │ " -" │ ● Code review 3 │ │ │ " -" │ │ │ │ " -" │ │ │ │ " -" │ │ │ │ " -" │ │ │ │ " -" ╰───────────────────────────────────────────────────────────────────╯ ╰───────────────────────────────────────────────────────────────────╯ " -" " -" enter focus · tab card · esc back " -" tab/1–6 report · z focus · ? help · R refresh " - -" Usage · Plus " -" Overview Usage Messages Plugins Skills Chats " -" ────────────────────────────────────────────────────────────────────── " -" Dashboard · enter focus · r 7d/30d · Aug 27–Sep 2, 2026 " -" g Feature " -" " -" ╭─ 1 Overview ─────────────────────────────────────────────────────╮ " -" │ │ " -" │ No history has been reported. │ " -" │ │ " -" │ │ " -" │ │ " -" │ │ " -" │ │ " -" │ │ " -" │ │ " -" │ │ " -" │ │ " -" │ │ " -" │ │ " -" │ │ " -" ╰────────────────────────────────────────────────────────────────────╯ " -" " -" ╭─ ▸ 2 Usage ────────────────────────────────────────────────────────╮ " -" │ │ " -" │ 7d │ " -" │ By feature │ " -" │ Total usage · relative units │ " -" │ 20 73 64 91 81 100 86 │ " -" │ 100 ▁▁▁▁▁ ▅▅▅▅▅▅ ▅▅▅▅▅▅ ▇▇▇▇▇ ▆▆▆▆▆▆ ██████ ▆▆▆▆▆▆ │ " -" │ 0 ───────────────────────────────────────────────────────────── │ " -" │ ▲ │ " -" │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ " -" │ │ " -" │ Sep 1 · 100 usage units │ " -" │ ● Tasks 65.0% │ " -" │ ● Code review 15.0% │ " -" │ │ " -" ╰────────────────────────────────────────────────────────────────────╯ " -" " -" ╭─ 3 Messages ─────────────────────────────────────────────────────╮ " -" │ │ " -" │ 7d │ " -" │ By model │ " -" │ 574 reported messages │ " -" │ 62 83 107 75 59 85 103 │ " -" enter focus · tab card · pgup/pgdn scroll · esc back " -" tab report · z focus · ? help · R refresh " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__recovery__tall_reports_use_available_height_and_wide_reports_put_details_beside_plot.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__recovery__tall_reports_use_available_height_and_wide_reports_put_details_beside_plot.snap deleted file mode 100644 index 84e14e97..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__recovery__tall_reports_use_available_height_and_wide_reports_put_details_beside_plot.snap +++ /dev/null @@ -1,64 +0,0 @@ ---- -source: tui/src/analytics/recovery_tests.rs -expression: output ---- -" Usage · Business " -" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills " -" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" r 7d/30d · Aug 27–Sep 2, 2026 · g Model · m All models " -" Updated · Sep 2 16:00 UTC " -" 4.4M tokens ──────────────────────────────────────────── " -" Sep 2 · 731,000 tokens " -" 1M Model Tokens " -" ● GPT-5.5 731,000 " -" " -" " -" " -" " -" 850K " -" ▆▆▆▆▆▆▆▆▆▆▆▆ " -" ████████████ " -" 773.5K ████████████ " -" ▁▁▁▁▁▁▁▁▁▁▁ ████████████ " -" ███████████ ████████████ 731K " -" ███████████ ████████████ " -" ███████████ 688.5K ████████████ ████████████ " -" ███████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ████████████ " -" 620.5K ███████████ ████████████ ████████████ ████████████ " -" ▆▆▆▆▆▆▆▆▆▆▆▆ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ 544K ███████████ ████████████ ████████████ ████████████ " -" ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" 500K ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" 170K ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ▁▁▁▁▁▁▁▁▁▁▁ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ " -" 0 ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" ▲ " -" Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 " -" ←/→ day · enter details · esc back " -" tab/1–5 report · z dashboard · ? help · R refresh " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__recovery__twelve_hour_metadata_keeps_utc_across_renderers.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__recovery__twelve_hour_metadata_keeps_utc_across_renderers.snap deleted file mode 100644 index 60c53c8b..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__recovery__twelve_hour_metadata_keeps_utc_across_renderers.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tui/src/analytics/recovery_tests.rs -expression: "output.join(\"\\n\")" ---- -" Updated · Sep 2 4:00 PM UTC " -Updated Sep 2 4:00 PM UTC -Report updated Sep 2 4:00 PM UTC -Updated Sep 2 4:00 PM UTC · recent activity may be delayed diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__redesign__narrow_help.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__redesign__narrow_help.snap deleted file mode 100644 index 96743c2d..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__redesign__narrow_help.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: tui/src/analytics/redesign_tests.rs -expression: help ---- -" Usage · Business " -" Overview Credits Tokens › " -" ────────────────────────────────────── " -" Usage shortcuts " -" " -" " -" Tab / ⇧tab · next / previous report " -" 1–5 · open a report directly " -" ← / → · select chart day or plan " -" window " -" ↑ / ↓ · select chat or plan period; " -" scroll Overview " -" enter · expand or collapse details " -" pgup / pgdn · scroll report " -" esc back · pgup/pgdn scroll " -" ? close help " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__redesign__reports_keep_tabs_fixed_and_expose_data_on_small_screens.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__redesign__reports_keep_tabs_fixed_and_expose_data_on_small_screens.snap deleted file mode 100644 index 8bf30d5e..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__redesign__reports_keep_tabs_fixed_and_expose_data_on_small_screens.snap +++ /dev/null @@ -1,37 +0,0 @@ ---- -source: tui/src/analytics/redesign_tests.rs -expression: "format!(\"{tokens}\\n{failed}\")" ---- -" Usage · Business " -" Overview Credits Tokens › " -" ────────────────────────────────────── " -" r 7d/30d · Aug 27–Sep 2, 2026 " -" g Model · m All models " -" Updated · Sep 2 16:00 UTC " -" 4.4M tokens " -" " -" ────────────────────────────────────── " -" Sep 2 · 731,000 tokens " -" Model Tokens " -" ● GPT-5.5 731,000 " -" " -" " -" ←/→ day · enter details · esc back " -" tab report · z all · ? · R refresh " - -" Usage · Business " -" Overview Credits Tokens › " -" ────────────────────────────────────── " -" r 7d/30d · Aug 27–Sep 2, 2026 " -" g Model · m All models " -" " -" Couldn't load tokens. " -" " -" " -" " -" " -" " -" " -" " -" ←/→ day · esc back " -" tab report · z all · ? · R refresh " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_cumulative_narrow.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_cumulative_narrow.snap deleted file mode 100644 index 8f5e767b..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_cumulative_narrow.snap +++ /dev/null @@ -1,64 +0,0 @@ ---- -source: tui/src/analytics/summary_tests.rs -expression: "screen(&mut view, 64, 60)" ---- -" Usage · Plus " -" Overview Usage Messages Plugins Skills Chats " -" ────────────────────────────────────────────────────────────── " -" g Cumulative " -" " -" " -" " -" " -" " -" " -" " -" " -" " -" Example User " -" @example.user " -" Plus " -" " -" 142.3B 7B 44h 7m " -" Lifetime tokens Peak tokens Longest chat " -" " -" 158 days 160 days " -" Current streak Longest streak " -" " -" Token activity " -" Last 12 months " -" " -" Mar Apr May Jun Jul Aug " -" max █ " -" █ " -" █ " -" █ " -" █ " -" █ " -" 0 █ " -" " -" Running total · top 300 " -" " -" Activity insights " -" " -" Fast Mode 37% " -" Most used reasoning high · 26% " -" Skills explored 147 " -" Total skills used 13,190 " -" Total chats 21,482 " -" " -" Most used plugins and skills " -" " -" $review 1,142 runs " -" @GitHub 1,059 runs " -" " -" Statistics as of Sep 9, 2026 " -" " -" " -" " -" " -" " -" " -" " -" esc back " -" tab report · z dashboard · ? help · R refresh " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_daily_wide.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_daily_wide.snap deleted file mode 100644 index cff3b93e..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_daily_wide.snap +++ /dev/null @@ -1,48 +0,0 @@ ---- -source: tui/src/analytics/summary_tests.rs -expression: "screen(&mut view, 140, 44)" ---- -" Usage · Plus " -" 1 Overview 2 Usage 3 Messages 4 Plugins 5 Skills 6 Chats " -" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── " -" g Daily " -" " -" " -" " -" " -" Example User " -" @example.user " -" Plus " -" " -" 142.3B 7B 44h 7m 158 days 160 days " -" Lifetime tokens Peak tokens Longest chat Current streak Longest streak " -" " -" Token activity " -" Last 12 months " -" " -" Oct Nov Dec Jan Feb Mar Apr May Jun Jul Aug " -" Su □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ " -" Mo □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ " -" Tu □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ ■ " -" We □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ ■ " -" Th □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ " -" Fr □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ " -" Sa □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ " -" " -" Less □ ■ ■ ■ ■ More " -" " -" Activity insights Most used plugins and skills " -" " -" Fast Mode 37% $review 1,142 runs " -" Most used reasoning high · 26% @GitHub 1,059 runs " -" Skills explored 147 " -" Total skills used 13,190 " -" Total chats 21,482 " -" " -" Statistics as of Sep 9, 2026 " -" " -" " -" " -" " -" esc back " -" tab/1–6 report · z dashboard · ? help · R refresh " diff --git a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_partial.snap b/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_partial.snap deleted file mode 100644 index bea6ed85..00000000 --- a/codex-rs/tui/src/analytics/snapshots/codex_tui__analytics__tests__summary__summary_partial.snap +++ /dev/null @@ -1,44 +0,0 @@ ---- -source: tui/src/analytics/summary_tests.rs -expression: rendered ---- -" Usage · Business " -" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills " -" ────────────────────────────────────────────────────────────────────────────────────────────────── " -" g Daily " -" " -" " -" " -" " -" " -" " -" " -" " -" Business " -" " -" 0 — — — — " -" Lifetime tokens Peak tokens Longest chat Current streak Longest streak " -" " -" Token activity " -" Last 12 months " -" " -" Token activity history unavailable " -" " -" Activity insights Most used plugins and skills " -" " -" Fast Mode 0% No reported plugins or skills. " -" Most used reasoning — " -" Skills explored — " -" Total skills used — " -" Total chats 0 " -" " -" Some profile statistics are unavailable. " -" " -" " -" " -" " -" " -" " -" " -" esc back " -" tab/1–5 report · z dashboard · ? help · R refresh " diff --git a/codex-rs/tui/src/analytics/styles.rs b/codex-rs/tui/src/analytics/styles.rs deleted file mode 100644 index 29fb2edd..00000000 --- a/codex-rs/tui/src/analytics/styles.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Charts and legends share the terminal's ANSI palette. -//! Secondary text blends probed defaults only when the terminal supports that color depth. - -use crate::color::blend; -use crate::style::accent_style; -use crate::terminal_palette::StdoutColorLevel; -use crate::terminal_palette::best_color; -use crate::terminal_palette::default_bg; -use crate::terminal_palette::default_fg; -use crate::terminal_palette::effective_stdout_color_level; -use ratatui::style::Color; -use ratatui::style::Style; -use ratatui::text::Span; - -pub(super) fn series_colors() -> [Color; 4] { - [Color::Cyan, Color::Magenta, Color::Green, Color::Reset] -} - -pub(super) fn number(text: impl Into) -> Span<'static> { - Span::styled(text.into(), accent_style()) -} - -/// Labels and instructions need more contrast than decorative rules or inactive values. -pub(super) fn secondary_style() -> Style { - if !matches!( - effective_stdout_color_level(), - StdoutColorLevel::TrueColor | StdoutColorLevel::Ansi256 - ) { - return Style::default().dim(); - } - match (default_fg(), default_bg()) { - (Some(fg), Some(bg)) => { - Style::default().fg(best_color(blend(fg, bg, /*alpha*/ 0.70))) - } - _ => Style::default().dim(), - } -} - -/// Paint one selectable row, including its padding, using the shared picker accent. -pub(super) fn select_row(line: &mut ratatui::text::Line<'static>, width: usize) { - let style = crate::bottom_pane::selection_style(); - line.spans - .push(" ".repeat(width.saturating_sub(line.width())).into()); - line.style = style; - for span in &mut line.spans { - span.style = style; - } -} diff --git a/codex-rs/tui/src/analytics/styles_tests.rs b/codex-rs/tui/src/analytics/styles_tests.rs deleted file mode 100644 index 0c8ef24c..00000000 --- a/codex-rs/tui/src/analytics/styles_tests.rs +++ /dev/null @@ -1,185 +0,0 @@ -//! Render both account layouts with explicit terminal palettes, including color and selection styles. - -use super::*; -use crate::analytics::sections::Section; -use crate::style::accent_style; -use crate::terminal_palette::with_test_default_colors; -use crate::terminal_probe::DefaultColors; -use pretty_assertions::assert_eq; -use ratatui::buffer::Buffer; -use ratatui::layout::Rect; -use ratatui::style::Color; -use ratatui::style::Modifier; - -fn luminance(rgb: (u8, u8, u8)) -> f64 { - let [r, g, b] = [rgb.0, rgb.1, rgb.2].map(|channel| { - let value = f64::from(channel) / 255.0; - if value <= 0.04045 { - value / 12.92 - } else { - ((value + 0.055) / 1.055).powf(/*n*/ 2.4) - } - }); - 0.2126 * r + 0.7152 * g + 0.0722 * b -} - -#[test] -fn analytics_sections_adapt_to_terminal_colors() { - for (theme, colors) in [ - ( - "light", - DefaultColors { - fg: (0, 0, 0), - bg: (255, 255, 255), - }, - ), - ( - "dark", - DefaultColors { - fg: (230, 230, 230), - bg: (16, 16, 16), - }, - ), - ] { - with_test_default_colors(colors, || { - for kind in [ - models::AccountKind::Consumer, - models::AccountKind::Enterprise, - ] { - let mut view = fixture::view(kind); - view.sections[Section::Chats].detail = Some(0); - for section in view.visible_sections() { - let section = *section; - view.section = section; - let area = Rect::new( - /*x*/ 0, /*y*/ 0, /*width*/ 120, /*height*/ 42, - ); - let mut buffer = Buffer::empty(area); - view.render(area, &mut buffer); - let label = view.tab_label(section); - let tab = buffer - .content - .chunks(usize::from(area.width)) - .nth(/*n*/ 1) - .unwrap() - .windows(label.len()) - .find(|cells| { - cells - .iter() - .map(ratatui::buffer::Cell::symbol) - .collect::() - == label - }) - .expect("the report tab is visible"); - let heading = &tab[0]; - let active = crate::bottom_pane::active_tab_style(); - assert_eq!(heading.fg, active.fg.unwrap()); - assert_eq!(heading.bg, active.bg.unwrap()); - assert!(heading.modifier.contains(Modifier::BOLD)); - for marker in buffer.content.iter().filter(|cell| cell.symbol() == "▲") { - assert_eq!(marker.fg, accent_style().fg.unwrap()); - assert_eq!(marker.bg, Color::Reset); - assert!(marker.modifier.contains(Modifier::BOLD)); - } - if theme == "light" { - for (index, cell) in buffer - .content - .iter() - .enumerate() - .filter(|(_, cell)| !cell.symbol().trim().is_empty()) - { - // Keyboard hints deliberately keep the requested white key style. - // Report text and chart colors still adapt to light backgrounds. - if cell.fg == Color::White { - let y = area.y + (index / usize::from(area.width)) as u16; - assert!(y >= area.bottom() - 2 || (3..5).contains(&y)); - assert_eq!(cell.modifier, Modifier::BOLD); - continue; - } - let foreground = match cell.fg { - Color::Rgb(r, g, b) => (r, g, b), - Color::White => (255, 255, 255), - Color::Black => (0, 0, 0), - Color::Reset => colors.fg, - _ => continue, - }; - let background = match cell.bg { - Color::Rgb(r, g, b) => (r, g, b), - Color::White => (255, 255, 255), - Color::Black => (0, 0, 0), - Color::Reset => colors.bg, - _ => continue, - }; - let fg = luminance(foreground); - let bg = luminance(background); - let contrast = (fg.max(bg) + 0.05) / (fg.min(bg) + 0.05); - assert!( - contrast >= 4.5, - "{}: {:?} has contrast {contrast}", - cell.symbol(), - cell.fg - ); - } - } - } - } - }); - } -} - -#[test] -fn chat_selection_keeps_a_highlighted_trailing_blank_after_wrapping() { - with_test_default_colors( - DefaultColors { - fg: (30, 30, 30), - bg: (255, 255, 255), - }, - || { - for kind in [models::AccountKind::Business, models::AccountKind::Consumer] { - let mut view = fixture::view(kind); - view.section = Section::Chats; - view.tasks = Load::Ready(tasks::Chats { - rows: vec![tasks::Chat { - title: "Building Analytics".into(), - task: Some( - serde_json::from_value(serde_json::json!({ - "thread_id": "padding-fixture", - "data_status": "available", - "usage_source": "credits", - "weekly_limit_percent": 42.0, - "five_hour_limit_percent": 15.0, - "balance_usage_credits": "35.83", - "groups": [] - })) - .unwrap(), - ), - }], - ..tasks::Chats::default() - }); - for width in [40, 120] { - let area = Rect::new(/*x*/ 0, /*y*/ 0, width, /*height*/ 30); - let mut buffer = Buffer::empty(area); - view.render(area, &mut buffer); - let selection = crate::bottom_pane::selection_style().bg.unwrap(); - let selected_rows = buffer - .content - .chunks(usize::from(width)) - .skip(usize::from(view.body_area.y)) - .take(usize::from(view.body_area.height)) - .filter(|row| row.iter().any(|cell| cell.bg == selection)) - .collect::>(); - assert!(!selected_rows.is_empty()); - for row in selected_rows { - let end = row.iter().rposition(|cell| cell.bg == selection).unwrap(); - assert_eq!(row[end].symbol(), " "); - assert!( - row[..end] - .iter() - .any(|cell| !cell.symbol().trim().is_empty()) - ); - } - } - } - }, - ); -} diff --git a/codex-rs/tui/src/analytics/summary.rs b/codex-rs/tui/src/analytics/summary.rs deleted file mode 100644 index 7e55cae8..00000000 --- a/codex-rs/tui/src/analytics/summary.rs +++ /dev/null @@ -1,76 +0,0 @@ -//! Account profile loading and the Summary's year-view interaction. -//! Aggregation changes reuse the loaded profile; account refresh replaces all profile data. - -use super::AnalyticsView; -use super::activity_chart::TokenActivityView; -use super::client::Live; -use super::data::Load; -use super::sections::Section; -use crate::keymap::ListAction; -use codex_backend_client::AccountProfile; - -pub(super) const VIEWS: [TokenActivityView; 3] = [ - TokenActivityView::Daily, - TokenActivityView::Weekly, - TokenActivityView::Cumulative, -]; - -impl Live { - pub(super) async fn profile(&self) -> Result, String> { - let session = self.session().await?; - let profile = session - .backend - .request(|client| async move { client.get_account_profile().await }) - .await; - self.ensure_identity().await?; - profile.map(Some).map_err(super::client::request_error) - } -} - -impl AnalyticsView { - pub(crate) fn select_summary(&mut self, view: Option) { - self.section = Section::Summary; - self.zoomed = true; - self.show_help = false; - *self.scroll_offset_mut() = 0; - if let Some(view) = view { - self.sections[Section::Summary].group = VIEWS - .iter() - .position(|item| *item == view) - .unwrap_or_default(); - } - } - - pub(super) fn load_summary(&mut self) { - if let (Some((_, _, frame)), Some(live)) = (&self.connection, &self.live) { - let live = std::sync::Arc::clone(live); - self.profile = Load::start(async move { live.profile().await }, frame.clone()); - } - } - - pub(super) fn summary_action(&mut self, action: Option) { - let step = match action { - Some(ListAction::MoveUp) => Some(-1), - Some(ListAction::MoveDown) => Some(1), - Some(ListAction::PageUp) => Some(-(self.viewport_height as isize)), - Some(ListAction::PageDown) => Some(self.viewport_height as isize), - Some(ListAction::JumpTop) => { - *self.scroll_offset_mut() = 0; - Some(0) - } - Some(ListAction::JumpBottom) => { - *self.scroll_offset_mut() = usize::MAX; - Some(0) - } - Some(ListAction::Cancel) => { - self.is_done = true; - None - } - Some(ListAction::MoveLeft | ListAction::MoveRight | ListAction::Accept) | None => None, - }; - if let Some(step) = step { - *self.scroll_offset_mut() = self.scroll_offset().saturating_add_signed(step); - self.follow_selection = false; - } - } -} diff --git a/codex-rs/tui/src/analytics/summary_panel.rs b/codex-rs/tui/src/analytics/summary_panel.rs deleted file mode 100644 index 2303b4a4..00000000 --- a/codex-rs/tui/src/analytics/summary_panel.rs +++ /dev/null @@ -1,337 +0,0 @@ -//! Responsive profile summary using the Analytics container's typography and spacing. - -use super::AnalyticsView; -use super::activity_chart; -use super::render::columns; -use super::render::join_columns; -use super::sections::Section; -use super::styles::secondary_style; -use crate::line_truncation::truncate_line_with_ellipsis_if_overflow as truncate; -use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_lines; -use codex_backend_client::ProfileInvocationKind; -use ratatui::style::Styled; -use ratatui::style::Stylize; -use ratatui::text::Line; - -impl AnalyticsView { - pub(super) fn summary_lines(&self, width: usize) -> Vec> { - let width = width.max(/*other*/ 1); - let inner_width = width.min(/*other*/ 110); - let mut lines = Vec::new(); - let Some(profile) = self.profile.ready() else { - lines.push( - self.profile - .message() - .unwrap_or("Profile statistics unavailable.") - .to_owned() - .into(), - ); - return lines; - }; - if let Some(identity) = &profile.profile { - if let Some(name) = identity - .display_name - .as_deref() - .filter(|name| !name.trim().is_empty()) - { - lines.push(center( - truncate(name.trim().to_owned().bold().into(), inner_width), - inner_width, - )); - } - if let Some(username) = identity - .username - .as_deref() - .filter(|name| !name.trim().is_empty()) - { - lines.push(center( - truncate( - format!("@{}", username.trim().trim_start_matches('@')) - .set_style(secondary_style()) - .into(), - inner_width, - ), - inner_width, - )); - } - } - let plan = self - .account - .ready() - .map(|plan| crate::subscription::SubscriptionDisplay::Analytics.label(*plan)); - if let Some(plan) = plan { - lines.push(center( - plan.set_style(secondary_style()).into(), - inner_width, - )); - } - lines.push(Line::default()); - let tokens = &profile.stats.tokens; - let fields = [ - ( - "Lifetime tokens", - tokens - .lifetime_tokens - .map(|value| super::data::compact_amount(value as f64)), - ), - ( - "Peak tokens", - tokens - .peak_daily_tokens - .map(|value| super::data::compact_amount(value as f64)), - ), - ( - "Longest chat", - tokens.longest_running_turn_sec.map(duration), - ), - ( - "Current streak", - tokens - .current_streak_days - .map(|days| format!("{days} days")), - ), - ( - "Longest streak", - tokens - .longest_streak_days - .map(|days| format!("{days} days")), - ), - ]; - if !self.zoomed { - lines.extend(fields.into_iter().map(|(label, value)| { - columns( - label.set_style(secondary_style()).into(), - value.unwrap_or_else(|| "—".into()).bold().into(), - inner_width, - ) - })); - return lines; - } - let count = if inner_width >= 90 { - 5 - } else if inner_width >= 54 { - 3 - } else if inner_width >= 36 { - 2 - } else { - 1 - }; - for chunk in fields.chunks(count) { - let cell_width = inner_width / chunk.len(); - let mut values = Line::default(); - let mut labels = Line::default(); - for (index, (label, value)) in chunk.iter().enumerate() { - for (row, cell) in [ - ( - &mut values, - value.clone().unwrap_or_else(|| "—".into()).bold(), - ), - (&mut labels, label.to_string().set_style(secondary_style())), - ] { - let cell = center(truncate(cell.into(), cell_width), cell_width); - let padding = cell_width.saturating_sub(cell.width()); - row.spans.extend(cell.spans); - if index + 1 < chunk.len() { - row.spans.push(" ".repeat(padding).into()); - } - } - } - lines.extend([values, labels, Line::default()]); - } - let selected = self.sections[Section::Summary].group; - lines.push("Token activity".bold().into()); - lines.push("Last 12 months".set_style(secondary_style()).into()); - lines.push(Line::default()); - if let Some(buckets) = &tokens.daily_usage_buckets { - lines.extend(activity_chart::chart_lines( - super::summary::VIEWS[selected], - buckets, - self.end_date, - inner_width as u16, - )); - } else { - lines.push( - "Token activity history unavailable" - .set_style(secondary_style()) - .into(), - ); - } - lines.push(Line::default()); - let stats = &profile.stats; - let reasoning = stats - .most_used_reasoning_effort - .as_deref() - .map(|effort| { - let percentage = percent(stats.most_used_reasoning_effort_percentage.as_ref()); - format!("{effort} · {percentage}") - }) - .unwrap_or_else(|| "—".into()); - let metrics = [ - ( - "Fast Mode", - percent(stats.fast_mode_usage_percentage.as_ref()), - ), - ("Most used reasoning", reasoning), - ("Skills explored", count_value(stats.unique_skills_used)), - ("Total skills used", count_value(stats.total_skills_used)), - ("Total chats", count_value(stats.total_threads)), - ]; - let two_columns = inner_width >= 76; - let column_width = if two_columns { - (inner_width - 4) / 2 - } else { - inner_width - }; - let mut insights = vec!["Activity insights".bold().into(), Line::default()]; - for (label, value) in metrics { - insights.extend(word_wrap_lines( - [columns( - label.set_style(secondary_style()).into(), - value.into(), - column_width, - )], - RtOptions::new(column_width), - )); - } - let mut plugins = vec![ - "Most used plugins and skills".bold().into(), - Line::default(), - ]; - if let Some(invocations) = &stats.top_invocations { - let mut displayed = 0; - for invocation in invocations { - let (prefix, name) = match invocation.kind { - ProfileInvocationKind::Plugin => ("@", invocation.plugin_name.as_deref()), - ProfileInvocationKind::Skill => ("$", invocation.skill_name.as_deref()), - ProfileInvocationKind::Unknown => continue, - }; - let Some(name) = name.filter(|name| !name.trim().is_empty()) else { - continue; - }; - let value = invocation - .usage_count - .map(|count| { - format!( - "{} {}", - count_value(Some(count)), - if count == 1 { "run" } else { "runs" } - ) - }) - .unwrap_or_else(|| "—".into()); - plugins.extend(word_wrap_lines( - [columns( - truncate( - format!("{prefix}{}", name.trim()).into(), - column_width.saturating_sub(value.len() + 1), - ), - value.set_style(secondary_style()).into(), - column_width, - )], - RtOptions::new(column_width), - )); - displayed += 1; - if displayed == 5 { - break; - } - } - if displayed == 0 { - plugins.push( - "No reported plugins or skills." - .set_style(secondary_style()) - .into(), - ); - } - } else { - plugins.push( - "Plugin and skill usage unavailable." - .set_style(secondary_style()) - .into(), - ); - } - if two_columns { - lines.extend(join_columns(&insights, &plugins, column_width)); - } else { - lines.extend(insights); - lines.push(Line::default()); - lines.extend(plugins); - } - if let Some(metadata) = &profile.metadata { - lines.push(Line::default()); - if let Some(date) = metadata - .stats_as_of - .as_deref() - .and_then(|date| chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()) - { - lines.push( - format!("Statistics as of {}", date.format("%b %-d, %Y")) - .set_style(secondary_style()) - .into(), - ); - } - if metadata - .stats_error - .as_deref() - .is_some_and(|error| !error.trim().is_empty()) - { - lines.push( - "Some profile statistics are unavailable." - .set_style(secondary_style()) - .into(), - ); - } - } - let padding = " ".repeat(width.saturating_sub(inner_width) / 2); - word_wrap_lines(lines, RtOptions::new(inner_width)) - .into_iter() - .map(|mut line| { - line.spans.insert(/*index*/ 0, padding.clone().into()); - line - }) - .collect() - } -} - -fn center(mut line: Line<'static>, width: usize) -> Line<'static> { - line.spans.insert( - /*index*/ 0, - " ".repeat(width.saturating_sub(line.width()) / 2).into(), - ); - line -} - -fn percent(value: Option<&serde_json::Number>) -> String { - value - .and_then(serde_json::Number::as_f64) - .filter(|value| value.is_finite() && (0.0..=100.0).contains(value)) - .map(|value| format!("{value:.0}%")) - .unwrap_or_else(|| "—".into()) -} - -fn count_value(value: Option) -> String { - let Some(value) = value else { - return "—".into(); - }; - let digits = value.to_string(); - digits - .chars() - .enumerate() - .fold(String::new(), |mut result, (index, ch)| { - if index > 0 && (digits.len() - index).is_multiple_of(/*rhs*/ 3) { - result.push(','); - } - result.push(ch); - result - }) -} - -fn duration(seconds: i64) -> String { - let seconds = seconds.max(/*other*/ 0); - let (hours, minutes) = (seconds / 3600, seconds % 3600 / 60); - match (hours, minutes) { - (0, 0) => format!("{seconds}s"), - (0, minutes) => format!("{minutes}m"), - (hours, 0) => format!("{hours}h"), - (hours, minutes) => format!("{hours}h {minutes}m"), - } -} diff --git a/codex-rs/tui/src/analytics/summary_tests.rs b/codex-rs/tui/src/analytics/summary_tests.rs deleted file mode 100644 index 57d12425..00000000 --- a/codex-rs/tui/src/analytics/summary_tests.rs +++ /dev/null @@ -1,147 +0,0 @@ -//! Summary reflow, aggregation selection, and independently unavailable profile sections. -use super::*; -use pretty_assertions::assert_eq; -use serde_json::json; - -fn profile() -> codex_backend_client::AccountProfile { - serde_json::from_value(json!({ - "profile":{"display_name":"Example User","username":"example.user"}, - "metadata":{"stats_as_of":"2026-09-09"}, - "stats":{"lifetime_tokens":142_300_000_000_i64,"peak_daily_tokens":7_000_000_000_i64, - "longest_running_turn_sec":158820,"current_streak_days":158,"longest_streak_days":160, - "daily_usage_buckets":[{"start_date":"2026-09-08","tokens":100},{"start_date":"2026-09-09","tokens":200}], - "fast_mode_usage_percentage":37.0,"most_used_reasoning_effort":"high","most_used_reasoning_effort_percentage":26.0, - "unique_skills_used":147,"total_skills_used":13190,"total_threads":21482, - "top_invocations":[{"type":"skill","skill_name":"review","usage_count":1142},{"type":"plugin","plugin_name":"GitHub","usage_count":1059},{"type":"future"}]} - })).unwrap() -} - -#[test] -fn summary_modes_reflow_and_keep_selection_across_tabs() { - let mut view = fixture::view(models::AccountKind::Consumer); - view.profile = Load::Ready(profile()); - view.end_date = "2026-09-09".parse().unwrap(); - view.select_summary(Some(crate::analytics::TokenActivityView::Daily)); - insta::assert_snapshot!( - "summary_daily_wide", - screen(&mut view, /*width*/ 140, /*height*/ 44) - ); - press(&mut view, KeyCode::Char('g')); - assert_eq!(view.sections[Section::Summary].group, 1); - assert!(view.profile.ready().is_some()); - press(&mut view, KeyCode::Tab); - press(&mut view, KeyCode::BackTab); - assert_eq!(view.sections[Section::Summary].group, 1); - press(&mut view, KeyCode::Char('g')); - insta::assert_snapshot!( - "summary_cumulative_narrow", - screen(&mut view, /*width*/ 64, /*height*/ 60) - ); - for width in [1, 4, 28, 64] { - let lines = view.summary_lines(width); - assert!(lines.iter().all(|line| line.width() <= width)); - } - screen(&mut view, /*width*/ 64, /*height*/ 18); - press(&mut view, KeyCode::End); - screen(&mut view, /*width*/ 64, /*height*/ 18); - assert!(view.scroll_offset() > 0); - press(&mut view, KeyCode::Home); - assert_eq!(view.scroll_offset(), 0); - press(&mut view, KeyCode::Esc); - assert!(view.is_done); -} - -#[test] -fn partial_summary_keeps_missing_values_and_zero() { - let mut view = fixture::view(models::AccountKind::Business); - view.select_summary(/*view*/ None); - view.profile = Load::Ready(serde_json::from_value(json!({ - "metadata":{"stats_error":"sensitive upstream error"}, - "stats":{"lifetime_tokens":0,"fast_mode_usage_percentage":0,"total_threads":0,"top_invocations":[]} - })).unwrap()); - let rendered = screen(&mut view, /*width*/ 100, /*height*/ 40); - assert!(!rendered.contains("sensitive upstream error")); - insta::assert_snapshot!("summary_partial", rendered); - view.refresh(); - assert!(view.profile.ready().is_none()); -} - -#[tokio::test] -async fn summary_loads_once_per_open_and_does_not_block_other_reports() { - use wiremock::Mock; - use wiremock::ResponseTemplate; - use wiremock::matchers::header; - use wiremock::matchers::method; - use wiremock::matchers::path; - let server = test_support::server().await; - let requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(/*v*/ 0)); - let count = std::sync::Arc::clone(&requests); - Mock::given(method("GET")) - .and(path("/backend-api/wham/profiles/me")) - .and(header("chatgpt-account-id", "account-a")) - .respond_with(move |_: &wiremock::Request| { - if count.fetch_add(/*val*/ 1, std::sync::atomic::Ordering::SeqCst) == 0 { - ResponseTemplate::new(/*s*/ 503) - } else { - ResponseTemplate::new(/*s*/ 200) - .set_body_json(json!({"stats":{"lifetime_tokens":123}})) - } - }) - .expect(/*r*/ 2) - .mount(&server) - .await; - let (_home, _app_server, mut view) = client::tests::connected_view(&server, "plus").await; - test_support::settle(&mut view).await; - assert_eq!(view.section, Section::Summary); - assert!(matches!(view.profile, Load::Error(_))); - assert!(view.sections[Section::Usage].history.ready().is_some()); - press(&mut view, KeyCode::Char('g')); - press(&mut view, KeyCode::Tab); - test_support::settle(&mut view).await; - assert!(view.sections[Section::Usage].history.ready().is_some()); - press(&mut view, KeyCode::BackTab); - test_support::settle(&mut view).await; - assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1); - let (config, handle, frame) = view.connection.as_ref().unwrap().clone(); - view.cancel_loads(); - view.open(handle, frame, Vec::new(), config); - test_support::settle(&mut view).await; - assert_eq!( - view.profile.ready().unwrap().stats.tokens.lifetime_tokens, - Some(123) - ); - assert_eq!(view.sections[Section::Summary].group, 1); - view.cancel_loads(); - assert!(matches!(view.profile, Load::Unavailable)); -} - -#[tokio::test] -async fn closing_summary_aborts_its_pending_profile() { - let mut view = fixture::view(models::AccountKind::Consumer); - let (cancelled_tx, cancelled_rx) = tokio::sync::oneshot::channel::<()>(); - view.profile = Load::start( - async move { - let _cancelled = cancelled_tx; - std::future::pending().await - }, - crate::tui::FrameRequester::test_dummy(), - ); - view.cancel_loads(); - assert!(cancelled_rx.await.is_err()); -} - -#[test] -fn summary_scroll_hints_follow_overflow_and_grouping_wraps() { - let mut view = fixture::view(models::AccountKind::Consumer); - view.profile = Load::Ready(profile()); - view.select_summary(Some(crate::analytics::TokenActivityView::Daily)); - assert!(!screen(&mut view, /*width*/ 140, /*height*/ 60).contains("scroll")); - assert!(screen(&mut view, /*width*/ 80, /*height*/ 18).contains("scroll")); - let mut groups = Vec::new(); - for _ in 0..4 { - groups.push(view.sections[Section::Summary].group); - press(&mut view, KeyCode::Char('g')); - } - assert_eq!(groups, vec![0, 1, 2, 0]); - assert!(!screen(&mut view, /*width*/ 140, /*height*/ 60).contains("scroll")); -} diff --git a/codex-rs/tui/src/analytics/task_panel.rs b/codex-rs/tui/src/analytics/task_panel.rs deleted file mode 100644 index cbef9c0c..00000000 --- a/codex-rs/tui/src/analytics/task_panel.rs +++ /dev/null @@ -1,399 +0,0 @@ -//! Consumer chat metrics retain actual balance debits, current-limit comparisons, and partial states. - -use super::AnalyticsView; -use super::render::columns; -use super::sections::Section; -use super::styles::number; -use super::styles::secondary_style; -use super::tasks::Chat; -use crate::line_truncation::truncate_line_with_ellipsis_if_overflow as truncate; -use crate::style::accent_style; -use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_lines; -use codex_backend_client::TaskUsageAmounts; -use codex_backend_client::TaskUsageStatus; -use ratatui::style::Styled; -use ratatui::style::Stylize; -use ratatui::text::Line; -use std::cmp::Ordering; -use std::ops::Range; - -pub(super) const METRICS: [&str; 3] = ["Weekly %", "5-hour %", "Balance credits"]; - -fn compare(a: Option<&TaskUsageAmounts>, b: Option<&TaskUsageAmounts>, metric: usize) -> Ordering { - if metric == 2 { - a.and_then(|a| a.balance_usage_credits.as_ref()) - .cmp(&b.and_then(|b| b.balance_usage_credits.as_ref())) - } else { - let value = |amounts: &TaskUsageAmounts| { - if metric == 0 { - amounts.weekly_limit_percent - } else { - amounts.five_hour_limit_percent - } - }; - a.and_then(value) - .partial_cmp(&b.and_then(value)) - .unwrap_or(Ordering::Equal) - } -} - -pub(super) fn amount(amounts: Option<&TaskUsageAmounts>, metric: usize) -> String { - let Some(amounts) = amounts else { - return "—".into(); - }; - if metric == 2 { - amounts - .balance_usage_credits - .as_ref() - .map(|amount| { - let value = amount.as_str(); - let (mantissa, exponent) = value.split_once(['e', 'E']).unwrap_or((value, "0")); - let fraction = mantissa - .split_once('.') - .map_or("", |(_, fraction)| fraction); - let digits = mantissa.trim_start_matches(['+', '-']).replace('.', ""); - let digits = digits.trim_start_matches('0'); - if digits.is_empty() { - return "0.00".to_string(); - } - let cent_digits = digits.len() as i64 - + exponent.parse::().unwrap_or_default() as i64 - - fraction.len() as i64 - + 2; - // Retain tiny adjustments and bound the integer conversion before padding. - if !(1..=18).contains(¢_digits) { - return value.to_string(); - } - let mut cents = digits - .bytes() - .chain(std::iter::repeat(b'0')) - .take(cent_digits as usize) - .fold( - /*init*/ 0_i64, - |cents, digit| cents * 10 + i64::from(digit - b'0'), - ); - if digits - .as_bytes() - .get(cent_digits as usize) - .is_some_and(|digit| *digit >= b'5') - { - cents += 1; - } - cents - .checked_mul(/*rhs*/ 10_000) - .map(|micros| { - super::data::credits(if mantissa.starts_with('-') { - -micros - } else { - micros - }) - }) - .unwrap_or_else(|| value.to_string()) - }) - .unwrap_or_else(|| "—".into()) - } else { - (if metric == 0 { - amounts.weekly_limit_percent - } else { - amounts.five_hour_limit_percent - }) - .map(|value| format!("{value:.1}%")) - .unwrap_or_else(|| "—".into()) - } -} - -pub(super) fn available(chat: &Chat) -> Option<&TaskUsageAmounts> { - chat.task - .as_ref() - .filter(|task| task.data_status != TaskUsageStatus::Unavailable) - .map(|task| &task.amounts) -} - -impl AnalyticsView { - pub(super) fn task_metrics(&self) -> Vec { - (0..3) - .filter(|metric| { - *metric == 2 - || self.tasks.ready().is_some_and(|chats| { - chats.rows.iter().any(|chat| { - available(chat).is_some_and(|amounts| { - if *metric == 0 { - amounts.weekly_limit_percent.is_some() - } else { - amounts.five_hour_limit_percent.is_some() - } - }) - }) - }) - }) - .collect() - } - - pub(super) fn task_metric(&self) -> usize { - let metrics = self.task_metrics(); - if metrics.contains(&self.chat_metric) { - self.chat_metric - } else { - metrics[0] - } - } - - pub(super) fn task_rows(&self) -> Vec<&Chat> { - let mut rows = self - .tasks - .ready() - .map(|chats| chats.rows.iter().collect::>()) - .unwrap_or_default(); - rows.sort_by(|a, b| compare(available(b), available(a), self.task_metric())); - rows - } - - pub(super) fn task_lines(&self, width: usize) -> (Vec>, Range) { - let row_width = width.clamp(/*min*/ 1, /*max*/ 111); - let width = row_width.saturating_sub(/*rhs*/ 1).max(/*other*/ 1); - let wrap = |lines| word_wrap_lines(lines, RtOptions::new(width)); - let Some(chats) = self.tasks.ready() else { - return ( - wrap(vec![ - self.tasks - .message() - .unwrap_or("No task usage reported.") - .to_string() - .into(), - ]), - 0..1, - ); - }; - let metric = self.task_metric(); - let mut lines = wrap(vec![ - format!( - "Usage estimates · active in past 30 days · sorted by {}", - METRICS[metric] - ) - .set_style(secondary_style()) - .into(), - if metric == 2 { - "Credits debited from balance · includes adjustments" - } else { - "Recorded usage / current full limit · may exceed 100%" - } - .set_style(secondary_style()) - .into(), - ]); - if chats.rows.is_empty() { - lines.push("No recent local chats.".into()); - return (lines, 0..1); - } - let missing = chats - .rows - .iter() - .filter(|chat| amount(available(chat), metric) == "—") - .count(); - let partial = chats - .rows - .iter() - .filter(|chat| { - chat.task - .as_ref() - .is_some_and(|task| task.data_status == TaskUsageStatus::Partial) - }) - .count(); - if missing + partial > 0 { - lines.extend(wrap(vec![ - format!("Partial ranking · {partial} partial · {missing} unavailable") - .set_style(secondary_style()) - .into(), - ])); - } - let metrics = self.task_metrics(); - let widths = metrics - .iter() - .map(|index| { - chats - .rows - .iter() - .map(|chat| amount(available(chat), *index).len()) - .max() - .unwrap_or_default() - .max(METRICS[*index].len()) - }) - .collect::>(); - let show_all = widths.iter().sum::() + widths.len() * 2 + 24 <= width; - let metric_text = |chat: Option<&Chat>| { - if !show_all { - return chat.map_or_else( - || METRICS[metric].to_string(), - |chat| amount(available(chat), metric), - ); - } - metrics - .iter() - .zip(&widths) - .map(|(index, column_width)| { - let value = chat.map_or_else( - || METRICS[*index].to_string(), - |chat| amount(available(chat), *index), - ); - format!("{value:>column_width$}") - }) - .collect::>() - .join(" ") - }; - lines.push(Line::default()); - lines.push(columns( - " Chat".bold().into(), - metric_text(/*chat*/ None).bold().into(), - width, - )); - let rows = self - .task_rows() - .into_iter() - .enumerate() - .map(|(index, chat)| { - let selected = - self.section == Section::Chats && index == self.sections[Section::Chats].cursor; - let value = metric_text(Some(chat)); - let status = if chat - .task - .as_ref() - .is_some_and(|task| task.data_status == TaskUsageStatus::Partial) - { - " · partial" - } else { - "" - }; - let label = format!( - "{} {}{status}", - if selected { "›" } else { " " }, - chat.display_title() - ); - let label: Line<'static> = if selected { - label.set_style(accent_style()).into() - } else { - label.into() - }; - let mut row = vec![columns( - truncate(label, width.saturating_sub(value.len() + 1)), - if value == "—" { - value.set_style(secondary_style()).into() - } else if selected { - number(value).into() - } else { - value.into() - }, - width, - )]; - let header_len = row.len(); - if self.zoomed && self.sections[Section::Chats].detail == Some(index) { - row.push("─".repeat(width).dim().into()); - row.extend(word_wrap_lines( - [chat.display_title().to_owned().bold()], - RtOptions::new(width) - .initial_indent(" ".into()) - .subsequent_indent(" ".into()), - )); - for index in self.task_metrics() { - let label = METRICS[index]; - row.push(columns( - format!(" {label}").into(), - amount(available(chat), index).into(), - width, - )); - } - if let Some(task) = &chat.task { - if task.data_status != TaskUsageStatus::Unavailable - && !task.groups.is_empty() - { - let mut groups = task.groups.iter().collect::>(); - groups.sort_by(|a, b| { - compare(Some(&b.amounts), Some(&a.amounts), metric) - }); - row.push(Line::default()); - row.push(columns( - " Model / effort / speed".bold().into(), - METRICS[metric].bold().into(), - width, - )); - for group in groups { - let model = self - .model_name(group.model.as_deref().unwrap_or("Not reported")); - let value = amount(Some(&group.amounts), metric); - row.push(columns( - truncate( - format!(" {model}").bold().into(), - width.saturating_sub(value.len() + 1), - ), - value.into(), - width, - )); - row.push( - format!( - " {} · {} · {}", - group.reasoning_effort.as_deref().unwrap_or("Not reported"), - group.speed.as_deref().unwrap_or("Not reported"), - group - .product_experience - .as_deref() - .unwrap_or("Not reported") - ) - .set_style(secondary_style()) - .into(), - ); - } - } - } else { - row.push( - " Task usage unavailable." - .set_style(secondary_style()) - .into(), - ); - } - row.push(Line::default()); - } - let details = row.split_off(header_len); - let mut row = wrap(row); - // Wrap first: wrapping trims the highlighted trailing blank otherwise. - if selected { - for line in &mut row { - super::styles::select_row(line, row_width); - } - } - row.extend(wrap(details)); - row - }) - .collect::>(); - let mut coverage = vec![ - "Local chats · includes discovered descendants · excludes archived roots" - .set_style(secondary_style()) - .into(), - ]; - if chats.truncated { - coverage.push( - "Partial ranking · 100 most recently active chats" - .set_style(secondary_style()) - .into(), - ); - } - if let Some(time) = chats.updated_at { - coverage.push( - format!( - "Updated {} UTC · recent activity may be delayed", - time.format(self.clock_format.date_time_format()) - ) - .set_style(secondary_style()) - .into(), - ); - } - if !self.zoomed { - let count = rows.len(); - lines.extend(rows.into_iter().take(/*n*/ 5).flatten()); - lines.push(Line::default()); - lines.push(format!("Showing top {} of {count} chats", count.min(/*other*/ 5)).into()); - lines.extend(wrap(coverage)); - (lines, 0..1) - } else { - self.chat_window(lines, rows, wrap(coverage), width) - } - } -} diff --git a/codex-rs/tui/src/analytics/tasks.rs b/codex-rs/tui/src/analytics/tasks.rs deleted file mode 100644 index 35524a72..00000000 --- a/codex-rs/tui/src/analytics/tasks.rs +++ /dev/null @@ -1,248 +0,0 @@ -//! Consumer task queries preserve missing amounts and require complete descendant groups. -use super::client::Live; -use codex_app_server_client::AppServerRequestHandle; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::Thread; -use codex_app_server_protocol::ThreadListParams; -use codex_app_server_protocol::ThreadListResponse; -use codex_backend_client::TaskUsage; -use codex_backend_client::TaskUsageThread; -use futures::StreamExt; -use std::collections::HashMap; -use std::collections::HashSet; -use std::sync::Arc; - -pub(super) struct Chat { - pub title: String, - pub task: Option, -} -impl Chat { - /// Local history can span accounts; unavailable task data does not verify ownership. - pub(super) fn display_title(&self) -> &str { - if self.task.as_ref().is_some_and(|task| { - task.data_status != codex_backend_client::TaskUsageStatus::Unavailable - }) { - &self.title - } else { - "Chat usage unavailable" - } - } -} - -#[derive(Default)] -pub(super) struct Chats { - pub rows: Vec, - pub truncated: bool, - pub updated_at: Option>, -} - -pub(super) async fn read( - handle: AppServerRequestHandle, - live: Arc, -) -> Result, String> { - let session = live.session().await?; - if session.kind != super::models::AccountKind::Consumer { - return Ok(None); - } - 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()); - live.ensure_identity().await?; - let mut roots = roots??; - roots.sort_by(|a, b| { - b.updated_at - .cmp(&a.updated_at) - .then_with(|| a.id.cmp(&b.id)) - }); - let truncated = roots.len() > 100; - roots.truncate(/*len*/ 100); - let discoveries = roots - .iter() - .map(|root| descendants(&handle, root)) - .collect::>(); - let mut pending = futures::stream::iter(discoveries).buffer_unordered(/*n*/ 2); - let mut queries = Vec::new(); - // Keep complete groups collected before the deadline; never query partial descendants. - 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 { - if let Ok(query) = result { - queries.push(query); - } - } - drop(pending); - live.ensure_identity().await?; - let mut seen = HashSet::new(); - let mut batches = Vec::new(); - let mut batch = Vec::new(); - let mut count = 0; - for query in queries { - let ids = std::iter::once(&query.thread_id).chain(&query.descendant_thread_ids); - if ids.clone().any(|id| !seen.insert(id.clone())) { - return Err("Task descendant groups overlap.".into()); - } - let size = 1 + query.descendant_thread_ids.len(); - if count + size > 1_000 || batch.len() == 100 { - batches.push(std::mem::take(&mut batch)); - count = 0; - } - count += size; - batch.push(query); - } - if !batch.is_empty() { - batches.push(batch); - } - let requests = batches - .into_iter() - .map(|threads| async move { - session - .backend - .request(|client| { - let threads = threads.clone(); - async move { client.get_task_usage(&threads).await } - }) - .await - }) - .collect::>(); - let expected_batches = requests.len(); - let mut completed_batches = 0; - let mut pending = futures::stream::iter(requests).buffer_unordered(/*n*/ 2); - let mut usage = HashMap::new(); - let mut freshness = Vec::new(); - 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( - response - .data_as_of - .as_deref() - .map(chrono::DateTime::parse_from_rfc3339) - .transpose() - .map_err(|_| "Invalid task usage timestamp.")? - .map(|time| time.with_timezone(&chrono::Utc)), - ); - usage.extend( - response - .threads - .into_iter() - .map(|task| (task.thread_id.clone(), task)), - ); - } - Err(error) - if error - .status() - .is_some_and(|status| matches!(status.as_u16(), 404 | 503)) => - { - freshness.push(/*value*/ None); - } - Err(error) => return Err(super::client::request_error(error)), - } - } - if completed_batches < expected_batches { - freshness.push(/*value*/ None); - } - drop(pending); - live.ensure_identity().await?; - Ok(Some(Chats { - truncated, - updated_at: if freshness.iter().all(Option::is_some) { - freshness.into_iter().flatten().min() - } else { - None - }, - rows: roots - .into_iter() - .map(|thread| Chat { - task: usage.remove(&thread.id), - title: thread - .name - .filter(|name| !name.trim().is_empty()) - .unwrap_or_else(|| { - if thread.preview.trim().is_empty() { - "Untitled chat".into() - } else { - thread.preview - } - }), - }) - .collect(), - })) -} - -async fn descendants( - handle: &AppServerRequestHandle, - root: &Thread, -) -> Result { - let mut ids = HashSet::new(); - let mut parents = HashMap::new(); - for archived in [false, true] { - let mut cursor = None; - let mut seen = HashSet::new(); - loop { - let page: ThreadListResponse = handle - .request_typed(ClientRequest::ThreadList { - request_id: RequestId::String(uuid::Uuid::new_v4().to_string()), - params: ThreadListParams { - current_account_only: false, - ancestor_thread_id: Some(root.id.clone()), - archived: Some(archived), - cursor, - limit: Some(100), - ..super::chats::list_params() - }, - }) - .await - .map_err(super::data::error)?; - for thread in page.data { - let parent = thread - .parent_thread_id - .filter(|_| thread.id != root.id) - .ok_or("Task descendant discovery is unsupported.")?; - parents.insert(thread.id.clone(), parent); - ids.insert(thread.id); - } - if ids.len() >= 1_000 { - return Err("Task exceeds the reporting limit.".into()); - } - match page.next_cursor { - Some(next) if seen.insert(next.clone()) => cursor = Some(next), - Some(_) => return Err("Task listing repeated a cursor.".into()), - None => break, - } - } - } - // Older servers can ignore the ancestor filter. Prove every returned chain reaches this root. - for id in &ids { - let mut current = id; - let mut chain = HashSet::new(); - while current != &root.id { - if !chain.insert(current) { - return Err("Task descendant cycle.".into()); - } - current = parents - .get(current) - .ok_or("Task descendant discovery is incomplete.")?; - } - } - let mut descendant_thread_ids = ids.into_iter().collect::>(); - descendant_thread_ids.sort(); - Ok(TaskUsageThread { - thread_id: root.id.clone(), - created_at: (root.created_at > 0) - .then(|| chrono::DateTime::from_timestamp(root.created_at, /*nsecs*/ 0)) - .flatten() - .map(|time| time.to_rfc3339()), - descendant_thread_ids, - }) -} - -#[cfg(test)] -#[path = "tasks_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/tasks_tests.rs b/codex-rs/tui/src/analytics/tasks_tests.rs deleted file mode 100644 index bc1a6b1f..00000000 --- a/codex-rs/tui/src/analytics/tasks_tests.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! Consumer HTTP contract, descendant discovery, and partial-result regression coverage. - -use super::super::client::tests::live; -use super::*; -use pretty_assertions::assert_eq; -use serde_json::json; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; - -#[tokio::test] -async fn consumer_roots_include_paginated_archived_descendants_and_keep_missing_usage() { - 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; - use futures::SinkExt; - use tokio_tungstenite::tungstenite::Message; - - let server = MockServer::start().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 { - let (stream, _) = listener.accept().await.unwrap(); - let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap(); - let mut pages = 0; - while let Some(Ok(Message::Text(text))) = socket.next().await { - let request: serde_json::Value = serde_json::from_str(&text).unwrap(); - let result = match request["method"].as_str() { - Some("initialize") => { - json!({"userAgent":"analytics-test", "codexHome":"/unused"}) - } - Some("thread/list") => { - pages += 1; - if pages == 1 { - tokio::time::pause(); - tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 31)).await; - tokio::time::resume(); - } - let params = &request["params"]; - assert_eq!(params["modelProviders"], json!([])); - assert_ne!(params["useStateDbOnly"], json!(true)); - let ancestor = params["ancestorThreadId"].as_str(); - let archived = params["archived"] == true; - let cursor = params["cursor"].as_str(); - let ids = match (ancestor, archived, cursor) { - (None, false, None) => vec!["root", "missing"], - (Some("root"), false, None) if unsupported => vec!["unrelated"], - (Some("root"), false, None) => vec!["child"], - (Some("root"), false, Some("next")) => vec!["grandchild"], - (Some("root"), true, None) => vec!["archived-child"], - (Some("missing"), _, None) => Vec::new(), - _ => panic!("Unexpected thread listing: {params}"), - }; - let data = ids.into_iter().map(|id| json!({ - "id":id, "sessionId":id, "parentThreadId":if id == "unrelated" { None } else if id == "grandchild" { Some("child") } else { ancestor }, "preview":id, "ephemeral":false, - "modelProvider":"openai", "createdAt":1788220800_i64, - "updatedAt":chrono::Utc::now().timestamp(), "status":{"type":"idle"}, - "cwd":std::env::temp_dir(), "cliVersion":"test", "source":"cli", "turns":[] - })).collect::>(); - json!({"data":data, "nextCursor":if ancestor == Some("root") && !archived && cursor.is_none() { Some("next") } else { None }}) - } - _ => continue, - }; - socket - .send(Message::Text( - json!({"jsonrpc":"2.0", "id":request["id"], "result":result}) - .to_string() - .into(), - )) - .await - .unwrap(); - if pages == if unsupported { 4 } else { 6 } { - break; - } - } - pages - }); - let remote = RemoteAppServerClient::connect(RemoteAppServerConnectArgs { - required_human_approval: true, - endpoint: RemoteAppServerEndpoint::WebSocket { - websocket_url, - auth_token: None, - }, - client_name: "analytics-test".into(), - client_version: "test".into(), - experimental_api: false, - mcp_server_openai_form_elicitation: false, - opt_out_notification_methods: Vec::new(), - channel_capacity: 16, - }) - .await - .unwrap(); - Mock::given(method("POST")).and(path("/backend-api/wham/usage/thread_usage/query_v2")) - .respond_with(move |request:&wiremock::Request| { - let mut body:serde_json::Value = request.body_json().unwrap(); - body["threads"].as_array_mut().unwrap().sort_by_key(|thread| thread["thread_id"].as_str().unwrap().to_string()); - let mut expected=json!({"threads":[ - {"thread_id":"missing", "created_at":"2026-09-01T00:00:00+00:00", "descendant_thread_ids":[]}, - {"thread_id":"root", "created_at":"2026-09-01T00:00:00+00:00", "descendant_thread_ids":["archived-child", "child", "grandchild"]} - ]}); - 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 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(), - chats - .rows - .iter() - .filter_map(|chat| chat.task.as_ref().map(|task| task.data_status)) - .collect::>() - ), - ( - 2, - if unsupported || status != 200 { - vec![] - } else { - vec![codex_backend_client::TaskUsageStatus::Partial] - } - ) - ); - } -} diff --git a/codex-rs/tui/src/analytics/test_fixtures.rs b/codex-rs/tui/src/analytics/test_fixtures.rs deleted file mode 100644 index b9cf8d6b..00000000 --- a/codex-rs/tui/src/analytics/test_fixtures.rs +++ /dev/null @@ -1,242 +0,0 @@ -//! Bounded fictional dashboard data with raw daily units. -//! Charts and their totals share the same daily series; no account activity is read. - -use crate::analytics::sections::Section; -pub(super) const END_DATE: chrono::NaiveDate = - match chrono::NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 9, /*day*/ 2) { - Some(date) => date, - None => panic!("invalid test date"), - }; - -pub(super) const TOOL_DAILY: [[u32; 7]; 2] = [[34, 23, 29, 26, 22, 23, 29], [8, 6, 9, 8, 7, 5, 11]]; - -pub(super) const GROUPS: &[(&str, [&str; 4], [u32; 4])] = &[ - ( - "Surface", - ["Desktop app", "CLI", "IDE extension", "Web"], - [35, 36, 17, 12], - ), - ( - "Feature", - ["Tasks", "Code review", "Images", "Other"], - [65, 15, 12, 8], - ), - ( - "Model", - ["GPT-5.6-Sol", "GPT-5.6-Terra", "GPT-5.5", "Other"], - [60, 25, 10, 5], - ), - ( - "Task start", - ["User messages", "Goals", "Automations", "Other"], - [29, 10, 5, 5], - ), - ( - "Speed", - ["Standard", "Fast", "Priority", "Unknown"], - [65, 30, 5, 0], - ), - ( - "Reasoning", - ["Low", "Medium", "High", "Other"], - [10, 30, 50, 10], - ), - ( - "Token type", - ["Uncached input", "Cached input", "Output", "Other"], - [20, 70, 10, 0], - ), -]; - -pub(super) fn daily(section: Section, range: usize) -> Vec { - let (earlier, recent) = match section { - Section::Usage => (40, [20, 73, 64, 91, 81, 100, 86]), - Section::Credits => (35, [0, 41, 57, 85, 75, 109, 64]), - Section::Activity => (34, [62, 83, 107, 75, 59, 85, 103]), - _ => return Vec::new(), - }; - let mut values = vec![earlier; if range == 0 { 0 } else { 23 }]; - values.extend(recent); - values -} - -pub(super) fn breakdown(total: u32, group: usize) -> [u32; 4] { - let mut values = GROUPS[group].2.map(|weight| total * weight / 100); - if group != 3 { - values[3] = total - values[..3].iter().sum::(); - } - values -} - -/// Fixtures use the private report types and the same presentation path as live reports. -pub(super) fn history( - report: usize, - range: usize, - group: usize, -) -> crate::analytics::models::AccountAnalyticsHistory { - use crate::analytics::models::AccountAnalyticsDay; - use crate::analytics::models::AccountAnalyticsHistory; - use crate::analytics::models::AccountAnalyticsUnit; - use crate::analytics::models::AccountAnalyticsValue; - let section = [ - Section::Usage, - Section::Credits, - Section::Activity, - Section::Plugins, - Section::Skills, - ][report]; - let series = if report < 3 { - daily(section, range) - } else { - let mut series = vec![if report == 3 { 20 } else { 5 }; if range == 0 { 0 } else { 23 }]; - series.extend(TOOL_DAILY[report - 3]); - series - }; - let start = END_DATE - chrono::Days::new(if range == 0 { 6 } else { 29 }); - AccountAnalyticsHistory { - unit: if report == 0 { - AccountAnalyticsUnit::RelativeUsage - } else if report == 1 { - AccountAnalyticsUnit::Credits - } else { - AccountAnalyticsUnit::Count - }, - updated_at: None, - data: series - .into_iter() - .enumerate() - .map(|(day, total)| { - let labels = if report < 3 { - GROUPS[group].1 - } else if report == 3 { - ["Figma", "Slack", "Notion", "GitHub"] - } else { - ["Code review", "Planning", "Debugging", "Testing"] - }; - let values = breakdown(total, if report < 3 { group } else { 0 }); - let pairs = if report == 0 && group == 0 { - vec![ - ("Codex", total * 65 / 100), - ("Work", total - total * 65 / 100), - ] - } else { - labels.into_iter().zip(values).collect() - }; - AccountAnalyticsDay { - date: start + chrono::Days::new(day as u64), - total: f64::from(total), - values: pairs - .into_iter() - .map(|(label, value)| AccountAnalyticsValue { - key: label.into(), - label: label.into(), - value: f64::from(value), - }) - .collect(), - } - }) - .collect(), - } -} - -pub(super) fn chats() -> super::chats::Chats { - use codex_backend_client::ThreadUsage; - use codex_backend_client::ThreadUsageBreakdownGroup; - super::chats::Chats { - rows: [ - ("Q3 planning analysis", 120), - ("Refactor billing usage", 113), - ("Other usage", 109), - ("Launch readiness review", 85), - ("Plan the week", 0), - ] - .into_iter() - .enumerate() - .map(|(index, (title, credits))| super::chats::Chat { - title: title.into(), - usage: Some(ThreadUsage { - thread_id: format!("test-{index}"), - estimated_usage_credits_micros: credits * 1_000_000, - estimated_usage_usd_micros: None, - native_usage_usd_micros: None, - groups: vec![ThreadUsageBreakdownGroup { - model: Some("GPT-5.6-Sol".into()), - reasoning_effort: Some("high".into()), - speed: Some("standard".into()), - estimated_usage_credits_micros: credits * 1_000_000, - native_usage_usd_micros: None, - net_new_input_tokens: None, - cached_input_tokens: None, - input_tokens: None, - output_tokens: None, - total_tokens: None, - }], - }), - }) - .collect(), - } -} - -pub(super) fn tokens(range: usize, grouping: usize) -> super::models::AccountAnalyticsHistory { - let response = serde_json::json!({"data_freshness_ts":"2026-09-02T16:00:00Z", "data": - daily(Section::Usage, range).into_iter().enumerate().map(|(index, total)| serde_json::json!({ - "date": (END_DATE - chrono::Days::new(if range == 0 { 6 } else { 29 }) + chrono::Days::new(index as u64)).to_string(), - "groups": [{"dimensions":{"model":"GPT-5.5"}, "uncached_text_input_tokens": total * 1000, "cached_text_input_tokens":total * 7000, "text_output_tokens":total * 500}] - })).collect::>() - }); - match super::tokens::history( - match serde_json::from_value(response) { - Ok(response) => response, - Err(_) => panic!("invalid test token response"), - }, - super::data::GROUPINGS[grouping], - END_DATE - chrono::Days::new(if range == 0 { 6 } else { 29 }), - END_DATE, - ) { - Ok(history) => history, - Err(_) => panic!("invalid test token history"), - } -} - -/// Build a fixed account state for rendering tests; never opens a connection. -pub(super) fn view(kind: super::models::AccountKind) -> super::AnalyticsView { - let mut view = super::AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list); - view.end_date = END_DATE; - view.account = super::data::Load::Ready(match kind { - super::models::AccountKind::Consumer => codex_protocol::account::PlanType::Plus, - super::models::AccountKind::Business => codex_protocol::account::PlanType::Team, - super::models::AccountKind::Enterprise => { - codex_protocol::account::PlanType::EnterpriseCbpUsageBased - } - super::models::AccountKind::Unknown => codex_protocol::account::PlanType::Unknown, - }); - view.section = if view.business() { - super::sections::Section::Credits - } else { - super::sections::Section::Usage - }; - view.start_reports(); - seed_reports(&mut view); - view -} - -/// Populate explicit report state after a test chooses its account, period, and grouping. -pub(super) fn seed_reports(view: &mut super::AnalyticsView) { - use super::data::Load; - view.clock_format = crate::clock_format::ClockFormat::TwentyFourHour; - if view.business() { - view.chats = Load::Ready(chats()); - } - for section in view.visible_sections() { - if let Some(report) = section.report() { - let range = view.ranges[view.range_group(*section) as usize]; - let group = view.sections[*section].group; - view.sections[*section].history = - Load::Ready(if *section == Section::Usage && view.business() { - tokens(range, group) - } else { - history(report as usize, range, group) - }); - } - } -} diff --git a/codex-rs/tui/src/analytics/test_support.rs b/codex-rs/tui/src/analytics/test_support.rs deleted file mode 100644 index 82b605a1..00000000 --- a/codex-rs/tui/src/analytics/test_support.rs +++ /dev/null @@ -1,76 +0,0 @@ -//! Mock HTTP reports for tests that exercise the authenticated dashboard loading path. -use super::data::Load; -use serde_json::json; - -pub(super) async fn server() -> wiremock::MockServer { - let server = wiremock::MockServer::start().await; - wiremock::Mock::given(wiremock::matchers::method("GET")) - .and(wiremock::matchers::path_regex("^/backend-api/wham/(usage|analytics)/")) - .respond_with(|request: &wiremock::Request| { - let params = request.url.query_pairs().collect::>(); - let today = chrono::Utc::now().date_naive(); - let start = params.get("start_date").map_or(today, |date| date.parse().unwrap()); - let end = params.get("end_date").map_or(today, |date| date.parse().unwrap()); - let route = request.url.path().rsplit('/').next().unwrap(); - let data = start.iter_days().take_while(|date| *date <= end).map(|date| { - let date = date.to_string(); - match route { - "daily-token-usage-breakdown" | "daily-workspace-user-token-usage-breakdown" => json!({ - "date":date, "product_surface_usage_values":{"codex_cli":10.0}, - "premium_usage_values":{ - "credit_usage_credits":{"codex_cli":10.0}, "total_usage_credits":{}, - "uncached_text_input_tokens_by_surface":{}, "cached_text_input_tokens_by_surface":{}, - "text_output_tokens_by_surface":{}, "text_total_tokens_by_surface":{} - }, - "models":[{"model":"GPT-5.5","credits":10.0,"on_demand_credits":10.0,"turns":10,"speed":"standard"}], - "groups":[{"dimensions":{"model":"GPT-5.5"},"credits":10.0,"uncached_text_input_tokens":10,"cached_text_input_tokens":20,"text_output_tokens":30}] - }), - "credit-usage-events" => json!({"date":date,"product_surface":"cli","credit_amount":10.0}), - "daily-workspace-user-credit-usage" => json!({"date":date,"values":{"codex":10.0}}), - "daily-workspace-usage-counts" => json!({ - "date":date,"totals":{"users":1,"threads":1,"turns":10,"credits":10.0},"clients":[], - "models":[{"model":"GPT-5.5","credits":10.0,"turns":10}] - }), - "daily-plugin-usage-metrics" => json!({"date":date,"plugin_usage_overviews":[{ - "plugin_id":null,"plugin_name":"test","marketplace":null,"display_name":"Test plugin","invocation_counts":10 - }]}), - "daily-skill-usage-metrics" => json!({"date":date,"skill_usage_overviews":[{ - "skill_name":"test","skill_ids":[],"display_name":"Test skill","invocation_counts":10 - }]}), - _ => panic!("Unexpected mock analytics route: {route}"), - } - }).collect::>(); - let response = if route == "daily-workspace-user-credit-usage" { - json!({"breakdown":params["breakdown"],"series":[{"key":"codex","label":"Codex","total":data.len() as f64 * 10.0}],"data":data}) - } else { - json!({"data":data}) - }; - wiremock::ResponseTemplate::new(/*s*/ 200).set_body_json(response) - }) - .mount(&server).await; - server -} - -pub(super) async fn settle(view: &mut super::AnalyticsView) { - tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 10), async { - loop { - view.poll_reports(); - if !matches!(view.account, Load::Loading(_)) - && !view - .sections - .0 - .iter() - .any(|state| matches!(state.history, Load::Loading(_))) - && !matches!(view.chats, Load::Loading(_)) - && !matches!(view.tasks, Load::Loading(_)) - && !matches!(view.profile, Load::Loading(_)) - && !matches!(view.plan.report, Load::Loading(_)) - { - break; - } - tokio::time::sleep(std::time::Duration::from_millis(/*millis*/ 5)).await; - } - }) - .await - .unwrap(); -} diff --git a/codex-rs/tui/src/analytics/tokens.rs b/codex-rs/tui/src/analytics/tokens.rs deleted file mode 100644 index 7e8e1cae..00000000 --- a/codex-rs/tui/src/analytics/tokens.rs +++ /dev/null @@ -1,135 +0,0 @@ -//! Enterprise text token history, independent of credit and allowance accounting. - -use super::models::*; -use super::report_data::AnalyticsData; -use chrono::NaiveDate; -use std::collections::BTreeMap; - -pub(super) fn history( - response: AnalyticsData, - grouping: AccountAnalyticsGrouping, - start: NaiveDate, - end: NaiveDate, -) -> Result { - filtered_history(response, grouping, start, end, /*model_filter*/ None) -} - -pub(super) fn filtered_history( - response: AnalyticsData, - grouping: AccountAnalyticsGrouping, - start: NaiveDate, - end: NaiveDate, - model_filter: Option<&str>, -) -> Result { - let mut days: BTreeMap> = BTreeMap::new(); - for record in response.data { - let date = record - .date - .parse::() - .map_err(|_| "Invalid token report date.")?; - if date < start || date > end { - continue; - } - let groups = if let Some(groups) = record.groups { - groups - .into_iter() - .map(|group| { - ( - if group.is_other { - "Other".into() - } else { - group - .dimensions - .get("model") - .cloned() - .unwrap_or_else(|| "Unknown".into()) - }, - [ - group.uncached_text_input_tokens, - group.cached_text_input_tokens, - group.text_output_tokens, - ], - None, - ) - }) - .collect::>() - } else if let Some(models) = record.models { - models - .into_iter() - .map(|model| { - ( - model.model, - [ - model.uncached_text_input_tokens, - model.cached_text_input_tokens, - model.text_output_tokens, - ], - model.text_total_tokens, - ) - }) - .collect() - } else { - return Err("Token breakdown is not available in this report.".into()); - }; - let values = days.entry(date).or_default(); - for (model, counts, total) in groups { - if model_filter.is_some_and(|selected| selected != model) { - continue; - } - let missing_components = counts.iter().all(Option::is_none); - if grouping == AccountAnalyticsGrouping::Model - && let Some(total) = total.filter(|total| *total != 0.0 || missing_components) - { - if !total.is_finite() || total < 0.0 || total.fract() != 0.0 { - return Err("Invalid token count.".into()); - } - *values.entry(model).or_default() += total; - continue; - } - if missing_components { - return Err("Token counts were not reported.".into()); - } - for (label, count) in ["Uncached input", "Cached input", "Output"] - .into_iter() - .zip(counts) - { - let count = count.unwrap_or(/*default*/ 0.0); - if !count.is_finite() || count < 0.0 || count.fract() != 0.0 { - return Err("Invalid token count.".into()); - } - let key = if grouping == AccountAnalyticsGrouping::Model { - &model - } else { - label - }; - *values.entry(key.to_string()).or_default() += count; - } - } - } - Ok(AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::Tokens, - updated_at: response - .data_freshness_ts - .and_then(|time| chrono::DateTime::parse_from_rfc3339(&time).ok()) - .map(|time| time.timestamp()), - data: days - .into_iter() - .map(|(date, values)| AccountAnalyticsDay { - date, - total: values.values().sum(), - values: values - .into_iter() - .map(|(key, value)| AccountAnalyticsValue { - label: key.clone(), - key, - value, - }) - .collect(), - }) - .collect(), - }) -} - -#[cfg(test)] -#[path = "tokens_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/analytics/tokens_tests.rs b/codex-rs/tui/src/analytics/tokens_tests.rs deleted file mode 100644 index 3501317b..00000000 --- a/codex-rs/tui/src/analytics/tokens_tests.rs +++ /dev/null @@ -1,131 +0,0 @@ -//! Enterprise token normalization across supported groupings. - -use super::*; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[test] -fn tokens_use_text_components_and_keep_daily_totals_across_groupings() { - let response: AnalyticsData = serde_json::from_value(json!({"units":"credits", "data":[{ - "date":"2026-09-01", "groups":[{"dimensions":{"model":"gpt-5"}, "uncached_text_input_tokens":10, "cached_text_input_tokens":80, "text_output_tokens":10}] - }]})).unwrap(); - let date = "2026-09-01".parse().unwrap(); - let by_type = history( - response.clone(), - AccountAnalyticsGrouping::TokenType, - date, - date, - ) - .unwrap(); - let by_model = history(response, AccountAnalyticsGrouping::Model, date, date).unwrap(); - assert_eq!( - (by_type.unit, by_type.data[0].total, by_model.data[0].total), - (AccountAnalyticsUnit::Tokens, 100.0, 100.0) - ); - assert_eq!( - by_type.data[0] - .values - .iter() - .map(|v| (v.label.as_str(), v.value)) - .collect::>(), - vec![ - ("Cached input", 80.0), - ("Output", 10.0), - ("Uncached input", 10.0) - ] - ); -} - -#[test] -fn token_model_filter_retains_components_and_freshness() { - let date = "2026-09-01".parse().unwrap(); - let response: AnalyticsData = serde_json::from_value(json!({"data_freshness_ts":"2026-09-02T00:00:00Z", "data":[{ - "date":"2026-09-01", "groups":[ - {"dimensions":{"model":"alpha"}, "uncached_text_input_tokens":10,"cached_text_input_tokens":20,"text_output_tokens":30}, - {"dimensions":{"model":"beta"}, "uncached_text_input_tokens":100,"cached_text_input_tokens":200,"text_output_tokens":300} - ], "models":[{"model":"ignored", "text_total_tokens":1000}] - }]})).unwrap(); - let selected = filtered_history( - response.clone(), - AccountAnalyticsGrouping::TokenType, - date, - date, - Some("alpha"), - ) - .unwrap(); - let expected = history(serde_json::from_value(json!({"data_freshness_ts":"2026-09-02T00:00:00Z", "data":[{ - "date":"2026-09-01", "models":[{"model":"alpha", "uncached_text_input_tokens":10,"cached_text_input_tokens":20,"text_output_tokens":30}] - }]})).unwrap(), AccountAnalyticsGrouping::TokenType, date, date).unwrap(); - assert_eq!(selected, expected); - assert_eq!( - history(response, AccountAnalyticsGrouping::TokenType, date, date) - .unwrap() - .data[0] - .total, - 660.0 - ); -} - -#[test] -fn model_totals_use_reported_total_and_missing_components_remain_unavailable() { - let date = "2026-09-01".parse().unwrap(); - let response: AnalyticsData = serde_json::from_value(json!({"data":[{"date":"2026-09-01", "models":[{"model":"alpha", "text_total_tokens":123}]}]})).unwrap(); - assert_eq!( - history( - response.clone(), - AccountAnalyticsGrouping::Model, - date, - date - ) - .unwrap() - .data, - vec![AccountAnalyticsDay { - date: "2026-09-01".parse().unwrap(), - total: 123.0, - values: vec![AccountAnalyticsValue { - key: "alpha".into(), - label: "alpha".into(), - value: 123.0 - }] - }] - ); - assert_eq!( - history(response, AccountAnalyticsGrouping::TokenType, date, date).unwrap_err(), - "Token counts were not reported." - ); -} - -#[test] -fn explicit_zero_model_total_is_reported_without_components() { - let date = "2026-09-01".parse().unwrap(); - let response: AnalyticsData = serde_json::from_value(json!({ - "data": [{"date": "2026-09-01", "models": [ - {"model": "idle", "text_total_tokens": 0}, - {"model": "active", "text_total_tokens": 0, "text_output_tokens": 5} - ]}] - })) - .unwrap(); - assert_eq!( - history(response, AccountAnalyticsGrouping::Model, date, date).unwrap(), - AccountAnalyticsHistory { - unit: AccountAnalyticsUnit::Tokens, - updated_at: None, - data: vec![AccountAnalyticsDay { - date: "2026-09-01".parse().unwrap(), - total: 5.0, - values: vec![ - AccountAnalyticsValue { - key: "active".into(), - label: "active".into(), - value: 5.0, - }, - AccountAnalyticsValue { - key: "idle".into(), - label: "idle".into(), - value: 0.0, - }, - ], - }], - } - ); -} diff --git a/codex-rs/tui/src/analytics/tool_panel.rs b/codex-rs/tui/src/analytics/tool_panel.rs deleted file mode 100644 index c0a4d447..00000000 --- a/codex-rs/tui/src/analytics/tool_panel.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! Human-readable plugin and skill labels. - -pub(super) fn tool_name(label: &str) -> String { - let label = match label.split_once(':') { - Some((namespace, name)) if namespace.trim().eq_ignore_ascii_case(name.trim()) => { - name.trim() - } - _ => label, - }; - label - .split_whitespace() - .map(|word| match word.to_ascii_lowercase().as_str() { - "pr" => "PR", - "cli" => "CLI", - "api" => "API", - "ide" => "IDE", - "mcp" => "MCP", - "sdk" => "SDK", - "ui" => "UI", - "tui" => "TUI", - "openai" => "OpenAI", - _ => word, - }) - .collect::>() - .join(" ") -} diff --git a/codex-rs/tui/src/analytics/tool_panel_tests.rs b/codex-rs/tui/src/analytics/tool_panel_tests.rs deleted file mode 100644 index 797b82a7..00000000 --- a/codex-rs/tui/src/analytics/tool_panel_tests.rs +++ /dev/null @@ -1,97 +0,0 @@ -//! Tool chart layout, independent selection, naming, and partial report states. - -use super::*; -use crate::analytics::sections::Section; -use pretty_assertions::assert_eq; - -#[test] -fn analytics_tools_reflow_and_keep_independent_days() { - let mut view = fixture::view(models::AccountKind::Consumer); - press(&mut view, KeyCode::Char('4')); - let wide = screen(&mut view, /*width*/ 140, /*height*/ 48); - assert!(wide.contains("186 calls")); - press(&mut view, KeyCode::Char('5')); - press(&mut view, KeyCode::Left); - press(&mut view, KeyCode::Enter); - assert_eq!( - ( - view.sections[Section::Plugins].cursor, - view.sections[Section::Skills].cursor, - view.sections[Section::Skills].detail - ), - (6, 5, Some(5)) - ); - let narrow = screen(&mut view, /*width*/ 58, /*height*/ 32); - assert!(narrow.contains("Sep 1 · 5 uses")); - press(&mut view, KeyCode::Char('r')); - assert_eq!( - ( - view.sections[Section::Plugins].cursor, - view.sections[Section::Skills].cursor, - view.ranges - ), - (29, 28, [0, 0, 1]) - ); - press(&mut view, KeyCode::Char('r')); - assert_eq!( - ( - view.sections[Section::Plugins].cursor, - view.sections[Section::Skills].cursor, - view.sections[Section::Skills].detail - ), - (6, 5, Some(5)) - ); -} - -#[test] -fn analytics_tools_handle_empty_days_and_independent_failures() { - let mut view = fixture::view(models::AccountKind::Consumer); - let mut history = fixture::history(/*report*/ 4, /*range*/ 0, /*group*/ 0); - history.data[6].total = 0.0; - for value in &mut history.data[6].values { - value.value = 0.0; - } - history.data.remove(/*index*/ 5); - view.sections[Section::Skills].history = Load::Ready(history); - press(&mut view, KeyCode::Char('5')); - let empty = screen(&mut view, /*width*/ 140, /*height*/ 44); - assert!(empty.contains("No uses reported for Sep 2.")); - assert!(!empty.contains("details")); - press(&mut view, KeyCode::Enter); - assert_eq!(view.sections[Section::Skills].detail, None); - press(&mut view, KeyCode::Left); - let missing = screen(&mut view, /*width*/ 140, /*height*/ 44); - assert!(missing.contains("Data not reported for Sep 1.")); - assert_eq!( - empty.lines().position(|line| line.contains('▲')), - missing.lines().position(|line| line.contains('▲')), - ); - view.sections[Section::Skills].history = - Load::Error("Skills could not be loaded. Press R to retry.".into()); - let partial = screen(&mut view, /*width*/ 140, /*height*/ 44); - assert!(partial.contains("Skills could not be loaded")); - press(&mut view, KeyCode::Char('4')); - assert!(screen(&mut view, /*width*/ 140, /*height*/ 44).contains("186 calls")); -} - -#[test] -fn analytics_tool_names_preserve_acronyms_and_distinct_namespaces() { - let labels = [ - "Pr Reviewer", - "Slack Cli", - "Squatch: Squatch", - "Openai Docs", - "User Writing: Writing Style", - ]; - assert_eq!( - labels.map(tool_panel::tool_name), - [ - "PR Reviewer", - "Slack CLI", - "Squatch", - "OpenAI Docs", - "User Writing: Writing Style" - ] - .map(str::to_owned), - ); -} diff --git a/codex-rs/tui/src/analytics_tests.rs b/codex-rs/tui/src/analytics_tests.rs deleted file mode 100644 index 7dc5a541..00000000 --- a/codex-rs/tui/src/analytics_tests.rs +++ /dev/null @@ -1,667 +0,0 @@ -//! Dashboard layout, local detail, shared ranges, grouping, and scroll/focus retention. - -use crate::analytics::sections::Section; -#[path = "analytics/compact_tests.rs"] -mod compact; -#[path = "analytics/recovery_tests.rs"] -mod recovery; -#[path = "analytics/redesign_tests.rs"] -mod redesign; -#[path = "analytics/summary_tests.rs"] -mod summary; - -#[path = "analytics/account_layout_tests.rs"] -mod account_layout; - -#[path = "analytics/navigation_tests.rs"] -mod navigation; - -#[path = "analytics/consumer_refresh_tests.rs"] -mod consumer_refresh; - -#[path = "analytics/tool_panel_tests.rs"] -mod tools_panel; - -#[path = "analytics/styles_tests.rs"] -mod terminal_styles; - -use super::*; -use crate::keymap::RuntimeKeymap; -use crossterm::event::KeyModifiers; -use pretty_assertions::assert_eq; -use ratatui::Terminal; -use ratatui::backend::TestBackend; - -fn press(view: &mut AnalyticsView, code: KeyCode) { - view.handle_key(KeyEvent::new(code, KeyModifiers::NONE)); -} - -fn screen(view: &mut AnalyticsView, width: u16, height: u16) -> String { - let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); - terminal - .draw(|frame| view.render(frame.area(), frame.buffer_mut())) - .unwrap(); - terminal.backend().to_string() -} - -#[test] -fn analytics_exact_fit_content_has_no_scroll_hint() { - let mut view = fixture::view(models::AccountKind::Enterprise); - view.section = Section::Chats; - screen(&mut view, /*width*/ 120, /*height*/ 60); - let chrome_height = 60 - view.viewport_height; - let content_height = view - .panel(Section::Chats, /*width*/ 116, /*chart_height*/ 4) - .lines - .len(); - let exact_height = (chrome_height + content_height) as u16; - - let exact = screen(&mut view, /*width*/ 120, exact_height); - assert!(!exact.contains("scroll")); - assert_eq!(view.viewport_height, content_height); -} - -#[test] -fn analytics_narrow_charts_and_small_terminals_keep_valid_cursors() { - let mut view = fixture::view(models::AccountKind::Consumer); - for section in ['2', '3', '4'] { - press(&mut view, KeyCode::Char(section)); - press(&mut view, KeyCode::Char('r')); - fixture::seed_reports(&mut view); - press(&mut view, KeyCode::Home); - for _ in 0..30 { - screen(&mut view, /*width*/ 28, /*height*/ 12); - press(&mut view, KeyCode::Right); - } - assert_eq!(view.sections[view.section].cursor, 29); - } - for _ in 0..2 { - for width in [1, 4, 32, 107, 108] { - screen(&mut view, width, /*height*/ 1); - } - } - let empty = ratatui::layout::Rect::default(); - view.render(empty, &mut ratatui::buffer::Buffer::empty(empty)); -} - -#[tokio::test] -async fn analytics_credits_grouping_preserves_selected_day_and_total() { - let server = test_support::server().await; - let (_home, _app_server, mut view) = client::tests::connected_view(&server, "business").await; - test_support::settle(&mut view).await; - press(&mut view, KeyCode::Char('2')); - test_support::settle(&mut view).await; - press(&mut view, KeyCode::Left); - let before = view.sections[Section::Credits] - .history - .ready() - .unwrap() - .data - .iter() - .map(|day| day.total) - .collect::>(); - for group in [2, 4, 5, 0] { - press(&mut view, KeyCode::Char('g')); - test_support::settle(&mut view).await; - assert_eq!( - ( - view.sections[Section::Credits].group, - view.sections[Section::Credits].cursor - ), - (group, 5) - ); - assert_eq!( - view.sections[Section::Credits] - .history - .ready() - .unwrap() - .data - .iter() - .map(|day| day.total) - .collect::>(), - before - ); - } -} - -#[tokio::test] -async fn analytics_loading_errors_and_empty_reports_stay_independent() { - let mut view = AnalyticsView::new(RuntimeKeymap::defaults().list); - let (send, receive) = tokio::sync::oneshot::channel(); - view.sections[Section::Usage].history = Load::start( - async move { receive.await.unwrap() }, - FrameRequester::test_dummy(), - ); - view.sections[Section::Credits].history = - Load::Error("Couldn't load credits. Press R to retry.".into()); - let mut empty = fixture::history(/*report*/ 2, /*range*/ 0, /*group*/ 2); - empty.data.clear(); - view.sections[Section::Activity].history = Load::Ready(empty); - let panels = [ - Section::Usage, - Section::Plugins, - Section::Credits, - Section::Activity, - ] - .into_iter() - .map(|section| { - view.panel(section, /*width*/ 54, /*chart_height*/ 2) - .lines - .into_iter() - .map(|line| line.to_string()) - .collect::>() - .join("\n") - }) - .collect::>() - .join("\n\n"); - insta::assert_snapshot!(panels); - // Refresh drops pending work before a stale result can populate the retained view. - view.refresh(); - tokio::task::yield_now().await; - assert!(send.is_closed()); - assert!(matches!( - view.sections[Section::Usage].history, - Load::Unavailable - )); -} - -#[test] -fn analytics_preserves_full_denominators_and_signed_small_credits() { - use crate::analytics::models::AccountAnalyticsDay; - use crate::analytics::models::AccountAnalyticsValue; - let mut view = fixture::view(models::AccountKind::Consumer); - let mut history = fixture::history(/*report*/ 0, /*range*/ 0, /*group*/ 3); - history.data = vec![AccountAnalyticsDay { - date: "2026-09-02".parse().unwrap(), - total: 100.0, - values: vec![AccountAnalyticsValue { - key: "goal".into(), - label: "Goals".into(), - value: 30.0, - }], - }]; - view.sections[Section::Usage].history = Load::Ready(history.clone()); - view.sections[Section::Usage].group = 3; - view.sections[Section::Usage].cursor = 6; - let task = view - .panel(Section::Usage, /*width*/ 54, /*chart_height*/ 2) - .lines; - assert!( - task.iter() - .any(|line| line.to_string().contains("Goals") && line.to_string().contains("30.0%")) - ); - assert!( - task.iter() - .any(|line| line.to_string() == "Sep 2 · 100 usage units") - ); - history.unit = crate::analytics::models::AccountAnalyticsUnit::Credits; - history.data[0].total = -0.000004; - history.data[0].values[0].value = -0.000004; - history.data[0].values[0].label = "CLI".into(); - view.sections[Section::Credits].history = Load::Ready(history); - view.sections[Section::Credits].cursor = 6; - let credits = view - .panel(Section::Credits, /*width*/ 54, /*chart_height*/ 2) - .lines; - insta::assert_snapshot!( - task.into_iter() - .chain(credits) - .map(|line| line.to_string()) - .collect::>() - .join("\n") - ); -} - -#[test] -fn analytics_credit_display_retains_integer_precision() { - assert_eq!( - [753.71, 411.12, 47.4, 0.0, 1_212.224, -0.004, -0.000004].map(data::credit_amount), - [ - "753.71", - "411.12", - "47.40", - "0.00", - "1,212.22", - "-0.004", - "-0.000004" - ] - .map(str::to_string) - ); - assert_eq!( - [0, -4, 999_999_999, 19_350_041_555, i64::MIN, i64::MAX].map(data::credits), - [ - "0.00", - "-0.000004", - "1,000.00", - "19,350.04", - "-9,223,372,036,854.78", - "9,223,372,036,854.78" - ] - .map(str::to_string) - ); - assert_eq!( - [ - 12_746.441206, - -1_000.125, - 999.999, - 0.0, - -0.000004, - 0.009, - 7.5 - ] - .map(data::amount), - [ - "12,746.44", - "-1,000.12", - "1,000", - "0", - "-0.000004", - "0.009", - "7.5" - ] - .map(str::to_string) - ); -} - -#[test] -fn analytics_dates_distinguish_zero_missing_and_exact_details() { - let mut view = fixture::view(models::AccountKind::Enterprise); - let mut history = fixture::history(/*report*/ 1, /*range*/ 0, /*group*/ 0); - history.data[1].total = 12_746.441206; - history.data[1].values[0].value = 12_746.441206; - history.data[1].values.truncate(/*len*/ 1); - history.data.remove(/*index*/ 2); - view.sections[Section::Credits].history = Load::Ready(history.clone()); - press(&mut view, KeyCode::Char('2')); - press(&mut view, KeyCode::Home); - let mut screens = Vec::new(); - for keys in [ - vec![], - vec![KeyCode::Right, KeyCode::Enter], - vec![KeyCode::Right], - ] { - for key in keys { - press(&mut view, key); - } - screens.push( - view.panel(Section::Credits, /*width*/ 54, /*chart_height*/ 3) - .lines - .into_iter() - .map(|line| line.to_string()) - .collect::>() - .join("\n"), - ); - } - assert!(screens[0].contains("No activity (0)")); - assert!(screens[1].contains("12746.441206 credits")); - assert!(screens[2].contains("Aug 29 · Not reported")); - for day in &mut history.data { - day.total = 0.0; - day.values.clear(); - } - view.sections[Section::Credits].history = Load::Ready(history.clone()); - screens.push( - view.panel(Section::Credits, /*width*/ 54, /*chart_height*/ 3) - .lines - .into_iter() - .map(|line| line.to_string()) - .collect::>() - .join("\n"), - ); - history.data.clear(); - view.sections[Section::Credits].history = Load::Ready(history); - screens.push( - view.panel(Section::Credits, /*width*/ 54, /*chart_height*/ 3) - .lines - .into_iter() - .map(|line| line.to_string()) - .collect::>() - .join("\n"), - ); - insta::assert_snapshot!(screens.join("\n\n")); -} - -#[test] -fn analytics_model_labels_and_tool_remainders_are_unambiguous() { - let mut view = fixture::view(models::AccountKind::Consumer); - view.model_names - .insert("GPT-5.6-Sol".into(), "Friendly model".into()); - let mut tools = fixture::history(/*report*/ 4, /*range*/ 0, /*group*/ 0); - for day in &mut tools.data { - day.values[1].label = "Other".into(); - } - view.sections[Section::Skills].history = Load::Ready(tools); - press(&mut view, KeyCode::Char('3')); - let overview = screen(&mut view, /*width*/ 140, /*height*/ 64); - assert!(overview.contains("Friendly model")); - assert!(overview.contains("Skills")); - press(&mut view, KeyCode::Char('5')); - press(&mut view, KeyCode::Enter); - let skills = screen(&mut view, /*width*/ 100, /*height*/ 32); - assert!(skills.contains("Other")); -} - -#[test] -fn analytics_maximized_refunds_leave_room_for_both_bands() { - let mut view = fixture::view(models::AccountKind::Enterprise); - let mut history = fixture::history(/*report*/ 1, /*range*/ 0, /*group*/ 0); - history.data[6].total = -0.000004; - history.data[6].values = vec![crate::analytics::models::AccountAnalyticsValue { - key: "CLI".into(), - label: "CLI".into(), - value: -0.000004, - }]; - view.sections[Section::Credits].history = Load::Ready(history); - press(&mut view, KeyCode::Char('2')); - let output = screen(&mut view, /*width*/ 100, /*height*/ 32); - assert!(output.contains("Sep 2 · -0.000004 credits")); - assert!( - output - .lines() - .any(|line| line.contains("● CLI") && line.contains("-0.000004")) - ); - insta::assert_snapshot!(output); -} - -#[test] -fn analytics_day_navigation_keeps_geometry_and_legend() { - let mut view = fixture::view(models::AccountKind::Enterprise); - let mut history = fixture::history(/*report*/ 1, /*range*/ 0, /*group*/ 0); - history.data[1].values.truncate(/*len*/ 1); - history.data[1].total = history.data[1].values[0].value; - history.data.remove(/*index*/ 2); - view.sections[Section::Credits].history = Load::Ready(history); - press(&mut view, KeyCode::Char('2')); - for width in [58, 160] { - let mut terminal = Terminal::new(TestBackend::new(width, /*height*/ 38)).unwrap(); - for expanded in [false, true] { - press(&mut view, KeyCode::Home); - if expanded { - press(&mut view, KeyCode::Enter); - } - let mut previous = None; - for _ in 0..7 { - terminal - .draw(|frame| view.render(frame.area(), frame.buffer_mut())) - .unwrap(); - let buffer = terminal.backend().buffer(); - let bars = buffer - .content - .iter() - .enumerate() - .filter(|(_, cell)| { - matches!(cell.symbol(), "█" | "▁" | "▂" | "▃" | "▄" | "▅" | "▆" | "▇") - }) - .map(|(index, cell)| (index, cell.clone())) - .collect::>(); - let output = terminal.backend().to_string(); - let marker_row = output.lines().position(|line| line.contains('▲')).unwrap(); - let table_row = output - .lines() - .position(|line| line.contains("Product")) - .unwrap(); - let geometry = (bars, marker_row, table_row); - if let Some(previous) = &previous { - assert_eq!(&geometry, previous); - } - previous = Some(geometry); - assert!(output.contains("● CLI") && output.contains("● Desktop app")); - press(&mut view, KeyCode::Right); - } - if expanded { - press(&mut view, KeyCode::Enter); - } - } - } -} - -#[test] -fn analytics_series_rank_by_range_and_keep_calendar_ticks_stable() { - let mut view = fixture::view(models::AccountKind::Consumer); - screen(&mut view, /*width*/ 100, /*height*/ 38); - press(&mut view, KeyCode::Char('r')); - let mut history = fixture::history(/*report*/ 0, /*range*/ 1, /*group*/ 2); - for day in &mut history.data { - day.values[3].value += 500.0; - day.total += 500.0; - } - view.sections[Section::Usage].history = Load::Ready(history.clone()); - screen(&mut view, /*width*/ 100, /*height*/ 38); - let legend = view - .history_lines(Section::Usage, /*width*/ 96, /*height*/ 10) - .lines - .into_iter() - .filter(|line| line.spans.first().is_some_and(|span| span.content == "● ")) - .take(/*n*/ 3) - .map(|line| (line.spans[1].content.to_string(), line.spans[0].style.fg)) - .collect::>(); - assert_eq!( - legend, - ["Other", "GPT-5.6-Sol", "GPT-5.6-Terra"] - .into_iter() - .zip(styles::series_colors()) - .map(|(label, color)| (label.to_string(), Some(color))) - .collect::>() - ); - let series = render::categories(&history); - history.data[8].total = 0.4; - for value in &mut history.data[8].values { - value.value = 0.1; - } - let days = history - .data - .iter() - .map(|day| (day.date, Some(day))) - .collect::>(); - let mut ticks = None; - for cursor in [0, 7, 8, 25, 29] { - let chart = plot::chart( - &days, - &series, - cursor, - /*width*/ 96, - /*height*/ 10, - history.unit, - ); - let labels = chart.lines.last().unwrap().to_string(); - if let Some(ticks) = &ticks { - assert_eq!(&labels, ticks); - } - ticks = Some(labels); - assert_eq!( - chart - .lines - .iter() - .filter(|line| line.to_string().contains('▲')) - .count(), - 1 - ); - } - let crowded = plot::chart( - &days, - &series, - /*cursor*/ 8, - /*width*/ 54, - /*height*/ 10, - history.unit, - ) - .lines - .iter() - .map(ToString::to_string) - .collect::>() - .join("\n"); - assert!(crowded.contains('┊')); - assert!(crowded.contains("0.4")); - insta::assert_snapshot!(crowded); -} - -#[test] -fn analytics_usage_ranks_its_own_models_after_turns_load() { - let mut view = fixture::view(models::AccountKind::Consumer); - screen(&mut view, /*width*/ 100, /*height*/ 38); - press(&mut view, KeyCode::Char('g')); - press(&mut view, KeyCode::Down); - press(&mut view, KeyCode::Enter); - let mut history = fixture::history(/*report*/ 0, /*range*/ 0, /*group*/ 2); - for day in &mut history.data { - for label in ["Model E", "Model F"] { - day.values - .push(crate::analytics::models::AccountAnalyticsValue { - key: label.into(), - label: label.into(), - value: 0.0, - }); - } - for value in &mut day.values { - value.key = format!("remote-{}", value.key); - value.label = format!("Remote {}", value.label); - } - } - history.data[6].total = 100.0; - for (value, amount) in history.data[6] - .values - .iter_mut() - .zip([91.1, 0.0, 6.8, 2.1, 0.0, 0.0]) - { - value.value = amount; - } - view.sections[Section::Usage].history = Load::Ready(history); - - for _ in 0..7 { - screen(&mut view, /*width*/ 100, /*height*/ 38); - let expected = if view.sections[Section::Usage].cursor == 6 { - [ - ("Remote GPT-5.6-Sol", 0), - ("Remote GPT-5.5", 2), - ("Remote Other", 3), - ] - } else { - [ - ("Remote GPT-5.6-Sol", 0), - ("Remote GPT-5.6-Terra", 1), - ("Remote GPT-5.5", 2), - ] - } - .into_iter() - .map(|(label, color)| (label.to_string(), Some(styles::series_colors()[color]))) - .collect::>(); - let legend = view - .history_lines(Section::Usage, /*width*/ 96, /*height*/ 10) - .lines - .into_iter() - .filter(|line| line.spans.first().is_some_and(|span| span.content == "● ")) - .take(/*n*/ 3) - .map(|line| (line.spans[1].content.to_string(), line.spans[0].style.fg)) - .collect::>(); - assert_eq!(legend, expected); - press(&mut view, KeyCode::Left); - } -} - -#[test] -fn analytics_empty_turns_keep_geometry_and_disable_details() { - let mut view = fixture::view(models::AccountKind::Consumer); - let mut history = fixture::history(/*report*/ 2, /*range*/ 0, /*group*/ 2); - history.data[5].total = 0.0; - for value in &mut history.data[5].values { - value.value = 0.0; - } - history.data.remove(/*index*/ 6); - view.sections[Section::Activity].history = Load::Ready(history); - press(&mut view, KeyCode::Char('3')); - for width in [58, 100] { - view.sections[Section::Activity].cursor = 4; - let populated = screen(&mut view, width, /*height*/ 38); - assert!(populated.contains("reported messages")); - assert!(populated.contains("details")); - let marker_row = populated.lines().position(|line| line.contains('▲')); - for cursor in [5, 6] { - view.sections[Section::Activity].cursor = cursor; - let empty = screen(&mut view, width, /*height*/ 38); - assert!(empty.contains(if cursor == 5 { - "No messages reported for" - } else { - "Data not reported for" - })); - assert!(!empty.contains("details")); - assert!(!empty.contains('●')); - assert_eq!( - empty.lines().position(|line| line.contains('▲')), - marker_row - ); - press(&mut view, KeyCode::Enter); - assert_eq!(view.sections[Section::Activity].detail, None); - } - view.sections[Section::Activity].cursor = 4; - press(&mut view, KeyCode::Enter); - assert_eq!(view.sections[Section::Activity].detail, Some(4)); - let expanded = screen(&mut view, width, /*height*/ 38); - let marker_row = expanded.lines().position(|line| line.contains('▲')); - press(&mut view, KeyCode::Right); - let empty = screen(&mut view, width, /*height*/ 38); - assert_eq!( - empty.lines().position(|line| line.contains('▲')), - marker_row - ); - let details = view.sections[Section::Activity].detail; - press(&mut view, KeyCode::Enter); - assert_eq!(view.sections[Section::Activity].detail, details); - view.sections[Section::Activity].detail = None; - } -} - -#[path = "analytics/chat_panel_tests.rs"] -mod chats_table; - -#[test] -fn analytics_details_reflow_and_keep_focus() { - let mut view = fixture::view(models::AccountKind::Enterprise); - view.chats = Load::Ready(fixture::chats()); - press(&mut view, KeyCode::Char('6')); - press(&mut view, KeyCode::Enter); - screen(&mut view, /*width*/ 120, /*height*/ 42); - view.follow_selection = true; - let narrow = screen(&mut view, /*width*/ 58, /*height*/ 20); - assert!(narrow.contains("Q3 planning analysis") && narrow.contains("GPT-5.6-Sol")); - let before = ( - view.section, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections.0.each_ref().map(|state| state.detail), - ); - press(&mut view, KeyCode::PageDown); - screen(&mut view, /*width*/ 58, /*height*/ 20); - assert_eq!( - ( - view.section, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections.0.each_ref().map(|state| state.detail) - ), - before - ); - press(&mut view, KeyCode::Tab); - press(&mut view, KeyCode::Char('6')); - assert_eq!( - ( - view.section, - view.sections.0.each_ref().map(|state| state.cursor), - view.sections.0.each_ref().map(|state| state.detail) - ), - before - ); - press(&mut view, KeyCode::Esc); - assert_eq!( - ( - view.is_done, - view.sections.0.each_ref().map(|state| state.detail) - ), - (false, [None; 8]) - ); - press(&mut view, KeyCode::Esc); - assert!(view.is_done); -} - -#[path = "analytics/dashboard_tests.rs"] -mod dashboard; - -#[path = "analytics/mouse_tests.rs"] -mod mouse; diff --git a/codex-rs/tui/src/app/agents_overview_usage.rs b/codex-rs/tui/src/app/agents_overview_usage.rs deleted file mode 100644 index 47a4868d..00000000 --- a/codex-rs/tui/src/app/agents_overview_usage.rs +++ /dev/null @@ -1,205 +0,0 @@ -//! Demand-driven dashboard usage. Only the selected task is fetched on a one-minute -//! refresh cadence, including after failures. Account changes and reconnects invalidate -//! pending billing results and disabled capability state. - -use super::App; -use super::agents_overview::AGENTS_OVERVIEW_VIEW_ID; -use super::background_requests::THREAD_USAGE_FETCH_TIMEOUT; -use super::background_requests::fetch_thread_usage; -use crate::app_event::AppEvent; -use crate::app_server_session::AppServerSession; -use crate::chatwidget::ThreadUsageOutcome; -use crate::status::format_credit_micros; -use crate::status::format_estimated_usd_micros; -use crate::status::format_tokens_compact; -use crate::status::thread_cost_micros; -use crate::tui::FrameRequester; -use codex_app_server_protocol::ThreadUsage; -use codex_app_server_protocol::ThreadUsageBreakdownGroup; -use codex_app_server_protocol::TokenUsageBreakdown; -use codex_protocol::ThreadId; -use codex_protocol::account::PlanType; -use ratatui::style::Stylize; -use ratatui::text::Line; -use std::time::Duration; -use std::time::Instant; -use uuid::Uuid; - -const REFRESH_INTERVAL: Duration = Duration::from_secs(/*secs*/ 60); - -#[derive(Default)] -pub(super) struct AgentsOverviewUsage { - pub(super) tokens: Option, - pub(super) estimate: Option, - fetched_at: Option, -} - -impl App { - pub(super) fn refresh_agents_overview_usage( - &mut self, - app_server: &AppServerSession, - frame_requester: FrameRequester, - ) { - if self.reconnect.offline - || self.agents_overview.usage_disabled - || self.agents_overview.pending_usage.is_some() - || !self.chat_widget.has_codex_backend_auth() - || !matches!( - self.chat_widget.current_plan_type(), - Some( - PlanType::Ent26 - | PlanType::Business - | PlanType::EnterpriseCbpUsageBased - | PlanType::EnterpriseCbpAutomation - ) - ) - { - return; - } - let Some(thread_id) = self - .chat_widget - .selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID) - .and_then(|index| self.agents_overview.visible_thread_ids.get(index)) - .copied() - else { - return; - }; - if let Some(age) = self - .agents_overview - .usage - .get(&thread_id) - .and_then(|usage| usage.fetched_at) - .map(|fetched| fetched.elapsed()) - && age < REFRESH_INTERVAL - { - frame_requester.schedule_frame_in(REFRESH_INTERVAL - age); - return; - } - let request_id = Uuid::new_v4(); - self.agents_overview.pending_usage = Some((thread_id, request_id)); - 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( - THREAD_USAGE_FETCH_TIMEOUT, - fetch_thread_usage(request_handle, thread_id), - ) - .await - .map_err(|_| "dashboard usage request timed out".to_string()) - .and_then(|result| result.map_err(|error| error.to_string())); - app_event_tx.send(AppEvent::AgentsOverviewUsageLoaded { - thread_id, - request_id, - result, - }); - }); - } - - pub(super) fn finish_agents_overview_usage( - &mut self, - thread_id: ThreadId, - request_id: Uuid, - result: Result, - ) { - if self.agents_overview.pending_usage != Some((thread_id, request_id)) { - return; - } - self.agents_overview.pending_usage = None; - if self.agents_overview.threads.contains_key(&thread_id) - || self.agents_overview.search_matches.contains_key(&thread_id) - { - let usage = self.agents_overview.usage.entry(thread_id).or_default(); - usage.fetched_at = Some(Instant::now()); - match result { - Ok(ThreadUsageOutcome::Available(mut estimate)) - if estimate.thread_id == thread_id.to_string() => - { - if let Some(previous) = &usage.estimate { - let zero_credits = estimate.estimated_usage_credits_micros == 0 - && previous.estimated_usage_credits_micros > 0; - let zero_cost = estimate.estimated_usage_usd_micros == Some(0) - && previous - .estimated_usage_usd_micros - .is_some_and(|cost| cost > 0); - if zero_credits { - estimate.estimated_usage_credits_micros = - previous.estimated_usage_credits_micros; - } - if zero_cost { - estimate.estimated_usage_usd_micros = - previous.estimated_usage_usd_micros; - } - if (zero_credits || zero_cost) && estimate.groups.is_empty() { - estimate.groups.clone_from(&previous.groups); - } - } - usage.estimate = Some(estimate); - } - Ok(ThreadUsageOutcome::Disabled) => { - self.agents_overview.usage_disabled = true; - for usage in self.agents_overview.usage.values_mut() { - usage.estimate = None; - } - } - Ok(ThreadUsageOutcome::Available(_)) | Err(_) => {} - } - } - self.repaint_agents_overview(); - } -} - -pub(super) fn usage_lines( - usage: &AgentsOverviewUsage, - plan_type: Option, -) -> Vec> { - let sum = |count: fn(&ThreadUsageBreakdownGroup) -> Option| { - let groups = &usage.estimate.as_ref()?.groups; - if groups.is_empty() { - return None; - } - groups.iter().try_fold(/*init*/ 0_i64, |total, group| { - count(group) - .filter(|tokens| *tokens >= 0) - .map(|tokens| total.saturating_add(tokens)) - }) - }; - let input = usage - .tokens - .as_ref() - .map(|tokens| tokens.input_tokens) - .or_else(|| sum(|group| group.input_tokens)); - let output = usage - .tokens - .as_ref() - .map(|tokens| tokens.output_tokens) - .or_else(|| sum(|group| group.output_tokens)); - let mut lines = Vec::new(); - let mut tokens = Vec::new(); - if let Some(input) = input { - tokens.push(format!("{} in", format_tokens_compact(input))); - } - if let Some(output) = output { - tokens.push(format!("{} out", format_tokens_compact(output))); - } - if !tokens.is_empty() { - lines.push(vec!["Tokens: ".dim(), tokens.join(" · ").into()].into()); - } - if let Some(estimate) = &usage.estimate { - let mut values = Vec::new(); - if plan_type != Some(PlanType::Ent26) && estimate.estimated_usage_credits_micros >= 0 { - values.push(format!( - "{} credits", - format_credit_micros(estimate.estimated_usage_credits_micros) - )); - } - if let Some(cost) = - thread_cost_micros(estimate, plan_type).and_then(format_estimated_usd_micros) - { - values.push(cost); - } - if !values.is_empty() { - lines.push(vec!["Est. usage: ".dim(), values.join(" · ").into()].into()); - } - } - lines -} diff --git a/codex-rs/tui/src/app/agents_overview_usage_tests.rs b/codex-rs/tui/src/app/agents_overview_usage_tests.rs deleted file mode 100644 index 35fb2d47..00000000 --- a/codex-rs/tui/src/app/agents_overview_usage_tests.rs +++ /dev/null @@ -1,281 +0,0 @@ -use super::*; -use crate::app::agents_overview_usage::AgentsOverviewUsage; -use crate::app::agents_overview_usage::usage_lines; -use crate::chatwidget::ThreadUsageOutcome; -use codex_app_server_protocol::AccountUpdatedNotification; -use codex_app_server_protocol::ThreadTokenUsage; -use codex_app_server_protocol::ThreadTokenUsageUpdatedNotification; -use codex_app_server_protocol::ThreadUsage; -use codex_app_server_protocol::TokenUsageBreakdown; -use codex_protocol::account::PlanType; -use pretty_assertions::assert_eq; - -#[tokio::test] -async fn selected_usage_is_cached_and_account_changes_discard_old_results() -> Result<()> { - let mut app = make_test_app_with_chat().await; - let app_server = crate::start_embedded_app_server_for_picker(&app.config).await?; - app.chat_widget.update_account_state( - /*status_account_display*/ None, - Some(PlanType::Business), - /*has_chatgpt_account*/ false, - /*has_codex_backend_auth*/ true, - ); - let selected = ThreadId::from_u128(/*value*/ 1); - let other = ThreadId::new(); - let threads = [(selected, "Review parser"), (other, "Other task")].map(|(id, name)| { - overview_thread(id, /*parent_thread_id*/ None, name, ThreadStatus::Idle) - }); - app.agents_overview.threads = threads - .iter() - .cloned() - .map(|thread| (ThreadId::from_string(&thread.id).unwrap(), Some(thread))) - .collect(); - let view = app.agents_overview_view(threads.to_vec(), Some(selected)); - app.agents_overview.visible_thread_ids = view.thread_ids(); - app.chat_widget.show_bottom_pane_view(Box::new(view)); - let thread_id = selected; - let request_id = Uuid::new_v4(); - let result = ThreadUsageOutcome::Available(serde_json::from_value(serde_json::json!({ - "threadId": selected.to_string(), - "estimatedUsageCreditsMicros": 3_400_000, - "estimatedUsageUsdMicros": 140_000, - "groups": [{"estimatedUsageCreditsMicros": 3_400_000, "inputTokens": 12_000, "outputTokens": 3_000}] - })).unwrap()); - let tui = crate::tui::test_support::make_test_tui()?; - app.agents_overview.pending_usage = Some((thread_id, request_id)); - app.refresh_agents_overview_usage(&app_server, tui.frame_requester()); - assert_eq!( - app.agents_overview.pending_usage, - Some((thread_id, request_id)) - ); - app.finish_agents_overview_usage(thread_id, request_id, Ok(result.clone())); - app.refresh_agents_overview_usage(&app_server, tui.frame_requester()); - assert_eq!(app.agents_overview.pending_usage, None); - - let ThreadUsageOutcome::Available(mut expected) = result.clone() else { - panic!("expected usage estimate") - }; - for (credits, cost, expected_credits) in [(0, 200_000, 3_400_000), (5_000_000, 0, 5_000_000)] { - let mut settlement = expected.clone(); - settlement.estimated_usage_credits_micros = credits; - settlement.estimated_usage_usd_micros = Some(cost); - settlement.groups.clear(); - expected.estimated_usage_credits_micros = expected_credits; - expected.estimated_usage_usd_micros = Some(200_000); - app.agents_overview.pending_usage = Some((thread_id, request_id)); - app.finish_agents_overview_usage( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(settlement)), - ); - assert_eq!( - app.agents_overview.usage[&selected].estimate, - Some(expected.clone()) - ); - } - - let tokens = TokenUsageBreakdown { - total_tokens: 17_000, - input_tokens: 13_000, - cached_input_tokens: 1_000, - cache_write_input_tokens: 0, - output_tokens: 4_000, - reasoning_output_tokens: 0, - }; - app.agents_overview.threads.remove(&selected); - app.agents_overview.request_id = Some(request_id); - app.track_agents_overview_notification(&ServerNotification::ThreadTokenUsageUpdated( - ThreadTokenUsageUpdatedNotification { - thread_id: selected.to_string(), - turn_id: "turn".into(), - token_usage: ThreadTokenUsage { - total: tokens.clone(), - last: tokens.clone(), - model_context_window: None, - }, - }, - )); - app.apply_agents_overview_thread_refresh( - &app_server, - request_id, - Ok(AgentsOverviewThreadRefresh { - cleared_unread: Vec::new(), - threads: HashMap::from([(selected, Some((threads[0].clone(), false, None)))]), - last_messages: HashMap::new(), - recent_seed_complete: true, - discovery: None, - pinned_thread_ids: None, - }), - ); - assert_eq!( - app.agents_overview.usage[&selected].tokens, - Some(tokens.clone()) - ); - assert!( - render_bottom_popup(&app.chat_widget, /*width*/ 96).contains("Tokens: 13K in · 4K out") - ); - let mut view = app.agents_overview_view(threads.to_vec(), Some(selected)); - let row = view - .rows - .iter_mut() - .find(|row| row.thread_id == selected) - .unwrap(); - row.group = AgentsOverviewGroup::NeedsYou; - row.details.lines = vec![ - Line::default(), - "Needs attention".into(), - "Which dependency version should I use?".into(), - "Open task to review.".into(), - ]; - app.chat_widget.show_bottom_pane_view(Box::new(view)); - let project = test_path_display("/tmp/project"); - let group = format!( - "/tmp/project 2{}", - " ".repeat(project.len().saturating_sub("/tmp/project".len())) - ); - insta::assert_snapshot!( - "agents_overview_usage", - render_bottom_popup(&app.chat_widget, /*width*/ 96) - .replace(&format!("{project} 2"), &group) - .replace(&project, "/tmp/project") - .replace("fwd del", "del") - ); - for notification in [ - ServerNotification::ThreadReverted(codex_app_server_protocol::ThreadRevertedNotification { - thread_id: selected.to_string(), - }), - ServerNotification::ThreadClosed(ThreadClosedNotification { - thread_id: selected.to_string(), - }), - ] { - app.agents_overview.usage.get_mut(&selected).unwrap().tokens = Some(tokens.clone()); - app.track_agents_overview_notification(¬ification); - assert_eq!(app.agents_overview.usage[&selected].tokens, None); - } - assert_eq!( - app.agents_overview.usage[&selected].estimate, - Some(expected.clone()) - ); - let other_usage = app.agents_overview.usage.entry(other).or_default(); - other_usage.estimate = Some(expected.clone()); - other_usage.tokens = Some(tokens.clone()); - app.agents_overview.pending_usage = Some((thread_id, request_id)); - app.finish_agents_overview_usage(thread_id, request_id, Ok(ThreadUsageOutcome::Disabled)); - assert!( - app.agents_overview - .usage - .values() - .all(|usage| usage.estimate.is_none()) - ); - assert_eq!( - app.agents_overview.usage[&other].tokens, - Some(tokens.clone()) - ); - // A different selection must not retry an unavailable account-wide capability. - let view = app.agents_overview_view(threads.to_vec(), Some(other)); - app.agents_overview.visible_thread_ids = view.thread_ids(); - app.chat_widget.show_bottom_pane_view(Box::new(view)); - app.refresh_agents_overview_usage(&app_server, tui.frame_requester()); - assert!(app.agents_overview.usage_disabled); - assert_eq!(app.agents_overview.pending_usage, None); - for event in [ - AppServerEvent::Lagged { skipped: 1 }, - AppServerEvent::ServerNotification(Box::new(ServerNotification::AccountUpdated( - AccountUpdatedNotification { - auth_mode: None, - plan_type: None, - }, - ))), - ] { - app.agents_overview - .usage - .entry(selected) - .or_default() - .tokens = Some(tokens.clone()); - app.agents_overview.pending_usage = Some((thread_id, request_id)); - app.agents_overview.usage_disabled = true; - app.handle_app_server_event(&app_server, event).await; - app.finish_agents_overview_usage(thread_id, request_id, Ok(result.clone())); - assert!(app.agents_overview.usage.is_empty()); - assert_eq!(app.agents_overview.pending_usage, None); - assert!(!app.agents_overview.usage_disabled); - } - app.chat_widget.update_account_state( - /*status_account_display*/ None, - Some(PlanType::Ent26), - /*has_chatgpt_account*/ false, - /*has_codex_backend_auth*/ true, - ); - let view = app.agents_overview_view(threads.to_vec(), Some(selected)); - app.agents_overview.visible_thread_ids = view.thread_ids(); - app.chat_widget.show_bottom_pane_view(Box::new(view)); - app.refresh_agents_overview_usage(&app_server, tui.frame_requester()); - let (thread_id, request_id) = app - .agents_overview - .pending_usage - .expect("request ENT26 usage"); - assert_eq!(thread_id, selected); - let mut native_usage = expected.clone(); - native_usage.estimated_usage_credits_micros = 0; - native_usage.estimated_usage_usd_micros = Some(0); - native_usage.native_usage_usd_micros = Some(750_000); - app.finish_agents_overview_usage( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(native_usage)), - ); - let view = app.agents_overview_view(threads.to_vec(), Some(selected)); - let rendered = view - .rows - .iter() - .find(|row| row.thread_id == selected) - .unwrap() - .details - .usage_lines - .iter() - .map(ToString::to_string) - .collect::>() - .join("\n"); - insta::assert_snapshot!(rendered, @" - Tokens: 12K in · 3K out - Est. usage: ~$0.75 - "); - - app.agents_overview.usage_disabled = true; - app.agents_overview.pending_usage = Some((thread_id, request_id)); - app.app_server_target = AppServerTarget::LocalDaemon { - allow_embedded_fallback: true, - endpoint: crate::RemoteAppServerEndpoint::UnixSocket { - socket_path: test_path_buf("/tmp/test.sock").abs(), - }, - }; - assert!(app.begin_reconnect()); - app.finish_agents_overview_usage( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(expected)), - ); - assert!(app.agents_overview.usage.is_empty()); - assert_eq!(app.agents_overview.pending_usage, None); - assert!(!app.agents_overview.usage_disabled); - Ok(()) -} - -#[test] -fn incomplete_billing_groups_do_not_display_partial_token_totals() { - let estimate: ThreadUsage = serde_json::from_value(serde_json::json!({ - "threadId": "thread", "estimatedUsageCreditsMicros": 0, "estimatedUsageUsdMicros": null, - "groups": [ - {"estimatedUsageCreditsMicros": 0, "inputTokens": 100, "outputTokens": 10}, - {"estimatedUsageCreditsMicros": 0, "inputTokens": null, "outputTokens": 20} - ] - })) - .unwrap(); - let mut usage = AgentsOverviewUsage::default(); - usage.estimate = Some(estimate); - let text = usage_lines(&usage, Some(PlanType::Business)) - .into_iter() - .map(|line| line.to_string()) - .collect::>(); - assert_eq!(text, vec!["Tokens: 30 out", "Est. usage: 0 credits"]); -} diff --git a/codex-rs/tui/src/app/backend_banner_fallback.rs b/codex-rs/tui/src/app/backend_banner_fallback.rs deleted file mode 100644 index eef5bb03..00000000 --- a/codex-rs/tui/src/app/backend_banner_fallback.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! Apply backend-authorized fallback and task-local Reserve settings without saving defaults. - -use super::App; -use crate::app_event::AppEvent; -use crate::app_server_session::AppServerSession; -use crate::chatwidget::AutomaticModelSwitchReason; -use crate::model_catalog::LUNA_RESERVE_MODEL; -use crate::model_catalog::model_display_name; -use crate::service_tier_resolution; -use codex_app_server_protocol::ThreadSettingsUpdateParams; -use codex_protocol::ThreadId; -use codex_protocol::config_types::ModeKind; -use codex_protocol::openai_models::ReasoningEffort; - -impl App { - pub(super) async fn update_luna_reserve_reasoning( - &mut self, - app_server: &mut AppServerSession, - thread_id: ThreadId, - effort: Option, - ) { - // A picker left open during recovery or a task switch must not affect the new model. - if self.active_thread_id != Some(thread_id) - || self.chat_widget.thread_id() != Some(thread_id) - || self.chat_widget.current_model() != LUNA_RESERVE_MODEL - { - return; - } - self.app_event_tx.send(AppEvent::FollowTranscript); - let mut mode = self.chat_widget.effective_collaboration_mode(); - mode.settings.reasoning_effort = effort.clone(); - let params = ThreadSettingsUpdateParams { - thread_id: thread_id.to_string(), - effort: effort.clone(), - collaboration_mode: Some(mode.clone()), - ..ThreadSettingsUpdateParams::default() - }; - if self.send_thread_settings_update(app_server, params).await { - self.chat_widget.set_reasoning_effort(effort.clone()); - if mode.mode == ModeKind::Plan { - self.chat_widget.set_plan_mode_reasoning_effort(effort); - } - } - } - - pub(super) async fn apply_backend_banner_fallback( - &mut self, - app_server: &mut AppServerSession, - ) { - // Reattached tasks must wait for the read that supersedes the latest hard stop. - if self.rate_limit_refresh_state.has_pending_recovery() { - return; - } - let Some(thread_id) = self.active_thread_id else { - return; - }; - if Some(thread_id) != self.chat_widget.thread_id() { - return; - } - let Some(switch) = self.chat_widget.backend_banner_fallback() else { - return; - }; - let target = switch.model; - let entering_reserve = target.model == crate::model_catalog::LUNA_RESERVE_MODEL; - if entering_reserve && !self.chat_widget.prepare_luna_reserve_return() { - self.chat_widget.show_unavailable_reserve_recovery(); - return; - } - let effort = switch - .effort - .filter(|effort| { - target - .supported_reasoning_efforts - .iter() - .any(|option| option.effort == *effort) - }) - .unwrap_or(target.default_reasoning_effort); - let mut mode = self.chat_widget.effective_collaboration_mode(); - mode.settings.model = target.model.clone(); - mode.settings.reasoning_effort = Some(effort.clone()); - // Automatic recovery must not apply the permission defaults used by manual model selection. - let params = ThreadSettingsUpdateParams { - thread_id: thread_id.to_string(), - model: Some(target.model.clone()), - effort: Some(effort.clone()), - collaboration_mode: Some(mode.clone()), - service_tier: service_tier_resolution::service_tier_update_for_core( - self.chat_widget.config_ref(), - &self.local_settings.notices, - &target.model, - &self.model_catalog.try_list_models().unwrap_or_default(), - ), - ..ThreadSettingsUpdateParams::default() - }; - // Older remote servers can decline this method. Keep the existing recovery UI in that - // case or on failure, rather than changing local selection before the task accepts it. - // Event dispatch awaits this operation; a queued manual model selection runs afterward. - if self.send_thread_settings_update(app_server, params).await { - self.chat_widget.finish_backend_banner_fallback(mode); - self.sync_active_thread_service_tier_to_cached_session() - .await; - let (prefix, suffix) = match switch.reason { - AutomaticModelSwitchReason::UsageLimit => { - ("Automatically switched to", " due to usage limits.") - } - AutomaticModelSwitchReason::UsageRecovered => ( - "Automatically switched back to", - " because ordinary usage is available again.", - ), - }; - let mut message = format!("{prefix} {}", model_display_name(&target.model)); - if let Some(label) = Self::reasoning_label_for(&target.model, Some(&effort)) { - message.push(' '); - message.push_str(&label); - } - message.push_str(suffix); - self.chat_widget.add_info_message(message, /*hint*/ None); - } else if entering_reserve { - self.chat_widget.show_unavailable_reserve_recovery(); - } - } -} diff --git a/codex-rs/tui/src/app/rate_limit_refresh.rs b/codex-rs/tui/src/app/rate_limit_refresh.rs deleted file mode 100644 index 29a478a0..00000000 --- a/codex-rs/tui/src/app/rate_limit_refresh.rs +++ /dev/null @@ -1,131 +0,0 @@ -//! Orders full usage reads and coalesces recovery refreshes within an account/limit generation. -//! Periodic reads share that ordering and wait while another periodic read or recovery is pending. - -use crate::app_event::RateLimitRefreshOrigin; -use std::time::Duration; -use std::time::Instant; - -#[derive(Default)] -pub(super) struct RateLimitRefreshState { - next_id: u64, - applied_id: u64, - recovery: Option, - periodic: Option<(u64, u64)>, - last_requested_at: Option, -} - -struct PendingRecovery { - request: (u64, u64), - origin: RateLimitRefreshOrigin, -} - -#[derive(Debug, PartialEq, Eq)] -pub(super) enum RateLimitRefreshOutcome { - Apply, - Ignore, - RefreshRecovery, -} - -#[derive(PartialEq, Eq)] -pub(super) enum RateLimitReadStatus { - Succeeded, - Failed, -} - -impl RateLimitRefreshState { - pub(super) fn poll_deadline(&self, interval: Duration) -> Option { - if self.periodic.is_some() || self.recovery.is_some() { - return None; - } - Some( - self.last_requested_at - .map(|last| last + interval) - .unwrap_or_else(Instant::now), - ) - } - - pub(super) fn has_pending_recovery(&self) -> bool { - self.recovery.is_some() - } - - pub(super) fn start( - &mut self, - origin: RateLimitRefreshOrigin, - generation: &mut u64, - ) -> Option<(u64, u64)> { - if origin == RateLimitRefreshOrigin::Periodic - && (self.periodic.is_some() || self.recovery.is_some()) - { - return None; - } - if matches!(origin, RateLimitRefreshOrigin::Recovery) { - // A new hard error supersedes a post-reset read that started before the error. - if self - .recovery - .as_ref() - .is_some_and(|pending| pending.origin == RateLimitRefreshOrigin::Recovery) - { - return None; - } - // A hard error invalidates even an older read without a preceding rolling notification. - *generation = generation.wrapping_add(1); - } - self.next_id = self.next_id.wrapping_add(1); - let request = (self.next_id, *generation); - self.last_requested_at = Some(Instant::now()); - if origin == RateLimitRefreshOrigin::Periodic { - self.periodic = Some(request); - } - // The post-reset read takes over the hold from the invalidated recovery request. - if matches!( - origin, - RateLimitRefreshOrigin::Recovery | RateLimitRefreshOrigin::ResetConsume { .. } - ) { - self.recovery = Some(PendingRecovery { request, origin }); - } - Some(request) - } - - // Account changes and successful resets invalidate the need as well as the old response. - pub(super) fn invalidate_recovery(&mut self) { - self.recovery = None; - self.periodic = None; - self.last_requested_at = None; - } - - pub(super) fn finish( - &mut self, - request_id: u64, - generation: u64, - current_generation: u64, - status: RateLimitReadStatus, - ) -> RateLimitRefreshOutcome { - if self.periodic == Some((request_id, generation)) { - self.periodic = None; - } - if generation == current_generation && request_id == self.next_id { - // Completion starts the next wait, including after failures/timeouts, so errors - // cannot create a tight retry loop while the account is nearly exhausted. - self.last_requested_at = Some(Instant::now()); - } - if self - .recovery - .as_ref() - .is_some_and(|pending| pending.request == (request_id, generation)) - { - self.recovery = None; - // A rolling hard stop can arrive after the error, without another error notification. - if generation != current_generation { - return RateLimitRefreshOutcome::RefreshRecovery; - } - } - if generation != current_generation - || request_id < self.applied_id - || status == RateLimitReadStatus::Failed - { - return RateLimitRefreshOutcome::Ignore; - } - self.applied_id = request_id; - RateLimitRefreshOutcome::Apply - } -} diff --git a/codex-rs/tui/src/app/tests/backend_banner_fallback_tests.rs b/codex-rs/tui/src/app/tests/backend_banner_fallback_tests.rs deleted file mode 100644 index f6b6949f..00000000 --- a/codex-rs/tui/src/app/tests/backend_banner_fallback_tests.rs +++ /dev/null @@ -1,505 +0,0 @@ -use super::*; -use crate::chatwidget::UserMessage; -use crate::chatwidget::tests::helpers::normalize_snapshot_paths; -use crate::chatwidget::tests::helpers::set_fast_mode_test_catalog_for_models; -use codex_app_server_protocol::GetAccountRateLimitsResponse; -use codex_app_server_protocol::ThreadSettingsUpdateParams; -use pretty_assertions::assert_eq; -use serde_json::json; - -pub(super) fn fallback_response() -> GetAccountRateLimitsResponse { - serde_json::from_value(json!({ - "accountId": "workspace-a", "rateLimits": {}, - "rateLimitUpsell": { - "banner_type": "model_recovery", "model_slug": "gpt-5.5", - "blocked_model_slug": "gpt-5.5", - "fallback_model_slugs": ["unavailable-model", "gpt-5.5", "gpt-5.6-terra"], - "title": "Selected model usage exhausted", - "description": "Add credits to use this model again.", - "presentation": "dismissible", - "ctas": [{"action": "view_usage", "label": "View usage"}] - } - })) - .unwrap() -} - -fn configure_fallback_model(app: &mut App) { - set_chatgpt_auth(&mut app.chat_widget); - set_fast_mode_test_catalog_for_models(&mut app.chat_widget, "gpt-5.5", "gpt-5.6-terra"); - app.model_catalog = app.chat_widget.model_catalog(); - app.chat_widget.set_model("gpt-5.5"); -} - -pub(super) async fn start_fallback_thread( - app: &mut App, -) -> Result { - let (mut server, requests, proxy) = session_lifecycle_requests::start_recording_app_server( - &app.config, - /*blocked_thread_list*/ None, - /*failed_thread_name*/ None, - ) - .await?; - let started = server.start_thread(&app.config).await?; - app.enqueue_primary_thread_session(started.session, started.turns) - .await?; - configure_fallback_model(app); - Ok((server, requests, proxy)) -} - -#[tokio::test] -async fn backend_banner_fallback_updates_task_settings_and_keeps_notice() -> Result<()> { - for mode_kind in [ModeKind::Default, ModeKind::Plan] { - let (mut app, mut events, mut ops) = make_test_app_with_channels().await; - let (mut server, requests, proxy) = start_fallback_thread(&mut app).await?; - let thread_id = app.active_thread_id.expect("active fallback thread"); - app.chat_widget - .set_reasoning_effort(Some(ReasoningEffortConfig::Medium)); - if mode_kind == ModeKind::Plan { - app.chat_widget - .handle_key_event(KeyEvent::from(KeyCode::BackTab)); - app.chat_widget - .set_plan_mode_reasoning_effort(Some(ReasoningEffortConfig::High)); - } - app.chat_widget - .set_feature_enabled(Feature::FastMode, /*enabled*/ true); - app.chat_widget - .set_service_tier(Some(ServiceTier::Fast.request_value().to_string())); - let mut expected_mode = app.chat_widget.effective_collaboration_mode(); - assert_eq!(expected_mode.mode, mode_kind); - expected_mode.settings.model = "gpt-5.6-terra".into(); - expected_mode.settings.reasoning_effort = Some(ReasoningEffortConfig::Medium); - let default_model = app.config.model.clone(); - let default_plan_effort = app.config.plan_mode_reasoning_effort.clone(); - let config_path = app.config.codex_home.join("config.toml"); - let saved_config = std::fs::read(&config_path).ok(); - while events.try_recv().is_ok() {} - while ops.try_recv().is_ok() {} - requests.lock().unwrap().clear(); - let response = fallback_response(); - let generation = app.rate_limit_hard_stop_generation; - let mut tui = crate::tui::test_support::make_test_tui()?; - app.handle_event( - &mut tui, - &mut server, - AppEvent::RateLimitsLoaded { - request_id: 1, - origin: RateLimitRefreshOrigin::StatusCommand { request_id: 0 }, - hard_stop_generation: generation, - result: Ok(response.clone()), - }, - ) - .await?; - - let actual_mode = app.chat_widget.effective_collaboration_mode(); - assert_eq!(actual_mode, expected_mode); - assert_eq!(app.chat_widget.current_service_tier(), None); - let sent = requests.lock().unwrap().clone(); - let methods: Vec<_> = sent.iter().map(|request| request.method.as_str()).collect(); - assert_eq!(methods, ["thread/settings/update"]); - assert_eq!( - serde_json::from_value::(sent[0].params.clone().unwrap())?, - ThreadSettingsUpdateParams { - thread_id: thread_id.to_string(), - model: Some("gpt-5.6-terra".into()), - effort: Some(ReasoningEffortConfig::Medium), - collaboration_mode: Some(expected_mode.clone()), - service_tier: Some(Some("default".into())), - ..Default::default() - } - ); - let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 72); - assert!(rendered.contains("Selected model usage exhausted")); - if mode_kind == ModeKind::Default { - insta::assert_snapshot!( - "backend_banner_after_fallback", - normalize_snapshot_paths(rendered) - ); - } - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); - let queued = std::iter::from_fn(|| events.try_recv().ok()).collect::>(); - assert!(queued.iter().any(|event| matches!(event, AppEvent::OpenUrlInBrowser { url } if url == "https://chatgpt.com/settings/usage"))); - let notices = queued - .iter() - .filter_map(|event| match event { - AppEvent::InsertHistoryCell(cell) => { - Some(lines_to_single_string(&cell.display_lines(/*width*/ 80))) - } - _ => None, - }) - .collect::>(); - assert_eq!(notices.len(), 1); - insta::assert_snapshot!("backend_banner_fallback_notice", notices[0]); - assert!(!queued.iter().any(|event| matches!( - event, - AppEvent::PersistModelSelection { .. } | AppEvent::CodexOp(_) - ))); - assert!(ops.try_recv().is_err(), "switch must not replay a turn"); - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - app.chat_widget.update_backend_banner(&response); - app.apply_backend_banner_fallback(&mut server).await; - assert!( - !render_bottom_popup(&app.chat_widget, /*width*/ 72) - .contains("Selected model usage exhausted") - ); - let mut healthy = response; - healthy.rate_limit_upsell = None; - app.chat_widget.update_backend_banner(&healthy); - app.apply_backend_banner_fallback(&mut server).await; - assert_eq!(app.chat_widget.current_model(), "gpt-5.6-terra"); - assert_eq!(requests.lock().unwrap().len(), 1); - assert!( - !std::iter::from_fn(|| events.try_recv().ok()) - .any(|event| matches!(event, AppEvent::InsertHistoryCell(_))) - ); - assert_eq!(app.config.model, default_model); - assert_eq!(app.config.plan_mode_reasoning_effort, default_plan_effort); - assert_eq!(std::fs::read(&config_path).ok(), saved_config); - if mode_kind == ModeKind::Plan { - let chat = &mut app.chat_widget; - chat.handle_key_event(KeyEvent::from(KeyCode::BackTab)); - assert_eq!(chat.active_collaboration_mode_kind(), ModeKind::Default); - chat.handle_key_event(KeyEvent::from(KeyCode::BackTab)); - } - app.chat_widget - .restore_user_message_to_composer(UserMessage::from("continue")); - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_matches!(next_user_turn_op(&mut ops), AppCommand::UserTurn { model, collaboration_mode: Some(mode), .. } - if model == "gpt-5.6-terra" && mode == expected_mode); - server.shutdown().await?; - proxy.await??; - } - Ok(()) -} - -#[tokio::test] -async fn backend_banner_fallback_uses_current_task_and_accepted_generation() -> Result<()> { - let (mut app, _events, _ops) = make_test_app_with_channels().await; - let (mut server, requests, proxy) = start_fallback_thread(&mut app).await?; - let read_generation = app.rate_limit_hard_stop_generation; - let second = server.start_thread(&app.config).await?; - let active_id = second.session.thread_id; - let mut tui = crate::tui::test_support::make_test_tui()?; - let init = app.chatwidget_init_for_forked_or_resumed_thread( - &mut tui, - app.config.clone(), - /*initial_user_message*/ None, - ); - app.replace_chat_widget(ChatWidget::new_with_app_event(init)); - app.store_active_thread_receiver().await; - app.active_thread_id = None; - app.enqueue_primary_thread_session(second.session, second.turns) - .await?; - configure_fallback_model(&mut app); - requests.lock().unwrap().clear(); - app.rate_limit_hard_stop_generation = read_generation.wrapping_add(1); - for generation in [read_generation, app.rate_limit_hard_stop_generation] { - app.handle_event( - &mut tui, - &mut server, - AppEvent::RateLimitsLoaded { - request_id: 1, - origin: RateLimitRefreshOrigin::StatusCommand { request_id: 0 }, - hard_stop_generation: generation, - result: Ok(fallback_response()), - }, - ) - .await?; - if generation == read_generation { - assert_eq!(app.chat_widget.current_model(), "gpt-5.5"); - assert!(requests.lock().unwrap().is_empty()); - } - } - let sent = requests.lock().unwrap().clone(); - assert_eq!(sent.len(), 1); - assert_eq!( - sent[0].params.as_ref().unwrap()["threadId"], - active_id.to_string() - ); - assert_eq!(app.chat_widget.current_model(), "gpt-5.6-terra"); - server.shutdown().await?; - proxy.await??; - Ok(()) -} - -#[tokio::test] -async fn backend_banner_fallback_keeps_existing_recovery_without_candidate() -> Result<()> { - let (mut app, _events, _ops) = make_test_app_with_channels().await; - let (mut server, requests, proxy) = start_fallback_thread(&mut app).await?; - requests.lock().unwrap().clear(); - for (replacement, expect_legacy_banner) in [ - (json!([]), true), - (json!(["unavailable-model"]), false), - (json!(["gpt-5.5"]), false), - ] { - let mut response = fallback_response(); - response.rate_limit_upsell.as_mut().unwrap()["fallback_model_slugs"] = replacement; - app.chat_widget.update_backend_banner(&response); - app.apply_backend_banner_fallback(&mut server).await; - assert_eq!(app.chat_widget.current_model(), "gpt-5.5"); - let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 72); - assert_eq!(rendered.contains("View usage"), expect_legacy_banner); - if !expect_legacy_banner { - insta::assert_snapshot!( - "backend_banner_fallback_unavailable", - normalize_snapshot_paths(rendered) - ); - } - } - app.chat_widget.set_model("gpt-5.6-terra"); - app.chat_widget.update_backend_banner(&fallback_response()); - app.apply_backend_banner_fallback(&mut server).await; - assert_eq!(app.chat_widget.current_model(), "gpt-5.6-terra"); - assert!( - render_bottom_popup(&app.chat_widget, /*width*/ 72) - .contains("Selected model usage exhausted") - ); - assert!(requests.lock().unwrap().is_empty()); - server.shutdown().await?; - proxy.await??; - Ok(()) -} - -#[tokio::test] -async fn backend_banner_fallback_handles_settings_failure_and_queued_manual_selection() -> Result<()> -{ - use futures::SinkExt; - use futures::StreamExt; - use tokio_tungstenite::tungstenite::Message; - - for (use_reserve, error_code) in [false, true] - .into_iter() - .flat_map(|reserve| [Some(-32601), Some(-32603), None].map(|error| (reserve, error))) - { - let (mut app, mut events, _ops) = make_test_app_with_channels().await; - let id = ThreadId::new(); - app.active_thread_id = Some(id); - app.chat_widget - .handle_thread_session(test_thread_session(id, app.config.cwd.to_path_buf())); - if use_reserve { - app.primary_session_configured = - Some(test_thread_session(id, app.config.cwd.to_path_buf())); - super::luna_reserve_recovery_tests::configure_reserve_catalog(&mut app); - } else { - configure_fallback_model(&mut app); - } - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; - let websocket_url = format!("ws://{}", listener.local_addr()?); - let codex_home = app.config.codex_home.display().to_string(); - let manual_selection_tx = app.app_event_tx.clone(); - let fake = tokio::spawn(async move { - let (stream, _) = listener.accept().await?; - let mut socket = tokio_tungstenite::accept_async(stream).await?; - let mut settings_requests = 0; - while let Some(frame) = socket.next().await { - let Message::Text(text) = frame? else { - continue; - }; - let request: serde_json::Value = serde_json::from_str(&text)?; - if request["id"].is_null() { - continue; - } - let response = if request["method"] == "initialize" { - json!({"id": request["id"], "result": {"userAgent": "test", "codexHome": codex_home}}) - } else { - assert_eq!(request["method"], "thread/settings/update"); - settings_requests += 1; - if let Some(error_code) = error_code { - json!({"id": request["id"], "error": {"code": error_code, "message": "settings unavailable"}}) - } else { - if settings_requests == 1 { - // A manual selection arriving while the RPC is pending must win afterward. - manual_selection_tx.send(AppEvent::UpdateModel("gpt-5.5".into())); - } - json!({"id": request["id"], "result": {}}) - } - }; - socket - .send(Message::Text(response.to_string().into())) - .await?; - } - Result::<()>::Ok(()) - }); - let client = crate::connect_remote_app_server(crate::RemoteAppServerEndpoint::WebSocket { - websocket_url, - auth_token: None, - }) - .await?; - let mut server = AppServerSession::new( - crate::backend_id::BackendId::new(), - client, - crate::app_server_session::ThreadParamsMode::Embedded, - ); - assert!(!crate::app::safety_recourse::supports_server(&server)); - while events.try_recv().is_ok() {} - let pending_turn = if use_reserve && error_code.is_some() { - app.chat_widget - .restore_user_message_to_composer(UserMessage::from("queued before usage reply")); - app.chat_widget - .handle_key_event(KeyEvent::from(KeyCode::Enter)); - Some( - std::iter::from_fn(|| events.try_recv().ok()) - .find(|event| matches!(event, AppEvent::CodexOp(AppCommand::UserTurn { .. }))) - .expect("turn already queued before the failed switch"), - ) - } else { - None - }; - let response = if use_reserve { - super::luna_reserve_recovery_tests::reserve_response() - } else { - fallback_response() - }; - app.chat_widget.update_backend_banner(&response); - app.apply_backend_banner_fallback(&mut server).await; - let queued = std::iter::from_fn(|| events.try_recv().ok()).collect::>(); - let switch_notices = queued - .iter() - .filter(|event| match event { - AppEvent::InsertHistoryCell(cell) => { - lines_to_single_string(&cell.display_lines(/*width*/ 80)) - .contains("Automatically switched") - } - _ => false, - }) - .count(); - assert_eq!(switch_notices, usize::from(error_code.is_none())); - if error_code.is_none() { - assert_eq!( - app.chat_widget.current_model(), - if use_reserve { - "gpt-reserve" - } else { - "gpt-5.6-terra" - } - ); - let manual_selection = queued - .into_iter() - .find(|event| matches!(event, AppEvent::UpdateModel(_))) - .unwrap(); - let mut tui = crate::tui::test_support::make_test_tui()?; - app.handle_event(&mut tui, &mut server, manual_selection) - .await?; - } - assert_eq!(app.chat_widget.current_model(), "gpt-5.5"); - assert!(!render_bottom_popup(&app.chat_widget, /*width*/ 72).contains("View usage")); - if use_reserve && error_code.is_some() { - let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 90); - assert!(rendered.contains("Add credits")); - assert!(!rendered.contains("You’re now using Luna")); - if error_code == Some(-32601) { - insta::assert_snapshot!( - "luna_reserve_settings_unavailable", - normalize_snapshot_paths(rendered) - ); - } - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); - assert!( - std::iter::from_fn(|| events.try_recv().ok()) - .any(|event| matches!(event, AppEvent::OpenUrlInBrowser { .. })) - ); - let mut tui = crate::tui::test_support::make_test_tui()?; - app.handle_event(&mut tui, &mut server, pending_turn.unwrap()) - .await?; - assert_eq!( - app.chat_widget.queued_user_message_texts(), - vec!["queued before usage reply"] - ); - app.chat_widget.finish_rate_limit_recovery(); - app.chat_widget - .restore_user_message_to_composer(UserMessage::from("after recovery")); - app.chat_widget - .handle_key_event(KeyEvent::from(KeyCode::Enter)); - assert_eq!( - app.chat_widget.queued_user_message_texts(), - vec!["queued before usage reply", "after recovery"] - ); - assert!( - !std::iter::from_fn(|| events.try_recv().ok()) - .any(|event| matches!(event, AppEvent::CodexOp(AppCommand::UserTurn { .. }))) - ); - } - server.shutdown().await?; - fake.await??; - } - Ok(()) -} - -#[tokio::test] -async fn backend_banner_fallback_preserves_permissions_for_first_eligible_cyber_model() -> Result<()> -{ - let mut app = make_test_app().await; - assert!( - app.apply_permission_profile_selection(PermissionProfileSelection { - profile_id: codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY.into(), - approval_policy: Some(AskForApproval::UnlessTrusted), - approvals_reviewer: Some(ApprovalsReviewer::User), - display_label: "Read Only".into(), - }) - .await - ); - let mut server = crate::start_embedded_app_server_for_picker(&app.config).await?; - let started = server.start_thread(&app.config).await?; - let thread_id = started.session.thread_id; - app.enqueue_primary_thread_session(started.session, started.turns) - .await?; - configure_fallback_model(&mut app); - let mut models = app.model_catalog.try_list_models()?; - let mut cyber_model = models - .iter() - .find(|model| model.model == "gpt-5.6-terra") - .unwrap() - .clone(); - // Like the manual-selection tests, classify a fixture model through catalog metadata. - cyber_model.model = "cyber-test-model".into(); - cyber_model.model_specialty = Some(MODEL_SPECIALTY_CYBER.into()); - models.push(cyber_model.clone()); - app.model_catalog = Arc::new(ModelCatalog::new(models)); - let mut tui = crate::tui::test_support::make_test_tui()?; - let mut init = app.chatwidget_init_for_forked_or_resumed_thread( - &mut tui, - app.config.clone(), - /*initial_user_message*/ None, - ); - init.model_catalog = app.model_catalog.clone(); - app.replace_chat_widget(ChatWidget::new_with_app_event(init)); - app.chat_widget - .handle_thread_session(app.primary_session_configured.clone().unwrap()); - app.chat_widget.set_model("gpt-5.5"); - app.chat_widget - .set_reasoning_effort(Some(ReasoningEffortConfig::Medium)); - let mut response = fallback_response(); - response.rate_limit_upsell.as_mut().unwrap()["fallback_model_slugs"] = json!([ - "unavailable-model", - "gpt-5.5", - cyber_model.model, - "gpt-5.6-terra" - ]); - app.chat_widget.update_backend_banner(&response); - app.apply_backend_banner_fallback(&mut server).await; - assert_eq!(app.chat_widget.current_model(), cyber_model.model); - let settings = next_thread_settings_updated(&mut server, thread_id) - .await - .thread_settings; - assert_eq!( - ( - settings.model, - settings.effort, - settings.approval_policy, - settings.approvals_reviewer.to_core(), - settings.active_permission_profile.unwrap().id - ), - ( - cyber_model.model, - Some(ReasoningEffortConfig::Medium), - AskForApproval::UnlessTrusted, - ApprovalsReviewer::User, - codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY.to_string() - ), - ); - server.shutdown().await?; - Ok(()) -} diff --git a/codex-rs/tui/src/app/tests/backend_banner_recovery_tests.rs b/codex-rs/tui/src/app/tests/backend_banner_recovery_tests.rs deleted file mode 100644 index 60d8639a..00000000 --- a/codex-rs/tui/src/app/tests/backend_banner_recovery_tests.rs +++ /dev/null @@ -1,567 +0,0 @@ -use super::*; -use crate::app::rate_limit_refresh::RateLimitReadStatus; -use crate::app::rate_limit_refresh::RateLimitRefreshOutcome; -use app_test_support::ChatGptAuthFixture; -use app_test_support::write_chatgpt_auth; -use codex_app_server_protocol::CodexErrorInfo; -use codex_app_server_protocol::ErrorNotification; -use codex_app_server_protocol::GetAccountRateLimitsResponse; -use codex_config::types::AuthCredentialsStoreMode; -use pretty_assertions::assert_eq; -use serde_json::json; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; - -fn response_with_banner() -> GetAccountRateLimitsResponse { - serde_json::from_value(json!({ - "accountId":"workspace-a", "rateLimitUpsell":{ - "banner_type":"selected_model_limit", "model_slug":"test-model-a", "presentation":"inline", - "title":"Selected model usage exhausted", "description":"Switch to another model or contact your owner.", - "ctas":[{"action":"notify_owner","label":"Notify owner"}] - }, - "rateLimits":{}, "rateLimitsByLimitId":null,"rateLimitResetCredits":null - })).unwrap() -} - -async fn next_rate_limits_loaded( - events: &mut tokio::sync::mpsc::UnboundedReceiver, -) -> Result { - Ok( - tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 10), async { - loop { - let event = events.recv().await.expect("app event channel"); - if matches!(event, AppEvent::RateLimitsLoaded { .. }) { - break event; - } - } - }) - .await?, - ) -} - -#[tokio::test] -async fn luna_reserve_periodic_refresh_adapts_without_an_experiment_banner() -> Result<()> { - let backend = MockServer::start().await; - let home = tempdir()?; - write_chatgpt_auth( - home.path(), - ChatGptAuthFixture::new("local-test-token") - .account_id("workspace-a") - .chatgpt_user_id("user-a") - .plan_type("plus"), - AuthCredentialsStoreMode::File, - ) - .expect("write synthetic auth"); - std::fs::write( - home.path().join("config.toml"), - format!( - "chatgpt_base_url = {:?}\ncli_auth_credentials_store = \"file\"\n", - backend.uri() - ), - )?; - let (mut app, mut events, _ops) = make_test_app_with_channels().await; - app.config.codex_home = home.path().to_path_buf().abs(); - app.config.chatgpt_base_url = backend.uri(); - app.config.sqlite = codex_state::SqliteConfig::new_for_testing(home.path().abs()); - set_chatgpt_auth(&mut app.chat_widget); - let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - for (used, seconds) in [(10, 60), (75, 30), (90, 15), (99, 5), (20, 60)] { - backend.reset().await; - Mock::given(method("GET")) - .and(path("/api/codex/usage")) - .respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({ - "account_id": "workspace-a", "user_id": "user-a", "plan_type": "plus", - "rate_limit": {"allowed": true, "limit_reached": false, - "primary_window": {"used_percent": used, "limit_window_seconds": 18000, - "reset_after_seconds": 1800, "reset_at": 2000000000}}, - "rate_limit_reset_credits": {"available_count": 1} - }))) - .expect(/*r*/ 1) - .mount(&backend) - .await; - Mock::given(method("GET")) - .and(path("/api/codex/rate-limit-reset-credits")) - .respond_with(ResponseTemplate::new(/*s*/ 200)) - .expect(/*r*/ 0) - .mount(&backend) - .await; - app.refresh_rate_limits(&session, RateLimitRefreshOrigin::Periodic); - // A second timer tick while this RPC is pending must not add another request. - app.refresh_rate_limits(&session, RateLimitRefreshOrigin::Periodic); - assert!( - app.rate_limit_refresh_state - .poll_deadline(Duration::from_secs(/*secs*/ 60)) - .is_none() - ); - let loaded = next_rate_limits_loaded(&mut events).await?; - assert_matches!(&loaded, AppEvent::RateLimitsLoaded { result: Ok(_), .. }); - let before = std::time::Instant::now(); - app.handle_event(&mut tui, &mut session, loaded).await?; - let after = std::time::Instant::now(); - let interval = app.chat_widget.rate_limit_refresh_interval().unwrap(); - assert_eq!(interval, Duration::from_secs(seconds)); - let deadline = app - .rate_limit_refresh_state - .poll_deadline(interval) - .unwrap(); - assert!(deadline >= before + interval && deadline <= after + interval); - let requests = backend.received_requests().await.unwrap(); - let usage = requests - .iter() - .find(|request| request.url.path() == "/api/codex/usage") - .unwrap(); - assert!(usage.headers.contains_key("x-openai-codex-luna-reserve")); - backend.verify().await; - } - session.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn backend_banner_limit_error_refreshes_again_after_intervening_rolling_hard_stop() --> Result<()> { - let server = MockServer::start().await; - let home = tempdir()?; - write_chatgpt_auth( - home.path(), - ChatGptAuthFixture::new("local-test-token") - .account_id("workspace-a") - .chatgpt_user_id("user-a") - .plan_type("team"), - AuthCredentialsStoreMode::File, - ) - .expect("write synthetic auth"); - std::fs::write( - home.path().join("config.toml"), - format!( - "chatgpt_base_url = {:?}\ncli_auth_credentials_store = \"file\"\n", - server.uri() - ), - )?; - let (mut app, mut events, _ops) = make_test_app_with_channels().await; - app.config.codex_home = home.path().to_path_buf().abs(); - app.config.chatgpt_base_url = server.uri(); - app.config.sqlite = codex_state::SqliteConfig::new_for_testing(home.path().abs()); - set_chatgpt_auth(&mut app.chat_widget); - app.chat_widget.set_model("test-model-a"); - let mut healthy = response_with_banner(); - healthy.rate_limit_upsell = None; - app.chat_widget.update_backend_banner(&healthy); - assert!( - !render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted") - ); - Mock::given(method("GET")) - .and(path("/api/codex/usage")) - .respond_with( - ResponseTemplate::new(200) - .set_delay(std::time::Duration::from_millis(/*millis*/ 100)) - .set_body_json(json!({ - "account_id":"workspace-a","user_id":"user-a","plan_type":"team", - "rate_limit":{"allowed":true,"limit_reached":false}, - "rate_limit_upsell":response_with_banner().rate_limit_upsell, - "rate_limit_reset_credits":{"available_count":0} - })), - ) - .expect(3) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/api/codex/rate-limit-reset-credits")) - .respond_with( - ResponseTemplate::new(200).set_body_json(json!({"available_count":0,"credits":[]})), - ) - .expect(3) - .mount(&server) - .await; - let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - while events.try_recv().is_ok() {} - app.chat_widget.handle_server_notification( - ServerNotification::Error(ErrorNotification { - error: AppServerTurnError { - misalignment: None, - message: "credits exhausted".into(), - codex_error_info: Some(CodexErrorInfo::UsageLimitExceeded), - additional_details: None, - }, - will_retry: false, - thread_id: "thread-a".into(), - turn_id: "turn-a".into(), - }), - /*replay_kind*/ None, - ); - let recovery = loop { - let event = events - .try_recv() - .expect("limit error should request recovery without a command"); - if matches!( - event, - AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::Recovery - } - ) { - break event; - } - }; - app.handle_event(&mut tui, &mut session, recovery).await?; - app.handle_event( - &mut tui, - &mut session, - AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::Recovery, - }, - ) - .await?; - let mut rolling = response_with_banner().rate_limits; - rolling.rate_limit_reached_type = - Some(codex_app_server_protocol::RateLimitReachedType::WorkspaceMemberCreditsDepleted); - app.handle_app_server_event( - &session, - codex_app_server_client::AppServerEvent::ServerNotification(Box::new( - ServerNotification::AccountRateLimitsUpdated( - codex_app_server_protocol::AccountRateLimitsUpdatedNotification { - rate_limits: rolling.clone(), - }, - ), - )), - ) - .await; - let loaded = next_rate_limits_loaded(&mut events).await?; - assert!( - matches!(&loaded, AppEvent::RateLimitsLoaded { result: Ok(_), .. }), - "{loaded:?}" - ); - app.handle_event(&mut tui, &mut session, loaded).await?; - assert!( - !render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted") - ); - // No second inference Error or explicit refresh: the obsolete read starts its own replacement. - let loaded = next_rate_limits_loaded(&mut events).await?; - app.handle_event(&mut tui, &mut session, loaded).await?; - let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 90); - assert!(rendered.contains("Selected model usage exhausted")); - assert!(rendered.contains("Notify owner")); - // A background operation can report the same hard stop after the full response omitted - // aggregate reached_type: included usage for other models is still available. - app.handle_app_server_event( - &session, - codex_app_server_client::AppServerEvent::ServerNotification(Box::new( - ServerNotification::AccountRateLimitsUpdated( - codex_app_server_protocol::AccountRateLimitsUpdatedNotification { - rate_limits: rolling, - }, - ), - )), - ) - .await; - assert!( - render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted") - ); - let loaded = next_rate_limits_loaded(&mut events).await?; - app.handle_event(&mut tui, &mut session, loaded).await?; - assert!( - render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted") - ); - app.chat_widget.set_model("test-model-b"); - assert!( - !render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted") - ); - session.shutdown().await?; - server.verify().await; - Ok(()) -} - -#[test] -fn backend_banner_recovery_follows_rolling_invalidation_without_another_error() { - let mut refresh = crate::app::rate_limit_refresh::RateLimitRefreshState::default(); - let mut epoch = 0; - let first = refresh - .start(RateLimitRefreshOrigin::Recovery, &mut epoch) - .unwrap(); - epoch += 1; - assert_eq!( - refresh.finish(first.0, first.1, epoch, RateLimitReadStatus::Succeeded), - RateLimitRefreshOutcome::RefreshRecovery - ); -} - -#[tokio::test] -async fn backend_banner_rolling_only_recovery_holds_new_input() -> Result<()> { - let (mut app, _events, mut ops) = make_test_app_with_channels().await; - let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - app.chat_widget.handle_thread_session(test_thread_session( - ThreadId::new(), - app.config.cwd.to_path_buf(), - )); - set_chatgpt_auth(&mut app.chat_widget); - app.chat_widget.set_model("test-model-a"); - let mut rolling = response_with_banner().rate_limits; - rolling.spend_control_reached = Some(true); - app.handle_app_server_event( - &session, - codex_app_server_client::AppServerEvent::ServerNotification(Box::new( - ServerNotification::AccountRateLimitsUpdated( - codex_app_server_protocol::AccountRateLimitsUpdatedNotification { - rate_limits: rolling, - }, - ), - )), - ) - .await; - app.chat_widget.apply_external_edit("follow-up".into()); - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!( - app.chat_widget.queued_user_message_texts(), - vec!["follow-up"] - ); - assert!( - !std::iter::from_fn(|| ops.try_recv().ok()).any(|op| matches!(op, Op::UserTurn { .. })) - ); - app.handle_event( - &mut tui, - &mut session, - AppEvent::RateLimitsLoaded { - request_id: 1, - origin: RateLimitRefreshOrigin::Recovery, - hard_stop_generation: app.rate_limit_hard_stop_generation, - result: Ok(response_with_banner()), - }, - ) - .await?; - assert!( - matches!(next_user_turn_op(&mut ops), Op::UserTurn { items, .. } - if items == vec![UserInput::Text { text: "follow-up".into(), text_elements: Vec::new() }]) - ); - session.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn backend_banner_account_changes_invalidate_pending_recovery() -> Result<()> { - let (mut app, _events, _ops) = make_test_app_with_channels().await; - let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - app.chat_widget.set_model("test-model-a"); - let current = response_with_banner(); - app.chat_widget.update_backend_banner(¤t); - assert!( - render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted") - ); - let pending = app - .rate_limit_refresh_state - .start( - RateLimitRefreshOrigin::Recovery, - &mut app.rate_limit_hard_stop_generation, - ) - .unwrap(); - app.handle_app_server_event( - &session, - codex_app_server_client::AppServerEvent::ServerNotification(Box::new( - ServerNotification::AccountUpdated( - codex_app_server_protocol::AccountUpdatedNotification { - auth_mode: None, - plan_type: None, - }, - ), - )), - ) - .await; - app.handle_event( - &mut tui, - &mut session, - AppEvent::RateLimitsLoaded { - request_id: pending.0, - origin: RateLimitRefreshOrigin::Recovery, - hard_stop_generation: pending.1, - result: Ok(current), - }, - ) - .await?; - assert!( - !render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted") - ); - assert!( - app.rate_limit_refresh_state - .start( - RateLimitRefreshOrigin::Recovery, - &mut app.rate_limit_hard_stop_generation - ) - .is_some() - ); - session.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn backend_banner_reset_redemption_rejects_pre_reset_content() -> Result<()> { - let (mut app, _events, mut ops) = make_test_app_with_channels().await; - let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - app.chat_widget.handle_thread_session(test_thread_session( - ThreadId::new(), - app.config.cwd.to_path_buf(), - )); - app.chat_widget.set_model("test-model-a"); - let banner = response_with_banner(); - app.chat_widget.update_backend_banner(&banner); - assert!( - render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted") - ); - let pending = app - .rate_limit_refresh_state - .start( - RateLimitRefreshOrigin::Recovery, - &mut app.rate_limit_hard_stop_generation, - ) - .unwrap(); - app.chat_widget.hold_rate_limit_recovery(); - app.chat_widget.apply_external_edit("after reset".into()); - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!( - app.chat_widget.queued_user_message_texts(), - vec!["after reset"] - ); - let request_id = app.chat_widget.show_rate_limit_reset_consuming_popup(); - app.handle_event( - &mut tui, - &mut session, - AppEvent::RateLimitResetCreditConsumed { - request_id, - idempotency_key: "mock-reset".into(), - credit_id: None, - result: Ok( - codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse { - outcome: - codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome::Reset, - }, - ), - }, - ) - .await?; - let mut recovered = banner.clone(); - recovered.rate_limit_upsell = None; - recovered.rate_limit_reset_credits = - Some(codex_app_server_protocol::RateLimitResetCreditsSummary { - available_count: 0, - credits: None, - }); - app.handle_event( - &mut tui, - &mut session, - AppEvent::RateLimitsLoaded { - request_id: 2, - origin: RateLimitRefreshOrigin::ResetConsume { request_id }, - hard_stop_generation: app.rate_limit_hard_stop_generation, - result: Ok(recovered), - }, - ) - .await?; - assert!( - matches!(next_user_turn_op(&mut ops), Op::UserTurn { items, .. } - if items == vec![UserInput::Text { text: "after reset".into(), text_elements: Vec::new() }]) - ); - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - app.handle_event( - &mut tui, - &mut session, - AppEvent::RateLimitsLoaded { - request_id: pending.0, - origin: RateLimitRefreshOrigin::Recovery, - hard_stop_generation: pending.1, - result: Ok(banner), - }, - ) - .await?; - assert!( - !render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted") - ); - assert!( - app.rate_limit_refresh_state - .start( - RateLimitRefreshOrigin::Recovery, - &mut app.rate_limit_hard_stop_generation - ) - .is_some() - ); - session.shutdown().await?; - Ok(()) -} - -#[test] -fn backend_banner_post_reset_read_preserves_newer_recovery_hold() { - let mut refresh = crate::app::rate_limit_refresh::RateLimitRefreshState::default(); - let mut epoch = 0; - let old = refresh - .start(RateLimitRefreshOrigin::Recovery, &mut epoch) - .unwrap(); - epoch += 1; - refresh.invalidate_recovery(); - let reset = refresh - .start( - RateLimitRefreshOrigin::ResetConsume { request_id: 1 }, - &mut epoch, - ) - .unwrap(); - assert_eq!( - refresh.finish(old.0, old.1, epoch, RateLimitReadStatus::Succeeded), - RateLimitRefreshOutcome::Ignore - ); - assert!(refresh.has_pending_recovery()); - let newer = refresh - .start(RateLimitRefreshOrigin::Recovery, &mut epoch) - .unwrap(); - assert_eq!( - refresh.finish(reset.0, reset.1, epoch, RateLimitReadStatus::Succeeded), - RateLimitRefreshOutcome::Ignore - ); - assert!(refresh.has_pending_recovery()); - assert_eq!( - refresh.finish(newer.0, newer.1, epoch, RateLimitReadStatus::Failed), - RateLimitRefreshOutcome::Ignore - ); - assert!(!refresh.has_pending_recovery()); -} - -#[test] -fn backend_banner_recovery_coalesces_until_newer_epoch_can_be_read() { - let mut refresh = crate::app::rate_limit_refresh::RateLimitRefreshState::default(); - let mut epoch = 0; - let first = refresh - .start(RateLimitRefreshOrigin::Recovery, &mut epoch) - .unwrap(); - epoch += 1; // A newer rolling hard stop makes the in-flight response obsolete. - for _ in 0..10 { - assert_eq!( - refresh.start(RateLimitRefreshOrigin::Recovery, &mut epoch), - None - ); - } - assert_eq!( - refresh.finish(first.0, first.1, epoch, RateLimitReadStatus::Succeeded), - RateLimitRefreshOutcome::RefreshRecovery - ); - let next = refresh - .start(RateLimitRefreshOrigin::Recovery, &mut epoch) - .unwrap(); - assert_eq!( - refresh.finish(next.0, next.1, epoch, RateLimitReadStatus::Succeeded), - RateLimitRefreshOutcome::Apply - ); -} diff --git a/codex-rs/tui/src/app/tests/backend_banner_startup_tests.rs b/codex-rs/tui/src/app/tests/backend_banner_startup_tests.rs deleted file mode 100644 index 68670ee7..00000000 --- a/codex-rs/tui/src/app/tests/backend_banner_startup_tests.rs +++ /dev/null @@ -1,95 +0,0 @@ -use super::backend_banner_fallback_tests::fallback_response; -use super::*; -use crate::chatwidget::UserMessage; -use crate::chatwidget::tests::helpers::set_fast_mode_test_catalog_for_models; -use pretty_assertions::assert_eq; - -#[tokio::test] -async fn backend_banner_fallback_applies_before_initial_and_queued_startup_prompts() -> Result<()> { - let (mut app, mut events, _ops) = make_test_app_with_channels().await; - let mut config = app.config.clone(); - config.model = Some("gpt-5.5".into()); - let mut tui = crate::tui::test_support::make_test_tui()?; - let init = app.chatwidget_init_for_forked_or_resumed_thread( - &mut tui, - config.clone(), - Some(UserMessage::from("initial prompt")), - ); - app.replace_chat_widget(ChatWidget::new_with_app_event(init)); - set_chatgpt_auth(&mut app.chat_widget); - set_fast_mode_test_catalog_for_models(&mut app.chat_widget, "gpt-5.5", "gpt-5.6-terra"); - app.model_catalog = app.chat_widget.model_catalog(); - app.pending_startup_thread_start = true; - app.chat_widget.set_model("gpt-5.5"); - app.chat_widget - .set_queue_submissions_until_session_configured(/*queue*/ true); - app.chat_widget - .apply_external_edit("queued follow-up".into()); - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - let (mut server, requests, proxy) = session_lifecycle_requests::start_recording_app_server( - &config, /*blocked_thread_list*/ None, /*failed_thread_name*/ None, - ) - .await?; - let generation = app.rate_limit_hard_stop_generation; - app.handle_event( - &mut tui, - &mut server, - AppEvent::RateLimitsLoaded { - request_id: 1, - origin: RateLimitRefreshOrigin::StartupPrefetch { - reset_hint_request_id: 0, - }, - hard_stop_generation: generation, - result: Ok(fallback_response()), - }, - ) - .await?; - assert!(requests.lock().unwrap().is_empty()); - assert!( - !render_bottom_popup(&app.chat_widget, /*width*/ 72) - .contains("Selected model usage exhausted") - ); - let started = server.start_thread(&config).await?; - let thread_id = started.session.thread_id; - requests.lock().unwrap().clear(); - while events.try_recv().is_ok() {} - app.handle_startup_thread_started(&mut server, Ok(started)) - .await?; - assert_eq!(app.active_thread_id, Some(thread_id)); - let submissions = std::iter::from_fn(|| events.try_recv().ok()) - .filter_map(|event| { - if let AppEvent::CodexOp(AppCommand::UserTurn { model, items, .. }) = event { - Some((model, items)) - } else { - None - } - }) - .collect::>(); - assert_eq!( - submissions, - vec![( - "gpt-5.6-terra".into(), - vec![UserInput::Text { - text: "initial prompt".into(), - text_elements: Vec::new(), - }] - )] - ); - assert_eq!( - app.chat_widget.queued_user_message_texts(), - vec!["queued follow-up"] - ); - assert_eq!( - requests - .lock() - .unwrap() - .iter() - .map(|request| request.method.as_str()) - .collect::>(), - vec!["thread/settings/update"] - ); - server.shutdown().await?; - proxy.await??; - Ok(()) -} diff --git a/codex-rs/tui/src/app/tests/luna_reserve_recovery_tests.rs b/codex-rs/tui/src/app/tests/luna_reserve_recovery_tests.rs deleted file mode 100644 index 8dbceb0c..00000000 --- a/codex-rs/tui/src/app/tests/luna_reserve_recovery_tests.rs +++ /dev/null @@ -1,384 +0,0 @@ -//! Verify Reserve recovery through accepted usage reads and the task settings RPC. - -use super::*; -use crate::chatwidget::UserMessage; -use codex_app_server_protocol::GetAccountRateLimitsResponse; -use codex_app_server_protocol::ThreadSettingsUpdateParams; -use pretty_assertions::assert_eq; -use serde_json::json; - -pub(super) fn reserve_response() -> GetAccountRateLimitsResponse { - serde_json::from_value(json!({ - "accountId": "workspace-a", "ordinaryUsageAllowed": false, - "rateLimits": {"limitId": "codex", "primary": {"usedPercent": 100}}, - "rateLimitsByLimitId": {"base_model_inference": { - "limitId": "base_model_inference", "limitName": "gpt-reserve", - "primary": {"usedPercent": 48, "windowDurationMins": 10080} - }}, - "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"}] - } - })) - .unwrap() -} - -pub(super) fn configure_reserve_catalog(app: &mut App) { - let mut models = app.model_catalog.try_list_models().unwrap(); - let mut reserve = models - .iter() - .find(|model| model.model == "gpt-5.5") - .unwrap() - .clone(); - reserve.model = "gpt-reserve".into(); - reserve.show_in_picker = false; - models.push(reserve); - let original = models - .iter_mut() - .find(|model| model.model == "gpt-5.5") - .unwrap(); - let mut high = original.supported_reasoning_efforts[0].clone(); - high.effort = ReasoningEffortConfig::High; - original.supported_reasoning_efforts.push(high); - Arc::make_mut(&mut app.model_catalog).models = models; - let mut tui = crate::tui::test_support::make_test_tui().unwrap(); - let mut init = app.chatwidget_init_for_forked_or_resumed_thread( - &mut tui, - app.config.clone(), - /*initial_user_message*/ None, - ); - init.has_chatgpt_account = true; - init.has_codex_backend_auth = true; - app.replace_chat_widget(ChatWidget::new_with_app_event(init)); - app.chat_widget - .handle_thread_session(app.primary_session_configured.clone().unwrap()); - app.chat_widget.set_model("gpt-5.5"); -} - -#[tokio::test] -async fn luna_reserve_recovery_survives_task_reconstruction() -> Result<()> { - let (mut app, _events, _ops) = make_test_app_with_channels().await; - let (mut server, requests, proxy) = - backend_banner_fallback_tests::start_fallback_thread(&mut app).await?; - configure_reserve_catalog(&mut app); - app.chat_widget - .set_reasoning_effort(Some(ReasoningEffortConfig::High)); - app.chat_widget.update_backend_banner(&reserve_response()); - app.apply_backend_banner_fallback(&mut server).await; - let mut resumed = app.primary_session_configured.clone().unwrap(); - resumed.model = "gpt-reserve".into(); - resumed.collaboration_mode = Some(Box::new(app.chat_widget.effective_collaboration_mode())); - let mut tui = crate::tui::test_support::make_test_tui()?; - let mut init = app.chatwidget_init_for_forked_or_resumed_thread( - &mut tui, - app.config.clone(), - /*initial_user_message*/ None, - ); - init.has_chatgpt_account = true; - init.has_codex_backend_auth = true; - // No in-memory transition state is inherited: resume must recover the persisted target. - app.replace_chat_widget(ChatWidget::new_with_app_event(init)); - app.chat_widget.handle_thread_session(resumed); - assert_eq!(app.chat_widget.current_model(), "gpt-reserve"); - let mut recovered = reserve_response(); - recovered.ordinary_usage_allowed = Some(true); - recovered.rate_limit_upsell = None; - app.chat_widget.update_backend_banner(&recovered); - app.apply_backend_banner_fallback(&mut server).await; - assert_eq!(app.chat_widget.current_model(), "gpt-5.5"); - assert_eq!( - app.chat_widget.current_reasoning_effort(), - Some(ReasoningEffortConfig::High) - ); - assert_eq!( - requests - .lock() - .unwrap() - .iter() - .filter(|request| request.method == "thread/settings/update") - .count(), - 2 - ); - assert!( - !app.config - .codex_home - .join("tui-luna-reserve") - .join(format!("{}.json", app.active_thread_id.unwrap())) - .exists() - ); - server.shutdown().await?; - proxy.await??; - Ok(()) -} - -#[tokio::test] -async fn luna_reserve_entry_dispatches_an_already_queued_turn_with_accepted_settings() -> Result<()> -{ - for mode in [ModeKind::Default, ModeKind::Plan] { - let (mut app, mut events, _ops) = make_test_app_with_channels().await; - let (mut server, requests, proxy) = - backend_banner_fallback_tests::start_fallback_thread(&mut app).await?; - configure_reserve_catalog(&mut app); - app.chat_widget - .set_feature_enabled(Feature::FastMode, /*enabled*/ true); - app.chat_widget.set_service_tier(Some("fast".into())); - if mode == ModeKind::Plan { - app.chat_widget - .handle_key_event(KeyEvent::from(KeyCode::BackTab)); - } - app.chat_widget - .restore_user_message_to_composer(UserMessage::from("continue")); - app.chat_widget - .handle_key_event(KeyEvent::from(KeyCode::Enter)); - let pending = std::iter::from_fn(|| events.try_recv().ok()) - .find(|event| matches!(event, AppEvent::CodexOp(AppCommand::UserTurn { .. }))) - .expect("queued turn before the usage response"); - requests.lock().unwrap().clear(); - let mut tui = crate::tui::test_support::make_test_tui()?; - let generation = app.rate_limit_hard_stop_generation; - app.handle_event( - &mut tui, - &mut server, - AppEvent::RateLimitsLoaded { - request_id: 1, - origin: RateLimitRefreshOrigin::Periodic, - hard_stop_generation: generation, - result: Ok(reserve_response()), - }, - ) - .await?; - app.handle_event(&mut tui, &mut server, pending).await?; - let sent = requests.lock().unwrap().clone(); - let methods: Vec<_> = sent.iter().map(|request| request.method.as_str()).collect(); - assert_eq!(methods, ["thread/settings/update", "turn/start"]); - let settings: ThreadSettingsUpdateParams = - serde_json::from_value(sent[0].params.clone().unwrap())?; - let turn: codex_app_server_protocol::TurnStartParams = - serde_json::from_value(sent[1].params.clone().unwrap())?; - assert_eq!( - ( - turn.model, - turn.effort, - turn.service_tier, - turn.collaboration_mode - ), - ( - settings.model, - settings.effort, - settings.service_tier, - settings.collaboration_mode - ) - ); - assert_eq!(app.chat_widget.effective_collaboration_mode().mode, mode); - server.shutdown().await?; - proxy.await??; - } - Ok(()) -} - -#[tokio::test] -async fn luna_reserve_recovery_restores_task_and_pending_turn_after_fresh_backend_read() --> Result<()> { - for has_credits in [false, true] { - let (mut app, mut events, _ops) = make_test_app_with_channels().await; - let (mut server, requests, proxy) = - backend_banner_fallback_tests::start_fallback_thread(&mut app).await?; - configure_reserve_catalog(&mut app); - app.chat_widget - .set_feature_enabled(Feature::FastMode, /*enabled*/ false); - app.chat_widget - .set_feature_enabled(Feature::UltrafastMode, /*enabled*/ false); - app.chat_widget - .set_reasoning_effort(Some(ReasoningEffortConfig::High)); - let original_mode = app.chat_widget.effective_collaboration_mode(); - let config_path = app.config.codex_home.join("config.toml"); - let saved_config = std::fs::read(&config_path).ok(); - let mut tui = crate::tui::test_support::make_test_tui()?; - requests.lock().unwrap().clear(); - let generation = app.rate_limit_hard_stop_generation; - app.handle_event( - &mut tui, - &mut server, - AppEvent::RateLimitsLoaded { - request_id: 1, - origin: RateLimitRefreshOrigin::Periodic, - hard_stop_generation: generation, - result: Ok(reserve_response()), - }, - ) - .await?; - assert_eq!(app.chat_widget.current_model(), "gpt-reserve"); - - // A prompt composed before the next accepted read must use the recovered model, once. - app.chat_widget - .handle_key_event(KeyEvent::from(KeyCode::Esc)); - app.chat_widget - .restore_user_message_to_composer(UserMessage::from("continue")); - app.chat_widget - .handle_key_event(KeyEvent::from(KeyCode::Enter)); - let mut pending = std::iter::from_fn(|| events.try_recv().ok()) - .find_map(|event| match event { - AppEvent::CodexOp(op @ AppCommand::UserTurn { .. }) => Some(op), - _ => None, - }) - .expect("queued user turn"); - assert_matches!(&pending, AppCommand::UserTurn {model, ..} if model == "gpt-reserve"); - while events.try_recv().is_ok() {} - - let mut recovered = reserve_response(); - recovered.ordinary_usage_allowed = Some(!has_credits); - recovered.rate_limits.credits = Some(codex_app_server_protocol::CreditsSnapshot { - has_credits, - unlimited: false, - balance: None, - }); - recovered.rate_limit_upsell = None; - // A rounded percentage is not an authorization decision; backend allowed=true wins. - for (request_id, hard_stop_generation, expected) in [ - (2, generation.wrapping_sub(1), "gpt-reserve"), - (3, generation, "gpt-5.5"), - (4, generation, "gpt-5.5"), - ] { - app.handle_event( - &mut tui, - &mut server, - AppEvent::RateLimitsLoaded { - request_id, - origin: RateLimitRefreshOrigin::Periodic, - hard_stop_generation, - result: Ok(recovered.clone()), - }, - ) - .await?; - assert_eq!(app.chat_widget.current_model(), expected); - } - assert_eq!( - app.chat_widget.effective_collaboration_mode(), - original_mode - ); - assert!(!render_bottom_popup(&app.chat_widget, /*width*/ 100).contains("Luna Reserve")); - app.chat_widget - .apply_reserve_fallback_to_pending_turn(&mut pending); - assert_matches!(pending, AppCommand::UserTurn { model, effort, collaboration_mode, .. } - if model == "gpt-5.5" && effort == original_mode.reasoning_effort() - && collaboration_mode == Some(original_mode.clone())); - let sent = requests.lock().unwrap().clone(); - assert_eq!(sent.len(), 2); - let restored: ThreadSettingsUpdateParams = - serde_json::from_value(sent[1].params.clone().unwrap())?; - assert_eq!( - restored, - ThreadSettingsUpdateParams { - thread_id: app.active_thread_id.unwrap().to_string(), - model: Some("gpt-5.5".into()), - effort: Some(ReasoningEffortConfig::High), - collaboration_mode: Some(original_mode), - service_tier: None, - ..Default::default() - } - ); - assert_eq!(std::fs::read(&config_path).ok(), saved_config); - let queued = std::iter::from_fn(|| events.try_recv().ok()).collect::>(); - assert!( - !queued.iter().any(|event| matches!( - event, - AppEvent::CodexOp(_) | AppEvent::PersistModelSelection { .. } - )), - "recovery must not replay a turn or change global defaults" - ); - let notice = queued - .iter() - .find_map(|event| match event { - AppEvent::InsertHistoryCell(cell) => { - Some(lines_to_single_string(&cell.display_lines(/*width*/ 100))) - } - _ => None, - }) - .expect("recovery notice"); - insta::assert_snapshot!("luna_reserve_recovery_notice", notice); - server.shutdown().await?; - proxy.await??; - } - Ok(()) -} - -#[tokio::test] -async fn luna_reserve_recovery_requires_permission_and_no_remaining_blocker() -> Result<()> { - let (mut app, _events, _ops) = make_test_app_with_channels().await; - let (mut server, requests, proxy) = - backend_banner_fallback_tests::start_fallback_thread(&mut app).await?; - configure_reserve_catalog(&mut app); - app.chat_widget.update_backend_banner(&reserve_response()); - app.apply_backend_banner_fallback(&mut server).await; - requests.lock().unwrap().clear(); - let mut recovered = reserve_response(); - recovered.rate_limit_upsell = None; - recovered.rate_limits.primary.as_mut().unwrap().used_percent = 0; - recovered.rate_limits.primary.as_mut().unwrap().resets_at = Some(0); - for allowed in [None, Some(false)] { - recovered.ordinary_usage_allowed = allowed; - app.chat_widget.update_backend_banner(&recovered); - app.apply_backend_banner_fallback(&mut server).await; - assert_eq!(app.chat_widget.current_model(), "gpt-reserve"); - } - recovered.ordinary_usage_allowed = Some(true); - for blocker in [ - json!({"accountId": null, "ordinaryUsageAllowed": null}), - json!({"rateLimitUpsell": {"unsupported": true}}), - json!({"rateLimits": {"spendControlReached": true}}), - json!({"rateLimits": {"rateLimitReachedType": "workspace_owner_usage_limit_reached"}}), - ] { - let mut raw = serde_json::to_value(&recovered)?; - for (key, value) in blocker.as_object().unwrap() { - raw[key] = value.clone(); - } - app.chat_widget - .update_backend_banner(&serde_json::from_value(raw)?); - app.apply_backend_banner_fallback(&mut server).await; - assert_eq!(app.chat_widget.current_model(), "gpt-reserve"); - } - // Reset redemption clears presentation before the authoritative follow-up read. - app.chat_widget.clear_backend_banner(); - app.chat_widget.update_backend_banner(&recovered); - app.apply_backend_banner_fallback(&mut server).await; - assert_eq!(app.chat_widget.current_model(), "gpt-5.5"); - assert_eq!(requests.lock().unwrap().len(), 1); - server.shutdown().await?; - proxy.await??; - Ok(()) -} - -#[tokio::test] -async fn luna_reserve_recovery_does_not_override_manual_choice_or_account_change() -> Result<()> { - for change_account in [false, true] { - let (mut app, _events, _ops) = make_test_app_with_channels().await; - let (mut server, requests, proxy) = - backend_banner_fallback_tests::start_fallback_thread(&mut app).await?; - configure_reserve_catalog(&mut app); - app.chat_widget.update_backend_banner(&reserve_response()); - app.apply_backend_banner_fallback(&mut server).await; - requests.lock().unwrap().clear(); - let mut recovered = reserve_response(); - recovered.ordinary_usage_allowed = Some(true); - recovered.rate_limit_upsell = None; - let expected = if change_account { - recovered.account_id = Some("workspace-b".into()); - "gpt-reserve" - } else { - app.chat_widget.set_model("gpt-5.6-terra"); - "gpt-5.6-terra" - }; - app.chat_widget.update_backend_banner(&recovered); - app.apply_backend_banner_fallback(&mut server).await; - recovered.account_id = Some("workspace-a".into()); - app.chat_widget.update_backend_banner(&recovered); - app.apply_backend_banner_fallback(&mut server).await; - assert_eq!(app.chat_widget.current_model(), expected); - assert!(requests.lock().unwrap().is_empty()); - server.shutdown().await?; - proxy.await??; - } - Ok(()) -} diff --git a/codex-rs/tui/src/app/tests/rate_limits.rs b/codex-rs/tui/src/app/tests/rate_limits.rs deleted file mode 100644 index 6b0cffaa..00000000 --- a/codex-rs/tui/src/app/tests/rate_limits.rs +++ /dev/null @@ -1,563 +0,0 @@ -use super::*; -use codex_app_server_protocol::AccountRateLimitsUpdatedNotification; -use codex_app_server_protocol::CodexErrorInfo; -use codex_app_server_protocol::CreditsSnapshot; -use codex_app_server_protocol::ErrorNotification; -use codex_app_server_protocol::GetAccountRateLimitsResponse; -use codex_app_server_protocol::RateLimitReachedType; -use codex_app_server_protocol::RateLimitResetCreditsSummary; -use codex_app_server_protocol::RateLimitSnapshot; -use codex_app_server_protocol::RateLimitWindow; -use crossterm::event::KeyCode; -use crossterm::event::KeyEvent; -use pretty_assertions::assert_eq; - -fn rate_limit_snapshot( - used_percent: i32, - rate_limit_reached_type: Option, - spend_control_reached: Option, -) -> RateLimitSnapshot { - RateLimitSnapshot { - limit_id: Some("codex".to_string()), - limit_name: None, - normal_model_slug: None, - primary: Some(RateLimitWindow { - used_percent, - window_duration_mins: Some(300), - resets_at: None, - }), - secondary: None, - credits: Some(CreditsSnapshot { - has_credits: true, - unlimited: false, - balance: None, - }), - individual_limit: None, - spend_control_reached, - plan_type: None, - rate_limit_reached_type, - } -} - -fn account_rate_limits_response(snapshot: RateLimitSnapshot) -> GetAccountRateLimitsResponse { - GetAccountRateLimitsResponse { - ordinary_usage_allowed: None, - account_id: None, - rate_limit_upsell: None, - rate_limits: snapshot, - rate_limits_by_limit_id: None, - rate_limit_reset_credits: Some(RateLimitResetCreditsSummary { - available_count: 0, - credits: None, - }), - } -} - -async fn deliver_rolling_rate_limit_snapshot( - app: &mut App, - app_server: &AppServerSession, - snapshot: RateLimitSnapshot, -) { - app.handle_app_server_event( - app_server, - codex_app_server_client::AppServerEvent::ServerNotification(Box::new( - ServerNotification::AccountRateLimitsUpdated(AccountRateLimitsUpdatedNotification { - rate_limits: snapshot, - }), - )), - ) - .await; -} - -fn render_status_output( - app: &mut App, - app_event_rx: &mut tokio::sync::mpsc::UnboundedReceiver, -) -> String { - while app_event_rx.try_recv().is_ok() {} - app.chat_widget.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); - match app_event_rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell - .display_lines(/*width*/ 120) - .into_iter() - .map(|line| line.to_string()) - .collect::>() - .join("\n"), - other => panic!("expected status output, got {other:?}"), - } -} - -fn deliver_usage_limit_error(app: &mut App) { - app.chat_widget.handle_server_notification( - ServerNotification::Error(ErrorNotification { - error: AppServerTurnError { - misalignment: None, - message: "Usage limit reached.".to_string(), - codex_error_info: Some(CodexErrorInfo::UsageLimitExceeded), - additional_details: None, - }, - will_retry: false, - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - }), - /*replay_kind*/ None, - ); -} - -#[tokio::test] -async fn backend_banner_state_survives_widget_replacement() -> Result<()> { - for dismiss in [false, true] { - let (mut app, _rx, _op_rx) = make_test_app_with_channels().await; - set_chatgpt_auth(&mut app.chat_widget); - let mut response = account_rate_limits_response(rate_limit_snapshot( - /*used_percent*/ 100, /*rate_limit_reached_type*/ None, - /*spend_control_reached*/ None, - )); - response.rate_limit_upsell = Some(serde_json::json!({ - "banner_type": "plus_rate_limit_reached", "title": "Usage limit reached", - "presentation": "dismissible", - "description": "Choose how to continue.", - "ctas": [{"action": "view_usage", "label": "View usage"}] - })); - app.chat_widget.update_backend_banner(&response); - assert!(render_bottom_popup(&app.chat_widget, /*width*/ 90).contains("View usage")); - if dismiss { - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - } - let mut tui = crate::tui::test_support::make_test_tui()?; - let init = app.chatwidget_init_for_forked_or_resumed_thread( - &mut tui, - app.config.clone(), - /*initial_user_message*/ None, - ); - app.replace_chat_widget(ChatWidget::new_with_app_event(init)); - set_active_cell( - &mut app.chat_widget, - Box::new(PlainHistoryCell::new(Vec::new())), - ); - app.chat_widget.pre_draw_tick(); - assert_eq!( - render_bottom_popup(&app.chat_widget, /*width*/ 90).contains("View usage"), - !dismiss - ); - app.chat_widget.update_backend_banner(&response); - assert_eq!( - render_bottom_popup(&app.chat_widget, /*width*/ 90).contains("View usage"), - !dismiss - ); - response.rate_limit_upsell = None; - app.chat_widget.update_backend_banner(&response); - assert!(!render_bottom_popup(&app.chat_widget, /*width*/ 90).contains("View usage")); - } - 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; - let app_server = crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()) - .await - .expect("embedded app server"); - - let cases = [ - (None, None, false), - (Some(RateLimitReachedType::RateLimitReached), None, false), - (None, Some(false), false), - (None, Some(true), true), - ( - Some(RateLimitReachedType::WorkspaceOwnerCreditsDepleted), - None, - true, - ), - ( - Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted), - None, - true, - ), - ( - Some(RateLimitReachedType::WorkspaceOwnerUsageLimitReached), - None, - true, - ), - ( - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached), - None, - true, - ), - ]; - let mut expected_generation = 0; - for (reached_type, spend_control_reached, invalidates) in cases { - deliver_rolling_rate_limit_snapshot( - &mut app, - &app_server, - rate_limit_snapshot( - /*used_percent*/ 95, - reached_type, - spend_control_reached, - ), - ) - .await; - if invalidates { - expected_generation += 1; - } - assert_eq!( - app.rate_limit_hard_stop_generation, expected_generation, - "reached_type={reached_type:?}, spend_control_reached={spend_control_reached:?}" - ); - } - - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn stale_rate_limit_reads_preserve_newer_workspace_hard_stop_for_every_origin() -> Result<()> -{ - for origin_name in [ - "startup", - "status", - "usage", - "reset-picker", - "reset-consume", - ] { - let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; - set_chatgpt_auth(&mut app.chat_widget); - let mut tui = crate::tui::test_support::make_test_tui()?; - let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker( - app.chat_widget.config_ref(), - )) - .await?; - - app.chat_widget - .on_rate_limit_snapshot(Some(rate_limit_snapshot( - /*used_percent*/ 20, - /*rate_limit_reached_type*/ None, - Some(false), - ))); - let origin = match origin_name { - "startup" => RateLimitRefreshOrigin::StartupPrefetch { - reset_hint_request_id: app.chat_widget.start_rate_limit_reset_startup_check(), - }, - "status" => { - let request_id = 7; - app.chat_widget - .add_status_output(/*refreshing_rate_limits*/ true, Some(request_id)); - RateLimitRefreshOrigin::StatusCommand { request_id } - } - "usage" => { - let startup_request_id = app.chat_widget.start_rate_limit_reset_startup_check(); - app.chat_widget.finish_rate_limit_reset_hint_refresh( - startup_request_id, - Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 0, - credits: None, - }), - ); - app.chat_widget.insert_str("/usage"); - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - loop { - match app_event_rx.try_recv() { - Ok(AppEvent::RefreshRateLimits { origin }) => break origin, - Ok(_) => {} - other => panic!("expected usage refresh request, got {other:?}"), - } - } - } - "reset-picker" => RateLimitRefreshOrigin::ResetPicker { - request_id: app.chat_widget.show_rate_limit_reset_loading_popup(), - }, - "reset-consume" => RateLimitRefreshOrigin::ResetConsume { - request_id: app.chat_widget.show_rate_limit_reset_consuming_popup(), - }, - _ => unreachable!("unknown refresh origin"), - }; - let read_generation = app.rate_limit_hard_stop_generation; - let mut rolling_snapshot = rate_limit_snapshot( - /*used_percent*/ 95, - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached), - Some(true), - ); - if origin_name == "reset-picker" { - rolling_snapshot.limit_id = Some("codex_other".to_string()); - } - deliver_rolling_rate_limit_snapshot(&mut app, &app_server, rolling_snapshot).await; - assert_ne!(read_generation, app.rate_limit_hard_stop_generation); - - let control = Box::pin(app.handle_event( - &mut tui, - &mut app_server, - AppEvent::RateLimitsLoaded { - request_id: 0, - origin, - hard_stop_generation: read_generation, - result: Ok(account_rate_limits_response(rate_limit_snapshot( - /*used_percent*/ 0, - /*rate_limit_reached_type*/ None, - Some(false), - ))), - }, - )) - .await?; - assert!(matches!(control, AppRunControl::Continue)); - - let popup = render_bottom_popup(&app.chat_widget, /*width*/ 100); - match origin_name { - "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.")); - } - "reset-consume" => { - assert!(popup.contains("Usage reset. You have 0 usage limit resets left.")); - } - "startup" | "status" => {} - _ => unreachable!("unknown refresh origin"), - } - - let status = render_status_output(&mut app, &mut app_event_rx); - assert!( - status.contains("80% left"), - "expected {origin_name} to preserve the last account usage snapshot, got: {status}" - ); - deliver_usage_limit_error(&mut app); - let popup = render_bottom_popup(&app.chat_widget, /*width*/ 100); - assert!( - popup.contains("Request a limit increase from your owner"), - "expected {origin_name} to preserve workspace error routing, got: {popup}" - ); - - app_server.shutdown().await?; - } - - Ok(()) -} - -#[tokio::test] -async fn stale_rate_limit_read_does_not_dismiss_visible_workspace_advisory() -> Result<()> { - let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; - set_chatgpt_auth(&mut app.chat_widget); - let mut tui = crate::tui::test_support::make_test_tui()?; - let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker( - app.chat_widget.config_ref(), - )) - .await?; - let request_id = 7; - app.chat_widget - .add_status_output(/*refreshing_rate_limits*/ true, Some(request_id)); - let read_generation = app.rate_limit_hard_stop_generation; - - deliver_rolling_rate_limit_snapshot( - &mut app, - &app_server, - rate_limit_snapshot( - /*used_percent*/ 95, - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached), - Some(true), - ), - ) - .await; - app.chat_widget.handle_server_notification( - turn_completed_notification(ThreadId::new(), "turn-1", TurnStatus::Completed), - /*replay_kind*/ None, - ); - assert!( - render_bottom_popup(&app.chat_widget, /*width*/ 100).contains("Approaching rate limits") - ); - - Box::pin(app.handle_event( - &mut tui, - &mut app_server, - AppEvent::RateLimitsLoaded { - request_id: 0, - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - hard_stop_generation: read_generation, - result: Ok(account_rate_limits_response(rate_limit_snapshot( - /*used_percent*/ 0, - /*rate_limit_reached_type*/ None, - Some(false), - ))), - }, - )) - .await?; - - assert!( - render_bottom_popup(&app.chat_widget, /*width*/ 100).contains("Approaching rate limits") - ); - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn post_hard_stop_rate_limit_read_clears_recovered_workspace_limit() -> Result<()> { - let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; - set_chatgpt_auth(&mut app.chat_widget); - let mut tui = crate::tui::test_support::make_test_tui()?; - let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker( - app.chat_widget.config_ref(), - )) - .await?; - deliver_rolling_rate_limit_snapshot( - &mut app, - &app_server, - rate_limit_snapshot( - /*used_percent*/ 95, - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached), - Some(true), - ), - ) - .await; - let read_generation = app.rate_limit_hard_stop_generation; - let request_id = 7; - app.chat_widget - .add_status_output(/*refreshing_rate_limits*/ true, Some(request_id)); - - let control = Box::pin(app.handle_event( - &mut tui, - &mut app_server, - AppEvent::RateLimitsLoaded { - request_id: 0, - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - hard_stop_generation: read_generation, - result: Ok(account_rate_limits_response(rate_limit_snapshot( - /*used_percent*/ 0, - /*rate_limit_reached_type*/ None, - Some(false), - ))), - }, - )) - .await?; - assert!(matches!(control, AppRunControl::Continue)); - - let status = render_status_output(&mut app, &mut app_event_rx); - assert!( - status.contains("100% left"), - "expected recovered limits, got: {status}" - ); - deliver_usage_limit_error(&mut app); - let popup = render_bottom_popup(&app.chat_widget, /*width*/ 100); - assert!( - !popup.contains("Request a limit increase from your owner"), - "expected recovered state to clear workspace error routing, got: {popup}" - ); - - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn failed_rate_limit_read_preserves_visible_backend_banner() -> Result<()> { - let (mut app, _events, _ops) = make_test_app_with_channels().await; - let mut tui = crate::tui::test_support::make_test_tui()?; - let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker( - app.chat_widget.config_ref(), - )) - .await?; - let mut response = account_rate_limits_response(rate_limit_snapshot( - /*used_percent*/ 25, - /*rate_limit_reached_type*/ None, - Some(false), - )); - response.account_id = Some("workspace-a".into()); - response.rate_limit_upsell = Some(serde_json::json!({ - "banner_type": "workspace_recovery", "presentation": "inline", - "title": "Workspace needs credits", "description": "Ask your owner for credits.", - "ctas": [] - })); - app.chat_widget.update_backend_banner(&response); - let before = render_bottom_popup(&app.chat_widget, /*width*/ 90); - assert!(before.contains("Workspace needs credits")); - let request_id = 7; - app.chat_widget - .add_status_output(/*refreshing_rate_limits*/ true, Some(request_id)); - let generation = app.rate_limit_hard_stop_generation; - app.handle_event( - &mut tui, - &mut app_server, - AppEvent::RateLimitsLoaded { - request_id: 0, - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - hard_stop_generation: generation, - result: Err("transient test failure".into()), - }, - ) - .await?; - assert_eq!(render_bottom_popup(&app.chat_widget, /*width*/ 90), before); - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn backend_banner_reads_ignore_older_completions() -> Result<()> { - let (mut app, _events, _ops) = make_test_app_with_channels().await; - let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - app.chat_widget.set_model("test-model-a"); - let mut current = account_rate_limits_response(rate_limit_snapshot( - /*used_percent*/ 100, /*rate_limit_reached_type*/ None, - /*spend_control_reached*/ None, - )); - current.rate_limit_upsell = Some(serde_json::json!({ - "banner_type":"selected_model_limit", "model_slug":"test-model-a", "presentation":"inline", - "title":"Selected model usage exhausted", "description":"Contact your owner.", "ctas":[] - })); - for request_id in 1..=5 { - app.rate_limit_refresh_state - .start( - RateLimitRefreshOrigin::StatusCommand { request_id }, - &mut app.rate_limit_hard_stop_generation, - ) - .unwrap(); - } - for (id, generation, result, expect_visible) in [ - (2, 0, Ok(current.clone()), true), - ( - 1, - 0, - Ok({ - let mut absent = current.clone(); - absent.rate_limit_upsell = None; - absent - }), - true, - ), - (4, 0, Err("transient failure".into()), true), - ( - 3, - 0, - Ok({ - let mut absent = current.clone(); - absent.rate_limit_upsell = None; - absent - }), - false, - ), - (5, 0, Ok(current.clone()), true), - ] { - app.handle_event( - &mut tui, - &mut session, - AppEvent::RateLimitsLoaded { - request_id: id, - origin: RateLimitRefreshOrigin::StatusCommand { request_id: id }, - hard_stop_generation: generation, - result, - }, - ) - .await?; - assert_eq!( - render_bottom_popup(&app.chat_widget, /*width*/ 90) - .contains("Selected model usage exhausted"), - expect_visible - ); - } - session.shutdown().await?; - Ok(()) -} diff --git a/codex-rs/tui/src/app/tests/thread_usage.rs b/codex-rs/tui/src/app/tests/thread_usage.rs deleted file mode 100644 index 6a5ad7a7..00000000 --- a/codex-rs/tui/src/app/tests/thread_usage.rs +++ /dev/null @@ -1,356 +0,0 @@ -use super::*; -use crate::chatwidget::ThreadUsageOutcome; -use codex_app_server_client::AppServerEvent; -use codex_app_server_protocol::AccountUpdatedNotification; -use codex_app_server_protocol::AuthMode; -use codex_app_server_protocol::ThreadUsage; -use codex_protocol::account::PlanType; -use pretty_assertions::assert_eq; -use ratatui::layout::Rect; -use ratatui::layout::Size; - -async fn app_with_pending_thread_usage() --> Result<(Box, AppServerSession, tui::Tui, ThreadId, u64)> { - let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; - let thread_id = ThreadId::new(); - app.chat_widget.handle_thread_session(test_thread_session( - thread_id, - test_path_buf("/tmp/project"), - )); - app.chat_widget.update_account_state( - /*status_account_display*/ None, - Some(PlanType::Business), - /*has_chatgpt_account*/ false, - /*has_codex_backend_auth*/ true, - ); - while app_event_rx.try_recv().is_ok() {} - let mut app_server = - crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - tui.terminal.set_viewport_area(Rect::new( - /*x*/ 0, /*y*/ 21, /*width*/ 80, /*height*/ 3, - )); - - app.chat_widget.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); - let initial_status = match app_event_rx.try_recv() { - Ok(event @ AppEvent::InsertHistoryCell(_)) => event, - other => panic!("expected immediate status card, got {other:?}"), - }; - let request_id = match app_event_rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - request_id, - }) if requested_thread_id == thread_id => request_id, - other => panic!("expected asynchronous thread usage request, got {other:?}"), - }; - app.handle_event(&mut tui, &mut app_server, initial_status) - .await?; - - Ok((app, app_server, tui, thread_id, request_id)) -} - -fn successful_thread_usage(thread_id: ThreadId, request_id: u64) -> AppEvent { - AppEvent::ThreadUsageLoaded { - thread_id, - request_id, - result: Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 50_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - } -} - -fn pending_history_text(tui: &tui::Tui) -> String { - tui.pending_history_lines_for_test() - .into_iter() - .map(|line| { - line.line - .spans - .iter() - .map(|span| span.content.as_ref()) - .collect::() - }) - .collect::>() - .join("\n") -} - -#[tokio::test] -async fn account_updated_with_backend_only_auth_enables_thread_usage() -> Result<()> { - let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; - let thread_id = ThreadId::new(); - app.chat_widget.handle_thread_session(test_thread_session( - thread_id, - test_path_buf("/tmp/project"), - )); - while app_event_rx.try_recv().is_ok() {} - let app_server = - crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?; - - app.handle_app_server_event( - &app_server, - AppServerEvent::ServerNotification(Box::new(ServerNotification::AccountUpdated( - AccountUpdatedNotification { - auth_mode: Some(AuthMode::AgentIdentity), - plan_type: Some(PlanType::Business), - }, - ))), - ) - .await; - - assert!(!app.chat_widget.has_chatgpt_account()); - assert!(app.chat_widget.has_codex_backend_auth()); - app.chat_widget.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); - assert_matches!(app_event_rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))); - assert_matches!( - app_event_rx.try_recv(), - Ok(AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - .. - }) if requested_thread_id == thread_id - ); - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn completed_thread_usage_updates_status_without_scrollback_reflow() -> Result<()> { - let (mut app, mut app_server, mut tui, thread_id, request_id) = - app_with_pending_thread_usage().await?; - assert!(!app.transcript_reflow.has_pending_reflow()); - assert!(pending_history_text(&tui).contains("/status")); - - let status = Arc::clone(app.transcript_cells.last().expect("status card")); - app.insert_history_cell( - &mut tui, - Box::new(history_cell::new_warning_event("diagnostic".into())), - ); - - app.handle_event( - &mut tui, - &mut app_server, - successful_thread_usage(thread_id, request_id), - ) - .await?; - - assert!(!app.transcript_reflow.has_pending_reflow()); - assert!( - tui.pending_history_lines_for_test().is_empty(), - "a visible status tail should be replaced directly instead of appending a duplicate card" - ); - let rendered = lines_to_single_string(&status.display_lines(/*width*/ 90)); - assert!(rendered.contains("50 credits"), "{rendered}"); - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn thread_usage_after_intervening_history_appends_refreshed_status() -> Result<()> { - let (mut app, mut app_server, mut tui, thread_id, request_id) = - app_with_pending_thread_usage().await?; - app.insert_history_cell( - &mut tui, - Box::new(PlainHistoryCell::new(vec![ - Line::from("/status"), - Line::from("intervening model output"), - ])), - ); - - app.handle_event( - &mut tui, - &mut app_server, - successful_thread_usage(thread_id, request_id), - ) - .await?; - - let pending = pending_history_text(&tui); - assert!(pending.contains("intervening model output"), "{pending}"); - assert!(pending.contains("50 credits"), "{pending}"); - assert!(!app.transcript_reflow.has_pending_reflow()); - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn failed_thread_usage_after_intervening_history_does_not_duplicate_status() -> Result<()> { - let (mut app, mut app_server, mut tui, thread_id, request_id) = - app_with_pending_thread_usage().await?; - app.insert_history_cell( - &mut tui, - Box::new(PlainHistoryCell::new(vec![Line::from( - "intervening model output", - )])), - ); - let pending_before_failure = pending_history_text(&tui); - - app.handle_event( - &mut tui, - &mut app_server, - AppEvent::ThreadUsageLoaded { - thread_id, - request_id, - result: Err("thread usage request timed out".to_string()), - }, - ) - .await?; - - assert_eq!(pending_history_text(&tui), pending_before_failure); - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn thread_usage_finishing_during_overlay_updates_history_after_close() -> Result<()> { - let (mut app, mut app_server, mut tui, thread_id, request_id) = - app_with_pending_thread_usage().await?; - tui.set_alt_screen_enabled(/*enabled*/ false); - app.open_transcript_overlay(&mut tui); - - app.handle_event( - &mut tui, - &mut app_server, - successful_thread_usage(thread_id, request_id), - ) - .await?; - assert!(app.pending_thread_usage_history_refresh); - - app.close_transcript_overlay(&mut tui); - - assert!(!app.pending_thread_usage_history_refresh); - assert!(tui.pending_history_lines_for_test().is_empty()); - assert!( - app.last_rendered_history_tail - .as_ref() - .expect("updated status should remain the rendered history tail") - .lines - .iter() - .any(|line| line.line.to_string().contains("50 credits")) - ); - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn account_change_discards_thread_usage_deferred_while_overlay_is_open() -> Result<()> { - let (mut app, mut app_server, mut tui, thread_id, request_id) = - app_with_pending_thread_usage().await?; - tui.set_alt_screen_enabled(/*enabled*/ false); - app.open_transcript_overlay(&mut tui); - app.handle_event( - &mut tui, - &mut app_server, - successful_thread_usage(thread_id, request_id), - ) - .await?; - assert!(app.pending_thread_usage_history_refresh); - - app.handle_app_server_event( - &app_server, - AppServerEvent::ServerNotification(Box::new(ServerNotification::AccountUpdated( - AccountUpdatedNotification { - auth_mode: Some(AuthMode::AgentIdentity), - plan_type: Some(PlanType::Business), - }, - ))), - ) - .await; - assert!(!app.pending_thread_usage_history_refresh); - assert!(app.last_thread_usage_status_cell.is_none()); - - app.close_transcript_overlay(&mut tui); - - assert!(!pending_history_text(&tui).contains("50 credits")); - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn terminal_reflow_rebases_pending_status_update_to_new_width() -> Result<()> { - let (mut app, mut app_server, mut tui, thread_id, request_id) = - app_with_pending_thread_usage().await?; - app.insert_history_cell( - &mut tui, - Box::new(history_cell::new_warning_event("diagnostic".into())), - ); - app.insert_history_cell( - &mut tui, - Box::new( - history_cell::DynamicToolCallCell::from_item(ThreadItemPayload::DynamicToolCall { - id: "pending-tool".into(), - namespace: None, - tool: "lookup".into(), - arguments: serde_json::json!({}), - status: codex_app_server_protocol::DynamicToolCallStatus::InProgress, - success: None, - duration_ms: None, - content_items: None, - }) - .unwrap(), - ), - ); - let original = app - .last_rendered_history_tail - .as_ref() - .expect("initial rendered status") - .lines - .clone(); - let screen_size = Size::new(/*width*/ 52, /*height*/ 24); - tui.terminal.last_known_screen_size = screen_size; - let viewport = Rect::new( - /*x*/ 0, - /*y*/ 21, - screen_size.width, - /*height*/ 3, - ); - tui.terminal.set_viewport_area(viewport); - - app.reflow_transcript_now(&mut tui, screen_size.into())?; - - let resized = app - .last_rendered_history_tail - .as_ref() - .expect("resized rendered status") - .lines - .clone(); - assert_ne!(original, resized); - // Bazel tests run without a TTY, so model the settled viewport explicitly - // before simulating an asynchronous usage update after resize replay. - tui.terminal.set_viewport_area(viewport); - app.handle_event( - &mut tui, - &mut app_server, - successful_thread_usage(thread_id, request_id), - ) - .await?; - assert!(tui.pending_history_lines_for_test().is_empty()); - assert!(!app.transcript_reflow.has_pending_reflow()); - app_server.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn queued_status_reads_refreshed_usage_only_when_emitted() -> Result<()> { - let (mut app, mut app_server, mut tui, thread_id, request_id) = - app_with_pending_thread_usage().await?; - let status = Arc::clone(app.transcript_cells.last().unwrap()); - tui.clear_pending_history_lines(); - app.native_history.defer(&status); - app.render_inserted_history_cell(&mut tui, &status, /*deferred*/ true); - app.handle_event( - &mut tui, - &mut app_server, - successful_thread_usage(thread_id, request_id), - ) - .await?; - assert!(tui.pending_history_lines_for_test().is_empty()); - app.flush_native_history(&mut tui); - assert_eq!(pending_history_text(&tui).matches("50 credits").count(), 1); - app_server.shutdown().await?; - Ok(()) -} diff --git a/codex-rs/tui/src/backend_banners.rs b/codex-rs/tui/src/backend_banners.rs deleted file mode 100644 index 4109b896..00000000 --- a/codex-rs/tui/src/backend_banners.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! Backend banner payload and CTA mapping, supplied by the existing account usage read. -//! -//! The backend owns eligibility, copy, actions, and ordered model fallback instructions. - -use codex_protocol::account::PlanType; -use serde::Deserialize; - -mod actions; -mod render; - -pub(crate) const LUNA_RESERVE_BANNER: &str = "luna_reserve"; -pub(crate) const LUNA_RESERVE_RECOVERY_VIEW_ID: &str = "luna-reserve-recovery"; - -#[cfg(test)] -#[path = "backend_banners_tests.rs"] -mod tests; - -#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] -pub(crate) struct BackendBanner { - pub(crate) banner_type: String, - pub(crate) title: String, - pub(crate) description: String, - pub(crate) ctas: Vec, - pub(crate) reset_at: Option, - pub(crate) model_slug: Option, - pub(crate) blocked_model_slug: Option, - #[serde(default)] - pub(crate) fallback_model_slugs: Vec, - #[serde(default)] - pub(crate) presentation: BannerPresentation, - request_url: Option, - #[serde(skip)] - pub(crate) account_id: String, - #[serde(skip)] - pub(crate) plan_type: Option, -} - -#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "snake_case")] -pub(crate) enum BannerPresentation { - #[default] - Inline, - Dismissible, -} - -#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] -pub(crate) struct BackendBannerCta { - action: String, - label: String, -} - -impl BackendBanner { - /// Parse supported, bounded content before constructing rendered copy or CTA closures. - pub(crate) fn parse(raw: &serde_json::Value) -> Option { - serde_json::from_value::(raw.clone()) - .ok() - .filter(|banner| { - let valid_slug = |slug: &str| { - !slug.trim().is_empty() - && slug.len() <= 256 - && !slug.chars().any(char::is_control) - }; - banner.title.len() <= 1024 - && banner.description.len() <= 4096 - && banner.ctas.len() <= 8 - && !banner.title.trim().is_empty() - && banner.title.lines().count() <= 3 - && banner.description.lines().count() <= 12 - && banner.blocked_model_slug.as_deref().is_none_or(valid_slug) - && banner.fallback_model_slugs.len() <= 16 - && banner - .fallback_model_slugs - .iter() - .all(|slug| valid_slug(slug)) - }) - } -} diff --git a/codex-rs/tui/src/backend_banners/actions.rs b/codex-rs/tui/src/backend_banners/actions.rs deleted file mode 100644 index 4ff66e26..00000000 --- a/codex-rs/tui/src/backend_banners/actions.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! Map backend CTA names to existing CLI actions and desktop-equivalent browser destinations. - -use super::BackendBanner; -use codex_app_server_protocol::AddCreditsNudgeCreditType; -use codex_protocol::account::PlanType; - -const USAGE_URL: &str = "https://chatgpt.com/settings/usage"; -const WORKSPACE_USAGE_URL: &str = "https://chatgpt.com/admin/usage-limits/workspace"; - -pub(super) enum BannerAction { - OpenUrl(String), - NotifyOwner(AddCreditsNudgeCreditType), - ResetUsage, -} - -impl BackendBanner { - pub(super) fn resolve_action(&self, action: &str) -> Option { - match action { - "notify_owner" | "contact_owner" => { - return Some(BannerAction::NotifyOwner( - AddCreditsNudgeCreditType::Credits, - )); - } - "request_increase" => { - let Some(destination) = self.request_url.as_deref() else { - return Some(BannerAction::NotifyOwner( - AddCreditsNudgeCreditType::UsageLimit, - )); - }; - let url = url::Url::parse(destination).ok()?; - if !matches!(url.scheme(), "https" | "http") - || url.host_str().is_none() - || !url.username().is_empty() - || url.password().is_some() - { - return None; - } - return Some(BannerAction::OpenUrl(url.to_string())); - } - // Keep the existing picker and explicit confirmation before consuming a reset. - "reset_usage" => return Some(BannerAction::ResetUsage), - _ => {} - } - let destination = match action { - "add_credits" | "buy_credits" - if self.plan_type.is_some_and(PlanType::is_workspace_account) => - { - "https://chatgpt.com/admin/billing?codex_credit_action=add_credits".to_string() - } - "add_credits" | "buy_credits" => format!("{USAGE_URL}?credits_modal=true"), - "buy_reset" => "https://chatgpt.com/codex/purchase/reset".to_string(), - "view_usage" | "request_increase_usage_settings" => USAGE_URL.to_string(), - "view_workspace_usage" | "increase_spend_cap" => WORKSPACE_USAGE_URL.to_string(), - "open_plus_pricing_web" => "https://chatgpt.com/explore/plus".to_string(), - "open_pro_pricing_web" => "https://chatgpt.com/explore/pro".to_string(), - "open_pricing_dialog" => { - let mut url = url::Url::parse("https://chatgpt.com/").ok()?; - let target = if matches!(self.plan_type, Some(PlanType::Plus | PlanType::ProLite)) { - "pro" - } else { - "plus" - }; - url.query_pairs_mut() - .append_pair("cta_tab", "personal") - .append_pair("highlight_plan", target); - if self.plan_type == Some(PlanType::ProLite) { - url.query_pairs_mut().append_pair("pro_variant", "2x"); - } - url.set_fragment(Some("pricing")); - url.to_string() - } - // Desktop-only referral and Premium dialogs need their own CLI flow. - _ => return None, - }; - let mut destination = url::Url::parse(&destination).ok()?; - if destination.path().starts_with("/admin/") { - if self.account_id.is_empty() { - return None; - } - // The existing admin route selects the requested workspace before opening the modal. - destination - .query_pairs_mut() - .append_pair("account_id", &self.account_id); - } - Some(BannerAction::OpenUrl(destination.to_string())) - } -} diff --git a/codex-rs/tui/src/backend_banners/render.rs b/codex-rs/tui/src/backend_banners/render.rs deleted file mode 100644 index 41e3b7d5..00000000 --- a/codex-rs/tui/src/backend_banners/render.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! Render backend-owned copy and ordered CTA labels with the shared inline banner UI. - -use super::BackendBanner; -use super::BannerPresentation; -use super::actions::BannerAction; -use crate::app_event::AppEvent; -use crate::bottom_pane::ActionableBanner; -use crate::bottom_pane::BannerDismissal; -use crate::bottom_pane::SelectionItem; -use crate::clock_format::ClockFormat; -use chrono::DateTime; -use chrono::Local; - -impl BackendBanner { - pub(crate) fn actionable_banner(&self, clock_format: ClockFormat) -> ActionableBanner { - let reset_time = self - .reset_at - .and_then(|timestamp| DateTime::from_timestamp(timestamp, /*nsecs*/ 0)) - .map(|time| { - crate::status::format_reset_timestamp( - time.with_timezone(&Local), - Local::now(), - clock_format, - ) - }); - let copy = |text: &str| { - let text: String = text - .chars() - .filter(|c| !c.is_control() || *c == '\n') - .collect(); - match reset_time.as_deref() { - Some(reset_time) => text.replace("{time}", reset_time), - None => text, - } - }; - let actions = self - .ctas - .iter() - .filter_map(|cta| { - if cta.label.trim().is_empty() - || cta.label.len() > 256 - || cta.label.chars().any(char::is_control) - { - return None; - } - let action = self.resolve_action(&cta.action)?; - Some(SelectionItem { - name: cta.label.clone(), - actions: vec![Box::new(move |tx| { - tx.send(match &action { - BannerAction::OpenUrl(url) => { - AppEvent::OpenUrlInBrowser { url: url.clone() } - } - BannerAction::NotifyOwner(credit_type) => { - AppEvent::SendAddCreditsNudgeEmail { - credit_type: *credit_type, - } - } - BannerAction::ResetUsage => AppEvent::OpenRateLimitResetCredits, - }) - })], - dismiss_on_select: false, - ..Default::default() - }) - }) - .collect::>(); - ActionableBanner { - title: copy(&self.title), - description: copy(&self.description), - actions, - dismissal: if self.presentation == BannerPresentation::Dismissible { - BannerDismissal::Dismissible - } else { - BannerDismissal::Persistent - }, - ..Default::default() - } - } -} diff --git a/codex-rs/tui/src/backend_banners_tests.rs b/codex-rs/tui/src/backend_banners_tests.rs deleted file mode 100644 index b9545124..00000000 --- a/codex-rs/tui/src/backend_banners_tests.rs +++ /dev/null @@ -1,57 +0,0 @@ -use super::BackendBanner; -use pretty_assertions::assert_eq; -use serde_json::json; - -#[test] -fn parse_rejects_more_actions_than_the_inline_banner_can_display() { - let labels: Vec<_> = (1..=8).map(|index| format!("Action {index}")).collect(); - let mut raw = json!({ - "banner_type": "usage_limit", "title": "Usage limit reached", - "description": "Choose how to continue.", - "ctas": labels.iter().map(|label| json!({ - "action": "view_usage", "label": label, - })).collect::>(), - }); - let banner = BackendBanner::parse(&raw).expect("eight actions fit"); - assert_eq!( - banner - .actionable_banner(crate::clock_format::ClockFormat::TwentyFourHour) - .actions - .into_iter() - .map(|action| action.name) - .collect::>(), - labels - ); - - raw["ctas"].as_array_mut().unwrap().push(json!({ - "action": "view_usage", "label": "Hidden ninth action", - })); - assert_eq!(BackendBanner::parse(&raw), None); -} - -#[test] -fn parse_rejects_unsupported_or_unrenderable_content() { - let valid = json!({ - "banner_type": "usage_limit", "title": "Usage limit reached", - "description": "Choose how to continue.", "ctas": [], - }); - for invalid_fields in [ - json!({"presentation":"future_mode"}), - json!({"presentation":null}), - json!({"title":" "}), - json!({"title":"x".repeat(1025)}), - json!({"title":"line\n".repeat(4)}), - json!({"description":"x".repeat(4097)}), - json!({"description":"line\n".repeat(13)}), - json!({"blocked_model_slug":""}), - json!({"blocked_model_slug":"bad\nslug"}), - json!({"fallback_model_slugs":["x".repeat(257)]}), - json!({"fallback_model_slugs":vec!["model"; 17]}), - ] { - let mut raw = valid.clone(); - raw.as_object_mut() - .unwrap() - .extend(invalid_fields.as_object().unwrap().clone()); - assert_eq!(BackendBanner::parse(&raw), None, "{invalid_fields}"); - } -} diff --git a/codex-rs/tui/src/chatwidget/backend_banners.rs b/codex-rs/tui/src/chatwidget/backend_banners.rs deleted file mode 100644 index e769319d..00000000 --- a/codex-rs/tui/src/chatwidget/backend_banners.rs +++ /dev/null @@ -1,523 +0,0 @@ -//! Account banners and response-driven model transitions for the selected task. -//! -//! Only explicitly dismissible, previously shown occurrences can be dismissed. Model changes hide -//! content without dismissing it; an authoritative replacement/absence starts a new occurrence. -//! Reserve recovery uses a focused picker and a persisted task-local return model. -//! Its entry notice is shared across chats until the backend confirms ordinary usage has recovered. - -use super::ChatWidget; -use super::QueuedUserMessage; -use super::luna_reserve_return::ReserveReturnModel; -use crate::app_command::AppCommand; -use crate::backend_banners::BackendBanner; -use crate::backend_banners::BannerPresentation; -use crate::backend_banners::LUNA_RESERVE_BANNER; -use crate::backend_banners::LUNA_RESERVE_RECOVERY_VIEW_ID; -use crate::bottom_pane::SelectionItem; -use crate::bottom_pane::SelectionViewParams; -use crate::bottom_pane::popup_consts::accept_cancel_hint_line; -use crate::keymap::ListAction; -use crate::model_catalog::LUNA_RESERVE_MODEL; -use codex_app_server_protocol::GetAccountRateLimitsResponse; -use codex_protocol::config_types::CollaborationMode; -use codex_protocol::config_types::ModeKind; -use codex_protocol::openai_models::ModelPreset; -use codex_protocol::openai_models::ReasoningEffort; -use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; - -#[derive(Debug, PartialEq)] -pub(crate) enum AutomaticModelSwitchReason { - UsageLimit, - UsageRecovered, -} - -#[derive(Debug, PartialEq)] -pub(crate) struct AutomaticModelSwitch { - pub model: ModelPreset, - pub effort: Option, - pub reason: AutomaticModelSwitchReason, -} - -/// Live transition state; the return target is also persisted per task for reconstruction. -#[derive(Default)] -pub(super) struct AutomaticModelSwitchState { - reserve_return: Option, - replaced_model: Option, -} - -#[derive(Default)] -pub(super) struct BackendBannerState { - account_id: Option, - ordinary_usage_recovered: bool, - banner: Option, - presented: Option, - shown: bool, - dismissed: bool, - picker_dismissed: Arc, -} - -impl ChatWidget { - pub(super) fn restrict_model_picker_to_luna_reserve(&self) -> bool { - // A fresh account read can allow manual recovery even without a valid saved return model. - self.current_model() == LUNA_RESERVE_MODEL - && !self.backend_banner_state.ordinary_usage_recovered - } - - pub(crate) fn invalidate_ordinary_usage_recovery(&mut self) { - // Keep the current banner, but never reuse permission from before a new hard stop. - self.backend_banner_state.ordinary_usage_recovered = false; - } - - pub(super) fn waiting_for_luna_reserve(&self) -> bool { - self.current_model() != LUNA_RESERVE_MODEL - && self - .backend_banner_state - .banner - .as_ref() - .is_some_and(|banner| banner.banner_type == LUNA_RESERVE_BANNER) - } - - pub(crate) fn backend_banner_fallback(&mut self) -> Option { - if !self.has_chatgpt_account || !self.requires_openai_auth { - return None; - } - if self.current_model() == LUNA_RESERVE_MODEL - && self.automatic_model_switch_state.reserve_return.is_none() - { - self.automatic_model_switch_state.reserve_return = - self.thread_id().and_then(|thread_id| { - ReserveReturnModel::load(self.config.codex_home.as_path(), thread_id).or_else( - || { - // Forks inherit Reserve settings, but need their own return target: - // the parent's recovery will delete the parent's saved target. - let previous = ReserveReturnModel::load( - self.config.codex_home.as_path(), - self.forked_from?, - )?; - if self.backend_banner_state.account_id.as_deref() - != Some(previous.account_id.as_str()) - { - return None; - } - previous - .save(self.config.codex_home.as_path(), thread_id) - .ok()?; - Some(previous) - }, - ) - }); - } - if self - .automatic_model_switch_state - .reserve_return - .as_ref() - .is_some_and(|previous| { - self.backend_banner_state - .account_id - .as_ref() - .is_some_and(|account_id| account_id != &previous.account_id) - }) - { - self.clear_reserve_return(); - } - let models = self.model_catalog.try_list_models().ok()?; - if self.current_model() == LUNA_RESERVE_MODEL - && self.backend_banner_state.ordinary_usage_recovered - { - let previous = self.automatic_model_switch_state.reserve_return.as_ref()?; - if self.backend_banner_state.account_id.as_deref() != Some(previous.account_id.as_str()) - { - return None; - } - let model = models - .into_iter() - .find(|model| model.show_in_picker && model.model == previous.model)?; - return Some(AutomaticModelSwitch { - model, - effort: previous.effort.clone(), - reason: AutomaticModelSwitchReason::UsageRecovered, - }); - } - let banner = self.backend_banner_state.banner.as_ref()?; - // The backend emits this banner only after ordinary usage is exhausted and Reserve - // is available. Reserve is deliberately hidden from manual model selection. - let model = if banner.banner_type == LUNA_RESERVE_BANNER { - models.into_iter().find(|model| { - model.model == LUNA_RESERVE_MODEL - && model.model != self.current_model() - && banner - .blocked_model_slug - .as_deref() - .is_none_or(|blocked| blocked == self.current_model()) - }) - } else { - if banner.blocked_model_slug.as_deref() != Some(self.current_model()) { - return None; - } - banner.fallback_model_slugs.iter().find_map(|candidate| { - models - .iter() - .find(|model| { - model.show_in_picker - && model.model == *candidate - && model.model != self.current_model() - }) - .cloned() - }) - }?; - Some(AutomaticModelSwitch { - model, - effort: self.current_reasoning_effort(), - reason: AutomaticModelSwitchReason::UsageLimit, - }) - } - - /// Save the return target before changing server state, including before any turn is sent. - pub(crate) fn prepare_luna_reserve_return(&mut self) -> bool { - let Some((account_id, thread_id)) = self - .backend_banner_state - .account_id - .clone() - .zip(self.thread_id()) - else { - return false; - }; - let previous = ReserveReturnModel { - account_id, - model: self.current_model().to_string(), - effort: self.current_reasoning_effort(), - }; - previous - .save(self.config.codex_home.as_path(), thread_id) - .is_ok() - } - - pub(super) fn clear_reserve_return(&mut self) { - if let Some(thread_id) = self.thread_id() { - ReserveReturnModel::clear(self.config.codex_home.as_path(), thread_id); - } - self.automatic_model_switch_state = AutomaticModelSwitchState::default(); - } - - pub(crate) fn show_unavailable_reserve_recovery(&mut self) { - self.clear_reserve_return(); - // A failed switch still needs recovery actions, even if another chat used Reserve. - self.backend_banner_state.dismissed = false; - self.backend_banner_state.picker_dismissed = Arc::default(); - self.backend_banner_state.presented = None; - self.refresh_backend_banner_visibility(); - } - - /// A composer submission can already be in the app queue when a Reserve switch fails. - /// Reuse the retained prompt/steer rather than sending it on the blocked model. - pub(crate) fn defer_pending_turn_for_luna_reserve(&mut self) -> bool { - if !self.waiting_for_luna_reserve() { - return false; - } - if self.input_queue.user_turn_pending_start - && let Some(prompt) = self.safety_buffering_prompt.take() - { - self.finalize_turn(); - self.input_queue - .queued_user_messages - .push_front(QueuedUserMessage { - source: self.safety_buffering_source, - ..QueuedUserMessage::from(prompt) - }); - self.input_queue - .queued_user_message_history_records - .push_front(super::UserMessageHistoryRecord::UserMessageText); - self.refresh_pending_input_preview(); - return true; - } - !self.input_queue.pending_steers.is_empty() && self.enqueue_rejected_steer() - } - - /// Commit a successfully applied task setting and keep its recovery notice visible together. - pub(crate) fn finish_backend_banner_fallback(&mut self, mode: CollaborationMode) { - let previous_model = self.current_model().to_string(); - let reserve_return = (mode.model() == LUNA_RESERVE_MODEL) - .then(|| self.backend_banner_state.account_id.clone()) - .flatten() - .map(|account_id| ReserveReturnModel { - account_id, - model: previous_model.clone(), - effort: self.current_reasoning_effort(), - }); - let involves_reserve = - mode.model() == LUNA_RESERVE_MODEL || previous_model == LUNA_RESERVE_MODEL; - self.set_model(mode.model()); - self.set_reasoning_effort(mode.reasoning_effort()); - if mode.mode == ModeKind::Plan { - self.set_plan_mode_reasoning_effort(mode.reasoning_effort()); - } - self.set_effective_collaboration_mode(mode); - self.automatic_model_switch_state = AutomaticModelSwitchState { - reserve_return, - replaced_model: involves_reserve.then_some(previous_model), - }; - // Showing the post-switch notice is distinct from having seen the original blocked state. - self.backend_banner_state.shown = false; - self.backend_banner_state.dismissed = self.reserve_notice_already_shown(); - self.backend_banner_state.picker_dismissed = Arc::default(); - self.bottom_pane - .dismiss_view_by_id(LUNA_RESERVE_RECOVERY_VIEW_ID); - self.backend_banner_state.presented = None; - self.backend_banner_notice_model = Some(self.current_model().to_string()); - self.refresh_backend_banner_visibility(); - } - - /// A queued command may have been composed before the account read switched this task. - pub(crate) fn apply_reserve_fallback_to_pending_turn(&self, op: &mut AppCommand) { - let AppCommand::UserTurn { - model, - effort, - service_tier, - collaboration_mode, - .. - } = op - else { - return; - }; - if self.automatic_model_switch_state.replaced_model.as_deref() != Some(model.as_str()) { - return; - } - *model = self.current_model().to_string(); - *effort = self.current_reasoning_effort(); - *service_tier = self.service_tier_update_for_core(); - if let Some(mode) = collaboration_mode { - mode.settings.model = model.clone(); - mode.settings.reasoning_effort = effort.clone(); - } - } - - pub(crate) fn inherit_backend_banner_state(&mut self, previous: &mut ChatWidget) { - previous.observe_backend_banner_view(); - self.backend_banner_state = std::mem::take(&mut previous.backend_banner_state); - self.luna_reserve_notice_account_id = previous.luna_reserve_notice_account_id.take(); - self.backend_banner_state.dismissed |= self.reserve_notice_already_shown(); - // Usage belongs to the account, so switching tasks must not reset the polling cadence - // or discard the already-known limits shown by /status. - self.rate_limit_snapshots_by_limit_id = - std::mem::take(&mut previous.rate_limit_snapshots_by_limit_id); - 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; - self.backend_banner_state.presented = None; - self.refresh_backend_banner_visibility(); - } - - pub(crate) fn update_backend_banner(&mut self, response: &GetAccountRateLimitsResponse) { - self.observe_backend_banner_view(); - self.backend_banner_state.account_id = response.account_id.clone(); - // Only a full, identity-validated backend read can authorize recovery. Unknown banners - // still block it; percentages, sparse notifications and reset timestamps cannot prove it. - let has_usable_credits = response - .rate_limits - .credits - .as_ref() - .is_some_and(|credits| credits.unlimited || credits.has_credits); - self.backend_banner_state.ordinary_usage_recovered = - response.ordinary_usage_allowed.is_some() - && (response.ordinary_usage_allowed == Some(true) || has_usable_credits) - && response.rate_limit_upsell.is_none() - && response.rate_limits.spend_control_reached != Some(true) - && response.rate_limits.rate_limit_reached_type.is_none(); - if self.backend_banner_state.ordinary_usage_recovered { - self.luna_reserve_notice_account_id = None; - } - let banner = response - .rate_limit_upsell - .as_ref() - .and_then(BackendBanner::parse) - .map(|mut banner| { - banner.account_id = response.account_id.clone().unwrap_or_default(); - banner.plan_type = response.rate_limits.plan_type; - banner - }); - let same_occurrence = self - .backend_banner_state - .banner - .as_ref() - .zip(banner.as_ref()) - .is_some_and(|(old, new)| { - old.account_id == new.account_id - && old.banner_type == new.banner_type - && old.reset_at == new.reset_at - && old.presentation == new.presentation - && old.blocked_model_slug.as_ref().or(old.model_slug.as_ref()) - == new.blocked_model_slug.as_ref().or(new.model_slug.as_ref()) - && old.fallback_model_slugs == new.fallback_model_slugs - }); - self.backend_banner_state.banner = banner; - if !same_occurrence { - self.backend_banner_state.shown = false; - self.backend_banner_state.dismissed = self.reserve_notice_already_shown(); - self.backend_banner_state.picker_dismissed = Arc::default(); - self.backend_banner_notice_model = None; - } - if self.waiting_for_luna_reserve() { - self.hold_rate_limit_recovery(); - } - self.refresh_backend_banner_visibility(); - } - - fn reserve_notice_already_shown(&self) -> bool { - self.backend_banner_state - .banner - .as_ref() - .is_some_and(|banner| { - banner.banner_type == LUNA_RESERVE_BANNER - && self.luna_reserve_notice_account_id.as_deref() - == Some(banner.account_id.as_str()) - }) - } - - fn observe_backend_banner_view(&mut self) { - if self.backend_banner_state.presented.is_some() { - let (shown, dismissed) = self.bottom_pane.inline_banner_lifecycle(); - self.backend_banner_state.shown |= shown; - self.backend_banner_state.dismissed |= dismissed; - } - self.backend_banner_state.dismissed |= self - .backend_banner_state - .picker_dismissed - .load(Ordering::Relaxed); - } - - pub(super) fn refresh_backend_banner_visibility(&mut self) { - let banner = self.backend_banner_state.banner.as_ref().filter(|banner| { - // Keep recovery actions available while switching, including on older servers - // without settings/update. The copy below describes the accepted model only. - if banner.banner_type == LUNA_RESERVE_BANNER { - return !self.backend_banner_state.dismissed; - } - // Explicit fallback payloads describe the selected replacement, not a pending switch. - let matches_selected_model = match banner.blocked_model_slug.as_deref() { - Some(blocked) if !banner.fallback_model_slugs.is_empty() => { - blocked != self.current_model() - && banner - .fallback_model_slugs - .iter() - .any(|model| model == self.current_model()) - } - Some(_) | None => { - banner - .model_slug - .as_deref() - .is_none_or(|model| model == self.current_model()) - || self.backend_banner_notice_model.as_deref() == Some(self.current_model()) - } - }; - !self.backend_banner_state.dismissed && matches_selected_model - }); - if banner == self.backend_banner_state.presented.as_ref() { - return; - } - let is_reserve = banner.is_some_and(|banner| banner.banner_type == LUNA_RESERVE_BANNER); - let content = banner.map(|banner| { - let mut content = banner.actionable_banner(self.clock_format); - if banner.banner_type == LUNA_RESERVE_BANNER - && self.current_model() != LUNA_RESERVE_MODEL - { - content.title = "Usage limit reached".to_string(); - content.description = - "Your included usage is exhausted. Choose an option below to continue." - .to_string(); - } - content - }); - self.backend_banner_state.presented = banner.cloned(); - if content.is_some() { - self.bottom_pane - .dismiss_view_by_id(super::rate_limits::WORKSPACE_NUDGE_VIEW_ID); - if self - .bottom_pane - .dismiss_view_by_id(super::rate_limits::RATE_LIMIT_SWITCH_PROMPT_VIEW_ID) - { - // Replacing the view is not the user's decision to dismiss the prompt. - self.rate_limit_switch_prompt = super::RateLimitSwitchPromptState::Pending; - } - } - self.bottom_pane - .dismiss_view_by_id(LUNA_RESERVE_RECOVERY_VIEW_ID); - self.clear_security_setup_banner(); - match (is_reserve, content) { - (true, Some(content)) => { - self.bottom_pane.set_inline_banner(/*banner*/ None); - let mut params: SelectionViewParams = content.into(); - params.view_id = Some(LUNA_RESERVE_RECOVERY_VIEW_ID); - if self.current_model() == LUNA_RESERVE_MODEL { - self.luna_reserve_notice_account_id = - self.backend_banner_state.account_id.clone(); - // Continuing is a local dismissal, separate from the backend's purchase CTAs. - params.items.push(SelectionItem { - name: "Continue with Luna Reserve".to_string(), - ..Default::default() - }); - let list_keymap = self.bottom_pane.list_keymap(); - params.footer_hint = Some(accept_cancel_hint_line( - list_keymap.primary_hint(ListAction::Accept), - "to confirm", - list_keymap.primary_hint(ListAction::Cancel), - "to continue working", - )); - } - // Use the standard focused picker: arrows/Enter and numeric shortcuts select, - // Escape returns to the unchanged composer and its saved draft. - let dismissed = Arc::clone(&self.backend_banner_state.picker_dismissed); - params.on_cancel = - Some(Box::new(move |_| dismissed.store(true, Ordering::Relaxed))); - for item in &mut params.items { - item.dismiss_on_select = true; - let dismissed = Arc::clone(&self.backend_banner_state.picker_dismissed); - item.actions - .push(Box::new(move |_| dismissed.store(true, Ordering::Relaxed))); - } - self.backend_banner_state.shown = true; - self.bottom_pane.show_selection_view(params); - } - (_, content) => self.bottom_pane.set_inline_banner(content), - } - if self.backend_banner_state.presented.is_none() - && !self.bottom_pane.is_task_running() - && self.bottom_pane.no_modal_or_popup_active() - { - self.maybe_show_pending_rate_limit_prompt(); - } - } - - pub(super) fn sync_backend_banner_view(&mut self) { - self.observe_backend_banner_view(); - self.refresh_backend_banner_visibility(); - } - - pub(super) fn dismiss_backend_banner_for_new_turn(&mut self) { - self.observe_backend_banner_view(); - if self.backend_banner_state.shown - && self - .backend_banner_state - .presented - .as_ref() - .is_some_and(|banner| banner.presentation == BannerPresentation::Dismissible) - { - self.backend_banner_state.dismissed = true; - self.refresh_backend_banner_visibility(); - } - } - - pub(super) fn has_applicable_backend_banner(&self) -> bool { - !self.backend_banner_state.dismissed && self.backend_banner_state.presented.is_some() - } - - pub(crate) fn clear_backend_banner(&mut self) { - self.clear_security_setup_banner(); - self.backend_banner_state = BackendBannerState::default(); - self.backend_banner_notice_model = None; - self.bottom_pane - .dismiss_view_by_id(LUNA_RESERVE_RECOVERY_VIEW_ID); - self.bottom_pane.set_inline_banner(/*banner*/ None); - } -} diff --git a/codex-rs/tui/src/chatwidget/luna_reserve_model.rs b/codex-rs/tui/src/chatwidget/luna_reserve_model.rs deleted file mode 100644 index 859ea8d7..00000000 --- a/codex-rs/tui/src/chatwidget/luna_reserve_model.rs +++ /dev/null @@ -1,67 +0,0 @@ -//! The Reserve-only /model picker uses normal-model metadata while keeping Reserve routing. - -use super::*; -use crate::bottom_pane::popup_consts::picker_hint_line_for_keymap; -use crate::model_catalog::LUNA_MODEL; -use crate::model_catalog::LUNA_RESERVE_MODEL; - -impl ChatWidget { - pub(super) fn open_luna_reserve_model_popup( - &mut self, - presets: Vec, - view_id: &'static str, - ) { - let normal_model_slug = self - .rate_limit_snapshots_by_limit_id - .values() - .find(|snapshot| snapshot.limit_name == LUNA_RESERVE_MODEL) - .and_then(|snapshot| snapshot.normal_model_slug.as_deref()); - let preset = normal_model_slug - .and_then(|slug| presets.iter().find(|preset| preset.model == slug)) - .or_else(|| presets.iter().find(|preset| preset.model == LUNA_MODEL)); - let Some(mut preset) = preset.cloned() else { - self.bottom_pane.dismiss_view_by_id(view_id); - self.add_info_message( - "Luna model settings are unavailable; please try /model again in a moment." - .to_string(), - /*hint*/ None, - ); - return; - }; - - // Only borrow the normal model's presentation and supported efforts. Selecting an - // effort must keep the authorized Reserve model and the saved ordinary return target. - preset.model = LUNA_RESERVE_MODEL.to_string(); - let single_supported_effort = preset.supported_reasoning_efforts.len() == 1; - let name = preset.display_name.clone(); - let description = (!preset.description.is_empty()).then_some(preset.description.clone()); - let scoped = self.scope_model_picker_event(); - let actions: Vec = vec![Box::new(move |tx| { - tx.send(scoped(AppEvent::OpenReasoningPopup { - model: preset.clone(), - })); - })]; - let header = self.model_menu_header( - "Select Model", - "Other models return when ordinary usage is available again.", - ); - self.show_model_selection_view( - vec![LUNA_RESERVE_MODEL.to_string()], - SelectionViewParams { - view_id: Some(view_id), - header, - footer_hint: Some(picker_hint_line_for_keymap(&self.bottom_pane.list_keymap())), - items: vec![SelectionItem { - name, - description, - is_current: true, - actions, - dismiss_on_select: single_supported_effort, - dismiss_parent_on_child_accept: !single_supported_effort, - ..Default::default() - }], - ..SelectionViewParams::picker() - }, - ); - } -} diff --git a/codex-rs/tui/src/chatwidget/luna_reserve_return.rs b/codex-rs/tui/src/chatwidget/luna_reserve_return.rs deleted file mode 100644 index 36a7da02..00000000 --- a/codex-rs/tui/src/chatwidget/luna_reserve_return.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Persist the account-bound return model for a task before automatically entering Reserve. -//! Task IDs scope the cache across reconnects/resumes without changing global model defaults. - -use codex_protocol::ThreadId; -use codex_protocol::openai_models::ReasoningEffort; -use serde::Deserialize; -use serde::Serialize; -use std::io; -use std::io::Read; -use std::path::Path; -use std::path::PathBuf; - -#[derive(Clone, Serialize, Deserialize)] -pub(super) struct ReserveReturnModel { - pub account_id: String, - pub model: String, - pub effort: Option, -} - -impl ReserveReturnModel { - fn path(codex_home: &Path, thread_id: ThreadId) -> PathBuf { - codex_home - .join("tui-luna-reserve") - .join(format!("{thread_id}.json")) - } - - pub(super) fn load(codex_home: &Path, thread_id: ThreadId) -> Option { - let file = std::fs::File::open(Self::path(codex_home, thread_id)).ok()?; - // A corrupt or unrelated cache file must not cause an unbounded read. - serde_json::from_reader(file.take(/*limit*/ 4096)).ok() - } - - pub(super) fn save(&self, codex_home: &Path, thread_id: ThreadId) -> io::Result<()> { - let path = Self::path(codex_home, thread_id); - let directory = path.parent().ok_or(io::ErrorKind::InvalidInput)?; - std::fs::create_dir_all(directory)?; - let mut file = tempfile::NamedTempFile::new_in(directory)?; - serde_json::to_writer(&mut file, self)?; - file.as_file().sync_all()?; - file.persist(path).map_err(|error| error.error)?; - Ok(()) - } - - pub(super) fn clear(codex_home: &Path, thread_id: ThreadId) { - // A missing cache needs no cleanup; the live model is authoritative after leaving Reserve. - let _ = std::fs::remove_file(Self::path(codex_home, thread_id)); - } -} diff --git a/codex-rs/tui/src/chatwidget/reset_credits.rs b/codex-rs/tui/src/chatwidget/reset_credits.rs deleted file mode 100644 index 8128d543..00000000 --- a/codex-rs/tui/src/chatwidget/reset_credits.rs +++ /dev/null @@ -1,79 +0,0 @@ -use crate::clock_format::ClockFormat; -use chrono::DateTime; -use chrono::Local; -use chrono::Utc; -use codex_app_server_protocol::RateLimitResetCreditStatus; -use codex_app_server_protocol::RateLimitResetCreditsSummary; - -#[derive(Debug, Eq, PartialEq)] -pub(super) struct ResetCreditOption { - pub(super) credit_id: Option, - pub(super) name: String, - pub(super) detail: Option, - pub(super) description: String, -} - -pub(super) fn reset_credit_options( - summary: &RateLimitResetCreditsSummary, - clock_format: ClockFormat, -) -> Vec { - let available_count = summary.available_count.max(0); - let detail_limit = usize::try_from(available_count).unwrap_or(usize::MAX); - let mut available_credits = summary - .credits - .as_deref() - .unwrap_or_default() - .iter() - .filter(|credit| credit.status == RateLimitResetCreditStatus::Available) - .collect::>(); - available_credits.sort_by_key(|credit| credit.expires_at.unwrap_or(i64::MAX)); - - let mut options = available_credits - .into_iter() - .take(detail_limit) - .map(|credit| { - let expiration = match credit.expires_at { - Some(expires_at) => DateTime::::from_timestamp(expires_at, 0) - .map(|expires_at| { - let expires_at = expires_at.with_timezone(&Local); - format!( - "Expires {} on {}", - expires_at.format(clock_format.time_format()), - expires_at.format("%-d %b %Y") - ) - }) - .unwrap_or_else(|| "Expiration unavailable".to_string()), - None => "Does not expire".to_string(), - }; - let reset_title = credit - .title - .as_deref() - .map(str::trim) - .filter(|title| !title.is_empty()) - .unwrap_or("Full reset"); - let reset_description = credit - .description - .as_deref() - .map(str::trim) - .filter(|description| !description.is_empty()) - .unwrap_or("Reset your current usage limits"); - ResetCreditOption { - credit_id: Some(credit.id.clone()), - name: reset_title.to_string(), - detail: Some(expiration), - description: reset_description.to_string(), - } - }) - .collect::>(); - - if options.is_empty() { - options.push(ResetCreditOption { - credit_id: None, - name: "Full reset".to_string(), - detail: None, - description: "Reset your current usage limits".to_string(), - }); - } - - options -} diff --git a/codex-rs/tui/src/chatwidget/tests/backend_banners_tests.rs b/codex-rs/tui/src/chatwidget/tests/backend_banners_tests.rs deleted file mode 100644 index 1f6b4d0f..00000000 --- a/codex-rs/tui/src/chatwidget/tests/backend_banners_tests.rs +++ /dev/null @@ -1,438 +0,0 @@ -use super::*; -use codex_app_server_protocol::GetAccountRateLimitsResponse; -use pretty_assertions::assert_eq; -use serde_json::json; - -fn banner_response( - presentation: Option<&str>, - ctas: serde_json::Value, -) -> GetAccountRateLimitsResponse { - let mut banner = json!({ - "banner_type": "selected_model_limit", "model_slug": "test-model-a", - "title": "Selected model usage exhausted", - "description": "Ask your owner for credits or switch to another model.", "ctas": ctas, - }); - if let Some(presentation) = presentation { - banner["presentation"] = json!(presentation); - } - GetAccountRateLimitsResponse { - ordinary_usage_allowed: None, - account_id: Some("workspace-a".into()), - rate_limit_upsell: Some(banner), - rate_limits: snapshot(/*percent*/ 25.0), - rate_limits_by_limit_id: None, - rate_limit_reset_credits: None, - } -} - -#[tokio::test] -async fn backend_banner_presentation_and_cta_do_not_imply_recovery() { - for presentation in [None, Some("inline"), Some("dismissible")] { - let (mut chat, mut rx, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - let mut response = banner_response( - presentation, - json!([{"action":"notify_owner","label":"Notify owner"}]), - ); - if presentation == Some("inline") { - use chrono::Timelike; - chat.clock_format = crate::clock_format::ClockFormat::TwelveHour; - let banner = response.rate_limit_upsell.as_mut().unwrap(); - banner["description"] = - json!("Your usage resets at {time}. Ask your owner for credits."); - banner["reset_at"] = json!( - chrono::Local::now() - .with_hour(17) - .unwrap() - .with_minute(30) - .unwrap() - .timestamp() - ); - } - chat.update_backend_banner(&response); - let initial = render_bottom_popup(&chat, /*width*/ 70); - assert!(initial.contains("Selected model usage exhausted")); - assert_eq!( - initial.contains("esc to dismiss"), - presentation == Some("dismissible") - ); - chat.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); - assert!( - rx.try_recv() - .is_ok_and(|event| matches!(event, AppEvent::SendAddCreditsNudgeEmail { .. })) - ); - assert_eq!(render_bottom_popup(&chat, /*width*/ 70), initial); - let request_id = chat - .start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::Credits) - .expect("start notification"); - if presentation == Some("inline") { - insta::assert_snapshot!( - "backend_banner_notification", - normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 70)) - ); - } - chat.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); - assert!( - rx.try_recv() - .is_ok_and(|event| matches!(event, AppEvent::SendAddCreditsNudgeEmail { .. })) - ); - assert_eq!(chat.composer_text_with_pending(), ""); - assert!( - chat.start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::Credits) - .is_none() - ); - chat.finish_add_credits_nudge_email_request(request_id, Err("local failure".into())); - chat.update_backend_banner(&response); - assert_eq!(render_bottom_popup(&chat, /*width*/ 70), initial); - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert_eq!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted"), - presentation != Some("dismissible") - ); - chat.set_model("test-model-b"); - assert!(!chat.has_applicable_backend_banner()); - assert!( - !render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted") - ); - chat.set_model("test-model-a"); - assert_eq!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted"), - presentation != Some("dismissible") - ); - } -} - -#[tokio::test] -async fn backend_banner_zero_actions_preserve_guidance_and_composer_input() { - for presentation in [None, Some("inline"), Some("dismissible")] { - for ctas in [ - json!([]), - json!([{"action":"future_action","label":"Unsupported"}]), - ] { - let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - chat.update_backend_banner(&banner_response(presentation, ctas)); - let rendered = render_bottom_popup(&chat, /*width*/ 70); - assert!(rendered.contains("Selected model usage exhausted")); - assert!(rendered.contains("switch to another model")); - assert!(!rendered.to_lowercase().contains("no matches")); - assert!(!rendered.contains("Press a number")); - assert_eq!( - rendered.contains("esc to dismiss"), - presentation == Some("dismissible") - ); - if presentation == Some("dismissible") { - insta::assert_snapshot!( - "backend_banner_information_dismissible", - normalize_snapshot_paths(rendered) - ); - } else { - insta::assert_snapshot!( - "backend_banner_information_only", - normalize_snapshot_paths(rendered) - ); - } - chat.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); - // An ordinary navigation key flushes the composer's pending first-character buffer. - chat.handle_key_event(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); - assert_eq!(chat.composer_text_with_pending(), "1"); - } - } -} - -#[tokio::test] -async fn backend_banner_dismissal_tracks_occurrence_not_copy_or_model() { - let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - let mut response = banner_response(Some("dismissible"), json!([])); - chat.update_backend_banner(&response); - assert!(render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted")); - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - chat.set_model("test-model-b"); - response.rate_limit_upsell.as_mut().unwrap()["description"] = json!("Updated backend copy"); - chat.update_backend_banner(&response); - chat.set_model("test-model-a"); - assert!(!render_bottom_popup(&chat, /*width*/ 70).contains("Updated backend copy")); - response.rate_limit_upsell.as_mut().unwrap()["reset_at"] = json!(2000000000); - chat.update_backend_banner(&response); - assert!(render_bottom_popup(&chat, /*width*/ 70).contains("Updated backend copy")); - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - let mut absent = response.clone(); - absent.rate_limit_upsell = None; - chat.update_backend_banner(&absent); - chat.update_backend_banner(&response); - assert!(render_bottom_popup(&chat, /*width*/ 70).contains("Updated backend copy")); -} - -#[tokio::test] -async fn backend_banner_occurrence_uses_explicit_or_legacy_source_model() { - for explicit_source in [false, true] { - let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - let mut response = banner_response(Some("dismissible"), json!([])); - if explicit_source { - response.rate_limit_upsell.as_mut().unwrap()["blocked_model_slug"] = - json!("test-model-a"); - } - chat.update_backend_banner(&response); - assert!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted") - ); - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - response.rate_limit_upsell.as_mut().unwrap()["model_slug"] = json!("test-model-b"); - chat.update_backend_banner(&response); - chat.set_model("test-model-b"); - assert_eq!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted"), - !explicit_source - ); - } -} - -#[tokio::test] -async fn backend_banner_turn_on_another_model_preserves_hidden_occurrence() { - let (mut chat, _rx, mut ops) = make_chatwidget_manual(Some("test-model-a")).await; - chat.thread_id = Some(ThreadId::new()); - chat.update_backend_banner(&banner_response(Some("dismissible"), json!([]))); - assert!(render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted")); - chat.set_model("test-model-b"); - assert!(!render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted")); - chat.submit_user_message(UserMessage::from("hello")); - assert!( - ops.try_recv() - .is_ok_and(|op| matches!(op, Op::UserTurn { .. })) - ); - handle_turn_started(&mut chat, "turn-1"); - handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None); - chat.set_model("test-model-a"); - assert!(render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted")); -} - -#[tokio::test] -async fn backend_banner_restores_only_programmatically_displaced_switch_prompt() { - for user_dismissed in [false, true] { - let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("gpt-5")).await; - chat.has_chatgpt_account = true; - chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0))); - chat.maybe_show_pending_rate_limit_prompt(); - assert!(render_bottom_popup(&chat, /*width*/ 90).contains("Approaching rate limits")); - if user_dismissed { - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - } - let mut response = banner_response(Some("inline"), json!([])); - response.rate_limit_upsell.as_mut().unwrap()["model_slug"] = json!("gpt-5"); - chat.update_backend_banner(&response); - assert!( - render_bottom_popup(&chat, /*width*/ 90).contains("Selected model usage exhausted") - ); - response.rate_limit_upsell = None; - chat.update_backend_banner(&response); - assert_eq!( - render_bottom_popup(&chat, /*width*/ 90).contains("Approaching rate limits"), - !user_dismissed - ); - } -} - -#[tokio::test] -async fn owner_notification_completion_cannot_cross_account_change() { - let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await; - let previous = chat - .start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::Credits) - .expect("start previous account request"); - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ true, /*has_codex_backend_auth*/ true, - ); - let current = chat - .start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::UsageLimit) - .expect("new account must be actionable"); - drain_insert_history(&mut rx); - chat.finish_add_credits_nudge_email_request(previous, Ok(AddCreditsNudgeEmailStatus::Sent)); - assert!(drain_insert_history(&mut rx).is_empty()); - assert!( - chat.start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::UsageLimit) - .is_none() - ); - chat.finish_add_credits_nudge_email_request(current, Ok(AddCreditsNudgeEmailStatus::Sent)); - let rendered = drain_insert_history(&mut rx) - .into_iter() - .map(|lines| lines_to_single_string(&lines)) - .collect::(); - insta::assert_snapshot!("owner_notification_after_account_change", rendered); -} - -#[tokio::test] -async fn backend_banner_new_turn_dismisses_only_shown_dismissible_content() { - for (presentation, show_before_submit) in [ - (None, true), - (Some("inline"), true), - (Some("dismissible"), true), - (Some("dismissible"), false), - ] { - let (mut chat, _rx, mut ops) = make_chatwidget_manual(Some("test-model-a")).await; - chat.thread_id = Some(ThreadId::new()); - chat.update_backend_banner(&banner_response(presentation, json!([]))); - if show_before_submit { - assert!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted") - ); - } - chat.submit_user_message(UserMessage::from("hello")); - assert!( - ops.try_recv() - .is_ok_and(|op| matches!(op, Op::UserTurn { .. })) - ); - handle_turn_started(&mut chat, "turn-1"); - handle_turn_completed(&mut chat, "turn-1", /*duration_ms*/ None); - assert_eq!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted"), - !(presentation == Some("dismissible") && show_before_submit) - ); - } -} - -#[tokio::test] -async fn backend_banner_invalid_content_and_absence_restore_fallback() { - for replacement in [ - serde_json::Value::Null, - json!({"presentation":"future_mode"}), - json!({"presentation":null}), - json!({"title":" "}), - ] { - let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - let mut response = banner_response(Some("inline"), json!([])); - chat.update_backend_banner(&response); - assert!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted") - ); - if replacement.is_null() { - response.rate_limit_upsell = None; - } else { - for (key, value) in replacement.as_object().unwrap() { - response.rate_limit_upsell.as_mut().unwrap()[key.as_str()] = value.clone(); - } - } - chat.update_backend_banner(&response); - assert!(!chat.has_applicable_backend_banner()); - chat.codex_rate_limit_reached_type = - Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted); - chat.on_rate_limit_error(RateLimitErrorKind::Generic, "limit".into()); - assert!(render_bottom_popup(&chat, /*width*/ 90).contains("workspace owner")); - } -} - -#[tokio::test] -async fn backend_banner_fallback_candidates_and_notice_follow_selected_model() { - let (mut chat, _events, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - chat.has_chatgpt_account = true; - let template = chat.model_catalog.try_list_models().unwrap()[0].clone(); - let models = ["hidden-model", "test-model-b", "test-model-c"].map(|model| ModelPreset { - model: model.into(), - show_in_picker: model != "hidden-model", - ..template.clone() - }); - chat.model_catalog = Arc::new(ModelCatalog::new(models.to_vec())); - let mut response = banner_response(Some("inline"), json!([])); - response.rate_limit_upsell.as_mut().unwrap()["blocked_model_slug"] = json!("test-model-a"); - 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().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); - chat.requires_openai_auth = true; - let mut mode = chat.effective_collaboration_mode(); - mode.settings.model = "test-model-c".into(); - chat.finish_backend_banner_fallback(mode); - let before = render_bottom_popup(&chat, /*width*/ 70); - assert!(before.contains("Selected model usage exhausted")); - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!(render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted")); - assert_eq!(chat.backend_banner_fallback(), None); - let (mut other_task, _events, _ops) = make_chatwidget_manual(Some("test-model-c")).await; - other_task.inherit_backend_banner_state(&mut chat); - assert!( - render_bottom_popup(&other_task, /*width*/ 70).contains("Selected model usage exhausted") - ); - other_task.set_model("test-model-a"); - assert!( - !render_bottom_popup(&other_task, /*width*/ 70).contains("Selected model usage exhausted") - ); - other_task.set_model("unrelated-model"); - assert!( - !render_bottom_popup(&other_task, /*width*/ 70).contains("Selected model usage exhausted") - ); - other_task.set_model("test-model-c"); - assert!( - render_bottom_popup(&other_task, /*width*/ 70).contains("Selected model usage exhausted") - ); -} - -#[tokio::test] -async fn backend_banner_sparse_updates_preserve_visible_and_dismissed_occurrences() { - for dismiss in [false, true] { - let (mut chat, _events, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - chat.update_backend_banner(&banner_response(Some("dismissible"), json!([]))); - assert!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted") - ); - if dismiss { - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - } - let before = render_bottom_popup(&chat, /*width*/ 70); - chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 60.0)); - assert_eq!(render_bottom_popup(&chat, /*width*/ 70), before); - // A model-scoped banner can coexist with an absent aggregate reached type. - let mut exhausted = snapshot(/*percent*/ 100.0); - exhausted.rate_limit_reached_type = - Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted); - chat.on_rolling_rate_limit_snapshot(exhausted); - assert_eq!(render_bottom_popup(&chat, /*width*/ 70), before); - } -} - -#[tokio::test] -async fn backend_banner_changed_remedy_keeps_fallback_until_applicable_replacement() { - for rolling_update in [false, true] { - let (mut chat, _events, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - let mut credits = snapshot(/*percent*/ 100.0); - credits.rate_limit_reached_type = - Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted); - chat.on_rate_limit_snapshot(Some(credits)); - let mut response = banner_response( - Some("inline"), - json!([{"action":"notify_owner","label":"Notify owner"}]), - ); - chat.update_backend_banner(&response); - assert!(render_bottom_popup(&chat, /*width*/ 90).contains("Notify owner")); - let mut cap = snapshot(/*percent*/ 100.0); - cap.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached); - if rolling_update { - chat.on_rolling_rate_limit_snapshot(cap); - } - chat.on_rate_limit_error(RateLimitErrorKind::UsageLimit, "Usage cap reached".into()); - assert!( - render_bottom_popup(&chat, /*width*/ 90) - .contains("Request a limit increase from your owner") - ); - response.rate_limit_upsell.as_mut().unwrap()["title"] = - json!("Workspace spending cap reached"); - response.rate_limit_upsell.as_mut().unwrap()["ctas"] = - json!([{"action":"request_increase","label":"Request more usage"}]); - chat.update_backend_banner(&response); - let rendered = render_bottom_popup(&chat, /*width*/ 90); - assert!( - rendered.contains("Workspace spending cap reached"), - "{rendered}" - ); - assert!(rendered.contains("Request more usage")); - assert!(!rendered.contains("Request a limit increase from your owner")); - chat.set_model("test-model-b"); - chat.on_rate_limit_error(RateLimitErrorKind::UsageLimit, "Usage cap reached".into()); - assert!( - render_bottom_popup(&chat, /*width*/ 90) - .contains("Request a limit increase from your owner") - ); - } -} diff --git a/codex-rs/tui/src/chatwidget/tests/luna_reserve_usage_tests.rs b/codex-rs/tui/src/chatwidget/tests/luna_reserve_usage_tests.rs deleted file mode 100644 index 8ff7c234..00000000 --- a/codex-rs/tui/src/chatwidget/tests/luna_reserve_usage_tests.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! 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/settings/usage?credits_modal=true"), - ), - ( - vec![KeyCode::Char('1')], - Some("https://chatgpt.com/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::>(); - 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::>()); - 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); - }); - } -} diff --git a/codex-rs/tui/src/chatwidget/tests/rate_limit_recovery_tests.rs b/codex-rs/tui/src/chatwidget/tests/rate_limit_recovery_tests.rs deleted file mode 100644 index 53d61827..00000000 --- a/codex-rs/tui/src/chatwidget/tests/rate_limit_recovery_tests.rs +++ /dev/null @@ -1,65 +0,0 @@ -use super::*; -use pretty_assertions::assert_eq; - -#[tokio::test] -async fn rate_limit_recovery_holds_submissions_until_model_change() { - let (mut chat, mut events, mut ops) = make_chatwidget_manual(Some("test-model-a")).await; - set_chatgpt_auth(&mut chat); - chat.thread_id = Some(ThreadId::new()); - handle_turn_started(&mut chat, "failed-turn"); - chat.queue_user_message(UserMessage::from("queued follow-up")); - chat.on_rate_limit_error(RateLimitErrorKind::UsageLimit, "Usage exhausted".into()); - assert!( - std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!( - event, - AppEvent::RefreshRateLimits { - origin: crate::app_event::RateLimitRefreshOrigin::Recovery - } - )) - ); - chat.submit_user_message(UserMessage::from("submitted during recovery")); - assert_no_submit_op(&mut ops); - assert_eq!( - chat.queued_user_message_texts(), - vec!["queued follow-up", "submitted during recovery"] - ); - - chat.set_model("test-model-b"); - chat.finish_rate_limit_recovery(); - let Op::UserTurn { model, items, .. } = next_submit_op(&mut ops) else { - panic!("expected queued follow-up on the fallback model"); - }; - assert_eq!(model, "test-model-b"); - assert!( - matches!(items.as_slice(), [UserInput::Text { text, .. }] if text == "queued follow-up") - ); - assert_eq!( - chat.queued_user_message_texts(), - vec!["submitted during recovery"] - ); - chat.finish_rate_limit_recovery(); - assert_no_submit_op(&mut ops); -} - -#[tokio::test] -async fn rate_limit_recovery_preserves_settings_hold_and_clears_on_account_change() { - let (mut chat, _events, mut ops) = make_chatwidget_manual(Some("test-model-a")).await; - set_chatgpt_auth(&mut chat); - chat.thread_id = Some(ThreadId::new()); - chat.set_queue_autosend_suppressed(/*suppressed*/ true); - chat.on_rate_limit_error(RateLimitErrorKind::UsageLimit, "Usage exhausted".into()); - chat.queue_user_message(UserMessage::from("queued follow-up")); - chat.finish_rate_limit_recovery(); - assert_no_submit_op(&mut ops); - assert!(chat.input_queue.suppress_queue_autosend); - assert!(!chat.input_queue.rate_limit_recovery_pending); - - chat.on_rate_limit_error(RateLimitErrorKind::UsageLimit, "Usage exhausted".into()); - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ false, - ); - assert!(!chat.input_queue.rate_limit_recovery_pending); - assert_eq!(chat.queued_user_message_texts(), vec!["queued follow-up"]); - assert_no_submit_op(&mut ops); -} diff --git a/codex-rs/tui/src/chatwidget/tests/usage.rs b/codex-rs/tui/src/chatwidget/tests/usage.rs deleted file mode 100644 index 18cffed0..00000000 --- a/codex-rs/tui/src/chatwidget/tests/usage.rs +++ /dev/null @@ -1,1127 +0,0 @@ -use super::super::reset_credits::ResetCreditOption; -use super::super::reset_credits::reset_credit_options; -use super::*; -use chrono::TimeZone; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse; -use codex_app_server_protocol::RateLimitResetCredit; -use codex_app_server_protocol::RateLimitResetCreditStatus; -use codex_app_server_protocol::RateLimitResetCreditsSummary; -use codex_app_server_protocol::RateLimitResetType; -use pretty_assertions::assert_eq; -use uuid::Uuid; - -const TEST_OVERLAY_VIEW_ID: &str = "usage-test-overlay"; - -#[tokio::test] -async fn usage_menu_opens_analytics() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - chat.dispatch_command(SlashCommand::Usage); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_matches!(rx.try_recv(), Ok(AppEvent::OpenAnalytics { view: None })); -} - -fn reset_credits(available_count: i64) -> RateLimitResetCreditsSummary { - RateLimitResetCreditsSummary { - available_count, - credits: None, - } -} - -fn detailed_reset_credits( - available_count: i64, - credits: Vec, -) -> RateLimitResetCreditsSummary { - RateLimitResetCreditsSummary { - available_count, - credits: Some(credits), - } -} - -fn reset_credit(id: &str, expires_at: Option) -> RateLimitResetCredit { - RateLimitResetCredit { - id: id.to_string(), - reset_type: RateLimitResetType::CodexRateLimits, - status: RateLimitResetCreditStatus::Available, - granted_at: 0, - expires_at, - title: None, - description: None, - } -} - -fn reset_credit_with_title(id: &str, expires_at: Option, title: &str) -> RateLimitResetCredit { - RateLimitResetCredit { - title: Some(title.to_string()), - ..reset_credit(id, expires_at) - } -} - -fn expiry_timestamp(day: u32, hour: u32, minute: u32) -> i64 { - chrono::Local - .with_ymd_and_hms(2026, 6, day, hour, minute, 0) - .single() - .expect("valid test timestamp") - .timestamp() -} - -fn show_rate_limit_reset_confirmation_from_event( - chat: &mut ChatWidget, - rx: &mut tokio::sync::mpsc::UnboundedReceiver, -) -> u64 { - let Ok(AppEvent::OpenRateLimitResetConfirmation { - picker_request_id, - confirmation_gate, - credit_id, - reset_title, - reset_detail, - reset_description, - }) = rx.try_recv() - else { - panic!("expected reset confirmation event"); - }; - assert!(chat.show_rate_limit_reset_confirmation( - picker_request_id, - confirmation_gate, - credit_id, - reset_title, - reset_detail, - reset_description, - )); - picker_request_id -} - -#[test] -fn reset_credit_options_use_generic_copy_when_backend_copy_is_missing() { - let mut credit = reset_credit("future-credit", /*expires_at*/ None); - credit.reset_type = RateLimitResetType::Unknown; - - assert_eq!( - reset_credit_options( - &detailed_reset_credits(/*available_count*/ 1, vec![credit],), - crate::clock_format::ClockFormat::TwentyFourHour - ), - vec![ResetCreditOption { - credit_id: Some("future-credit".to_string()), - name: "Full reset".to_string(), - detail: Some("Does not expire".to_string()), - description: "Reset your current usage limits".to_string(), - }] - ); -} - -#[tokio::test] -async fn usage_command_opens_menu_when_reset_is_available_snapshot() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - - chat.dispatch_command(SlashCommand::Usage); - - assert_chatwidget_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 })); -} - -#[tokio::test] -async fn usage_command_disables_reset_after_cached_zero_snapshot() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 0)), - )); - - chat.dispatch_command(SlashCommand::Usage); - - assert_chatwidget_snapshot!( - "usage_command_menu_without_resets", - render_bottom_popup(&chat, /*width*/ 80) - ); - assert_matches!( - rx.try_recv(), - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::UsageMenu { request_id: 1 } - }) - ); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_matches!(rx.try_recv(), Ok(AppEvent::OpenAnalytics { view: None })); -} - -#[tokio::test] -async fn usage_menu_refresh_enables_newly_available_reset() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 0)), - )); - - chat.dispatch_command(SlashCommand::Usage); - assert_matches!( - rx.try_recv(), - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::UsageMenu { request_id: 1 } - }) - ); - chat.finish_usage_menu_rate_limit_refresh( - /*request_id*/ 1, - Vec::new(), - Ok(reset_credits(/*available_count*/ 1)), - ); - chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - assert_matches!(rx.try_recv(), Ok(AppEvent::OpenRateLimitResetCredits)); -} - -#[tokio::test] -async fn usage_menu_refresh_failure_preserves_disabled_known_zero() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 0)), - )); - - chat.dispatch_command(SlashCommand::Usage); - assert_matches!( - rx.try_recv(), - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::UsageMenu { request_id: 1 } - }) - ); - chat.finish_usage_menu_rate_limit_refresh( - /*request_id*/ 1, - Vec::new(), - Err("backend unavailable".to_string()), - ); - - 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 })); -} - -#[tokio::test] -async fn account_update_invalidates_usage_menu_refresh_when_visible_state_is_unchanged() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let startup_request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - startup_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 0)), - )); - chat.dispatch_command(SlashCommand::Usage); - assert_matches!( - rx.try_recv(), - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::UsageMenu { request_id: 1 } - }) - ); - - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ true, /*has_codex_backend_auth*/ true, - ); - chat.finish_usage_menu_rate_limit_refresh( - /*request_id*/ 1, - vec![snapshot(/*percent*/ 92.0)], - Ok(reset_credits(/*available_count*/ 2)), - ); - - assert_eq!(chat.available_rate_limit_reset_credits, None); - assert!(chat.rate_limit_snapshots_by_limit_id.is_empty()); - assert!(chat.bottom_pane.no_modal_or_popup_active()); -} - -#[tokio::test] -async fn usage_command_can_check_reset_availability_before_startup_refresh_finishes_snapshot() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - chat.start_rate_limit_reset_startup_check(); - - chat.dispatch_command(SlashCommand::Usage); - - assert_chatwidget_snapshot!( - "usage_command_menu_before_reset_refresh", - render_bottom_popup(&chat, /*width*/ 80) - ); - chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_matches!(rx.try_recv(), Ok(AppEvent::OpenRateLimitResetCredits)); -} - -#[tokio::test] -async fn usage_command_can_check_reset_availability_for_workspace_accounts() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - chat.plan_type = Some(PlanType::Business); - - chat.dispatch_command(SlashCommand::Usage); - - chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_matches!(rx.try_recv(), Ok(AppEvent::OpenRateLimitResetCredits)); -} - -#[tokio::test] -async fn usage_menu_rate_limit_reset_entry_opens_reset_flow() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - chat.dispatch_command(SlashCommand::Usage); - - chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - assert_matches!(rx.try_recv(), Ok(AppEvent::OpenRateLimitResetCredits)); -} - -#[tokio::test] -async fn rate_limit_reset_popup_states_snapshot() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let mut states = Vec::new(); - - let loading_request_id = chat.show_rate_limit_reset_loading_popup(); - record_popup(&chat, &mut states); - let first_expiry = expiry_timestamp(/*day*/ 18, /*hour*/ 9, /*minute*/ 39); - let second_expiry = expiry_timestamp(/*day*/ 27, /*hour*/ 8, /*minute*/ 59); - let mut rate_limit_snapshot = snapshot(/*percent*/ 50.0); - rate_limit_snapshot.limit_id = Some("codex".to_string()); - rate_limit_snapshot - .primary - .as_mut() - .expect("primary window") - .window_duration_mins = Some(5 * 60); - rate_limit_snapshot.secondary = Some(RateLimitWindow { - used_percent: 50, - window_duration_mins: Some(7 * 24 * 60), - resets_at: None, - }); - assert!(chat.finish_rate_limit_reset_credits_refresh( - loading_request_id, - vec![rate_limit_snapshot], - Ok(detailed_reset_credits( - /*available_count*/ 2, - vec![ - reset_credit_with_title( - "credit-2", - Some(second_expiry), - "Full reset (Weekly + 5 hr)", - ), - reset_credit_with_title( - "credit-1", - Some(first_expiry), - "Full reset (Weekly + 5 hr)", - ), - ], - )), - )); - record_popup(&chat, &mut states); - - dismiss_popup(&mut chat); - let empty_request_id = chat.show_rate_limit_reset_loading_popup(); - assert!(chat.finish_rate_limit_reset_credits_refresh( - empty_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 0)), - )); - record_popup(&chat, &mut states); - - dismiss_popup(&mut chat); - let load_error_request_id = chat.show_rate_limit_reset_loading_popup(); - assert!(chat.finish_rate_limit_reset_credits_refresh( - load_error_request_id, - Vec::new(), - Err("backend unavailable".to_string()), - )); - record_popup(&chat, &mut states); - - dismiss_popup(&mut chat); - let consuming_request_id = chat.show_rate_limit_reset_consuming_popup(); - record_popup(&chat, &mut states); - assert!(!chat.finish_rate_limit_reset_consume( - consuming_request_id, - "redeem-1".to_string(), - /*credit_id*/ None, - Err("request timed out".to_string()), - )); - record_popup(&chat, &mut states); - - dismiss_popup(&mut chat); - let nothing_request_id = chat.show_rate_limit_reset_consuming_popup(); - assert!(!finish_reset_consume_outcome( - &mut chat, - nothing_request_id, - "redeem-2", - ConsumeAccountRateLimitResetCreditOutcome::NothingToReset, - )); - record_popup(&chat, &mut states); - - dismiss_popup(&mut chat); - let no_credit_request_id = chat.show_rate_limit_reset_consuming_popup(); - assert!(!finish_reset_consume_outcome( - &mut chat, - no_credit_request_id, - "redeem-3", - ConsumeAccountRateLimitResetCreditOutcome::NoCredit, - )); - record_popup(&chat, &mut states); - - dismiss_popup(&mut chat); - let success_request_id = chat.show_rate_limit_reset_consuming_popup(); - assert!(finish_reset_consume_outcome( - &mut chat, - success_request_id, - "redeem-4", - ConsumeAccountRateLimitResetCreditOutcome::Reset, - )); - record_popup(&chat, &mut states); - assert!(chat.finish_post_consume_reset_credits_refresh( - success_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 1)), - )); - record_popup(&chat, &mut states); - - assert_chatwidget_snapshot!("rate_limit_reset_popup_states", states.join("\n---\n")); -} - -#[tokio::test] -async fn rate_limit_reset_picker_wraps_expiry_details_snapshot() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.clock_format = crate::clock_format::ClockFormat::TwelveHour; - let request_id = chat.show_rate_limit_reset_loading_popup(); - let expiry = expiry_timestamp(/*day*/ 18, /*hour*/ 9, /*minute*/ 39); - assert!(chat.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Ok(detailed_reset_credits( - /*available_count*/ 2, - vec![ - reset_credit("credit-2", /*expires_at*/ None), - reset_credit("credit-1", Some(expiry)), - ], - )), - )); - - assert_chatwidget_snapshot!( - "rate_limit_reset_picker_narrow", - render_bottom_popup(&chat, /*width*/ 44) - ); -} - -#[tokio::test] -async fn rate_limit_reset_confirmation_uses_backend_copy_snapshot() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let expiry = expiry_timestamp(/*day*/ 18, /*hour*/ 9, /*minute*/ 39); - let mut credit = - reset_credit_with_title("weekly-credit", Some(expiry), "Full reset (Weekly + 5 hr)"); - credit.description = Some("Reset your weekly and 5-hour usage limits.".to_string()); - let request_id = chat.show_rate_limit_reset_loading_popup(); - assert!(chat.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Ok(detailed_reset_credits( - /*available_count*/ 1, - vec![credit], - )), - )); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - let Ok(AppEvent::OpenRateLimitResetConfirmation { - picker_request_id, - confirmation_gate, - credit_id, - reset_title, - reset_detail, - reset_description, - }) = rx.try_recv() - else { - panic!("expected reset confirmation event"); - }; - assert_eq!( - ( - picker_request_id, - credit_id.as_deref(), - reset_title.as_str(), - reset_detail.as_deref(), - reset_description.as_str(), - ), - ( - request_id, - Some("weekly-credit"), - "Full reset (Weekly + 5 hr)", - Some("Expires 09:39 on 18 Jun 2026"), - "Reset your weekly and 5-hour usage limits.", - ) - ); - assert!(chat.show_rate_limit_reset_confirmation( - picker_request_id, - confirmation_gate, - credit_id, - reset_title, - reset_detail, - reset_description, - )); - - assert_chatwidget_snapshot!( - "rate_limit_reset_confirmation", - render_bottom_popup(&chat, /*width*/ 80) - ); -} - -#[tokio::test] -async fn rate_limit_reset_confirmation_no_and_escape_return_to_picker() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat.show_rate_limit_reset_loading_popup(); - assert!(chat.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 1)), - )); - let picker = render_bottom_popup(&chat, /*width*/ 80); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - show_rate_limit_reset_confirmation_from_event(&mut chat, &mut rx); - assert!(rx.try_recv().is_err()); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!(render_bottom_popup(&chat, /*width*/ 80), picker); - - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - show_rate_limit_reset_confirmation_from_event(&mut chat, &mut rx); - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert_eq!(render_bottom_popup(&chat, /*width*/ 80), picker); - - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - show_rate_limit_reset_confirmation_from_event(&mut chat, &mut rx); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_eq!(render_bottom_popup(&chat, /*width*/ 80), picker); - assert!(rx.try_recv().is_err()); -} - -#[tokio::test] -async fn reset_picker_allows_only_one_pending_confirmation() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat.show_rate_limit_reset_loading_popup(); - let first_expiry = expiry_timestamp(/*day*/ 18, /*hour*/ 9, /*minute*/ 39); - assert!(chat.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Ok(detailed_reset_credits( - /*available_count*/ 2, - vec![ - reset_credit_with_title("credit-1", Some(first_expiry), "First reset"), - reset_credit_with_title("credit-2", /*expires_at*/ None, "Second reset"), - ], - )), - )); - - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - show_rate_limit_reset_confirmation_from_event(&mut chat, &mut rx); - assert!(rx.try_recv().is_err()); - - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - show_rate_limit_reset_confirmation_from_event(&mut chat, &mut rx); - - assert!(render_bottom_popup(&chat, /*width*/ 80).contains("Second reset · Does not expire")); -} - -#[tokio::test] -async fn rate_limit_reset_picker_starts_with_soonest_expiries_and_keeps_all_rows_reachable() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat.show_rate_limit_reset_loading_popup(); - let first_expiry = expiry_timestamp(/*day*/ 18, /*hour*/ 9, /*minute*/ 39); - let credits = (0..9) - .rev() - .map(|index| { - reset_credit( - &format!("credit-{index}"), - Some(first_expiry + i64::from(index) * 86_400), - ) - }) - .collect(); - assert!(chat.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Ok(detailed_reset_credits(/*available_count*/ 9, credits)), - )); - - let rendered = render_bottom_popup(&chat, /*width*/ 80); - assert!( - rendered.contains("Expires 09:39 on 18 Jun 2026"), - "{rendered}" - ); - assert!(!rendered.contains("Full reset ("), "{rendered}"); - - for _ in 0..8 { - chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); - } - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - assert_matches!( - rx.try_recv(), - Ok(AppEvent::OpenRateLimitResetConfirmation { - picker_request_id, - confirmation_gate: _, - credit_id, - reset_title, - reset_detail, - reset_description, - }) if picker_request_id == request_id - && credit_id.as_deref() == Some("credit-8") - && reset_title == "Full reset" - && reset_detail.as_deref() == Some("Expires 09:39 on 26 Jun 2026") - && reset_description == "Reset your current usage limits" - ); -} - -#[tokio::test] -async fn rate_limit_reset_confirmation_can_use_reset() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat.show_rate_limit_reset_loading_popup(); - assert!(chat.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Ok(detailed_reset_credits( - /*available_count*/ 1, - vec![reset_credit("credit-1", /*expires_at*/ None)], - )), - )); - - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - show_rate_limit_reset_confirmation_from_event(&mut chat, &mut rx); - assert!(rx.try_recv().is_err()); - chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - let Ok(AppEvent::ConsumeRateLimitResetCredit { - idempotency_key, - credit_id, - }) = rx.try_recv() - else { - panic!("expected reset consume event"); - }; - assert!(Uuid::parse_str(&idempotency_key).is_ok()); - assert_eq!(credit_id.as_deref(), Some("credit-1")); - - assert_eq!(chat.start_rate_limit_reset_consumption("wrong-key"), None); - let consume_request_id = chat - .start_rate_limit_reset_consumption(&idempotency_key) - .expect("confirmed reset should start consumption"); - assert_eq!( - chat.start_rate_limit_reset_consumption(&idempotency_key), - None - ); - assert!(!chat.finish_rate_limit_reset_consume( - consume_request_id, - idempotency_key, - credit_id, - Ok(consume_response( - ConsumeAccountRateLimitResetCreditOutcome::NothingToReset, - )), - )); - dismiss_popup(&mut chat); - assert!(chat.bottom_pane.no_modal_or_popup_active()); -} - -#[tokio::test] -async fn rate_limit_reset_retry_reuses_idempotency_key() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat.show_rate_limit_reset_consuming_popup(); - assert!(!chat.finish_rate_limit_reset_consume( - request_id, - "stable-redeem-id".to_string(), - Some("credit-1".to_string()), - Err("response lost".to_string()), - )); - - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - let Ok(AppEvent::ConsumeRateLimitResetCredit { - idempotency_key, - credit_id, - }) = rx.try_recv() - else { - panic!("expected reset retry event"); - }; - assert_eq!( - (idempotency_key.as_str(), credit_id.as_deref()), - ("stable-redeem-id", Some("credit-1")) - ); - assert_eq!(chat.start_rate_limit_reset_consumption("wrong-key"), None); - assert!( - chat.start_rate_limit_reset_consumption(&idempotency_key) - .is_some() - ); -} - -#[tokio::test] -async fn no_credit_outcome_disables_reset_entry_in_usage_menu() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let startup_request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - startup_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 1)), - )); - let consume_request_id = chat.show_rate_limit_reset_consuming_popup(); - assert!(!finish_reset_consume_outcome( - &mut chat, - consume_request_id, - "redeem-1", - ConsumeAccountRateLimitResetCreditOutcome::NoCredit, - )); - dismiss_popup(&mut chat); - - chat.dispatch_command(SlashCommand::Usage); - assert_matches!( - rx.try_recv(), - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::UsageMenu { request_id: 2 } - }) - ); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - assert_matches!(rx.try_recv(), Ok(AppEvent::OpenAnalytics { view: None })); - - chat.available_rate_limit_reset_credits = Some(2); - let consume_request_id = chat.show_rate_limit_reset_consuming_popup(); - assert!(!chat.finish_rate_limit_reset_consume( - consume_request_id, - "redeem-selected".to_string(), - Some("stale-credit".to_string()), - Ok(consume_response( - ConsumeAccountRateLimitResetCreditOutcome::NoCredit - )), - )); - assert_eq!(chat.available_rate_limit_reset_credits, None); - assert!( - render_bottom_popup(&chat, /*width*/ 80).contains("That reset is no longer available.") - ); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_matches!(rx.try_recv(), Ok(AppEvent::OpenRateLimitResetCredits)); -} - -#[tokio::test] -async fn rate_limit_reset_redemption_cannot_be_dismissed_while_in_flight() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - - let request_id = chat.show_rate_limit_reset_consuming_popup(); - dismiss_popup(&mut chat); - assert!(render_bottom_popup(&chat, /*width*/ 80).contains("Using a reset...")); - - assert!(finish_reset_consume_outcome( - &mut chat, - request_id, - "redeem-123", - ConsumeAccountRateLimitResetCreditOutcome::Reset, - )); - dismiss_popup(&mut chat); - assert!(render_bottom_popup(&chat, /*width*/ 80).contains("Refreshing...")); - - assert!(chat.finish_post_consume_reset_credits_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 1)), - )); - dismiss_popup(&mut chat); - assert!(chat.bottom_pane.no_modal_or_popup_active()); -} - -#[tokio::test] -async fn rate_limit_reset_redemption_allows_ctrl_c_to_quit_while_in_flight() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - - chat.show_rate_limit_reset_consuming_popup(); - chat.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)); - - assert_matches!(rx.try_recv(), Ok(AppEvent::Exit(ExitMode::ShutdownFirst))); - assert!(render_bottom_popup(&chat, /*width*/ 80).contains("Using a reset...")); -} - -#[tokio::test] -async fn already_redeemed_is_an_idempotent_success() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat.show_rate_limit_reset_consuming_popup(); - - assert!(finish_reset_consume_outcome( - &mut chat, - request_id, - "stable-redeem-id", - ConsumeAccountRateLimitResetCreditOutcome::AlreadyRedeemed, - )); - assert!(chat.finish_post_consume_reset_credits_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 0)), - )); - assert!( - render_bottom_popup(&chat, /*width*/ 80) - .contains("Usage reset. You have 0 usage limit resets left.") - ); -} - -#[tokio::test] -async fn failed_post_consume_refresh_does_not_keep_stale_reset_count() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let startup_request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - startup_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - let consume_request_id = chat.show_rate_limit_reset_consuming_popup(); - assert!(finish_reset_consume_outcome( - &mut chat, - consume_request_id, - "redeem-with-refresh-error", - ConsumeAccountRateLimitResetCreditOutcome::Reset, - )); - - assert!(chat.finish_post_consume_reset_credits_refresh( - consume_request_id, - Vec::new(), - Err("backend unavailable".to_string()), - )); - dismiss_popup(&mut chat); - chat.dispatch_command(SlashCommand::Usage); - - let rendered = render_bottom_popup(&chat, /*width*/ 80); - assert!(rendered.contains("Check availability")); - assert!(!rendered.contains("2 available")); -} - -#[tokio::test] -async fn account_change_invalidates_pending_reset_requests() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let request_id = chat.show_rate_limit_reset_loading_popup(); - - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ false, - ); - - assert!(!chat.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - assert!(chat.bottom_pane.no_modal_or_popup_active()); -} - -#[tokio::test] -async fn clearing_pending_reset_hint_preserves_in_flight_redemption() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let consume_request_id = chat.show_rate_limit_reset_consuming_popup(); - let hint_request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - hint_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - - chat.clear_pending_rate_limit_reset_hint(); - - assert!(chat.pending_rate_limit_reset_hint().is_none()); - assert!(finish_reset_consume_outcome( - &mut chat, - consume_request_id, - "redeem-after-rollback", - ConsumeAccountRateLimitResetCreditOutcome::Reset, - )); -} - -#[tokio::test] -async fn rate_limit_reset_load_result_updates_popup_beneath_overlay() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat.show_rate_limit_reset_loading_popup(); - show_usage_test_overlay(&mut chat); - - assert!(chat.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - assert_eq!( - chat.bottom_pane.active_view_id(), - Some(TEST_OVERLAY_VIEW_ID) - ); - - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!(render_bottom_popup(&chat, /*width*/ 80).contains("2 usage limit resets available.")); -} - -#[tokio::test] -async fn rate_limit_reset_success_updates_popup_beneath_overlay() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat.show_rate_limit_reset_consuming_popup(); - show_usage_test_overlay(&mut chat); - - assert!(finish_reset_consume_outcome( - &mut chat, - request_id, - "redeem-covered", - ConsumeAccountRateLimitResetCreditOutcome::Reset, - )); - assert!(chat.finish_post_consume_reset_credits_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 1)), - )); - assert_eq!( - chat.bottom_pane.active_view_id(), - Some(TEST_OVERLAY_VIEW_ID) - ); - - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!( - render_bottom_popup(&chat, /*width*/ 80) - .contains("Usage reset. You have 1 usage limit reset left.") - ); -} - -#[tokio::test] -async fn account_change_dismisses_reset_popup_beneath_overlay() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let request_id = chat.show_rate_limit_reset_loading_popup(); - assert!(chat.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 1)), - )); - assert!(chat.show_rate_limit_reset_confirmation( - request_id, - Arc::new(AtomicBool::new(true)), - /*credit_id*/ None, - "Full reset".to_string(), - /*reset_detail*/ None, - "Reset your current usage limits.".to_string(), - )); - chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - let Ok(AppEvent::ConsumeRateLimitResetCredit { - idempotency_key, - credit_id: None, - }) = rx.try_recv() - else { - panic!("expected reset consume event"); - }; - show_usage_test_overlay(&mut chat); - - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ false, - ); - assert!(!chat.show_rate_limit_reset_confirmation( - request_id, - Arc::new(AtomicBool::new(true)), - /*credit_id*/ None, - "Stale reset".to_string(), - /*reset_detail*/ None, - "This stale confirmation should be ignored.".to_string(), - )); - assert_eq!( - chat.start_rate_limit_reset_consumption(&idempotency_key), - None - ); - assert_eq!( - chat.bottom_pane.active_view_id(), - Some(TEST_OVERLAY_VIEW_ID) - ); - - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!(chat.bottom_pane.no_modal_or_popup_active()); -} - -#[tokio::test] -async fn startup_check_shows_available_reset_hint_snapshot() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let hint_request_id = chat.start_rate_limit_reset_startup_check(); - - assert!(chat.finish_rate_limit_reset_hint_refresh( - hint_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - let rendered = lines_to_single_string( - &chat - .pending_rate_limit_reset_hint() - .expect("pending reset hint") - .display_lines(/*width*/ 80), - ); - assert_chatwidget_snapshot!("rate_limit_reset_available_hint", rendered); -} - -#[tokio::test] -async fn startup_reset_hint_waits_for_active_output_snapshot() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let hint_request_id = chat.start_rate_limit_reset_startup_check(); - chat.transcript.active_cell = Some(Box::new(PlainHistoryCell::new(vec![Line::from( - "active tool", - )]))); - - assert!(chat.finish_rate_limit_reset_hint_refresh( - hint_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - - assert!(chat.usage_history_insertion_blocked()); - assert!(drain_insert_history(&mut rx).is_empty()); - assert_chatwidget_snapshot!( - "rate_limit_reset_hint_waits_for_active_output", - lines_to_single_string( - &chat - .active_cell_transcript_lines(/*width*/ 80) - .expect("active output with reset hint"), - ) - ); - - chat.flush_active_cell(); - - assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))); - assert_matches!(rx.try_recv(), Ok(AppEvent::CommitPendingUsageOutput)); -} - -#[tokio::test] -async fn opening_rate_limit_reset_flow_invalidates_in_flight_startup_hint() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let hint_request_id = chat.start_rate_limit_reset_startup_check(); - - chat.show_rate_limit_reset_loading_popup(); - - assert!(!chat.finish_rate_limit_reset_hint_refresh( - hint_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - assert!(chat.pending_rate_limit_reset_hint().is_none()); -} - -#[tokio::test] -async fn starting_rate_limit_reset_redemption_clears_deferred_startup_hint() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let hint_request_id = chat.start_rate_limit_reset_startup_check(); - assert!(chat.finish_rate_limit_reset_hint_refresh( - hint_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - assert!(chat.pending_rate_limit_reset_hint().is_some()); - - chat.show_rate_limit_reset_consuming_popup(); - - assert!(chat.pending_rate_limit_reset_hint().is_none()); -} - -#[tokio::test] -async fn startup_check_omits_reset_hint_when_none_are_available() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let hint_request_id = chat.start_rate_limit_reset_startup_check(); - - assert!(chat.finish_rate_limit_reset_hint_refresh( - hint_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 0)), - )); - assert!(chat.pending_rate_limit_reset_hint().is_none()); -} - -#[tokio::test] -async fn startup_check_shows_reset_hint_for_workspace_account_with_credit() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - chat.plan_type = Some(PlanType::Business); - let hint_request_id = chat.start_rate_limit_reset_startup_check(); - - assert!(chat.finish_rate_limit_reset_hint_refresh( - hint_request_id, - Vec::new(), - Ok(reset_credits(/*available_count*/ 2)), - )); - assert!(chat.pending_rate_limit_reset_hint().is_some()); - assert_eq!(chat.available_rate_limit_reset_credits, Some(2)); -} - -fn consume_response( - outcome: ConsumeAccountRateLimitResetCreditOutcome, -) -> ConsumeAccountRateLimitResetCreditResponse { - ConsumeAccountRateLimitResetCreditResponse { outcome } -} - -fn finish_reset_consume_outcome( - chat: &mut ChatWidget, - request_id: u64, - idempotency_key: &str, - outcome: ConsumeAccountRateLimitResetCreditOutcome, -) -> bool { - chat.finish_rate_limit_reset_consume( - request_id, - idempotency_key.to_string(), - /*credit_id*/ None, - Ok(consume_response(outcome)), - ) -} - -fn record_popup(chat: &ChatWidget, states: &mut Vec) { - states.push(render_bottom_popup(chat, /*width*/ 80)); -} - -fn dismiss_popup(chat: &mut ChatWidget) { - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); -} - -fn show_usage_test_overlay(chat: &mut ChatWidget) { - chat.bottom_pane.show_selection_view(SelectionViewParams { - view_id: Some(TEST_OVERLAY_VIEW_ID), - title: Some("Covering overlay".to_string()), - items: vec![SelectionItem { - name: "Close".to_string(), - dismiss_on_select: true, - ..Default::default() - }], - ..Default::default() - }); -} diff --git a/codex-rs/tui/src/chatwidget/thread_usage.rs b/codex-rs/tui/src/chatwidget/thread_usage.rs deleted file mode 100644 index 19ba15a9..00000000 --- a/codex-rs/tui/src/chatwidget/thread_usage.rs +++ /dev/null @@ -1,432 +0,0 @@ -//! Demand-driven estimated-cost state for the currently visible enterprise thread. - -use super::AppEvent; -use super::ChatWidget; -use super::Duration; -use super::Instant; -use super::PlanType; -use super::StatusLineItem; -use super::TerminalTitleItem; -use super::ThreadId; -use crate::status::StatusHistoryHandle; -use crate::status::thread_cost_micros; -use codex_app_server_protocol::ThreadUsage; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) enum ThreadUsageOutcome { - Available(ThreadUsage), - Disabled, -} - -const THREAD_USAGE_SETTLEMENT_DELAYS: [Duration; 3] = [ - Duration::from_secs(/*secs*/ 15), - Duration::from_secs(/*secs*/ 60), - Duration::from_secs(/*secs*/ 120), -]; -const THREAD_USAGE_RETRY_DELAYS: [Duration; 3] = [ - Duration::from_secs(/*secs*/ 5), - Duration::from_secs(/*secs*/ 15), - Duration::from_secs(/*secs*/ 60), -]; - -#[derive(Debug, Default)] -struct SelectedThreadUsage { - credits: bool, - estimated_cost: bool, -} - -#[derive(Debug, Default)] -pub(super) struct ThreadUsageState { - thread_id: Option, - estimate: Option, - pending_request_id: Option, - next_request_id: u64, - requested: bool, - feature_disabled: bool, - status_history_handles: Vec, - status_requested: bool, - retry_attempts: usize, - retry_due_at: Option, - settlement_attempts: usize, - settlement_baseline_credits_micros: Option, - settlement_baseline_usd_micros: Option, - settlement_request_id: Option, - settlement_refresh_due_at: Option, - pub(super) replaying_turn_completion: bool, -} - -impl ChatWidget { - pub(super) fn clear_thread_usage_state(&mut self) { - let next_request_id = self.thread_usage.next_request_id; - self.thread_usage = ThreadUsageState { - next_request_id, - ..ThreadUsageState::default() - }; - } - - pub(super) fn ensure_thread_usage_requested(&mut self) { - let Some(thread_id) = self.thread_id else { - return; - }; - if self.thread_usage.thread_id != Some(thread_id) { - self.clear_thread_usage_state(); - self.thread_usage.thread_id = Some(thread_id); - } - if self.thread_usage.requested { - return; - } - self.request_thread_usage(); - } - - pub(super) fn refresh_thread_usage_after_turn(&mut self) { - if self.thread_usage.replaying_turn_completion - || !self.thread_usage_is_selected() - || !self.thread_usage_is_available() - { - return; - } - - self.thread_usage.settlement_attempts = 0; - self.thread_usage.settlement_request_id = None; - self.thread_usage.settlement_baseline_credits_micros = Some( - self.thread_usage - .estimate - .as_ref() - .map(|estimate| estimate.estimated_usage_credits_micros) - .unwrap_or_default(), - ); - self.thread_usage.settlement_baseline_usd_micros = self - .thread_usage - .estimate - .as_ref() - .and_then(|estimate| thread_cost_micros(estimate, self.plan_type)); - self.schedule_next_thread_usage_settlement(); - self.request_thread_usage(); - } - - pub(super) fn refresh_thread_usage_if_settlement_due(&mut self) { - let now = Instant::now(); - let settlement_due = self - .thread_usage - .settlement_refresh_due_at - .is_some_and(|due_at| now >= due_at); - let retry_due = self - .thread_usage - .retry_due_at - .is_some_and(|due_at| now >= due_at); - if !settlement_due && !retry_due { - if let Some(next_due_at) = [ - self.thread_usage.settlement_refresh_due_at, - self.thread_usage.retry_due_at, - ] - .into_iter() - .flatten() - .min() - { - self.frame_requester - .schedule_frame_in(next_due_at.saturating_duration_since(now)); - } - return; - } - - if !self.thread_usage_is_selected() { - self.cancel_thread_usage_polling(); - return; - } - - if settlement_due { - self.thread_usage.settlement_refresh_due_at = None; - } - if retry_due { - self.thread_usage.retry_due_at = None; - } - self.request_thread_usage(); - } - - pub(super) fn request_thread_usage_for_status(&mut self, handle: StatusHistoryHandle) { - if !self.thread_usage_is_available() { - return; - } - - let Some(thread_id) = self.thread_id else { - return; - }; - if self.thread_usage.thread_id != Some(thread_id) { - self.clear_thread_usage_state(); - self.thread_usage.thread_id = Some(thread_id); - } - - self.thread_usage.status_history_handles.push(handle); - self.thread_usage.status_requested = true; - self.thread_usage.retry_attempts = 0; - self.request_thread_usage(); - } - - pub(super) fn cancel_thread_usage_polling(&mut self) { - if self.thread_usage.status_requested { - return; - } - - self.thread_usage.pending_request_id = None; - self.thread_usage.requested = false; - self.thread_usage.retry_attempts = 0; - self.thread_usage.retry_due_at = None; - self.thread_usage.settlement_attempts = 0; - self.thread_usage.settlement_baseline_credits_micros = None; - self.thread_usage.settlement_baseline_usd_micros = None; - self.thread_usage.settlement_request_id = None; - self.thread_usage.settlement_refresh_due_at = None; - } - - pub(crate) fn finish_thread_usage_refresh( - &mut self, - thread_id: ThreadId, - request_id: u64, - result: Result, - ) -> bool { - if self.thread_id != Some(thread_id) - || self.thread_usage.thread_id != Some(thread_id) - || self.thread_usage.pending_request_id != Some(request_id) - { - return false; - } - - self.thread_usage.pending_request_id = None; - let mut usage_updated = false; - self.thread_usage.status_requested = false; - let post_turn_request = self.thread_usage.settlement_request_id == Some(request_id); - match result { - Ok(ThreadUsageOutcome::Disabled) => { - self.thread_usage.feature_disabled = true; - self.thread_usage.estimate = None; - usage_updated = true; - self.thread_usage.retry_due_at = None; - self.thread_usage.settlement_refresh_due_at = None; - self.thread_usage.settlement_baseline_credits_micros = None; - self.thread_usage.settlement_baseline_usd_micros = None; - self.thread_usage.settlement_request_id = None; - } - Ok(ThreadUsageOutcome::Available(usage)) - if usage.thread_id != thread_id.to_string() => - { - tracing::warn!( - requested_thread_id = %thread_id, - returned_thread_id = %usage.thread_id, - "thread usage response referred to another thread" - ); - self.schedule_thread_usage_retry(); - } - Ok(ThreadUsageOutcome::Available(mut usage)) => { - usage_updated = true; - self.thread_usage.retry_attempts = 0; - self.thread_usage.retry_due_at = None; - let previous_positive_credits_micros = self - .thread_usage - .estimate - .as_ref() - .map(|estimate| estimate.estimated_usage_credits_micros) - .filter(|micros| *micros > 0); - let transient_zero_credits = usage.estimated_usage_credits_micros == 0 - && previous_positive_credits_micros.is_some(); - if let Some(previous_positive_credits_micros) = previous_positive_credits_micros - && transient_zero_credits - { - usage.estimated_usage_credits_micros = previous_positive_credits_micros; - } - let previous_positive_usd_micros = self - .thread_usage - .estimate - .as_ref() - .and_then(|estimate| estimate.estimated_usage_usd_micros) - .filter(|micros| *micros > 0); - let transient_zero_cost = usage.estimated_usage_usd_micros == Some(0) - && previous_positive_usd_micros.is_some(); - if let Some(previous_positive_usd_micros) = previous_positive_usd_micros - && transient_zero_cost - { - usage.estimated_usage_usd_micros = Some(previous_positive_usd_micros); - } - if (transient_zero_credits || transient_zero_cost) - && usage.groups.is_empty() - && let Some(previous_usage) = self.thread_usage.estimate.as_ref() - { - usage.groups.clone_from(&previous_usage.groups); - } - let estimated_credits_micros = usage.estimated_usage_credits_micros; - let estimated_usd_micros = thread_cost_micros(&usage, self.plan_type); - self.thread_usage.estimate = Some(usage); - if let Some(baseline) = self.thread_usage.settlement_baseline_credits_micros { - if !post_turn_request { - self.thread_usage.settlement_baseline_credits_micros = - Some(baseline.max(estimated_credits_micros)); - self.thread_usage.settlement_baseline_usd_micros = match ( - self.thread_usage.settlement_baseline_usd_micros, - estimated_usd_micros, - ) { - (Some(previous), Some(current)) => Some(previous.max(current)), - (previous, current) => previous.or(current), - }; - } else { - let mut selected = self.selected_thread_usage(); - if !self.thread_usage.status_history_handles.is_empty() { - selected.credits = self.plan_type != Some(PlanType::Ent26); - selected.estimated_cost |= self.plan_type == Some(PlanType::Ent26) - || self.thread_usage.settlement_baseline_usd_micros.is_some() - || estimated_usd_micros.is_some(); - } - let credits_settled = - !selected.credits || estimated_credits_micros > baseline; - let cost_settled = !selected.estimated_cost - || estimated_usd_micros.is_some_and(|current| { - self.thread_usage - .settlement_baseline_usd_micros - .map_or(current > 0, |previous| current > previous) - }); - if credits_settled && cost_settled { - self.thread_usage.settlement_baseline_credits_micros = None; - self.thread_usage.settlement_baseline_usd_micros = None; - self.thread_usage.settlement_request_id = None; - self.thread_usage.settlement_refresh_due_at = None; - } else if self.thread_usage.settlement_refresh_due_at.is_none() { - self.schedule_next_thread_usage_settlement(); - } - } - } - } - Err(err) => { - tracing::debug!(error = %err, "failed to fetch estimated thread usage"); - self.schedule_thread_usage_retry(); - } - } - 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()); - } - if self - .thread_usage - .settlement_baseline_credits_micros - .is_none() - { - self.thread_usage.status_history_handles.clear(); - } - } - if self - .thread_usage - .settlement_baseline_credits_micros - .is_some() - && self.thread_usage.settlement_request_id.is_none() - && self.thread_usage_is_selected() - { - self.request_thread_usage(); - } - self.refresh_status_line(); - self.request_redraw(); - true - } - - pub(super) fn estimated_thread_usage(&self) -> Option<&ThreadUsage> { - self.thread_usage.estimate.as_ref() - } - - fn request_thread_usage(&mut self) { - let Some(thread_id) = self.thread_id else { - return; - }; - if !self.thread_usage_is_available() || self.thread_usage.pending_request_id.is_some() { - return; - } - - let request_id = self.thread_usage.next_request_id; - self.thread_usage.next_request_id = - self.thread_usage.next_request_id.wrapping_add(/*rhs*/ 1); - self.thread_usage.pending_request_id = Some(request_id); - self.thread_usage.requested = true; - self.thread_usage.thread_id = Some(thread_id); - if self - .thread_usage - .settlement_baseline_credits_micros - .is_some() - { - self.thread_usage.settlement_request_id = Some(request_id); - } - self.app_event_tx.send(AppEvent::RefreshThreadUsage { - thread_id, - request_id, - }); - } - - pub(super) fn thread_usage_is_available(&self) -> bool { - self.has_codex_backend_auth - && !self.thread_usage.feature_disabled - && self.thread_id.is_some() - && matches!( - self.plan_type, - Some( - PlanType::Ent26 - | PlanType::Business - | PlanType::EnterpriseCbpUsageBased - | PlanType::EnterpriseCbpAutomation - ) - ) - } - - fn thread_usage_is_selected(&self) -> bool { - let selected = self.selected_thread_usage(); - selected.credits || selected.estimated_cost - } - - fn selected_thread_usage(&self) -> SelectedThreadUsage { - let mut selected = SelectedThreadUsage::default(); - for item in self.configured_status_line_items() { - match item.parse::() { - Ok(StatusLineItem::ThreadCredits) => selected.credits = true, - Ok(StatusLineItem::EstimatedThreadCost) => selected.estimated_cost = true, - Ok(_) | Err(_) => {} - } - } - for item in self.configured_terminal_title_items() { - match item.parse::() { - Ok(TerminalTitleItem::ThreadCredits) => selected.credits = true, - Ok(TerminalTitleItem::EstimatedThreadCost) => selected.estimated_cost = true, - Ok(_) | Err(_) => {} - } - } - selected.credits &= self.plan_type != Some(PlanType::Ent26); - selected - } - - fn schedule_next_thread_usage_settlement(&mut self) { - let Some(delay) = THREAD_USAGE_SETTLEMENT_DELAYS - .get(self.thread_usage.settlement_attempts) - .copied() - else { - self.thread_usage.settlement_baseline_credits_micros = None; - self.thread_usage.settlement_baseline_usd_micros = None; - self.thread_usage.settlement_request_id = None; - return; - }; - self.thread_usage.settlement_attempts += 1; - self.thread_usage.settlement_refresh_due_at = Some(Instant::now() + delay); - self.frame_requester.schedule_frame_in(delay); - } - - fn schedule_thread_usage_retry(&mut self) { - if !self.thread_usage_is_selected() { - return; - } - - let Some(delay) = THREAD_USAGE_RETRY_DELAYS - .get(self.thread_usage.retry_attempts) - .copied() - else { - return; - }; - self.thread_usage.retry_attempts += 1; - self.thread_usage.retry_due_at = Some(Instant::now() + delay); - self.frame_requester.schedule_frame_in(delay); - } -} - -#[cfg(test)] -#[path = "thread_usage_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/chatwidget/thread_usage_tests.rs b/codex-rs/tui/src/chatwidget/thread_usage_tests.rs deleted file mode 100644 index f0b525de..00000000 --- a/codex-rs/tui/src/chatwidget/thread_usage_tests.rs +++ /dev/null @@ -1,1060 +0,0 @@ -use super::THREAD_USAGE_RETRY_DELAYS; -use super::THREAD_USAGE_SETTLEMENT_DELAYS; -use super::ThreadUsageOutcome; -use crate::app_event::AppEvent; -use crate::chatwidget::ReplayKind; -use crate::chatwidget::tests::make_chatwidget_manual_with_sender; -use crate::status::format_estimated_usd_micros; -use crate::tui::FrameRequester; -use codex_app_server_protocol::CodexErrorInfo; -use codex_app_server_protocol::ErrorNotification; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ThreadUsage; -use codex_app_server_protocol::ThreadUsageBreakdownGroup; -use codex_app_server_protocol::Turn; -use codex_app_server_protocol::TurnError; -use codex_app_server_protocol::TurnItemsView; -use codex_app_server_protocol::TurnStatus; -use codex_protocol::ThreadId; -use codex_protocol::account::PlanType; -use pretty_assertions::assert_eq; -use std::time::Duration; -use std::time::Instant; -use tokio::sync::mpsc::UnboundedReceiver; - -fn thread_usage_request_id(events: &mut UnboundedReceiver) -> u64 { - match events.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected a thread usage request, got {event:?}"), - } -} - -fn thread_usage( - thread_id: ThreadId, - estimated_usage_credits_micros: i64, - estimated_usage_usd_micros: Option, -) -> ThreadUsage { - ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros, - estimated_usage_usd_micros, - groups: Vec::new(), - } -} - -#[test] -fn estimated_cost_formats_dollars_and_sub_cent_values() { - assert_eq!( - format_estimated_usd_micros(/*micros*/ 0), - Some("~$0.00".to_string()) - ); - assert_eq!( - format_estimated_usd_micros(/*micros*/ 1), - Some("~$0.000001".to_string()) - ); - assert_eq!( - format_estimated_usd_micros(/*micros*/ 400), - Some("~$0.0004".to_string()) - ); - assert_eq!( - format_estimated_usd_micros(/*micros*/ 1_820_000), - Some("~$1.82".to_string()) - ); - assert_eq!( - format_estimated_usd_micros(/*micros*/ 995_000), - Some("~$1.00".to_string()) - ); - assert_eq!(format_estimated_usd_micros(/*micros*/ -1), None); -} - -#[tokio::test] -async fn temporary_thread_usage_failures_have_bounded_retries() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.refresh_status_line(); - - for attempt in 0..=THREAD_USAGE_RETRY_DELAYS.len() { - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected retry attempt {attempt}, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Err("thread usage temporarily unavailable".to_string()), - )); - - if attempt < THREAD_USAGE_RETRY_DELAYS.len() { - assert!(chat.thread_usage.retry_due_at.is_some()); - chat.thread_usage.retry_due_at = Some(Instant::now()); - chat.refresh_thread_usage_if_settlement_due(); - } - } - - assert!(chat.thread_usage.retry_due_at.is_none()); - assert!(rx.try_recv().is_err(), "retries must stop after the bound"); -} - -#[tokio::test] -async fn status_history_survives_exhausted_billing_retries() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.refresh_status_line(); - let mut request_id = thread_usage_request_id(&mut rx); - - chat.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); - let first_status_cell = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell, - event => panic!("expected the first /status card, got {event:?}"), - }; - - for attempt in 0..=THREAD_USAGE_RETRY_DELAYS.len() { - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Err("thread usage temporarily unavailable".to_string()), - )); - assert_eq!(chat.thread_usage.status_history_handles.len(), 1); - - if attempt < THREAD_USAGE_RETRY_DELAYS.len() { - chat.thread_usage.retry_due_at = Some(Instant::now()); - chat.refresh_thread_usage_if_settlement_due(); - request_id = thread_usage_request_id(&mut rx); - } - } - - assert_eq!(chat.thread_usage.retry_due_at, None); - chat.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); - let retry_status_cell = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell, - event => panic!("expected a fresh /status card, got {event:?}"), - }; - request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 50_000_000, - Some(2_100_000), - ))), - )); - - for status_cell in [&first_status_cell, &retry_status_cell] { - let rendered = status_cell - .display_lines(/*width*/ 90) - .into_iter() - .flat_map(|line| line.spans) - .map(|span| span.content.into_owned()) - .collect::(); - assert!(rendered.contains("50 credits · ~$2.10")); - } - assert!(chat.thread_usage.status_history_handles.is_empty()); -} - -#[tokio::test] -async fn status_history_updates_again_after_billing_settles() { - for (selected_item, stale_credits_micros, stale_usd_micros) in [ - ("estimated-thread-cost", 40_000_000, 1_820_000), - ("thread-credits", 50_000_000, 1_820_000), - ("estimated-thread-cost", 40_000_000, 2_100_000), - ] { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec![selected_item.to_string()]); - chat.refresh_status_line(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 40_000_000, - Some(1_820_000), - ))), - )); - - chat.refresh_thread_usage_after_turn(); - let request_id = thread_usage_request_id(&mut rx); - chat.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); - let status_cell = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell, - event => panic!("expected an immediate /status card, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - stale_credits_micros, - Some(stale_usd_micros), - ))), - )); - assert_eq!(chat.thread_usage.status_history_handles.len(), 1); - - chat.thread_usage.settlement_refresh_due_at = Some(Instant::now()); - chat.refresh_thread_usage_if_settlement_due(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 50_000_000, - Some(2_100_000), - ))), - )); - - let rendered = status_cell - .display_lines(/*width*/ 90) - .into_iter() - .flat_map(|line| line.spans) - .map(|span| span.content.into_owned()) - .collect::(); - assert!(rendered.contains("50 credits · ~$2.10")); - assert!(chat.thread_usage.status_history_handles.is_empty()); - } -} - -#[tokio::test] -async fn replayed_turn_completions_do_not_start_live_billing_refreshes() { - for replay_kind in [ - ReplayKind::ResumeInitialMessages, - ReplayKind::ThreadSnapshot, - ] { - for (status, error) in [ - (TurnStatus::Completed, None), - (TurnStatus::Interrupted, None), - (TurnStatus::Failed, None), - ( - TurnStatus::Failed, - Some(TurnError { - misalignment: None, - message: "the replayed turn failed".to_string(), - codex_error_info: Some(CodexErrorInfo::ServerOverloaded), - additional_details: None, - }), - ), - ] { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.refresh_status_line(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 46_000_000, - Some(1_820_000), - ))), - )); - - chat.replay_thread_turns( - vec![Turn { - id: "replayed-turn".to_string(), - root_turn_id: None, - items: Vec::new(), - items_view: TurnItemsView::NotLoaded, - status: status.clone(), - error, - started_at: None, - completed_at: None, - duration_ms: None, - }], - replay_kind, - ); - - assert!( - !std::iter::from_fn(|| rx.try_recv().ok()) - .any(|event| matches!(event, AppEvent::RefreshThreadUsage { .. })), - "{replay_kind:?} replay of {status:?} must not start live billing settlement" - ); - assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None); - assert_eq!(chat.thread_usage.settlement_baseline_usd_micros, None); - assert_eq!(chat.thread_usage.settlement_refresh_due_at, None); - assert!(!chat.thread_usage.replaying_turn_completion); - } - } -} - -#[tokio::test] -async fn replayed_errors_do_not_start_live_billing_refreshes() { - for replay_kind in [ - ReplayKind::ResumeInitialMessages, - ReplayKind::ThreadSnapshot, - ] { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.refresh_status_line(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 46_000_000, - Some(1_820_000), - ))), - )); - - let notification = ServerNotification::Error(ErrorNotification { - error: TurnError { - misalignment: None, - message: "the replayed turn failed".to_string(), - codex_error_info: Some(CodexErrorInfo::ServerOverloaded), - additional_details: None, - }, - will_retry: false, - thread_id: thread_id.to_string(), - turn_id: "replayed-turn".to_string(), - }); - chat.handle_server_notification(notification.clone(), Some(replay_kind)); - assert!( - !std::iter::from_fn(|| rx.try_recv().ok()) - .any(|event| matches!(event, AppEvent::RefreshThreadUsage { .. })), - "{replay_kind:?} error replay must not start live billing settlement" - ); - assert!(!chat.thread_usage.replaying_turn_completion); - - chat.handle_server_notification(notification, /*replay_kind*/ None); - assert!( - std::iter::from_fn(|| rx.try_recv().ok()) - .any(|event| matches!(event, AppEvent::RefreshThreadUsage { .. })), - "a later live error must still refresh billing" - ); - } -} - -#[tokio::test] -async fn transient_zero_cost_preserves_fresh_credits_and_breakdowns() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec![ - "thread-credits".to_string(), - "estimated-thread-cost".to_string(), - ]); - chat.local_settings.tui.terminal_title = chat.local_settings.tui.status_line.clone(); - chat.refresh_status_surfaces(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 46_000_000, - Some(1_820_000), - ))), - )); - - chat.refresh_thread_usage_after_turn(); - let request_id = thread_usage_request_id(&mut rx); - let fresh_usage = ThreadUsage { - groups: vec![ThreadUsageBreakdownGroup { - model: Some("gpt-5.4".to_string()), - reasoning_effort: Some("high".to_string()), - speed: Some("fast".to_string()), - estimated_usage_credits_micros: 50_000_000, - net_new_input_tokens: Some(80), - cached_input_tokens: Some(20), - input_tokens: Some(100), - output_tokens: Some(40), - total_tokens: Some(140), - }], - ..thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 50_000_000, - Some(0), - ) - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(fresh_usage.clone())), - )); - - assert_eq!( - chat.estimated_thread_usage(), - Some(&ThreadUsage { - estimated_usage_usd_micros: Some(1_820_000), - ..fresh_usage - }) - ); - assert_eq!( - chat.status_line_text(), - Some("50 credits · ~$1.82".to_string()) - ); - assert_eq!( - chat.last_terminal_title, - Some("50 credits | ~$1.82".to_string()) - ); - assert!(chat.thread_usage.settlement_refresh_due_at.is_some()); -} - -#[tokio::test] -async fn transient_zero_credits_preserves_credits_only_estimates() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["thread-credits".to_string()]); - chat.local_settings.tui.terminal_title = chat.local_settings.tui.status_line.clone(); - chat.refresh_status_surfaces(); - let request_id = thread_usage_request_id(&mut rx); - let previous_usage = ThreadUsage { - groups: vec![ThreadUsageBreakdownGroup { - model: Some("gpt-5.4".to_string()), - reasoning_effort: Some("high".to_string()), - speed: Some("fast".to_string()), - estimated_usage_credits_micros: 46_000_000, - net_new_input_tokens: Some(80), - cached_input_tokens: Some(20), - input_tokens: Some(100), - output_tokens: Some(40), - total_tokens: Some(140), - }], - ..thread_usage( - thread_id, /*estimated_usage_credits_micros*/ 46_000_000, - /*estimated_usage_usd_micros*/ None, - ) - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(previous_usage.clone())), - )); - - chat.refresh_thread_usage_after_turn(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, /*estimated_usage_credits_micros*/ 0, - /*estimated_usage_usd_micros*/ None, - ))), - )); - - assert_eq!(chat.estimated_thread_usage(), Some(&previous_usage)); - assert_eq!(chat.status_line_text(), Some("46 credits".to_string())); - assert_eq!(chat.last_terminal_title, Some("46 credits".to_string())); - assert!(chat.thread_usage.settlement_refresh_due_at.is_some()); -} - -#[tokio::test] -async fn cost_settlement_waits_for_new_or_missing_usd_estimates() { - for (plan_type, previous_usd_micros, stale_usd_micros) in [ - (PlanType::Business, Some(1_820_000), Some(1_820_000)), - (PlanType::Business, None, None), - (PlanType::Business, None, Some(0)), - (PlanType::Ent26, Some(1_820_000), Some(1_820_000)), - (PlanType::Ent26, None, None), - (PlanType::Ent26, None, Some(0)), - (PlanType::Ent26, Some(1_820_000), Some(0)), - ] { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - let [previous_usage, stale_usage, settled_usage] = [ - (40_000_000, previous_usd_micros), - (50_000_000, stale_usd_micros), - (50_000_000, Some(2_100_000)), - ] - .map(|(credits, cost)| { - let mut usage = thread_usage(thread_id, credits, cost); - usage.native_usage_usd_micros = cost; - if plan_type == PlanType::Ent26 { - usage.estimated_usage_credits_micros = 0; - usage.estimated_usage_usd_micros = Some(0); - } - usage - }); - let previous_credits_micros = previous_usage.estimated_usage_credits_micros; - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(plan_type); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.local_settings.tui.terminal_title = - (plan_type == PlanType::Ent26).then(|| vec!["thread-credits".to_string()]); - chat.refresh_status_line(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(previous_usage)), - )); - - chat.refresh_thread_usage_after_turn(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(stale_usage)), - )); - if plan_type == PlanType::Ent26 { - assert_eq!( - chat.status_line_text(), - stale_usd_micros.and_then(format_estimated_usd_micros) - ); - } - assert_eq!( - chat.thread_usage.settlement_baseline_credits_micros, - Some(previous_credits_micros) - ); - assert_eq!( - chat.thread_usage.settlement_baseline_usd_micros, - previous_usd_micros - ); - assert!(chat.thread_usage.settlement_refresh_due_at.is_some()); - - chat.thread_usage.settlement_refresh_due_at = Some(Instant::now()); - chat.refresh_thread_usage_if_settlement_due(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(settled_usage)), - )); - - assert_eq!(chat.status_line_text(), Some("~$2.10".to_string())); - assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None); - assert_eq!(chat.thread_usage.settlement_baseline_usd_micros, None); - assert_eq!(chat.thread_usage.settlement_refresh_due_at, None); - } -} - -#[tokio::test] -async fn credits_only_settlement_completes_without_usd_estimates() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.terminal_title = Some(vec!["thread-credits".to_string()]); - chat.refresh_terminal_title(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, /*estimated_usage_credits_micros*/ 40_000_000, - /*estimated_usage_usd_micros*/ None, - ))), - )); - - chat.refresh_thread_usage_after_turn(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, /*estimated_usage_credits_micros*/ 50_000_000, - /*estimated_usage_usd_micros*/ None, - ))), - )); - - assert_eq!(chat.last_terminal_title, Some("50 credits".to_string())); - assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None); - assert_eq!(chat.thread_usage.settlement_baseline_usd_micros, None); - assert_eq!(chat.thread_usage.settlement_refresh_due_at, None); -} - -#[tokio::test] -async fn combined_billing_surfaces_wait_for_credits_and_cost() { - for (status_line_item, title_item) in [ - ("thread-credits", "estimated-thread-cost"), - ("estimated-thread-cost", "thread-credits"), - ] { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec![status_line_item.to_string()]); - chat.local_settings.tui.terminal_title = Some(vec![title_item.to_string()]); - chat.refresh_status_surfaces(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 40_000_000, - Some(1_820_000), - ))), - )); - - chat.refresh_thread_usage_after_turn(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 50_000_000, - Some(1_820_000), - ))), - )); - assert!(chat.thread_usage.settlement_refresh_due_at.is_some()); - - chat.thread_usage.settlement_refresh_due_at = Some(Instant::now()); - chat.refresh_thread_usage_if_settlement_due(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(thread_usage( - thread_id, - /*estimated_usage_credits_micros*/ 50_000_000, - Some(2_100_000), - ))), - )); - - assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None); - assert_eq!(chat.thread_usage.settlement_baseline_usd_micros, None); - assert_eq!(chat.thread_usage.settlement_refresh_due_at, None); - } -} - -#[tokio::test] -async fn billing_surfaces_render_for_every_supported_enterprise_plan() { - for plan_type in [ - PlanType::Business, - PlanType::EnterpriseCbpUsageBased, - PlanType::EnterpriseCbpAutomation, - PlanType::Ent26, - ] { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(plan_type); - chat.local_settings.tui.status_line = Some(vec![ - "thread-credits".to_string(), - "estimated-thread-cost".to_string(), - ]); - chat.local_settings.tui.terminal_title = chat.local_settings.tui.status_line.clone(); - chat.refresh_status_surfaces(); - let request_id = thread_usage_request_id(&mut rx); - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: Some(750_000), - ..thread_usage( - thread_id, - if plan_type == PlanType::Ent26 { - 0 - } else { - 5_200_000 - }, - Some(if plan_type == PlanType::Ent26 { - 0 - } else { - 210_000 - }), - ) - })), - )); - - assert!(rx.try_recv().is_err(), "billing surfaces share a request"); - if plan_type == PlanType::Ent26 { - insta::assert_snapshot!(chat.status_line_text().unwrap(), @"~$0.75"); - insta::assert_snapshot!(chat.last_terminal_title.as_ref().unwrap(), @"~$0.75"); - chat.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); - let status_cell = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell, - event => panic!("expected /status card, got {event:?}"), - }; - let usage_row = status_cell - .display_lines(/*width*/ 90) - .into_iter() - .map(|line| line.to_string()) - .find(|line| line.contains("Thread usage:")) - .unwrap(); - insta::assert_snapshot!(usage_row, @" Thread usage: ~$0.75"); - continue; - } - - assert_eq!( - chat.status_line_text(), - Some("5.2 credits · ~$0.21".to_string()) - ); - assert_eq!( - chat.last_terminal_title, - Some("5.2 credits | ~$0.21".to_string()) - ); - } -} - -#[tokio::test] -async fn early_draw_rearms_thread_usage_retry_after_immediate_redraw() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.refresh_status_line(); - - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected initial thread usage request, got {event:?}"), - }; - let (frame_requester, mut frame_rx) = FrameRequester::test_channel(); - chat.frame_requester = frame_requester; - - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Err("thread usage temporarily unavailable".to_string()), - )); - let retry_due_at = chat - .thread_usage - .retry_due_at - .expect("temporary failures schedule a retry"); - let scheduled = std::iter::from_fn(|| frame_rx.try_recv().ok()).collect::>(); - assert!(scheduled.iter().any(|deadline| *deadline >= retry_due_at)); - assert!(scheduled.iter().any(|deadline| *deadline < retry_due_at)); - - chat.pre_draw_tick(); - - let rearmed = std::iter::from_fn(|| frame_rx.try_recv().ok()) - .find(|deadline| *deadline >= retry_due_at) - .expect("the immediate redraw must re-arm the pending billing retry"); - assert!(rearmed.duration_since(retry_due_at) < Duration::from_secs(/*secs*/ 1)); -} - -#[tokio::test] -async fn unchanged_thread_usage_has_bounded_settlement_refreshes() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.refresh_status_line(); - - let initial_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected initial thread usage request, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - initial_request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 46_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - )); - - let (mut owner, _, _, _) = make_chatwidget_manual_with_sender().await; - owner.park_voice(); - chat.resume_background_voice(&mut owner); - for attempt in 0..=THREAD_USAGE_SETTLEMENT_DELAYS.len() { - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected settlement attempt {attempt}, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 46_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - )); - - if attempt < THREAD_USAGE_SETTLEMENT_DELAYS.len() { - assert!(chat.thread_usage.settlement_refresh_due_at.is_some()); - chat.thread_usage.settlement_refresh_due_at = Some(Instant::now()); - chat.refresh_thread_usage_if_settlement_due(); - } - } - - assert!(chat.thread_usage.settlement_refresh_due_at.is_none()); - assert!( - chat.thread_usage - .settlement_baseline_credits_micros - .is_none() - ); - assert!(rx.try_recv().is_err(), "settlement polling must stop"); -} - -#[tokio::test] -async fn early_draw_rearms_thread_usage_settlement_after_immediate_redraw() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.refresh_status_line(); - - let initial_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected initial thread usage request, got {event:?}"), - }; - let usage = ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 46_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - initial_request_id, - Ok(ThreadUsageOutcome::Available(usage.clone())), - )); - - let (frame_requester, mut frame_rx) = FrameRequester::test_channel(); - chat.frame_requester = frame_requester; - chat.refresh_thread_usage_after_turn(); - let settlement_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected immediate post-turn thread usage request, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - settlement_request_id, - Ok(ThreadUsageOutcome::Available(usage)), - )); - let settlement_due_at = chat - .thread_usage - .settlement_refresh_due_at - .expect("unchanged post-turn billing schedules a settlement refresh"); - let scheduled = std::iter::from_fn(|| frame_rx.try_recv().ok()).collect::>(); - assert!( - scheduled - .iter() - .any(|deadline| *deadline >= settlement_due_at) - ); - assert!( - scheduled - .iter() - .any(|deadline| *deadline < settlement_due_at) - ); - - chat.pre_draw_tick(); - - let rearmed = std::iter::from_fn(|| frame_rx.try_recv().ok()) - .find(|deadline| *deadline >= settlement_due_at) - .expect("the immediate redraw must re-arm the pending billing settlement"); - assert!(rearmed.duration_since(settlement_due_at) < Duration::from_secs(/*secs*/ 1)); -} - -#[tokio::test] -async fn thread_usage_settlement_requires_request_started_after_turn_completion() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.refresh_status_line(); - - let initial_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected initial thread usage request, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - initial_request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 40_000_000, - estimated_usage_usd_micros: Some(1_600_000), - groups: Vec::new(), - })), - )); - - chat.thread_usage.status_requested = true; - chat.request_thread_usage(); - let pre_turn_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected pre-turn thread usage request, got {event:?}"), - }; - chat.refresh_thread_usage_after_turn(); - assert_eq!(chat.thread_usage.settlement_request_id, None); - assert_eq!( - chat.thread_usage.settlement_baseline_credits_micros, - Some(40_000_000) - ); - - assert!(chat.finish_thread_usage_refresh( - thread_id, - pre_turn_request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 46_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - )); - let post_turn_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected a request started after turn completion, got {event:?}"), - }; - assert_eq!( - chat.thread_usage.settlement_baseline_credits_micros, - Some(46_000_000) - ); - assert!(chat.thread_usage.settlement_refresh_due_at.is_some()); - - assert!(chat.finish_thread_usage_refresh( - thread_id, - post_turn_request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 46_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - )); - assert!(chat.thread_usage.settlement_refresh_due_at.is_some()); - - chat.thread_usage.settlement_refresh_due_at = Some(Instant::now()); - chat.refresh_thread_usage_if_settlement_due(); - let settlement_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected another post-turn settlement request, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - settlement_request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 50_000_000, - estimated_usage_usd_micros: Some(2_100_000), - groups: Vec::new(), - })), - )); - assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None); - assert_eq!(chat.thread_usage.settlement_refresh_due_at, None); -} - -#[tokio::test] -async fn deselecting_billing_surfaces_cancels_polling_and_preserves_status_cache() { - let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Business); - chat.local_settings.tui.status_line = Some(vec!["estimated-thread-cost".to_string()]); - chat.local_settings.tui.terminal_title = Some(vec!["thread-credits".to_string()]); - chat.refresh_status_surfaces(); - - let initial_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected initial thread usage request, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - initial_request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 46_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - )); - - chat.thread_usage.status_requested = true; - chat.request_thread_usage(); - assert!(chat.thread_usage.status_requested); - let status_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected explicit /status refresh, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - status_request_id, - Err("thread usage temporarily unavailable".to_string()), - )); - assert!(!chat.thread_usage.status_requested); - assert!(chat.thread_usage.retry_due_at.is_some()); - - chat.refresh_thread_usage_after_turn(); - let settlement_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected post-turn thread usage refresh, got {event:?}"), - }; - assert!(chat.thread_usage.settlement_refresh_due_at.is_some()); - - chat.local_settings.tui.status_line = Some(Vec::new()); - chat.local_settings.tui.terminal_title = Some(Vec::new()); - chat.refresh_status_surfaces(); - - assert!(!chat.thread_usage.status_requested); - assert!(!chat.thread_usage.requested); - assert_eq!(chat.thread_usage.pending_request_id, None); - assert_eq!(chat.thread_usage.retry_due_at, None); - assert_eq!(chat.thread_usage.settlement_refresh_due_at, None); - assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None); - assert_eq!( - chat.estimated_thread_usage(), - Some(&ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 46_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - }) - ); - assert!(!chat.finish_thread_usage_refresh( - thread_id, - settlement_request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 50_000_000, - estimated_usage_usd_micros: Some(2_100_000), - groups: Vec::new(), - })), - )); - chat.refresh_thread_usage_if_settlement_due(); - assert!(rx.try_recv().is_err(), "deselected billing must not poll"); -} diff --git a/codex-rs/tui/src/chatwidget/usage.rs b/codex-rs/tui/src/chatwidget/usage.rs deleted file mode 100644 index 7d1f4201..00000000 --- a/codex-rs/tui/src/chatwidget/usage.rs +++ /dev/null @@ -1,601 +0,0 @@ -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse; -use codex_app_server_protocol::RateLimitResetCreditsSummary; -use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; -use uuid::Uuid; - -use super::reset_credits::reset_credit_options; -use super::*; - -const USAGE_MENU_VIEW_ID: &str = "usage-menu"; -const RATE_LIMIT_RESET_VIEW_ID: &str = "rate-limit-reset"; -const RATE_LIMIT_RESET_CONFIRMATION_VIEW_ID: &str = "rate-limit-reset-confirmation"; - -impl ChatWidget { - pub(super) fn open_usage_menu(&mut self) { - self.clear_pending_rate_limit_reset_hint(); - let should_refresh_reset_availability = self.available_rate_limit_reset_credits == Some(0); - self.bottom_pane - .show_selection_view(self.usage_menu_params()); - if should_refresh_reset_availability { - let request_id = self.take_next_rate_limit_reset_request_id(); - self.pending_usage_menu_rate_limit_request_id = Some(request_id); - self.app_event_tx.send(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::UsageMenu { request_id }, - }); - } - self.request_redraw(); - } - - fn usage_menu_params(&self) -> SelectionViewParams { - 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!("{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("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("Usage history".to_string()), - actions: vec![Box::new(|tx| { - tx.send(AppEvent::OpenAnalytics { view: None }); - })], - dismiss_on_select: true, - ..Default::default() - }, - SelectionItem { - name: "Redeem reset".to_string(), - description: Some(reset_description), - is_disabled: !reset_action_enabled, - actions: vec![Box::new(|tx| { - tx.send(AppEvent::OpenRateLimitResetCredits); - })], - dismiss_on_select: true, - ..Default::default() - }, - ], - ..SelectionViewParams::picker() - } - } - - pub(crate) fn finish_usage_menu_rate_limit_refresh( - &mut self, - request_id: u64, - snapshots: Vec, - result: Result, - ) { - if self.pending_usage_menu_rate_limit_request_id != Some(request_id) { - return; - } - self.pending_usage_menu_rate_limit_request_id = None; - for snapshot in snapshots { - self.on_rate_limit_snapshot(Some(snapshot)); - } - if let Ok(response) = result { - self.available_rate_limit_reset_credits = Some(response.available_count); - } - let params = self.usage_menu_params(); - if self - .bottom_pane - .replace_selection_view_if_present(USAGE_MENU_VIEW_ID, params) - { - self.request_redraw(); - } - } - - pub(crate) fn show_rate_limit_reset_loading_popup(&mut self) -> u64 { - self.clear_pending_rate_limit_reset_hint(); - self.pending_rate_limit_reset_idempotency_key = None; - self.rate_limit_reset_picker_request_id = None; - let request_id = self.take_next_rate_limit_reset_request_id(); - self.pending_rate_limit_reset_request_id = Some(request_id); - self.bottom_pane.show_selection_view(SelectionViewParams { - view_id: Some(RATE_LIMIT_RESET_VIEW_ID), - title: Some("Usage limit resets".to_string()), - subtitle: Some("Checking your available resets...".to_string()), - items: vec![SelectionItem { - name: "Loading...".to_string(), - is_disabled: true, - ..Default::default() - }], - ..SelectionViewParams::picker() - }); - self.request_redraw(); - request_id - } - - pub(crate) fn finish_rate_limit_reset_credits_refresh( - &mut self, - request_id: u64, - snapshots: Vec, - result: Result, - ) -> bool { - if self.pending_rate_limit_reset_request_id != Some(request_id) { - return false; - } - self.pending_rate_limit_reset_request_id = None; - for snapshot in snapshots { - self.on_rate_limit_snapshot(Some(snapshot)); - } - - let mut shows_picker = false; - let params = match result { - Ok(response) => { - let available_count = response.available_count; - let params = if available_count > 0 { - shows_picker = true; - self.rate_limit_reset_picker_params(request_id, &response) - } else { - Self::rate_limit_reset_message_params( - "You don't have any usage limit resets available.", - ) - }; - self.available_rate_limit_reset_credits = Some(available_count); - params - } - Err(_) => { - Self::reset_refresh_params("Couldn't load usage limit resets. Please try again.") - } - }; - let replaced = self - .bottom_pane - .replace_selection_view_if_present(RATE_LIMIT_RESET_VIEW_ID, params); - self.rate_limit_reset_picker_request_id = (replaced && shows_picker).then_some(request_id); - if replaced { - self.request_redraw(); - } - replaced - } - - fn rate_limit_reset_picker_params( - &self, - picker_request_id: u64, - reset_credits: &RateLimitResetCreditsSummary, - ) -> SelectionViewParams { - let confirmation_gate = Arc::new(AtomicBool::new(true)); - let mut items = reset_credit_options(reset_credits, self.clock_format) - .into_iter() - .map(|option| { - let confirmation_gate = confirmation_gate.clone(); - let credit_id = option.credit_id; - let reset_title = option.name.clone(); - let reset_detail = option.detail; - let reset_description = option.description; - let picker_description = reset_detail - .clone() - .unwrap_or_else(|| reset_description.clone()); - SelectionItem { - name: option.name, - description: Some(picker_description), - actions: vec![Box::new(move |tx| { - if confirmation_gate.swap(false, Ordering::AcqRel) { - tx.send(AppEvent::OpenRateLimitResetConfirmation { - picker_request_id, - confirmation_gate: confirmation_gate.clone(), - credit_id: credit_id.clone(), - reset_title: reset_title.clone(), - reset_detail: reset_detail.clone(), - reset_description: reset_description.clone(), - }); - } - })], - ..Default::default() - } - }) - .collect::>(); - items.push(SelectionItem { - name: "Cancel".to_string(), - dismiss_on_select: true, - ..Default::default() - }); - SelectionViewParams { - view_id: Some(RATE_LIMIT_RESET_VIEW_ID), - title: Some("Usage limit resets".to_string()), - subtitle: Some(format!( - "{} {} available.", - reset_credits.available_count, - reset_label(reset_credits.available_count) - )), - footer_hint: Some(usage_hint_line(&self.bottom_pane.list_keymap(), "choose")), - items, - initial_selected_idx: Some(0), - ..SelectionViewParams::picker() - } - } - - pub(crate) fn show_rate_limit_reset_confirmation( - &mut self, - picker_request_id: u64, - confirmation_gate: Arc, - credit_id: Option, - reset_title: String, - reset_detail: Option, - reset_description: String, - ) -> bool { - if self.rate_limit_reset_picker_request_id != Some(picker_request_id) - || self - .bottom_pane - .selected_index_for_active_view(RATE_LIMIT_RESET_VIEW_ID) - .is_none() - { - confirmation_gate.store(true, Ordering::Release); - return false; - } - let idempotency_key = Uuid::new_v4().to_string(); - self.pending_rate_limit_reset_idempotency_key = Some(idempotency_key.clone()); - let no_confirmation_gate = confirmation_gate.clone(); - let subtitle = reset_detail.map_or_else( - || reset_title.clone(), - |reset_detail| format!("{reset_title} · {reset_detail}"), - ); - self.bottom_pane.show_selection_view(SelectionViewParams { - view_id: Some(RATE_LIMIT_RESET_CONFIRMATION_VIEW_ID), - title: Some("Use this reset?".to_string()), - subtitle: Some(subtitle), - footer_hint: Some(usage_hint_line(&self.bottom_pane.list_keymap(), "confirm")), - items: vec![ - SelectionItem { - name: "Yes, use reset".to_string(), - description: Some(reset_description), - actions: vec![Box::new(move |tx| { - tx.send(AppEvent::ConsumeRateLimitResetCredit { - idempotency_key: idempotency_key.clone(), - credit_id: credit_id.clone(), - }); - })], - dismiss_on_select: true, - ..Default::default() - }, - SelectionItem { - name: "No, go back".to_string(), - description: Some("Choose a different reset".to_string()), - actions: vec![Box::new(move |_| { - no_confirmation_gate.store(true, Ordering::Release); - })], - dismiss_on_select: true, - ..Default::default() - }, - ], - initial_selected_idx: Some(1), - on_cancel: Some(Box::new(move |_| { - confirmation_gate.store(true, Ordering::Release); - })), - ..SelectionViewParams::confirmation() - }); - true - } - - pub(crate) fn start_rate_limit_reset_consumption( - &mut self, - idempotency_key: &str, - ) -> Option { - if self.pending_rate_limit_reset_idempotency_key.as_deref() != Some(idempotency_key) { - return None; - } - Some(self.show_rate_limit_reset_consuming_popup()) - } - - fn rate_limit_reset_message_params(message: &str) -> SelectionViewParams { - SelectionViewParams { - view_id: Some(RATE_LIMIT_RESET_VIEW_ID), - title: Some("Usage limit resets".to_string()), - subtitle: Some(message.to_string()), - items: vec![SelectionItem { - name: "Close".to_string(), - dismiss_on_select: true, - ..Default::default() - }], - ..SelectionViewParams::picker() - } - } - - fn reset_refresh_params(message: &str) -> SelectionViewParams { - SelectionViewParams { - view_id: Some(RATE_LIMIT_RESET_VIEW_ID), - title: Some("Usage limit resets".to_string()), - subtitle: Some(message.to_string()), - items: vec![ - SelectionItem { - name: "Try again".to_string(), - actions: vec![Box::new(|tx| { - tx.send(AppEvent::OpenRateLimitResetCredits); - })], - dismiss_on_select: true, - ..Default::default() - }, - SelectionItem { - name: "Close".to_string(), - dismiss_on_select: true, - ..Default::default() - }, - ], - ..SelectionViewParams::picker() - } - } - - pub(crate) fn show_rate_limit_reset_consuming_popup(&mut self) -> u64 { - self.clear_pending_rate_limit_reset_hint(); - self.pending_rate_limit_reset_idempotency_key = None; - self.rate_limit_reset_picker_request_id = None; - let request_id = self.take_next_rate_limit_reset_request_id(); - self.pending_rate_limit_reset_request_id = Some(request_id); - self.bottom_pane - .dismiss_view_by_id(RATE_LIMIT_RESET_CONFIRMATION_VIEW_ID); - self.bottom_pane - .dismiss_view_by_id(RATE_LIMIT_RESET_VIEW_ID); - self.bottom_pane.show_selection_view(SelectionViewParams { - view_id: Some(RATE_LIMIT_RESET_VIEW_ID), - title: Some("Usage limit resets".to_string()), - subtitle: Some("Resetting your usage...".to_string()), - items: vec![SelectionItem { - name: "Using a reset...".to_string(), - is_disabled: true, - ..Default::default() - }], - allow_cancel: false, - ..SelectionViewParams::picker() - }); - self.request_redraw(); - request_id - } - - pub(crate) fn finish_rate_limit_reset_consume( - &mut self, - request_id: u64, - idempotency_key: String, - credit_id: Option, - result: Result, - ) -> bool { - if self.pending_rate_limit_reset_request_id != Some(request_id) { - return false; - } - - match result { - Ok(response) - if matches!( - response.outcome, - ConsumeAccountRateLimitResetCreditOutcome::Reset - | ConsumeAccountRateLimitResetCreditOutcome::AlreadyRedeemed - ) => - { - self.available_rate_limit_reset_credits = None; - self.replace_rate_limit_reset_popup(Self::rate_limit_reset_success_loading_params()); - true - } - Ok(response) => { - self.pending_rate_limit_reset_request_id = None; - let message = match response.outcome { - ConsumeAccountRateLimitResetCreditOutcome::NothingToReset => { - "Your usage does not need a reset right now." - } - ConsumeAccountRateLimitResetCreditOutcome::NoCredit if credit_id.is_some() => { - self.available_rate_limit_reset_credits = None; - self.replace_rate_limit_reset_popup(Self::reset_refresh_params( - "That reset is no longer available. Refresh to see your current resets.", - )); - return false; - } - ConsumeAccountRateLimitResetCreditOutcome::NoCredit => { - self.available_rate_limit_reset_credits = Some(0); - "No usage limit resets are available." - } - ConsumeAccountRateLimitResetCreditOutcome::Reset - | ConsumeAccountRateLimitResetCreditOutcome::AlreadyRedeemed => unreachable!(), - }; - self.replace_rate_limit_reset_popup(Self::rate_limit_reset_message_params(message)); - false - } - Err(_) => { - self.pending_rate_limit_reset_request_id = None; - self.pending_rate_limit_reset_idempotency_key = Some(idempotency_key.clone()); - self.replace_rate_limit_reset_popup(SelectionViewParams { - view_id: Some(RATE_LIMIT_RESET_VIEW_ID), - title: Some("Usage limit resets".to_string()), - subtitle: Some("Couldn't reset usage. Please try again.".to_string()), - items: vec![ - SelectionItem { - name: "Try again".to_string(), - actions: vec![Box::new(move |tx| { - tx.send(AppEvent::ConsumeRateLimitResetCredit { - idempotency_key: idempotency_key.clone(), - credit_id: credit_id.clone(), - }); - })], - dismiss_on_select: true, - ..Default::default() - }, - SelectionItem { - name: "Close".to_string(), - dismiss_on_select: true, - ..Default::default() - }, - ], - ..SelectionViewParams::picker() - }); - false - } - } - } - - pub(crate) fn finish_post_consume_reset_credits_refresh( - &mut self, - request_id: u64, - snapshots: Vec, - result: Result, - ) -> bool { - if self.pending_rate_limit_reset_request_id != Some(request_id) { - return false; - } - self.pending_rate_limit_reset_request_id = None; - for snapshot in snapshots { - self.on_rate_limit_snapshot(Some(snapshot)); - } - - let message = match result { - Ok(response) => { - let available_count = response.available_count; - self.available_rate_limit_reset_credits = Some(available_count); - format!( - "Usage reset. You have {available_count} {} left.", - reset_label(available_count) - ) - } - Err(_) => "Usage reset.".to_string(), - }; - self.replace_rate_limit_reset_popup(Self::rate_limit_reset_message_params(&message)); - true - } - - fn rate_limit_reset_success_loading_params() -> SelectionViewParams { - SelectionViewParams { - view_id: Some(RATE_LIMIT_RESET_VIEW_ID), - title: Some("Usage limit resets".to_string()), - subtitle: Some("Usage reset. Checking your remaining resets...".to_string()), - items: vec![SelectionItem { - name: "Refreshing...".to_string(), - is_disabled: true, - ..Default::default() - }], - allow_cancel: false, - ..SelectionViewParams::picker() - } - } - - fn replace_rate_limit_reset_popup(&mut self, params: SelectionViewParams) { - if self - .bottom_pane - .replace_selection_view_if_present(RATE_LIMIT_RESET_VIEW_ID, params) - { - self.request_redraw(); - } - } - - pub(crate) fn start_rate_limit_reset_startup_check(&mut self) -> u64 { - self.clear_pending_rate_limit_reset_hint(); - let request_id = self.take_next_rate_limit_reset_request_id(); - self.pending_rate_limit_reset_hint_request_id = Some(request_id); - request_id - } - - pub(crate) fn finish_rate_limit_reset_hint_refresh( - &mut self, - request_id: u64, - snapshots: Vec, - result: Result, - ) -> bool { - if self.pending_rate_limit_reset_hint_request_id != Some(request_id) { - return false; - } - self.pending_rate_limit_reset_hint_request_id = None; - for snapshot in snapshots { - self.on_rate_limit_snapshot(Some(snapshot)); - } - if !self.has_codex_backend_auth { - return false; - } - if let Ok(response) = result { - let available_count = response.available_count; - self.available_rate_limit_reset_credits = Some(available_count); - self.set_rate_limit_reset_available_hint(available_count); - } - true - } - - pub(crate) fn clear_pending_rate_limit_reset_requests(&mut self) { - self.pending_rate_limit_reset_request_id = None; - self.pending_rate_limit_reset_idempotency_key = None; - self.rate_limit_reset_picker_request_id = None; - self.pending_usage_menu_rate_limit_request_id = None; - self.available_rate_limit_reset_credits = None; - self.rate_limit_snapshots_by_limit_id.clear(); - self.clear_pending_rate_limit_reset_hint(); - self.bottom_pane.dismiss_view_by_id(USAGE_MENU_VIEW_ID); - self.bottom_pane - .dismiss_view_by_id(RATE_LIMIT_RESET_VIEW_ID); - self.bottom_pane - .dismiss_view_by_id(RATE_LIMIT_RESET_CONFIRMATION_VIEW_ID); - } - - pub(crate) fn clear_pending_rate_limit_reset_hint(&mut self) { - self.pending_rate_limit_reset_hint_request_id = None; - let cleared_hint = self.pending_rate_limit_reset_hint.take().is_some(); - if cleared_hint { - self.bump_active_cell_revision(); - self.request_redraw(); - } - } - - pub(super) fn pending_rate_limit_reset_hint(&self) -> Option<&PlainHistoryCell> { - self.pending_rate_limit_reset_hint.as_ref() - } - - pub(crate) fn take_pending_rate_limit_reset_hint(&mut self) -> Option { - let hint = self.pending_rate_limit_reset_hint.take()?; - self.bump_active_cell_revision(); - Some(hint) - } - - fn set_rate_limit_reset_available_hint(&mut self, available_count: i64) { - if available_count <= 0 { - return; - } - self.pending_rate_limit_reset_hint = Some(history_cell::new_info_event( - format!( - "You have {available_count} {} available. Run /usage to use one.", - reset_label(available_count) - ), - /*hint*/ None, - )); - self.bump_active_cell_revision(); - self.request_redraw(); - } - - fn take_next_rate_limit_reset_request_id(&mut self) -> u64 { - let request_id = self.next_rate_limit_reset_request_id; - self.next_rate_limit_reset_request_id = self - .next_rate_limit_reset_request_id - .wrapping_add(/*rhs*/ 1); - request_id - } -} - -/// 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" - } else { - "usage limit resets" - } -} diff --git a/codex-rs/tui/src/status/thread_usage.rs b/codex-rs/tui/src/status/thread_usage.rs deleted file mode 100644 index ef419ad2..00000000 --- a/codex-rs/tui/src/status/thread_usage.rs +++ /dev/null @@ -1,356 +0,0 @@ -//! Live-updating, thread-scoped billing details embedded in `/status` history cards. - -use super::format::FieldFormatter; -use super::format::push_label; -use super::helpers::format_tokens_compact; -use crate::wrapping::RtOptions; -use crate::wrapping::word_wrap_lines; -use codex_app_server_protocol::ThreadUsage; -use codex_app_server_protocol::ThreadUsageBreakdownGroup; -use codex_protocol::account::PlanType; -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; - -const REASONING_ORDER: [&str; 8] = [ - "None", - "Minimal", - "Light", - "Medium", - "High", - "Extra High", - "Max", - "Ultra", -]; -const SPEED_ORDER: [&str; 3] = ["Fast mode", "Ultrafast", "Standard"]; -const MODELS_LABEL: &str = " Models"; -const REASONING_LABEL: &str = " Reasoning"; -const SPEED_LABEL: &str = " Speed"; -const BILLED_TOKENS_LABEL: &str = " Billed tokens"; - -/// ENT26 is billed directly in dollars; missing native usage is not a zero estimate. -pub(crate) fn thread_cost_micros(usage: &ThreadUsage, plan_type: Option) -> Option { - if plan_type == Some(PlanType::Ent26) { - usage.native_usage_usd_micros - } else { - usage.estimated_usage_usd_micros - } -} - -/// Shared state updates a committed `/status` card when its asynchronous estimate arrives. -#[derive(Clone, Debug, Default)] -pub(crate) struct StatusThreadUsage { - estimate: Arc>>, - reserve_label_width: Arc, -} - -impl StatusThreadUsage { - pub(crate) fn reserve_label_width(&self) { - self.reserve_label_width - .store(/*val*/ true, Ordering::Relaxed); - } - - pub(crate) fn set_estimate(&self, estimate: Option) { - #[expect(clippy::expect_used)] - let mut stored_estimate = self - .estimate - .write() - .expect("status history thread-usage state poisoned"); - *stored_estimate = estimate; - } - - pub(crate) fn push_labels(&self, labels: &mut Vec, seen: &mut BTreeSet) { - // Keep existing card rows stable when asynchronous billing details arrive. Reserving a - // formatter label does not emit a loading placeholder or an empty billing row. - if self.reserve_label_width.load(Ordering::Relaxed) { - push_label(labels, seen, BILLED_TOKENS_LABEL); - } - #[expect(clippy::expect_used)] - let stored_estimate = self - .estimate - .read() - .expect("status history thread-usage state poisoned"); - let Some(estimate) = stored_estimate.as_ref() else { - return; - }; - push_label(labels, seen, "Thread usage"); - if !estimate.groups.is_empty() { - push_label(labels, seen, MODELS_LABEL); - push_label(labels, seen, REASONING_LABEL); - push_label(labels, seen, SPEED_LABEL); - if estimate - .groups - .iter() - .any(|group| group.input_tokens.is_some() || group.output_tokens.is_some()) - { - push_label(labels, seen, BILLED_TOKENS_LABEL); - } - } - } - - pub(crate) fn lines( - &self, - formatter: &FieldFormatter, - value_width: usize, - plan_type: Option, - ) -> Vec> { - #[expect(clippy::expect_used)] - let stored_estimate = self - .estimate - .read() - .expect("status history thread-usage state poisoned"); - let Some(estimate) = stored_estimate.as_ref() else { - return Vec::new(); - }; - - if plan_type == Some(PlanType::Ent26) { - // Credit-weighted breakdowns do not describe native dollar usage. - return thread_cost_micros(estimate, plan_type) - .and_then(format_estimated_usd_micros) - .map(|cost| vec![formatter.line("Thread usage", vec![cost.into()])]) - .unwrap_or_default(); - } - - let credits_micros = estimate.estimated_usage_credits_micros; - let mut usage = vec![format!("{} credits", format_credit_micros(credits_micros)).into()]; - if let Some(cost) = estimate - .estimated_usage_usd_micros - .and_then(format_estimated_usd_micros) - { - usage.push(" · ".dim()); - usage.push(cost.into()); - } - let mut lines = vec![formatter.line("Thread usage", usage)]; - - for (label, dimension) in [ - (MODELS_LABEL, BreakdownDimension::Model), - (REASONING_LABEL, BreakdownDimension::Reasoning), - (SPEED_LABEL, BreakdownDimension::Speed), - ] { - let Some(value) = grouped_usage(&estimate.groups, dimension) else { - continue; - }; - let mut wrapped = word_wrap_lines( - [Line::from(value)], - RtOptions::new(value_width.max(/*other*/ 1)), - ) - .into_iter(); - if let Some(first) = wrapped.next() { - lines.push(formatter.line(label, first.spans)); - lines.extend(wrapped.map(|line| formatter.continuation(line.spans))); - } - } - - let sum_tokens = |count: fn(&ThreadUsageBreakdownGroup) -> Option| { - estimate - .groups - .iter() - .try_fold(/*init*/ 0_i64, |total, group| { - count(group).map(|tokens| total.saturating_add(tokens)) - }) - }; - let input_tokens = sum_tokens(|group| group.input_tokens); - let cached_tokens = sum_tokens(|group| group.cached_input_tokens); - let output_tokens = sum_tokens(|group| group.output_tokens); - if !estimate.groups.is_empty() && (input_tokens.is_some() || output_tokens.is_some()) { - let mut tokens = Vec::new(); - if let Some(input_tokens) = input_tokens { - tokens.push(format!("{} input", format_tokens_compact(input_tokens))); - if let Some(cached_tokens) = cached_tokens { - tokens.push(format!("({} cached)", format_tokens_compact(cached_tokens))); - } - } - if let Some(output_tokens) = output_tokens { - if !tokens.is_empty() { - tokens.push("+".to_string()); - } - tokens.push(format!("{} output", format_tokens_compact(output_tokens))); - } - lines.push(formatter.line(BILLED_TOKENS_LABEL, vec![tokens.join(" ").into()])); - } - - lines - } -} - -#[derive(Clone, Copy)] -enum BreakdownDimension { - Model, - Reasoning, - Speed, -} - -fn grouped_usage( - groups: &[ThreadUsageBreakdownGroup], - dimension: BreakdownDimension, -) -> Option { - let mut totals = BTreeMap::::new(); - for group in groups { - if group.estimated_usage_credits_micros < 0 { - continue; - } - let value = match dimension { - BreakdownDimension::Model => group - .model - .as_deref() - .map(format_model_display_name) - .unwrap_or_else(|| "Other".to_string()), - BreakdownDimension::Reasoning => match group.reasoning_effort.as_deref() { - Some("none") => "None", - Some("minimal") => "Minimal", - Some("low") => "Light", - Some("medium") => "Medium", - Some("high") => "High", - Some("xhigh") => "Extra High", - Some("max") => "Max", - Some("ultra") => "Ultra", - Some(other) => other, - None => "Other", - } - .to_string(), - BreakdownDimension::Speed => match group.speed.as_deref() { - Some("fast") => "Fast mode", - Some("ultrafast") => "Ultrafast", - Some("standard") => "Standard", - Some(other) => other, - None => "Other", - } - .to_string(), - }; - let total = totals.entry(value).or_default(); - *total = total.saturating_add(group.estimated_usage_credits_micros); - } - if totals.is_empty() { - return None; - } - - let total_credits_micros = - totals.values().fold( - /*init*/ 0_i64, - |total, credits| total.saturating_add(*credits), - ); - let mut totals = totals.into_iter().collect::>(); - totals.sort_by( - |(left_name, left_credits), (right_name, right_credits)| match dimension { - BreakdownDimension::Model => right_credits - .cmp(left_credits) - .then_with(|| left_name.cmp(right_name)), - BreakdownDimension::Reasoning => REASONING_ORDER - .iter() - .position(|value| value == left_name) - .unwrap_or(usize::MAX) - .cmp( - &REASONING_ORDER - .iter() - .position(|value| value == right_name) - .unwrap_or(usize::MAX), - ) - .then_with(|| left_name.cmp(right_name)), - BreakdownDimension::Speed => SPEED_ORDER - .iter() - .position(|value| value == left_name) - .unwrap_or(usize::MAX) - .cmp( - &SPEED_ORDER - .iter() - .position(|value| value == right_name) - .unwrap_or(usize::MAX), - ) - .then_with(|| left_name.cmp(right_name)), - }, - ); - Some( - totals - .into_iter() - .map(|(name, credits)| { - let percentage = if total_credits_micros <= 0 { - 0 - } else { - (i128::from(credits) * 100 + i128::from(total_credits_micros) / 2) - / i128::from(total_credits_micros) - }; - format!("{name} {percentage}%") - }) - .collect::>() - .join(", "), - ) -} - -fn format_model_display_name(model: &str) -> String { - let model = crate::model_catalog::model_display_name(model); - let Some((prefix, remainder)) = model.split_once('-') else { - return model.to_string(); - }; - if !prefix.eq_ignore_ascii_case("gpt") || remainder.is_empty() { - return model.to_string(); - } - - let mut segments = remainder.split('-'); - let first = segments.next().unwrap_or_default(); - let mut display_name = format!("GPT-{first}"); - let numeric_model = first - .chars() - .next() - .is_some_and(|character| character.is_ascii_digit()); - for segment in segments { - display_name.push(if numeric_model { ' ' } else { '-' }); - if segment.eq_ignore_ascii_case("oai") { - display_name.push_str("OAI"); - continue; - } - - let mut characters = segment.chars(); - if let Some(first_character) = characters.next() { - display_name.extend(first_character.to_uppercase()); - display_name.push_str(characters.as_str()); - } - } - - display_name -} - -pub(crate) fn format_credit_micros(micros: i64) -> String { - let micros = i128::from(micros.max(/*other*/ 0)); - let (unit_micros, suffix) = [ - (1_000_000_000_000_000_000_i128, "T"), - (1_000_000_000_000_000_i128, "B"), - (1_000_000_000_000_i128, "M"), - (1_000_000_000_i128, "K"), - ] - .into_iter() - .find(|(unit, _)| micros >= *unit) - .unwrap_or((1_000_000, "")); - let tenths = (micros * 10 + unit_micros / 2) / unit_micros; - let whole = tenths / 10; - let fraction = tenths % 10; - if fraction == 0 { - format!("{whole}{suffix}") - } else { - format!("{whole}.{fraction}{suffix}") - } -} - -pub(crate) fn format_estimated_usd_micros(micros: i64) -> Option { - if micros < 0 { - return None; - } - if micros > 0 && micros < 100 { - return Some(format!("~$0.{micros:06}")); - } - if micros > 0 && micros < 10_000 { - let ten_thousandths = micros.saturating_add(/*rhs*/ 50) / 100; - return Some(format!("~$0.{ten_thousandths:04}")); - } - - let cents = micros.saturating_add(/*rhs*/ 5_000) / 10_000; - Some(format!("~${}.{:02}", cents / 100, cents % 100)) -} - -#[cfg(test)] -#[path = "thread_usage_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/status/thread_usage_tests.rs b/codex-rs/tui/src/status/thread_usage_tests.rs deleted file mode 100644 index e05a879b..00000000 --- a/codex-rs/tui/src/status/thread_usage_tests.rs +++ /dev/null @@ -1,70 +0,0 @@ -use super::BreakdownDimension; -use super::format_credit_micros; -use super::format_model_display_name; -use super::grouped_usage; -use codex_app_server_protocol::ThreadUsageBreakdownGroup; -use pretty_assertions::assert_eq; - -#[test] -fn thread_usage_breakdown_groups_aggregate_model_credit_percentages() { - let group = ThreadUsageBreakdownGroup { - model: Some("gpt-5.4".to_string()), - reasoning_effort: Some("high".to_string()), - speed: Some("fast".to_string()), - estimated_usage_credits_micros: 30_000_000, - net_new_input_tokens: Some(60), - cached_input_tokens: Some(10), - input_tokens: Some(70), - output_tokens: Some(20), - total_tokens: Some(90), - }; - let groups = vec![ - group.clone(), - ThreadUsageBreakdownGroup { - reasoning_effort: Some("medium".to_string()), - speed: Some("standard".to_string()), - estimated_usage_credits_micros: 10_000_000, - ..group.clone() - }, - ThreadUsageBreakdownGroup { - model: Some("gpt-5-mini".to_string()), - reasoning_effort: Some("low".to_string()), - speed: Some("standard".to_string()), - estimated_usage_credits_micros: 10_000_000, - ..group - }, - ]; - - assert_eq!( - grouped_usage(&groups, BreakdownDimension::Model), - Some("GPT-5.4 80%, GPT-5 Mini 20%".to_string()) - ); - assert_eq!( - grouped_usage(&groups, BreakdownDimension::Reasoning), - Some("Light 20%, Medium 20%, High 60%".to_string()) - ); - assert_eq!( - grouped_usage(&groups, BreakdownDimension::Speed), - Some("Fast mode 60%, Standard 40%".to_string()) - ); -} - -#[test] -fn thread_usage_credit_formatting_rounds_to_one_decimal_place() { - assert_eq!(format_credit_micros(/*micros*/ 0), "0"); - assert_eq!(format_credit_micros(/*micros*/ 400_000), "0.4"); - assert_eq!(format_credit_micros(/*micros*/ 5_200_000), "5.2"); - assert_eq!(format_credit_micros(/*micros*/ 5_240_000), "5.2"); - assert_eq!(format_credit_micros(/*micros*/ 5_250_000), "5.3"); - assert_eq!(format_credit_micros(/*micros*/ 46_000_000), "46"); - assert_eq!(format_credit_micros(/*micros*/ 1_240_000_000), "1.2K"); - assert_eq!(format_credit_micros(/*micros*/ 12_400_000_000), "12.4K"); -} - -#[test] -fn thread_usage_model_names_match_desktop_display_names() { - assert_eq!(format_model_display_name("gpt-5.4"), "GPT-5.4"); - assert_eq!(format_model_display_name("gpt-5-mini"), "GPT-5 Mini"); - assert_eq!(format_model_display_name("gpt-5.6-sol"), "GPT-5.6 Sol"); - assert_eq!(format_model_display_name("examplemodel"), "examplemodel"); -} diff --git a/codex-rs/tui/src/workspace_messages.rs b/codex-rs/tui/src/workspace_messages.rs deleted file mode 100644 index 4f5695f8..00000000 --- a/codex-rs/tui/src/workspace_messages.rs +++ /dev/null @@ -1,29 +0,0 @@ -use codex_app_server_protocol::GetWorkspaceMessagesResponse; -use codex_app_server_protocol::WorkspaceMessageType; -use std::time::Duration; - -pub(crate) const WORKSPACE_HEADLINE_REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60); - -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) enum WorkspaceHeadlineFetchResult { - Available(Option), - FeatureDisabled, -} - -pub(crate) fn workspace_headline_from_response( - response: GetWorkspaceMessagesResponse, -) -> WorkspaceHeadlineFetchResult { - if !response.feature_enabled { - return WorkspaceHeadlineFetchResult::FeatureDisabled; - } - - WorkspaceHeadlineFetchResult::Available(response.messages.into_iter().find_map(|message| { - (message.message_type == WorkspaceMessageType::Headline) - .then(|| message.message_body.trim().to_string()) - .filter(|headline| !headline.is_empty()) - })) -} - -#[cfg(test)] -#[path = "workspace_messages_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/workspace_messages_tests.rs b/codex-rs/tui/src/workspace_messages_tests.rs deleted file mode 100644 index 962d2ceb..00000000 --- a/codex-rs/tui/src/workspace_messages_tests.rs +++ /dev/null @@ -1,51 +0,0 @@ -use super::*; -use codex_app_server_protocol::WorkspaceMessage; -use pretty_assertions::assert_eq; - -#[test] -fn workspace_headline_from_response_uses_first_non_empty_headline() { - let response = GetWorkspaceMessagesResponse { - feature_enabled: true, - messages: vec![ - WorkspaceMessage { - message_id: "announcement-id".to_string(), - message_type: WorkspaceMessageType::Announcement, - message_body: "Announcement body".to_string(), - created_at: None, - archived_at: None, - }, - WorkspaceMessage { - message_id: "empty-headline-id".to_string(), - message_type: WorkspaceMessageType::Headline, - message_body: " ".to_string(), - created_at: None, - archived_at: None, - }, - WorkspaceMessage { - message_id: "headline-id".to_string(), - message_type: WorkspaceMessageType::Headline, - message_body: " Workspace headline ".to_string(), - created_at: None, - archived_at: None, - }, - ], - }; - - assert_eq!( - workspace_headline_from_response(response), - WorkspaceHeadlineFetchResult::Available(Some("Workspace headline".to_string())) - ); -} - -#[test] -fn workspace_headline_from_response_reports_feature_disabled() { - let response = GetWorkspaceMessagesResponse { - feature_enabled: false, - messages: Vec::new(), - }; - - assert_eq!( - workspace_headline_from_response(response), - WorkspaceHeadlineFetchResult::FeatureDisabled - ); -}