From 981745ccc8109d8ac42f8857cc49ae57062ff399 Mon Sep 17 00:00:00 2001 From: Andrea Date: Mon, 9 Nov 2026 16:24:36 +0100 Subject: [PATCH] aKode fase 2b-1: rimossi plugin remoti e share, bundle download, UI usage/crediti/banner/workspace ChatGPT; fix argomenti MCP (inviati vuoti dopo e4209e2) e overlay TUI; test analytics-upload rimossi; test sicurezza MCP adattati --- README.md | 3 +- codex-rs/Cargo.lock | 1 - codex-rs/app-server/README.md | 18 - codex-rs/app-server/src/request_processors.rs | 9 - .../request_processors/account_processor.rs | 1 - .../src/request_processors/plugins.rs | 402 +---- codex-rs/cli/src/debug_sandbox.rs | 1 - .../src/client_capabilities_tests.rs | 7 +- .../codex-mcp/src/connection_manager_tests.rs | 30 +- codex-rs/codex-mcp/src/elicitation_tests.rs | 44 +- codex-rs/codex-mcp/src/mcp/mod.rs | 32 + codex-rs/codex-mcp/src/mcp/mod_tests.rs | 168 +- codex-rs/core-plugins/src/lib.rs | 1 - .../core-plugins/src/plugin_bundle_archive.rs | 1 - codex-rs/core-plugins/src/remote.rs | 136 +- .../remote/remote_installed_plugin_sync.rs | 83 +- codex-rs/core-plugins/src/remote/search.rs | 1 - codex-rs/core-plugins/src/remote/share.rs | 88 - .../src/remote/share/local_paths.rs | 61 +- codex-rs/core-plugins/src/remote_mutations.rs | 121 +- .../core-plugins/src/script_attribution.rs | 1 - codex-rs/core/src/codex_delegate_tests.rs | 80 - codex-rs/core/src/mcp_tool_call.rs | 3 +- codex-rs/core/src/mcp_tool_call_tests.rs | 148 -- codex-rs/core/src/session/tests.rs | 245 --- codex-rs/core/src/thread_manager_tests.rs | 284 +--- .../core/tests/common/apps_test_server.rs | 13 + .../core/tests/suite/app_tool_exposure.rs | 7 +- codex-rs/core/tests/suite/code_mode.rs | 32 +- codex-rs/core/tests/suite/mcp_auth_refresh.rs | 9 +- .../core/tests/suite/realtime_conversation.rs | 22 +- .../tests/suite/realtime_initial_items.rs | 8 +- codex-rs/exec-server-cli/src/config.rs | 6 - codex-rs/ext/mcp/src/cloud_plugin_tests.rs | 468 ------ codex-rs/tui/Cargo.toml | 1 - codex-rs/tui/src/app.rs | 14 +- codex-rs/tui/src/app/agents_overview.rs | 2 - .../tui/src/app/agents_overview_details.rs | 7 +- codex-rs/tui/src/app/agents_overview_tests.rs | 3 - codex-rs/tui/src/app/agents_overview_usage.rs | 22 + codex-rs/tui/src/app/app_server_events.rs | 38 +- codex-rs/tui/src/app/backend_selection.rs | 4 - codex-rs/tui/src/app/background_requests.rs | 351 ---- codex-rs/tui/src/app/composer_hints_tests.rs | 14 +- .../src/app/empty_state_animation_tests.rs | 18 - codex-rs/tui/src/app/event_dispatch.rs | 314 +--- codex-rs/tui/src/app/history_ui.rs | 191 +-- codex-rs/tui/src/app/reconnect.rs | 3 - codex-rs/tui/src/app/resize_reflow.rs | 19 +- codex-rs/tui/src/app/session_lifecycle.rs | 9 +- ...__tests__usage__agents_overview_usage.snap | 28 - codex-rs/tui/src/app/startup.rs | 30 - codex-rs/tui/src/app/test_support.rs | 5 - codex-rs/tui/src/app/tests.rs | 21 - .../src/app/tests/active_reconnect_tests.rs | 14 - .../tui/src/app/tests/backend_event_tests.rs | 2 - .../app/tests/local_command_scroll_tests.rs | 55 - .../app/tests/session_lifecycle_requests.rs | 4 - ..._tests__backend_banner_after_fallback.snap | 14 - ...tests__backend_banner_fallback_notice.snap | 5 - ...__backend_banner_fallback_unavailable.snap | 7 - ...ts__luna_reserve_settings_unavailable.snap | 11 - ...y_tests__luna_reserve_recovery_notice.snap | 5 - .../tui/src/app/tests/transcript_composer.rs | 177 -- codex-rs/tui/src/app_backtrack.rs | 10 +- codex-rs/tui/src/app_event.rs | 139 -- codex-rs/tui/src/app_event_sender.rs | 1 - codex-rs/tui/src/app_server_session.rs | 66 - .../tui/src/bottom_pane/actionable_banner.rs | 4 - codex-rs/tui/src/bottom_pane/chat_composer.rs | 9 - .../bottom_pane/chat_composer/slash_input.rs | 2 - codex-rs/tui/src/bottom_pane/command_popup.rs | 3 - codex-rs/tui/src/bottom_pane/mod.rs | 59 - .../tui/src/bottom_pane/slash_commands.rs | 27 - ..._snapshot_includes_thread_usage_items.snap | 21 - .../tui/src/bottom_pane/status_line_setup.rs | 59 - .../tui/src/bottom_pane/status_line_style.rs | 28 +- .../src/bottom_pane/status_surface_preview.rs | 9 - .../tests/actionable_banner_tests.rs | 60 - codex-rs/tui/src/bottom_pane/title_setup.rs | 29 - codex-rs/tui/src/chatwidget.rs | 55 +- codex-rs/tui/src/chatwidget/constructor.rs | 26 +- codex-rs/tui/src/chatwidget/hook_lifecycle.rs | 4 - codex-rs/tui/src/chatwidget/input_flow.rs | 5 +- codex-rs/tui/src/chatwidget/input_queue.rs | 3 - codex-rs/tui/src/chatwidget/input_restore.rs | 3 +- .../tui/src/chatwidget/input_submission.rs | 5 +- codex-rs/tui/src/chatwidget/interaction.rs | 1 - codex-rs/tui/src/chatwidget/model_command.rs | 6 - codex-rs/tui/src/chatwidget/model_popups.rs | 22 +- codex-rs/tui/src/chatwidget/protocol.rs | 12 +- codex-rs/tui/src/chatwidget/quick_dials.rs | 1 - codex-rs/tui/src/chatwidget/rate_limits.rs | 280 +--- .../tui/src/chatwidget/realtime_navigation.rs | 2 - .../chatwidget/realtime_tests/lifecycle.rs | 9 - codex-rs/tui/src/chatwidget/rendering.rs | 15 - .../tui/src/chatwidget/rendering_tests.rs | 10 - codex-rs/tui/src/chatwidget/security_setup.rs | 10 +- codex-rs/tui/src/chatwidget/session_flow.rs | 18 - codex-rs/tui/src/chatwidget/settings.rs | 33 +- codex-rs/tui/src/chatwidget/slash_dispatch.rs | 43 +- ...ests__rate_limit_reset_available_hint.snap | 5 - ..._tests__rate_limit_reset_confirmation.snap | 13 - ...it_reset_hint_waits_for_active_output.snap | 7 - ...tests__rate_limit_reset_picker_narrow.snap | 14 - ..._tests__rate_limit_reset_popup_states.snap | 83 - ...and_reports_chatgpt_login_requirement.snap | 5 - ...idget__tests__slash_copy_whole_status.snap | 4 - ...status_command_estimated_thread_usage.snap | 9 - ...nd_estimated_thread_usage_without_usd.snap | 9 - ...tus_line_estimated_thread_cost_footer.snap | 9 - ...s_line_setup_popup_workspace_headline.snap | 20 - ..._status_surface_previews_thread_usage.snap | 6 - ...rminal_title_setup_popup_thread_usage.snap | 20 - ...chatwidget__tests__usage_command_menu.snap | 12 - ...age_command_menu_before_reset_refresh.snap | 12 - ...get__tests__usage_command_menu_narrow.snap | 12 - ...ts__usage_command_menu_without_resets.snap | 12 - ...mmand_with_invalid_view_reports_usage.snap | 5 - ...kspace_member_credits_depleted_prompt.snap | 12 - ...__workspace_member_usage_limit_prompt.snap | 12 - ...ner_credits_nudge_completion_feedback.snap | 11 - ..._workspace_owner_limit_state_messages.snap | 8 - ...usage_limit_nudge_completion_feedback.snap | 11 - .../tui/src/chatwidget/startup_submission.rs | 1 - .../tui/src/chatwidget/status_controls.rs | 68 +- .../tui/src/chatwidget/status_surfaces.rs | 133 -- codex-rs/tui/src/chatwidget/streaming.rs | 5 - codex-rs/tui/src/chatwidget/tests.rs | 9 - .../tui/src/chatwidget/tests/app_server.rs | 4 +- .../chatwidget/tests/composer_submission.rs | 19 +- .../chatwidget/tests/security_setup_tests.rs | 98 -- .../src/chatwidget/tests/slash_commands.rs | 114 -- ...ackend_banner_information_dismissible.snap | 14 - ...ests__backend_banner_information_only.snap | 12 - ...rs_tests__backend_banner_notification.snap | 14 - ...ner_notification_after_account_change.snap | 5 - ...__luna_reserve_selector_second_choice.snap | 13 - ...sage_tests__luna_reserve_usage_narrow.snap | 8 - ...age_tests__luna_reserve_usage_running.snap | 10 - ..._usage_tests__luna_reserve_usage_wide.snap | 8 - ...tests__luna_reserve_usage_with_upsell.snap | 13 - ..._security_setup_dismissed_after_usage.snap | 7 - .../src/chatwidget/tests/status_and_layout.rs | 1440 +---------------- .../chatwidget/tests/status_command_tests.rs | 565 ------- .../tests/status_surface_previews.rs | 131 -- codex-rs/tui/src/chatwidget/turn_runtime.rs | 47 +- codex-rs/tui/src/chatwidget/usage_history.rs | 35 +- codex-rs/tui/src/chatwidget/usage_notice.rs | 39 +- .../tui/src/chatwidget/usage_notice_tests.rs | 194 +-- codex-rs/tui/src/clock_format.rs | 7 - codex-rs/tui/src/lib.rs | 17 - codex-rs/tui/src/pager_overlay.rs | 5 +- codex-rs/tui/src/slash_command.rs | 5 - ...nguish_zero_missing_and_exact_details.snap | 63 - ...rs_and_empty_reports_stay_independent.snap | 11 - ...zed_refunds_leave_room_for_both_bands.snap | 36 - ...denominators_and_signed_small_credits.snap | 33 - ..._range_and_keep_calendar_ticks_stable.snap | 18 - codex-rs/tui/src/status/card.rs | 150 +- codex-rs/tui/src/status/mod.rs | 6 - codex-rs/tui/src/status/rate_limits.rs | 174 +- ...ests__status_server_auth_not_required.snap | 16 - ...s__tests__status_server_auth_required.snap | 19 - ...ched_limits_hide_credits_without_flag.snap | 3 - ..._snapshot_includes_credits_and_limits.snap | 5 +- ...ludes_enterprise_monthly_credit_limit.snap | 20 - ...s_enterprise_monthly_credit_limit.snap.new | 21 - ..._status_snapshot_includes_forked_from.snap | 4 - ...tatus_snapshot_includes_monthly_limit.snap | 3 - ...s_snapshot_includes_reasoning_details.snap | 3 - ...atus_snapshot_local_background_server.snap | 4 - ..._tests__status_snapshot_remote_server.snap | 4 - ...hot_shows_active_user_defined_profile.snap | 4 - ...napshot_shows_auto_review_permissions.snap | 4 - ...shot_shows_chatgpt_plan_without_email.snap | 5 +- ...snapshot_shows_missing_limits_message.snap | 4 - ...apshot_shows_refreshing_limits_notice.snap | 20 - ...s_snapshot_shows_stale_limits_message.snap | 3 - ...shot_shows_unavailable_limits_message.snap | 3 - ...tes_halfwidth_kana_in_narrow_terminal.snap | 8 +- ...snapshot_truncates_in_narrow_terminal.snap | 3 - ...s_default_reasoning_when_config_empty.snap | 4 - ..._limit_labels_for_unsupported_windows.snap | 3 - ...hly_credit_details_in_narrow_terminal.snap | 30 - ...ipt_overlay_status_rate_limit_refresh.snap | 66 - codex-rs/tui/src/status/tests.rs | 691 +------- codex-rs/tui/src/subscription.rs | 9 +- codex-rs/tui/src/tui/history_tail.rs | 79 +- codex-rs/tui/src/tui/history_tail_tests.rs | 178 -- 190 files changed, 313 insertions(+), 9756 deletions(-) create mode 100644 codex-rs/tui/src/app/agents_overview_usage.rs delete mode 100644 codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__usage__agents_overview_usage.snap delete mode 100644 codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_after_fallback.snap delete mode 100644 codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_fallback_notice.snap delete mode 100644 codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_fallback_unavailable.snap delete mode 100644 codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__luna_reserve_settings_unavailable.snap delete mode 100644 codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__luna_reserve_recovery_tests__luna_reserve_recovery_notice.snap delete mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_includes_thread_usage_items.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_available_hint.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_confirmation.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_hint_waits_for_active_output.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_picker_narrow.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_popup_states.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__signed_out_usage_command_reports_chatgpt_login_requirement.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_command_estimated_thread_usage.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_command_estimated_thread_usage_without_usd.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_estimated_thread_cost_footer.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_workspace_headline.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_thread_usage.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_thread_usage.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_before_reset_refresh.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_narrow.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_without_resets.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_with_invalid_view_reports_usage.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_member_credits_depleted_prompt.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_member_usage_limit_prompt.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_credits_nudge_completion_feedback.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_limit_state_messages.snap delete mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_usage_limit_nudge_completion_feedback.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_information_dismissible.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_information_only.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_notification.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__owner_notification_after_account_change.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_selector_second_choice.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_narrow.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_running.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_wide.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_with_upsell.snap delete mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__security_setup_tests__security_setup_dismissed_after_usage.snap delete mode 100644 codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_dates_distinguish_zero_missing_and_exact_details.snap delete mode 100644 codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_loading_errors_and_empty_reports_stay_independent.snap delete mode 100644 codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_maximized_refunds_leave_room_for_both_bands.snap delete mode 100644 codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_preserves_full_denominators_and_signed_small_credits.snap delete mode 100644 codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_series_rank_by_range_and_keep_calendar_ticks_stable.snap delete mode 100644 codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_server_auth_not_required.snap delete mode 100644 codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_server_auth_required.snap delete mode 100644 codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_enterprise_monthly_credit_limit.snap delete mode 100644 codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_enterprise_monthly_credit_limit.snap.new delete mode 100644 codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_refreshing_limits_notice.snap delete mode 100644 codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_wraps_enterprise_monthly_credit_details_in_narrow_terminal.snap delete mode 100644 codex-rs/tui/src/status/snapshots/codex_tui__status__tests__transcript_overlay_status_rate_limit_refresh.snap delete mode 100644 codex-rs/tui/src/tui/history_tail_tests.rs diff --git a/README.md b/README.md index 5dbbec95..dccf698c 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,8 @@ |---|---|---| | 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-1 | Backend ChatGPT: utilizzo, limiti e crediti, configurazione cloud, app e connettori ChatGPT, plugin remoti, upload di file, attribuzione git remota | βœ… | +| 2c | Eliminazione completa del codice di invio dati: crate analytics, upload del feedback e Sentry, esportatori OpenTelemetry | ⏳ | | 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 | ⏳ | diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index cb6222ba..41e63c90 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -4987,7 +4987,6 @@ dependencies = [ "codex-app-server-daemon", "codex-app-server-protocol", "codex-arg0", - "codex-backend-client", "codex-build-info", "codex-config", "codex-connectors", diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 6539b7f6..97d2220c 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -202,24 +202,6 @@ late proofs after the approval is canceled or resolved. Only one native worker runs per app-server; if an OS call remains active after cancellation or timeout, subsequent local operations return `failed/providerError` until that worker exits. -# Hosted Codex Apps MCP protocol - -The host-owned HTTP `codex_apps` server uses Legacy by default in app-server and -standalone Codex. To discover the 2026-07-28 protocol, set -`codex_apps_mcp_2026_07_28 = true` under `[features]`, or send a true runtime -override via `experimentalFeature/enablement/set`. Discovery falls back to Legacy -when the server does not support it. Explicit config takes precedence. -The dedicated setting does not apply to third-party HTTP or local `codex_app` -stdio servers. The existing `mcp_2026_07_28` flag still governs eligible other -servers, regardless of whether their names or URLs resemble hosted Apps. -App-server does not persist this selection. - -## Hosted resource reads - -`mcpServer/resource/read` accepts `target: {connectorId, linkId}` for direct hosted app reads without tool discovery. A string `linkId` selects that account; `null` explicitly requests no-auth access subject to backend policy. Do not infer no-auth access from unknown or synthetic links. - -`originCallId` with `threadId` takes precedence and retains the originating app/account scope. Requests without `target` retain discovery; `connectorId` continues to restrict reads to that connector. Direct targets require backend support for app/account resource reads. - # Project trust `thread/start` does not persist project trust for a directory where configuration diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 7b5a9544..76cc71b2 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -127,22 +127,14 @@ use codex_app_server_protocol::PluginMarketplaceEntry; use codex_app_server_protocol::PluginReadParams; use codex_app_server_protocol::PluginReadResponse; use codex_app_server_protocol::PluginShareCheckoutParams; -use codex_app_server_protocol::PluginShareCheckoutResponse; use codex_app_server_protocol::PluginShareContext; use codex_app_server_protocol::PluginShareDeleteParams; -use codex_app_server_protocol::PluginShareDeleteResponse; use codex_app_server_protocol::PluginShareDiscoverability; -use codex_app_server_protocol::PluginShareListItem; use codex_app_server_protocol::PluginShareListParams; -use codex_app_server_protocol::PluginShareListResponse; use codex_app_server_protocol::PluginSharePrincipal; use codex_app_server_protocol::PluginSharePrincipalType; use codex_app_server_protocol::PluginShareSaveParams; -use codex_app_server_protocol::PluginShareSaveResponse; -use codex_app_server_protocol::PluginShareTarget; -use codex_app_server_protocol::PluginShareUpdateDiscoverability; use codex_app_server_protocol::PluginShareUpdateTargetsParams; -use codex_app_server_protocol::PluginShareUpdateTargetsResponse; use codex_app_server_protocol::PluginSkillReadParams; use codex_app_server_protocol::PluginSkillReadResponse; use codex_app_server_protocol::PluginSource; @@ -352,7 +344,6 @@ use codex_core_plugins::remote::RemotePluginCatalogError; use codex_core_plugins::remote::RemotePluginDetail as RemoteCatalogPluginDetail; use codex_core_plugins::remote::RemotePluginServiceConfig; use codex_core_plugins::remote::RemotePluginShareContext as RemoteCatalogPluginShareContext; -use codex_core_plugins::remote::RemotePluginShareSummary as RemoteCatalogPluginShareSummary; use codex_core_plugins::remote::RemotePluginSummary as RemoteCatalogPluginSummary; use codex_exec_server::EnvironmentManager; use codex_exec_server::EnvironmentObservedStatus; diff --git a/codex-rs/app-server/src/request_processors/account_processor.rs b/codex-rs/app-server/src/request_processors/account_processor.rs index a6b92ab1..e2f8d760 100644 --- a/codex-rs/app-server/src/request_processors/account_processor.rs +++ b/codex-rs/app-server/src/request_processors/account_processor.rs @@ -1202,4 +1202,3 @@ pub(crate) async fn clear_account_configuration( } Ok(()) } - diff --git a/codex-rs/app-server/src/request_processors/plugins.rs b/codex-rs/app-server/src/request_processors/plugins.rs index f6ee4327..62ca5e2b 100644 --- a/codex-rs/app-server/src/request_processors/plugins.rs +++ b/codex-rs/app-server/src/request_processors/plugins.rs @@ -6,7 +6,6 @@ use crate::error_code::method_not_found; use codex_analytics::PluginInstallSource; use codex_app_server_protocol::PluginAvailability; use codex_app_server_protocol::PluginSharePrincipalRole; -use codex_app_server_protocol::PluginShareTargetRole; use codex_config::types::McpServerConfig; use codex_config::types::PluginsConfigToml; use codex_core_plugins::OPENAI_CURATED_MARKETPLACE_NAME; @@ -29,7 +28,6 @@ use codex_core_plugins::remote::RemotePluginCatalogCacheMode; use codex_core_plugins::remote::RemotePluginScope; use codex_core_plugins::remote::is_valid_remote_plugin_id; use codex_core_plugins::remote::validate_remote_plugin_id; -use codex_core_plugins::remote_bundle::RemotePluginBundleInstallError; use codex_mcp::McpOAuthLoginSupport; use codex_mcp::McpRuntimeContext; use codex_mcp::oauth_login_support; @@ -286,65 +284,6 @@ fn installed_plugin_names(plugins: &[PluginSummary]) -> HashSet { .collect() } -fn remote_plugin_share_discoverability( - discoverability: PluginShareDiscoverability, -) -> codex_core_plugins::remote::RemotePluginShareDiscoverability { - match discoverability { - PluginShareDiscoverability::Listed => { - codex_core_plugins::remote::RemotePluginShareDiscoverability::Listed - } - PluginShareDiscoverability::Unlisted => { - codex_core_plugins::remote::RemotePluginShareDiscoverability::Unlisted - } - PluginShareDiscoverability::Private => { - codex_core_plugins::remote::RemotePluginShareDiscoverability::Private - } - } -} - -fn remote_plugin_share_update_discoverability( - discoverability: PluginShareUpdateDiscoverability, -) -> codex_core_plugins::remote::RemotePluginShareUpdateDiscoverability { - match discoverability { - PluginShareUpdateDiscoverability::Listed => { - codex_core_plugins::remote::RemotePluginShareUpdateDiscoverability::Listed - } - PluginShareUpdateDiscoverability::Unlisted => { - codex_core_plugins::remote::RemotePluginShareUpdateDiscoverability::Unlisted - } - PluginShareUpdateDiscoverability::Private => { - codex_core_plugins::remote::RemotePluginShareUpdateDiscoverability::Private - } - } -} - -fn validate_client_plugin_share_targets( - targets: &[PluginShareTarget], -) -> Result<(), JSONRPCErrorError> { - if targets - .iter() - .any(|target| target.principal_type == PluginSharePrincipalType::Workspace) - { - return Err(invalid_request( - "shareTargets cannot include workspace principals; use discoverability UNLISTED for workspace link access", - )); - } - Ok(()) -} - -fn remote_plugin_share_target_role( - role: PluginShareTargetRole, -) -> codex_core_plugins::remote::RemotePluginShareTargetRole { - match role { - PluginShareTargetRole::Reader => { - codex_core_plugins::remote::RemotePluginShareTargetRole::Reader - } - PluginShareTargetRole::Editor => { - codex_core_plugins::remote::RemotePluginShareTargetRole::Editor - } - } -} - fn plugin_share_principal_role_from_remote( role: codex_core_plugins::remote::RemotePluginSharePrincipalRole, ) -> PluginSharePrincipalRole { @@ -361,31 +300,6 @@ fn plugin_share_principal_role_from_remote( } } -fn remote_plugin_share_targets( - targets: Vec, -) -> Vec { - targets - .into_iter() - .map( - |target| codex_core_plugins::remote::RemotePluginShareTarget { - principal_type: match target.principal_type { - PluginSharePrincipalType::User => { - codex_core_plugins::remote::RemotePluginSharePrincipalType::User - } - PluginSharePrincipalType::Group => { - codex_core_plugins::remote::RemotePluginSharePrincipalType::Group - } - PluginSharePrincipalType::Workspace => { - codex_core_plugins::remote::RemotePluginSharePrincipalType::Workspace - } - }, - principal_id: target.principal_id, - role: remote_plugin_share_target_role(target.role), - }, - ) - .collect() -} - fn plugin_share_principal_from_remote( principal: codex_core_plugins::remote::RemotePluginSharePrincipal, ) -> PluginSharePrincipal { @@ -466,47 +380,37 @@ impl PluginRequestProcessor { pub(crate) async fn plugin_share_save( &self, - params: PluginShareSaveParams, + _params: PluginShareSaveParams, ) -> Result, JSONRPCErrorError> { - self.plugin_share_save_response(params) - .await - .map(|response| Some(response.into())) + Err(plugin_sharing_unavailable()) } pub(crate) async fn plugin_share_update_targets( &self, - params: PluginShareUpdateTargetsParams, + _params: PluginShareUpdateTargetsParams, ) -> Result, JSONRPCErrorError> { - self.plugin_share_update_targets_response(params) - .await - .map(|response| Some(response.into())) + Err(plugin_sharing_unavailable()) } pub(crate) async fn plugin_share_list( &self, - params: PluginShareListParams, + _params: PluginShareListParams, ) -> Result, JSONRPCErrorError> { - self.plugin_share_list_response(params) - .await - .map(|response| Some(response.into())) + Err(plugin_sharing_unavailable()) } pub(crate) async fn plugin_share_checkout( &self, - params: PluginShareCheckoutParams, + _params: PluginShareCheckoutParams, ) -> Result, JSONRPCErrorError> { - self.plugin_share_checkout_response(params) - .await - .map(|response| Some(response.into())) + Err(plugin_sharing_unavailable()) } pub(crate) async fn plugin_share_delete( &self, - params: PluginShareDeleteParams, + _params: PluginShareDeleteParams, ) -> Result, JSONRPCErrorError> { - self.plugin_share_delete_response(params) - .await - .map(|response| Some(response.into())) + Err(plugin_sharing_unavailable()) } pub(crate) async fn plugin_install( @@ -1290,225 +1194,6 @@ impl PluginRequestProcessor { }) } - async fn plugin_share_save_response( - &self, - params: PluginShareSaveParams, - ) -> Result { - let (config, auth) = self.load_plugin_share_config_and_auth().await?; - if !config.features.enabled(Feature::PluginSharing) { - return Err(invalid_request("plugin sharing is disabled")); - } - let PluginShareSaveParams { - plugin_path, - remote_plugin_id, - discoverability, - share_targets, - } = params; - if let Some(remote_plugin_id) = remote_plugin_id.as_ref() - && (remote_plugin_id.is_empty() || !is_valid_remote_plugin_id(remote_plugin_id)) - { - return Err(invalid_request("invalid remote plugin id")); - } - if remote_plugin_id.is_some() && (discoverability.is_some() || share_targets.is_some()) { - return Err(invalid_request( - "discoverability and shareTargets are only supported when creating a plugin share; use plugin/share/updateTargets to update share settings", - )); - } - if discoverability == Some(PluginShareDiscoverability::Listed) { - return Err(invalid_request( - "discoverability LISTED is not supported for plugin/share/save; use UNLISTED or PRIVATE", - )); - } - if let Some(share_targets) = share_targets.as_ref() { - validate_client_plugin_share_targets(share_targets)?; - } - - let remote_plugin_service_config = - remote_plugin_service_config(&self.thread_manager, &config)?; - let access_policy = codex_core_plugins::remote::RemotePluginShareAccessPolicy { - discoverability: discoverability.map(remote_plugin_share_discoverability), - share_targets: share_targets.map(remote_plugin_share_targets), - }; - let result = codex_core_plugins::remote::save_remote_plugin_share( - &remote_plugin_service_config, - auth.as_ref(), - config.codex_home.as_path(), - &plugin_path, - remote_plugin_id.as_deref(), - access_policy, - ) - .await - .map_err(|err| remote_plugin_catalog_error_to_jsonrpc(err, "save remote plugin share"))?; - codex_core_plugins::remote::invalidate_cached_remote_plugin_catalog_scopes( - config.codex_home.as_path(), - &remote_plugin_service_config, - auth.as_ref(), - &[RemotePluginScope::User, RemotePluginScope::Workspace], - ); - let remote_plugin_id = result.remote_plugin_id; - self.clear_plugin_related_caches(); - Ok(PluginShareSaveResponse { - remote_plugin_id, - share_url: result.share_url.unwrap_or_default(), - can_publish_to_workspace: result.can_publish_to_workspace, - }) - } - - async fn plugin_share_update_targets_response( - &self, - params: PluginShareUpdateTargetsParams, - ) -> Result { - let (config, auth) = self.load_plugin_share_config_and_auth().await?; - if !config.features.enabled(Feature::PluginSharing) { - return Err(invalid_request("plugin sharing is disabled")); - } - let PluginShareUpdateTargetsParams { - remote_plugin_id, - discoverability, - share_targets, - } = params; - if remote_plugin_id.is_empty() || !is_valid_remote_plugin_id(&remote_plugin_id) { - return Err(invalid_request("invalid remote plugin id")); - } - validate_client_plugin_share_targets(&share_targets)?; - - let remote_plugin_service_config = - remote_plugin_service_config(&self.thread_manager, &config)?; - let result = codex_core_plugins::remote::update_remote_plugin_share_targets( - &remote_plugin_service_config, - auth.as_ref(), - &remote_plugin_id, - remote_plugin_share_targets(share_targets), - remote_plugin_share_update_discoverability(discoverability), - ) - .await - .map_err(|err| { - remote_plugin_catalog_error_to_jsonrpc(err, "update remote plugin share targets") - })?; - codex_core_plugins::remote::invalidate_cached_remote_plugin_catalog_scopes( - config.codex_home.as_path(), - &remote_plugin_service_config, - auth.as_ref(), - &[RemotePluginScope::User, RemotePluginScope::Workspace], - ); - self.clear_plugin_related_caches(); - Ok(PluginShareUpdateTargetsResponse { - principals: result - .principals - .into_iter() - .map(plugin_share_principal_from_remote) - .collect(), - discoverability: remote_plugin_share_discoverability_to_info(result.discoverability), - }) - } - - async fn plugin_share_list_response( - &self, - _params: PluginShareListParams, - ) -> Result { - let (config, auth) = self.load_plugin_share_config_and_auth().await?; - let remote_plugin_service_config = - remote_plugin_service_config(&self.thread_manager, &config)?; - let plugin_policy = &config.plugins; - let data = codex_core_plugins::remote::list_remote_plugin_shares( - &remote_plugin_service_config, - auth.as_ref(), - config.codex_home.as_path(), - ) - .await - .map_err(|err| remote_plugin_catalog_error_to_jsonrpc(err, "list remote plugin shares"))? - .into_iter() - .map(|summary| { - let RemoteCatalogPluginShareSummary { - summary, - local_plugin_path, - } = summary; - let plugin = remote_plugin_summary_to_info(summary, plugin_policy); - PluginShareListItem { - plugin, - local_plugin_path, - } - }) - .collect(); - Ok(PluginShareListResponse { data }) - } - - async fn plugin_share_checkout_response( - &self, - params: PluginShareCheckoutParams, - ) -> Result { - let (config, auth) = self.load_plugin_share_config_and_auth().await?; - if !config.features.enabled(Feature::PluginSharing) { - return Err(invalid_request("plugin sharing is disabled")); - } - let PluginShareCheckoutParams { remote_plugin_id } = params; - if remote_plugin_id.is_empty() || !is_valid_remote_plugin_id(&remote_plugin_id) { - return Err(invalid_request("invalid remote plugin id")); - } - - let remote_plugin_service_config = - remote_plugin_service_config(&self.thread_manager, &config)?; - let result = codex_core_plugins::remote::checkout_remote_plugin_share( - &remote_plugin_service_config, - auth.as_ref(), - config.codex_home.as_path(), - &remote_plugin_id, - ) - .await - .map_err(|err| remote_plugin_catalog_error_to_jsonrpc(err, "checkout plugin share"))?; - self.clear_plugin_related_caches(); - Ok(PluginShareCheckoutResponse { - remote_plugin_id: result.remote_plugin_id, - plugin_id: result.plugin_id, - plugin_name: result.plugin_name, - plugin_path: result.plugin_path, - marketplace_name: result.marketplace_name, - marketplace_path: result.marketplace_path, - remote_version: result.remote_version, - }) - } - - async fn plugin_share_delete_response( - &self, - params: PluginShareDeleteParams, - ) -> Result { - let (config, auth) = self.load_plugin_share_config_and_auth().await?; - let PluginShareDeleteParams { remote_plugin_id } = params; - if remote_plugin_id.is_empty() || !is_valid_remote_plugin_id(&remote_plugin_id) { - return Err(invalid_request("invalid remote plugin id")); - } - - let remote_plugin_service_config = - remote_plugin_service_config(&self.thread_manager, &config)?; - codex_core_plugins::remote::delete_remote_plugin_share( - &remote_plugin_service_config, - auth.as_ref(), - config.codex_home.as_path(), - &remote_plugin_id, - ) - .await - .map_err(|err| remote_plugin_catalog_error_to_jsonrpc(err, "delete remote plugin share"))?; - codex_core_plugins::remote::invalidate_cached_remote_plugin_catalog_scopes( - config.codex_home.as_path(), - &remote_plugin_service_config, - auth.as_ref(), - &[RemotePluginScope::User, RemotePluginScope::Workspace], - ); - self.clear_plugin_related_caches(); - Ok(PluginShareDeleteResponse {}) - } - - async fn load_plugin_share_config_and_auth( - &self, - ) -> Result<(Config, Option), JSONRPCErrorError> { - let config = self.load_latest_config(/*fallback_cwd*/ None).await?; - if !config.features.enabled(Feature::Plugins) { - return Err(invalid_request("plugin sharing is not enabled")); - } - let auth = self.auth_manager.auth().await; - Ok((config, auth)) - } - async fn plugin_install_response( &self, params: PluginInstallParams, @@ -1660,10 +1345,6 @@ impl PluginRequestProcessor { remote_plugin_catalog_error_type(source), source.sub_error_type(), )), - RemotePluginOperationErrorKind::Bundle(source) => Some(( - remote_plugin_bundle_install_error_type(source), - source.sub_error_type(), - )), RemotePluginOperationErrorKind::DisabledByAdmin(_) => Some(( "remote_plugin_not_available", Some("disabled_by_admin".to_string()), @@ -2328,56 +2009,12 @@ fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static "remote_catalog_unexpected_enabled_state" } RemotePluginCatalogError::InvalidPluginPath { .. } => "remote_catalog_invalid_plugin_path", - RemotePluginCatalogError::PluginShareCheckoutNotAvailable { .. } => { - "remote_catalog_plugin_share_checkout_not_available" - } - RemotePluginCatalogError::Archive { .. } => "remote_catalog_archive", - RemotePluginCatalogError::ArchiveJoin(_) => "remote_catalog_archive_join", - RemotePluginCatalogError::ArchiveTooLarge { .. } => "remote_catalog_archive_too_large", - RemotePluginCatalogError::MissingUploadEtag => "remote_catalog_missing_upload_etag", RemotePluginCatalogError::UnexpectedResponse(_) => "remote_catalog_unexpected_response", RemotePluginCatalogError::InstalledPluginsFetchTimeout => "remote_catalog_timeout", RemotePluginCatalogError::CacheRemove(_) => "remote_catalog_cache_remove", } } -fn remote_plugin_bundle_install_error_type(err: &RemotePluginBundleInstallError) -> &'static str { - match err { - RemotePluginBundleInstallError::Unavailable => "remote_bundle_unavailable", - RemotePluginBundleInstallError::MissingReleaseVersion { .. } => { - "remote_bundle_missing_release_version" - } - RemotePluginBundleInstallError::InvalidReleaseVersion { .. } => { - "remote_bundle_invalid_release_version" - } - RemotePluginBundleInstallError::MissingBundleDownloadUrl { .. } => { - "remote_bundle_missing_download_url" - } - RemotePluginBundleInstallError::InvalidBundleDownloadUrl { .. } => { - "remote_bundle_invalid_download_url" - } - RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme { .. } => { - "remote_bundle_unsupported_download_url_scheme" - } - RemotePluginBundleInstallError::InvalidPluginId { .. } => "remote_bundle_invalid_plugin_id", - RemotePluginBundleInstallError::DownloadRequest { .. } => "remote_bundle_download_request", - RemotePluginBundleInstallError::DownloadStatus { .. } => "remote_bundle_download_status", - RemotePluginBundleInstallError::DownloadBody { .. } => "remote_bundle_download_body", - RemotePluginBundleInstallError::DownloadTooLarge { .. } => { - "remote_bundle_download_too_large" - } - RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. } => { - "remote_bundle_unsupported_download_final_url" - } - RemotePluginBundleInstallError::ExtractedBundleTooLarge { .. } => { - "remote_bundle_extracted_too_large" - } - RemotePluginBundleInstallError::Io { .. } => "remote_bundle_io", - RemotePluginBundleInstallError::InvalidBundle(_) => "remote_bundle_invalid_bundle", - RemotePluginBundleInstallError::Store(_) => "remote_bundle_store", - } -} - fn remote_plugin_catalog_error_to_jsonrpc( err: RemotePluginCatalogError, context: &str, @@ -2392,8 +2029,6 @@ fn remote_plugin_catalog_error_to_jsonrpc( invalid_request(message) } RemotePluginCatalogError::InvalidPluginPath { .. } - | RemotePluginCatalogError::PluginShareCheckoutNotAvailable { .. } - | RemotePluginCatalogError::ArchiveTooLarge { .. } | RemotePluginCatalogError::UnknownMarketplace { .. } => invalid_request(message), RemotePluginCatalogError::AuthToken(_) | RemotePluginCatalogError::Request { .. } @@ -2404,29 +2039,17 @@ fn remote_plugin_catalog_error_to_jsonrpc( | RemotePluginCatalogError::UnexpectedPluginId { .. } | RemotePluginCatalogError::UnexpectedSkillName { .. } | RemotePluginCatalogError::UnexpectedEnabledState { .. } - | RemotePluginCatalogError::Archive { .. } - | RemotePluginCatalogError::ArchiveJoin(_) - | RemotePluginCatalogError::MissingUploadEtag | RemotePluginCatalogError::UnexpectedResponse(_) | RemotePluginCatalogError::InstalledPluginsFetchTimeout | RemotePluginCatalogError::CacheRemove(_) => internal_error(message), } } -fn remote_plugin_bundle_install_error_to_jsonrpc( - err: codex_core_plugins::remote_bundle::RemotePluginBundleInstallError, -) -> JSONRPCErrorError { - internal_error(format!("install remote plugin bundle: {err}")) -} - fn remote_plugin_operation_error_to_jsonrpc(err: RemotePluginOperationError) -> JSONRPCErrorError { match *err.kind { RemotePluginOperationErrorKind::Catalog { context, source } => { remote_plugin_catalog_error_to_jsonrpc(source, context) } - RemotePluginOperationErrorKind::Bundle(source) => { - remote_plugin_bundle_install_error_to_jsonrpc(source) - } RemotePluginOperationErrorKind::Sync { context, source } => { internal_error(format!("{context}: {source}")) } @@ -2436,3 +2059,8 @@ fn remote_plugin_operation_error_to_jsonrpc(err: RemotePluginOperationError) -> RemotePluginOperationErrorKind::Internal(message) => internal_error(message), } } + +/// aKode never shares plugins through the ChatGPT backend. +fn plugin_sharing_unavailable() -> JSONRPCErrorError { + method_not_found("plugin sharing is not available in aKode".to_string()) +} diff --git a/codex-rs/cli/src/debug_sandbox.rs b/codex-rs/cli/src/debug_sandbox.rs index 0ac491bd..e4f0ca20 100644 --- a/codex-rs/cli/src/debug_sandbox.rs +++ b/codex-rs/cli/src/debug_sandbox.rs @@ -13,7 +13,6 @@ use codex_core::config::Config; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; use codex_core::config::NetworkProxyAuditMetadata; -use codex_core::config::find_codex_home; use codex_core::exec_env::create_env; #[cfg(target_os = "macos")] use codex_core::spawn::CODEX_SANDBOX_ENV_VAR; diff --git a/codex-rs/codex-mcp/src/client_capabilities_tests.rs b/codex-rs/codex-mcp/src/client_capabilities_tests.rs index 17691735..420512fd 100644 --- a/codex-rs/codex-mcp/src/client_capabilities_tests.rs +++ b/codex-rs/codex-mcp/src/client_capabilities_tests.rs @@ -67,14 +67,9 @@ fn user_verification_is_projected_only_to_the_host_owned_plugin_service() { use crate::catalog::McpServerRegistration; use crate::catalog::ResolvedMcpCatalog; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; - use crate::mcp::codex_apps_mcp_server_config; use codex_rmcp_client::McpProtocolMode; - let config = codex_apps_mcp_server_config( - "https://example.com", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ); + let config = crate::mcp::test_http_mcp_server_config("https://example.com"); let extensions = ClientMcpExtensions::new([ ( OPENAI_ELICITATION_EXTENSION_ID.to_string(), diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs index 750d84a3..ba47fdd9 100644 --- a/codex-rs/codex-mcp/src/connection_manager_tests.rs +++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs @@ -4718,11 +4718,7 @@ async fn list_all_tools_adds_server_metadata_to_tools() { #[test] fn server_metadata_preserves_tool_approval_policy() { - let mut config = crate::codex_apps_mcp_server_config( - "https://docs.example", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ); + let mut config = crate::mcp::test_http_mcp_server_config("https://docs.example"); config.environment_id = "remote".to_string(); config.default_tools_approval_mode = Some(AppToolApproval::Prompt); config.tools.insert( @@ -4757,11 +4753,7 @@ fn hosted_actor_credentials_are_only_available_to_host_owned_mcp_servers() { ); let hosted_auth = CodexAuth::Headers(AuthHeaders::new(actor_headers)); let provider = codex_model_provider::auth_provider_from_auth(&hosted_auth); - let mut local_config = crate::codex_apps_mcp_server_config( - "https://chatgpt.com", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ); + let mut local_config = crate::mcp::test_http_mcp_server_config("https://chatgpt.com"); local_config.auth = McpServerAuth::ChatGpt; let local_server = EffectiveMcpServer::from_host_config(local_config.clone()); @@ -4795,11 +4787,9 @@ fn gov_codex_apps_retain_local_chatgpt_auth_provider() -> anyhow::Result<()> { config.chatgpt_base_url = "https://gov.chatgpt.com/backend-api/".to_string(); config.apps_enabled = true; - let local_config = crate::codex_apps_mcp_server_config( - &config.chatgpt_base_url, - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ); + let mut local_config = + crate::mcp::test_http_mcp_server_config("https://gov.chatgpt.com/backend-api/ps/mcp"); + local_config.auth = McpServerAuth::ChatGpt; let mut remote_config = local_config.clone(); remote_config.environment_id = "customer-executor".to_string(); let mut custom_oauth = local_config.clone(); @@ -4822,14 +4812,8 @@ fn gov_codex_apps_retain_local_chatgpt_auth_provider() -> anyhow::Result<()> { config.mcp_server_catalog = catalog.build(); let servers = crate::effective_mcp_servers(&config, Some(&auth)); - let local = &servers[CODEX_APPS_MCP_SERVER_NAME]; - assert_eq!(local.config().auth, McpServerAuth::ChatGpt); - let retained = chatgpt_auth_provider_for_server(local, Some(Arc::clone(&provider))) - .expect("local Gov Apps must retain ChatGPT authentication"); - assert!( - Arc::ptr_eq(&provider, &retained), - "server selection must preserve the supplied provider" - ); + // aKode never connects to the ChatGPT-hosted apps MCP server. + assert!(!servers.contains_key(CODEX_APPS_MCP_SERVER_NAME)); assert_eq!(servers["custom-oauth"].config().auth, McpServerAuth::OAuth); assert_eq!(servers["remote-gov"].config().auth, McpServerAuth::ChatGpt); diff --git a/codex-rs/codex-mcp/src/elicitation_tests.rs b/codex-rs/codex-mcp/src/elicitation_tests.rs index 7cd09719..ed90da57 100644 --- a/codex-rs/codex-mcp/src/elicitation_tests.rs +++ b/codex-rs/codex-mcp/src/elicitation_tests.rs @@ -760,11 +760,7 @@ async fn reused_elicitation_senders_follow_each_servers_latest_permission_author config.apps_enabled = true; let auth = codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let hosted_server = crate::codex_apps_mcp_server_config( - "https://example.com", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ); + let hosted_server = crate::mcp::test_http_mcp_server_config("https://example.com"); let mut attached_server = hosted_server.clone(); attached_server.environment_id = "attached".to_string(); let mut catalog = crate::ResolvedMcpCatalog::builder(); @@ -772,9 +768,9 @@ async fn reused_elicitation_senders_follow_each_servers_latest_permission_author "attached".to_string(), attached_server, )); - catalog.register(crate::McpServerRegistration::from_hosted_apps( - "host", - /*contribution_order*/ 0, + // A user-configured server on the local environment, which is not attached below. + catalog.register(crate::McpServerRegistration::from_config( + "local".to_string(), hosted_server, )); config.mcp_server_catalog = catalog.build(); @@ -785,14 +781,8 @@ async fn reused_elicitation_senders_follow_each_servers_latest_permission_author codex_utils_path_uri::PathUri::from_host_native_path(std::env::temp_dir()).unwrap(), ); let sandbox = Arc::new(sandbox); - // Hosted Apps must still use thread permissions when a local environment is attached. - [ - ("attached".to_string(), Arc::clone(&sandbox)), - ( - codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(), - sandbox, - ), - ] + // Unattached local servers keep using thread permissions. + [("attached".to_string(), sandbox)] }; config.set_server_permissions(&servers, attachment(PermissionProfile::read_only())); @@ -808,7 +798,7 @@ async fn reused_elicitation_senders_follow_each_servers_latest_permission_author &ClientMcpExtensions::default(), ); let hosted = manager.make_sender( - crate::CODEX_APPS_MCP_SERVER_NAME.to_string(), + "local".to_string(), /*tx_event*/ None, &ClientMcpExtensions::default(), ); @@ -853,6 +843,14 @@ async fn reused_elicitation_senders_follow_each_servers_latest_permission_author ElicitationAction::Decline ); + let mut configured_servers = config.mcp_server_catalog.configured_servers(); + configured_servers + .get_mut("local") + .expect("local server should be registered") + .enabled = false; + config.mcp_server_catalog = config + .mcp_server_catalog + .with_materialized_servers(configured_servers); let servers = crate::effective_mcp_servers(&config, /*auth*/ None); config.set_server_permissions(&servers, std::iter::empty()); assert!(manager.update( @@ -879,11 +877,7 @@ fn verification_fixture( catalog.register(crate::catalog::McpServerRegistration::from_hosted_apps( "verification-test", /*contribution_order*/ 0, - crate::mcp::codex_apps_mcp_server_config( - "https://example.com", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ), + crate::mcp::test_http_mcp_server_config("https://example.com"), )); Arc::make_mut(&mut config).mcp_server_catalog = catalog.build(); let manager = ElicitationRequestManager::new( @@ -1072,11 +1066,7 @@ async fn user_verification_rejects_attached_servers_even_if_they_use_the_plugin_ let mut catalog = crate::catalog::ResolvedMcpCatalog::builder(); catalog.register(crate::catalog::McpServerRegistration::from_config( name.into(), - crate::mcp::codex_apps_mcp_server_config( - "https://example.com", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ), + crate::mcp::test_http_mcp_server_config("https://example.com"), )); config.mcp_server_catalog = catalog.build(); } diff --git a/codex-rs/codex-mcp/src/mcp/mod.rs b/codex-rs/codex-mcp/src/mcp/mod.rs index ced2c129..340b1a72 100644 --- a/codex-rs/codex-mcp/src/mcp/mod.rs +++ b/codex-rs/codex-mcp/src/mcp/mod.rs @@ -824,3 +824,35 @@ pub(crate) async fn collect_mcp_server_status_snapshot_from_manager( #[cfg(test)] #[path = "mod_tests.rs"] pub(crate) mod tests; + +/// Test fixture: a generic user-configured streamable HTTP MCP server at `url`. +#[cfg(test)] +pub(crate) fn test_http_mcp_server_config(url: &str) -> McpServerConfig { + McpServerConfig { + transport: McpServerTransportConfig::StreamableHttp { + url: url.to_string(), + bearer_token_env_var: None, + http_headers: None, + env_http_headers: None, + http_headers_helper: None, + }, + auth: McpServerAuth::default(), + environment_id: codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(), + enabled: true, + required: false, + startup_readiness: Default::default(), + supports_parallel_tool_calls: false, + tool_input_schema_max_bytes: None, + omit_tools_from: None, + disabled_reason: None, + startup_timeout_sec: Some(Duration::from_secs(30)), + tool_timeout_sec: None, + default_tools_approval_mode: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + oauth: None, + oauth_resource: None, + tools: HashMap::new(), + } +} diff --git a/codex-rs/codex-mcp/src/mcp/mod_tests.rs b/codex-rs/codex-mcp/src/mcp/mod_tests.rs index 8367b530..7eb88208 100644 --- a/codex-rs/codex-mcp/src/mcp/mod_tests.rs +++ b/codex-rs/codex-mcp/src/mcp/mod_tests.rs @@ -334,11 +334,7 @@ fn qualified_mcp_tool_name_prefix_sanitizes_server_names_without_lowercasing() { fn mcp_server_permissions_handle_unattached_and_threadless_servers() { let mut config = test_mcp_config(PathBuf::new()); config.permission_profile = PermissionProfile::Disabled; - let mut missing_server = codex_apps_mcp_server_config( - "https://example.com", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ); + let mut missing_server = test_http_mcp_server_config("https://example.com"); missing_server.environment_id = "missing".to_string(); let mut selected_server = missing_server.clone(); selected_server.environment_id = "unattached".to_string(); @@ -445,11 +441,7 @@ fn tool_plugin_context_collects_app_and_mcp_sources() { "alpha".to_string(), McpPluginAttribution::new("alpha@test".to_string(), "alpha-plugin".to_string()), /*plugin_order*/ 0, - codex_apps_mcp_server_config( - "https://alpha.example", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ), + test_http_mcp_server_config("https://alpha.example"), )); config.mcp_server_catalog = catalog.build(); config.connector_snapshot = @@ -520,11 +512,7 @@ fn selected_mcp_attribution_does_not_join_an_unrelated_local_summary() { ), /*selection_order*/ 0, "executor-1", - codex_apps_mcp_server_config( - "https://github.example", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ), + test_http_mcp_server_config("https://github.example"), )); config.mcp_server_catalog = catalog.build(); config.connector_snapshot = @@ -559,128 +547,6 @@ fn selected_mcp_attribution_does_not_join_an_unrelated_local_summary() { assert!(provenance.is_selected_plugin_mcp_server("github")); } -#[test] -fn codex_apps_mcp_url_for_base_url_uses_plugin_service_paths() { - assert_eq!( - codex_apps_mcp_url_for_base_url("https://chatgpt.com/backend-api"), - "https://chatgpt.com/backend-api/ps/mcp" - ); - assert_eq!( - codex_apps_mcp_url_for_base_url("https://chat.openai.com"), - "https://chat.openai.com/backend-api/ps/mcp" - ); - assert_eq!( - codex_apps_mcp_url_for_base_url("https://gov.chatgpt.com/backend-api/"), - "https://gov.chatgpt.com/backend-api/ps/mcp" - ); - assert_eq!( - codex_apps_mcp_url_for_base_url("http://localhost:8080/api/codex"), - "http://localhost:8080/api/codex/ps/mcp" - ); - assert_eq!( - codex_apps_mcp_url_for_base_url("http://localhost:8080"), - "http://localhost:8080/api/codex/ps/mcp" - ); -} - -#[test] -fn codex_apps_server_config_uses_plugin_service_path() { - let config = codex_apps_mcp_server_config( - "https://chatgpt.com", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ); - let url = match &config.transport { - McpServerTransportConfig::StreamableHttp { url, .. } => url, - _ => panic!("expected streamable http transport for codex apps"), - }; - - assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp"); -} - -#[test] -fn codex_apps_server_config_forwards_thread_originator_header() { - let config = codex_apps_mcp_server_config( - "https://chatgpt.com", - /*apps_mcp_product_sku*/ None, - Some("thread_originator"), - ); - - match &config.transport { - McpServerTransportConfig::StreamableHttp { - http_headers, - env_http_headers, - .. - } => { - assert_eq!( - http_headers, - &Some(HashMap::from([ - ("originator".to_string(), "thread_originator".to_string()), - ("X-OpenAI-Product-Sku".to_string(), "codex".to_string()), - ])) - ); - assert!(env_http_headers.is_none()); - } - other => panic!("expected streamable http transport, got {other:?}"), - } -} - -#[test] -fn codex_apps_server_config_sets_product_sku_header() { - for (configured_product_sku, expected_product_sku) in [(None, "codex"), (Some("tpp"), "tpp")] { - let config = codex_apps_mcp_server_config( - "https://chatgpt.com", - configured_product_sku, - /*originator*/ None, - ); - - match &config.transport { - McpServerTransportConfig::StreamableHttp { - http_headers, - env_http_headers, - .. - } => { - assert_eq!( - http_headers, - &Some(HashMap::from([( - "X-OpenAI-Product-Sku".to_string(), - expected_product_sku.to_string(), - )])) - ); - assert!(env_http_headers.is_none()); - } - other => panic!("expected streamable http transport, got {other:?}"), - } - } -} - -#[test] -fn codex_apps_server_config_forwards_originator_and_configured_product_sku_headers() { - let config = codex_apps_mcp_server_config( - "https://chatgpt.com", - Some("tpp"), - Some("thread_originator"), - ); - - match &config.transport { - McpServerTransportConfig::StreamableHttp { - http_headers, - env_http_headers, - .. - } => { - assert_eq!( - http_headers, - &Some(HashMap::from([ - ("originator".to_string(), "thread_originator".to_string()), - ("X-OpenAI-Product-Sku".to_string(), "tpp".to_string()), - ])) - ); - assert!(env_http_headers.is_none()); - } - other => panic!("expected streamable http transport, got {other:?}"), - } -} - #[test] fn effective_mcp_servers_preserve_executor_credential_policy() { let mut config = test_mcp_config(PathBuf::new()); @@ -747,9 +613,8 @@ fn effective_mcp_servers_preserve_chatgpt_auth_for_trusted_origins() { ] { let mut config = test_mcp_config(PathBuf::new()); config.chatgpt_base_url = base_url.to_string(); - let server = codex_apps_mcp_server_config( - server_url, /*apps_mcp_product_sku*/ None, /*originator*/ None, - ); + let mut server = test_http_mcp_server_config(server_url); + server.auth = McpServerAuth::ChatGpt; let mut catalog = ResolvedMcpCatalog::builder(); catalog.register(McpServerRegistration::from_config( "trusted".to_string(), @@ -780,9 +645,8 @@ fn effective_mcp_servers_reject_untrusted_origins_for_chatgpt_auth() { ] { let mut config = test_mcp_config(PathBuf::new()); config.chatgpt_base_url = url.to_string(); - let server = codex_apps_mcp_server_config( - url, /*apps_mcp_product_sku*/ None, /*originator*/ None, - ); + let mut server = test_http_mcp_server_config(url); + server.auth = McpServerAuth::ChatGpt; let mut catalog = ResolvedMcpCatalog::builder(); catalog.register(McpServerRegistration::from_config( "untrusted".to_string(), @@ -870,11 +734,7 @@ async fn effective_mcp_servers_preserve_runtime_servers() { )); catalog.register(McpServerRegistration::from_config( CODEX_APPS_MCP_SERVER_NAME.to_string(), - codex_apps_mcp_server_config( - &config.chatgpt_base_url, - config.apps_mcp_product_sku.as_deref(), - /*originator*/ None, - ), + test_http_mcp_server_config("https://chatgpt.com/backend-api/ps/mcp"), )); config.mcp_server_catalog = catalog.build(); @@ -884,13 +744,11 @@ async fn effective_mcp_servers_preserve_runtime_servers() { let docs = effective .get("docs") .expect("configured server should exist"); - let codex_apps = effective - .get(CODEX_APPS_MCP_SERVER_NAME) - .expect("codex apps server should exist"); + // aKode never connects to the ChatGPT-hosted apps MCP server. + assert!(!effective.contains_key(CODEX_APPS_MCP_SERVER_NAME)); let sample = sample.config(); let docs = docs.config(); - let codex_apps = codex_apps.config(); match &sample.transport { McpServerTransportConfig::StreamableHttp { url, .. } => { @@ -904,10 +762,4 @@ async fn effective_mcp_servers_preserve_runtime_servers() { } other => panic!("expected streamable http transport, got {other:?}"), } - match &codex_apps.transport { - McpServerTransportConfig::StreamableHttp { url, .. } => { - assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp"); - } - other => panic!("expected streamable http transport, got {other:?}"), - } } diff --git a/codex-rs/core-plugins/src/lib.rs b/codex-rs/core-plugins/src/lib.rs index 37489a97..138dfd33 100644 --- a/codex-rs/core-plugins/src/lib.rs +++ b/codex-rs/core-plugins/src/lib.rs @@ -27,7 +27,6 @@ mod plugin_metrics_sidecar; mod provider; mod recommended_plugin_install; pub mod remote; -pub mod remote_bundle; pub mod remote_legacy; mod remote_metadata; mod remote_plugin_id_resolver; diff --git a/codex-rs/core-plugins/src/plugin_bundle_archive.rs b/codex-rs/core-plugins/src/plugin_bundle_archive.rs index 2722620c..2f5a2f2c 100644 --- a/codex-rs/core-plugins/src/plugin_bundle_archive.rs +++ b/codex-rs/core-plugins/src/plugin_bundle_archive.rs @@ -162,4 +162,3 @@ fn enforce_total_extracted_size( *extracted_bytes = next_total; Ok(()) } - diff --git a/codex-rs/core-plugins/src/remote.rs b/codex-rs/core-plugins/src/remote.rs index fbb6137f..7325c8bd 100644 --- a/codex-rs/core-plugins/src/remote.rs +++ b/codex-rs/core-plugins/src/remote.rs @@ -1,4 +1,3 @@ - use crate::app_mcp_routing::apply_app_mcp_routing_policy; use crate::error_subtype::http_status_sub_error_type; use crate::http_client_selector::HttpClientSelector; @@ -27,7 +26,6 @@ use codex_plugin::PluginId; use codex_plugin::app_connector_ids_from_declarations; use codex_plugin::prompt_safe_plugin_description; use codex_runtime_agent_instance::RuntimeAuthSlot; -use codex_utils_absolute_path::AbsolutePathBuf; use http::StatusCode; use serde::Deserialize; use serde::Serialize; @@ -61,22 +59,11 @@ pub(crate) use remote_installed_plugin_sync::sync_remote_installed_plugin_bundle pub use search::RemotePluginSearchPage; pub use search::RemotePluginSearchRequest; pub use search::search_remote_plugins; -pub use share::RemotePluginShareAccessPolicy; pub use share::RemotePluginShareDiscoverability; pub use share::RemotePluginSharePrincipal; pub use share::RemotePluginSharePrincipalRole; pub use share::RemotePluginSharePrincipalType; -pub use share::RemotePluginShareSaveResult; -pub use share::RemotePluginShareTarget; -pub use share::RemotePluginShareTargetRole; -pub use share::RemotePluginShareUpdateDiscoverability; -pub use share::RemotePluginShareUpdateTargetsResult; -pub use share::checkout_remote_plugin_share; -pub use share::delete_remote_plugin_share; -pub use share::list_remote_plugin_shares; pub use share::load_plugin_share_remote_ids_by_local_path; -pub use share::save_remote_plugin_share; -pub use share::update_remote_plugin_share_targets; pub const REMOTE_GLOBAL_MARKETPLACE_NAME: &str = "openai-curated-remote"; pub const REMOTE_CREATED_BY_ME_MARKETPLACE_NAME: &str = "created-by-me-remote"; @@ -168,7 +155,6 @@ impl RemotePluginServiceConfig { runtime_auth: None, } } - } impl PartialEq for RemotePluginServiceConfig { @@ -287,12 +273,6 @@ pub struct RemotePluginShareContext { pub can_publish_to_workspace: Option, } -#[derive(Debug, Clone, PartialEq)] -pub struct RemotePluginShareSummary { - pub summary: RemotePluginSummary, - pub local_plugin_path: Option, -} - #[derive(Debug, Clone, PartialEq)] pub struct RemotePluginDetail { pub marketplace_name: String, @@ -301,7 +281,6 @@ pub struct RemotePluginDetail { pub share_url: Option, pub description: Option, pub release_version: Option, - pub bundle_download_url: Option, pub app_manifest: Option, pub skills: Vec, pub onboarding_skill_name: Option, @@ -459,27 +438,6 @@ pub enum RemotePluginCatalogError { #[error("invalid plugin path `{path}`: {reason}")] InvalidPluginPath { path: PathBuf, reason: String }, - #[error("remote plugin `{remote_plugin_id}` is not available for plugin/share/checkout")] - PluginShareCheckoutNotAvailable { remote_plugin_id: String }, - - #[error("failed to archive plugin at `{path}`: {source}")] - Archive { - path: PathBuf, - #[source] - source: std::io::Error, - }, - - #[error("failed to join plugin archive task: {0}")] - ArchiveJoin(#[source] tokio::task::JoinError), - - #[error( - "plugin archive would be {bytes} bytes, exceeding the maximum upload size of {max_bytes} bytes" - )] - ArchiveTooLarge { bytes: usize, max_bytes: usize }, - - #[error("workspace plugin upload response did not include an etag")] - MissingUploadEtag, - #[error("{0}")] UnexpectedResponse(String), @@ -510,11 +468,6 @@ impl RemotePluginCatalogError { | Self::UnexpectedSkillName { .. } | Self::UnexpectedEnabledState { .. } | Self::InvalidPluginPath { .. } - | Self::PluginShareCheckoutNotAvailable { .. } - | Self::Archive { .. } - | Self::ArchiveJoin(_) - | Self::ArchiveTooLarge { .. } - | Self::MissingUploadEtag | Self::UnexpectedResponse(_) | Self::InstalledPluginsFetchTimeout | Self::CacheRemove(_) => None, @@ -626,8 +579,6 @@ struct RemotePluginReleaseResponse { display_name: String, description: String, #[serde(default)] - bundle_download_url: Option, - #[serde(default)] app_ids: Vec, #[serde(default)] app_manifest: Option, @@ -1025,7 +976,6 @@ pub(crate) async fn fetch_recommended_plugin_install_metadata( config, auth, plugin_id, - /*include_download_urls*/ false, RECOMMENDED_PLUGINS_TIMEOUT, ) .await @@ -1202,7 +1152,6 @@ pub(crate) async fn fetch_remote_installed_plugins_with_display_assets( config, auth, RemoteInstalledPluginScope::All, - /*include_download_urls*/ false, display_assets, ) .await? @@ -1277,14 +1226,16 @@ pub async fn fetch_remote_plugin_detail( marketplace_name: &str, plugin_id: &str, ) -> Result { - fetch_remote_plugin_detail_with_download_url_option( - config, - auth, - marketplace_name, - plugin_id, - /*include_download_urls*/ false, - ) - .await + let auth = ensure_chatgpt_auth(auth)?; + let _ = marketplace_name; + let plugin = fetch_plugin_detail(config, auth, plugin_id).await?; + let scope = plugin.scope; + let marketplace_name = remote_plugin_canonical_marketplace_name(&plugin)?.to_string(); + // Remote plugin IDs uniquely identify remote plugins, so the caller-provided + // marketplace name is not validated here. The backend detail response is the + // source of truth for the plugin's actual scope/marketplace. + + build_remote_plugin_detail(config, auth, scope, marketplace_name, plugin_id, plugin).await } pub async fn fetch_remote_plugin_share_context( @@ -1293,29 +1244,10 @@ pub async fn fetch_remote_plugin_share_context( plugin_id: &str, ) -> Result, RemotePluginCatalogError> { let auth = ensure_chatgpt_auth(auth)?; - let plugin = fetch_plugin_detail( - config, auth, plugin_id, /*include_download_urls*/ false, - ) - .await?; + let plugin = fetch_plugin_detail(config, auth, plugin_id).await?; remote_plugin_share_context(&plugin) } -pub async fn fetch_remote_plugin_detail_with_download_urls( - config: &RemotePluginServiceConfig, - auth: Option<&CodexAuth>, - marketplace_name: &str, - plugin_id: &str, -) -> Result { - fetch_remote_plugin_detail_with_download_url_option( - config, - auth, - marketplace_name, - plugin_id, - /*include_download_urls*/ true, - ) - .await -} - pub async fn fetch_remote_plugin_skill_detail( config: &RemotePluginServiceConfig, auth: Option<&CodexAuth>, @@ -1327,24 +1259,6 @@ pub async fn fetch_remote_plugin_skill_detail( Err(RemotePluginCatalogError::Unavailable) } -async fn fetch_remote_plugin_detail_with_download_url_option( - config: &RemotePluginServiceConfig, - auth: Option<&CodexAuth>, - _marketplace_name: &str, - plugin_id: &str, - include_download_urls: bool, -) -> Result { - let auth = ensure_chatgpt_auth(auth)?; - let plugin = fetch_plugin_detail(config, auth, plugin_id, include_download_urls).await?; - let scope = plugin.scope; - let marketplace_name = remote_plugin_canonical_marketplace_name(&plugin)?.to_string(); - // Remote plugin IDs uniquely identify remote plugins, so the caller-provided - // marketplace name is not validated here. The backend detail response is the - // source of truth for the plugin's actual scope/marketplace. - - build_remote_plugin_detail(config, auth, scope, marketplace_name, plugin_id, plugin).await -} - async fn build_remote_plugin_detail( config: &RemotePluginServiceConfig, auth: &CodexAuth, @@ -1392,7 +1306,6 @@ async fn build_remote_plugin_detail( share_url: plugin.share_url, description: non_empty_string(Some(&plugin.release.description)), release_version: plugin.release.version, - bundle_download_url: plugin.release.bundle_download_url, app_manifest: plugin.release.app_manifest, skills, onboarding_skill_name: plugin.release.onboarding_skill_name, @@ -1509,13 +1422,7 @@ pub async fn resolve_remote_plugin_uninstall_target( remote_plugin_id: &str, ) -> Result { let auth = ensure_chatgpt_auth(auth)?; - let plugin = fetch_plugin_detail( - config, - auth, - remote_plugin_id, - /*include_download_urls*/ false, - ) - .await?; + let plugin = fetch_plugin_detail(config, auth, remote_plugin_id).await?; let marketplace_name = remote_plugin_canonical_marketplace_name(&plugin)?.to_string(); let plugin_id = PluginId::new(plugin.name.clone(), marketplace_name).map_err(|err| { RemotePluginCatalogError::UnexpectedResponse(format!( @@ -1928,7 +1835,6 @@ async fn fetch_installed_plugins_for_scope( config, auth, RemoteInstalledPluginScope::Single(scope), - /*include_download_urls*/ false, InstalledPluginDisplayAssets::Include, ) .await @@ -1938,7 +1844,6 @@ async fn fetch_installed_plugins( config: &RemotePluginServiceConfig, auth: &CodexAuth, scope: RemoteInstalledPluginScope, - include_download_urls: bool, display_assets: InstalledPluginDisplayAssets, ) -> Result, RemotePluginCatalogError> { // Only a complete inventory is authoritative: every failure discards all fetched pages @@ -1953,7 +1858,6 @@ async fn fetch_installed_plugins( auth, scope, page_token.as_deref(), - include_download_urls, display_assets, ) .await?; @@ -2001,10 +1905,9 @@ async fn get_remote_plugin_installed_page( auth: &CodexAuth, scope: RemoteInstalledPluginScope, page_token: Option<&str>, - include_download_urls: bool, display_assets: InstalledPluginDisplayAssets, ) -> Result { - let _ = (config, auth, scope, page_token, include_download_urls, display_assets); + let _ = (config, auth, scope, page_token, display_assets); Err(RemotePluginCatalogError::Unavailable) } @@ -2012,26 +1915,17 @@ async fn fetch_plugin_detail( config: &RemotePluginServiceConfig, auth: &CodexAuth, plugin_id: &str, - include_download_urls: bool, ) -> Result { - fetch_plugin_detail_with_timeout( - config, - auth, - plugin_id, - include_download_urls, - REMOTE_PLUGIN_CATALOG_TIMEOUT, - ) - .await + fetch_plugin_detail_with_timeout(config, auth, plugin_id, REMOTE_PLUGIN_CATALOG_TIMEOUT).await } async fn fetch_plugin_detail_with_timeout( config: &RemotePluginServiceConfig, auth: &CodexAuth, plugin_id: &str, - include_download_urls: bool, timeout: Duration, ) -> Result { - let _ = (config, auth, plugin_id, include_download_urls, timeout); + let _ = (config, auth, plugin_id, timeout); Err(RemotePluginCatalogError::Unavailable) } diff --git a/codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs b/codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs index 74a97d35..f068d68e 100644 --- a/codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs +++ b/codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs @@ -137,12 +137,10 @@ pub(crate) async fn sync_remote_installed_plugin_bundles_once_with_snapshot( ) -> Result { let auth = ensure_chatgpt_auth(auth)?; let config = &config.for_current_account(); - let authenticated_account_id = auth.get_account_id(); let fetched_installed_plugins = fetch_installed_plugins( config, auth, RemoteInstalledPluginScope::All, - /*include_download_urls*/ true, InstalledPluginDisplayAssets::Include, ) .await?; @@ -213,7 +211,6 @@ pub(crate) async fn sync_remote_installed_plugin_bundles_once_with_snapshot( BTreeSet::new(), ), ]); - let mut materialized_remote_plugins = BTreeMap::new(); let mut failed_remote_plugin_ids = BTreeSet::new(); let mut failed_materialization_remote_plugin_ids = BTreeSet::new(); let mut installed_plugins = Vec::new(); @@ -221,8 +218,6 @@ pub(crate) async fn sync_remote_installed_plugin_bundles_once_with_snapshot( for (installed_plugin, cached_plugin, plugin_id) in validated_installed_plugins { let marketplace_name = cached_plugin.marketplace_name.clone(); let plugin = installed_plugin.plugin; - let scope = plugin.scope; - let discoverability = plugin.discoverability; installed_plugin_names_by_marketplace .entry(marketplace_name.clone()) .or_default() @@ -250,73 +245,15 @@ pub(crate) async fn sync_remote_installed_plugin_bundles_once_with_snapshot( continue; } - let bundle = match crate::remote_bundle::validate_remote_plugin_bundle( - &plugin.id, - &marketplace_name, - &plugin.name, - release_version, - plugin.release.bundle_download_url.as_deref(), - plugin.release.app_manifest.clone(), - ) { - Ok(bundle) => bundle, - Err(err) => { - warn!( - remote_plugin_id = %plugin.id, - plugin = %plugin.name, - marketplace = %marketplace_name, - error = %err, - "skipping remote installed plugin bundle download" - ); - failed_remote_plugin_ids.insert(plugin.id.clone()); - failed_materialization_remote_plugin_ids.insert(plugin.id); - installed_plugins.push(cached_plugin); - continue; - } - }; - - // Read the old bundle before installation replaces it, including capabilities removed - // by the new version. Unchanged bundles never reach this metadata-loading path. - let mut capabilities = RemotePluginCapabilities::default(); - capabilities.include_active_bundle(&store, &plugin_id).await; - match crate::remote_bundle::download_and_install_remote_plugin_bundle( - config, - codex_home.clone(), - bundle, - ) - .await - { - Ok(result) => { - let plugin_id = result.plugin_id; - capabilities.include_active_bundle(&store, &plugin_id).await; - changed_plugins.insert( - plugin_id.as_key(), - RemotePluginChange { - plugin_id: plugin_id.as_key(), - capabilities, - }, - ); - materialized_remote_plugins.insert( - plugin_id.as_key(), - RemotePluginMaterialization { - plugin_id, - scope, - discoverability, - authenticated_account_id: authenticated_account_id.clone(), - }, - ); - } - Err(err) => { - warn!( - remote_plugin_id = %plugin.id, - plugin = %plugin.name, - marketplace = %marketplace_name, - error = %err, - "failed to download remote installed plugin bundle" - ); - failed_remote_plugin_ids.insert(plugin.id.clone()); - failed_materialization_remote_plugin_ids.insert(plugin.id); - } - } + // aKode never downloads plugin bundles from backend-provided URLs. + warn!( + remote_plugin_id = %plugin.id, + plugin = %plugin.name, + marketplace = %marketplace_name, + "remote plugin bundle downloads are not supported" + ); + failed_remote_plugin_ids.insert(plugin.id.clone()); + failed_materialization_remote_plugin_ids.insert(plugin.id); installed_plugins.push(cached_plugin); } @@ -343,7 +280,7 @@ pub(crate) async fn sync_remote_installed_plugin_bundles_once_with_snapshot( Ok(RemoteInstalledPluginBundleSyncResult { outcome: RemoteInstalledPluginBundleSyncOutcome { - materialized_remote_plugins: materialized_remote_plugins.into_values().collect(), + materialized_remote_plugins: Vec::new(), changed_plugins: changed_plugins.into_values().collect(), failed_remote_plugin_ids: failed_remote_plugin_ids.into_iter().collect(), failed_materialization_remote_plugin_ids: failed_materialization_remote_plugin_ids diff --git a/codex-rs/core-plugins/src/remote/search.rs b/codex-rs/core-plugins/src/remote/search.rs index 91dc6475..3d26b1f4 100644 --- a/codex-rs/core-plugins/src/remote/search.rs +++ b/codex-rs/core-plugins/src/remote/search.rs @@ -35,4 +35,3 @@ pub async fn search_remote_plugins( let _ = (config, auth, search); Err(RemotePluginCatalogError::Unavailable) } - diff --git a/codex-rs/core-plugins/src/remote/share.rs b/codex-rs/core-plugins/src/remote/share.rs index 6b139167..05af2a48 100644 --- a/codex-rs/core-plugins/src/remote/share.rs +++ b/codex-rs/core-plugins/src/remote/share.rs @@ -1,5 +1,4 @@ use super::*; -use codex_login::CodexAuth; use codex_utils_absolute_path::AbsolutePathBuf; use serde::Deserialize; use serde::Serialize; @@ -7,24 +6,8 @@ use std::collections::BTreeMap; use std::io; use std::path::Path; -mod checkout; mod local_paths; -pub use checkout::checkout_remote_plugin_share; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RemotePluginShareSaveResult { - pub remote_plugin_id: String, - pub share_url: Option, - pub can_publish_to_workspace: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct RemotePluginShareAccessPolicy { - pub discoverability: Option, - pub share_targets: Option>, -} - #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RemotePluginShareDiscoverability { @@ -33,14 +16,6 @@ pub enum RemotePluginShareDiscoverability { Private, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum RemotePluginShareUpdateDiscoverability { - Listed, - Unlisted, - Private, -} - #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum RemotePluginSharePrincipalType { @@ -49,13 +24,6 @@ pub enum RemotePluginSharePrincipalType { Workspace, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct RemotePluginShareTarget { - pub principal_type: RemotePluginSharePrincipalType, - pub principal_id: String, - pub role: RemotePluginShareTargetRole, -} - #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub struct RemotePluginSharePrincipal { pub principal_type: RemotePluginSharePrincipalType, @@ -64,13 +32,6 @@ pub struct RemotePluginSharePrincipal { pub name: String, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum RemotePluginShareTargetRole { - Reader, - Editor, -} - #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum RemotePluginSharePrincipalRole { @@ -79,33 +40,6 @@ pub enum RemotePluginSharePrincipalRole { Owner, } -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RemotePluginShareUpdateTargetsResult { - pub principals: Vec, - pub discoverability: RemotePluginShareDiscoverability, -} - -pub async fn save_remote_plugin_share( - config: &RemotePluginServiceConfig, - auth: Option<&CodexAuth>, - codex_home: &Path, - plugin_path: &AbsolutePathBuf, - remote_plugin_id: Option<&str>, - access_policy: RemotePluginShareAccessPolicy, -) -> Result { - let _ = (config, auth, codex_home, plugin_path, remote_plugin_id, access_policy); - Err(RemotePluginCatalogError::Unavailable) -} - -pub async fn list_remote_plugin_shares( - config: &RemotePluginServiceConfig, - auth: Option<&CodexAuth>, - codex_home: &Path, -) -> Result, RemotePluginCatalogError> { - let _ = (config, auth, codex_home); - Err(RemotePluginCatalogError::Unavailable) -} - pub fn load_plugin_share_remote_ids_by_local_path( codex_home: &Path, ) -> io::Result> { @@ -125,25 +59,3 @@ pub fn load_plugin_share_remote_ids_by_local_path( }) .collect() } - -pub async fn delete_remote_plugin_share( - config: &RemotePluginServiceConfig, - auth: Option<&CodexAuth>, - codex_home: &Path, - remote_plugin_id: &str, -) -> Result<(), RemotePluginCatalogError> { - let _ = (config, auth, codex_home, remote_plugin_id); - Err(RemotePluginCatalogError::Unavailable) -} - -pub async fn update_remote_plugin_share_targets( - config: &RemotePluginServiceConfig, - auth: Option<&CodexAuth>, - remote_plugin_id: &str, - targets: Vec, - discoverability: RemotePluginShareUpdateDiscoverability, -) -> Result { - let _ = (config, auth, remote_plugin_id, targets, discoverability); - Err(RemotePluginCatalogError::Unavailable) -} - diff --git a/codex-rs/core-plugins/src/remote/share/local_paths.rs b/codex-rs/core-plugins/src/remote/share/local_paths.rs index 646687dd..7d01e0b0 100644 --- a/codex-rs/core-plugins/src/remote/share/local_paths.rs +++ b/codex-rs/core-plugins/src/remote/share/local_paths.rs @@ -1,16 +1,14 @@ use codex_utils_absolute_path::AbsolutePathBuf; use serde::Deserialize; -use serde::Serialize; use std::collections::BTreeMap; use std::io; -use std::io::Write; use std::path::Path; use std::sync::Mutex; const PLUGIN_SHARE_LOCAL_PATHS_FILE: &str = ".tmp/plugin-share-local-paths-v1.json"; static PLUGIN_SHARE_LOCAL_PATHS_LOCK: Mutex<()> = Mutex::new(()); -#[derive(Debug, Default, Deserialize, Serialize)] +#[derive(Debug, Default, Deserialize)] #[serde(rename_all = "camelCase")] struct PluginShareLocalPaths { #[serde(default)] @@ -24,17 +22,6 @@ pub(crate) fn load_plugin_share_local_paths( read_plugin_share_local_paths(codex_home) } -pub(crate) fn record_plugin_share_local_path( - codex_home: &Path, - remote_plugin_id: &str, - plugin_path: AbsolutePathBuf, -) -> io::Result<()> { - let _guard = lock_plugin_share_local_paths()?; - let mut mapping = read_plugin_share_local_paths_for_update(codex_home)?; - mapping.insert(remote_plugin_id.to_string(), plugin_path); - write_plugin_share_local_paths(codex_home, mapping) -} - fn lock_plugin_share_local_paths() -> io::Result> { PLUGIN_SHARE_LOCAL_PATHS_LOCK .lock() @@ -63,52 +50,6 @@ fn read_plugin_share_local_paths( Ok(mapping.local_plugin_paths_by_remote_plugin_id) } -fn read_plugin_share_local_paths_for_update( - codex_home: &Path, -) -> io::Result> { - match read_plugin_share_local_paths(codex_home) { - Ok(mapping) => Ok(mapping), - // This is a best-effort cache under .tmp, so malformed state should not - // permanently block future share saves or deletes. - Err(err) if err.kind() == io::ErrorKind::InvalidData => Ok(BTreeMap::new()), - Err(err) => Err(err), - } -} - -fn write_plugin_share_local_paths( - codex_home: &Path, - mapping: BTreeMap, -) -> io::Result<()> { - let path = plugin_share_local_paths_path(codex_home); - if mapping.is_empty() { - match std::fs::remove_file(&path) { - Ok(()) => return Ok(()), - Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(err) => return Err(err), - } - } - - let contents = serde_json::to_string_pretty(&PluginShareLocalPaths { - local_plugin_paths_by_remote_plugin_id: mapping, - }) - .map_err(io::Error::other)?; - write_atomically(&path, &format!("{contents}\n")) -} - -fn write_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(()) -} - fn plugin_share_local_paths_path(codex_home: &Path) -> std::path::PathBuf { codex_home.join(PLUGIN_SHARE_LOCAL_PATHS_FILE) } diff --git a/codex-rs/core-plugins/src/remote_mutations.rs b/codex-rs/core-plugins/src/remote_mutations.rs index 4878d241..14ef2891 100644 --- a/codex-rs/core-plugins/src/remote_mutations.rs +++ b/codex-rs/core-plugins/src/remote_mutations.rs @@ -6,23 +6,16 @@ use super::EffectivePluginsChangedCallback; use super::PluginInstallOutcome; use super::PluginsConfigInput; use super::PluginsManager; -use crate::marketplace::MarketplacePluginAuthPolicy; use crate::remote; use crate::remote::RemoteInstalledPluginBundleSyncError; use crate::remote::RemotePluginCacheMutationGuard; use crate::remote::RemotePluginCatalogError; use crate::remote::RemotePluginDetail; -use crate::remote_bundle; -use crate::remote_bundle::RemotePluginBundleInstallError; -use codex_app_server_protocol::PluginAuthPolicy; -use codex_app_server_protocol::PluginAvailability; -use codex_app_server_protocol::PluginInstallPolicy; use codex_login::CodexAuth; use codex_plugin::PluginId; use codex_plugin::PluginTelemetryMetadata; use std::sync::Arc; - pub struct RemotePluginInstallRequest { pub marketplace_name: String, pub remote_plugin_id: String, @@ -60,8 +53,6 @@ pub enum RemotePluginOperationErrorKind { context: &'static str, source: RemotePluginCatalogError, }, - #[error("install remote plugin bundle: {0}")] - Bundle(#[source] RemotePluginBundleInstallError), #[error("{context}: {source}")] Sync { context: &'static str, @@ -103,112 +94,12 @@ impl PluginsManager { } remote::validate_remote_plugin_id(&remote_plugin_id) .map_err(|err| unresolved(Error::InvalidRequest(err.message)))?; - let service = self - .remote_plugin_service_config(config) - .for_current_account(); - let detail = remote::fetch_remote_plugin_detail_with_download_urls( - &service, - auth, - &marketplace_name, - &remote_plugin_id, - ) - .await - .map_err(|source| { - unresolved(Error::Catalog { - context: "read remote plugin details before install", - source, - }) - })?; - let plugin_id = PluginId::parse(&detail.summary.id).map_err(|err| { - unresolved(Error::Internal(format!( - "invalid resolved plugin id `{}`: {err}", - detail.summary.id - ))) - })?; - let resolved = |kind| RemotePluginOperationError { - plugin_id: Some(plugin_id.clone()), - kind: Box::new(kind), - }; - if detail.summary.availability == PluginAvailability::DisabledByAdmin { - return Err(resolved(Error::DisabledByAdmin(remote_plugin_id))); - } - if detail.summary.install_policy == PluginInstallPolicy::NotAvailable { - return Err(resolved(Error::NotAvailable(remote_plugin_id))); - } - let bundle = remote_bundle::validate_remote_plugin_bundle( - &remote_plugin_id, - &detail.marketplace_name, - &detail.summary.name, - detail.release_version.as_deref(), - detail.bundle_download_url.as_deref(), - detail.app_manifest.clone(), - ) - .map_err(|err| resolved(Error::Bundle(err)))?; - let _sync_guard = self - .acquire_remote_installed_plugin_sync_guard() - .await - .map_err(|source| { - resolved(Error::Sync { - context: "failed to coordinate remote plugin install", - source, - }) - })?; - let cache_mutation = remote::mark_remote_plugin_cache_mutation_in_flight( - &self.codex_home, - &detail.marketplace_name, - &detail.summary.name, - ); - // Materialize first: a failed download must never leave a backend installation behind. - let installed = remote_bundle::download_and_install_remote_plugin_bundle( - &service, - self.codex_home.clone(), - bundle, - ) - .await - .map_err(|err| resolved(Error::Bundle(err)))?; - let install_result = if let Some(install_attempt_id) = install_attempt_id.as_deref() { - remote::install_remote_plugin_with_install_attempt_id( - &service, - auth, - &detail.marketplace_name, - &remote_plugin_id, - install_attempt_id, - ) - .await - } else { - remote::install_remote_plugin( - &service, - auth, - &detail.marketplace_name, - &remote_plugin_id, - ) - .await - } - .map_err(|source| { - resolved(Error::Catalog { - context: "install remote plugin", - source, - }) - })?; - self.maybe_start_remote_installed_plugins_cache_refresh_after_mutation( - config, - auth.cloned(), - on_effective_plugins_changed, - ); - Ok(RemotePluginInstallOutcome { - installed: PluginInstallOutcome { - plugin_id: installed.plugin_id, - plugin_version: installed.plugin_version, - installed_path: installed.installed_path, - auth_policy: match detail.summary.auth_policy { - PluginAuthPolicy::OnInstall => MarketplacePluginAuthPolicy::OnInstall, - PluginAuthPolicy::OnUse => MarketplacePluginAuthPolicy::OnUse, - }, - }, - detail, - app_ids_needing_auth: install_result.app_ids_needing_auth, - _cache_mutation: cache_mutation, - }) + // aKode never downloads plugin bundles from backend-provided URLs. + let _ = (auth, install_attempt_id, on_effective_plugins_changed); + Err(unresolved(Error::Catalog { + context: "install remote plugin", + source: RemotePluginCatalogError::Unavailable, + })) } /// Remove the backend installation and local cache, then schedule an installed-state refresh. diff --git a/codex-rs/core-plugins/src/script_attribution.rs b/codex-rs/core-plugins/src/script_attribution.rs index 7869007b..9a10ea77 100644 --- a/codex-rs/core-plugins/src/script_attribution.rs +++ b/codex-rs/core-plugins/src/script_attribution.rs @@ -124,7 +124,6 @@ impl PluginMeasurementTarget { } impl TrustedPluginRoots { - /// Adds already-trusted roots, preserving the existing root for each plugin and version. /// Distinct versions remain eligible for exact executor-version matching. pub fn extend(&mut self, other: &Self) { diff --git a/codex-rs/core/src/codex_delegate_tests.rs b/codex-rs/core/src/codex_delegate_tests.rs index 26e780e3..5aa1c7a4 100644 --- a/codex-rs/core/src/codex_delegate_tests.rs +++ b/codex-rs/core/src/codex_delegate_tests.rs @@ -236,86 +236,6 @@ async fn run_codex_thread_interactive_respects_pre_cancelled_spawn() { } } -#[tokio::test] -async fn delegate_start_analytics_honors_child_opt_out_with_enabled_parent() { - use codex_analytics::AnalyticsEventsClient; - use codex_login::CodexAuth; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::path; - - let server = MockServer::start().await; - Mock::given(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - let client = AnalyticsEventsClient::new( - AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()), - server.uri(), - /*analytics_enabled*/ Some(true), - ); - let (mut parent_session, parent_ctx, _rx_events) = - crate::session::tests::make_session_and_context_with_rx().await; - Arc::get_mut(&mut parent_session) - .expect("parent session should be uniquely owned") - .services - .analytics_events_client = client.clone(); - parent_session - .set_app_server_client_info( - Some("codex-test".to_string()), - Some("1.0.0".to_string()), - /*mcp_elicitations_auto_deny*/ false, - ) - .await - .expect("set parent client metadata"); - - let mut expected_events = Vec::new(); - for analytics_enabled in [false, true] { - let mut config = parent_ctx.config.as_ref().clone(); - config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never); - config.analytics_enabled = Some(analytics_enabled); - let (session, io) = run_codex_thread_interactive( - config, - Arc::clone(&parent_session.services.auth_manager), - Arc::clone(&parent_session.services.models_manager), - Arc::clone(&parent_session), - Arc::clone(&parent_ctx), - parent_ctx.initial_environments.clone(), - CancellationToken::new(), - SubAgentSource::Review, - codex_extension_api::SessionIsolation::Inherit, - /*initial_history*/ None, - crate::session::GitEnrichmentPolicy::Fresh, - codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile, - ) - .await - .expect("delegate session should start"); - if analytics_enabled { - expected_events.push(serde_json::json!([ - "codex_thread_initialized", - session.thread_id().to_string(), - ])); - } - io.shutdown_and_wait() - .await - .expect("delegate session should shut down"); - } - client.flush().await; - let events = server - .received_requests() - .await - .expect("analytics requests") - .into_iter() - .flat_map(|request| { - let payload: Value = serde_json::from_slice(&request.body).expect("analytics payload"); - payload["events"].as_array().expect("events array").clone() - }) - .map(|event| serde_json::json!([event["event_type"], event["event_params"]["thread_id"]])) - .collect::>(); - assert_eq!(events, expected_events); -} - #[tokio::test] async fn delegate_isolation_does_not_depend_on_attribution() { let (mut parent_session, mut parent_ctx, _rx_events) = diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 34e207fb..7e3e4723 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -645,7 +645,8 @@ async fn handle_approved_mcp_tool_call( ) .await?; } - Ok((None, request_meta)) + // The model-supplied arguments are what the MCP server receives. + Ok((arguments_value, request_meta)) }) .await .map_err(|error| { diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index 406cb2ad..edee128e 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -16,7 +16,6 @@ use crate::state::ActiveTurn; use crate::test_support::models_manager_with_provider; use crate::tools::hook_names::HookToolName; use crate::turn_metadata::ExecutionMetadata; -use codex_app_server_protocol as app_server_protocol; use codex_config::CONFIG_TOML_FILE; use codex_config::config_toml::ConfigToml; use codex_config::types::AppConfig; @@ -2275,153 +2274,6 @@ fn accepted_elicitation_without_content_defaults_to_accept() { assert_eq!(response, ReviewDecision::Approved); } -#[tokio::test] -async fn dispatched_mcp_approval_with_closed_response_is_classified_as_approval() { - use wiremock::matchers::method; - use wiremock::matchers::path; - - let server = wiremock::MockServer::start().await; - wiremock::Mock::given(method("POST")) - .and(path("/codex/analytics-events/events")) - .respond_with(wiremock::ResponseTemplate::new(200)) - .mount(&server) - .await; - - let (mut session, turn_context, rx_event) = make_session_and_context_with_rx().await; - let client = codex_analytics::AnalyticsEventsClient::new( - crate::test_support::auth_manager_from_auth( - codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ), - server.uri(), - /*analytics_enabled*/ Some(true), - ); - Arc::get_mut(&mut session) - .expect("session should be uniquely owned") - .services - .analytics_events_client = client.clone(); - *session.active_turn.lock().await = Some(ActiveTurn::default()); - - let call_id = "modern-missing-response"; - let thread_id = session.thread_id.to_string(); - let turn_id = turn_context.sub_id.clone(); - client.track_initialize( - /*connection_id*/ 1, - app_server_protocol::InitializeParams::default(), - "test-client".to_string(), - codex_analytics::AppServerRpcTransport::Stdio, - ); - let response = serde_json::from_value(serde_json::json!({ - "thread": { - "id": thread_id, "sessionId": thread_id, "preview": "", "ephemeral": false, - "modelProvider": "openai", "createdAt": 1, "updatedAt": 1, - "status": {"type": "idle"}, "cwd": &turn_context.config.cwd, - "cliVersion": "0.0.0", "source": "exec", "turns": [], - }, - "model": "test-model", "modelProvider": "openai", "cwd": &turn_context.config.cwd, - "approvalPolicy": "on-request", "approvalsReviewer": "user", - "sandbox": {"type": "dangerFullAccess"}, - })) - .expect("thread-start response should deserialize"); - client.track_response( - /*connection_id*/ 1, - app_server_protocol::RequestId::Integer(1), - &app_server_protocol::ClientResponsePayload::ThreadStart(response), - ); - client.track_notification(&app_server_protocol::ServerNotification::TurnStarted( - serde_json::from_value(serde_json::json!({ - "threadId": thread_id, - "turn": {"id": turn_id, "items": [], "status": "inProgress"}, - })) - .expect("turn-started notification should deserialize"), - )); - let mut item = serde_json::json!({ - "type": "mcpToolCall", "id": call_id, "server": "calendar", "tool": "send", - "status": "inProgress", "arguments": {}, - "appContext": {"connectorId": "calendar"}, - }); - client.track_notification(&app_server_protocol::ServerNotification::ItemStarted( - serde_json::from_value(serde_json::json!({ - "threadId": thread_id, "turnId": turn_id, "startedAtMs": 1, "item": item, - })) - .expect("item-started notification should deserialize"), - )); - - let action = ApprovalAction::McpToolCall { - id: call_id.to_string(), - environment_id: test_environment_id(&turn_context).to_owned(), - server: "calendar".to_string(), - tool_name: "send".to_string(), - arguments: None, - connector_id: Some("calendar".to_string()), - connector_name: None, - connector_description: None, - connected_account_email: None, - tool_title: None, - tool_description: None, - annotations: None, - hook_tool_name: HookToolName::new("mcp__calendar__send"), - approval_policy: AskForApproval::OnRequest, - reviewer: ApprovalsReviewer::User, - approval_mode: AppToolApproval::Auto, - allow_session_remember: true, - allow_persistent_approval: true, - prompt_permissions: None, - }; - let approval = tokio::spawn({ - let session = Arc::clone(&session); - let turn_context = Arc::clone(&turn_context); - async move { request_mcp_tool_user_approval(&session, &turn_context, call_id, &action).await } - }); - let event = tokio::time::timeout(std::time::Duration::from_secs(1), rx_event.recv()) - .await - .expect("approval request should be dispatched") - .expect("approval request should be received"); - assert!(matches!(event.msg, EventMsg::ElicitationRequest(_))); - *session.active_turn.lock().await = None; - assert_eq!( - approval.await.expect("approval task should complete"), - ApprovalResolution { - decision: ReviewDecision::Abort, - source: ApprovalResolutionSource::User, - cancellation_reason: Some(McpApprovalCancellationReason::Interrupted), - } - ); - - item["status"] = serde_json::json!("failed"); - client.track_notification(&app_server_protocol::ServerNotification::ItemCompleted( - serde_json::from_value(serde_json::json!({ - "threadId": thread_id, "turnId": turn_id, "completedAtMs": 2, "item": item, - })) - .expect("item-completed notification should deserialize"), - )); - client.flush().await; - let events = server - .received_requests() - .await - .expect("analytics requests should be recorded") - .into_iter() - .flat_map(|request| { - serde_json::from_slice::(&request.body) - .expect("analytics request should deserialize")["events"] - .as_array() - .expect("analytics events should be an array") - .clone() - }) - .collect::>(); - let mcp_events = events - .iter() - .filter(|event| { - event["event_type"] == "codex_mcp_tool_call_event" - && event["event_params"]["item_id"] == call_id - }) - .collect::>(); - assert_eq!(mcp_events.len(), 1); - assert_eq!( - mcp_events[0]["event_params"]["elicitation_type"], - "approval" - ); -} - #[tokio::test] async fn persist_codex_app_tool_approval_writes_tool_override() { let tmp = tempdir().expect("tempdir"); diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 018111b2..54e4a1c8 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -65,10 +65,8 @@ use core_test_support::test_codex::TurnInputRequest as ExternalTurnInputRequest; use codex_features::Feature; use codex_file_system::FileSystemSandboxContext; -use codex_http_client::ClientRouteClass; use codex_http_client::HttpClientFactory; use codex_http_client::OutboundProxyPolicy; -use codex_http_client::RouteAwareClientPool; use codex_login::CodexAuth; use codex_login::auth::AgentIdentityAuthPolicy; use codex_model_provider::create_model_provider; @@ -5293,143 +5291,6 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati } } -#[tokio::test] -async fn emit_subagent_session_started_includes_fork_lineage_and_originator() { - use codex_app_server_protocol::ServerNotification; - use codex_app_server_protocol::ThreadArchivedNotification; - use wiremock::Mock; - use wiremock::MockServer; - use wiremock::ResponseTemplate; - use wiremock::matchers::method; - use wiremock::matchers::path; - - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(200)) - .mount(&server) - .await; - - let auth_manager = - AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - let analytics_events_client = AnalyticsEventsClient::new( - auth_manager, - server.uri(), - /*analytics_enabled*/ Some(true), - ); - - let parent_thread_id = ThreadId::new(); - let forked_from_thread_id = ThreadId::new(); - let child_thread_id = ThreadId::new(); - let mut session_configuration = make_session_configuration_for_tests().await; - session_configuration.forked_from_thread_id = Some(forked_from_thread_id); - session_configuration.thread_source = Some(ThreadSource::GuardianReview); - - emit_subagent_session_started( - &analytics_events_client, - AppServerClientMetadata { - client_name: Some("codex-tui".to_string()), - client_version: Some("1.0.0".to_string()), - }, - SessionId::from(child_thread_id), - child_thread_id, - Some(parent_thread_id), - session_configuration.thread_config_snapshot(Vec::new()), - SubAgentSource::Other(crate::guardian::GUARDIAN_REVIEWER_NAME.to_string()), - /*resumed_created_at*/ None, - ); - - let event = timeout(Duration::from_secs(1), async { - 'wait_for_event: loop { - if let Some(requests) = server.received_requests().await { - for request in requests { - let payload: serde_json::Value = - serde_json::from_slice(&request.body).expect("valid analytics payload"); - if let Some(event) = payload["events"].as_array().and_then(|events| { - events - .iter() - .find(|event| event["event_type"] == "codex_thread_initialized") - }) { - break 'wait_for_event event.clone(); - } - } - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("subagent initialization analytics should be emitted"); - - assert_eq!(event["event_params"]["initialization_mode"], "new"); - assert_eq!(event["event_params"]["thread_source"], "guardian_review"); - assert_eq!( - event["event_params"]["parent_thread_id"], - parent_thread_id.to_string() - ); - assert_eq!( - event["event_params"]["forked_from_thread_id"], - forked_from_thread_id.to_string() - ); - assert_eq!( - event["event_params"]["app_server_client"]["product_client_id"], - "test_originator" - ); - - let prewarmed_thread_id = ThreadId::new(); - emit_subagent_session_started( - &analytics_events_client, - AppServerClientMetadata { - client_name: None, - client_version: None, - }, - SessionId::from(parent_thread_id), - prewarmed_thread_id, - Some(parent_thread_id), - session_configuration.thread_config_snapshot(Vec::new()), - SubAgentSource::Other(crate::guardian::GUARDIAN_REVIEWER_NAME.to_string()), - /*resumed_created_at*/ None, - ); - // Archive analytics exposes retained lineage even before a parent connection exists. - analytics_events_client.track_notification(&ServerNotification::ThreadArchived( - ThreadArchivedNotification { - thread_id: prewarmed_thread_id.to_string(), - }, - )); - analytics_events_client.flush().await; - let events = server - .received_requests() - .await - .expect("analytics requests") - .into_iter() - .flat_map(|request| { - let payload: serde_json::Value = - serde_json::from_slice(&request.body).expect("valid analytics payload"); - payload["events"] - .as_array() - .expect("analytics events") - .clone() - }) - .collect::>(); - let [initialization, archive] = events.as_slice() else { - panic!("expected one complete initialization and one archive: {events:?}"); - }; - assert_eq!(initialization, &event); - assert_eq!( - json!([ - archive["event_type"], - archive["event_params"]["thread_id"], - archive["event_params"]["thread_source"], - archive["event_params"]["parent_thread_id"], - ]), - json!([ - "codex_thread_archive_event", - prewarmed_thread_id.to_string(), - "guardian_review", - parent_thread_id.to_string(), - ]) - ); -} - async fn resolved_environments_for_configuration( session_configuration: &SessionConfiguration, environment_selections: &[TurnEnvironmentSelection], @@ -6780,24 +6641,6 @@ async fn response_metadata_builders_capture_fresh_mcp_attribution() { assert_eq!(compaction.mcp_attribution, expected); } -#[tokio::test] -async fn responses_metadata_uses_selected_harness_analytics_client() { - for enabled in [true, false] { - let (mut session, mut turn_context) = make_session_and_context().await; - session.services.analytics_events_client = AnalyticsEventsClient::new( - Arc::clone(&session.services.auth_manager), - turn_context.config.chatgpt_base_url.clone(), - Some(enabled), - ); - Arc::make_mut(&mut turn_context.config).analytics_enabled = Some(!enabled); - let step_context = StepContext::for_test(Arc::new(turn_context)); - let metadata = session - .responses_metadata(&step_context, CodexResponsesRequestKind::Turn) - .await; - assert_eq!(metadata.analytics_enabled, Some(enabled)); - } -} - // todo: use online model info pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { let (tx_event, _rx_event) = async_channel::unbounded(); @@ -6955,7 +6798,6 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { exec_policy, auth_manager: auth_manager.clone(), runtime_auth: Default::default(), - .with_legacy_custom_ca_fallback(), session_telemetry: session_telemetry.clone(), models_manager: Arc::clone(&models_manager), git_root_discovery: Arc::default(), @@ -9295,7 +9137,6 @@ where exec_policy, auth_manager: Arc::clone(&auth_manager), runtime_auth: Default::default(), - .with_legacy_custom_ca_fallback(), session_telemetry: session_telemetry.clone(), models_manager: Arc::clone(&models_manager), git_root_discovery: Arc::default(), @@ -10766,92 +10607,6 @@ async fn record_context_updates_emits_realtime_end_when_session_stops_being_live ); } -#[tokio::test] -async fn build_initial_context_reuses_in_flight_recommendation_prewarm() { - use wiremock::Mock; - use wiremock::ResponseTemplate; - use wiremock::matchers::method; - use wiremock::matchers::path; - use wiremock::matchers::query_param; - - core_test_support::skip_if_no_network!(); - - let server = start_mock_server().await; - Mock::given(method("GET")) - .and(path("/ps/plugins/suggested/codex")) - .and(query_param("scope", "GLOBAL")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "enabled": true, - "plugins": [{ - "id": "plugin_github", - "name": "github", - "display_name": "GitHub" - }] - }))) - .expect(1) - .mount(&server) - .await; - let (session, turn_context, _rx_event) = make_session_and_context_with_auth_and_config_and_rx( - CodexAuth::create_dummy_chatgpt_auth_for_testing(), - /*dynamic_tools*/ Vec::new(), - |config| { - config.chatgpt_base_url = server.uri(); - config - .features - .disable(Feature::ToolSuggest) - .expect("test config should allow feature update"); - for enabled_feature in [ - Feature::Apps, - Feature::Plugins, - Feature::RemotePlugin, - Feature::RecommendedPlugins, - ] { - config - .features - .enable(enabled_feature) - .expect("test config should allow feature update"); - } - }, - ) - .await; - let plugins_manager = &session.services.plugins_manager; - let plugins_config = turn_context.config.plugins_config_input(); - let auth = session.services.auth_manager.auth().await; - // Cached plugin loading and auth let initial context reach the shared recommendation lookup - // without awaiting unrelated I/O. - plugins_manager.plugins_for_config(&plugins_config).await; - let prewarm = - plugins_manager.recommended_plugins_mode_for_config(&plugins_config, auth.as_ref()); - tokio::pin!(prewarm); - assert!(futures::poll!(prewarm.as_mut()).is_pending()); - - // Keep the OnceCell initializer unpolled while first-thread context joins its in-flight fetch. - // This does not depend on how quickly the HTTP server returns its response. - let world_state = WorldState::default(); - let step_context = StepContext::for_test(Arc::clone(&turn_context)); - let initial_context = - session.build_initial_context_with_world_state(&step_context, &world_state); - tokio::pin!(initial_context); - assert!(futures::poll!(initial_context.as_mut()).is_pending()); - - let (_, (initial_context, _)) = tokio::join!(prewarm, initial_context); - let initial_context = - crate::context_manager::updates::merge_world_state_updates(initial_context); - assert_eq!( - developer_input_texts(&initial_context) - .into_iter() - .filter(|text| text.starts_with("")) - .collect::>(), - vec![concat!( - "\n", - "Here is a list of plugins that are available but not installed.\n\n", - "- GitHub (github@openai-curated-remote)\n", - "", - )] - ); - server.verify().await; -} - #[tokio::test] async fn build_initial_context_describes_active_realtime_state() { let (session, mut turn_context) = make_session_and_context().await; diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index c0b81388..7167756c 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -430,262 +430,6 @@ async fn fixed_thread_text_supersedes_the_live_provider_and_isolated_helpers_rej } } -#[test_case::test_case(None, "chatgpt.com", 1; "ordinary_openai")] -#[test_case::test_case(Some(codex_features::RuntimeAuthMode::DualHeader), "chatgpt.com", 0; "dual_header_openai")] -#[test_case::test_case(Some(codex_features::RuntimeAuthMode::AssertionOnly), "chatgpt.com", 0; "assertion_only_openai")] -#[test_case::test_case(Some(codex_features::RuntimeAuthMode::DualHeader), "example.test", 1; "dual_header_custom_backend")] -#[test_case::test_case(Some(codex_features::RuntimeAuthMode::AssertionOnly), "example.test", 1; "assertion_only_custom_backend")] -#[tokio::test] -async fn resumed_analytics_validates_openai_destination( - mode: Option, - host: &str, - expected_requests: usize, -) { - let proxy = MockServer::start().await; - wiremock::Mock::given(wiremock::matchers::path("/codex/analytics-events/events")) - .respond_with(wiremock::ResponseTemplate::new(200)) - .mount(&proxy) - .await; - let home = tempdir().expect("tempdir"); - let mut config = test_config().await; - config.codex_home = home.path().abs(); - config.cwd = home.path().abs(); - config.chatgpt_base_url = format!("http://{host}:{}", proxy.address().port()); - config.model_provider.base_url = Some(proxy.uri()); - config.respect_system_proxy = true; - config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File; - config.analytics_enabled = Some(true); - if let Some(mode) = mode { - config - .features - .enable(Feature::RuntimeAgentInstances) - .unwrap(); - config.runtime_auth_mode = mode; - } else { - config - .features - .disable(Feature::RuntimeAgentInstances) - .unwrap(); - } - codex_http_client::cache_system_proxy_route_for_test( - &format!("{}/codex/analytics-events/events", config.chatgpt_base_url), - proxy.uri(), - ); - codex_login::login_with_api_key( - &config.codex_home, - "resumed-key", - codex_login::AuthCredentialsStoreMode::File, - codex_login::AuthKeyringBackendKind::default(), - ) - .unwrap(); - let resumed_auth = - AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false) - .await - .unwrap(); - let original_auth = CodexAuth::from_api_key("startup-key"); - let mut manager = ThreadManager::with_models_provider_and_home_for_tests( - original_auth.clone(), - config.model_provider.clone(), - config.codex_home.to_path_buf(), - Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ); - let startup_analytics = AnalyticsEventsClient::new( - AuthManager::from_auth_for_testing(original_auth), - proxy.uri(), - /*analytics_enabled*/ Some(true), - ); - Arc::get_mut(&mut manager.state) - .expect("unshared thread manager state") - .analytics_events_client = Some(startup_analytics); - - let original = manager - .start_thread(StartThreadOptions { - history_mode: Some(ThreadHistoryMode::Legacy), - ..StartThreadOptions::new(config.clone()) - }) - .await - .expect("start original thread"); - original.thread.ensure_rollout_materialized().await; - original.thread.flush_rollout().await.unwrap(); - original.thread.shutdown_and_wait().await.unwrap(); - manager.remove_thread(&original.thread_id).await; - - let resumed = manager - .resume_thread_with_history( - config, - InitialHistory::Resumed(ResumedHistory { - history_revision: None, - conversation_id: original.thread_id, - history: Arc::new(Vec::new()), - rollout_path: original.thread.rollout_path(), - }), - resumed_auth, - /*parent_trace*/ None, - ClientMcpExtensions::default(), - ) - .await - .expect("resume with another auth owner"); - let analytics = &resumed.thread.session.services.analytics_events_client; - analytics.track_plugin_used( - codex_analytics::TrackEventsContext { - turn_metadata: None, - model_slug: "test-model".to_string(), - turn_id: "test-turn".to_string(), - thread_id: resumed.thread_id.to_string(), - product_client_id: "codex_work_cca".to_string(), - }, - codex_plugin::PluginTelemetryMetadata { - plugin_id: Some(codex_plugin::PluginId::parse("test@local").expect("valid plugin ID")), - remote_plugin_id: None, - capability_summary: None, - }, - ); - analytics.flush().await; - resumed.thread.shutdown_and_wait().await.unwrap(); - - let requests: Vec<_> = proxy - .received_requests() - .await - .unwrap() - .into_iter() - .filter(|request| request.url.path() == "/codex/analytics-events/events") - .collect(); - assert_eq!(requests.len(), expected_requests); - for request in requests { - assert_eq!(request.headers["authorization"], "Bearer resumed-key"); - assert!(!request.headers.contains_key("x-openai-agent-assertion")); - } -} - -/// A thread opt-out wins over a shared client without disabling its siblings. -#[tokio::test] -async fn thread_analytics_opt_out_overrides_shared_client() { - let server = MockServer::start().await; - wiremock::Mock::given(wiremock::matchers::method("POST")) - .and(wiremock::matchers::path("/codex/analytics-events/events")) - .respond_with(wiremock::ResponseTemplate::new(200)) - .mount(&server) - .await; - let temp_dir = tempdir().expect("tempdir"); - let mut config = test_config().await; - config.chatgpt_base_url = server.uri(); - config.model_provider.base_url = Some(server.uri()); - let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing(); - let shared_client = AnalyticsEventsClient::new( - AuthManager::from_auth_for_testing(auth.clone()), - server.uri(), - /*analytics_enabled*/ Some(true), - ); - let mut expected_thread_ids = Vec::new(); - let mut opted_out_thread_ids = Vec::new(); - - for (name, client_override, expected_enabled) in [ - ( - "enabled_override", - Some(shared_client.clone()), - [false, true, true], - ), - ( - "disabled_override", - Some(AnalyticsEventsClient::disabled()), - [false, false, false], - ), - ("no_override", None, [false, true, true]), - ] { - config.codex_home = temp_dir.path().join(name).abs(); - config.cwd = config.codex_home.abs(); - std::fs::create_dir_all(&config.codex_home).expect("create codex home"); - let mut manager = ThreadManager::with_models_provider_and_home_for_tests( - auth.clone(), - config.model_provider.clone(), - config.codex_home.to_path_buf(), - Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), - ); - Arc::get_mut(&mut manager.state) - .expect("unshared thread manager state") - .analytics_events_client = client_override; - - for (setting, enabled) in [Some(false), Some(true), None] - .into_iter() - .zip(expected_enabled) - { - config.analytics_enabled = setting; - let started = manager - .start_thread(StartThreadOptions::new(config.clone())) - .await - .expect("start analytics test thread"); - let services = &started.thread.session.services; - assert_eq!(started.thread.analytics_enabled(), enabled); - assert_eq!( - services - .session_extension_data - .get::() - .expect("analytics client in session store") - .is_enabled(), - enabled, - ); - let thread_id = started.thread_id.to_string(); - if enabled { - expected_thread_ids.push(thread_id.clone()); - } else { - opted_out_thread_ids.push(thread_id.clone()); - } - services.analytics_events_client.track_app_used( - codex_analytics::TrackEventsContext { - turn_metadata: None, - model_slug: "test-model".to_string(), - turn_id: format!("test-turn-{thread_id}"), - thread_id, - product_client_id: "codex_work_cca".to_string(), - }, - codex_analytics::AppInvocation { - connector_id: Some("test-connector".to_string()), - app_name: None, - invocation_type: None, - }, - /*elicitation_type*/ None, - ); - services.analytics_events_client.flush().await; - } - let shutdown = manager - .shutdown_all_threads_bounded(Duration::from_secs(10)) - .await; - assert_eq!(shutdown.completed.len(), 3); - } - - let events: Vec = server - .received_requests() - .await - .expect("analytics requests") - .into_iter() - .filter(|request| request.url.path() == "/codex/analytics-events/events") - .flat_map(|request| { - request.body_json::().expect("JSON body")["events"] - .as_array() - .expect("events array") - .clone() - }) - .collect(); - assert!(events.iter().all(|event| { - !opted_out_thread_ids - .iter() - .any(|thread_id| event["event_params"]["thread_id"] == thread_id.as_str()) - })); - let mut actual_thread_ids: Vec = events - .iter() - .filter(|event| event["event_type"] == "codex_app_used") - .map(|event| { - event["event_params"]["thread_id"] - .as_str() - .expect("app usage thread ID") - .to_string() - }) - .collect(); - actual_thread_ids.sort(); - expected_thread_ids.sort(); - assert_eq!(actual_thread_ids, expected_thread_ids); -} - /// Controls without a custom allocation policy still produce distinct thread identifiers. #[test] fn thread_id_generator_defaults_to_standard_ids() { @@ -2196,11 +1940,11 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors() .expect("thread-scoped MCP resolution should identify its source") .clone(), )); - let mut server = codex_mcp::codex_apps_mcp_server_config( - "https://selected.invalid", - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ); + let mut server: codex_config::McpServerConfig = + serde_json::from_value(serde_json::json!({ + "url": "https://selected.invalid/mcp", + })) + .expect("valid MCP server config"); let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location; let source_environment_id = environment_id.clone(); @@ -2414,20 +2158,10 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors() )); assert_eq!(Some(server), expected.build().server(name)); } - let codex_apps_server = codex_mcp::configured_mcp_servers(&first_resolved.config) - .remove(codex_mcp::CODEX_APPS_MCP_SERVER_NAME) - .expect("Codex Apps server should be configured"); - let codex_apps_headers = match codex_apps_server.transport { - codex_config::McpServerTransportConfig::StreamableHttp { http_headers, .. } => http_headers, - codex_config::McpServerTransportConfig::Stdio { .. } => { - panic!("Codex Apps server should use streamable HTTP") - } - }; - assert_eq!( - codex_apps_headers - .expect("Codex Apps headers should be configured") - .get("originator"), - Some(&"codex_work_desktop".to_string()) + // aKode never contributes the ChatGPT-hosted Codex Apps server. + assert!( + !codex_mcp::configured_mcp_servers(&first_resolved.config) + .contains_key(codex_mcp::CODEX_APPS_MCP_SERVER_NAME) ); for (policy, disabled_plugin_ids, selected_enabled, expected_mcp_loads) in [ ("", vec!["plugin-selected-a".to_string()], false, 1), diff --git a/codex-rs/core/tests/common/apps_test_server.rs b/codex-rs/core/tests/common/apps_test_server.rs index 3d090cbd..366493c5 100644 --- a/codex-rs/core/tests/common/apps_test_server.rs +++ b/codex-rs/core/tests/common/apps_test_server.rs @@ -843,3 +843,16 @@ impl Respond for CodexAppsJsonRpcResponder { } } } + +/// Builds an MCP server config that points at this mock apps server. aKode no longer ships a +/// production helper for the ChatGPT-hosted apps server; tests that exercise the generic +/// streamable HTTP and ChatGPT-auth MCP paths use this mock-only config instead. +pub fn mock_apps_mcp_server_config(mock_base_url: &str) -> codex_config::McpServerConfig { + #[expect(clippy::expect_used, reason = "static test config is valid")] + serde_json::from_value(json!({ + "url": format!("{}/api/codex/ps/mcp", mock_base_url.trim_end_matches('/')), + "auth": "chatgpt", + "startup_timeout_sec": 30, + })) + .expect("valid mock apps MCP server config") +} diff --git a/codex-rs/core/tests/suite/app_tool_exposure.rs b/codex-rs/core/tests/suite/app_tool_exposure.rs index 95bdcb3d..ec86d8ad 100644 --- a/codex-rs/core/tests/suite/app_tool_exposure.rs +++ b/codex-rs/core/tests/suite/app_tool_exposure.rs @@ -1,6 +1,7 @@ //! Verifies connector-scoped exposure, server restrictions, and MCP dispatch. use codex_core::config::Config; +use core_test_support::apps_test_server::mock_apps_mcp_server_config; use codex_extension_api::ExtensionFuture; use codex_extension_api::ExtensionRegistryBuilder; use codex_extension_api::McpServerContribution; @@ -32,11 +33,7 @@ impl McpServerContributor for AppsServer { context: McpServerContributionContext<'a, Config>, ) -> ExtensionFuture<'a, Vec> { Box::pin(async move { - let mut config = codex_mcp::hosted_plugin_runtime_mcp_server_config( - &context.config().chatgpt_base_url, - /*apps_mcp_product_sku*/ None, - context.originator(), - ); + let mut config = mock_apps_mcp_server_config(&context.config().chatgpt_base_url); config.omit_tools_from = Some(self.0.clone()); vec![McpServerContribution::HostedApps { config: Box::new(config), diff --git a/codex-rs/core/tests/suite/code_mode.rs b/codex-rs/core/tests/suite/code_mode.rs index 4a4de630..6b073c74 100644 --- a/codex-rs/core/tests/suite/code_mode.rs +++ b/codex-rs/core/tests/suite/code_mode.rs @@ -38,7 +38,7 @@ use codex_http_client::DestinationPolicy; use codex_http_client::NetworkPolicyController; use codex_login::CodexAuth; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; -use codex_mcp::codex_apps_mcp_server_config; +use core_test_support::apps_test_server::mock_apps_mcp_server_config; use codex_models_manager::bundled_models_response; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::CollaborationMode; @@ -2046,11 +2046,7 @@ async fn code_mode_mcp_metadata_keeps_originating_window_after_compaction() -> R let (release_tx, release_rx) = oneshot::channel(); let control = Arc::new(ResultMetadataTestControl { server: Mutex::new(McpServerContribution::HostedApps { - config: Box::new(codex_apps_mcp_server_config( - &apps_server.chatgpt_base_url, - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - )), + config: Box::new(mock_apps_mcp_server_config(&apps_server.chatgpt_base_url)), protocol_mode: None, }), gate: Mutex::new(Some((reached_tx, release_rx))), @@ -2643,11 +2639,7 @@ async fn result_metadata_follows_call_binding( extensions.mcp_server_contributor(Arc::new(ResultMetadataTestControl { server: Mutex::new(McpServerContribution::Set { name: CODEX_APPS_MCP_SERVER_NAME.to_string(), - config: Box::new(codex_apps_mcp_server_config( - &apps_server.chatgpt_base_url, - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - )), + config: Box::new(mock_apps_mcp_server_config(&apps_server.chatgpt_base_url)), }), gate: Mutex::new(None), })); @@ -2880,11 +2872,7 @@ async fn code_mode_result_metadata_keeps_prepared_call_binding_across_runtime_re let (release_tx, release_rx) = oneshot::channel(); let control = Arc::new(ResultMetadataTestControl { server: Mutex::new(McpServerContribution::HostedApps { - config: Box::new(codex_apps_mcp_server_config( - &apps_server.chatgpt_base_url, - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - )), + config: Box::new(mock_apps_mcp_server_config(&apps_server.chatgpt_base_url)), protocol_mode: None, }), gate: Mutex::new(Some((reached_tx, release_rx))), @@ -2949,11 +2937,7 @@ async fn code_mode_result_metadata_keeps_prepared_call_binding_across_runtime_re // The next call uses an extension-owned binding, but the held call keeps its host proof. *control.server.lock().unwrap() = McpServerContribution::Set { name: CODEX_APPS_MCP_SERVER_NAME.to_string(), - config: Box::new(codex_apps_mcp_server_config( - &refreshed_apps.chatgpt_base_url, - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - )), + config: Box::new(mock_apps_mcp_server_config(&refreshed_apps.chatgpt_base_url)), }; let current_config = test.codex.config().await; let _ = test @@ -3031,11 +3015,7 @@ async fn code_mode_late_result_metadata_with_large_arguments_survives_waits() -> let (release_tx, release_rx) = oneshot::channel(); let control = Arc::new(ResultMetadataTestControl { server: Mutex::new(McpServerContribution::HostedApps { - config: Box::new(codex_apps_mcp_server_config( - &apps_server.chatgpt_base_url, - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - )), + config: Box::new(mock_apps_mcp_server_config(&apps_server.chatgpt_base_url)), protocol_mode: None, }), gate: Mutex::new(Some((reached_tx, release_rx))), diff --git a/codex-rs/core/tests/suite/mcp_auth_refresh.rs b/codex-rs/core/tests/suite/mcp_auth_refresh.rs index baaa61aa..7f1cad22 100644 --- a/codex-rs/core/tests/suite/mcp_auth_refresh.rs +++ b/codex-rs/core/tests/suite/mcp_auth_refresh.rs @@ -1,6 +1,7 @@ #![allow(clippy::unwrap_used)] use anyhow::Result; +use core_test_support::apps_test_server::mock_apps_mcp_server_config; use codex_config::McpServerTransportConfig; use codex_core::config::ConfigBuilder; use codex_core::config::Constrained; @@ -64,11 +65,7 @@ async fn hosted_plugin_runtime_ps_mcp_tool_calls_use_current_auth_manager_token( // Build the hosted-plugin config directly so the local test origin can // exercise the connection-manager auth path. Effective server resolution // correctly strips ChatGPT auth from untrusted localhost origins. - let mut hosted_plugin_runtime_config = codex_mcp::hosted_plugin_runtime_mcp_server_config( - &apps_server.chatgpt_base_url, - /*apps_mcp_product_sku*/ None, - /*originator*/ None, - ); + let mut hosted_plugin_runtime_config = mock_apps_mcp_server_config(&apps_server.chatgpt_base_url); let McpServerTransportConfig::StreamableHttp { bearer_token_env_var, .. @@ -78,7 +75,7 @@ async fn hosted_plugin_runtime_ps_mcp_tool_calls_use_current_auth_manager_token( }; // Keep the test on the AuthManager path even if the developer has the // debug bearer override in their environment. - *bearer_token_env_var = None; + bearer_token_env_var.take(); let mcp_servers = HashMap::from([( CODEX_APPS_MCP_SERVER_NAME.to_string(), EffectiveMcpServer::from_host_config(hosted_plugin_runtime_config), diff --git a/codex-rs/core/tests/suite/realtime_conversation.rs b/codex-rs/core/tests/suite/realtime_conversation.rs index 88384274..1f57dc0e 100644 --- a/codex-rs/core/tests/suite/realtime_conversation.rs +++ b/codex-rs/core/tests/suite/realtime_conversation.rs @@ -303,12 +303,13 @@ async fn conversation_start_audio_text_close_round_trip() -> Result<()> { let mut builder = test_codex().with_config({ let provider_base_url = format!("{}/v1", server.uri()); + let realtime_ws_base_url = format!("{}/v1", server.uri()); move |config| { - // Exercise the default Realtime endpoint without Responses prewarm - // connections competing for this server's scripted replies. + // aKode requires an explicit Realtime endpoint; keep Responses prewarm + // connections from competing for this server's scripted replies. config.model_provider.base_url = Some(provider_base_url); config.model_provider.supports_websockets = false; - config.experimental_realtime_ws_base_url = None; + config.experimental_realtime_ws_base_url = Some(realtime_ws_base_url); config.experimental_realtime_ws_model = Some("realtime-test-model".to_string()); config.realtime.version = RealtimeWsVersion::V1; } @@ -1740,8 +1741,10 @@ async fn conversation_webrtc_default_v1_rejects_explicit_v2_voice() -> Result<() skip_if_no_network!(Ok(())); let api_server = start_mock_server().await; - let mut builder = test_codex().with_config(|config| { + let realtime_base_url = api_server.uri(); + let mut builder = test_codex().with_config(move |config| { config.realtime.version = RealtimeWsVersion::V2; + config.experimental_realtime_ws_base_url = Some(realtime_base_url); }); let test = builder.build(&api_server).await?; @@ -2467,7 +2470,12 @@ async fn conversation_start_preflight_failure_emits_realtime_error_only() -> Res skip_if_no_network!(Ok(())); let server = start_websocket_server(vec![]).await; - let mut builder = test_codex().with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()); + let realtime_base_url = server.uri().to_string(); + let mut builder = test_codex() + .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) + .with_config(move |config| { + config.experimental_realtime_ws_base_url = Some(realtime_base_url); + }); let test = builder.build_with_websocket_server(&server).await?; test.codex @@ -3182,8 +3190,10 @@ async fn conversation_rejects_voice_for_wrong_realtime_version() -> Result<()> { skip_if_no_network!(Ok(())); let api_server = start_mock_server().await; - let mut builder = test_codex().with_config(|config| { + let realtime_base_url = api_server.uri(); + let mut builder = test_codex().with_config(move |config| { config.realtime.version = RealtimeWsVersion::V2; + config.experimental_realtime_ws_base_url = Some(realtime_base_url); }); let test = builder.build(&api_server).await?; diff --git a/codex-rs/core/tests/suite/realtime_initial_items.rs b/codex-rs/core/tests/suite/realtime_initial_items.rs index ae9cb4e7..cff3d548 100644 --- a/codex-rs/core/tests/suite/realtime_initial_items.rs +++ b/codex-rs/core/tests/suite/realtime_initial_items.rs @@ -178,7 +178,13 @@ async fn realtime_end_instructions_enforce_token_limit() -> Result<()> { async fn assert_start_error(params: ConversationStartParams, expected_error: &str) -> Result<()> { let api_server = start_mock_server().await; - let test = test_codex().build_with_auto_env(&api_server).await?; + let realtime_base_url = api_server.uri(); + let test = test_codex() + .with_config(move |config| { + config.experimental_realtime_ws_base_url = Some(realtime_base_url); + }) + .build_with_auto_env(&api_server) + .await?; test.codex .submit(Op::RealtimeConversationStart(params)) .await?; diff --git a/codex-rs/exec-server-cli/src/config.rs b/codex-rs/exec-server-cli/src/config.rs index c5125c41..e8b62136 100644 --- a/codex-rs/exec-server-cli/src/config.rs +++ b/codex-rs/exec-server-cli/src/config.rs @@ -2,17 +2,11 @@ use anyhow::Context; use codex_app_server::in_process::EmbeddedNetworkPolicy; -use codex_config::LoaderOverrides; use codex_core::config::ConfigBuilder; -use codex_core::config::ConfigLoadOptions; -use codex_core::config::bootstrap_auth_config; -use codex_core::config::find_codex_home; -use codex_core::config::load_config_toml_with_layer_stack; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::read_codex_access_token_from_env; use codex_protocol::auth::AuthMode; -use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_cli::CliConfigOverrides; use std::io::BufRead; use std::io::Read; diff --git a/codex-rs/ext/mcp/src/cloud_plugin_tests.rs b/codex-rs/ext/mcp/src/cloud_plugin_tests.rs index af96289c..050d1e16 100644 --- a/codex-rs/ext/mcp/src/cloud_plugin_tests.rs +++ b/codex-rs/ext/mcp/src/cloud_plugin_tests.rs @@ -7,38 +7,21 @@ use crate::PluginProviderFuture; use crate::PluginProviders; use crate::PluginsThreadState; use crate::install_plugin_providers; -use anyhow::Context; -use codex_config::test_support::CloudConfigBundleFixture; use codex_core_plugins::ExecutorPluginProvider; use codex_core_plugins::PluginCatalog; use codex_core_plugins::PluginCatalogEntry; use codex_core_plugins::PluginIdentity; use codex_exec_server::EnvironmentManager; -use codex_extension_api::ContextContributor; use codex_extension_api::ExtensionRegistryBuilder; use codex_extension_api::McpServerContributionContext; use codex_extension_api::McpServerContributor; -use codex_extension_api::SelectedPluginSnapshot; -use codex_extension_api::WorldStateContributionInput; -use codex_extension_api::WorldStateSectionContribution; use codex_protocol::capabilities::CapabilityRootLocation; use codex_protocol::capabilities::SelectedCapabilityRoot; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; use codex_utils_path_uri::PathUri; -use core_test_support::apps_test_server::AppsTestServer; -use core_test_support::apps_test_server::recorded_apps_tool_calls; -use core_test_support::responses; -use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_function_call_with_namespace; -use core_test_support::responses::ev_response_created; -use core_test_support::responses::mount_sse_sequence; -use core_test_support::responses::sse; -use core_test_support::test_codex::run_test_with_large_stack; -use core_test_support::test_codex::test_codex; use pretty_assertions::assert_eq; -use serde_json::json; use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::AtomicBool; @@ -357,40 +340,6 @@ struct CloudProvider { resume_discovery: Notify, } -type ObservedPackages = Vec<(String, Option)>; - -#[derive(Default)] -struct StepPackages(Mutex>); - -impl ContextContributor for StepPackages { - fn contribute_world_state<'a>( - &'a self, - input: WorldStateContributionInput<'a>, - ) -> ExtensionFuture<'a, Vec> { - Box::pin(async move { - *self - .0 - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = input - .thread_store - .get::() - .map(|snapshot| { - snapshot - .plugins - .iter() - .map(|plugin| { - ( - plugin.plugin_id.as_str().to_string(), - plugin.selected_root_id.clone(), - ) - }) - .collect() - }); - Vec::new() - }) - } -} - impl Default for CloudProvider { fn default() -> Self { Self { @@ -455,420 +404,3 @@ fn cloud_catalog() -> PluginCatalog { ..Default::default() } } - -fn app_tool(connector: &str, action: &str) -> serde_json::Value { - json!({ - "name": format!("{connector}_{action}"), - "description": format!("Run {action} in {connector}."), - "annotations": {"readOnlyHint": true}, - "inputSchema": {"type": "object", "properties": {}, "additionalProperties": false}, - "_meta": { - "connector_id": connector, - "connector_name": connector, - "_codex_apps": { - "resource_uri": format!("connector://{connector}/tools/{connector}_{action}"), - "contains_mcp_source": true, - "connector_id": connector, - }, - }, - }) -} - -#[test] -fn cloud_catalog_refreshes_per_turn_and_invalidates_on_auth_change() -> anyhow::Result<()> { - run_test_with_large_stack( - "cloud-plugin-lifecycle", - run_cloud_catalog_refresh_lifecycle, - ) -} - -async fn run_cloud_catalog_refresh_lifecycle() -> anyhow::Result<()> { - core_test_support::skip_if_no_network!(Ok(())); - - let server = responses::start_mock_server().await; - // Each account has a fixed inventory; only the auth switch changes the server's tools. - let apps_tools = Arc::new(Mutex::new(vec![app_tool("calendar", "list_events")])); - let apps_server = AppsTestServer::mount_with_tools(&server, apps_tools.clone()).await?; - let mut gmail_catalog = cloud_catalog(); - gmail_catalog.entries[0].id = PluginIdentity::Remote { - remote_plugin_id: "plugin_gmail".to_string(), - }; - gmail_catalog.entries[0].display_name = "Gmail Demo".to_string(); - gmail_catalog.entries[0].connector_ids = vec!["gmail".to_string()]; - let mut disabled_catalog = cloud_catalog(); - disabled_catalog.entries[0].enabled = false; - let mut partial_catalog = gmail_catalog.clone(); - partial_catalog.is_partial = true; - let partial_empty_catalog = PluginCatalog { - is_partial: true, - warnings: vec!["resource listing was truncated".to_string()], - ..Default::default() - }; - let provider = Arc::new(CloudProvider::default()); - let step_packages = Arc::new(StepPackages::default()); - let mut extensions = ExtensionRegistryBuilder::new(); - crate::install(&mut extensions); - extensions.prompt_contributor(step_packages.clone()); - install_plugin_providers( - &mut extensions, - PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new( - EnvironmentManager::default_for_tests(), - )))) - .with_cloud_provider(provider.clone()), - ); - let mut builder = test_codex() - .with_cloud_config_bundle( - CloudConfigBundleFixture::enterprise_config( - "[mcp_servers.codex_apps]\nurl = 'https://example.com/custom'", - ) - .add_enterprise_requirement("[mcp_servers]") - .into_loader(), - ) - .with_exec_server_url("none") - .with_extensions(Arc::new(extensions.build())) - .with_auth(codex_login::CodexAuth::from_external_chatgpt_tokens( - "header.e30.initial", - "account-a", - /*chatgpt_plan_type*/ None, - )?) - .with_model_info_override("gpt-5.5", |model| { - model.supports_search_tool = false; - }) - .with_config(move |config| { - config - .features - .enable(Feature::Plugins) - .expect("enable plugins in fixture"); - config - .features - .enable(Feature::Apps) - .expect("enable apps in fixture"); - config.chatgpt_base_url = apps_server.chatgpt_base_url; - }); - let test = builder.build_with_auto_env(&server).await?; - assert!(!test.config.mcp_servers.get()[codex_mcp::CODEX_APPS_MCP_SERVER_NAME].enabled); - let calendar = ("calendar", "list_events", "Cloud Demo"); - let gmail = ("gmail", "search_email", "Gmail Demo"); - for (turn, reply, expected_plugin, new_account, tool_call) in [ - ( - "initial-partial", - Ok(partial_catalog.clone()), - Some("plugin_gmail"), - None, - None, - ), - ( - "partial-replaces-partial", - Ok(PluginCatalog { - is_partial: true, - ..cloud_catalog() - }), - Some("plugin_remote"), - None, - Some(calendar), - ), - ( - "partial-empty-replaces-partial", - Ok(partial_empty_catalog.clone()), - None, - None, - None, - ), - ( - "empty", - Ok(PluginCatalog::default()), - None, - None, - Some(calendar), - ), - ( - "partial-after-complete-empty", - Ok(partial_catalog.clone()), - None, - None, - None, - ), - ( - "discovered", - Ok(cloud_catalog()), - Some("plugin_remote"), - None, - Some(calendar), - ), - ( - "partial-refresh", - Ok(partial_catalog.clone()), - Some("plugin_remote"), - None, - Some(calendar), - ), - ( - "partial-empty-refresh", - Ok(partial_empty_catalog), - None, - None, - None, - ), - ( - "same-account-failure", - Err("temporarily unavailable".to_string()), - None, - None, - None, - ), - ( - "complete-with-warning-disables-plugin", - Ok(PluginCatalog { - warnings: vec!["optional bundle hint ignored".to_string()], - ..disabled_catalog - }), - None, - None, - None, - ), - ( - "partial-after-disable", - Ok(partial_catalog.clone()), - None, - None, - None, - ), - ( - "re-enabled", - Ok(cloud_catalog()), - Some("plugin_remote"), - None, - None, - ), - ("removed", Ok(PluginCatalog::default()), None, None, None), - ( - "restored", - Ok(cloud_catalog()), - Some("plugin_remote"), - None, - None, - ), - ( - "auth-changed-failure", - Err("unavailable after auth changed".to_string()), - None, - Some("account-b"), - None, - ), - ( - "new-account-partial", - Ok(partial_catalog), - Some("plugin_gmail"), - None, - Some(gmail), - ), - ( - "new-account-discovered", - Ok(gmail_catalog), - Some("plugin_gmail"), - None, - Some(gmail), - ), - ( - "in-flight-auth-change", - Ok(cloud_catalog()), - None, - None, - None, - ), - ] { - let previous_discoveries = provider.calls.load(Ordering::SeqCst); - let retry_discovery = turn == "in-flight-auth-change"; - if let Some(account) = new_account { - // Do not manually refresh MCP: the auth transition must pick up this new inventory. - *apps_tools - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = - vec![app_tool("gmail", "search_email")]; - let resources = provider - .resources - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - .context("cloud provider resource client missing")?; - let previous_auth = - resources.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME); - codex_login::auth::login_with_chatgpt_auth_tokens( - test.codex_home_path(), - "header.e30.changed", - account, - /*chatgpt_plan_type*/ None, - )?; - test.thread_manager.auth_manager().reload().await; - tokio::time::timeout(std::time::Duration::from_secs(10), async { - loop { - if resources.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME) - != previous_auth - && test - .codex - .thread_extension_data() - .get::() - .is_some_and(|snapshot| snapshot.plugins.is_empty()) - { - break; - } - tokio::task::yield_now().await; - } - }) - .await?; - assert_eq!(provider.calls.load(Ordering::SeqCst), previous_discoveries); - } - if matches!( - turn, - "complete-with-warning-disables-plugin" | "new-account-partial" - ) { - // Reconnecting permits recovery before the thread's cooldown expires. - test.codex - .submit(codex_protocol::protocol::Op::RefreshMcpServers) - .await?; - } - provider.set_reply(reply); - let previous_calls = recorded_apps_tool_calls(&server).await.len(); - let call_id = format!("{turn}-call"); - let mut events = vec![ev_response_created("resp")]; - if let Some((connector, action, _)) = tool_call { - events.push(ev_function_call_with_namespace( - &call_id, - &format!("mcp__codex_apps__{connector}"), - &format!("_{action}"), - "{}", - )); - } - events.push(ev_completed("resp")); - let mut responses = vec![sse(events)]; - if tool_call.is_some() { - responses.push(sse(vec![ - ev_response_created("after-tool"), - ev_completed("after-tool"), - ])); - } - let response = mount_sse_sequence(&server, responses).await; - *step_packages - .0 - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = None; - if turn == "in-flight-auth-change" { - provider.pause_discovery.store(true, Ordering::SeqCst); - tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async { - tokio::try_join!( - test.submit_turn("What capabilities are available?"), - async { - provider.discovery_started.notified().await; - let resources = provider - .resources - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - .context("cloud provider resource client missing")?; - let previous_auth = resources - .auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME); - // Rotate credentials without replacing the captured runtime/client. - codex_login::auth::login_with_chatgpt_auth_tokens( - test.codex_home_path(), - "header.e30.rotated", - "account-b", - /*chatgpt_plan_type*/ None, - )?; - test.thread_manager.auth_manager().reload().await; - // Auth must be published while cloud discovery remains paused. - while resources - .auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME) - == previous_auth - { - tokio::task::yield_now().await; - } - provider.set_reply(Err("new-scope discovery failed".to_string())); - provider.resume_discovery.notify_one(); - anyhow::Ok(()) - } - ) - }) - .await??; - // Refresh under the new auth without retaining the old catalog. - let state = test - .codex - .thread_extension_data() - .get::() - .context("plugin state missing")?; - assert_eq!(state.cloud_catalog(), None); - assert_eq!( - state - .contributor_state() - .cloud_generation - .as_ref() - .and_then(|generation| generation.catalog.clone()), - None, - ); - } else { - test.submit_turn("What capabilities are available?").await?; - } - let requests = response.requests(); - let request = &requests[0]; - if let Some((connector, action, plugin_name)) = tool_call { - assert_eq!(requests.len(), 2); - let calls = recorded_apps_tool_calls(&server).await; - let output = requests[1].function_call_output(&call_id); - assert_eq!(calls.len(), previous_calls + 1, "turn {turn}: {output}"); - let call = calls.last().context("expected an Apps tool call")?; - assert_eq!( - call["params"]["name"], - json!(format!("{connector}_{action}")) - ); - assert_eq!(call["params"]["arguments"], json!({})); - let (other_namespace, other_tool) = if connector == "calendar" { - ("mcp__codex_apps__gmail", "_search_email") - } else { - ("mcp__codex_apps__calendar", "_list_events") - }; - assert!(request.tool_by_name(other_namespace, other_tool).is_none()); - let tool = request - .tool_by_name( - &format!("mcp__codex_apps__{connector}"), - &format!("_{action}"), - ) - .expect("the current account's tool should be advertised"); - assert_eq!( - tool["description"] - .as_str() - .context("tool description missing")? - .contains(plugin_name), - expected_plugin.is_some(), - "cloud discovery should attribute tools to the current account's plugin" - ); - // The server echoes this URI in its result; it must reach the next model step. - assert!( - output["output"] - .as_str() - .context("tool output missing")? - .contains(&format!( - "connector://{connector}/tools/{connector}_{action}" - )), - "turn {turn}: {output}" - ); - } - assert_eq!( - *step_packages - .0 - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner), - Some( - expected_plugin - .into_iter() - .map(|id| (id.to_owned(), None)) - .collect() - ), - "turn {turn}" - ); - assert_eq!( - provider.calls.load(Ordering::SeqCst), - previous_discoveries + 1 + if retry_discovery { requests.len() } else { 0 }, - "turn {turn}" - ); - } - Ok(()) -} diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 90eabde6..d1bda69b 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -33,7 +33,6 @@ codex-app-server-client = { workspace = true } codex-app-server-daemon = { workspace = true } codex-app-server-protocol = { workspace = true } codex-arg0 = { workspace = true } -codex-backend-client = { workspace = true } codex-install-context = { workspace = true } codex-config = { workspace = true } codex-context-fragments = { workspace = true } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 541062ce..9e3e7567 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -14,7 +14,6 @@ use crate::app_event::HistoryLookupResponse; use crate::app_event::PermissionProfileSelection; use crate::app_event::PluginLocation; use crate::app_event::PluginRemoteSectionError; -use crate::app_event::RateLimitRefreshOrigin; use crate::app_event::RunningTaskExitAction; use crate::app_event::ThreadTitleDestination; #[cfg(target_os = "windows")] @@ -24,7 +23,6 @@ use crate::app_server_session::AppServerBootstrap; use crate::app_server_session::AppServerSession; use crate::app_server_session::AppServerStartedThread; use crate::app_server_session::TurnPermissionsOverride; -use crate::app_server_session::app_server_rate_limit_snapshots; use crate::bottom_pane::AppLinkViewParams; use crate::bottom_pane::ApplyPatchApprovalRequest; use crate::bottom_pane::ApprovalRequest; @@ -96,7 +94,6 @@ use crate::workspace_command::WorkspaceCommandRunner; use codex_ansi_escape::ansi_escape_line; use codex_app_server_client::AppServerRequestHandle; use codex_app_server_client::TypedRequestError; -use codex_app_server_protocol::AddCreditsNudgeCreditType; use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::CodexErrorInfo as AppServerCodexErrorInfo; @@ -105,7 +102,6 @@ use codex_app_server_protocol::ConfigReadResponse; use codex_app_server_protocol::ConfigValueWriteParams; use codex_app_server_protocol::ConfigWriteResponse; use codex_app_server_protocol::FeedbackUploadParams; -use codex_app_server_protocol::GetAccountRateLimitsResponse; use codex_app_server_protocol::HooksListEntry; use codex_app_server_protocol::ListMcpServerStatusParams; use codex_app_server_protocol::ListMcpServerStatusResponse; @@ -125,7 +121,6 @@ use codex_app_server_protocol::PluginReadResponse; use codex_app_server_protocol::PluginUninstallParams; use codex_app_server_protocol::PluginUninstallResponse; use codex_app_server_protocol::SandboxMode as AppServerSandboxMode; -use codex_app_server_protocol::SendAddCreditsNudgeEmailParams; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::SkillErrorInfo; @@ -216,7 +211,6 @@ mod app_server_event_targets; mod app_server_events; pub(crate) mod app_server_requests; mod app_server_thread_ownership; -mod backend_banner_fallback; mod backend_events; pub(crate) mod backend_selection; pub(crate) mod backend_sessions; @@ -258,7 +252,6 @@ mod pets; mod platform_actions; mod plugin_mentions; pub(crate) mod provider; -mod rate_limit_refresh; mod realtime_delivery; mod realtime_settings; mod reasoning_replay; @@ -588,13 +581,11 @@ pub(crate) struct App { turn_tips: turn_tips::TurnTips, pub(crate) transcript_view: crate::transcript_view::TranscriptView, conversation_frame: owned_transcript::ConversationFrame, + #[cfg_attr(not(test), allow(dead_code))] last_rendered_history_tail: Option, - last_thread_usage_status_cell: Option, - pub(crate) pending_thread_usage_history_refresh: bool, // Alternate-screen overlays: transcript, diff, and analytics. pub(crate) overlay: Option, - pub(crate) retained_analytics: Option>, pub(crate) deferred_history_lines: Vec, has_emitted_history_lines: bool, transcript_reflow: TranscriptReflowState, @@ -703,8 +694,6 @@ pub(crate) struct App { startup_pending_protected_request: bool, /// Invalidates in-flight full rate-limit reads when a newer rolling hard stop arrives. account_email_request_id: Option, - rate_limit_hard_stop_generation: u64, - rate_limit_refresh_state: rate_limit_refresh::RateLimitRefreshState, pending_mcp_login_start: Option, // Latest accepted attempt per server; stale retry completions must not update the UI. active_mcp_login_ids: HashMap, @@ -1311,7 +1300,6 @@ impl App { owner.refresh_realtime_microphone_level(); } self.chat_widget.pre_draw_tick(); - self.refresh_agents_overview_usage(app_server, tui.frame_requester()); let rendered_area = self.render_chat_widget_frame(tui, screen_size)?; if tui.is_owned_screen() && self.transcript_view.history diff --git a/codex-rs/tui/src/app/agents_overview.rs b/codex-rs/tui/src/app/agents_overview.rs index 6ef50577..263562a3 100644 --- a/codex-rs/tui/src/app/agents_overview.rs +++ b/codex-rs/tui/src/app/agents_overview.rs @@ -48,8 +48,6 @@ pub(super) struct AgentsOverviewState { pub(super) unread: HashSet, pub(super) last_messages: HashMap, pub(super) usage: HashMap, - pub(super) pending_usage: Option<(ThreadId, Uuid)>, - pub(super) usage_disabled: bool, pub(super) activity: HashMap, pub(super) initialized: bool, pub(super) discovery: super::agents_overview_discovery::AgentsOverviewDiscovery, diff --git a/codex-rs/tui/src/app/agents_overview_details.rs b/codex-rs/tui/src/app/agents_overview_details.rs index 04aa6824..1130887c 100644 --- a/codex-rs/tui/src/app/agents_overview_details.rs +++ b/codex-rs/tui/src/app/agents_overview_details.rs @@ -233,12 +233,7 @@ impl App { lines, usage_lines: root_id .and_then(|id| self.agents_overview.usage.get(&id)) - .map(|usage| { - super::agents_overview_usage::usage_lines( - usage, - self.chat_widget.current_plan_type(), - ) - }) + .map(super::agents_overview_usage::usage_lines) .unwrap_or_default(), last_message, } diff --git a/codex-rs/tui/src/app/agents_overview_tests.rs b/codex-rs/tui/src/app/agents_overview_tests.rs index 114e685a..3626c76e 100644 --- a/codex-rs/tui/src/app/agents_overview_tests.rs +++ b/codex-rs/tui/src/app/agents_overview_tests.rs @@ -3018,9 +3018,6 @@ fn trust_fixture_folders(app: &mut App) { )); } -#[path = "agents_overview_usage_tests.rs"] -mod usage; - #[tokio::test] async fn overview_grouping_persists_across_config_reloads() -> Result<()> { let (mut app, mut events, _ops) = crate::app::tests::make_test_app_with_channels().await; diff --git a/codex-rs/tui/src/app/agents_overview_usage.rs b/codex-rs/tui/src/app/agents_overview_usage.rs new file mode 100644 index 00000000..5da0d4aa --- /dev/null +++ b/codex-rs/tui/src/app/agents_overview_usage.rs @@ -0,0 +1,22 @@ +//! Local token usage shown for the selected task in the agents dashboard. + +use crate::status::format_tokens_compact; +use codex_app_server_protocol::TokenUsageBreakdown; +use ratatui::style::Stylize; +use ratatui::text::Line; + +#[derive(Default)] +pub(super) struct AgentsOverviewUsage { + pub(super) tokens: Option, +} + +pub(super) fn usage_lines(usage: &AgentsOverviewUsage) -> Vec> { + let Some(tokens) = usage.tokens.as_ref() else { + return Vec::new(); + }; + let tokens = [ + format!("{} in", format_tokens_compact(tokens.input_tokens)), + format!("{} out", format_tokens_compact(tokens.output_tokens)), + ]; + vec![vec!["Tokens: ".dim(), tokens.join(" Β· ").into()].into()] +} diff --git a/codex-rs/tui/src/app/app_server_events.rs b/codex-rs/tui/src/app/app_server_events.rs index 3743d0a1..6ec4954e 100644 --- a/codex-rs/tui/src/app/app_server_events.rs +++ b/codex-rs/tui/src/app/app_server_events.rs @@ -9,7 +9,6 @@ use super::app_server_event_targets::server_request_thread_id; use super::app_server_requests::BufferedServerRequest; use crate::app_command::AppCommand; use crate::app_event::AppEvent; -use crate::app_event::RateLimitRefreshOrigin; #[cfg(any(target_os = "windows", test))] use crate::app_event::WindowsSandboxEnableMode; use crate::app_info::app_info_from_api; @@ -20,7 +19,6 @@ use codex_app_server_client::TypedRequestError; use codex_app_server_protocol::AuthMode; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::JSONRPCErrorError; -use codex_app_server_protocol::RateLimitReachedType; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequest; @@ -126,8 +124,6 @@ impl App { self.agents_overview.activity.clear(); self.agents_overview.last_messages.clear(); self.agents_overview.usage.clear(); - self.agents_overview.pending_usage = None; - self.agents_overview.usage_disabled = false; self.repaint_agents_overview(); self.refresh_agents_overview_threads(app_server_client); if let Some(primary_thread_id) = self.primary_thread_id @@ -378,47 +374,15 @@ impl App { } ServerNotification::AccountRateLimitsUpdated(notification) => { - let workspace_hard_stop = matches!( - notification.rate_limits.rate_limit_reached_type, - Some( - RateLimitReachedType::WorkspaceOwnerCreditsDepleted - | RateLimitReachedType::WorkspaceMemberCreditsDepleted - | RateLimitReachedType::WorkspaceOwnerUsageLimitReached - | RateLimitReachedType::WorkspaceMemberUsageLimitReached - ) - ) || notification.rate_limits.spend_control_reached - == Some(true); - if workspace_hard_stop { - self.rate_limit_hard_stop_generation = - self.rate_limit_hard_stop_generation.wrapping_add(1); - } self.chat_widget - .on_rolling_rate_limit_snapshot(notification.rate_limits.clone()); - if workspace_hard_stop && self.chat_widget.has_chatgpt_account() { - // Background inference may publish a hard stop without a foreground Error. - self.refresh_rate_limits(app_server_client, RateLimitRefreshOrigin::Recovery); - } + .on_rate_limit_snapshot(Some(notification.rate_limits.clone())); return; } ServerNotification::AccountUpdated(notification) => { - self.agents_overview.usage.clear(); - self.agents_overview.pending_usage = None; - self.agents_overview.usage_disabled = false; self.repaint_agents_overview(); self.chat_widget.invalidate_security_setup(); - if let Some(crate::pager_overlay::Overlay::Analytics(view)) = &mut self.overlay { - view.refresh(); - } - if let Some(view) = &mut self.retained_analytics { - view.cancel_loads(); - } - self.rate_limit_hard_stop_generation = - self.rate_limit_hard_stop_generation.wrapping_add(1); - self.rate_limit_refresh_state.invalidate_recovery(); // Deferred terminal writes must never carry the previous account's billing into // the newly authenticated identity, even when both accounts share one thread. - self.last_thread_usage_status_cell = None; - self.pending_thread_usage_history_refresh = false; let has_codex_backend_auth = matches!( notification.auth_mode, Some( diff --git a/codex-rs/tui/src/app/backend_selection.rs b/codex-rs/tui/src/app/backend_selection.rs index e33c2a14..4e72b34e 100644 --- a/codex-rs/tui/src/app/backend_selection.rs +++ b/codex-rs/tui/src/app/backend_selection.rs @@ -387,8 +387,6 @@ impl App { self.store_active_thread_receiver().await; self.clear_active_thread().await; self.agents_overview.search_matches.clear(); - self.agents_overview.pending_usage = None; - self.agents_overview.usage_disabled = false; self.app_event_tx = AppEventSender::new(self.app_event_tx.app_event_tx.clone()); self.app_server_target = target; self.reconnect = Default::default(); @@ -396,8 +394,6 @@ impl App { state.connection_notice = None; state.restart_history_search(); } - self.rate_limit_hard_stop_generation = self.rate_limit_hard_stop_generation.wrapping_add(1); - self.rate_limit_refresh_state.invalidate_recovery(); self.account_email_request_id = None; self.file_search.on_user_query(String::new()); self.bind_backend_workspace(destination, cwd); diff --git a/codex-rs/tui/src/app/background_requests.rs b/codex-rs/tui/src/app/background_requests.rs index 44577744..1b39ab9f 100644 --- a/codex-rs/tui/src/app/background_requests.rs +++ b/codex-rs/tui/src/app/background_requests.rs @@ -9,15 +9,9 @@ use super::plugin_mentions::fetch_plugin_mentions; use super::*; use crate::app_event::ConnectorsSnapshot; use crate::app_info::app_info_from_api; -use crate::chatwidget::ThreadUsageOutcome; use crate::config_update::format_config_error; use codex_app_server_protocol::AppsListParams; use codex_app_server_protocol::AppsListResponse; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditParams; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse; -use codex_app_server_protocol::GetAccountRateLimitsParams; -use codex_app_server_protocol::GetAccountTokenUsageParams; -use codex_app_server_protocol::GetAccountTokenUsageResponse; use codex_app_server_protocol::MarketplaceAddParams; use codex_app_server_protocol::MarketplaceAddResponse; use codex_app_server_protocol::MarketplaceRemoveParams; @@ -33,13 +27,6 @@ use crate::hooks_rpc::write_hook_trust; use crate::hooks_rpc::write_hook_trusts; use codex_utils_absolute_path::AbsolutePathBuf; -pub(super) const THREAD_USAGE_FETCH_TIMEOUT: std::time::Duration = - std::time::Duration::from_secs(/*secs*/ 65); -const RATE_LIMIT_RESET_REQUEST_TIMEOUT: std::time::Duration = - std::time::Duration::from_secs(/*secs*/ 15); -const WORKSPACE_HEADLINE_FETCH_TIMEOUT: std::time::Duration = - std::time::Duration::from_millis(/*millis*/ 2000); - impl App { pub(super) fn start_mcp_login( &self, @@ -99,153 +86,6 @@ impl App { }) } - /// Spawns a background task to fetch account rate limits and deliver the - /// result as a `RateLimitsLoaded` event. - /// - /// Recovery requests are coalesced and bounded by the reset-request timeout. The origin - /// also identifies command-specific completion work, such as finalizing a `/status` card, - /// without confusing sparse inference notifications with authoritative usage responses. - pub(crate) fn refresh_rate_limits( - &mut self, - app_server: &AppServerSession, - origin: RateLimitRefreshOrigin, - ) { - if matches!( - origin, - RateLimitRefreshOrigin::Recovery | RateLimitRefreshOrigin::ResetConsume { .. } - ) { - self.chat_widget.invalidate_ordinary_usage_recovery(); - self.chat_widget.hold_rate_limit_recovery(); - } - let Some((request_id, hard_stop_generation)) = self - .rate_limit_refresh_state - .start(origin, &mut self.rate_limit_hard_stop_generation) - else { - return; - }; - self.chat_widget.start_usage_notice_read(request_id); - let request_handle = app_server.request_handle(); - let app_event_tx = self.app_event_tx.clone(); - tokio::spawn(async move { - let request = fetch_account_rate_limits(request_handle, origin); - let result = match origin { - RateLimitRefreshOrigin::Recovery - | RateLimitRefreshOrigin::Periodic - | RateLimitRefreshOrigin::ResetConsume { .. } - | RateLimitRefreshOrigin::ResetPicker { .. } => { - tokio::time::timeout(RATE_LIMIT_RESET_REQUEST_TIMEOUT, request) - .await - .map_err(|_| "account/rateLimits/read timed out in TUI".to_string()) - .and_then(|result| result.map_err(|err| err.to_string())) - } - RateLimitRefreshOrigin::StartupPrefetch { .. } - | RateLimitRefreshOrigin::StatusCommand { .. } - | RateLimitRefreshOrigin::UsageMenu { .. } => { - request.await.map_err(|err| err.to_string()) - } - }; - app_event_tx.send(AppEvent::RateLimitsLoaded { - request_id, - origin, - hard_stop_generation, - result, - }); - }); - } - - pub(super) fn refresh_thread_usage( - &mut self, - app_server: &AppServerSession, - thread_id: ThreadId, - request_id: u64, - ) { - let request_handle = app_server.request_handle(); - let app_event_tx = self.app_event_tx.clone(); - tokio::spawn(async move { - let result = tokio::time::timeout( - THREAD_USAGE_FETCH_TIMEOUT, - fetch_thread_usage(request_handle, thread_id), - ) - .await - .map_err(|_| "thread usage request timed out in TUI".to_string()) - .and_then(|result| result.map_err(|err| err.to_string())); - app_event_tx.send(AppEvent::ThreadUsageLoaded { - thread_id, - request_id, - result, - }); - }); - } - - pub(super) fn consume_rate_limit_reset_credit( - &mut self, - app_server: &AppServerSession, - request_id: u64, - idempotency_key: String, - credit_id: Option, - ) { - 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( - RATE_LIMIT_RESET_REQUEST_TIMEOUT, - consume_rate_limit_reset_credit_request( - request_handle, - idempotency_key.clone(), - credit_id.clone(), - ), - ) - .await - .map_err(|_| "account/rateLimitResetCredit/consume timed out in TUI".to_string()) - .and_then(|result| result.map_err(|err| err.to_string())); - app_event_tx.send(AppEvent::RateLimitResetCreditConsumed { - request_id, - idempotency_key, - credit_id, - result, - }); - }); - } - - pub(super) fn refresh_status_line_workspace_headline( - &mut self, - app_server: &AppServerSession, - request_id: u64, - ) { - let request_handle = app_server.request_handle(); - let app_event_tx = self.app_event_tx.clone(); - tokio::spawn(async move { - let result = tokio::time::timeout( - WORKSPACE_HEADLINE_FETCH_TIMEOUT, - fetch_workspace_messages(request_handle), - ) - .await - .map_err(|_| "account/workspaceMessages/read timed out in TUI".to_string()) - .and_then(|result| { - result - .map(crate::workspace_messages::workspace_headline_from_response) - .map_err(|err| err.to_string()) - }); - app_event_tx.send(AppEvent::StatusLineWorkspaceHeadlineUpdated { request_id, result }); - }); - } - - pub(super) fn send_add_credits_nudge_email( - &mut self, - app_server: &AppServerSession, - request_id: Uuid, - credit_type: AddCreditsNudgeCreditType, - ) { - let request_handle = app_server.request_handle(); - let app_event_tx = self.app_event_tx.clone(); - tokio::spawn(async move { - let result = send_add_credits_nudge_email(request_handle, credit_type) - .await - .map_err(|err| err.to_string()); - app_event_tx.send(AppEvent::AddCreditsNudgeEmailFinished { request_id, result }); - }); - } - /// Starts the initial skills refresh without delaying the first interactive frame. /// /// Startup only needs skill metadata to populate skill mentions and the skills UI; the prompt can be @@ -830,105 +670,6 @@ pub(super) async fn fetch_all_mcp_server_statuses( Ok(statuses) } -pub(super) async fn fetch_account_rate_limits( - request_handle: AppServerRequestHandle, - origin: RateLimitRefreshOrigin, -) -> Result { - let request_id = RequestId::String(format!("account-rate-limits-{}", Uuid::new_v4())); - let result = request_handle - .request_typed(ClientRequest::GetAccountRateLimits { - request_id: request_id.clone(), - params: Some(GetAccountRateLimitsParams { - supports_luna_reserve: true, - exclude_reset_credit_details: origin == RateLimitRefreshOrigin::Periodic, - }), - }) - .await; - // Older remote app servers accept only null params. Keep their usage reads working - // without opting them into exposure or pretending that they support the new capability. - if matches!( - &result, - Err(codex_app_server_client::TypedRequestError::Server { source, .. }) - if matches!(source.code, -32600 | -32602) - ) { - return request_handle - .request_typed(ClientRequest::GetAccountRateLimits { - request_id, - params: None, - }) - .await - .wrap_err("account/rateLimits/read failed in TUI"); - } - result.wrap_err("account/rateLimits/read failed in TUI") -} - -pub(super) async fn fetch_thread_usage( - request_handle: AppServerRequestHandle, - thread_id: ThreadId, -) -> Result { - let request_id = RequestId::String(format!("thread-usage-{}", Uuid::new_v4())); - let response: GetAccountTokenUsageResponse = request_handle - .request_typed(ClientRequest::GetAccountTokenUsage { - request_id, - params: Some(GetAccountTokenUsageParams { - thread_id: Some(thread_id.to_string()), - }), - }) - .await - .wrap_err("account/usage/read failed for thread usage in TUI")?; - Ok(response - .thread_usage - .map(ThreadUsageOutcome::Available) - .unwrap_or(ThreadUsageOutcome::Disabled)) -} - -pub(super) async fn consume_rate_limit_reset_credit_request( - request_handle: AppServerRequestHandle, - idempotency_key: String, - credit_id: Option, -) -> Result { - let request_id = RequestId::String(format!("consume-rate-limit-reset-{}", Uuid::new_v4())); - request_handle - .request_typed(ClientRequest::ConsumeAccountRateLimitResetCredit { - request_id, - params: ConsumeAccountRateLimitResetCreditParams { - idempotency_key, - credit_id, - }, - }) - .await - .wrap_err("account/rateLimitResetCredit/consume failed in TUI") -} - -pub(super) async fn fetch_workspace_messages( - request_handle: AppServerRequestHandle, -) -> Result { - let request_id = RequestId::String(format!("workspace-messages-{}", Uuid::new_v4())); - request_handle - .request_typed(ClientRequest::GetWorkspaceMessages { - request_id, - params: None, - }) - .await - .wrap_err("account/workspaceMessages/read failed in TUI") -} - -pub(super) async fn send_add_credits_nudge_email( - request_handle: AppServerRequestHandle, - credit_type: AddCreditsNudgeCreditType, -) -> Result { - let request_id = RequestId::String(format!("add-credits-nudge-{}", Uuid::new_v4())); - let response: codex_app_server_protocol::SendAddCreditsNudgeEmailResponse = request_handle - .request_typed(ClientRequest::SendAddCreditsNudgeEmail { - request_id, - params: SendAddCreditsNudgeEmailParams { credit_type }, - }) - .await - .wrap_err("account/sendAddCreditsNudgeEmail failed in TUI")?; - - Ok(response.status) -} - pub(super) async fn fetch_skills_list( request_handle: AppServerRequestHandle, request_id: RequestId, @@ -1365,103 +1106,11 @@ pub(super) fn mcp_inventory_maps_from_statuses(statuses: Vec) - mod tests { use super::*; use crate::app::test_support::make_test_app; - use app_test_support::ChatGptAuthFixture; - use app_test_support::write_chatgpt_auth; use codex_app_server_protocol::PluginMarketplaceEntry; - use codex_app_server_protocol::ThreadUsage; - use codex_config::types::AuthCredentialsStoreMode; use codex_protocol::mcp::Tool; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; - #[tokio::test] - async fn fetch_thread_usage_uses_app_server_auth_after_persisted_account_changes() { - let mut app = make_test_app().await; - let server = wiremock::MockServer::start().await; - let thread_id = ThreadId::new(); - app.config.chatgpt_base_url = server.uri(); - app.cli_kv_overrides = vec![( - "chatgpt_base_url".to_string(), - toml::Value::String(server.uri()), - )]; - app.config.cli_auth_credentials_store_mode = AuthCredentialsStoreMode::File; - wiremock::Mock::given(wiremock::matchers::method("GET")) - .and(wiremock::matchers::path("/api/codex/config/bundle")) - .respond_with(wiremock::ResponseTemplate::new(/*s*/ 200).set_body_string("{}")) - .mount(&server) - .await; - std::fs::write( - app.config.codex_home.join("config.toml"), - format!("chatgpt_base_url = {:?}\n", server.uri()), - ) - .expect("persist endpoint for account config reloads"); - write_chatgpt_auth( - app.config.codex_home.as_path(), - ChatGptAuthFixture::new("chatgpt-token").account_id("account-123"), - AuthCredentialsStoreMode::File, - ) - .expect("write ChatGPT authentication"); - let app_server = crate::start_app_server_for_picker( - crate::backend_id::BackendId::new(), - &app.config, - &crate::AppServerTarget::Embedded, - app.cli_kv_overrides.clone(), - app.loader_overrides.clone(), - /*state_db*/ None, - app.environment_manager.clone(), - ) - .await - .expect("start authenticated embedded app server"); - write_chatgpt_auth( - app.config.codex_home.as_path(), - ChatGptAuthFixture::new("different-token").account_id("different-account"), - AuthCredentialsStoreMode::File, - ) - .expect("replace persisted ChatGPT authentication"); - - wiremock::Mock::given(wiremock::matchers::method("POST")) - .and(wiremock::matchers::path( - "/api/codex/usage/thread_usage/query", - )) - .and(wiremock::matchers::header( - "authorization", - "Bearer chatgpt-token", - )) - .and(wiremock::matchers::header( - "chatgpt-account-id", - "account-123", - )) - .and(wiremock::matchers::body_json(serde_json::json!({ - "thread_ids": [thread_id.to_string()] - }))) - .respond_with(wiremock::ResponseTemplate::new(/*s*/ 200).set_body_json( - serde_json::json!({ - "threads": [{ - "thread_id": thread_id.to_string(), - "estimated_usage_credits_micros": 0, - "estimated_usage_usd_micros": 0, - "native_usage_usd_micros": 750_000 - }] - }), - )) - .expect(/*r*/ 1) - .mount(&server) - .await; - - assert_eq!( - fetch_thread_usage(app_server.request_handle(), thread_id) - .await - .expect("read thread usage through the authenticated app server"), - ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: Some(750_000), - thread_id: thread_id.to_string(), - estimated_usage_credits_micros: 0, - estimated_usage_usd_micros: Some(0), - groups: Vec::new(), - }) - ); - } - fn test_absolute_path(path: &str) -> AbsolutePathBuf { AbsolutePathBuf::try_from(PathBuf::from(path)).expect("absolute test path") } diff --git a/codex-rs/tui/src/app/composer_hints_tests.rs b/codex-rs/tui/src/app/composer_hints_tests.rs index 8c5ff521..9e477b4d 100644 --- a/codex-rs/tui/src/app/composer_hints_tests.rs +++ b/codex-rs/tui/src/app/composer_hints_tests.rs @@ -158,22 +158,10 @@ async fn usage_notice_yields_to_interactions_and_blocking_banners() { app.chat_widget.on_rate_limit_snapshot(Some(update)); assert_eq!(app.chat_widget.usage_notice(/*width*/ 80), None); } + app.chat_widget.on_rate_limit_snapshot(/*snapshot*/ None); app.chat_widget .on_rate_limit_snapshot(Some(quota(/*used_percent*/ 92))); assert_eq!(app.chat_widget.usage_notice(/*width*/ 78), notice_line); - app.chat_widget.update_backend_banner( - &serde_json::from_value(serde_json::json!({ - "rateLimits": quota(/*used_percent*/ 92), - "rateLimitUpsell": { - "banner_type": "selected_model_limit", "title": "Usage limit reached", - "description": "Choose another model.", "ctas": [], - }, - })) - .unwrap(), - ); - assert_eq!(app.chat_widget.usage_notice(/*width*/ 80), None); - app.chat_widget.clear_backend_banner(); - assert_eq!(app.chat_widget.usage_notice(/*width*/ 78), notice_line); } #[tokio::test] diff --git a/codex-rs/tui/src/app/empty_state_animation_tests.rs b/codex-rs/tui/src/app/empty_state_animation_tests.rs index a1a9a66c..dd82f43d 100644 --- a/codex-rs/tui/src/app/empty_state_animation_tests.rs +++ b/codex-rs/tui/src/app/empty_state_animation_tests.rs @@ -137,24 +137,6 @@ async fn non_startup_history_dismisses_logo_until_a_new_thread() -> Result<()> { draw(&mut app, &mut tui, size)?; assert!(has_blossom(&tui)); - crate::chatwidget::tests::set_chatgpt_auth(&mut app.chat_widget); - let request = app.chat_widget.start_rate_limit_reset_startup_check(); - assert!(app.chat_widget.finish_rate_limit_reset_hint_refresh( - request, - Vec::new(), - Ok(codex_app_server_protocol::RateLimitResetCreditsSummary { - available_count: 1, - credits: None, - }), - )); - // The same startup notice stays eligible both pending and committed to history. - assert!(app.chat_widget.empty_state_composer().is_some()); - draw(&mut app, &mut tui, size)?; - assert!(has_blossom(&tui)); - app.insert_pending_usage_output_if_ready(&mut tui); - draw(&mut app, &mut tui, size)?; - assert!(has_blossom(&tui)); - // Even invisible non-startup content ends eligibility before a frame or clear can erase it. app.insert_history_cell( &mut tui, diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 7c11ae71..f94cd8a1 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -3,8 +3,6 @@ //! This module contains the exhaustive `AppEvent` dispatcher and exit-mode handling. Large domain //! actions are delegated to focused app submodules so the central match remains the routing layer. -use super::rate_limit_refresh::RateLimitReadStatus; -use super::rate_limit_refresh::RateLimitRefreshOutcome; use super::resize_reflow::trailing_run_start; use super::session_lifecycle::ThreadAttachPresentation; use super::*; @@ -951,8 +949,6 @@ impl App { self.scrollback_has_older_history = app_server.has_older_history(thread_id); self.deferred_history_lines.clear(); self.last_rendered_history_tail = None; - self.last_thread_usage_status_cell = None; - self.pending_thread_usage_history_refresh = false; self.backtrack_render_pending = !tui.is_owned_screen(); self.chat_widget.set_queue_autosend_suppressed(/*suppressed*/ false); self.chat_widget.emit_prompt_edit_thread_event(); @@ -1114,7 +1110,6 @@ impl App { deferred_history_cell, )?; self.chat_widget.note_stream_consolidation_completed(); - self.insert_pending_usage_output_after_stream_shutdown(tui); } AppEvent::CorrectFlushedAgentMessage { item, cell } => { let belongs_to_item = |cell: &Arc| { @@ -1171,7 +1166,6 @@ impl App { self.maybe_finish_stream_reflow(tui)?; } self.chat_widget.note_stream_consolidation_completed(); - self.insert_pending_usage_output_after_stream_shutdown(tui); } AppEvent::StartCommitAnimation => { self.commit_animation.get_or_insert_with(|| { @@ -1327,7 +1321,7 @@ impl App { }); } } - AppEvent::CodexOp(mut op) => { + AppEvent::CodexOp(op) => { if let AppCommand::OverrideTurnContext { cwd, approval_policy, @@ -1345,15 +1339,6 @@ impl App { { return Ok(AppRunControl::Continue); } - if self.active_thread_id == self.chat_widget.thread_id() { - if matches!(&op, AppCommand::UserTurn { .. }) - && self.chat_widget.defer_pending_turn_for_luna_reserve() - { - return Ok(AppRunControl::Continue); - } - self.chat_widget - .apply_reserve_fallback_to_pending_turn(&mut op); - } let is_user_turn = matches!(&op, AppCommand::UserTurn { .. }); let is_realtime_stop = matches!(&op, AppCommand::RealtimeConversationStop { .. }); let realtime_stop_thread_id = match &op { @@ -2047,20 +2032,6 @@ impl App { self.chat_widget.on_task_search_result(&query, matches); } } - AppEvent::RefreshRateLimits { origin } => { - self.refresh_rate_limits(app_server, origin); - } - AppEvent::ApplyBackendBannerFallback { thread_id } => { - if self.active_thread_id == Some(thread_id) - && self.chat_widget.thread_id() == Some(thread_id) - { - self.apply_backend_banner_fallback(app_server).await; - if !self.rate_limit_refresh_state.has_pending_recovery() { - self.chat_widget.finish_rate_limit_recovery(); - } - self.refresh_rate_limits(app_server, RateLimitRefreshOrigin::Periodic); - } - } AppEvent::RestoreBackgroundTerminals(thread_id) => { if self.chat_widget.thread_id() == Some(thread_id) { let request_id = self.chat_widget.begin_background_terminal_restore(); @@ -2075,15 +2046,6 @@ impl App { AppEvent::BackgroundTerminalsLoaded { request_id, terminals } => { self.chat_widget.restore_background_terminals(request_id, terminals); } - AppEvent::RefreshThreadUsage { - thread_id, - request_id, - } => { - self.refresh_thread_usage(app_server, thread_id, request_id); - } - AppEvent::RefreshStatusLineWorkspaceHeadline { request_id } => { - self.refresh_status_line_workspace_headline(app_server, request_id); - } AppEvent::OpenThreadGoalMenu { thread_id } => { self.open_thread_goal_menu(app_server, thread_id).await; } @@ -2105,268 +2067,6 @@ impl App { AppEvent::ClearThreadGoal { thread_id } => { self.clear_thread_goal(app_server, thread_id).await; } - AppEvent::SendAddCreditsNudgeEmail { credit_type } => { - if let Some(request_id) = self - .chat_widget - .start_add_credits_nudge_email_request(credit_type) - { - self.send_add_credits_nudge_email(app_server, request_id, credit_type); - } - } - AppEvent::AddCreditsNudgeEmailFinished { request_id, result } => { - self.chat_widget - .finish_add_credits_nudge_email_request(request_id, result); - } - AppEvent::RateLimitsLoaded { - request_id, - origin, - hard_stop_generation, - result, - } => { - let accepted = match self.rate_limit_refresh_state.finish( - request_id, - hard_stop_generation, - self.rate_limit_hard_stop_generation, - if result.is_ok() { - RateLimitReadStatus::Succeeded - } else { - RateLimitReadStatus::Failed - }, - ) { - RateLimitRefreshOutcome::Apply => true, - RateLimitRefreshOutcome::Ignore => false, - RateLimitRefreshOutcome::RefreshRecovery => { - // Start in this account's event turn; a queued refresh could cross an account change. - self.refresh_rate_limits(app_server, RateLimitRefreshOrigin::Recovery); - false - } - }; - match result { - Ok(response) => { - let rate_limit_reset_credits = response.rate_limit_reset_credits.clone(); - let snapshots = if accepted - { - self.chat_widget.apply_usage_notice_read(request_id); - self.chat_widget.update_backend_banner(&response); - self.apply_backend_banner_fallback(app_server).await; - app_server_rate_limit_snapshots(response) - } else { - Vec::new() - }; - match origin { - RateLimitRefreshOrigin::Recovery | RateLimitRefreshOrigin::Periodic => { - for snapshot in snapshots { - self.chat_widget.on_rate_limit_snapshot(Some(snapshot)); - } - } - RateLimitRefreshOrigin::StartupPrefetch { - reset_hint_request_id, - } => { - if self.chat_widget.finish_rate_limit_reset_hint_refresh( - reset_hint_request_id, - snapshots, - rate_limit_reset_credits.ok_or_else(|| { - "account/rateLimits/read response did not include rateLimitResetCredits" - .to_string() - }), - ) { - self.insert_pending_usage_output_if_ready(tui); - } - tui.frame_requester().schedule_frame(); - } - RateLimitRefreshOrigin::ResetConsume { request_id } => { - self.chat_widget.finish_post_consume_reset_credits_refresh( - request_id, - snapshots, - rate_limit_reset_credits.ok_or_else(|| { - "account/rateLimits/read response did not include rateLimitResetCredits" - .to_string() - }), - ); - tui.frame_requester().schedule_frame(); - } - RateLimitRefreshOrigin::StatusCommand { request_id } => { - self.chat_widget - .finish_status_rate_limit_refresh(request_id, snapshots); - } - RateLimitRefreshOrigin::UsageMenu { request_id } => { - self.chat_widget.finish_usage_menu_rate_limit_refresh( - request_id, - snapshots, - rate_limit_reset_credits.ok_or_else(|| { - "account/rateLimits/read response did not include rateLimitResetCredits" - .to_string() - }), - ); - } - RateLimitRefreshOrigin::ResetPicker { request_id } => { - self.chat_widget.finish_rate_limit_reset_credits_refresh( - request_id, - snapshots, - rate_limit_reset_credits.ok_or_else(|| { - "account/rateLimits/read response did not include rateLimitResetCredits" - .to_string() - }), - ); - } - } - } - Err(err) => { - // A failed read is not authoritative recovery. Keep the last valid banner. - tracing::warn!("account/rateLimits/read failed during TUI refresh: {err}"); - match origin { - RateLimitRefreshOrigin::Recovery | RateLimitRefreshOrigin::Periodic => { - // Re-evaluate snapshot age even when the backend cannot refresh it. - // This updates display freshness without authorizing model recovery. - self.chat_widget.refresh_status_surfaces(); - }, - RateLimitRefreshOrigin::StartupPrefetch { - reset_hint_request_id, - } => { - self.chat_widget.finish_rate_limit_reset_hint_refresh( - reset_hint_request_id, - Vec::new(), - Err(err), - ); - } - RateLimitRefreshOrigin::ResetConsume { request_id } => { - self.chat_widget.finish_post_consume_reset_credits_refresh( - request_id, - Vec::new(), - Err(err), - ); - } - RateLimitRefreshOrigin::StatusCommand { request_id } => { - self.chat_widget - .finish_status_rate_limit_refresh(request_id, Vec::new()); - } - RateLimitRefreshOrigin::UsageMenu { request_id } => { - self.chat_widget.finish_usage_menu_rate_limit_refresh( - request_id, - Vec::new(), - Err(err), - ); - } - RateLimitRefreshOrigin::ResetPicker { request_id } => { - self.chat_widget.finish_rate_limit_reset_credits_refresh( - request_id, - Vec::new(), - Err(err), - ); - } - } - } - } - if (accepted || matches!( - origin, - RateLimitRefreshOrigin::Recovery | RateLimitRefreshOrigin::ResetConsume { .. } - )) && !self.rate_limit_refresh_state.has_pending_recovery() - { - self.chat_widget.finish_rate_limit_recovery(); - } - }, - AppEvent::OpenAnalytics { view: summary_view } => { - tui.enter_alt_screen()?; - let mut view = self.retained_analytics.take().unwrap_or_else(|| { - Box::new(crate::analytics::AnalyticsView::new(self.keymap.list.clone())) - }); - view.keymap = self.keymap.list.clone(); - if summary_view.is_some() { - view.select_summary(summary_view); - } - view.open( - app_server.request_handle(), - tui.frame_requester(), - self.model_catalog.try_list_models()?, - std::sync::Arc::new(self.config.clone()), - ); - self.overlay = Some(Overlay::Analytics(view)); - tui.frame_requester().schedule_frame(); - } - AppEvent::OpenRateLimitResetCredits => { - let request_id = self.chat_widget.show_rate_limit_reset_loading_popup(); - self.refresh_rate_limits( - app_server, - RateLimitRefreshOrigin::ResetPicker { request_id }, - ); - } - AppEvent::OpenRateLimitResetConfirmation { - picker_request_id, - confirmation_gate, - credit_id, - reset_title, - reset_detail, - reset_description, - } => { - self.chat_widget.show_rate_limit_reset_confirmation( - picker_request_id, - confirmation_gate, - credit_id, - reset_title, - reset_detail, - reset_description, - ); - } - AppEvent::ConsumeRateLimitResetCredit { - idempotency_key, - credit_id, - } => { - if let Some(request_id) = self - .chat_widget - .start_rate_limit_reset_consumption(&idempotency_key) - { - self.consume_rate_limit_reset_credit( - app_server, - request_id, - idempotency_key, - credit_id, - ); - } - } - AppEvent::RateLimitResetCreditConsumed { - request_id, - idempotency_key, - credit_id, - result, - } => { - if let Err(err) = &result { - tracing::warn!( - "account/rateLimitResetCredit/consume failed during TUI request: {err}" - ); - } - if self.chat_widget.finish_rate_limit_reset_consume( - request_id, - idempotency_key, - credit_id, - result, - ) { - // Reads started before redemption must not restore the pre-reset banner. - self.rate_limit_hard_stop_generation = - self.rate_limit_hard_stop_generation.wrapping_add(1); - self.rate_limit_refresh_state.invalidate_recovery(); - self.chat_widget.clear_backend_banner(); - self.refresh_rate_limits( - app_server, - RateLimitRefreshOrigin::ResetConsume { request_id }, - ); - } - } - AppEvent::ThreadUsageLoaded { - thread_id, - request_id, - result, - } => { - self.finish_thread_usage_refresh(tui, thread_id, request_id, result)?; - } - AppEvent::AgentsOverviewUsageLoaded { thread_id, request_id, result } => { - self.finish_agents_overview_usage(thread_id, request_id, result); - } - AppEvent::CommitPendingUsageOutput => { - self.insert_pending_usage_output_if_ready(tui); - } - AppEvent::CommitPendingUsageOutputAfterStreamShutdown => { - self.insert_pending_usage_output_after_stream_shutdown(tui); - } AppEvent::ConnectorsLoaded { thread_id, cwd, @@ -2400,10 +2100,6 @@ impl App { self.sync_active_thread_reasoning_setting(app_server, effort) .await; } - AppEvent::UpdateLunaReserveReasoning { thread_id, effort } => { - self.update_luna_reserve_reasoning(app_server, thread_id, effort) - .await; - } AppEvent::UpdateModel(model) => { if self .active_thread_model_setting_update_params(model.clone()) @@ -3717,14 +3413,6 @@ impl App { self.chat_widget.set_status_line_git_summary(cwd, summary); self.refresh_status_line(); } - AppEvent::StatusLineWorkspaceHeadlineUpdated { request_id, result } => { - if self - .chat_widget - .set_status_line_workspace_headline(request_id, result) - { - tui.frame_requester().schedule_frame(); - } - } AppEvent::StatusLineSetupCancelled => { self.chat_widget.cancel_status_line_setup(); self.chat_widget.refresh_config_panel(/*notice*/ None); diff --git a/codex-rs/tui/src/app/history_ui.rs b/codex-rs/tui/src/app/history_ui.rs index ac38f111..16814772 100644 --- a/codex-rs/tui/src/app/history_ui.rs +++ b/codex-rs/tui/src/app/history_ui.rs @@ -6,18 +6,12 @@ use super::*; use crate::terminal_hyperlinks::HyperlinkLine; -use std::sync::Weak; const DESKTOP_THREAD_OPENED_MESSAGE: &str = "Opened this session in the Desktop app."; +/// Lines of the most recently committed history cell, kept so reflow and restore can be verified. pub(super) struct RenderedHistoryTail { - pub(super) cell: Weak, - pub(super) lines: Vec, -} - -pub(super) struct ThreadUsageStatusHistory { - thread_id: ThreadId, - pub(super) cell: Weak, + #[cfg_attr(not(test), allow(dead_code))] pub(super) lines: Vec, } @@ -78,7 +72,6 @@ impl App { self.render_inserted_history_cell(tui, &cell, deferred); // A committed cell can unblock a settled /usage card that was waiting // behind a transient active cell or a provisional stream tail. - self.chat_widget.request_pending_usage_output_insertion(); if is_session_header { self.merge_startup_warnings(tui, &history_cell::StartupWarningsCell::default()); } @@ -101,18 +94,6 @@ impl App { } else { Vec::new() }; - if cell.as_any().is::() - && lines.first().is_some_and(|line| { - line.line.spans.len() == 1 && line.line.spans[0].content.as_ref() == "/status" - }) - && let Some(thread_id) = self.chat_widget.thread_id() - { - self.last_thread_usage_status_cell = Some(ThreadUsageStatusHistory { - thread_id, - cell: Arc::downgrade(cell), - lines: lines.clone(), - }); - } // Invisible diagnostics still update the badge without replacing the rendered tail. if deferred || lines.is_empty() { tui.frame_requester().schedule_frame(); @@ -124,176 +105,13 @@ impl App { } else { self.insert_history_cell_lines(tui, cell.as_ref(), width); self.last_rendered_history_tail = if self.overlay.is_none() { - Some(RenderedHistoryTail { - cell: Arc::downgrade(cell), - lines, - }) + Some(RenderedHistoryTail { lines }) } else { None }; } } - pub(super) fn finish_thread_usage_refresh( - &mut self, - tui: &mut tui::Tui, - thread_id: ThreadId, - request_id: u64, - result: std::result::Result, - ) -> Result<()> { - let may_update_status = match &result { - Ok(crate::chatwidget::ThreadUsageOutcome::Available(usage)) => { - usage.thread_id == thread_id.to_string() - } - Ok(crate::chatwidget::ThreadUsageOutcome::Disabled) => true, - Err(_) => false, - }; - if !self - .chat_widget - .finish_thread_usage_refresh(thread_id, request_id, result) - || !may_update_status - { - return Ok(()); - } - - if !tui.is_owned_screen() - && (self.overlay.is_some() || self.initial_history_replay_buffer.is_some()) - { - self.pending_thread_usage_history_refresh = true; - return Ok(()); - } - self.refresh_thread_usage_history_tail(tui) - } - - pub(crate) fn refresh_thread_usage_history_tail(&mut self, tui: &mut tui::Tui) -> Result<()> { - let Some(status_history) = self.last_thread_usage_status_cell.as_ref() else { - self.pending_thread_usage_history_refresh = false; - return Ok(()); - }; - if self.chat_widget.thread_id() != Some(status_history.thread_id) { - self.last_thread_usage_status_cell = None; - self.pending_thread_usage_history_refresh = false; - return Ok(()); - } - let Some(status_cell) = status_history.cell.upgrade() else { - self.last_thread_usage_status_cell = None; - self.pending_thread_usage_history_refresh = false; - return Ok(()); - }; - - // A queued card reads the latest usage when it is first emitted. - if self.native_history.contains(&status_cell) { - self.pending_thread_usage_history_refresh = false; - return Ok(()); - } - - let width = self - .chat_widget - .history_wrap_width(tui.terminal.last_known_screen_size.width); - let updated_lines = status_cell - .display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode()); - if updated_lines == status_history.lines { - self.pending_thread_usage_history_refresh = false; - return Ok(()); - } - if tui.is_owned_screen() { - // Composite cells are backed by mutable usage state, so the retained view remeasures - // them on its next frame without replacing native terminal history. - if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() { - status_history.lines = updated_lines; - } - self.last_rendered_history_tail = None; - self.pending_thread_usage_history_refresh = false; - tui.frame_requester().schedule_frame(); - return Ok(()); - } - let Some(rendered_tail) = self.last_rendered_history_tail.as_ref() else { - self.insert_history_cell_lines(tui, status_cell.as_ref(), width); - self.last_rendered_history_tail = Some(RenderedHistoryTail { - cell: Arc::downgrade(&status_cell), - lines: updated_lines.clone(), - }); - if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() { - status_history.lines = updated_lines; - } - self.pending_thread_usage_history_refresh = false; - return Ok(()); - }; - if !rendered_tail - .cell - .upgrade() - .is_some_and(|cell| Arc::ptr_eq(&cell, &status_cell)) - { - self.insert_history_cell_lines(tui, status_cell.as_ref(), width); - self.last_rendered_history_tail = Some(RenderedHistoryTail { - cell: Arc::downgrade(&status_cell), - lines: updated_lines.clone(), - }); - if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() { - status_history.lines = updated_lines; - } - self.pending_thread_usage_history_refresh = false; - return Ok(()); - } - - let prefix_len = rendered_tail - .lines - .iter() - .zip(&updated_lines) - .take_while(|(previous, updated)| previous == updated) - .count(); - if prefix_len == rendered_tail.lines.len() && prefix_len == updated_lines.len() { - self.pending_thread_usage_history_refresh = false; - return Ok(()); - } - - let wrap_policy = self.history_line_wrap_policy(); - if !tui.replace_visible_history_tail( - &rendered_tail.lines[prefix_len..], - &updated_lines[prefix_len..], - wrap_policy, - )? { - self.insert_history_cell_lines(tui, status_cell.as_ref(), width); - } - self.last_rendered_history_tail = Some(RenderedHistoryTail { - cell: Arc::downgrade(&status_cell), - lines: updated_lines.clone(), - }); - if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() { - status_history.lines = updated_lines; - } - self.pending_thread_usage_history_refresh = false; - Ok(()) - } - - pub(super) fn pending_usage_output_insertion_blocked(&self) -> bool { - self.chat_widget.usage_history_insertion_blocked() - || self - .transcript_cells - .last() - .is_some_and(|cell| cell.as_any().is::()) - } - - fn insert_pending_usage_output(&mut self, tui: &mut tui::Tui) { - if let Some(cell) = self.chat_widget.take_pending_rate_limit_reset_hint() { - self.insert_history_cell(tui, Box::new(history_cell::SessionNoticeCell(cell))); - } - } - - pub(super) fn insert_pending_usage_output_if_ready(&mut self, tui: &mut tui::Tui) { - if self.pending_usage_output_insertion_blocked() { - return; - } - self.insert_pending_usage_output(tui); - } - - pub(super) fn insert_pending_usage_output_after_stream_shutdown(&mut self, tui: &mut tui::Tui) { - if self.chat_widget.usage_history_insertion_blocked() { - return; - } - self.insert_pending_usage_output(tui); - } - pub(super) fn open_url_in_browser(&mut self, url: String) { if let Err(err) = webbrowser::open(&url) { self.chat_widget @@ -429,12 +247,9 @@ impl App { self.transcript_view = Default::default(); *self.chat_widget.rendered_selection.borrow_mut() = Default::default(); self.last_rendered_history_tail = None; - self.last_thread_usage_status_cell = None; - self.pending_thread_usage_history_refresh = false; self.deferred_history_lines.clear(); self.has_emitted_history_lines = false; self.transcript_reflow.clear(); - self.chat_widget.clear_pending_rate_limit_reset_hint(); self.initial_history_replay_buffer = None; self.scrollback_has_older_history = false; self.backtrack = BacktrackState::default(); diff --git a/codex-rs/tui/src/app/reconnect.rs b/codex-rs/tui/src/app/reconnect.rs index 3b0a6496..cc801cb2 100644 --- a/codex-rs/tui/src/app/reconnect.rs +++ b/codex-rs/tui/src/app/reconnect.rs @@ -258,8 +258,6 @@ impl App { self.agents_overview.refresh_pending = false; self.agents_overview.refresh_notifications.clear(); self.agents_overview.pending_pin_change = None; - self.agents_overview.pending_usage = None; - self.agents_overview.usage_disabled = false; self.agents_overview.usage.clear(); self.agents_overview.activity.clear(); self.agents_overview.last_messages.clear(); @@ -386,7 +384,6 @@ impl App { } self.agent_navigation.picker_refresh = None; self.last_subagent_backfill_attempt = None; - self.rate_limit_refresh_state.invalidate_recovery(); session.worktree_source_config_builder = app_server.worktree_source_config_builder.clone(); session.inherit_task_tool_capabilities(app_server); *app_server = session; diff --git a/codex-rs/tui/src/app/resize_reflow.rs b/codex-rs/tui/src/app/resize_reflow.rs index d946ea41..48a42760 100644 --- a/codex-rs/tui/src/app/resize_reflow.rs +++ b/codex-rs/tui/src/app/resize_reflow.rs @@ -192,11 +192,6 @@ impl App { retained_lines, self.history_line_wrap_policy(), ); - if self.pending_thread_usage_history_refresh - && let Err(err) = self.refresh_thread_usage_history_tail(tui) - { - tracing::warn!(error = %err, "failed to refresh thread usage after initial replay"); - } self.request_scrollback_history_top_up(retained_rows); } @@ -551,20 +546,8 @@ impl App { width, self.chat_widget.history_render_mode(), ); - (!lines.is_empty()).then(|| super::history_ui::RenderedHistoryTail { - cell: Arc::downgrade(cell), - lines, - }) + (!lines.is_empty()).then(|| super::history_ui::RenderedHistoryTail { lines }) }); - if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() - && let Some(cell) = status_history.cell.upgrade() - { - status_history.lines = cell - .display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode()); - } - if self.pending_thread_usage_history_refresh { - self.refresh_thread_usage_history_tail(tui)?; - } self.request_scrollback_history_top_up(reflowed_rows); Ok(terminal_width) diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 03159bb4..5f443088 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -561,7 +561,7 @@ impl App { if chat_widget.status_account_display() == self.chat_widget.status_account_display() && chat_widget.has_chatgpt_account() == self.chat_widget.has_chatgpt_account() { - chat_widget.inherit_backend_banner_state(&mut self.chat_widget); + chat_widget.inherit_rate_limit_state(&mut self.chat_widget); chat_widget.inherit_security_setup(&mut self.chat_widget); } chat_widget @@ -1097,9 +1097,6 @@ impl App { .blank_sessions .insert(thread_id, started.clone()); } - // A full usage read can finish before thread/start. Apply its cached fallback - // after attachment but before the initial prompt or queued draft is submitted. - let recovery_was_pending = self.chat_widget.hold_rate_limit_recovery(); if self.loader_overrides.user_config_profile.is_none() { self.chat_widget.accept_startup_approval_policy( &mut self.config.permissions.approval_policy, @@ -1108,7 +1105,6 @@ impl App { } self.enqueue_primary_thread_session(started.session, started.turns) .await?; - self.apply_backend_banner_fallback(app_server).await; if let Some(model) = self.harness_overrides.model.as_deref() && model == self.chat_widget.current_model() && self.chat_widget.has_chatgpt_account() @@ -1126,9 +1122,6 @@ impl App { if let Some(notice) = self.pending_server_version_notice.take() { self.chat_widget.add_server_version_warning(notice); } - if !recovery_was_pending { - self.chat_widget.finish_rate_limit_recovery(); - } self.chat_widget.maybe_send_next_queued_input(); } Err(err) if self.recover_transport_error(&err) => {} diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__usage__agents_overview_usage.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__usage__agents_overview_usage.snap deleted file mode 100644 index ca8bb3b1..00000000 --- a/codex-rs/tui/src/app/snapshots/codex_tui__app__agents_overview__tests__usage__agents_overview_usage.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: tui/src/app/agents_overview_usage_tests.rs -expression: "render_bottom_popup(&app.chat_widget,\n96).replace(&format!(\"{project} 2\"),\n&group).replace(&project, \"/tmp/project\").replace(\"fwd del\", \"del\")" ---- - Agent command center Group: Project g - All 2 Needs you 1 Working 0 Ready 1 Inactive 0 tab/⇧tab filter - ──────────────────────────────────────────────────────────────────────────────────────────── - Tasks β”‚ Task details - /tmp/project 2 β”‚ - β€Ί ● Review parser β”‚ Review parser - β—‹ Other task β”‚ ● Needs input - β”‚ - β”‚ Model: Unknown - β”‚ Reasoning: Unknown - β”‚ - β”‚ Project - β”‚ /tmp/project - β”‚ Tokens: 13K in Β· 4K out - β”‚ Est. usage: 5 credits Β· ~$0.20 - β”‚ - β”‚ Needs attention - β”‚ Which dependency version should I use? - β”‚ Open task to review. - β”‚ - β”‚ Prompt - β”‚ Review parser - β”‚ - ? help esc back ↑/↓ move enter open n new diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index 15f7f453..3f17cb20 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -1020,10 +1020,7 @@ See the Codex keymap documentation for supported actions and examples." transcript_view: Default::default(), conversation_frame: Default::default(), last_rendered_history_tail: None, - last_thread_usage_status_cell: None, - pending_thread_usage_history_refresh: false, overlay: None, - retained_analytics: None, deferred_history_lines: Vec::new(), has_emitted_history_lines: false, transcript_reflow: TranscriptReflowState::default(), @@ -1104,8 +1101,6 @@ See the Codex keymap documentation for supported actions and examples." startup_protected_input_boundary: true, startup_pending_protected_request: false, account_email_request_id: None, - rate_limit_hard_stop_generation: 0, - rate_limit_refresh_state: Default::default(), pending_mcp_login_start: None, active_mcp_login_ids: HashMap::new(), pending_plugin_enabled_writes: HashMap::new(), @@ -1262,9 +1257,6 @@ See the Codex keymap documentation for supported actions and examples." "tui startup initial frame scheduled" ); app.refresh_startup_skills(&app_server); - // Kick off a non-blocking rate-limit prefetch so the first `/status` - // already has data and available reset credits can be surfaced, without - // delaying the initial frame render. if requires_openai_auth && has_chatgpt_account { crate::security_setup::prefetch( &app.config, @@ -1272,13 +1264,6 @@ See the Codex keymap documentation for supported actions and examples." app.app_event_tx.clone(), app.chat_widget.security_setup_request_id, ); - let reset_hint_request_id = app.chat_widget.start_rate_limit_reset_startup_check(); - app.refresh_rate_limits( - &app_server, - RateLimitRefreshOrigin::StartupPrefetch { - reset_hint_request_id, - }, - ); } let mut last_screen_size = tui.terminal.last_known_screen_size; @@ -1481,10 +1466,6 @@ See the Codex keymap documentation for supported actions and examples." Some((size, Instant::now() + Duration::from_secs(/*secs*/ 15))); } last_screen_size = size; - let rate_limit_poll_deadline = app - .chat_widget - .rate_limit_refresh_interval() - .and_then(|interval| app.rate_limit_refresh_state.poll_deadline(interval)); let control = select! { result = async { match app.daemon_restart.as_mut() { @@ -1706,17 +1687,6 @@ See the Codex keymap documentation for supported actions and examples." } AppRunControl::Continue } - () = async { - match rate_limit_poll_deadline { - Some(deadline) => { - tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await; - } - None => std::future::pending().await, - } - }, if backends.is_listening(displayed_owner) => { - app.refresh_rate_limits(backends.session_at(displayed_session), RateLimitRefreshOrigin::Periodic); - AppRunControl::Continue - } () = async { match app.chat_widget.terminal_title_next_refresh { Some(deadline) => { diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index 6376a1c4..2d6ed293 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -77,10 +77,7 @@ pub(crate) async fn make_test_app() -> Box { transcript_view: Default::default(), conversation_frame: Default::default(), last_rendered_history_tail: None, - last_thread_usage_status_cell: None, - pending_thread_usage_history_refresh: false, overlay: None, - retained_analytics: None, deferred_history_lines: Vec::new(), has_emitted_history_lines: false, transcript_reflow: TranscriptReflowState::default(), @@ -156,8 +153,6 @@ pub(crate) async fn make_test_app() -> Box { startup_protected_input_boundary: false, startup_pending_protected_request: false, account_email_request_id: None, - rate_limit_hard_stop_generation: 0, - rate_limit_refresh_state: Default::default(), pending_mcp_login_start: None, active_mcp_login_ids: HashMap::new(), pending_plugin_enabled_writes: HashMap::new(), diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 4864e46c..a263eff8 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -19,12 +19,6 @@ mod advanced_reasoning_tests; mod agents_navigation_tests; #[path = "tests/approvals_reviewer_error_tests.rs"] mod approvals_reviewer_error_tests; -#[path = "tests/backend_banner_fallback_tests.rs"] -mod backend_banner_fallback_tests; -#[path = "tests/backend_banner_recovery_tests.rs"] -mod backend_banner_recovery_tests; -#[path = "tests/backend_banner_startup_tests.rs"] -mod backend_banner_startup_tests; #[path = "tests/background_exit_tests.rs"] mod background_exit_tests; #[path = "tests/background_task_defaults_tests.rs"] @@ -49,8 +43,6 @@ mod home_cleanup_tests; mod key_chords; #[path = "tests/local_command_scroll_tests.rs"] mod local_command_scroll_tests; -#[path = "tests/luna_reserve_recovery_tests.rs"] -mod luna_reserve_recovery_tests; #[path = "tests/marketplace_upgrade_tests.rs"] mod marketplace_upgrade_tests; #[path = "tests/mcp_startup.rs"] @@ -80,7 +72,6 @@ mod history_hydration_tests; #[path = "tests/permission_shortcuts_tests.rs"] mod permission_shortcuts_tests; mod plugin_catalog; -mod rate_limits; #[path = "tests/realtime_handoff_e2e.rs"] mod realtime_handoff_e2e; #[path = "tests/realtime_requests.rs"] @@ -107,8 +98,6 @@ mod startup_warnings_tests; mod stream_animation_tests; #[path = "tests/streaming_interleave_e2e.rs"] mod streaming_interleave_e2e; -#[path = "tests/thread_usage.rs"] -mod thread_usage; #[path = "tests/transcript_composer.rs"] mod transcript_composer; #[path = "tests/transcript_selection.rs"] @@ -8648,10 +8637,7 @@ async fn make_test_app() -> Box { transcript_view: Default::default(), conversation_frame: Default::default(), last_rendered_history_tail: None, - last_thread_usage_status_cell: None, - pending_thread_usage_history_refresh: false, overlay: None, - retained_analytics: None, deferred_history_lines: Vec::new(), has_emitted_history_lines: false, transcript_reflow: TranscriptReflowState::default(), @@ -8728,8 +8714,6 @@ async fn make_test_app() -> Box { startup_protected_input_boundary: false, startup_pending_protected_request: false, account_email_request_id: None, - rate_limit_hard_stop_generation: 0, - rate_limit_refresh_state: Default::default(), pending_mcp_login_start: None, active_mcp_login_ids: HashMap::new(), pending_plugin_enabled_writes: HashMap::new(), @@ -8787,10 +8771,7 @@ pub(super) async fn make_test_app_with_channels() -> ( transcript_view: Default::default(), conversation_frame: Default::default(), last_rendered_history_tail: None, - last_thread_usage_status_cell: None, - pending_thread_usage_history_refresh: false, overlay: None, - retained_analytics: None, deferred_history_lines: Vec::new(), has_emitted_history_lines: false, transcript_reflow: TranscriptReflowState::default(), @@ -8867,8 +8848,6 @@ pub(super) async fn make_test_app_with_channels() -> ( startup_protected_input_boundary: false, startup_pending_protected_request: false, account_email_request_id: None, - rate_limit_hard_stop_generation: 0, - rate_limit_refresh_state: Default::default(), pending_mcp_login_start: None, active_mcp_login_ids: HashMap::new(), pending_plugin_enabled_writes: HashMap::new(), diff --git a/codex-rs/tui/src/app/tests/active_reconnect_tests.rs b/codex-rs/tui/src/app/tests/active_reconnect_tests.rs index a56853b2..4b68aad3 100644 --- a/codex-rs/tui/src/app/tests/active_reconnect_tests.rs +++ b/codex-rs/tui/src/app/tests/active_reconnect_tests.rs @@ -272,12 +272,6 @@ async fn reconnect_restores_history_permissions_and_resumes_unsent_input() -> Re } let stale_picker_refresh = app.agent_navigation.begin_picker_refresh(id).unwrap(); app.last_subagent_backfill_attempt = Some(id); - app.rate_limit_refresh_state - .start( - RateLimitRefreshOrigin::Recovery, - &mut app.rate_limit_hard_stop_generation, - ) - .unwrap(); let before_disconnect = Instant::now(); app.recap.note_focus_lost(before_disconnect); for _ in 0..3 { @@ -345,14 +339,6 @@ async fn reconnect_restores_history_permissions_and_resumes_unsent_input() -> Re assert!(!app.reconnect.offline); assert!(!app.thread_unavailable(id)); assert_eq!(app.last_subagent_backfill_attempt, None); - assert!( - app.rate_limit_refresh_state - .start( - RateLimitRefreshOrigin::Recovery, - &mut app.rate_limit_hard_stop_generation - ) - .is_some() - ); assert!(app.agent_navigation.begin_picker_refresh(id).is_some()); assert!( app.agent_navigation diff --git a/codex-rs/tui/src/app/tests/backend_event_tests.rs b/codex-rs/tui/src/app/tests/backend_event_tests.rs index 6f74cb1c..97c76c30 100644 --- a/codex-rs/tui/src/app/tests/backend_event_tests.rs +++ b/codex-rs/tui/src/app/tests/backend_event_tests.rs @@ -25,7 +25,6 @@ async fn foreign_backend_events_leave_thread_cache_and_connection_untouched() -> while events.try_recv().is_ok() {} requests.lock().unwrap().clear(); let input = app.chat_widget.capture_thread_input_state(); - let hard_stop_generation = app.rate_limit_hard_stop_generation; let foreign = BackendId::new(); let request = exec_approval_request(id, "foreign-turn", "command", /*approval_id*/ None); let loss: codex_app_server_protocol::ErrorNotification = @@ -81,7 +80,6 @@ async fn foreign_backend_events_leave_thread_cache_and_connection_untouched() -> .await; } assert!(!app.reconnect.offline); - assert_eq!(app.rate_limit_hard_stop_generation, hard_stop_generation); assert!( !app.pending_app_server_requests .contains_server_request(&request) diff --git a/codex-rs/tui/src/app/tests/local_command_scroll_tests.rs b/codex-rs/tui/src/app/tests/local_command_scroll_tests.rs index 504a26b4..9ad1e768 100644 --- a/codex-rs/tui/src/app/tests/local_command_scroll_tests.rs +++ b/codex-rs/tui/src/app/tests/local_command_scroll_tests.rs @@ -2,7 +2,6 @@ //! steal the reader's position in the owned transcript. use super::*; -use codex_app_server_protocol::RateLimitResetCreditsSummary; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use pretty_assertions::assert_eq; @@ -237,13 +236,6 @@ async fn settings_confirmations_reveal_their_history_output() -> Result<()> { }, "Failed to update thread settings", ), - ( - AppEvent::UpdateLunaReserveReasoning { - thread_id, - effort: Some(ReasoningEffortConfig::High), - }, - "Failed to update thread settings", - ), (AppEvent::ResetMemories, "Reset local memories."), ( AppEvent::KeymapCaptured { @@ -264,10 +256,6 @@ async fn settings_confirmations_reveal_their_history_output() -> Result<()> { ] { hold_older_history(&mut app, &mut tui); while events.try_recv().is_ok() {} - if matches!(event, AppEvent::UpdateLunaReserveReasoning { .. }) { - app.chat_widget - .set_model(crate::model_catalog::LUNA_RESERVE_MODEL); - } let previous_cells = app.transcript_cells.len(); app.handle_event(&mut tui, &mut server, event).await?; while let Ok(event) = events.try_recv() { @@ -510,49 +498,6 @@ async fn dynamic_service_tier_command_returns_to_latest() -> Result<()> { Ok(()) } -#[tokio::test] -async fn usage_picker_opens_analytics_without_moving_the_background_transcript() -> Result<()> { - let (mut app, mut events, _op_rx) = make_test_app_with_channels().await; - set_chatgpt_auth(&mut app.chat_widget); - let startup_request = app.chat_widget.start_rate_limit_reset_startup_check(); - assert!(app.chat_widget.finish_rate_limit_reset_hint_refresh( - startup_request, - Vec::new(), - Ok(RateLimitResetCreditsSummary { - available_count: 1, - credits: None, - }), - )); - let mut tui = crate::tui::test_support::make_test_tui()?; - let mut server = start_config_write_test_app_server(&app).await?; - tui.set_owned_screen(/*owned*/ true)?; - hold_older_history(&mut app, &mut tui); - while events.try_recv().is_ok() {} - - submit_local_command(&mut app, "/usage"); - let follow = events.try_recv().expect("usage command follow event"); - assert_matches!(&follow, AppEvent::FollowTranscript); - app.handle_event(&mut tui, &mut server, follow).await?; - assert!(render_bottom_popup(&app.chat_widget, /*width*/ 80).contains("View analytics")); - while events.try_recv().is_ok() {} - app.transcript_view - .jump_to_entry(&app.transcript_cells, /*index*/ 0); - - app.chat_widget - .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - let open = events.try_recv().expect("usage picker action"); - assert_matches!(&open, AppEvent::OpenAnalytics { view: None }); - let held = transcript_buffer(&mut app); - app.handle_event(&mut tui, &mut server, open).await?; - assert!(matches!(app.overlay.as_ref(), Some(Overlay::Analytics(_)))); - assert_eq!(transcript_buffer(&mut app), held); - assert!(!app.transcript_view.is_following()); - - tui.set_owned_screen(/*owned*/ false)?; - server.shutdown().await?; - Ok(()) -} - #[tokio::test] async fn background_history_insertion_keeps_the_visible_reading_rows() -> Result<()> { let (mut app, _events, _op_rx) = make_test_app_with_channels().await; diff --git a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs index 3040e2d9..53cf5d2f 100644 --- a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs +++ b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs @@ -5474,8 +5474,6 @@ fn fresh_session_keeps_its_name_and_draft_when_cycling_backends() -> Result<()> app.agents_overview.threads.insert(retained_thread, Some(retained)); app.chat_widget.insert_str("unsent draft"); - app.agents_overview.pending_usage = Some((thread_id, uuid::Uuid::new_v4())); - app.agents_overview.usage_disabled = true; let cwd = tempdir()?; let mut settings = app.backend_settings(); settings.config.cwd = cwd.path().to_path_buf().abs(); @@ -5525,8 +5523,6 @@ fn fresh_session_keeps_its_name_and_draft_when_cycling_backends() -> Result<()> write_user("user-a"); assert_eq!(app.other_new_session_backend(&backends).await, None); - assert_eq!(app.agents_overview.pending_usage, None); - assert!(!app.agents_overview.usage_disabled); assert_eq!(app.config.cwd.as_path(), cwd.path()); assert_eq!(app.chat_widget.thread_name().as_deref(), Some("Add User")); assert_eq!(app.chat_widget.composer_text_with_pending(), "unsent draft"); diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_after_fallback.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_after_fallback.snap deleted file mode 100644 index 21016667..00000000 --- a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_after_fallback.snap +++ /dev/null @@ -1,14 +0,0 @@ ---- -source: tui/src/app/tests/backend_banner_fallback_tests.rs -expression: normalize_snapshot_paths(rendered) ---- - Selected model usage exhausted - Add credits to use this model again. - -β€Ί 1. View usage - - Press a number to choose Β· esc to dismiss Β· type to continue - -β€Ί Ask Codex to do anything - - gpt-5.6-terra medium Β· /tmp/project diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_fallback_notice.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_fallback_notice.snap deleted file mode 100644 index 982f6789..00000000 --- a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_fallback_notice.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tui/src/app/tests/backend_banner_fallback_tests.rs -expression: "notices[0]" ---- -β€’ Automatically switched to gpt-5.6-terra medium due to usage limits. diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_fallback_unavailable.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_fallback_unavailable.snap deleted file mode 100644 index bb2bcc2e..00000000 --- a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__backend_banner_fallback_unavailable.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tui/src/app/tests/backend_banner_fallback_tests.rs -expression: normalize_snapshot_paths(rendered) ---- -β€Ί Ask Codex to do anything - - gpt-5.5 default Β· /tmp/project diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__luna_reserve_settings_unavailable.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__luna_reserve_settings_unavailable.snap deleted file mode 100644 index 221a3f24..00000000 --- a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__backend_banner_fallback_tests__luna_reserve_settings_unavailable.snap +++ /dev/null @@ -1,11 +0,0 @@ ---- -source: tui/src/app/tests/backend_banner_fallback_tests.rs -expression: normalize_snapshot_paths(rendered) ---- - Usage limit reached - Your included usage is exhausted. Choose an option below to continue. - - -β€Ί 1. Add credits - - enter select Β· esc back diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__luna_reserve_recovery_tests__luna_reserve_recovery_notice.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__luna_reserve_recovery_tests__luna_reserve_recovery_notice.snap deleted file mode 100644 index 363704bd..00000000 --- a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__luna_reserve_recovery_tests__luna_reserve_recovery_notice.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tui/src/app/tests/luna_reserve_recovery_tests.rs -expression: notice ---- -β€’ Automatically switched back to gpt-5.5 high because ordinary usage is available again. diff --git a/codex-rs/tui/src/app/tests/transcript_composer.rs b/codex-rs/tui/src/app/tests/transcript_composer.rs index 846034a1..60d056cf 100644 --- a/codex-rs/tui/src/app/tests/transcript_composer.rs +++ b/codex-rs/tui/src/app/tests/transcript_composer.rs @@ -41,183 +41,6 @@ async fn press_key( Ok(()) } -#[tokio::test] -async fn analytics_preserves_the_draft_and_retains_the_view_on_reopen() -> Result<()> { - let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; - let mut app_server = start_config_write_test_app_server(&app).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - app.chat_widget - .apply_external_edit("preserved draft".into()); - app.handle_event( - &mut tui, - &mut app_server, - AppEvent::OpenAnalytics { view: None }, - ) - .await?; - for code in [ - KeyCode::Char('4'), - KeyCode::Enter, - KeyCode::Down, - KeyCode::Char('r'), - ] { - press_key(&mut app, &mut tui, &mut app_server, code).await?; - assert!(matches!(app.overlay, Some(Overlay::Analytics(_)))); - assert!(!app.backtrack.overlay_preview_active); - } - press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('q')).await?; - assert!(app.overlay.is_none()); - assert!(app.retained_analytics.is_some()); - app.handle_event( - &mut tui, - &mut app_server, - AppEvent::OpenAnalytics { view: None }, - ) - .await?; - assert!(matches!(app.overlay, Some(Overlay::Analytics(_)))); - assert!(app.retained_analytics.is_none()); - press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('q')).await?; - assert_eq!( - app.chat_widget.composer_text_with_pending(), - "preserved draft" - ); - Ok(()) -} - -#[tokio::test] -async fn analytics_menu_reopen_preserves_navigation_and_explicit_view_selects_summary() -> Result<()> -{ - let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; - let http = wiremock::MockServer::start().await; - wiremock::Mock::given(wiremock::matchers::method("GET")) - .and(wiremock::matchers::path("/backend-api/wham/accounts/check")) - .and(wiremock::matchers::header( - "chatgpt-account-id", - "test-account", - )) - .respond_with(wiremock::ResponseTemplate::new(/*s*/ 200).set_body_json( - serde_json::json!({"accounts": [{"id": "test-account", "plan_type": "plus"}]}), - )) - .expect(/*r*/ 3) - .mount(&http) - .await; - wiremock::Mock::given(wiremock::matchers::method("GET")) - .respond_with( - wiremock::ResponseTemplate::new(/*s*/ 200) - .set_body_json(serde_json::json!({"stats":{"lifetime_tokens":12345},"data":[]})), - ) - .mount(&http) - .await; - app.config.chatgpt_base_url = format!("{}/backend-api", http.uri()); - app.config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File; - app_test_support::write_chatgpt_auth( - &app.config.codex_home, - app_test_support::ChatGptAuthFixture::new("test-access-token") - .account_id("test-account") - .chatgpt_account_id("test-account") - .chatgpt_user_id("test-user") - .plan_type("plus"), - codex_login::AuthCredentialsStoreMode::File, - ) - .unwrap(); - let mut app_server = start_config_write_test_app_server(&app).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - let mut screens = Vec::new(); - for explicit in [ - None, - None, - Some(crate::analytics::TokenActivityView::Weekly), - ] { - app.handle_event( - &mut tui, - &mut app_server, - AppEvent::OpenAnalytics { view: explicit }, - ) - .await?; - tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 10), async { - loop { - app.handle_tui_event(&mut tui, &mut app_server, TuiEvent::Draw) - .await?; - let text = buffer_text(crate::custom_terminal::test_support::last_rendered_buffer( - &tui.terminal, - )); - if screens.is_empty() && text.contains("Lifetime tokens") { - press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('4')).await?; - continue; - } - if text.contains("Lifetime tokens") - || text.contains("No activity") - || text.contains("No data reported") - { - return Ok::<(), color_eyre::Report>(()); - } - tokio::time::sleep(std::time::Duration::from_millis(/*millis*/ 5)).await; - } - }) - .await??; - let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal); - if explicit.is_none() { - let plugins = buffer - .content() - .windows("Plugins".len()) - .find(|cells| { - cells - .iter() - .map(ratatui::buffer::Cell::symbol) - .collect::() - == "Plugins" - }) - .expect("Plugins tab is visible"); - let active = crate::bottom_pane::active_tab_style(); - assert_eq!( - (plugins[0].fg, plugins[0].bg), - (active.fg.unwrap(), active.bg.unwrap()), - "the initial and reopened report must select Plugins" - ); - } - screens.push(buffer_text(buffer)); - press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('q')).await?; - } - assert_eq!(screens[0], screens[1]); - assert!(screens[2].contains("Lifetime tokens")); - assert!(screens[2].contains("Weekly")); - Ok(()) -} - -#[tokio::test] -async fn analytics_keeps_queued_and_late_startup_history_out_of_the_overlay() -> Result<()> { - for alternate_screen in [true, false] { - let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; - let mut app_server = start_config_write_test_app_server(&app).await?; - let mut tui = crate::tui::test_support::make_test_tui()?; - tui.set_alt_screen_enabled(alternate_screen); - app.insert_history_cell( - &mut tui, - Box::new(PlainHistoryCell::new(vec!["Startup header".into()])), - ); - assert!(!tui.pending_history_lines_for_test().is_empty()); - app.handle_event( - &mut tui, - &mut app_server, - AppEvent::OpenAnalytics { view: None }, - ) - .await?; - assert!(tui.pending_history_lines_for_test().is_empty()); - app.insert_history_cell( - &mut tui, - Box::new(PlainHistoryCell::new(vec![ - "Late startup announcement".into(), - ])), - ); - assert!(tui.pending_history_lines_for_test().is_empty()); - let deferred = app.deferred_history_lines.clone(); - assert!(!deferred.is_empty()); - press_key(&mut app, &mut tui, &mut app_server, KeyCode::Char('q')).await?; - assert_eq!(tui.pending_history_lines_for_test(), deferred); - assert_eq!(app.transcript_cells.len(), 2); - } - Ok(()) -} - #[tokio::test] async fn transcript_flag_off_preserves_viewer_and_backtracking() -> Result<()> { let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await; diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index 03ede038..bff646cc 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -249,15 +249,7 @@ impl App { self.history_line_wrap_policy(), ); } - if let Some(Overlay::Analytics(mut view)) = self.overlay.take() { - view.cancel_loads(); - self.retained_analytics = Some(view); - } - if self.pending_thread_usage_history_refresh - && let Err(err) = self.refresh_thread_usage_history_tail(tui) - { - tracing::warn!(error = %err, "failed to refresh thread usage after closing overlay"); - } + self.overlay = None; self.backtrack.overlay_preview_active = false; tui.frame_requester().schedule_frame(); if was_backtrack { diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index bd2c418c..0cc984f6 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -10,16 +10,11 @@ use std::path::PathBuf; use std::sync::Arc; -use std::sync::atomic::AtomicBool; use std::time::Duration; use tokio_util::sync::CancellationToken; use crate::inline_visualization::InlineVisualizationContext; -use codex_app_server_protocol::AddCreditsNudgeCreditType; -use codex_app_server_protocol::AddCreditsNudgeEmailStatus; -use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse; use codex_app_server_protocol::DynamicToolCallResponse; -use codex_app_server_protocol::GetAccountRateLimitsResponse; use codex_app_server_protocol::MarketplaceAddResponse; use codex_app_server_protocol::MarketplaceRemoveResponse; use codex_app_server_protocol::MarketplaceUpgradeResponse; @@ -57,7 +52,6 @@ use crate::bottom_pane::TerminalTitleItem; use crate::chatwidget::AstraModelPickerAction; use crate::chatwidget::ConfiguredPetLoadGeneration; use crate::chatwidget::ConnectorScopeGeneration; -use crate::chatwidget::ThreadUsageOutcome; use crate::chatwidget::UserMessage; use crate::experimental_features::FeatureWriteResult; use crate::goal_files::GoalDraft; @@ -211,36 +205,6 @@ pub(crate) struct PluginRemoteSectionError { pub(crate) message: String, } -/// Distinguishes why a rate-limit refresh was requested so the completion -/// handler can route the result correctly. -/// -/// A `StartupPrefetch` fires once, concurrently with the rest of TUI init, and -/// updates the cached snapshots and any available reset-credit notice (no -/// status card to finalize). A `StatusCommand` is tied to a specific `/status` -/// invocation and must call `finish_status_rate_limit_refresh` when done so the -/// card stops showing a "refreshing" state. A `UsageMenu` refreshes a cached -/// zero reset count so the disabled menu entry can become available without a -/// restart. A `ResetPicker` refreshes the rate limits and detailed reset-credit -/// rows before showing redemption choices. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum RateLimitRefreshOrigin { - /// Eagerly fetched after bootstrap for `/status` data and reset availability. - StartupPrefetch { reset_hint_request_id: u64 }, - /// User-initiated via `/status`; the `request_id` correlates with the - /// status card that should be updated when the fetch completes. - StatusCommand { request_id: u64 }, - /// User reopened `/usage` while the cached reset-credit count was zero. - UsageMenu { request_id: u64 }, - /// User opened the reset-credit picker. - ResetPicker { request_id: u64 }, - /// Refresh requested after a reset credit was successfully consumed. - ResetConsume { request_id: u64 }, - /// Refresh backend recovery after an inference limit error. - Recovery, - /// Background account usage read, scheduled more frequently near exhaustion. - Periodic, -} - #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum KeymapEditIntent { ReplaceAll, @@ -860,16 +824,6 @@ pub(crate) enum AppEvent { matches: Vec, }, - /// Refresh account rate limits in the background. - RefreshRateLimits { - origin: RateLimitRefreshOrigin, - }, - - /// Reconcile inherited account usage with an attached task before its queued input runs. - ApplyBackendBannerFallback { - thread_id: ThreadId, - }, - /// Open the current thread goal summary/action menu. OpenThreadGoalMenu { thread_id: ThreadId, @@ -898,46 +852,6 @@ pub(crate) enum AppEvent { thread_id: ThreadId, }, - /// Result of refreshing rate limits. - RateLimitsLoaded { - request_id: u64, - origin: RateLimitRefreshOrigin, - hard_stop_generation: u64, - result: Result, - }, - - /// Open the authenticated account analytics dashboard. - OpenAnalytics { - view: Option, - }, - - /// Open the reset-credit flow selected from the `/usage` menu. - OpenRateLimitResetCredits, - - /// Confirm the reset credit selected from the reset-credit picker. - OpenRateLimitResetConfirmation { - picker_request_id: u64, - confirmation_gate: Arc, - credit_id: Option, - reset_title: String, - reset_detail: Option, - reset_description: String, - }, - - /// Consume one reset credit using a stable idempotency key. - ConsumeRateLimitResetCredit { - idempotency_key: String, - credit_id: Option, - }, - - /// Result of consuming one reset credit. - RateLimitResetCreditConsumed { - request_id: u64, - idempotency_key: String, - credit_id: Option, - result: Result, - }, - /// Restore the displayed thread's live terminals after replaying its history. RestoreBackgroundTerminals(ThreadId), BackgroundTerminalsLoaded { @@ -945,48 +859,6 @@ pub(crate) enum AppEvent { terminals: Vec, }, - /// Fetch backend-estimated usage for the currently visible enterprise thread. - RefreshThreadUsage { - thread_id: ThreadId, - request_id: u64, - }, - - /// Result of fetching backend-estimated usage for a specific thread. - ThreadUsageLoaded { - thread_id: ThreadId, - request_id: u64, - result: Result, - }, - - /// Result of fetching usage for the selected dashboard task. - AgentsOverviewUsageLoaded { - thread_id: ThreadId, - request_id: Uuid, - result: Result, - }, - - /// Fetch workspace messages for the status-line headline item. - RefreshStatusLineWorkspaceHeadline { - request_id: u64, - }, - - /// Commit settled asynchronous usage output after active-output barriers clear. - CommitPendingUsageOutput, - - /// Commit settled asynchronous usage output after stream shutdown. - CommitPendingUsageOutputAfterStreamShutdown, - - /// Send a user-confirmed request to notify the workspace owner. - SendAddCreditsNudgeEmail { - credit_type: AddCreditsNudgeCreditType, - }, - - /// Result of notifying the workspace owner. - AddCreditsNudgeEmailFinished { - request_id: Uuid, - result: Result, - }, - /// Result of prefetching connectors. ConnectorsLoaded { thread_id: Option, @@ -1387,12 +1259,6 @@ pub(crate) enum AppEvent { /// Update the current reasoning effort in the running app and widget. UpdateReasoningEffort(Option), - /// Change Reserve effort only on the task that opened the picker, without saving defaults. - UpdateLunaReserveReasoning { - thread_id: ThreadId, - effort: Option, - }, - /// Update the current model slug in the running app and widget. UpdateModel(String), @@ -1806,11 +1672,6 @@ pub(crate) enum AppEvent { cwd: PathBuf, summary: crate::chatwidget::StatusLineGitSummary, }, - /// Async update of the workspace notification headline for status line rendering. - StatusLineWorkspaceHeadlineUpdated { - request_id: u64, - result: Result, - }, /// Apply a user-confirmed status-line item ordering/selection. StatusLineSetup { items: Vec, diff --git a/codex-rs/tui/src/app_event_sender.rs b/codex-rs/tui/src/app_event_sender.rs index cf3882a4..dd914e0b 100644 --- a/codex-rs/tui/src/app_event_sender.rs +++ b/codex-rs/tui/src/app_event_sender.rs @@ -55,7 +55,6 @@ impl AppEventSender { | AppEvent::RealtimeConversationStateChanged | AppEvent::BackgroundVoiceError { .. } | AppEvent::SyncThreadGitBranch { .. } - | AppEvent::RefreshRateLimits { .. } ) { return; diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 0bb59cda..fcdbcde2 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -66,14 +66,12 @@ use codex_app_server_protocol::ConfigBatchWriteParams; use codex_app_server_protocol::ConfigRequirementsReadResponse; use codex_app_server_protocol::ConfigWriteResponse; use codex_app_server_protocol::GetAccountParams; -use codex_app_server_protocol::GetAccountRateLimitsResponse; use codex_app_server_protocol::GetAccountResponse; use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::LogoutAccountResponse; use codex_app_server_protocol::MemoryResetResponse; use codex_app_server_protocol::Model as ApiModel; use codex_app_server_protocol::NewThreadModelDefaults; -use codex_app_server_protocol::RateLimitSnapshot; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ReviewDelivery; use codex_app_server_protocol::ReviewStartParams; @@ -3055,26 +3053,6 @@ async fn thread_session_state_from_thread_response( }) } -pub(crate) fn app_server_rate_limit_snapshots( - response: GetAccountRateLimitsResponse, -) -> Vec { - let primary_limit_id = response.rate_limits.limit_id.clone(); - let mut snapshots = vec![response.rate_limits]; - if let Some(by_limit_id) = response.rate_limits_by_limit_id { - snapshots.extend(by_limit_id.into_iter().filter_map(|(limit_id, snapshot)| { - if primary_limit_id.as_deref().is_some_and(|primary_limit_id| { - primary_limit_id == limit_id - || Some(primary_limit_id) == snapshot.limit_id.as_deref() - }) { - None - } else { - Some(snapshot) - } - })); - } - snapshots -} - #[cfg(test)] #[path = "app_server_session/reasoning_defaults_tests.rs"] mod reasoning_defaults_tests; @@ -3369,25 +3347,6 @@ mod tests { Ok(()) } - fn rate_limit_snapshot(limit_id: &str) -> RateLimitSnapshot { - RateLimitSnapshot { - limit_id: Some(limit_id.to_string()), - limit_name: None, - normal_model_slug: None, - primary: Some(codex_app_server_protocol::RateLimitWindow { - used_percent: 0, - window_duration_mins: Some(10_080), - resets_at: None, - }), - secondary: None, - credits: None, - individual_limit: None, - spend_control_reached: None, - plan_type: None, - rate_limit_reached_type: None, - } - } - fn api_model_with_upgrade_retirement_at(retirement_at: Option) -> ApiModel { ApiModel { id: "model-id".to_string(), @@ -3455,31 +3414,6 @@ mod tests { ); } - #[test] - fn app_server_rate_limit_snapshots_deduplicates_top_level_limit_from_map() { - let response = GetAccountRateLimitsResponse { - ordinary_usage_allowed: None, - account_id: None, - rate_limit_upsell: None, - rate_limits: rate_limit_snapshot("codex"), - rate_limits_by_limit_id: Some(HashMap::from([ - ("codex".to_string(), rate_limit_snapshot("codex")), - ("other".to_string(), rate_limit_snapshot("other")), - ])), - rate_limit_reset_credits: None, - }; - - let snapshots = app_server_rate_limit_snapshots(response); - - assert_eq!( - snapshots - .iter() - .map(|snapshot| snapshot.limit_id.as_deref()) - .collect::>(), - vec![Some("codex"), Some("other")] - ); - } - #[test] fn thread_settings_update_compat_detects_unsupported_errors() { let cases = [ diff --git a/codex-rs/tui/src/bottom_pane/actionable_banner.rs b/codex-rs/tui/src/bottom_pane/actionable_banner.rs index 803adf86..89dacab3 100644 --- a/codex-rs/tui/src/bottom_pane/actionable_banner.rs +++ b/codex-rs/tui/src/bottom_pane/actionable_banner.rs @@ -184,10 +184,6 @@ impl BottomPane { self.request_redraw(); } - pub(crate) fn show_actionable_banner(&mut self, banner: ActionableBanner) { - self.show_selection_view(banner.into()); - } - /// Display a banner above the composer without interrupting active dialogs or losing a draft. pub(crate) fn set_inline_banner(&mut self, banner: Option) { self.inline_banner = banner.map(|banner| { diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 56d426bc..ef7b16d8 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -554,7 +554,6 @@ fn parent_owned_command_is_allowed(command: SlashCommand, args: &str) -> bool { | SlashCommand::Status | SlashCommand::Warnings | SlashCommand::Daemon - | SlashCommand::Usage | SlashCommand::Ide | SlashCommand::DebugConfig | SlashCommand::Theme @@ -669,7 +668,6 @@ pub(crate) struct ChatComposer { config: ChatComposerConfig, connectors_enabled: bool, plugins_command_enabled: bool, - token_activity_command_enabled: bool, service_tier_commands_enabled: bool, service_tier_commands: Vec, mentions_v2_enabled: bool, @@ -854,7 +852,6 @@ impl ChatComposer { config, connectors_enabled: false, plugins_command_enabled: false, - token_activity_command_enabled: false, service_tier_commands_enabled: false, service_tier_commands: Vec::new(), mentions_v2_enabled: false, @@ -1005,12 +1002,6 @@ impl ChatComposer { self.update_slash_command_catalog(|composer| composer.plugins_command_enabled = enabled); } - pub fn set_token_activity_command_enabled(&mut self, enabled: bool) { - self.update_slash_command_catalog(|composer| { - composer.token_activity_command_enabled = enabled - }); - } - pub fn set_mentions_v2_enabled(&mut self, enabled: bool) { self.mentions_v2_enabled = enabled; self.history.set_at_mention_restore_enabled(enabled); diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs b/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs index 066e56c3..d90ef8de 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs @@ -174,7 +174,6 @@ impl<'a> SlashInput<'a> { collaboration_modes_enabled: self.command_flags.collaboration_modes_enabled, connectors_enabled: self.command_flags.connectors_enabled, plugins_command_enabled: self.command_flags.plugins_command_enabled, - token_activity_command_enabled: self.command_flags.token_activity_command_enabled, service_tier_commands_enabled: self.command_flags.service_tier_commands_enabled, daybreak_command_description: self.command_flags.daybreak_command_description, goal_command_enabled: self.command_flags.goal_command_enabled, @@ -213,7 +212,6 @@ impl ChatComposer { collaboration_modes_enabled: self.collaboration_modes_enabled, connectors_enabled: self.connectors_enabled, plugins_command_enabled: self.plugins_command_enabled, - token_activity_command_enabled: self.token_activity_command_enabled, service_tier_commands_enabled: self.service_tier_commands_enabled, daybreak_command_description: self.popups.daybreak_command_description, goal_command_enabled: self.goal_command_enabled, diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index 93a89e81..52fc2dc2 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -45,7 +45,6 @@ pub(crate) struct CommandPopupFlags { pub(crate) collaboration_modes_enabled: bool, pub(crate) connectors_enabled: bool, pub(crate) plugins_command_enabled: bool, - pub(crate) token_activity_command_enabled: bool, pub(crate) service_tier_commands_enabled: bool, pub(crate) daybreak_command_description: Option<&'static str>, pub(crate) goal_command_enabled: bool, @@ -61,7 +60,6 @@ impl From for BuiltinCommandFlags { collaboration_modes_enabled: value.collaboration_modes_enabled, connectors_enabled: value.connectors_enabled, plugins_command_enabled: value.plugins_command_enabled, - token_activity_command_enabled: value.token_activity_command_enabled, service_tier_commands_enabled: value.service_tier_commands_enabled, daybreak_command_description: value.daybreak_command_description, goal_command_enabled: value.goal_command_enabled, @@ -669,7 +667,6 @@ mod tests { collaboration_modes_enabled: true, connectors_enabled: false, plugins_command_enabled: false, - token_activity_command_enabled: false, service_tier_commands_enabled: false, daybreak_command_description: None, goal_command_enabled: false, diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index c1d8257b..046b5809 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -104,7 +104,6 @@ mod warnings_view; pub(crate) use action_required_title::ACTION_REQUIRED_PREVIEW_PREFIX; pub(crate) use action_required_title::build_action_required_title_text; pub(crate) use actionable_banner::ActionableBanner; -pub(crate) use actionable_banner::BannerDismissal; pub(crate) use app_link_view::AppLinkElicitationTarget; pub(crate) use app_link_view::AppLinkSuggestionType; pub(crate) use app_link_view::AppLinkView; @@ -546,11 +545,6 @@ impl BottomPane { self.request_redraw(); } - pub fn set_token_activity_command_enabled(&mut self, enabled: bool) { - self.composer.set_token_activity_command_enabled(enabled); - self.request_redraw(); - } - pub fn set_mentions_v2_enabled(&mut self, enabled: bool) { self.composer.set_mentions_v2_enabled(enabled); self.request_redraw(); @@ -2902,59 +2896,6 @@ mod tests { assert_eq!(pane.inline_banner_lifecycle(), (true, true)); } - #[test] - fn backend_banner_snapshots_and_numbered_actions() { - for (kind, action, label) in [ - ("personal_limit", "view_usage", "View usage"), - ("workspace_member_credits", "notify_owner", "Notify owner"), - ] { - let banner = crate::backend_banners::BackendBanner::parse(&serde_json::json!({ - "banner_type": kind, - "presentation": "dismissible", - "title": "Usage limit\u{7} reached", - "description": "Your included usage is depleted.\nChoose an action to continue.", - "ctas": [ - {"action": "unsupported", "label": "Hidden action"}, - {"action": "view_usage", "label": "Open usage settings"}, - {"action": action, "label": label}, - {"action": "view_usage", "label": "Extra action"} - ] - })) - .expect("valid optional banner"); - let (tx, mut rx) = unbounded_channel(); - let mut pane = test_pane(AppEventSender::new(tx)); - pane.set_inline_banner(Some( - banner.actionable_banner(crate::clock_format::ClockFormat::TwentyFourHour), - )); - let width = 44; - let area = Rect::new( - /*x*/ 0, - /*y*/ 0, - width, - pane.desired_height(width), - ); - assert_snapshot!( - format!("backend_banner_{kind}"), - render_snapshot(&pane, area) - ); - pane.handle_key_event(KeyEvent::new(KeyCode::Char('2'), KeyModifiers::NONE)); - let selected = match rx.try_recv().expect("numbered CTA dispatch") { - AppEvent::OpenUrlInBrowser { url } => url, - AppEvent::SendAddCreditsNudgeEmail { credit_type } => format!("{credit_type:?}"), - other => panic!("unexpected banner action: {other:?}"), - }; - assert_eq!( - selected, - if action == "view_usage" { - "https://chatgpt.com/settings/usage" - } else { - "Credits" - } - ); - assert!(pane.inline_banner.is_some()); - } - } - #[derive(Default)] struct DismissibleView { id: Option<&'static str>, diff --git a/codex-rs/tui/src/bottom_pane/slash_commands.rs b/codex-rs/tui/src/bottom_pane/slash_commands.rs index b3d3b5e7..43621ac7 100644 --- a/codex-rs/tui/src/bottom_pane/slash_commands.rs +++ b/codex-rs/tui/src/bottom_pane/slash_commands.rs @@ -58,7 +58,6 @@ pub(crate) struct BuiltinCommandFlags { pub(crate) collaboration_modes_enabled: bool, pub(crate) connectors_enabled: bool, pub(crate) plugins_command_enabled: bool, - pub(crate) token_activity_command_enabled: bool, pub(crate) service_tier_commands_enabled: bool, pub(crate) daybreak_command_description: Option<&'static str>, pub(crate) goal_command_enabled: bool, @@ -76,7 +75,6 @@ pub(crate) fn builtins_for_input(flags: BuiltinCommandFlags) -> Vec<(&'static st .filter(|(_, cmd)| flags.collaboration_modes_enabled || *cmd != SlashCommand::Plan) .filter(|(_, cmd)| flags.connectors_enabled || *cmd != SlashCommand::Apps) .filter(|(_, cmd)| flags.plugins_command_enabled || *cmd != SlashCommand::Plugins) - .filter(|(_, cmd)| flags.token_activity_command_enabled || *cmd != SlashCommand::Usage) .filter(|(_, cmd)| flags.goal_command_enabled || *cmd != SlashCommand::Goal) .filter(|(_, cmd)| flags.worktrees_enabled || *cmd != SlashCommand::Worktree) .filter(|(_, cmd)| flags.voice_command_enabled || *cmd != SlashCommand::Voice) @@ -122,7 +120,6 @@ pub(crate) fn find_builtin_command(name: &str, flags: BuiltinCommandFlags) -> Op .then_some(SlashCommand::Goal) })?; builtins_for_input(BuiltinCommandFlags { - token_activity_command_enabled: true, daybreak_command_description: Some(""), side_conversation_active: false, ..flags @@ -182,7 +179,6 @@ mod tests { collaboration_modes_enabled: true, connectors_enabled: true, plugins_command_enabled: true, - token_activity_command_enabled: true, service_tier_commands_enabled: true, daybreak_command_description: Some(""), goal_command_enabled: true, @@ -303,28 +299,6 @@ mod tests { assert_eq!(find_builtin_command("voice", flags), None); } - #[test] - fn usage_command_is_hidden_from_input_when_account_token_activity_is_disabled() { - let mut flags = all_enabled_flags(); - flags.token_activity_command_enabled = false; - assert_eq!( - builtins_for_input(flags) - .into_iter() - .find(|(_, command)| *command == SlashCommand::Usage), - None - ); - } - - #[test] - fn usage_command_exact_lookup_still_resolves_when_account_token_activity_is_disabled() { - let mut flags = all_enabled_flags(); - flags.token_activity_command_enabled = false; - assert_eq!( - find_builtin_command("usage", flags), - Some(SlashCommand::Usage) - ); - } - #[test] fn side_conversation_hides_commands_without_side_flag() { let commands = builtins_for_input(BuiltinCommandFlags { @@ -350,7 +324,6 @@ mod tests { SlashCommand::Daemon, SlashCommand::Warnings, SlashCommand::Pwd, - SlashCommand::Usage, ] ); } diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_includes_thread_usage_items.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_includes_thread_usage_items.snap deleted file mode 100644 index 1919254a..00000000 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__status_line_setup__tests__setup_view_snapshot_includes_thread_usage_items.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: tui/src/bottom_pane/status_line_setup.rs -expression: "render_lines(&view, 100)" ---- - - Configure Status Line - Select which items to display in the status line. - - Type to search - -β€Ί [x] Use theme colors Apply colors from the active /theme - ─────────────────────── - [x] thread-credits Estimated current-thread credits (Enterprise workspaces only; omitted … - [x] estimated-thread-cost Estimated current-thread cost in USD (Enterprise workspaces only; omit… - [ ] model Current model name - [ ] model-with-reasoning Current model name with reasoning level - [ ] reasoning Current reasoning level - [ ] current-dir Current working directory -↓ - 5.2 credits Β· ~$1.82 - space toggle Β· ←/β†’ reorder Β· enter save Β· esc cancel diff --git a/codex-rs/tui/src/bottom_pane/status_line_setup.rs b/codex-rs/tui/src/bottom_pane/status_line_setup.rs index 0d7985f6..26ef2387 100644 --- a/codex-rs/tui/src/bottom_pane/status_line_setup.rs +++ b/codex-rs/tui/src/bottom_pane/status_line_setup.rs @@ -129,12 +129,6 @@ pub(crate) enum StatusLineItem { /// Total output tokens generated. TotalOutputTokens, - /// Estimated credits attributed directly to the current enterprise thread. - ThreadCredits, - - /// Estimated dollar cost attributed directly to the current enterprise thread. - EstimatedThreadCost, - /// Full thread UUID. #[strum(to_string = "thread-id", serialize = "session-id")] SessionId, @@ -154,9 +148,6 @@ pub(crate) enum StatusLineItem { /// Current thread title, falling back to its identifier when unnamed. ThreadTitle, - /// Current workspace notification headline. - WorkspaceHeadline, - /// Latest checklist task progress from `update_plan` (if available). TaskProgress, @@ -211,12 +202,6 @@ impl StatusLineItem { StatusLineItem::UsedTokens => "Total tokens used in session (omitted when zero)", StatusLineItem::TotalInputTokens => "Total input tokens used in session", StatusLineItem::TotalOutputTokens => "Total output tokens used in session", - StatusLineItem::ThreadCredits => { - "Estimated current-thread credits (Enterprise workspaces only; omitted when unavailable)" - } - StatusLineItem::EstimatedThreadCost => { - "Estimated current-thread cost in USD (Enterprise workspaces only; omitted when unavailable)" - } StatusLineItem::SessionId => "Current thread identifier (omitted until thread starts)", StatusLineItem::FastMode => "Effective processing tier for the current model", StatusLineItem::Daybreak => "Whether Daybreak is enabled for this thread", @@ -225,9 +210,6 @@ impl StatusLineItem { StatusLineItem::ThreadTitle => { "Current thread title, or thread identifier when unnamed" } - StatusLineItem::WorkspaceHeadline => { - "Workspace notification headline (Enterprise workspaces only; omitted when unavailable)" - } StatusLineItem::TaskProgress => { "Latest task progress from update_plan (omitted until available)" } @@ -259,15 +241,12 @@ impl StatusLineItem { StatusLineItem::UsedTokens => StatusSurfacePreviewItem::UsedTokens, StatusLineItem::TotalInputTokens => StatusSurfacePreviewItem::TotalInputTokens, StatusLineItem::TotalOutputTokens => StatusSurfacePreviewItem::TotalOutputTokens, - StatusLineItem::ThreadCredits => StatusSurfacePreviewItem::ThreadCredits, - StatusLineItem::EstimatedThreadCost => StatusSurfacePreviewItem::EstimatedThreadCost, StatusLineItem::SessionId => StatusSurfacePreviewItem::SessionId, StatusLineItem::FastMode => StatusSurfacePreviewItem::FastMode, StatusLineItem::Daybreak => StatusSurfacePreviewItem::Daybreak, StatusLineItem::RawOutput => StatusSurfacePreviewItem::RawOutput, StatusLineItem::ThreadName => StatusSurfacePreviewItem::ThreadName, StatusLineItem::ThreadTitle => StatusSurfacePreviewItem::ThreadTitle, - StatusLineItem::WorkspaceHeadline => StatusSurfacePreviewItem::WorkspaceHeadline, StatusLineItem::TaskProgress => StatusSurfacePreviewItem::TaskProgress, } } @@ -483,18 +462,6 @@ mod tests { ); } - #[test] - fn thread_usage_items_are_independently_selectable() { - assert_eq!( - "thread-credits".parse::(), - Ok(StatusLineItem::ThreadCredits) - ); - assert_eq!( - "estimated-thread-cost".parse::(), - Ok(StatusLineItem::EstimatedThreadCost) - ); - } - #[test] fn project_name_is_canonical_and_accepts_legacy_ids() { assert_eq!(StatusLineItem::ProjectRoot.to_string(), "project-name"); @@ -759,32 +726,6 @@ mod tests { assert_snapshot!(render_lines(&view, /*width*/ 72)); } - #[test] - fn setup_view_snapshot_includes_thread_usage_items() { - let (tx_raw, _rx) = unbounded_channel::(); - let view = StatusLineSetupView::new( - Some(&[ - StatusLineItem::ThreadCredits.to_string(), - StatusLineItem::EstimatedThreadCost.to_string(), - ]), - /*use_theme_colors*/ true, - StatusSurfacePreviewData::from_iter([ - ( - StatusLineItem::ThreadCredits.preview_item(), - "5.2 credits".to_string(), - ), - ( - StatusLineItem::EstimatedThreadCost.preview_item(), - "~$1.82".to_string(), - ), - ]), - AppEventSender::new(tx_raw), - crate::keymap::RuntimeKeymap::defaults().list, - ); - - assert_snapshot!(render_lines(&view, /*width*/ 100)); - } - #[test] fn setup_view_snapshot_includes_hostname() { let (tx_raw, _rx) = unbounded_channel::(); diff --git a/codex-rs/tui/src/bottom_pane/status_line_style.rs b/codex-rs/tui/src/bottom_pane/status_line_style.rs index 2efa1a07..9029a908 100644 --- a/codex-rs/tui/src/bottom_pane/status_line_style.rs +++ b/codex-rs/tui/src/bottom_pane/status_line_style.rs @@ -60,9 +60,7 @@ impl StatusLineAccent { | StatusLineItem::ContextWindowSize | StatusLineItem::UsedTokens | StatusLineItem::TotalInputTokens - | StatusLineItem::TotalOutputTokens - | StatusLineItem::ThreadCredits - | StatusLineItem::EstimatedThreadCost => Self::Usage, + | StatusLineItem::TotalOutputTokens => Self::Usage, StatusLineItem::FiveHourLimit | StatusLineItem::WeeklyLimit => Self::Limit, StatusLineItem::CodexVersion | StatusLineItem::Hostname @@ -73,9 +71,7 @@ impl StatusLineAccent { } StatusLineItem::Permissions => Self::Mode, StatusLineItem::ApprovalMode => Self::Mode, - StatusLineItem::ThreadName - | StatusLineItem::ThreadTitle - | StatusLineItem::WorkspaceHeadline => Self::Thread, + StatusLineItem::ThreadName | StatusLineItem::ThreadTitle => Self::Thread, StatusLineItem::TaskProgress => Self::Progress, } } @@ -297,26 +293,6 @@ mod tests { assert!(!line.spans[2].style.add_modifier.contains(Modifier::DIM)); } - #[test] - fn thread_usage_items_share_an_accent_and_secondary_separator() { - let line = status_line_from_segments_with_resolver( - [ - (StatusLineItem::ThreadCredits, "5.2 credits".to_string()), - (StatusLineItem::EstimatedThreadCost, "~$0.21".to_string()), - ], - /*use_theme_colors*/ true, - /*thread_id*/ None, - /*pull_request_url*/ None, - |_| None, - ) - .expect("thread usage status line") - .line; - - assert_eq!(line_text(&line), "5.2 credits Β· ~$0.21"); - assert_eq!(line.spans[0].style, line.spans[2].style); - assert_eq!(line.spans[1].style, secondary_text_style()); - } - #[test] #[allow(clippy::disallowed_methods)] fn status_line_segments_soften_rgb_theme_styles_without_dimming_text() { diff --git a/codex-rs/tui/src/bottom_pane/status_surface_preview.rs b/codex-rs/tui/src/bottom_pane/status_surface_preview.rs index 3018d127..5b731d76 100644 --- a/codex-rs/tui/src/bottom_pane/status_surface_preview.rs +++ b/codex-rs/tui/src/bottom_pane/status_surface_preview.rs @@ -30,13 +30,10 @@ pub(crate) enum StatusSurfacePreviewItem { UsedTokens, TotalInputTokens, TotalOutputTokens, - ThreadCredits, - EstimatedThreadCost, SessionId, FastMode, Daybreak, RawOutput, - WorkspaceHeadline, Model, ModelWithReasoning, Reasoning, @@ -70,13 +67,10 @@ impl StatusSurfacePreviewItem { StatusSurfacePreviewItem::UsedTokens => "0 used", StatusSurfacePreviewItem::TotalInputTokens => "0 in", StatusSurfacePreviewItem::TotalOutputTokens => "0 out", - StatusSurfacePreviewItem::ThreadCredits => "5.2 credits", - StatusSurfacePreviewItem::EstimatedThreadCost => "~$1.82", StatusSurfacePreviewItem::SessionId => "550e8400-e29b-41d4", StatusSurfacePreviewItem::FastMode => "Fast", StatusSurfacePreviewItem::Daybreak => "Daybreak off", StatusSurfacePreviewItem::RawOutput => "raw output", - StatusSurfacePreviewItem::WorkspaceHeadline => "Workspace headline", StatusSurfacePreviewItem::Model => "gpt-5.2-codex", StatusSurfacePreviewItem::ModelWithReasoning => "gpt-5.2-codex medium", StatusSurfacePreviewItem::Reasoning => "medium", @@ -110,13 +104,10 @@ impl StatusSurfacePreviewItem { Self::UsedTokens, Self::TotalInputTokens, Self::TotalOutputTokens, - Self::ThreadCredits, - Self::EstimatedThreadCost, Self::SessionId, Self::FastMode, Self::Daybreak, Self::RawOutput, - Self::WorkspaceHeadline, Self::Model, Self::ModelWithReasoning, Self::Reasoning, diff --git a/codex-rs/tui/src/bottom_pane/tests/actionable_banner_tests.rs b/codex-rs/tui/src/bottom_pane/tests/actionable_banner_tests.rs index 00e43a10..c2a922d8 100644 --- a/codex-rs/tui/src/bottom_pane/tests/actionable_banner_tests.rs +++ b/codex-rs/tui/src/bottom_pane/tests/actionable_banner_tests.rs @@ -2,66 +2,6 @@ use super::super::actionable_banner::BannerDismissal; use super::*; use pretty_assertions::assert_eq; -#[test] -fn promoted_banner_uses_picker_hints_and_preserves_the_draft() { - let width = 40; - for confirm in [false, true] { - let (tx, mut rx) = unbounded_channel(); - let mut pane = test_pane(AppEventSender::new(tx)); - let mut keymap = RuntimeKeymap::defaults(); - keymap.list.accept = vec![crate::key_hint::plain(KeyCode::F(/*n*/ 3))]; - keymap.list.cancel = vec![crate::key_hint::plain(KeyCode::F(/*n*/ 2))]; - pane.set_keymap_bindings(&keymap); - pane.set_composer_text("draft in progress".into(), Vec::new(), Vec::new()); - pane.handle_key_event(KeyEvent::from(KeyCode::Left)); - let draft = pane.composer.draft_snapshot(); - pane.show_actionable_banner(ActionableBanner { - title: "Usage limit reached".into(), - description: "Review your usage or keep working with another model.".into(), - actions: vec![SelectionItem { - name: "View usage".into(), - dismiss_on_select: true, - actions: vec![Box::new(|tx| { - tx.send(AppEvent::OpenUrlInBrowser { - url: "https://example.com/usage".into(), - }); - })], - ..Default::default() - }], - ..Default::default() - }); - let area = Rect::new( - /*x*/ 0, - /*y*/ 0, - width, - pane.desired_height(width), - ); - let rendered = render_snapshot(&pane, area); - assert!(rendered.contains("View usage"), "{rendered}"); - assert!(rendered.contains("f3 select Β· f2 back"), "{rendered}"); - if confirm { - assert_snapshot!(format!("promoted_action_banner_{width}"), rendered); - } - assert_eq!(pane.composer.draft_snapshot(), draft); - - let key = if confirm { - KeyCode::F(/*n*/ 3) - } else { - KeyCode::F(/*n*/ 2) - }; - pane.handle_key_event(KeyEvent::from(key)); - assert!(pane.view_stack.is_empty()); - assert_eq!(pane.composer.draft_snapshot(), draft); - if confirm { - assert!( - matches!(rx.try_recv(), Ok(AppEvent::OpenUrlInBrowser { url }) - if url == "https://example.com/usage") - ); - } - assert!(rx.try_recv().is_err()); - } -} - #[test] fn hidden_banner_preserves_input_before_render_and_after_resize() { let (tx, mut rx) = unbounded_channel(); diff --git a/codex-rs/tui/src/bottom_pane/title_setup.rs b/codex-rs/tui/src/bottom_pane/title_setup.rs index b0994c4c..713c8187 100644 --- a/codex-rs/tui/src/bottom_pane/title_setup.rs +++ b/codex-rs/tui/src/bottom_pane/title_setup.rs @@ -74,10 +74,6 @@ pub(crate) enum TerminalTitleItem { TotalInputTokens, /// Total output tokens generated. TotalOutputTokens, - /// Estimated credits attributed directly to the current enterprise thread. - ThreadCredits, - /// Estimated dollar cost attributed directly to the current enterprise thread. - EstimatedThreadCost, /// Full thread UUID. #[strum(to_string = "thread-id", serialize = "session-id")] SessionId, @@ -127,12 +123,6 @@ impl TerminalTitleItem { TerminalTitleItem::UsedTokens => "Total tokens used in session (omitted when zero)", TerminalTitleItem::TotalInputTokens => "Total input tokens used in session", TerminalTitleItem::TotalOutputTokens => "Total output tokens used in session", - TerminalTitleItem::ThreadCredits => { - "Estimated current-thread credits (Enterprise workspaces only; omitted when unavailable)" - } - TerminalTitleItem::EstimatedThreadCost => { - "Estimated current-thread cost (Enterprise workspaces only; omitted when unavailable)" - } TerminalTitleItem::SessionId => { "Current thread identifier (omitted until thread starts)" } @@ -167,10 +157,6 @@ impl TerminalTitleItem { TerminalTitleItem::TotalOutputTokens => { Some(StatusSurfacePreviewItem::TotalOutputTokens) } - TerminalTitleItem::ThreadCredits => Some(StatusSurfacePreviewItem::ThreadCredits), - TerminalTitleItem::EstimatedThreadCost => { - Some(StatusSurfacePreviewItem::EstimatedThreadCost) - } TerminalTitleItem::SessionId => Some(StatusSurfacePreviewItem::SessionId), TerminalTitleItem::FastMode => Some(StatusSurfacePreviewItem::FastMode), TerminalTitleItem::Daybreak => Some(StatusSurfacePreviewItem::Daybreak), @@ -559,17 +545,6 @@ mod tests { ); } - #[test] - fn thread_usage_items_are_independently_selectable() { - assert_eq!( - parse_terminal_title_items(["thread-credits", "estimated-thread-cost"].into_iter()), - Some(vec![ - TerminalTitleItem::ThreadCredits, - TerminalTitleItem::EstimatedThreadCost, - ]) - ); - } - #[test] fn parse_terminal_title_items_accepts_kebab_case_variants() { let items = parse_terminal_title_items( @@ -590,8 +565,6 @@ mod tests { "used-tokens", "total-input-tokens", "total-output-tokens", - "thread-credits", - "estimated-thread-cost", "session-id", "fast-mode", ] @@ -616,8 +589,6 @@ mod tests { TerminalTitleItem::UsedTokens, TerminalTitleItem::TotalInputTokens, TerminalTitleItem::TotalOutputTokens, - TerminalTitleItem::ThreadCredits, - TerminalTitleItem::EstimatedThreadCost, TerminalTitleItem::SessionId, TerminalTitleItem::FastMode, ]) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 89afcfc5..d4b7af59 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -66,7 +66,6 @@ use crate::session_state::SessionNetworkProxyRuntime; use crate::session_state::ThreadSessionState; use crate::status::RateLimitWindowDisplay; use crate::status::StatusAccountDisplay; -use crate::status::StatusHistoryHandle; use crate::status::format_directory_display; use crate::status::format_tokens_compact; use crate::status::rate_limit_snapshot_display_for_limit; @@ -78,8 +77,6 @@ use crate::text_formatting::proper_join; use crate::token_usage::TokenUsage; use crate::token_usage::TokenUsageInfo; use crate::version::CODEX_CLI_VERSION; -use codex_app_server_protocol::AddCreditsNudgeCreditType; -use codex_app_server_protocol::AddCreditsNudgeEmailStatus; use codex_app_server_protocol::AppSummary; use codex_app_server_protocol::CodexErrorInfo as AppServerCodexErrorInfo; use codex_app_server_protocol::CollabAgentTool; @@ -191,7 +188,6 @@ fn normalize_thread_name(name: &str) -> Option { use crate::app_event::AppEvent; use crate::app_event::ExitMode; use crate::app_event::PermissionProfileSelection; -use crate::app_event::RateLimitRefreshOrigin; use crate::app_event_sender::AppEventSender; use crate::auto_review_denials; use crate::auto_review_denials::RecentAutoReviewDenials; @@ -340,12 +336,8 @@ mod permission_shortcuts; mod permissions_menu; pub(crate) use self::permissions_menu::auto_review_available; pub(crate) use self::permissions_menu::cyber_model_approval_reviewer; -mod backend_banners; mod compaction; -mod luna_reserve_model; -mod luna_reserve_return; mod security_setup; -pub(crate) use backend_banners::AutomaticModelSwitchReason; mod protocol; pub(crate) use protocol::final_agent_message; pub(crate) use protocol::needs_agent_message; @@ -359,7 +351,6 @@ use self::rate_limits::app_server_rate_limit_error_kind; pub(crate) use self::rate_limits::fallback_limit_label; use self::rate_limits::is_app_server_cyber_policy_error; mod recap; -mod reset_credits; pub(crate) use self::rate_limits::limit_label_for_window; mod completion; mod realtime; @@ -401,8 +392,6 @@ mod status_surfaces; use self::status_surface_commands::StatusSurfaceOverrides; mod streaming; use self::status_surfaces::CachedProjectRootName; -mod thread_usage; -pub(crate) use self::thread_usage::ThreadUsageOutcome; mod tool_lifecycle; mod tool_requests; mod transcript; @@ -413,7 +402,6 @@ use self::transcript::TranscriptState; mod turn_lifecycle; mod turn_runtime; use self::turn_lifecycle::TurnLifecycleState; -mod usage; mod user_messages; mod working_directory; use self::user_messages::MessageDelivery; @@ -575,38 +563,24 @@ pub(crate) struct ChatWidget { pub(crate) windows_sandbox_elevated_setup_complete: bool, token_info: Option, token_usage_pending: bool, + // True while replaying a turn completion (resume/backfill) rather than handling a live event. + replaying_turn_completion: bool, // Status and polling use account usage reads; response streams may identify meters differently. rate_limit_snapshots_by_limit_id: BTreeMap, - refreshing_status_outputs: Vec<(u64, StatusHistoryHandle)>, - next_status_refresh_request_id: u64, - pending_rate_limit_reset_request_id: Option, - pending_rate_limit_reset_idempotency_key: Option, - rate_limit_reset_picker_request_id: Option, - pending_rate_limit_reset_hint_request_id: Option, - pending_usage_menu_rate_limit_request_id: Option, - pending_rate_limit_reset_hint: Option, - available_rate_limit_reset_credits: Option, - next_rate_limit_reset_request_id: u64, plan_type: Option, codex_rate_limit_reached_type: Option, codex_spend_control_reached: Option, rate_limit_warnings: RateLimitWarningState, clock_format: crate::clock_format::ClockFormat, usage_notice_state: usage_notice::UsageNoticeState, - backend_banner_state: backend_banners::BackendBannerState, pub(crate) security_setup_request_id: uuid::Uuid, security_setup_presented: bool, security_setup_identity: Option, security_setup_dismissed: bool, - automatic_model_switch_state: backend_banners::AutomaticModelSwitchState, - backend_banner_notice_model: Option, - // Remember the account's Reserve entry notice across chats and transient banner refreshes. - luna_reserve_notice_account_id: Option, pub(crate) warning_display_state: WarningDisplayState, pub(crate) composer_images: Option, pub(crate) rendered_selection: std::cell::RefCell, rate_limit_switch_prompt: RateLimitSwitchPromptState, - add_credits_nudge_email_in_flight: Option, adaptive_chunking: AdaptiveChunkingPolicy, // Stream lifecycle controller stream_controller: Option, @@ -783,18 +757,6 @@ pub(crate) struct ChatWidget { status_line_git_summary_pending: bool, // True once we've attempted a Git summary lookup for the current CWD. status_line_git_summary_lookup_complete: bool, - // Cached workspace notification headline for the status line. - status_line_workspace_headline: Option, - // Request ID for the async workspace headline fetch currently in flight. - status_line_workspace_headline_pending_request_id: Option, - // Request ID to assign to the next workspace headline fetch. - next_status_line_workspace_headline_request_id: u64, - // Last time a workspace headline fetch was requested. - status_line_workspace_headline_last_requested_at: Option, - // Set after the backend reports the workspace-message feature gate is disabled. - status_line_workspace_messages_disabled: bool, - // Cached backend-estimated cost and bounded refresh state for the current thread. - thread_usage: thread_usage::ThreadUsageState, // Current thread-goal status shown in the status line when plan mode is inactive. current_goal_status_indicator: Option, current_goal_status: Option, @@ -1209,8 +1171,6 @@ impl ChatWidget { { self.refresh_terminal_title(); } - self.refresh_status_line_if_workspace_headline_due(); - self.refresh_thread_usage_if_settlement_due(); self.refresh_terminal_program_status(); } @@ -1227,7 +1187,6 @@ impl ChatWidget { fn flush_active_cell(&mut self) { if let Some(active) = self.transcript.take_active_cell() { self.app_event_tx.send(AppEvent::InsertHistoryCell(active)); - self.request_pending_usage_output_insertion(); } } @@ -1259,7 +1218,6 @@ impl ChatWidget { }; if let Some(active) = self.take_history_insertion_prefix(cell.as_ref()) { self.app_event_tx.send(AppEvent::InsertHistoryCell(active)); - self.request_pending_usage_output_insertion(); } self.app_event_tx.send(AppEvent::InsertHistoryCell(cell)); } @@ -1477,7 +1435,6 @@ impl ChatWidget { computer.mark_failed(); } self.add_boxed_history(cell); - self.request_pending_usage_output_insertion(); } } @@ -2022,7 +1979,6 @@ impl ChatWidget { pub(crate) fn active_cell_transcript_key(&self) -> Option { let cell = self.transcript.active_cell.as_ref(); let mut realtime_cells = self.realtime_conversation.live_transcript_cells(); - let rate_limit_reset_hint = self.pending_rate_limit_reset_hint(); if cell.is_none() && self .realtime_conversation @@ -2030,14 +1986,10 @@ impl ChatWidget { .next() .is_none() && self.realtime_conversation.pending_history_cells.is_empty() - && rate_limit_reset_hint.is_none() { return None; } - let live_sources: [Option<&dyn HistoryCell>; 2] = [ - cell.map(AsRef::as_ref), - rate_limit_reset_hint.map(|cell| cell as &dyn HistoryCell), - ]; + let live_sources: [Option<&dyn HistoryCell>; 1] = [cell.map(AsRef::as_ref)]; Some(ActiveCellTranscriptKey { cacheable: live_sources .into_iter() @@ -2128,7 +2080,6 @@ impl Drop for ChatWidget { .send(AppEvent::StopRealtimeConversation { thread_id }); } self.reset_realtime_conversation(); - self.stop_rate_limit_poller(); } } diff --git a/codex-rs/tui/src/chatwidget/constructor.rs b/codex-rs/tui/src/chatwidget/constructor.rs index b7b35db0..2cc95d89 100644 --- a/codex-rs/tui/src/chatwidget/constructor.rs +++ b/codex-rs/tui/src/chatwidget/constructor.rs @@ -151,36 +151,22 @@ impl ChatWidget { windows_sandbox_elevated_setup_complete: false, token_info: None, token_usage_pending: false, + replaying_turn_completion: false, rate_limit_snapshots_by_limit_id: BTreeMap::new(), - refreshing_status_outputs: Vec::new(), - next_status_refresh_request_id: 0, - pending_rate_limit_reset_request_id: None, - pending_rate_limit_reset_idempotency_key: None, - rate_limit_reset_picker_request_id: None, - pending_rate_limit_reset_hint_request_id: None, - pending_usage_menu_rate_limit_request_id: None, - pending_rate_limit_reset_hint: None, - available_rate_limit_reset_credits: None, - next_rate_limit_reset_request_id: 0, plan_type: initial_plan_type, codex_rate_limit_reached_type: None, codex_spend_control_reached: None, rate_limit_warnings: RateLimitWarningState::default(), clock_format: crate::clock_format::ClockFormat::system(), usage_notice_state: usage_notice::UsageNoticeState::default(), - backend_banner_state: backend_banners::BackendBannerState::default(), security_setup_request_id: uuid::Uuid::new_v4(), security_setup_presented: false, security_setup_identity: None, security_setup_dismissed: false, - automatic_model_switch_state: backend_banners::AutomaticModelSwitchState::default(), - backend_banner_notice_model: None, - luna_reserve_notice_account_id: None, warning_display_state: WarningDisplayState::default(), composer_images: None, rendered_selection: Default::default(), rate_limit_switch_prompt: RateLimitSwitchPromptState::default(), - add_credits_nudge_email_in_flight: None, adaptive_chunking: AdaptiveChunkingPolicy::default(), stream_controller: None, plan_stream_controller: None, @@ -288,12 +274,6 @@ impl ChatWidget { status_line_git_summary_cwd: None, status_line_git_summary_pending: false, status_line_git_summary_lookup_complete: false, - status_line_workspace_headline: None, - status_line_workspace_headline_pending_request_id: None, - next_status_line_workspace_headline_request_id: 0, - status_line_workspace_headline_last_requested_at: None, - status_line_workspace_messages_disabled: false, - thread_usage: thread_usage::ThreadUsageState::default(), current_goal_status_indicator: None, current_goal_status: None, external_editor_state: ExternalEditorState::Closed, @@ -308,7 +288,6 @@ impl ChatWidget { widget.local_settings.codex_home.as_path(), widget.local_settings.history.persistence, ); - widget.prefetch_rate_limits(); if let Some(keymap) = runtime_keymap { widget.bottom_pane.set_keymap_bindings(&keymap); } @@ -336,9 +315,6 @@ impl ChatWidget { widget .bottom_pane .set_connectors_enabled(widget.connectors_enabled()); - widget - .bottom_pane - .set_token_activity_command_enabled(widget.has_codex_backend_auth); widget.refresh_status_surfaces(); widget diff --git a/codex-rs/tui/src/chatwidget/hook_lifecycle.rs b/codex-rs/tui/src/chatwidget/hook_lifecycle.rs index b2bb0d96..bf0199bc 100644 --- a/codex-rs/tui/src/chatwidget/hook_lifecycle.rs +++ b/codex-rs/tui/src/chatwidget/hook_lifecycle.rs @@ -11,7 +11,6 @@ impl ChatWidget { self.bottom_pane.set_hook_status_message(/*message*/ None); if self.active_hook_cell.take().is_some() { self.bump_active_cell_revision(); - self.request_pending_usage_output_insertion(); } } @@ -83,7 +82,6 @@ impl ChatWidget { self.bump_active_cell_revision(); self.app_event_tx .send(AppEvent::InsertHistoryCell(Box::new(completed_cell))); - self.request_pending_usage_output_insertion(); } pub(super) fn finish_active_hook_cell_if_idle(&mut self) { @@ -93,7 +91,6 @@ impl ChatWidget { if cell.is_empty() { self.active_hook_cell = None; self.bump_active_cell_revision(); - self.request_pending_usage_output_insertion(); return; } if cell.should_flush() @@ -102,7 +99,6 @@ impl ChatWidget { self.bump_active_cell_revision(); self.app_event_tx .send(AppEvent::InsertHistoryCell(Box::new(cell))); - self.request_pending_usage_output_insertion(); } } diff --git a/codex-rs/tui/src/chatwidget/input_flow.rs b/codex-rs/tui/src/chatwidget/input_flow.rs index 1cbabcbf..1968aa95 100644 --- a/codex-rs/tui/src/chatwidget/input_flow.rs +++ b/codex-rs/tui/src/chatwidget/input_flow.rs @@ -63,7 +63,6 @@ impl ChatWidget { let should_submit_now = self.is_session_configured() && !self.is_plan_streaming_in_tui() && !self.input_queue.submissions_paused() - && !self.input_queue.rate_limit_recovery_pending && (!self.input_queue.user_turn_pending_start || self.turn_lifecycle.agent_turn_running); if should_submit_now { @@ -183,8 +182,7 @@ impl ChatWidget { } let should_run_now = self.is_session_configured() && !self.is_user_turn_pending_or_running() - && !self.input_queue.submissions_paused() - && !self.input_queue.rate_limit_recovery_pending; + && !self.input_queue.submissions_paused(); if action != QueuedInputAction::ParseSlash { self.empty_state_animation.borrow_mut().dismiss(); } @@ -252,7 +250,6 @@ impl ChatWidget { || self.fork_in_progress || self.has_misalignment_policy_violation() || self.input_queue.submissions_paused() - || self.input_queue.rate_limit_recovery_pending || self.input_queue.recovered_queue || self.input_queue.has_unconfirmed_messages() { diff --git a/codex-rs/tui/src/chatwidget/input_queue.rs b/codex-rs/tui/src/chatwidget/input_queue.rs index dc162e98..20ded67b 100644 --- a/codex-rs/tui/src/chatwidget/input_queue.rs +++ b/codex-rs/tui/src/chatwidget/input_queue.rs @@ -51,8 +51,6 @@ pub(super) struct InputQueueState { pub(super) submit_pending_steers_after_interrupt: bool, pub(super) suppress_queue_autosend: bool, pub(super) transcript_copy: std::sync::Weak, - /// Hold submissions while a usage failure or backend-directed model fallback is resolved. - pub(super) rate_limit_recovery_pending: bool, /// Pause for user recovery (for example an image or permission failure), independent of delivery. pub(super) recovered_queue: bool, } @@ -93,7 +91,6 @@ impl InputQueueState { self.rejected_steer_history_records.clear(); self.pending_steers.clear(); self.submit_pending_steers_after_interrupt = false; - self.rate_limit_recovery_pending = false; } pub(super) fn preview(&self) -> PendingInputPreview { diff --git a/codex-rs/tui/src/chatwidget/input_restore.rs b/codex-rs/tui/src/chatwidget/input_restore.rs index 286566b2..6cbb3dac 100644 --- a/codex-rs/tui/src/chatwidget/input_restore.rs +++ b/codex-rs/tui/src/chatwidget/input_restore.rs @@ -172,8 +172,7 @@ impl ChatWidget { } pub(crate) fn submit_initial_user_message_if_pending(&mut self) { - if self.suppress_initial_user_message_submit || self.input_queue.rate_limit_recovery_pending - { + if self.suppress_initial_user_message_submit { return; } #[cfg(any(target_os = "windows", test))] diff --git a/codex-rs/tui/src/chatwidget/input_submission.rs b/codex-rs/tui/src/chatwidget/input_submission.rs index c616326e..ae096120 100644 --- a/codex-rs/tui/src/chatwidget/input_submission.rs +++ b/codex-rs/tui/src/chatwidget/input_submission.rs @@ -115,7 +115,6 @@ impl ChatWidget { if !self.is_session_configured() || self.is_user_turn_pending_or_running() || self.pending_image_submission.is_some() - || self.input_queue.rate_limit_recovery_pending || self.safety_recourse.is_some() { return None; @@ -161,8 +160,7 @@ impl ChatWidget { return (false, None); } self.empty_state_animation.borrow_mut().dismiss(); - if self.input_queue.rate_limit_recovery_pending - || self.pending_image_submission.is_some() + if self.pending_image_submission.is_some() || self.safety_recourse.is_some() { let model_prompt = matches!( @@ -543,7 +541,6 @@ impl ChatWidget { if source != UserMessageSource::QuestionAnswer { self.bottom_pane.clear_pending_questions(); } - self.dismiss_backend_banner_for_new_turn(); self.note_realtime_typed_input(&submitted_message.text); if render_in_history { self.input_queue.user_turn_pending_start = true; diff --git a/codex-rs/tui/src/chatwidget/interaction.rs b/codex-rs/tui/src/chatwidget/interaction.rs index 6876532b..5951a6b0 100644 --- a/codex-rs/tui/src/chatwidget/interaction.rs +++ b/codex-rs/tui/src/chatwidget/interaction.rs @@ -353,7 +353,6 @@ impl ChatWidget { self.refresh_startup_recovery(); } crate::startup_recovery::submitted(&input_result); - self.sync_backend_banner_view(); if should_pause_active_goal { self.pause_active_goal_for_interrupt(); } diff --git a/codex-rs/tui/src/chatwidget/model_command.rs b/codex-rs/tui/src/chatwidget/model_command.rs index a4fa6828..c4abcb0f 100644 --- a/codex-rs/tui/src/chatwidget/model_command.rs +++ b/codex-rs/tui/src/chatwidget/model_command.rs @@ -120,12 +120,6 @@ fn resolve_model_command(chat: &ChatWidget, args: &str) -> Result) { - if self.restrict_model_picker_to_luna_reserve() { - self.open_luna_reserve_model_popup(presets, MODEL_SELECTION_VIEW_ID); - return; - } let presets: Vec = presets .into_iter() .filter(|preset| preset.show_in_picker) @@ -219,13 +215,6 @@ impl ChatWidget { } pub(crate) fn open_all_models_popup(&mut self) { - if self.restrict_model_picker_to_luna_reserve() { - self.open_luna_reserve_model_popup( - self.model_catalog.try_list_models().unwrap_or_default(), - ALL_MODELS_SELECTION_VIEW_ID, - ); - return; - } let presets = self .model_catalog .try_list_models() @@ -306,19 +295,10 @@ impl ChatWidget { let warning = effort_for_action .as_ref() .and_then(|effort| self.ultra_reasoning_concurrency_warning(effort)); - let thread_id = self.thread_id(); let sparkle_thread = self.sparkle_thread_for_picker_action(&model_for_action); let scoped = self.scope_model_picker_event(); vec![Box::new(move |tx| { - if model_for_action == LUNA_RESERVE_MODEL { - // Reserve is temporary: update the active task without persisting a model default. - if let Some(thread_id) = thread_id { - tx.send(scoped(AppEvent::UpdateLunaReserveReasoning { - thread_id, - effort: effort_for_action.clone(), - })); - } - } else if effort_for_action == Some(ReasoningEffortConfig::Ultra) { + if effort_for_action == Some(ReasoningEffortConfig::Ultra) { tx.send(scoped( AstraModelPickerAction::ApplyAdvancedReasoning { effort: ReasoningEffortConfig::Ultra, diff --git a/codex-rs/tui/src/chatwidget/protocol.rs b/codex-rs/tui/src/chatwidget/protocol.rs index 3f1ea5a7..43a34fa9 100644 --- a/codex-rs/tui/src/chatwidget/protocol.rs +++ b/codex-rs/tui/src/chatwidget/protocol.rs @@ -20,7 +20,7 @@ impl ChatWidget { { return; } - let was_replaying_turn_completion = self.thread_usage.replaying_turn_completion; + let was_replaying_turn_completion = self.replaying_turn_completion; if replay_kind.is_some() || matches!( ¬ification, @@ -29,7 +29,7 @@ impl ChatWidget { { self.empty_state_animation.borrow_mut().dismiss(); } - self.thread_usage.replaying_turn_completion = replay_kind.is_some(); + self.replaying_turn_completion = replay_kind.is_some(); let from_replay = replay_kind.is_some(); let is_resume_initial_replay = matches!(replay_kind, Some(ReplayKind::ResumeInitialMessages)); @@ -447,7 +447,7 @@ impl ChatWidget { self.status_state.current_status.details_max_lines, ); } - self.thread_usage.replaying_turn_completion = was_replaying_turn_completion; + self.replaying_turn_completion = was_replaying_turn_completion; } pub(super) fn handle_turn_completed_notification( @@ -470,8 +470,8 @@ impl ChatWidget { let live_turn = replay_kind.is_none() && self.last_turn_id() == Some(notification.turn.id.as_str()); let mut recourse = self.safety_recourse.take_if(|_| live_turn); - let was_replaying_turn_completion = self.thread_usage.replaying_turn_completion; - self.thread_usage.replaying_turn_completion = replay_kind.is_some(); + let was_replaying_turn_completion = self.replaying_turn_completion; + self.replaying_turn_completion = replay_kind.is_some(); match notification.turn.status { TurnStatus::Completed => { let last_agent_message = final_agent_message( @@ -576,7 +576,7 @@ impl ChatWidget { if replay_kind.is_none() { self.finish_realtime_turn(¬ification.turn.id); } - self.thread_usage.replaying_turn_completion = was_replaying_turn_completion; + self.replaying_turn_completion = was_replaying_turn_completion; } fn handle_item_started_notification( diff --git a/codex-rs/tui/src/chatwidget/quick_dials.rs b/codex-rs/tui/src/chatwidget/quick_dials.rs index 7c775312..703a3d26 100644 --- a/codex-rs/tui/src/chatwidget/quick_dials.rs +++ b/codex-rs/tui/src/chatwidget/quick_dials.rs @@ -112,7 +112,6 @@ impl ChatWidget { .models .iter() .find(|model| model.model == self.current_model() && model.show_in_picker) - .filter(|_| !self.restrict_model_picker_to_luna_reserve()) else { return Err("The current model cannot be recalled with /model."); }; diff --git a/codex-rs/tui/src/chatwidget/rate_limits.rs b/codex-rs/tui/src/chatwidget/rate_limits.rs index 60c2470d..7bc18dab 100644 --- a/codex-rs/tui/src/chatwidget/rate_limits.rs +++ b/codex-rs/tui/src/chatwidget/rate_limits.rs @@ -1,16 +1,7 @@ -//! Rate-limit warning, prompt, and notice surfaces, plus quota-aware account refresh cadence. +//! Rate-limit warning, prompt, and notice surfaces. use super::*; -pub(super) const WORKSPACE_NUDGE_VIEW_ID: &str = "workspace-usage-nudge"; -use crate::bottom_pane::ActionableBanner; -use crate::model_catalog::LUNA_RESERVE_MODEL; use codex_app_server_protocol::CodexErrorInfo as AppServerCodexErrorInfo; -use uuid::Uuid; - -pub(super) struct PendingCreditsNudge { - request_id: Uuid, - credit_type: AddCreditsNudgeCreditType, -} pub(super) const NUDGE_MODEL_SLUG: &str = crate::model_catalog::LUNA_MODEL; pub(super) const RATE_LIMIT_SWITCH_PROMPT_THRESHOLD: f64 = 90.0; @@ -180,122 +171,39 @@ pub(super) fn is_app_server_cyber_policy_error(info: &AppServerCodexErrorInfo) - matches!(info, AppServerCodexErrorInfo::CyberPolicy) } -#[derive(Clone, Copy)] -pub(super) enum RateLimitSnapshotSource { - AccountUsage, - RollingUpdate, -} - fn has_usable_workspace_credits(credits: &CreditsSnapshot) -> bool { credits.unlimited || credits.has_credits } impl ChatWidget { - /// Poll more often near exhaustion for every ChatGPT account, independently of experiments. - pub(crate) fn rate_limit_refresh_interval(&self) -> Option { - if !self.should_prefetch_rate_limits() { - return None; - } - // Ignore unrelated model buckets; watch ordinary usage and the selected model's bucket. - let used_percent = self - .rate_limit_snapshots_by_limit_id - .iter() - .filter(|(limit_id, snapshot)| { - limit_id.as_str() == "codex" || snapshot.limit_name == self.current_model() - }) - .flat_map(|(_, snapshot)| snapshot.primary.iter().chain(snapshot.secondary.iter())) - .map(|window| window.used_percent) - .filter(|percent| percent.is_finite()) - .max_by(f64::total_cmp) - .unwrap_or_default(); - let seconds = if used_percent >= 99.0 { - 5 - } else if used_percent >= 90.0 { - 15 - } else if used_percent >= 75.0 { - 30 - } else { - 60 - }; - Some(std::time::Duration::from_secs(seconds)) - } - - pub(crate) fn hold_rate_limit_recovery(&mut self) -> bool { - std::mem::replace(&mut self.input_queue.rate_limit_recovery_pending, true) - } - - pub(crate) fn finish_rate_limit_recovery(&mut self) { - if self.waiting_for_luna_reserve() { - return; - } - if std::mem::take(&mut self.input_queue.rate_limit_recovery_pending) { - self.submit_initial_user_message_if_pending(); - self.maybe_send_next_queued_input(); - } + /// Carries account-scoped usage state into a widget created for another task. + pub(crate) fn inherit_rate_limit_state(&mut self, previous: &mut ChatWidget) { + // Usage belongs to the account, so switching tasks must not 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; } + /// Applies a rate-limit snapshot published by the app server; `None` clears cached limits. pub(crate) fn on_rate_limit_snapshot(&mut self, snapshot: Option) { - self.on_rate_limit_snapshot_from(snapshot, RateLimitSnapshotSource::AccountUsage); - } - - pub(crate) fn on_rolling_rate_limit_snapshot(&mut self, snapshot: RateLimitSnapshot) { - if let (Some(previous), Some(current)) = ( - self.codex_rate_limit_reached_type, - snapshot.rate_limit_reached_type, - ) && previous != current - { - // Do not keep a credits CTA when a newer notification requires a different remedy. - // An absent aggregate limit type is not a contradiction of model-scoped recovery. - self.clear_backend_banner(); - } - // Rolling app-server notifications are sparse. Preserve metadata learned from the full read. - self.on_rate_limit_snapshot_from(Some(snapshot), RateLimitSnapshotSource::RollingUpdate); - } - - fn on_rate_limit_snapshot_from( - &mut self, - snapshot: Option, - source: RateLimitSnapshotSource, - ) { - let usage_notice_blocked = self.codex_rate_limit_reached_type.is_some() - || self.codex_spend_control_reached == Some(true); - if let Some(mut snapshot) = snapshot { + if let Some(snapshot) = snapshot { let limit_id = snapshot .limit_id .clone() .unwrap_or_else(|| "codex".to_string()); let is_codex_limit = limit_id.eq_ignore_ascii_case("codex"); - if is_codex_limit - && self - .usage_notice_state - .update(&snapshot, source, self.plan_type) - { + if is_codex_limit && self.usage_notice_state.update(&snapshot, self.plan_type) { self.request_redraw(); } - if matches!(source, RateLimitSnapshotSource::RollingUpdate) - && snapshot.credits.is_none() - { - snapshot.credits = self - .rate_limit_snapshots_by_limit_id - .get(&limit_id) - .and_then(|display| display.credits.as_ref()) - .map(|credits| CreditsSnapshot { - has_credits: credits.has_credits, - unlimited: credits.unlimited, - balance: credits.balance.clone(), - }); - } self.plan_type = snapshot.plan_type.or(self.plan_type); - if is_codex_limit - && (matches!(source, RateLimitSnapshotSource::AccountUsage) - || snapshot.spend_control_reached.is_some()) - { + if is_codex_limit && snapshot.spend_control_reached.is_some() { self.codex_spend_control_reached = snapshot.spend_control_reached; } - if (is_codex_limit && matches!(source, RateLimitSnapshotSource::AccountUsage)) - || snapshot.rate_limit_reached_type.is_some() - { + if snapshot.rate_limit_reached_type.is_some() { self.codex_rate_limit_reached_type = snapshot.rate_limit_reached_type; } let workspace_limit_reached = self.codex_spend_control_reached == Some(true) @@ -374,22 +282,18 @@ impl ChatWidget { self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Pending; } - // /wham/usage identifies ordinary and additional model limits separately. Streamed - // updates still drive warnings/recovery above, but must not overwrite status data. - if matches!(source, RateLimitSnapshotSource::AccountUsage) { - let limit_label = snapshot - .limit_name - .clone() - .unwrap_or_else(|| limit_id.clone()); - let display = rate_limit_snapshot_display_for_limit( - &snapshot, - limit_label, - Local::now(), - self.clock_format, - ); - self.rate_limit_snapshots_by_limit_id - .insert(limit_id, display); - } + let limit_label = snapshot + .limit_name + .clone() + .unwrap_or_else(|| limit_id.clone()); + let display = rate_limit_snapshot_display_for_limit( + &snapshot, + limit_label, + Local::now(), + self.clock_format, + ); + self.rate_limit_snapshots_by_limit_id + .insert(limit_id, display); if !warnings.is_empty() { for warning in warnings { @@ -402,27 +306,10 @@ impl ChatWidget { self.codex_rate_limit_reached_type = None; self.codex_spend_control_reached = None; } - if usage_notice_blocked - != (self.codex_rate_limit_reached_type.is_some() - || self.codex_spend_control_reached == Some(true)) - { - self.request_redraw(); - } + self.request_redraw(); self.refresh_status_line(); } - pub(super) fn stop_rate_limit_poller(&mut self) {} - - #[cfg_attr(not(test), allow(dead_code))] - pub(super) fn prefetch_rate_limits(&mut self) { - self.stop_rate_limit_poller(); - } - - #[cfg_attr(not(test), allow(dead_code))] - pub(super) fn should_prefetch_rate_limits(&self) -> bool { - self.requires_openai_auth && self.has_chatgpt_account - } - fn lower_cost_preset(&self) -> Option { let models = self.model_catalog.try_list_models().ok()?; models @@ -439,11 +326,7 @@ impl ChatWidget { } pub(super) fn maybe_show_pending_rate_limit_prompt(&mut self) { - if self.has_applicable_backend_banner() { - return; - } - if self.rate_limit_switch_prompt_hidden() - || matches!(self.current_model(), NUDGE_MODEL_SLUG | LUNA_RESERVE_MODEL) + if self.rate_limit_switch_prompt_hidden() || self.current_model() == NUDGE_MODEL_SLUG { self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle; return; @@ -539,111 +422,6 @@ impl ChatWidget { }); } - pub(super) fn open_workspace_owner_nudge_prompt( - &mut self, - credit_type: AddCreditsNudgeCreditType, - ) { - if self.add_credits_nudge_email_in_flight.is_some() { - return; - } - - let (title, prompt) = match credit_type { - AddCreditsNudgeCreditType::Credits => ( - "You've reached your workspace credit limit", - "Your workspace is out of credits. Ask your workspace owner to add more. Notify owner?", - ), - AddCreditsNudgeCreditType::UsageLimit => ( - "Usage limit reached", - "Request a limit increase from your owner to continue using codex. Request increase?", - ), - }; - let send_actions: Vec = vec![Box::new(move |tx| { - tx.send(AppEvent::SendAddCreditsNudgeEmail { credit_type }); - })]; - let items = vec![ - SelectionItem { - name: "Yes".to_string(), - display_shortcut: Some(key_hint::plain(KeyCode::Char('y')).into()), - actions: send_actions, - dismiss_on_select: true, - ..Default::default() - }, - SelectionItem { - name: "No (default)".to_string(), - display_shortcut: Some(key_hint::plain(KeyCode::Char('n')).into()), - dismiss_on_select: true, - ..Default::default() - }, - ]; - - self.bottom_pane.show_actionable_banner(ActionableBanner { - view_id: Some(WORKSPACE_NUDGE_VIEW_ID), - title: title.to_string(), - description: prompt.to_string(), - actions: items, - initial_selected_idx: Some(1), - ..Default::default() - }); - } - - pub(crate) fn start_add_credits_nudge_email_request( - &mut self, - credit_type: AddCreditsNudgeCreditType, - ) -> Option { - if self.add_credits_nudge_email_in_flight.is_some() { - return None; - } - let request_id = Uuid::new_v4(); - self.add_credits_nudge_email_in_flight = Some(PendingCreditsNudge { - request_id, - credit_type, - }); - Some(request_id) - } - - pub(crate) fn finish_add_credits_nudge_email_request( - &mut self, - request_id: Uuid, - result: Result, - ) { - let Some(pending) = self - .add_credits_nudge_email_in_flight - .as_ref() - .filter(|pending| pending.request_id == request_id) - else { - return; - }; - let credit_type = pending.credit_type; - self.add_credits_nudge_email_in_flight = None; - let message = match (credit_type, result) { - (AddCreditsNudgeCreditType::Credits, Ok(AddCreditsNudgeEmailStatus::Sent)) => { - "Workspace owner notified." - } - ( - AddCreditsNudgeCreditType::Credits, - Ok(AddCreditsNudgeEmailStatus::CooldownActive), - ) => "Workspace owner was already notified recently.", - (AddCreditsNudgeCreditType::Credits, Err(_)) => { - "Could not notify your workspace owner. Please try again." - } - (AddCreditsNudgeCreditType::UsageLimit, Ok(AddCreditsNudgeEmailStatus::Sent)) => { - "Limit increase requested." - } - ( - AddCreditsNudgeCreditType::UsageLimit, - Ok(AddCreditsNudgeEmailStatus::CooldownActive), - ) => "A limit increase was already requested recently.", - (AddCreditsNudgeCreditType::UsageLimit, Err(_)) => { - "Could not request a limit increase. Please try again." - } - }; - self.add_to_history(history_cell::new_info_event( - message.to_string(), - /*hint*/ None, - )); - self.request_redraw(); - } - pub(crate) fn set_rate_limit_switch_prompt_hidden(&mut self, hidden: bool) { self.local_settings.notices.hide_rate_limit_model_nudge = Some(hidden); if hidden { diff --git a/codex-rs/tui/src/chatwidget/realtime_navigation.rs b/codex-rs/tui/src/chatwidget/realtime_navigation.rs index 6dbaaa13..190d56a8 100644 --- a/codex-rs/tui/src/chatwidget/realtime_navigation.rs +++ b/codex-rs/tui/src/chatwidget/realtime_navigation.rs @@ -19,7 +19,6 @@ impl ChatWidget { pub(crate) fn park_voice(&mut self) { self.app_event_tx.voice_only.store(true, Ordering::Relaxed); self.set_queue_autosend_suppressed(/*suppressed*/ true); - self.stop_rate_limit_poller(); } pub(crate) fn prepare_background_voice_replay( @@ -55,6 +54,5 @@ impl ChatWidget { self.realtime_conversation.pending_history_cells = replay.pending_history_cells; self.update_realtime_footer(); self.refresh_terminal_title(); - self.refresh_thread_usage_after_turn(); } } diff --git a/codex-rs/tui/src/chatwidget/realtime_tests/lifecycle.rs b/codex-rs/tui/src/chatwidget/realtime_tests/lifecycle.rs index 8ff6abc2..c4ebf4df 100644 --- a/codex-rs/tui/src/chatwidget/realtime_tests/lifecycle.rs +++ b/codex-rs/tui/src/chatwidget/realtime_tests/lifecycle.rs @@ -73,15 +73,6 @@ async fn stopping_while_the_offer_is_pending_resets_the_session() { chat.park_voice(); callback.send(AppEvent::ResetTranscriptForThreadSwitch); assert!(events.try_recv().is_err()); - callback.send(AppEvent::RefreshRateLimits { - origin: crate::app_event::RateLimitRefreshOrigin::Recovery, - }); - assert!(matches!( - events.try_recv(), - Ok(AppEvent::RefreshRateLimits { - origin: crate::app_event::RateLimitRefreshOrigin::Recovery - }) - )); sender.send(AppEvent::ResetTranscriptForThreadSwitch); assert!(events.try_recv().is_ok()); restored.resume_background_voice(&mut chat); diff --git a/codex-rs/tui/src/chatwidget/rendering.rs b/codex-rs/tui/src/chatwidget/rendering.rs index 1a78db7a..c7ee8444 100644 --- a/codex-rs/tui/src/chatwidget/rendering.rs +++ b/codex-rs/tui/src/chatwidget/rendering.rs @@ -212,17 +212,6 @@ impl ChatWidget { ); } - if let Some(cell) = self.pending_rate_limit_reset_hint() { - flex.push( - /*flex*/ 1, - RenderableItem::Owned(Box::new(TranscriptAreaRenderable { - child: cell, - top: 1, - right: active_cell_right_reserve, - persistent_layout: None, - })), - ); - } flex.push( /*flex*/ 0, self.bottom_pane_renderable(crate::bottom_pane::ComposerRenderOptions::default()) @@ -342,10 +331,6 @@ impl ChatWidget { .iter() .chain(self.realtime_conversation.live_transcript_cells()) .map(AsRef::as_ref), - ) - .chain( - self.pending_rate_limit_reset_hint() - .map(|cell| cell as &dyn HistoryCell), ); let mut lines = Vec::new(); for cell in cells { diff --git a/codex-rs/tui/src/chatwidget/rendering_tests.rs b/codex-rs/tui/src/chatwidget/rendering_tests.rs index 28108e89..630fb478 100644 --- a/codex-rs/tui/src/chatwidget/rendering_tests.rs +++ b/codex-rs/tui/src/chatwidget/rendering_tests.rs @@ -131,9 +131,6 @@ async fn owned_live_history_keeps_all_sources_in_each_presentation() { let (mut widget, _sender, _events, _operations) = make_chatwidget_manual_with_sender().await; widget.transcript.active_cell = Some(Box::new(PresentationCell("active"))); widget.realtime_conversation.live_transcript_cell = Some(Box::new(PresentationCell("voice"))); - widget.pending_rate_limit_reset_hint = Some(history_cell::PlainHistoryCell::new(vec![ - "rate limit hint".into(), - ])); let text = |lines: Option>| { lines .unwrap_or_default() @@ -151,20 +148,14 @@ async fn owned_live_history_keeps_all_sources_in_each_presentation() { compact active compact voice - - rate limit hint --- raw active raw voice - - rate limit hint --- detailed active detailed voice - - rate limit hint "); widget.local_settings.tui.animations = false; @@ -184,7 +175,6 @@ async fn owned_live_history_keeps_all_sources_in_each_presentation() { "deferred second", "user caption", "assistant caption", - "rate limit hint", ]; for latest_speaker in ["assistant", "user"] { diff --git a/codex-rs/tui/src/chatwidget/security_setup.rs b/codex-rs/tui/src/chatwidget/security_setup.rs index e001f07e..40fc5b94 100644 --- a/codex-rs/tui/src/chatwidget/security_setup.rs +++ b/codex-rs/tui/src/chatwidget/security_setup.rs @@ -16,7 +16,7 @@ impl ChatWidget { self.security_setup_dismissed = previous.security_setup_dismissed || (previous.security_setup_presented && previous.bottom_pane.inline_banner_lifecycle().1); - if previous.security_setup_presented && !self.has_applicable_backend_banner() { + if previous.security_setup_presented { self.bottom_pane .transfer_inline_banner_from(&mut previous.bottom_pane); self.security_setup_presented = true; @@ -54,13 +54,7 @@ impl ChatWidget { if self.security_setup_presented || self.security_setup_dismissed { return; } - tracing::debug!( - has_backend_banner = self.has_applicable_backend_banner(), - "presenting security setup notice" - ); - if self.has_applicable_backend_banner() { - return; - } + tracing::debug!("presenting security setup notice"); self.security_setup_presented = true; self.bottom_pane.set_inline_banner(Some(ActionableBanner { title: notice.title, diff --git a/codex-rs/tui/src/chatwidget/session_flow.rs b/codex-rs/tui/src/chatwidget/session_flow.rs index 57376049..6b19a5ae 100644 --- a/codex-rs/tui/src/chatwidget/session_flow.rs +++ b/codex-rs/tui/src/chatwidget/session_flow.rs @@ -118,11 +118,7 @@ impl ChatWidget { { self.refresh_account_scoped_models(); } - self.backend_banner_notice_model = None; - self.automatic_model_switch_state = - backend_banners::AutomaticModelSwitchState::default(); self.review.recent_auto_review_denials = RecentAutoReviewDenials::default(); - self.clear_thread_usage_state(); } let has_turn_history = previous_thread_id == self.thread_id && self.turn_lifecycle.has_turn_history; @@ -219,19 +215,6 @@ impl ChatWidget { .set_active_reasoning_effort_baseline(effort.as_ref()); self.refresh_model_display(); self.refresh_status_surfaces(); - if previous_thread_id != self.thread_id - && self.should_prefetch_rate_limits() - && (self.current_model() == crate::model_catalog::LUNA_RESERVE_MODEL - || self.backend_banner_fallback().is_some()) - { - // Reconcile this task with retained account state before sending its initial/queued - // prompt. Do not wait for the next usage poll after /new, /resume or a thread switch. - self.hold_rate_limit_recovery(); - self.app_event_tx - .send(AppEvent::ApplyBackendBannerFallback { - thread_id: session.thread_id, - }); - } self.sync_service_tier_commands(); self.sync_worktrees_enabled(); self.sync_plugins_command_enabled(); @@ -391,7 +374,6 @@ impl ChatWidget { self.transcript.last_plan_progress = None; self.last_rendered_user_message_display = None; self.last_rendered_user_message_client_id = None; - self.clear_pending_rate_limit_reset_hint(); self.set_token_info(/*info*/ None); self.bottom_pane.clear_pending_questions(); self.bottom_pane.set_task_running(/*running*/ false); diff --git a/codex-rs/tui/src/chatwidget/settings.rs b/codex-rs/tui/src/chatwidget/settings.rs index f6dea221..474e6ad2 100644 --- a/codex-rs/tui/src/chatwidget/settings.rs +++ b/codex-rs/tui/src/chatwidget/settings.rs @@ -260,12 +260,9 @@ impl ChatWidget { self.invalidate_permission_discovery(); self.permission_discovery = None; self.invalidate_connector_scope(); - self.clear_pending_rate_limit_reset_requests(); - self.clear_backend_banner(); - self.luna_reserve_notice_account_id = None; - self.automatic_model_switch_state = backend_banners::AutomaticModelSwitchState::default(); - self.input_queue.rate_limit_recovery_pending = false; - self.add_credits_nudge_email_in_flight = None; + self.rate_limit_snapshots_by_limit_id.clear(); + self.clear_security_setup_banner(); + self.bottom_pane.set_inline_banner(/*banner*/ None); self.codex_rate_limit_reached_type = None; self.codex_spend_control_reached = None; self.rate_limit_warnings = RateLimitWarningState::default(); @@ -273,19 +270,6 @@ impl ChatWidget { self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle; self.bottom_pane .dismiss_view_by_id(RATE_LIMIT_SWITCH_PROMPT_VIEW_ID); - let had_refreshing_status_outputs = !self.refreshing_status_outputs.is_empty(); - let now = Local::now(); - for (_, handle) in self.refreshing_status_outputs.drain(..) { - handle.finish_rate_limit_refresh(&[], now); - } - if had_refreshing_status_outputs { - self.request_redraw(); - } - self.status_line_workspace_headline = None; - self.status_line_workspace_headline_pending_request_id = None; - self.status_line_workspace_headline_last_requested_at = None; - self.status_line_workspace_messages_disabled = false; - self.clear_thread_usage_state(); self.status_account_display = status_account_display; self.plan_type = plan_type; self.has_chatgpt_account = has_chatgpt_account; @@ -297,8 +281,6 @@ impl ChatWidget { self.bottom_pane .set_connectors_enabled(self.connectors_enabled()); self.refresh_connector_mentions(/*force_refresh*/ false); - self.bottom_pane - .set_token_activity_command_enabled(has_codex_backend_auth); self.refresh_status_surfaces(); } @@ -310,14 +292,6 @@ impl ChatWidget { /// Set the model in the widget's config copy and stored collaboration mode. pub(crate) fn set_model(&mut self, model: &str) { - if model != self.current_model() { - if self.current_model() == crate::model_catalog::LUNA_RESERVE_MODEL { - self.clear_reserve_return(); - } else { - self.automatic_model_switch_state = - backend_banners::AutomaticModelSwitchState::default(); - } - } self.current_collaboration_mode = self.current_collaboration_mode.with_updates( Some(model.to_string()), /*effort*/ None, @@ -499,7 +473,6 @@ impl ChatWidget { /// header/title (`refresh_model_display`) but forget the footer status line /// (`refresh_status_line`). pub(super) fn refresh_model_dependent_surfaces(&mut self) { - self.sync_backend_banner_view(); self.refresh_model_display(); self.refresh_status_line(); self.refresh_open_model_picker(); diff --git a/codex-rs/tui/src/chatwidget/slash_dispatch.rs b/codex-rs/tui/src/chatwidget/slash_dispatch.rs index ee1c21bd..a28ff455 100644 --- a/codex-rs/tui/src/chatwidget/slash_dispatch.rs +++ b/codex-rs/tui/src/chatwidget/slash_dispatch.rs @@ -38,8 +38,6 @@ const SIDE_SLASH_COMMAND_UNAVAILABLE_HINT: &str = "Press Ctrl+C to return to the main thread first."; const GOAL_USAGE_HINT: &str = "Example: /goal improve benchmark coverage"; const RAW_USAGE: &str = "Usage: /raw [on|off]"; -const USAGE_CHATGPT_LOGIN_REQUIRED: &str = "Sign in with ChatGPT to use /usage."; - impl ChatWidget { /// Dispatch a bare slash command and record its staged local-history entry. /// @@ -550,19 +548,7 @@ impl ChatWidget { SlashCommand::Daemon => self.app_event_tx.send(AppEvent::OpenDaemonMenu), SlashCommand::Warnings => self.app_event_tx.send(AppEvent::OpenWarnings), SlashCommand::Status => { - if self.should_prefetch_rate_limits() { - let request_id = self.next_status_refresh_request_id; - self.next_status_refresh_request_id = - self.next_status_refresh_request_id.wrapping_add(1); - self.add_status_output(/*refreshing_rate_limits*/ true, Some(request_id)); - self.app_event_tx.send(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - }); - } else { - self.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); - } + self.add_status_output(); } SlashCommand::Cd => { self.dispatch_command_with_args(SlashCommand::Cd, "~".to_string(), Vec::new()); @@ -573,11 +559,6 @@ impl ChatWidget { /*hint*/ None, ); } - SlashCommand::Usage => { - if self.ensure_usage_command_available() { - self.open_usage_menu(); - } - } SlashCommand::Ide => { self.handle_ide_command(); } @@ -848,18 +829,6 @@ impl ChatWidget { SlashCommand::Pwd => { self.add_error_message("Usage: /pwd".to_string()); } - SlashCommand::Usage => { - if self.ensure_usage_command_available() { - match crate::analytics::TokenActivityView::parse(trimmed) { - Some(view) => self - .app_event_tx - .send(AppEvent::OpenAnalytics { view: Some(view) }), - None => self.add_error_message( - "Usage: /usage [daily|weekly|cumulative]".to_string(), - ), - } - } - } SlashCommand::Voice => match trimmed.to_ascii_lowercase().as_str() { "settings" => self.app_event_tx.send(AppEvent::OpenRealtimeSettings), "mute" => self.app_event_tx.send(AppEvent::VoiceControl { @@ -1275,7 +1244,6 @@ impl ChatWidget { collaboration_modes_enabled: self.collaboration_modes_enabled(), connectors_enabled: self.connectors_enabled(), plugins_command_enabled: self.config.features.enabled(Feature::Plugins), - token_activity_command_enabled: self.has_codex_backend_auth, goal_command_enabled: self.config.features.enabled(Feature::Goals), service_tier_commands_enabled: !self.current_model_service_tier_commands().is_empty(), daybreak_command_description: self.daybreak_command_description(), @@ -1286,14 +1254,6 @@ impl ChatWidget { } } - fn ensure_usage_command_available(&mut self) -> bool { - if self.has_codex_backend_auth { - return true; - } - self.add_error_message(USAGE_CHATGPT_LOGIN_REQUIRED.to_string()); - false - } - fn queued_command_drain_result(&self, cmd: SlashCommand) -> QueueDrain { if self.is_user_turn_pending_or_running() || !self.bottom_pane.no_modal_or_popup_active() { return QueueDrain::Stop; @@ -1303,7 +1263,6 @@ impl ChatWidget { | SlashCommand::Status | SlashCommand::Daemon | SlashCommand::Pwd - | SlashCommand::Usage | SlashCommand::DebugConfig | SlashCommand::Ps | SlashCommand::Stop diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_available_hint.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_available_hint.snap deleted file mode 100644 index 56f0fc2f..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_available_hint.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tui/src/chatwidget/tests/usage.rs -expression: rendered ---- -β€’ You have 2 usage limit resets available. Run /usage to use one. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_confirmation.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_confirmation.snap deleted file mode 100644 index 4889cd5d..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_confirmation.snap +++ /dev/null @@ -1,13 +0,0 @@ ---- -source: tui/src/chatwidget/tests/usage.rs -expression: "render_bottom_popup(&chat, 80)" ---- - Use this reset? - Us Full reset (Weekly + 5 hr) Β· Expires 09:39 on 18 Jun 2026 - 1 - - 1. Yes, use reset Reset your weekly and 5-hour usage limits. -β€Ί 1.β€Ί 2. No, go back Choose a different reset - 2. - enter confirm Β· esc back - enter choose Β· esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_hint_waits_for_active_output.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_hint_waits_for_active_output.snap deleted file mode 100644 index e18178d4..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_hint_waits_for_active_output.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tui/src/chatwidget/tests/usage.rs -expression: "lines_to_single_string(&chat.active_cell_transcript_lines(80).expect(\"active output with reset hint\"),)" ---- -active tool - -β€’ You have 2 usage limit resets available. Run /usage to use one. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_picker_narrow.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_picker_narrow.snap deleted file mode 100644 index 23aa0248..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_picker_narrow.snap +++ /dev/null @@ -1,14 +0,0 @@ ---- -source: tui/src/chatwidget/tests/usage.rs -expression: "render_bottom_popup(&chat, 44)" ---- - Usage limit resets - 2 usage limit resets available. - - -β€Ί 1. Full reset Expires 9:39 AM on 18 Jun - 2026 - 2. Full reset Does not expire - 3. Cancel - - enter choose Β· esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_popup_states.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_popup_states.snap deleted file mode 100644 index 4f7ca6ba..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_reset_popup_states.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: tui/src/chatwidget/tests/usage.rs -expression: "states.join(\"\\n---\\n\")" ---- - Usage limit resets - Checking your available resets... - - -β€Ί Loading... - - enter select Β· esc back ---- - Usage limit resets - 2 usage limit resets available. - - -β€Ί 1. Full reset (Weekly + 5 hr) Expires 09:39 on 18 Jun 2026 - 2. Full reset (Weekly + 5 hr) Expires 08:59 on 27 Jun 2026 - 3. Cancel - - enter choose Β· esc back ---- - Usage limit resets - You don't have any usage limit resets available. - - -β€Ί 1. Close - - enter select Β· esc back ---- - Usage limit resets - Couldn't load usage limit resets. Please try again. - - -β€Ί 1. Try again - 2. Close - - enter select Β· esc back ---- - Usage limit resets - Resetting your usage... - - -β€Ί Using a reset... ---- - Usage limit resets - Couldn't reset usage. Please try again. - - -β€Ί 1. Try again - 2. Close - - enter select Β· esc back ---- - Usage limit resets - Your usage does not need a reset right now. - - -β€Ί 1. Close - - enter select Β· esc back ---- - Usage limit resets - No usage limit resets are available. - - -β€Ί 1. Close - - enter select Β· esc back ---- - Usage limit resets - Usage reset. Checking your remaining resets... - - -β€Ί Refreshing... ---- - Usage limit resets - Usage reset. You have 1 usage limit reset left. - - -β€Ί 1. Close - - enter select Β· esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__signed_out_usage_command_reports_chatgpt_login_requirement.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__signed_out_usage_command_reports_chatgpt_login_requirement.snap deleted file mode 100644 index b777fe51..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__signed_out_usage_command_reports_chatgpt_login_requirement.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tui/src/chatwidget/tests/slash_commands.rs -expression: rendered ---- -β–  Sign in with ChatGPT to use /usage. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_copy_whole_status.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_copy_whole_status.snap index a8631ab1..342254c4 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_copy_whole_status.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_copy_whole_status.snap @@ -4,9 +4,6 @@ expression: "whole_status.replace(&directory,\n\"[[workspace]]\").replace(crate: --- >_ OpenAI Codex (vVERSION) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: GPT-5.5 (reasoning medium, summaries auto) Model provider: openai Directory: [[workspace]] @@ -17,4 +14,3 @@ expression: "whole_status.replace(&directory,\n\"[[workspace]]\").replace(crate: Session: 00000000-0000-0000-0000-000000000123 Token usage: 0 total (0 input + 0 output) - Limits: data not available yet diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_command_estimated_thread_usage.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_command_estimated_thread_usage.snap deleted file mode 100644 index b6369418..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_command_estimated_thread_usage.snap +++ /dev/null @@ -1,9 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_command_tests.rs -expression: thread_usage ---- - Thread usage: 50 credits Β· ~$1.82 - Models: GPT-5.4 80%, GPT-5 Mini 20% - Reasoning: Medium 20%, High 80% - Speed: Fast mode 80%, Standard 20% - Billed tokens: 120 input (25 cached) + 50 output diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_command_estimated_thread_usage_without_usd.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_command_estimated_thread_usage_without_usd.snap deleted file mode 100644 index 45aaf2c3..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_command_estimated_thread_usage_without_usd.snap +++ /dev/null @@ -1,9 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_command_tests.rs -expression: thread_usage ---- - Thread usage: 50 credits - Models: GPT-5.4 100% - Reasoning: High 100% - Speed: Fast mode 100% - Billed tokens: 100 input (20 cached) + 40 output diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_estimated_thread_cost_footer.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_estimated_thread_cost_footer.snap deleted file mode 100644 index d0d6e6d8..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_estimated_thread_cost_footer.snap +++ /dev/null @@ -1,9 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_and_layout.rs -expression: normalized_backend_snapshot(terminal.backend()) ---- -" " -" " -"β€Ί Ask Codex to do anything " -" " -" GPT-5.6-Sol default Β· 5.2 credits Β· ~$0.21 " diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_workspace_headline.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_workspace_headline.snap deleted file mode 100644 index 5fe11ae9..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_line_setup_popup_workspace_headline.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_surface_previews.rs -expression: status_line_popup_snapshot(&mut chat) ---- - Configure Status Line - Select which items to display in the status line. - - Type to search - -β€Ί [x] Use theme colors Apply colors from the active /theme - ─────────────────────── - [x] workspace-headline Workspace notification headline (Enterprise workspaces only; omitted wh… - [ ] model Current model name - [ ] model-with-reasoning Current model name with reasoning level - [ ] reasoning Current reasoning level - [ ] current-dir Current working directory - [ ] project-name Project name (omitted when unavailable) -↓ - Workspace maintenance starts at 5pm - space toggle Β· ←/β†’ reorder Β· enter save Β· esc cancel diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_thread_usage.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_thread_usage.snap deleted file mode 100644 index 86ef121b..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_thread_usage.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_surface_previews.rs -expression: snapshot ---- -status line: 5.2 credits Β· ~$0.21 -terminal title: 5.2 credits | ~$0.21 diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_thread_usage.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_thread_usage.snap deleted file mode 100644 index 3b417f4c..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__terminal_title_setup_popup_thread_usage.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_surface_previews.rs -expression: terminal_title_popup_snapshot(&mut chat) ---- - Configure Terminal Title - Select which items to display in the terminal title. - - Type to search - -β€Ί [x] thread-credits Estimated current-thread credits (Enterprise workspaces only; omitted … - [x] estimated-thread-cost Estimated current-thread cost (Enterprise workspaces only; omitted whe… - [ ] app-name Codex app name - [ ] project-name Project name (falls back to current directory name) - [ ] current-dir Current working directory - [ ] activity Spinner while working, action-required message while blocked - [ ] run-state Compact session run-state text (Ready, Working, Thinking) - [ ] thread-name Current thread name (omitted when unnamed) -↓ - 5.2 credits | ~$1.82 - space toggle Β· ←/β†’ reorder Β· enter save Β· esc cancel diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu.snap deleted file mode 100644 index 672e7409..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu.snap +++ /dev/null @@ -1,12 +0,0 @@ ---- -source: tui/src/chatwidget/tests/usage.rs -expression: "render_bottom_popup(&chat, 80)" ---- - Usage - Account usage and resets. - - -β€Ί 1. View analytics Usage history - 2. Redeem reset 2 available - - enter open Β· esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_before_reset_refresh.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_before_reset_refresh.snap deleted file mode 100644 index 61c55cad..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_before_reset_refresh.snap +++ /dev/null @@ -1,12 +0,0 @@ ---- -source: tui/src/chatwidget/tests/usage.rs -expression: "render_bottom_popup(&chat, 80)" ---- - Usage - Account usage and resets. - - -β€Ί 1. View analytics Usage history - 2. Redeem reset Check availability - - enter open Β· esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_narrow.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_narrow.snap deleted file mode 100644 index e8b702d1..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_narrow.snap +++ /dev/null @@ -1,12 +0,0 @@ ---- -source: tui/src/chatwidget/tests/usage.rs -expression: "render_bottom_popup(&chat, 40)" ---- - Usage - Account usage and resets. - - -β€Ί 1. View analytics - 2. Redeem reset - - enter open Β· esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_without_resets.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_without_resets.snap deleted file mode 100644 index 32735af3..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_menu_without_resets.snap +++ /dev/null @@ -1,12 +0,0 @@ ---- -source: tui/src/chatwidget/tests/usage.rs -expression: "render_bottom_popup(&chat, 80)" ---- - Usage - Account usage and resets. - - -β€Ί 1. View analytics Usage history - Redeem reset None available - - enter open Β· esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_with_invalid_view_reports_usage.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_with_invalid_view_reports_usage.snap deleted file mode 100644 index bd4615eb..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__usage_command_with_invalid_view_reports_usage.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tui/src/chatwidget/tests/slash_commands.rs -expression: rendered ---- -β–  Usage: /usage [daily|weekly|cumulative] diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_member_credits_depleted_prompt.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_member_credits_depleted_prompt.snap deleted file mode 100644 index 5f7f210a..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_member_credits_depleted_prompt.snap +++ /dev/null @@ -1,12 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_and_layout.rs -expression: popup ---- - You've reached your workspace credit limit - Your workspace is out of credits. Ask your workspace owner to add more. Notify owner? - - - 1. Yes (y) -β€Ί 2. No (default) (n) - - enter select Β· esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_member_usage_limit_prompt.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_member_usage_limit_prompt.snap deleted file mode 100644 index 3d99f588..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_member_usage_limit_prompt.snap +++ /dev/null @@ -1,12 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_and_layout.rs -expression: popup ---- - Usage limit reached - Request a limit increase from your owner to continue using codex. Request increase? - - - 1. Yes (y) -β€Ί 2. No (default) (n) - - enter select Β· esc back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_credits_nudge_completion_feedback.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_credits_nudge_completion_feedback.snap deleted file mode 100644 index e2b0885e..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_credits_nudge_completion_feedback.snap +++ /dev/null @@ -1,11 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_and_layout.rs -expression: "rendered_cases.join(\"\\n---\\n\")" ---- -β€’ Workspace owner notified. - ---- -β€’ Workspace owner was already notified recently. - ---- -β€’ Could not notify your workspace owner. Please try again. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_limit_state_messages.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_limit_state_messages.snap deleted file mode 100644 index b3c1022a..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_limit_state_messages.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_and_layout.rs -expression: "rendered_cases.join(\"\\n---\\n\")" ---- -β–  You're out of credits. Your workspace is out of credits. Add credits to continue using Codex. - ---- -β–  Usage limit reached. You've reached your usage limit. Increase your limits to continue using codex. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_usage_limit_nudge_completion_feedback.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_usage_limit_nudge_completion_feedback.snap deleted file mode 100644 index 8091deeb..00000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__workspace_owner_usage_limit_nudge_completion_feedback.snap +++ /dev/null @@ -1,11 +0,0 @@ ---- -source: tui/src/chatwidget/tests/status_and_layout.rs -expression: "rendered_cases.join(\"\\n---\\n\")" ---- -β€’ Limit increase requested. - ---- -β€’ A limit increase was already requested recently. - ---- -β€’ Could not request a limit increase. Please try again. diff --git a/codex-rs/tui/src/chatwidget/startup_submission.rs b/codex-rs/tui/src/chatwidget/startup_submission.rs index a04d1314..9304454d 100644 --- a/codex-rs/tui/src/chatwidget/startup_submission.rs +++ b/codex-rs/tui/src/chatwidget/startup_submission.rs @@ -53,7 +53,6 @@ impl ChatWidget { || self.is_plan_streaming_in_tui() || self.is_user_turn_pending_or_running() || self.input_queue.submissions_paused() - || self.input_queue.rate_limit_recovery_pending || self.input_queue.recovered_queue || self.input_queue.has_unconfirmed_messages() { diff --git a/codex-rs/tui/src/chatwidget/status_controls.rs b/codex-rs/tui/src/chatwidget/status_controls.rs index 4d947a95..908d255c 100644 --- a/codex-rs/tui/src/chatwidget/status_controls.rs +++ b/codex-rs/tui/src/chatwidget/status_controls.rs @@ -6,7 +6,6 @@ use super::*; use crate::bottom_pane::footer_content::FooterContent; -use crate::status::thread_cost_micros; impl ChatWidget { /// Update the status indicator header and details. @@ -209,11 +208,7 @@ impl ChatWidget { self.refresh_status_surfaces(); } - pub(crate) fn add_status_output( - &mut self, - refreshing_rate_limits: bool, - request_id: Option, - ) { + pub(crate) fn add_status_output(&mut self) { let default_usage = TokenUsage::default(); let token_info = self.token_info.as_ref(); let total_usage = token_info @@ -245,7 +240,6 @@ impl ChatWidget { crate::status::compose_agents_summary(&self.config, &self.instruction_source_paths); let (cell, handle) = crate::status::new_status_output_with_rate_limits_handle( &self.config, - self.requires_openai_auth, self.thread_id .map(|_| self.config.model_provider_id.as_str()), self.remote_connection.as_ref(), @@ -262,20 +256,8 @@ impl ChatWidget { collaboration_mode, reasoning_effort_override, agents_summary, - refreshing_rate_limits, ); - if let Some(request_id) = request_id { - self.refreshing_status_outputs - .push((request_id, handle.clone())); - } - if self.thread_usage_is_available() { - handle.reserve_thread_usage_label_width(); - handle.set_thread_usage(self.estimated_thread_usage().cloned()); - self.add_to_history(cell); - self.request_thread_usage_for_status(handle.clone()); - } else { - self.add_to_history(cell); - } + self.add_to_history(cell); // Capture the displayed status inputs before later configuration or thread changes. let mut copy_targets = vec![ ("Model".to_string(), Arc::::from(model)), @@ -296,45 +278,6 @@ impl ChatWidget { }); } - pub(crate) fn finish_status_rate_limit_refresh( - &mut self, - request_id: u64, - snapshots: Vec, - ) { - if !self - .refreshing_status_outputs - .iter() - .any(|(pending_request_id, _)| *pending_request_id == request_id) - { - return; - } - - for snapshot in snapshots { - self.on_rate_limit_snapshot(Some(snapshot)); - } - - let rate_limit_snapshots: Vec = self - .rate_limit_snapshots_by_limit_id - .values() - .cloned() - .collect(); - let now = Local::now(); - let mut remaining = Vec::with_capacity(self.refreshing_status_outputs.len()); - let mut updated_any = false; - for (pending_request_id, handle) in self.refreshing_status_outputs.drain(..) { - if pending_request_id == request_id { - updated_any = true; - handle.finish_rate_limit_refresh(rate_limit_snapshots.as_slice(), now); - } else { - remaining.push((pending_request_id, handle)); - } - } - self.refreshing_status_outputs = remaining; - if updated_any { - self.request_redraw(); - } - } - pub(super) fn open_status_line_setup(&mut self) { let configured_status_line_items = self.configured_status_line_items(); let view = StatusLineSetupView::new( @@ -381,13 +324,6 @@ impl ChatWidget { } } - if self - .estimated_thread_usage() - .is_some_and(|usage| thread_cost_micros(usage, self.plan_type).is_none()) - { - preview_data.suppress_placeholder(StatusSurfacePreviewItem::EstimatedThreadCost); - } - preview_data } diff --git a/codex-rs/tui/src/chatwidget/status_surfaces.rs b/codex-rs/tui/src/chatwidget/status_surfaces.rs index 00822bd4..53a74e55 100644 --- a/codex-rs/tui/src/chatwidget/status_surfaces.rs +++ b/codex-rs/tui/src/chatwidget/status_surfaces.rs @@ -10,10 +10,7 @@ use crate::chatwidget::limit_label_for_window; use crate::chatwidget::rate_limits::get_limits_duration; use crate::legacy_core::config::Config; use crate::model_catalog::LUNA_RESERVE_MODEL; -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::terminal_program_status::ProgramStatus; use codex_app_server_protocol::AskForApproval; use codex_config::ConfigLayerSource; @@ -74,24 +71,6 @@ impl StatusSurfaceSelections { .contains(&StatusLineItem::BranchChanges) } - fn uses_workspace_headline(&self) -> bool { - self.status_line_items - .contains(&StatusLineItem::WorkspaceHeadline) - } - - fn uses_thread_usage(&self) -> bool { - self.status_line_items.iter().any(|item| { - matches!( - item, - StatusLineItem::ThreadCredits | StatusLineItem::EstimatedThreadCost - ) - }) || self.terminal_title_items.iter().any(|item| { - matches!( - item, - TerminalTitleItem::ThreadCredits | TerminalTitleItem::EstimatedThreadCost - ) - }) - } } /// Cached project-root display name keyed by the cwd used for the last lookup. @@ -185,20 +164,6 @@ impl ChatWidget { } } - if !selections.uses_workspace_headline() { - self.status_line_workspace_headline = None; - self.status_line_workspace_headline_pending_request_id = None; - self.status_line_workspace_headline_last_requested_at = None; - self.status_line_workspace_messages_disabled = false; - } else { - self.request_status_line_workspace_headline_if_due(Instant::now()); - } - - if selections.uses_thread_usage() { - self.ensure_thread_usage_requested(); - } else { - self.cancel_thread_usage_polling(); - } } fn refresh_status_line_from_selections(&mut self, selections: &StatusSurfaceSelections) { @@ -637,85 +602,6 @@ impl ChatWidget { }); } - fn request_status_line_workspace_headline_if_due(&mut self, now: Instant) { - if !self.status_line_workspace_headline_should_fetch(now) { - return; - } - let request_id = self.next_status_line_workspace_headline_request_id; - self.next_status_line_workspace_headline_request_id = self - .next_status_line_workspace_headline_request_id - .wrapping_add(/*rhs*/ 1); - self.status_line_workspace_headline_pending_request_id = Some(request_id); - self.status_line_workspace_headline_last_requested_at = Some(now); - self.app_event_tx - .send(AppEvent::RefreshStatusLineWorkspaceHeadline { request_id }); - } - - fn status_line_workspace_headline_should_fetch(&self, now: Instant) -> bool { - if self - .status_line_workspace_headline_pending_request_id - .is_some() - || self.status_line_workspace_messages_disabled - || !self.has_codex_backend_auth - { - return false; - } - - self.status_line_workspace_headline_last_requested_at - .is_none_or(|last_requested_at| { - now.saturating_duration_since(last_requested_at) - >= crate::workspace_messages::WORKSPACE_HEADLINE_REFRESH_INTERVAL - }) - } - - pub(super) fn refresh_status_line_if_workspace_headline_due(&mut self) { - let now = Instant::now(); - if self.status_line_workspace_headline_should_fetch(now) - && self - .status_line_items_with_invalids() - .0 - .contains(&StatusLineItem::WorkspaceHeadline) - { - self.refresh_status_line(); - } - } - - pub(crate) fn set_status_line_workspace_headline( - &mut self, - request_id: u64, - result: Result, - ) -> bool { - if self.status_line_workspace_headline_pending_request_id != Some(request_id) { - return false; - } - self.status_line_workspace_headline_pending_request_id = None; - match result { - Ok(crate::workspace_messages::WorkspaceHeadlineFetchResult::Available(headline)) => { - self.status_line_workspace_messages_disabled = false; - self.status_line_workspace_headline = headline; - } - Ok(crate::workspace_messages::WorkspaceHeadlineFetchResult::FeatureDisabled) => { - self.status_line_workspace_messages_disabled = true; - self.status_line_workspace_headline = None; - } - Err(err) => { - tracing::debug!(error = %err, "failed to fetch workspace headline"); - } - } - - if !self.status_line_workspace_messages_disabled - && self - .status_line_items_with_invalids() - .0 - .contains(&StatusLineItem::WorkspaceHeadline) - { - self.frame_requester - .schedule_frame_in(crate::workspace_messages::WORKSPACE_HEADLINE_REFRESH_INTERVAL); - } - self.refresh_status_line(); - true - } - /// Resolves a display string for one configured status-line item. /// /// Returning `None` means "omit this item for now", not "configuration error". Callers rely on @@ -811,15 +697,6 @@ impl ChatWidget { format_tokens_compact(self.status_line_total_usage().output_tokens) ) }), - StatusLineItem::ThreadCredits => self - .estimated_thread_usage() - .filter(|_| self.plan_type != Some(PlanType::Ent26)) - .map(|usage| usage.estimated_usage_credits_micros) - .map(|credits| format!("{} credits", format_credit_micros(credits))), - StatusLineItem::EstimatedThreadCost => self - .estimated_thread_usage() - .and_then(|usage| thread_cost_micros(usage, self.plan_type)) - .and_then(format_estimated_usd_micros), StatusLineItem::SessionId => self.thread_id.map(|id| id.to_string()), StatusLineItem::FastMode => Some( self.processing_tier_display_name() @@ -842,7 +719,6 @@ impl ChatWidget { .as_deref() .and_then(normalize_thread_name) .or_else(|| self.thread_id.map(|id| id.to_string())), - StatusLineItem::WorkspaceHeadline => self.status_line_workspace_headline.clone(), StatusLineItem::TaskProgress => self.terminal_title_task_progress(), } } @@ -882,13 +758,10 @@ impl ChatWidget { StatusSurfacePreviewItem::UsedTokens => StatusLineItem::UsedTokens, StatusSurfacePreviewItem::TotalInputTokens => StatusLineItem::TotalInputTokens, StatusSurfacePreviewItem::TotalOutputTokens => StatusLineItem::TotalOutputTokens, - StatusSurfacePreviewItem::ThreadCredits => StatusLineItem::ThreadCredits, - StatusSurfacePreviewItem::EstimatedThreadCost => StatusLineItem::EstimatedThreadCost, StatusSurfacePreviewItem::SessionId => StatusLineItem::SessionId, StatusSurfacePreviewItem::FastMode => StatusLineItem::FastMode, StatusSurfacePreviewItem::Daybreak => StatusLineItem::Daybreak, StatusSurfacePreviewItem::RawOutput => StatusLineItem::RawOutput, - StatusSurfacePreviewItem::WorkspaceHeadline => StatusLineItem::WorkspaceHeadline, StatusSurfacePreviewItem::Model => StatusLineItem::ModelName, StatusSurfacePreviewItem::ModelWithReasoning => StatusLineItem::ModelWithReasoning, StatusSurfacePreviewItem::Reasoning => StatusLineItem::Reasoning, @@ -951,12 +824,6 @@ impl ChatWidget { TerminalTitleItem::TotalOutputTokens => self .status_line_value_for_item(StatusLineItem::TotalOutputTokens) .map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)), - TerminalTitleItem::ThreadCredits => self - .status_line_value_for_item(StatusLineItem::ThreadCredits) - .map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)), - TerminalTitleItem::EstimatedThreadCost => self - .status_line_value_for_item(StatusLineItem::EstimatedThreadCost) - .map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)), TerminalTitleItem::SessionId => self .status_line_value_for_item(StatusLineItem::SessionId) .map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)), diff --git a/codex-rs/tui/src/chatwidget/streaming.rs b/codex-rs/tui/src/chatwidget/streaming.rs index fdf5fda1..3c81641d 100644 --- a/codex-rs/tui/src/chatwidget/streaming.rs +++ b/codex-rs/tui/src/chatwidget/streaming.rs @@ -81,7 +81,6 @@ impl ChatWidget { self.app_event_tx .send(AppEvent::ConsolidateProposedPlan(source)); } - self.request_pending_usage_output_insertion_after_stream_shutdown(); } } @@ -161,9 +160,6 @@ impl ChatWidget { if had_stream_controller && self.stream_controllers_idle() { self.app_event_tx.send(AppEvent::StopCommitAnimation); } - if had_stream_controller { - self.request_pending_usage_output_insertion_after_stream_shutdown(); - } if completed_message.is_some() { self.transcript.active_streamed_agent_message = None; self.transcript.last_flushed_agent_message = None; @@ -394,7 +390,6 @@ impl ChatWidget { if should_restore_after_stream { self.status_state.pending_status_indicator_restore = true; self.maybe_restore_status_indicator_after_stream_idle(); - self.request_pending_usage_output_insertion_after_stream_shutdown(); } } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 42f292b5..c1a2950f 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -27,8 +27,6 @@ pub(super) use crate::token_usage::TokenUsage; pub(super) use crate::token_usage::TokenUsageInfo; pub(super) use crate::tui::FrameRequester; pub(super) use assert_matches::assert_matches; -pub(super) use codex_app_server_protocol::AddCreditsNudgeCreditType; -pub(super) use codex_app_server_protocol::AddCreditsNudgeEmailStatus; pub(super) use codex_app_server_protocol::AdditionalFileSystemPermissions as AppServerAdditionalFileSystemPermissions; pub(super) use codex_app_server_protocol::AdditionalNetworkPermissions as AppServerAdditionalNetworkPermissions; pub(super) use codex_app_server_protocol::AdditionalPermissionProfile as AppServerAdditionalPermissionProfile; @@ -228,8 +226,6 @@ fn next_goal_draft( mod app_server; mod approval_requests; -#[path = "tests/backend_banners_tests.rs"] -mod backend_banners_tests; #[path = "tests/bedrock_catalog_tests.rs"] mod bedrock_catalog_tests; #[path = "tests/collaboration_catalog_tests.rs"] @@ -257,8 +253,6 @@ mod history_projection; mod history_replay; #[path = "tests/home_cleanup_tests.rs"] mod home_cleanup_tests; -#[path = "tests/luna_reserve_usage_tests.rs"] -mod luna_reserve_usage_tests; mod mcp_startup; #[path = "tests/misalignment_policy_tests.rs"] mod misalignment_policy; @@ -277,8 +271,6 @@ mod plugin_catalog; mod popups_and_settings; #[path = "tests/program_status.rs"] mod program_status; -#[path = "tests/rate_limit_recovery_tests.rs"] -mod rate_limit_recovery_tests; #[path = "tests/reasoning_status_tests.rs"] mod reasoning_status_tests; #[path = "tests/replay_render_tests.rs"] @@ -308,7 +300,6 @@ mod terminal_program_status; mod terminal_title; #[path = "tests/tool_activity_tests.rs"] mod tool_activity_tests; -mod usage; #[path = "tests/worktree_picker_tests.rs"] mod worktree_picker; diff --git a/codex-rs/tui/src/chatwidget/tests/app_server.rs b/codex-rs/tui/src/chatwidget/tests/app_server.rs index e8db7d8f..bf9b1084 100644 --- a/codex-rs/tui/src/chatwidget/tests/app_server.rs +++ b/codex-rs/tui/src/chatwidget/tests/app_server.rs @@ -119,9 +119,7 @@ async fn session_and_settings_sync_server_provider_id() { chat.refresh_status_line(); assert_eq!(status_line_text(&chat), None); let status = |chat: &mut ChatWidget| { - chat.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); + chat.add_status_output(); chat.transcript .last_status_copy_targets .as_ref() diff --git a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs index 3b96b621..21172556 100644 --- a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs +++ b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs @@ -3001,7 +3001,6 @@ async fn image_preparation_failure_restores_full_input_without_submitting() { fn image_preparation_keeps_input_responsive_and_preserves_pending_input() { for scenario in [ "thread_switch", - "rate_limit_recovery", "model_change", "disconnect", "interrupt", @@ -3060,23 +3059,7 @@ fn image_preparation_keeps_input_responsive_and_preserves_pending_input() { break id; } }; - if scenario == "rate_limit_recovery" { - chat.input_queue.rate_limit_recovery_pending = true; - chat.on_images_prepared(id); - std::fs::remove_file(&message.local_images[0].path).unwrap(); - assert_eq!( - chat.input_queue - .queued_user_messages - .iter() - .map(|queued| queued.user_message.clone()) - .collect::>(), - vec![message, UserMessage::from("x")], - ); - chat.input_queue.rate_limit_recovery_pending = false; - assert!(chat.maybe_send_next_queued_input()); - assert_matches!(next_submit_op(&mut ops), Op::UserTurn { items, .. } - if matches!(items.first(), Some(UserInput::Image { .. }))); - } else if scenario == "model_change" { + if scenario == "model_change" { chat.handle_paste("new draft".into()); let mut models = chat.model_catalog.try_list_models().unwrap(); for model in &mut models { diff --git a/codex-rs/tui/src/chatwidget/tests/security_setup_tests.rs b/codex-rs/tui/src/chatwidget/tests/security_setup_tests.rs index b6fadbf1..17e14ef3 100644 --- a/codex-rs/tui/src/chatwidget/tests/security_setup_tests.rs +++ b/codex-rs/tui/src/chatwidget/tests/security_setup_tests.rs @@ -65,63 +65,6 @@ async fn security_setup_preserves_draft_action_and_dismissal_across_widgets() { assert!(render_bottom_popup(&replacement, /*width*/ 70).contains("Set up security")); } -#[tokio::test] -async fn security_setup_dismissal_survives_usage_banner_replacement() { - for dismiss_security in [true, false] { - let (mut chat, _events, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - chat.show_security_setup(setup_identity(), setup_notice()); - assert!(render_bottom_popup(&chat, /*width*/ 70).contains("Set up security")); - if dismiss_security { - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - } - - let response = codex_app_server_protocol::GetAccountRateLimitsResponse { - ordinary_usage_allowed: None, - account_id: Some("account".into()), - rate_limit_upsell: Some(json!({ - "banner_type": "selected_model_limit", "model_slug": "test-model-a", - "title": "Selected model usage exhausted", "description": "Switch models.", - "presentation": "dismissible", "ctas": [], - })), - rate_limits: snapshot(/*percent*/ 100.0), - rate_limits_by_limit_id: None, - rate_limit_reset_credits: None, - }; - chat.update_backend_banner(&response); - assert!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted") - ); - if !dismiss_security { - // Dismissing usage must not dismiss the security reminder instead. - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - } - - // Account refresh must not read the replacement banner's dismissal state. - chat.invalidate_security_setup(); - chat.clear_backend_banner(); - chat.show_security_setup(setup_identity(), setup_notice()); - let rendered = normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 70)); - assert_eq!(rendered.contains("Set up security"), !dismiss_security); - if dismiss_security { - insta::assert_snapshot!("security_setup_dismissed_after_usage", rendered); - } - - let (mut replacement, _events, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - replacement.inherit_security_setup(&mut chat); - replacement.invalidate_security_setup(); - replacement.show_security_setup(setup_identity(), setup_notice()); - assert_eq!( - render_bottom_popup(&replacement, /*width*/ 70).contains("Set up security"), - !dismiss_security - ); - - // A fresh CLI run has no inherited dismissal and reminds the same eligible user. - let (mut fresh, _events, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - fresh.show_security_setup(setup_identity(), setup_notice()); - assert!(render_bottom_popup(&fresh, /*width*/ 70).contains("Set up security")); - } -} - #[tokio::test] async fn security_setup_after_cutoff_wraps_in_narrow_terminal() { let (mut chat, _events, _ops) = make_chatwidget_manual(Some("test-model-a")).await; @@ -147,44 +90,3 @@ async fn security_setup_after_persona_grace_wraps_in_narrow_terminal() { normalize_snapshot_paths(render_bottom_popup(&chat, /*width*/ 48)) ); } - -#[tokio::test] -async fn security_setup_respects_applicable_backend_banner() { - for state in ["visible", "dismissed", "another-model"] { - let (mut chat, _events, _ops) = make_chatwidget_manual(Some("test-model-a")).await; - let response = codex_app_server_protocol::GetAccountRateLimitsResponse { - ordinary_usage_allowed: None, - account_id: Some("workspace-a".into()), - rate_limit_upsell: Some(json!({ - "banner_type": "selected_model_limit", "model_slug": "test-model-a", - "title": "Selected model usage exhausted", "description": "Switch models.", - "presentation": "dismissible", "ctas": [], - })), - rate_limits: snapshot(/*percent*/ 25.0), - rate_limits_by_limit_id: None, - rate_limit_reset_credits: None, - }; - chat.update_backend_banner(&response); - render_bottom_popup(&chat, /*width*/ 70); - match state { - "dismissed" => { - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - } - "another-model" => chat.set_model("test-model-b"), - "visible" => {} - _ => unreachable!(), - } - chat.show_security_setup(setup_identity(), setup_notice()); - assert_eq!( - render_bottom_popup(&chat, /*width*/ 70).contains("Set up security"), - state != "visible" - ); - if state == "another-model" { - chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - chat.set_model("test-model-a"); - assert!( - render_bottom_popup(&chat, /*width*/ 70).contains("Selected model usage exhausted") - ); - } - } -} diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index 54320008..8d5a0ed8 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -1421,119 +1421,6 @@ async fn usage_error_slash_command_is_available_from_local_recall() { assert_eq!(recall_latest_after_clearing(&mut chat), "/raw maybe"); } -#[tokio::test] -async fn signed_out_usage_command_reports_chatgpt_login_requirement() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - - submit_composer_text(&mut chat, "/usage"); - - let cells = drain_insert_history(&mut rx); - let rendered = cells - .iter() - .map(|cell| lines_to_single_string(cell)) - .collect::>() - .join("\n"); - assert_chatwidget_snapshot!( - "signed_out_usage_command_reports_chatgpt_login_requirement", - rendered - ); - assert_eq!(recall_latest_after_clearing(&mut chat), "/usage"); -} - -#[tokio::test] -async fn signed_out_usage_command_with_args_reports_chatgpt_login_requirement() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - - submit_composer_text(&mut chat, "/usage weekly"); - - let cells = drain_insert_history(&mut rx); - let rendered = cells - .iter() - .map(|cell| lines_to_single_string(cell)) - .collect::>() - .join("\n"); - assert!( - rendered.contains("Sign in with ChatGPT to use /usage."), - "expected ChatGPT login requirement, got: {rendered:?}" - ); - assert_eq!(recall_latest_after_clearing(&mut chat), "/usage weekly"); -} - -#[tokio::test] -async fn usage_command_with_invalid_view_reports_usage_snapshot() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - - submit_composer_text(&mut chat, "/usage monthly"); - - let rendered = drain_insert_history(&mut rx) - .iter() - .map(|cell| lines_to_single_string(cell)) - .collect::>() - .join("\n"); - assert_chatwidget_snapshot!("usage_command_with_invalid_view_reports_usage", rendered); - assert_eq!(recall_latest_after_clearing(&mut chat), "/usage monthly"); -} - -#[tokio::test] -async fn usage_views_open_the_requested_summary_mode() { - use crate::analytics::TokenActivityView; - for (argument, expected) in [ - ("daily", TokenActivityView::Daily), - ("weekly", TokenActivityView::Weekly), - ("cumulative", TokenActivityView::Cumulative), - ] { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - chat.dispatch_command_with_args(SlashCommand::Usage, argument.to_string(), Vec::new()); - match rx.try_recv().unwrap() { - AppEvent::OpenAnalytics { view } => assert_eq!(view, Some(expected)), - other => panic!("expected Analytics, got {other:?}"), - } - } -} - -#[tokio::test] -async fn usage_command_runs_with_backend_auth_without_chatgpt_account_flag() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ true, - ); - - chat.dispatch_command_with_args(SlashCommand::Usage, "daily".to_string(), Vec::new()); - - assert_matches!( - rx.try_recv(), - Ok(AppEvent::OpenAnalytics { - view: Some(crate::analytics::TokenActivityView::Daily) - }) - ); - assert!(!chat.has_chatgpt_account()); -} - -#[tokio::test] -async fn usage_command_runs_with_backend_auth_from_widget_init() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual_with_auth( - /*model_override*/ None, - /*has_chatgpt_account*/ false, - /*has_codex_backend_auth*/ true, - FrameRequester::test_dummy(), - ) - .await; - - chat.dispatch_command_with_args(SlashCommand::Usage, "daily".to_string(), Vec::new()); - - assert_matches!( - rx.try_recv(), - Ok(AppEvent::OpenAnalytics { - view: Some(crate::analytics::TokenActivityView::Daily) - }) - ); - assert!(!chat.has_chatgpt_account()); - assert!(chat.has_codex_backend_auth()); -} - #[tokio::test] async fn unrecognized_slash_command_is_not_added_to_local_recall() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -1982,7 +1869,6 @@ async fn slash_copy_status_yields_to_later_turns_and_commands_even_after_refresh NextTurn::ServiceTier => chat.handle_service_tier_command_dispatch(fast_tier_command()), NextTurn::ShellCommand => chat.submit_user_message(UserMessage::from("!echo hello")), } - chat.finish_status_rate_limit_refresh(/*request_id*/ 0, Vec::new()); drain_insert_history(&mut rx); chat.dispatch_command(SlashCommand::Copy); chat.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_information_dismissible.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_information_dismissible.snap deleted file mode 100644 index dd73e1cf..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_information_dismissible.snap +++ /dev/null @@ -1,14 +0,0 @@ ---- -source: tui/src/chatwidget/tests/backend_banners_tests.rs -assertion_line: 66 -expression: rendered ---- - Selected model usage exhausted - Ask your owner for credits or switch to another model. - - esc to dismiss Β· type to continue - - -β€Ί Ask Codex to do anything - - test-model-a default Β· /tmp/project diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_information_only.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_information_only.snap deleted file mode 100644 index af451575..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_information_only.snap +++ /dev/null @@ -1,12 +0,0 @@ ---- -source: tui/src/chatwidget/tests/backend_banners_tests.rs -assertion_line: 62 -expression: rendered ---- - Selected model usage exhausted - Ask your owner for credits or switch to another model. - - -β€Ί Ask Codex to do anything - - test-model-a default Β· /tmp/project diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_notification.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_notification.snap deleted file mode 100644 index eecda45a..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__backend_banner_notification.snap +++ /dev/null @@ -1,14 +0,0 @@ ---- -source: tui/src/chatwidget/tests/backend_banners_tests.rs -expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 70))" ---- - Selected model usage exhausted - Your usage resets at 5:30 PM. Ask your owner for credits. - -β€Ί 1. Notify owner - - Press a number to choose - -β€Ί Ask Codex to do anything - - test-model-a default Β· /tmp/project diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__owner_notification_after_account_change.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__owner_notification_after_account_change.snap deleted file mode 100644 index 94013f08..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__backend_banners_tests__owner_notification_after_account_change.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tui/src/chatwidget/tests/backend_banners_tests.rs -expression: rendered ---- -β€’ Limit increase requested. diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_selector_second_choice.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_selector_second_choice.snap deleted file mode 100644 index ce5f75ef..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_selector_second_choice.snap +++ /dev/null @@ -1,13 +0,0 @@ ---- -source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs -expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 90))" ---- - You’re now using Luna, a faster model for simpler tasks. - Add credits or upgrade to continue using the most advanced models. - - - 1. Add credits -β€Ί 2. Upgrade - 3. Continue with Luna Reserve - - Press enter to confirm or esc to continue working diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_narrow.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_narrow.snap deleted file mode 100644 index 0644d12b..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_narrow.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs -expression: "render_bottom_popup(&chat, 34)" ---- - -β€Ί Ask Codex to do anything - - Luna Reserve default Β· /tmp/pro… diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_running.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_running.snap deleted file mode 100644 index 4f4664d1..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_running.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs -expression: rendered ---- -β€’ Working (0s β€’ esc to interrupt) - - -β€Ί x - - tab to queue message 100% context left diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_wide.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_wide.snap deleted file mode 100644 index d6537e35..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_wide.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs -expression: rendered ---- - -β€Ί Ask Codex to do anything - - Luna Reserve default Β· /tmp/project diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_with_upsell.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_with_upsell.snap deleted file mode 100644 index d5ff3b8e..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__luna_reserve_usage_tests__luna_reserve_usage_with_upsell.snap +++ /dev/null @@ -1,13 +0,0 @@ ---- -source: tui/src/chatwidget/tests/luna_reserve_usage_tests.rs -expression: "normalize_snapshot_paths(render_bottom_popup(&chat, 80))" ---- - You’re now using Luna, a faster model for simpler tasks. - Add credits or upgrade to continue using the most advanced models. - - -β€Ί 1. Add credits - 2. Upgrade - 3. Continue with Luna Reserve - - Press enter to confirm or esc to continue working diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__security_setup_tests__security_setup_dismissed_after_usage.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__security_setup_tests__security_setup_dismissed_after_usage.snap deleted file mode 100644 index 77b7fbd6..00000000 --- a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__security_setup_tests__security_setup_dismissed_after_usage.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: tui/src/chatwidget/tests/security_setup_tests.rs -expression: rendered ---- -β€Ί Ask Codex to do anything - - test-model-a default Β· /tmp/project diff --git a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs index 9074c5ec..5ce23508 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs @@ -1,12 +1,9 @@ use super::helpers::drain_insert_history_transcript; use super::*; use crate::bottom_pane::goal_status_indicator_line; -use crate::chatwidget::ThreadUsageOutcome; use crate::chatwidget::rate_limits::NUDGE_MODEL_SLUG; use crate::chatwidget::rate_limits::get_limits_duration; use crate::chatwidget::realtime::tests::activate_voice_for_thread; -use codex_app_server_protocol::SpendControlLimitSnapshot; -use codex_app_server_protocol::ThreadUsage; use pretty_assertions::assert_eq; use ratatui::Terminal; use ratatui::backend::TestBackend; @@ -47,15 +44,6 @@ fn enable_test_ambient_pet(chat: &mut ChatWidget) { chat.install_test_ambient_pet_for_tests(/*animations_enabled*/ false); } -fn take_workspace_headline_request_id( - rx: &mut tokio::sync::mpsc::UnboundedReceiver, -) -> u64 { - match rx.try_recv() { - Ok(AppEvent::RefreshStatusLineWorkspaceHeadline { request_id }) => request_id, - event => panic!("expected workspace headline refresh, got {event:?}"), - } -} - /// Receiving a token usage update without usage clears the context indicator. #[tokio::test] async fn token_count_none_resets_context_indicator() { @@ -158,12 +146,12 @@ async fn daybreak_refusal_offers_enable_for_the_next_turn() { }); chat.model_catalog = std::sync::Arc::new(ModelCatalog::new(vec![model])); - chat.thread_usage.replaying_turn_completion = true; + chat.replaying_turn_completion = true; chat.on_cyber_policy_error(); let cells = drain_insert_history(&mut events); assert!(lines_to_single_string(&cells[0]).contains("Daybreak is currently off")); assert!(chat.bottom_pane.no_modal_or_popup_active()); - chat.thread_usage.replaying_turn_completion = false; + chat.replaying_turn_completion = false; chat.daybreak_enabled = true; chat.on_cyber_policy_error(); @@ -323,9 +311,7 @@ async fn token_usage_update_uses_runtime_context_window() { ); assert_eq!(chat.bottom_pane.context_window_percent(), Some(100)); - chat.add_status_output( - /*refreshing_rate_limits*/ false, /*request_id*/ None, - ); + chat.add_status_output(); let cells = drain_insert_history(&mut rx); let context_line = cells @@ -673,26 +659,6 @@ async fn configured_pet_load_is_deferred_until_after_construction() { ); } -#[tokio::test] -async fn prefetch_rate_limits_is_gated_on_chatgpt_auth_provider() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - - assert!(!chat.should_prefetch_rate_limits()); - - // The server requires auth even if the local provider does not. - chat.config.model_provider.requires_openai_auth = false; - set_chatgpt_auth(&mut chat); - assert!(chat.should_prefetch_rate_limits()); - - // Conversely, a local OpenAI provider cannot enable usage for a different server. - chat.config.model_provider.requires_openai_auth = true; - chat.requires_openai_auth = false; - assert!(!chat.should_prefetch_rate_limits()); - - chat.prefetch_rate_limits(); - assert!(!chat.should_prefetch_rate_limits()); -} - #[tokio::test] async fn rate_limit_warnings_emit_thresholds() { let mut state = RateLimitWarningState::default(); @@ -748,7 +714,7 @@ async fn rate_limit_usage_warnings_early_threshold_is_scoped_and_deduplicated() // Rolling updates retain the plan learned from the account usage response. usage.plan_type = None; usage.primary.as_mut().unwrap().used_percent = 50; - chat.on_rolling_rate_limit_snapshot(usage.clone()); + chat.on_rate_limit_snapshot(Some(usage.clone())); let warnings = drain_insert_history_transcript(&mut rx); assert_eq!(!warnings.is_empty(), should_warn_early); if should_warn_early { @@ -760,13 +726,13 @@ async fn rate_limit_usage_warnings_early_threshold_is_scoped_and_deduplicated() } } - chat.on_rolling_rate_limit_snapshot(usage.clone()); + chat.on_rate_limit_snapshot(Some(usage.clone())); assert!(drain_insert_history_transcript(&mut rx).is_empty()); for used_percent in [75, 90, 95] { usage.primary.as_mut().unwrap().used_percent = used_percent; - chat.on_rolling_rate_limit_snapshot(usage.clone()); + chat.on_rate_limit_snapshot(Some(usage.clone())); assert_eq!(drain_insert_history_transcript(&mut rx).len(), 1); - chat.on_rolling_rate_limit_snapshot(usage.clone()); + chat.on_rate_limit_snapshot(Some(usage.clone())); assert!(drain_insert_history_transcript(&mut rx).is_empty()); } } @@ -1034,105 +1000,6 @@ async fn status_line_secondary_only_non_weekly_limit_omits_primary_limit_item() ); } -#[tokio::test] -async fn rate_limit_snapshot_keeps_prior_credits_when_missing_from_headers() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - - chat.on_rate_limit_snapshot(Some(RateLimitSnapshot { - limit_id: None, - limit_name: None, - normal_model_slug: None, - primary: Some(RateLimitWindow { - used_percent: 10, - window_duration_mins: Some(60), - resets_at: Some(123), - }), - secondary: None, - credits: Some(CreditsSnapshot { - has_credits: true, - unlimited: false, - balance: Some("17.5".to_string()), - }), - individual_limit: None, - plan_type: None, - spend_control_reached: None, - rate_limit_reached_type: None, - })); - let initial_balance = chat - .rate_limit_snapshots_by_limit_id - .get("codex") - .and_then(|snapshot| snapshot.credits.as_ref()) - .and_then(|credits| credits.balance.as_deref()); - assert_eq!(initial_balance, Some("17.5")); - - chat.on_rolling_rate_limit_snapshot(RateLimitSnapshot { - limit_id: None, - limit_name: None, - normal_model_slug: None, - primary: Some(RateLimitWindow { - used_percent: 80, - window_duration_mins: Some(60), - resets_at: Some(123), - }), - secondary: None, - credits: None, - individual_limit: None, - plan_type: None, - spend_control_reached: None, - rate_limit_reached_type: None, - }); - - let display = chat - .rate_limit_snapshots_by_limit_id - .get("codex") - .expect("rate limits should be cached"); - let credits = display - .credits - .as_ref() - .expect("credits should persist when headers omit them"); - - assert_eq!(credits.balance.as_deref(), Some("17.5")); - assert!(!credits.unlimited); - assert_eq!( - display.primary.as_ref().map(|window| window.used_percent), - Some(10.0) - ); -} - -#[tokio::test] -async fn rolling_rate_limit_snapshot_preserves_prior_individual_limit() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let mut usage_limits = snapshot(/*percent*/ 10.0); - usage_limits.individual_limit = Some(SpendControlLimitSnapshot { - limit: "25000".to_string(), - used: "8000".to_string(), - remaining_percent: 68, - resets_at: 1_800_000_000, - }); - chat.on_rate_limit_snapshot(Some(usage_limits)); - - chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 20.0)); - - let display = chat - .rate_limit_snapshots_by_limit_id - .get("codex") - .expect("rate limits should be cached"); - let individual_limit = display - .individual_limit - .as_ref() - .expect("rolling updates should preserve monthly limits"); - assert_eq!(individual_limit.used, "8,000"); - assert_eq!(individual_limit.limit, "25,000"); - assert_eq!(individual_limit.percent_remaining, 68.0); - - chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 30.0))); - let display = chat - .rate_limit_snapshots_by_limit_id - .get("codex") - .expect("rate limits should be cached"); - assert!(display.individual_limit.is_none()); -} - #[tokio::test] async fn rate_limit_snapshot_updates_and_retains_plan_type() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -1256,15 +1123,7 @@ async fn rate_limit_snapshots_keep_separate_entries_per_limit_id() { .expect("codex_other snapshot should exist"); assert_eq!(codex.primary.as_ref().map(|w| w.used_percent), Some(20.0)); - assert_eq!( - codex - .credits - .as_ref() - .and_then(|credits| credits.balance.as_deref()), - Some("5.00") - ); assert_eq!(other.primary.as_ref().map(|w| w.used_percent), Some(90.0)); - assert!(other.credits.is_none()); } #[tokio::test] @@ -1495,7 +1354,7 @@ async fn rate_limit_usage_warnings_preserve_workspace_limit_for_sparse_snapshots blocked_snapshot.rate_limit_reached_type = Some(rate_limit_reached_type); chat.on_rate_limit_snapshot(Some(blocked_snapshot)); - chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 95.0)); + chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0))); assert!( !drain_insert_history(&mut rx).is_empty(), @@ -1558,11 +1417,11 @@ async fn rate_limit_usage_warnings_keep_workspace_limit_after_rolling_credits() balance: None, }); blocked_snapshot.rate_limit_reached_type = Some(rate_limit_reached_type); - chat.on_rolling_rate_limit_snapshot(blocked_snapshot); + chat.on_rate_limit_snapshot(Some(blocked_snapshot)); let mut rolling_snapshot = snapshot(/*percent*/ 95.0); rolling_snapshot.credits = Some(credits); - chat.on_rolling_rate_limit_snapshot(rolling_snapshot); + chat.on_rate_limit_snapshot(Some(rolling_snapshot)); assert!( !drain_insert_history(&mut rx).is_empty(), @@ -1600,7 +1459,7 @@ async fn rate_limit_usage_warnings_keep_explicit_rolling_workspace_limit() { }); rolling_snapshot.rate_limit_reached_type = Some(rate_limit_reached_type); rolling_snapshot.spend_control_reached = spend_control_reached; - chat.on_rolling_rate_limit_snapshot(rolling_snapshot); + chat.on_rate_limit_snapshot(Some(rolling_snapshot)); assert!( !drain_insert_history(&mut rx).is_empty(), @@ -1618,54 +1477,6 @@ async fn rate_limit_usage_warnings_keep_explicit_rolling_workspace_limit() { } } -#[tokio::test] -async fn rate_limit_usage_warnings_keep_newly_reached_workspace_limit() { - for (limit_id, should_warn) in [("codex", true), ("codex_other", false)] { - let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await; - chat.has_chatgpt_account = true; - - let mut initial_snapshot = snapshot(/*percent*/ 0.0); - initial_snapshot.credits = Some(CreditsSnapshot { - has_credits: true, - unlimited: false, - balance: None, - }); - initial_snapshot.spend_control_reached = Some(false); - chat.on_rate_limit_snapshot(Some(initial_snapshot)); - - let mut capped_snapshot = snapshot(/*percent*/ 95.0); - capped_snapshot.limit_id = Some(limit_id.to_string()); - capped_snapshot.credits = Some(CreditsSnapshot { - has_credits: true, - unlimited: false, - balance: None, - }); - capped_snapshot.rate_limit_reached_type = - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached); - chat.on_rolling_rate_limit_snapshot(capped_snapshot); - - assert_eq!(!drain_insert_history(&mut rx).is_empty(), should_warn); - assert_eq!( - matches!( - chat.rate_limit_switch_prompt, - RateLimitSwitchPromptState::Pending - ), - should_warn - ); - assert_eq!( - chat.codex_rate_limit_reached_type, - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached) - ); - - chat.on_rate_limit_error( - RateLimitErrorKind::UsageLimit, - "Usage limit reached.".to_string(), - ); - let popup = render_bottom_popup(&chat, /*width*/ 100); - assert!(popup.contains("Request a limit increase from your owner")); - } -} - #[tokio::test] async fn rate_limit_usage_warnings_preserve_and_clear_spend_control_state() { let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await; @@ -1683,7 +1494,7 @@ async fn rate_limit_usage_warnings_preserve_and_clear_spend_control_state() { chat.on_rate_limit_snapshot(Some(blocked_snapshot)); assert_eq!(chat.codex_spend_control_reached, Some(true)); - chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 95.0)); + chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0))); assert!( !drain_insert_history(&mut rx).is_empty(), "a sparse rolling snapshot should preserve a reached spend control" @@ -1701,7 +1512,7 @@ async fn rate_limit_usage_warnings_preserve_and_clear_spend_control_state() { balance: None, }); recovered_snapshot.spend_control_reached = Some(false); - chat.on_rolling_rate_limit_snapshot(recovered_snapshot); + chat.on_rate_limit_snapshot(Some(recovered_snapshot)); assert!(drain_insert_history(&mut rx).is_empty()); assert!(matches!( @@ -1714,7 +1525,7 @@ async fn rate_limit_usage_warnings_preserve_and_clear_spend_control_state() { Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached) ); - chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 95.0)); + chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 95.0))); assert!( drain_insert_history(&mut rx).is_empty(), "a later sparse rolling snapshot should not clear an existing workspace hard stop" @@ -1730,81 +1541,6 @@ async fn rate_limit_usage_warnings_preserve_and_clear_spend_control_state() { ); } -#[tokio::test] -async fn rolling_credits_preserve_depleted_workspace_error_routing() { - let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await; - chat.has_chatgpt_account = true; - - let mut blocked_snapshot = snapshot(/*percent*/ 0.0); - blocked_snapshot.rate_limit_reached_type = - Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted); - chat.on_rate_limit_snapshot(Some(blocked_snapshot)); - - let mut rolling_snapshot = snapshot(/*percent*/ 95.0); - rolling_snapshot.credits = Some(CreditsSnapshot { - has_credits: true, - unlimited: false, - balance: Some("0".to_string()), - }); - rolling_snapshot.spend_control_reached = Some(false); - chat.on_rolling_rate_limit_snapshot(rolling_snapshot); - - assert!(!drain_insert_history(&mut rx).is_empty()); - assert!(matches!( - chat.rate_limit_switch_prompt, - RateLimitSwitchPromptState::Pending - )); - assert_eq!( - chat.codex_rate_limit_reached_type, - Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted) - ); - - chat.on_rate_limit_error( - RateLimitErrorKind::Generic, - "Usage limit reached.".to_string(), - ); - let popup = render_bottom_popup(&chat, /*width*/ 100); - assert!( - popup.contains("Ask your workspace owner to add more"), - "popup: {popup}" - ); -} - -#[tokio::test] -async fn rate_limit_usage_warnings_clear_workspace_limit_from_authoritative_snapshot() { - let (mut chat, mut rx, _) = make_chatwidget_manual(Some("gpt-5")).await; - chat.has_chatgpt_account = true; - - let mut blocked_snapshot = snapshot(/*percent*/ 0.0); - blocked_snapshot.credits = Some(CreditsSnapshot { - has_credits: true, - unlimited: false, - balance: None, - }); - blocked_snapshot.rate_limit_reached_type = - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached); - chat.on_rate_limit_snapshot(Some(blocked_snapshot)); - - let mut recovered_snapshot = snapshot(/*percent*/ 0.0); - recovered_snapshot.credits = Some(CreditsSnapshot { - has_credits: true, - unlimited: false, - balance: None, - }); - chat.on_rate_limit_snapshot(Some(recovered_snapshot)); - chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 95.0)); - - assert!( - drain_insert_history(&mut rx).is_empty(), - "an authoritative recovery should prevent sparse updates from restoring a stale limit" - ); - assert!(matches!( - chat.rate_limit_switch_prompt, - RateLimitSwitchPromptState::Idle - )); - assert_eq!(chat.codex_rate_limit_reached_type, None); -} - #[tokio::test] async fn rate_limit_switch_prompt_shows_once_per_session() { let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5")).await; @@ -1910,158 +1646,6 @@ async fn rate_limit_switch_prompt_popup_snapshot() { assert_chatwidget_snapshot!("rate_limit_switch_prompt_popup", popup); } -#[tokio::test] -async fn workspace_member_credits_depleted_prompts_and_sends_credits() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let mut limits = snapshot(/*percent*/ 100.0); - limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted); - chat.on_rate_limit_snapshot(Some(limits)); - - chat.on_rate_limit_error( - RateLimitErrorKind::Generic, - "Usage limit reached.".to_string(), - ); - let popup = render_bottom_popup(&chat, /*width*/ 90); - assert_chatwidget_snapshot!("workspace_member_credits_depleted_prompt", popup); - - chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); - let event = next_send_add_credits_nudge_email_event(&mut rx); - assert_eq!(event, AddCreditsNudgeCreditType::Credits); -} - -#[tokio::test] -async fn workspace_member_usage_limit_prompts_and_sends_usage_limit() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let mut limits = snapshot(/*percent*/ 100.0); - limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached); - chat.on_rate_limit_snapshot(Some(limits)); - - chat.on_rate_limit_error( - RateLimitErrorKind::UsageLimit, - "Usage limit reached.".to_string(), - ); - let popup = render_bottom_popup(&chat, /*width*/ 100); - assert_chatwidget_snapshot!("workspace_member_usage_limit_prompt", popup); - - chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); - let event = next_send_add_credits_nudge_email_event(&mut rx); - assert_eq!(event, AddCreditsNudgeCreditType::UsageLimit); -} - -#[tokio::test] -async fn sparse_rate_limit_snapshot_preserves_member_limit_type_for_error_prompt() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let mut usage_limits = snapshot(/*percent*/ 100.0); - usage_limits.rate_limit_reached_type = - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached); - chat.on_rate_limit_snapshot(Some(usage_limits)); - - let mut rolling_limits = snapshot(/*percent*/ 100.0); - rolling_limits.rate_limit_reached_type = None; - chat.on_rolling_rate_limit_snapshot(rolling_limits); - - chat.on_rate_limit_error( - RateLimitErrorKind::UsageLimit, - "Usage limit reached.".to_string(), - ); - let popup = render_bottom_popup(&chat, /*width*/ 100); - assert!( - popup.contains("Request a limit increase from your owner"), - "popup: {popup}" - ); - - chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); - let event = next_send_add_credits_nudge_email_event(&mut rx); - assert_eq!(event, AddCreditsNudgeCreditType::UsageLimit); -} - -#[tokio::test] -async fn usage_limit_error_remaps_stale_member_credits_state_to_usage_limit_prompt() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let mut limits = snapshot(/*percent*/ 100.0); - limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted); - chat.on_rate_limit_snapshot(Some(limits)); - - chat.on_rate_limit_error( - RateLimitErrorKind::UsageLimit, - "Usage limit reached.".to_string(), - ); - let popup = render_bottom_popup(&chat, /*width*/ 100); - assert!( - popup.contains("Request a limit increase from your owner"), - "popup: {popup}" - ); - - chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); - let event = next_send_add_credits_nudge_email_event(&mut rx); - assert_eq!(event, AddCreditsNudgeCreditType::UsageLimit); -} - -#[tokio::test] -async fn workspace_owner_limit_states_do_not_prompt_for_owner_nudge() { - for (limit_type, error_kind) in [ - ( - RateLimitReachedType::WorkspaceOwnerCreditsDepleted, - RateLimitErrorKind::Generic, - ), - ( - RateLimitReachedType::WorkspaceOwnerUsageLimitReached, - RateLimitErrorKind::UsageLimit, - ), - ( - RateLimitReachedType::RateLimitReached, - RateLimitErrorKind::Generic, - ), - ] { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let mut limits = snapshot(/*percent*/ 100.0); - limits.rate_limit_reached_type = Some(limit_type); - chat.on_rate_limit_snapshot(Some(limits)); - - chat.on_rate_limit_error(error_kind, "Usage limit reached.".to_string()); - let popup = render_bottom_popup(&chat, /*width*/ 90); - assert!(!popup.contains("workspace owner")); - assert_no_owner_nudge_or_rate_limit_refresh(&mut rx); - } -} - -#[tokio::test] -async fn workspace_owner_limit_states_render_state_specific_messages() { - let cases = [ - ( - RateLimitReachedType::WorkspaceOwnerCreditsDepleted, - RateLimitErrorKind::Generic, - "You're out of credits. Your workspace is out of credits. Add credits to continue using Codex.", - ), - ( - RateLimitReachedType::WorkspaceOwnerUsageLimitReached, - RateLimitErrorKind::UsageLimit, - "Usage limit reached. You've reached your usage limit. Increase your limits to continue using codex.", - ), - ]; - - let mut rendered_cases = Vec::new(); - for (limit_type, error_kind, expected) in cases { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let mut limits = snapshot(/*percent*/ 100.0); - limits.rate_limit_reached_type = Some(limit_type); - chat.on_rate_limit_snapshot(Some(limits)); - - chat.on_rate_limit_error(error_kind, "Usage limit reached.".to_string()); - let rendered = drain_insert_history(&mut rx) - .into_iter() - .map(|lines| lines_to_single_string(&lines)) - .collect::(); - assert!(rendered.contains(expected), "rendered: {rendered}"); - rendered_cases.push(rendered); - } - - assert_chatwidget_snapshot!( - "workspace_owner_limit_state_messages", - rendered_cases.join("\n---\n") - ); -} - #[tokio::test] async fn academic_researchers_usage_limit_renders_admin_guidance() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -2085,170 +1669,6 @@ async fn academic_researchers_usage_limit_renders_admin_guidance() { ); } -#[tokio::test] -async fn missing_rate_limit_reached_type_does_not_prompt_or_refresh() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.on_rate_limit_snapshot(Some(snapshot(/*percent*/ 100.0))); - - chat.on_rate_limit_error( - RateLimitErrorKind::UsageLimit, - "Usage limit reached.".to_string(), - ); - let popup = render_bottom_popup(&chat, /*width*/ 90); - assert!(!popup.contains("workspace owner")); - assert_no_owner_nudge_or_rate_limit_refresh(&mut rx); -} - -#[tokio::test] -async fn workspace_owner_nudge_default_no_dismisses_without_sending() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let mut limits = snapshot(/*percent*/ 100.0); - limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted); - chat.on_rate_limit_snapshot(Some(limits)); - - chat.on_rate_limit_error( - RateLimitErrorKind::Generic, - "Usage limit reached.".to_string(), - ); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - - assert_no_owner_nudge_or_rate_limit_refresh(&mut rx); -} - -#[tokio::test] -async fn workspace_owner_nudge_reappears_after_dismissing_no() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let mut limits = snapshot(/*percent*/ 100.0); - limits.rate_limit_reached_type = Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached); - chat.on_rate_limit_snapshot(Some(limits)); - - chat.on_rate_limit_error( - RateLimitErrorKind::UsageLimit, - "Usage limit reached.".to_string(), - ); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_no_owner_nudge_or_rate_limit_refresh(&mut rx); - - chat.on_rate_limit_error( - RateLimitErrorKind::UsageLimit, - "Usage limit reached.".to_string(), - ); - let popup = render_bottom_popup(&chat, /*width*/ 100); - assert!( - popup.contains("Request a limit increase from your owner"), - "popup: {popup}" - ); -} - -#[tokio::test] -async fn workspace_owner_credits_nudge_completion_renders_feedback() { - let cases = [ - ( - Ok(AddCreditsNudgeEmailStatus::Sent), - "Workspace owner notified.", - ), - ( - Ok(AddCreditsNudgeEmailStatus::CooldownActive), - "Workspace owner was already notified recently.", - ), - ( - Err("request failed".to_string()), - "Could not notify your workspace owner. Please try again.", - ), - ]; - - let mut rendered_cases = Vec::new(); - for (result, expected) in cases { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat - .start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::Credits) - .expect("start notification"); - chat.finish_add_credits_nudge_email_request(request_id, result); - let rendered = drain_insert_history(&mut rx) - .into_iter() - .map(|lines| lines_to_single_string(&lines)) - .collect::(); - assert!(rendered.contains(expected), "rendered: {rendered}"); - rendered_cases.push(rendered); - } - - assert_chatwidget_snapshot!( - "workspace_owner_credits_nudge_completion_feedback", - rendered_cases.join("\n---\n") - ); -} - -#[tokio::test] -async fn workspace_owner_usage_limit_nudge_completion_renders_feedback() { - let cases = [ - ( - Ok(AddCreditsNudgeEmailStatus::Sent), - "Limit increase requested.", - ), - ( - Ok(AddCreditsNudgeEmailStatus::CooldownActive), - "A limit increase was already requested recently.", - ), - ( - Err("request failed".to_string()), - "Could not request a limit increase. Please try again.", - ), - ]; - - let mut rendered_cases = Vec::new(); - for (result, expected) in cases { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let request_id = chat - .start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::UsageLimit) - .expect("start notification"); - assert!( - chat.start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::Credits) - .is_none() - ); - chat.finish_add_credits_nudge_email_request(request_id, result); - let rendered = drain_insert_history(&mut rx) - .into_iter() - .map(|lines| lines_to_single_string(&lines)) - .collect::(); - assert!(rendered.contains(expected), "rendered: {rendered}"); - rendered_cases.push(rendered); - assert!( - chat.start_add_credits_nudge_email_request(AddCreditsNudgeCreditType::Credits) - .is_some() - ); - } - - assert_chatwidget_snapshot!( - "workspace_owner_usage_limit_nudge_completion_feedback", - rendered_cases.join("\n---\n") - ); -} - -fn next_send_add_credits_nudge_email_event( - rx: &mut tokio::sync::mpsc::UnboundedReceiver, -) -> AddCreditsNudgeCreditType { - while let Ok(event) = rx.try_recv() { - if let AppEvent::SendAddCreditsNudgeEmail { credit_type } = event { - return credit_type; - } - } - panic!("expected SendAddCreditsNudgeEmail app event"); -} - -fn assert_no_owner_nudge_or_rate_limit_refresh( - rx: &mut tokio::sync::mpsc::UnboundedReceiver, -) { - while let Ok(event) = rx.try_recv() { - assert!( - !matches!( - event, - AppEvent::SendAddCreditsNudgeEmail { .. } | AppEvent::RefreshRateLimits { .. } - ), - "unexpected event: {event:?}" - ); - } -} - #[tokio::test] async fn streaming_final_answer_keeps_task_running_state() { let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -3145,838 +2565,6 @@ async fn status_line_legacy_context_usage_renders_context_used_percent() { ); } -#[tokio::test] -async fn status_line_estimated_thread_cost_fetches_and_renders_backend_estimate() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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(); - assert_eq!(status_line_text(&chat), None); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - request_id, - }) => { - assert_eq!(requested_thread_id, thread_id); - request_id - } - event => panic!("expected estimated thread usage refresh, 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(), - })), - )); - assert_eq!(status_line_text(&chat), Some("~$1.82".to_string())); - assert!(rx.try_recv().is_err(), "idle refresh must not poll"); -} - -#[tokio::test] -async fn status_line_thread_credits_fetches_and_renders_fractional_credits() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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.refresh_status_line(); - assert_eq!(status_line_text(&chat), None); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - request_id, - }) => { - assert_eq!(requested_thread_id, thread_id); - request_id - } - event => panic!("expected thread credits refresh, 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: 5_240_000, - estimated_usage_usd_micros: Some(210_000), - groups: Vec::new(), - })), - )); - assert_eq!(status_line_text(&chat), Some("5.2 credits".to_string())); - assert!(rx.try_recv().is_err(), "idle refresh must not poll"); -} - -#[tokio::test] -async fn status_line_thread_credits_and_cost_share_one_backend_request() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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.refresh_status_line(); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected a shared thread usage refresh, got {event:?}"), - }; - assert!(rx.try_recv().is_err(), "both items must share one request"); - - 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: 5_200_000, - estimated_usage_usd_micros: Some(210_000), - groups: Vec::new(), - })), - )); - assert_eq!( - status_line_text(&chat), - Some("5.2 credits Β· ~$0.21".to_string()) - ); - assert!(rx.try_recv().is_err(), "idle refresh must not poll"); -} - -#[tokio::test] -async fn status_line_thread_credits_remain_visible_when_usd_is_unavailable() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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.refresh_status_line(); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected a shared thread usage refresh, 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: 5_200_000, - estimated_usage_usd_micros: None, - groups: Vec::new(), - })), - )); - - assert_eq!(status_line_text(&chat), Some("5.2 credits".to_string())); - assert!( - rx.try_recv().is_err(), - "credits-only estimates must not trigger retries" - ); -} - -#[tokio::test] -async fn terminal_title_thread_usage_fetches_and_renders_without_status_line() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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::new()); - chat.local_settings.tui.terminal_title = Some(vec![ - "thread-credits".to_string(), - "estimated-thread-cost".to_string(), - ]); - - chat.refresh_terminal_title(); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - request_id, - }) => { - assert_eq!(requested_thread_id, thread_id); - request_id - } - event => panic!("expected title-only thread usage refresh, 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: 5_200_000, - estimated_usage_usd_micros: Some(210_000), - groups: Vec::new(), - })), - )); - - assert_eq!( - chat.last_terminal_title, - Some("5.2 credits | ~$0.21".to_string()) - ); - assert_eq!(status_line_text(&chat), None); - assert!(rx.try_recv().is_err(), "title-only refresh must not poll"); -} - -#[tokio::test] -async fn terminal_title_thread_credits_remain_visible_when_usd_is_unavailable() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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::new()); - chat.local_settings.tui.terminal_title = Some(vec![ - "thread-credits".to_string(), - "estimated-thread-cost".to_string(), - ]); - - chat.refresh_terminal_title(); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected title-only thread usage refresh, 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: 5_200_000, - estimated_usage_usd_micros: None, - groups: Vec::new(), - })), - )); - - assert_eq!(chat.last_terminal_title, Some("5.2 credits".to_string())); - assert!( - rx.try_recv().is_err(), - "credits-only title estimates must not trigger retries" - ); -} - -#[tokio::test] -async fn terminal_title_and_status_line_share_one_thread_usage_request() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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 request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected a shared title/footer thread usage request, got {event:?}"), - }; - assert!( - rx.try_recv().is_err(), - "title and footer must share one request" - ); - 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: 5_200_000, - estimated_usage_usd_micros: Some(210_000), - groups: Vec::new(), - })), - )); - - assert_eq!(chat.last_terminal_title, Some("5.2 credits".to_string())); - assert_eq!(status_line_text(&chat), Some("~$0.21".to_string())); -} - -#[tokio::test] -async fn status_line_estimated_thread_cost_avoids_unsupported_plan_requests() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.thread_id = Some(ThreadId::new()); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::Pro); - chat.local_settings.tui.status_line = Some(vec![ - "estimated-thread-cost".to_string(), - "run-state".to_string(), - ]); - - chat.refresh_status_line(); - - assert_eq!(status_line_text(&chat), Some("Ready".to_string())); - assert!( - rx.try_recv().is_err(), - "unsupported plans must not query usage" - ); -} - -#[tokio::test] -async fn status_line_estimated_thread_cost_stops_after_backend_disables_feature() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.has_codex_backend_auth = true; - chat.plan_type = Some(PlanType::EnterpriseCbpAutomation); - 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 estimated thread usage refresh, got {event:?}"), - }; - - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Ok(ThreadUsageOutcome::Disabled), - )); - chat.refresh_thread_usage_after_turn(); - - assert_eq!(status_line_text(&chat), None); - assert!(rx.try_recv().is_err(), "disabled feature must not retry"); -} - -#[tokio::test] -async fn status_line_estimated_thread_cost_preserves_cached_amount_during_settlement() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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 refresh, 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.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.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: 0, - estimated_usage_usd_micros: Some(0), - groups: Vec::new(), - })), - )); - - assert_eq!(status_line_text(&chat), Some("~$1.82".to_string())); - assert!( - rx.try_recv().is_err(), - "settlement must not poll continuously" - ); -} - -#[tokio::test] -async fn completed_turn_refreshes_estimated_thread_cost() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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 refresh, 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.on_task_complete( - /*last_agent_message*/ None, /*completion*/ None, /*from_replay*/ false, - ); - - let request_id = std::iter::from_fn(|| rx.try_recv().ok()) - .find_map(|event| match event { - AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - request_id, - } if requested_thread_id == thread_id => Some(request_id), - _ => None, - }) - .expect("completed turns should refresh estimated thread usage"); - 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: 50_000_000, - estimated_usage_usd_micros: Some(2_100_000), - groups: Vec::new(), - })), - )); - assert_eq!(status_line_text(&chat), Some("~$2.10".to_string())); -} - -#[tokio::test] -async fn completed_turn_refreshes_credits_only_terminal_title() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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::new()); - chat.local_settings.tui.terminal_title = Some(vec!["thread-credits".to_string()]); - chat.refresh_terminal_title(); - - let initial_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected title-only thread usage refresh, 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: 5_200_000, - estimated_usage_usd_micros: None, - groups: Vec::new(), - })), - )); - - chat.on_task_complete( - /*last_agent_message*/ None, /*completion*/ None, /*from_replay*/ false, - ); - - let request_id = std::iter::from_fn(|| rx.try_recv().ok()) - .find_map(|event| match event { - AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - request_id, - } if requested_thread_id == thread_id => Some(request_id), - _ => None, - }) - .expect("completed turns should refresh title-only thread usage"); - 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: 6_200_000, - estimated_usage_usd_micros: None, - groups: Vec::new(), - })), - )); - assert_eq!(chat.last_terminal_title, Some("6.2 credits".to_string())); -} - -#[tokio::test] -async fn interrupted_turn_refreshes_estimated_thread_usage() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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 refresh, 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.on_interrupted_turn(TurnAbortReason::Interrupted); - - assert!( - std::iter::from_fn(|| rx.try_recv().ok()).any(|event| { - matches!( - event, - AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - .. - } if requested_thread_id == thread_id - ) - }), - "interrupted turns must refresh estimated thread usage" - ); -} - -#[tokio::test] -async fn failed_turn_refreshes_estimated_thread_usage() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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 refresh, 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.handle_non_retry_error( - "turn failed after generating tokens".to_string(), - /*codex_error_info*/ None, - ); - - assert!( - std::iter::from_fn(|| rx.try_recv().ok()).any(|event| { - matches!( - event, - AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - .. - } if requested_thread_id == thread_id - ) - }), - "failed turns must refresh estimated thread usage" - ); -} - -#[tokio::test] -async fn status_line_estimated_thread_cost_rejects_stale_thread_completions() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - let previous_thread_id = ThreadId::new(); - let active_thread_id = ThreadId::new(); - chat.thread_id = Some(previous_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 previous_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected previous-thread usage refresh, got {event:?}"), - }; - - chat.thread_id = Some(active_thread_id); - chat.refresh_status_line(); - let active_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected active-thread usage refresh, got {event:?}"), - }; - assert!(!chat.finish_thread_usage_refresh( - previous_thread_id, - previous_request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: previous_thread_id.to_string(), - estimated_usage_credits_micros: 46_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - )); - assert_eq!(status_line_text(&chat), None); - - assert!(chat.finish_thread_usage_refresh( - active_thread_id, - active_request_id, - Ok(ThreadUsageOutcome::Available(ThreadUsage { - native_usage_usd_micros: None, - thread_id: active_thread_id.to_string(), - estimated_usage_credits_micros: 1_000_000, - estimated_usage_usd_micros: Some(400), - groups: Vec::new(), - })), - )); - assert_eq!(status_line_text(&chat), Some("~$0.0004".to_string())); -} - -#[tokio::test] -async fn status_line_estimated_thread_cost_footer_snapshot() { - use ratatui::Terminal; - use ratatui::backend::TestBackend; - - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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.show_welcome_banner = false; - chat.local_settings.tui.status_line = Some(vec![ - "model-with-reasoning".to_string(), - "thread-credits".to_string(), - "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 estimated thread usage refresh, 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: 5_200_000, - estimated_usage_usd_micros: Some(210_000), - groups: Vec::new(), - })), - )); - - let width = 80; - let height = chat.desired_height(width); - let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal"); - terminal - .draw(|frame| chat.render(frame.area(), frame.buffer_mut())) - .expect("draw estimated-thread-cost footer"); - assert_chatwidget_snapshot!( - "status_line_estimated_thread_cost_footer", - normalized_backend_snapshot(terminal.backend()) - ); -} - -#[tokio::test] -async fn status_line_workspace_headline_renders_cached_value() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.thread_id = Some(ThreadId::new()); - chat.local_settings.tui.status_line = Some(vec!["workspace-headline".to_string()]); - chat.status_line_workspace_headline = Some("Workspace maintenance starts at 5pm".to_string()); - - chat.refresh_status_line(); - - assert_eq!( - status_line_text(&chat), - Some("Workspace maintenance starts at 5pm".to_string()) - ); - assert!( - drain_insert_history(&mut rx).is_empty(), - "workspace-headline should be a valid status line item" - ); -} - -#[tokio::test] -async fn status_line_workspace_headline_omits_when_unavailable() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.thread_id = Some(ThreadId::new()); - chat.local_settings.tui.status_line = Some(vec![ - "workspace-headline".to_string(), - "run-state".to_string(), - ]); - - chat.refresh_status_line(); - - assert_eq!(status_line_text(&chat), Some("Ready".to_string())); - assert!( - drain_insert_history(&mut rx).is_empty(), - "workspace-headline should be omitted without warning when no headline is cached" - ); -} - -#[tokio::test] -async fn workspace_headline_update_applies_feature_disabled_result() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.local_settings.tui.status_line = Some(vec!["workspace-headline".to_string()]); - chat.status_line_workspace_headline = Some("Old headline".to_string()); - let request_id = 3; - chat.status_line_workspace_headline_pending_request_id = Some(request_id); - - assert!(chat.set_status_line_workspace_headline( - request_id, - Ok(crate::workspace_messages::WorkspaceHeadlineFetchResult::FeatureDisabled), - )); - - assert_eq!(status_line_text(&chat), None); - assert!(chat.status_line_workspace_messages_disabled); -} - -#[tokio::test] -async fn workspace_headline_update_applies_available_headline() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.local_settings.tui.status_line = Some(vec!["workspace-headline".to_string()]); - let request_id = 4; - chat.status_line_workspace_headline_pending_request_id = Some(request_id); - - assert!(chat.set_status_line_workspace_headline( - request_id, - Ok( - crate::workspace_messages::WorkspaceHeadlineFetchResult::Available(Some( - "Fresh workspace headline".to_string(), - )) - ), - )); - - assert_eq!( - status_line_text(&chat), - Some("Fresh workspace headline".to_string()) - ); - assert!(!chat.status_line_workspace_messages_disabled); -} - -#[tokio::test] -async fn account_update_clears_workspace_headline_state() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.local_settings.tui.status_line = Some(vec!["workspace-headline".to_string()]); - chat.status_line_workspace_headline = Some("Old workspace headline".to_string()); - chat.status_line_workspace_headline_pending_request_id = Some(5); - chat.status_line_workspace_headline_last_requested_at = Some(Instant::now()); - chat.status_line_workspace_messages_disabled = true; - - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ false, - ); - - assert_eq!( - ( - status_line_text(&chat), - chat.status_line_workspace_headline_pending_request_id, - chat.status_line_workspace_headline_last_requested_at, - chat.status_line_workspace_messages_disabled, - ), - (None, None, None, false) - ); -} - -#[tokio::test] -async fn workspace_headline_fetch_allows_backend_auth_without_chatgpt_account() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.local_settings.tui.status_line = Some(vec!["workspace-headline".to_string()]); - - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ true, - ); - - let request_id = take_workspace_headline_request_id(&mut rx); - assert_eq!( - chat.status_line_workspace_headline_pending_request_id, - Some(request_id) - ); -} - -#[tokio::test] -async fn account_update_discards_stale_workspace_headline_results() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.local_settings.tui.status_line = Some(vec!["workspace-headline".to_string()]); - - chat.update_account_state( - Some(StatusAccountDisplay::ChatGpt { - email: Some("first@example.com".to_string()), - plan: None, - workspace: None, - }), - /*plan_type*/ None, - /*has_chatgpt_account*/ true, - /*has_codex_backend_auth*/ true, - ); - let stale_request_id = take_workspace_headline_request_id(&mut rx); - - chat.update_account_state( - Some(StatusAccountDisplay::ChatGpt { - email: Some("second@example.com".to_string()), - plan: None, - workspace: None, - }), - /*plan_type*/ None, - /*has_chatgpt_account*/ true, - /*has_codex_backend_auth*/ true, - ); - let current_request_id = take_workspace_headline_request_id(&mut rx); - - assert_ne!(stale_request_id, current_request_id); - assert!(!chat.set_status_line_workspace_headline( - stale_request_id, - Ok( - crate::workspace_messages::WorkspaceHeadlineFetchResult::Available(Some( - "First account headline".to_string(), - )) - ), - )); - assert_eq!( - ( - chat.status_line_workspace_headline.clone(), - chat.status_line_workspace_headline_pending_request_id, - chat.status_line_workspace_messages_disabled, - ), - (None, Some(current_request_id), false) - ); - - assert!(chat.set_status_line_workspace_headline( - current_request_id, - Ok( - crate::workspace_messages::WorkspaceHeadlineFetchResult::Available(Some( - "Second account headline".to_string(), - )) - ), - )); - assert!(!chat.set_status_line_workspace_headline( - stale_request_id, - Ok(crate::workspace_messages::WorkspaceHeadlineFetchResult::FeatureDisabled), - )); - assert_eq!( - ( - status_line_text(&chat), - chat.status_line_workspace_headline_pending_request_id, - chat.status_line_workspace_messages_disabled, - ), - (Some("Second account headline".to_string()), None, false,) - ); -} - #[tokio::test] async fn status_line_branch_state_resets_when_git_branch_disabled() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs b/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs index b6daf7a3..1988bcba 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_command_tests.rs @@ -1,79 +1,7 @@ use super::*; -use crate::chatwidget::ThreadUsageOutcome; use assert_matches::assert_matches; -use codex_app_server_protocol::ThreadUsage; -use codex_app_server_protocol::ThreadUsageBreakdownGroup; use codex_utils_path_uri::PathUri; -#[tokio::test] -async fn status_command_renders_immediately_and_refreshes_rate_limits_for_chatgpt_auth() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - - chat.dispatch_command(SlashCommand::Status); - - let rendered = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => { - lines_to_single_string(&cell.display_lines(/*width*/ 80)) - } - other => panic!("expected status output before refresh request, got {other:?}"), - }; - assert!( - !rendered.contains("refreshing limits"), - "expected /status to avoid transient refresh text in terminal history, got: {rendered}" - ); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - }) => request_id, - other => panic!("expected rate-limit refresh request, got {other:?}"), - }; - pretty_assertions::assert_eq!(request_id, 0); -} - -#[tokio::test] -async fn status_command_refresh_updates_cached_limits_for_future_status_outputs() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - - chat.dispatch_command(SlashCommand::Status); - - match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(_)) => {} - other => panic!("expected status output before refresh request, got {other:?}"), - } - let first_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - }) => request_id, - other => panic!("expected rate-limit refresh request, got {other:?}"), - }; - - chat.finish_status_rate_limit_refresh(first_request_id, vec![snapshot(/*percent*/ 92.0)]); - drain_insert_history(&mut rx); - - chat.dispatch_command(SlashCommand::Copy); - chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); - assert_matches!( - rx.try_recv(), - Ok(AppEvent::CopySelection { text, label, .. }) - if label == "Whole status" && text.contains("8% left") - ); - assert_matches!(rx.try_recv(), Ok(AppEvent::SettingsSelectionClosed)); - - chat.dispatch_command(SlashCommand::Status); - let refreshed = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => { - lines_to_single_string(&cell.display_lines(/*width*/ 80)) - } - other => panic!("expected refreshed status output, got {other:?}"), - }; - assert!( - refreshed.contains("8% left"), - "expected a future /status output to use refreshed cached limits, got: {refreshed}" - ); -} - #[tokio::test] async fn status_command_renders_immediately_without_rate_limit_refresh() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -81,11 +9,6 @@ async fn status_command_renders_immediately_without_rate_limit_refresh() { chat.dispatch_command(SlashCommand::Status); assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))); - assert!( - !std::iter::from_fn(|| rx.try_recv().ok()) - .any(|event| matches!(event, AppEvent::RefreshRateLimits { .. })), - "non-ChatGPT sessions should not request a rate-limit refresh for /status" - ); } #[tokio::test] @@ -143,491 +66,3 @@ async fn status_command_renders_native_and_foreign_instruction_sources() { "expected /status to avoid stale when app-server provided instruction sources, got: {rendered}" ); } - -#[tokio::test] -async fn status_command_overlapping_refreshes_update_matching_cells_only() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - - chat.dispatch_command(SlashCommand::Status); - match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(_)) => {} - other => panic!("expected first status output, got {other:?}"), - } - let first_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - }) => request_id, - other => panic!("expected first refresh request, got {other:?}"), - }; - - chat.dispatch_command(SlashCommand::Status); - let second_rendered = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => { - lines_to_single_string(&cell.display_lines(/*width*/ 80)) - } - other => panic!("expected second status output, got {other:?}"), - }; - let second_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - }) => request_id, - other => panic!("expected second refresh request, got {other:?}"), - }; - - assert_ne!(first_request_id, second_request_id); - assert!( - !second_rendered.contains("refreshing limits"), - "expected /status to avoid transient refresh text in terminal history, got: {second_rendered}" - ); - - chat.finish_status_rate_limit_refresh(first_request_id, Vec::new()); - pretty_assertions::assert_eq!(chat.refreshing_status_outputs.len(), 1); - - chat.finish_status_rate_limit_refresh(second_request_id, vec![snapshot(/*percent*/ 92.0)]); - assert!(chat.refreshing_status_outputs.is_empty()); -} - -#[tokio::test] -async fn account_update_rejects_stale_status_rate_limit_snapshots() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - chat.dispatch_command(SlashCommand::Status); - assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshRateLimits { - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - }) => request_id, - other => panic!("expected status refresh request, got {other:?}"), - }; - - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ true, /*has_codex_backend_auth*/ true, - ); - chat.finish_status_rate_limit_refresh(request_id, vec![snapshot(/*percent*/ 92.0)]); - - assert!(chat.rate_limit_snapshots_by_limit_id.is_empty()); -} - -#[tokio::test] -async fn status_command_renders_immediately_and_updates_first_card_without_status_line() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let thread_id = - ThreadId::from_string("019fc8ab-1fb2-7000-8000-000000000001").expect("valid thread id"); - chat.thread_id = Some(thread_id); - chat.plan_type = Some(PlanType::Business); - - chat.dispatch_command(SlashCommand::Status); - - let first_cell = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell, - event => panic!("expected immediate /status output, got {event:?}"), - }; - let initial = lines_to_single_string(&first_cell.display_lines(/*width*/ 90)); - assert!(!initial.contains("Thread usage")); - - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { - thread_id: requested_thread_id, - request_id, - }) => { - assert_eq!(requested_thread_id, thread_id); - request_id - } - event => panic!("expected /status to request thread usage, got {event:?}"), - }; - drain_insert_history(&mut rx); - 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: 50_000_000, - estimated_usage_usd_micros: Some(1_820_000), - 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: 40_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), - }, - ThreadUsageBreakdownGroup { - model: Some("gpt-5-mini".to_string()), - reasoning_effort: Some("medium".to_string()), - speed: Some("standard".to_string()), - estimated_usage_credits_micros: 10_000_000, - net_new_input_tokens: Some(15), - cached_input_tokens: Some(5), - input_tokens: Some(20), - output_tokens: Some(10), - total_tokens: Some(30), - }, - ], - })), - )); - - let settled = lines_to_single_string(&first_cell.display_lines(/*width*/ 90)); - assert!(settled.contains("50 credits Β· ~$1.82")); - assert!(settled.contains("GPT-5.4 80%, GPT-5 Mini 20%")); - assert!(drain_insert_history(&mut rx).is_empty()); - chat.dispatch_command(SlashCommand::Status); - let cell = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell, - event => panic!("expected /status output with cached thread usage, got {event:?}"), - }; - let rendered = - normalize_snapshot_paths(lines_to_single_string(&cell.display_lines(/*width*/ 90))); - assert!(rendered.contains("50 credits Β· ~$1.82")); - assert!(rendered.contains("GPT-5.4 80%, GPT-5 Mini 20%")); - assert!(rendered.contains("Medium 20%, High 80%")); - assert!(rendered.contains("Fast mode 80%, Standard 20%")); - assert!(rendered.contains("120 input (25 cached) + 50 output")); - assert!( - rendered.find("Limits:") < rendered.find("Thread usage:"), - "account limits should appear above the thread usage group: {rendered}" - ); - let thread_usage = rendered - .lines() - .skip_while(|line| !line.contains("Thread usage:")) - .collect::>() - .join("\n"); - assert_chatwidget_snapshot!("status_command_estimated_thread_usage", thread_usage); -} - -#[tokio::test] -async fn status_command_omits_thread_usage_for_unsupported_plans() { - for plan_type in [ - Some(PlanType::Enterprise), - Some(PlanType::Pro), - Some(PlanType::Edu), - Some(PlanType::SelfServeBusinessUsageBased), - Some(PlanType::Unknown), - None, - ] { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - chat.thread_id = Some(ThreadId::new()); - chat.plan_type = plan_type; - - chat.dispatch_command(SlashCommand::Status); - - let rendered = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => { - lines_to_single_string(&cell.display_lines(/*width*/ 90)) - } - event => panic!("expected immediate /status output, got {event:?}"), - }; - assert!(!rendered.contains("Thread usage")); - assert!( - !std::iter::from_fn(|| rx.try_recv().ok()) - .any(|event| matches!(event, AppEvent::RefreshThreadUsage { .. })), - "unsupported plan {plan_type:?} must not request thread usage", - ); - } -} - -#[tokio::test] -async fn status_command_stays_visible_and_updates_after_thread_usage_retry() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.plan_type = Some(PlanType::Business); - - chat.dispatch_command(SlashCommand::Status); - let cell = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell, - event => panic!("expected immediate /status output, got {event:?}"), - }; - assert!(!lines_to_single_string(&cell.display_lines(/*width*/ 90)).contains("Thread usage")); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected thread usage request, got {event:?}"), - }; - while rx.try_recv().is_ok() {} - assert!(chat.finish_thread_usage_refresh( - thread_id, - request_id, - Err("thread usage temporarily unavailable".to_string()), - )); - assert!(drain_insert_history(&mut rx).is_empty()); - - chat.dispatch_command(SlashCommand::Status); - let retry_cell = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell, - event => panic!("expected another immediate /status output, got {event:?}"), - }; - let retry_request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected thread usage retry, got {event:?}"), - }; - assert!(chat.finish_thread_usage_refresh( - thread_id, - retry_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(1_820_000), - groups: Vec::new(), - })), - )); - - for status_cell in [&cell, &retry_cell] { - assert!( - lines_to_single_string(&status_cell.display_lines(/*width*/ 90)) - .contains("50 credits Β· ~$1.82") - ); - } -} - -#[tokio::test] -async fn status_command_renders_credits_and_breakdowns_without_usd_estimate() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.plan_type = Some(PlanType::Business); - - chat.dispatch_command(SlashCommand::Status); - let first_cell = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => cell, - event => panic!("expected immediate /status output, got {event:?}"), - }; - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected thread usage request, got {event:?}"), - }; - drain_insert_history(&mut rx); - 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: 50_000_000, - estimated_usage_usd_micros: None, - 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), - }], - })), - )); - - let first_rendered = lines_to_single_string(&first_cell.display_lines(/*width*/ 90)); - assert!(first_rendered.contains("50 credits")); - assert!(first_rendered.contains("GPT-5.4 100%")); - assert!(!first_rendered.contains("~$")); - drain_insert_history(&mut rx); - chat.dispatch_command(SlashCommand::Status); - let rendered = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => { - lines_to_single_string(&cell.display_lines(/*width*/ 90)) - } - event => panic!("expected cached credits-only /status output, got {event:?}"), - }; - assert!(rendered.contains("50 credits")); - assert!(rendered.contains("GPT-5.4 100%")); - assert!(rendered.contains("High 100%")); - assert!(rendered.contains("Fast mode 100%")); - assert!(rendered.contains("100 input (20 cached) + 40 output")); - assert!(!rendered.contains("~$")); - let thread_usage = rendered - .lines() - .skip_while(|line| !line.contains("Thread usage:")) - .collect::>() - .join("\n"); - assert_chatwidget_snapshot!( - "status_command_estimated_thread_usage_without_usd", - thread_usage - ); -} - -#[tokio::test] -async fn status_command_drops_stale_usd_when_updated_usage_has_only_credits() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.plan_type = Some(PlanType::Business); - - chat.dispatch_command(SlashCommand::Status); - assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected initial thread usage request, got {event:?}"), - }; - drain_insert_history(&mut rx); - 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: 40_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - )); - - drain_insert_history(&mut rx); - chat.dispatch_command(SlashCommand::Status); - let cached = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => { - lines_to_single_string(&cell.display_lines(/*width*/ 90)) - } - event => panic!("expected cached /status output, got {event:?}"), - }; - assert!(cached.contains("40 credits Β· ~$1.82")); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected refreshed thread usage request, got {event:?}"), - }; - drain_insert_history(&mut rx); - 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: 50_000_000, - estimated_usage_usd_micros: None, - groups: Vec::new(), - })), - )); - - drain_insert_history(&mut rx); - chat.dispatch_command(SlashCommand::Status); - let refreshed = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => { - lines_to_single_string(&cell.display_lines(/*width*/ 90)) - } - event => panic!("expected credits-only /status output, got {event:?}"), - }; - assert!(refreshed.contains("50 credits")); - assert!(!refreshed.contains("~$1.82")); -} - -#[tokio::test] -async fn status_command_requests_thread_usage_for_remote_connection_metadata() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.thread_id = Some(ThreadId::new()); - chat.update_account_state( - /*status_account_display*/ None, - Some(PlanType::Business), - /*has_chatgpt_account*/ false, - /*has_codex_backend_auth*/ true, - ); - chat.remote_connection = Some(crate::status::remote_connection::RemoteConnectionStatus { - address: "wss://remote.example.com".to_string(), - version: "v1.0.0".to_string(), - is_local_daemon: false, - is_managed_daemon: false, - }); - - chat.dispatch_command(SlashCommand::Status); - - assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))); - assert_matches!(rx.try_recv(), Ok(AppEvent::RefreshThreadUsage { .. })); -} - -#[tokio::test] -async fn status_command_requests_thread_usage_with_backend_only_authentication() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.thread_id = Some(ThreadId::new()); - chat.update_account_state( - /*status_account_display*/ None, - Some(PlanType::Business), - /*has_chatgpt_account*/ false, - /*has_codex_backend_auth*/ true, - ); - assert!(!chat.has_chatgpt_account()); - assert!(chat.has_codex_backend_auth()); - chat.dispatch_command(SlashCommand::Status); - - assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))); - assert_matches!(rx.try_recv(), Ok(AppEvent::RefreshThreadUsage { .. })); -} - -#[tokio::test] -async fn status_command_remains_visible_when_account_changes_during_usage_refresh() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.plan_type = Some(PlanType::Business); - - chat.dispatch_command(SlashCommand::Status); - assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected thread usage request, got {event:?}"), - }; - drain_insert_history(&mut rx); - - chat.update_account_state( - /*status_account_display*/ None, /*plan_type*/ None, - /*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ false, - ); - - 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: 50_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - )); - assert!(drain_insert_history(&mut rx).is_empty()); -} - -#[tokio::test] -async fn status_command_remains_visible_when_thread_changes_during_usage_refresh() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - set_chatgpt_auth(&mut chat); - let thread_id = ThreadId::new(); - chat.thread_id = Some(thread_id); - chat.plan_type = Some(PlanType::Business); - - chat.dispatch_command(SlashCommand::Status); - assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))); - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected thread usage request, got {event:?}"), - }; - drain_insert_history(&mut rx); - - chat.thread_id = Some(ThreadId::new()); - chat.clear_thread_usage_state(); - - 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: 50_000_000, - estimated_usage_usd_micros: Some(1_820_000), - groups: Vec::new(), - })), - )); - assert!(drain_insert_history(&mut rx).is_empty()); -} diff --git a/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs b/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs index 70d000f9..b2ea53f4 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_surface_previews.rs @@ -1,7 +1,5 @@ use super::*; use crate::bottom_pane::preview_line_for_title_items; -use crate::chatwidget::ThreadUsageOutcome; -use codex_app_server_protocol::ThreadUsage; use pretty_assertions::assert_eq; use ratatui::text::Line; @@ -235,18 +233,6 @@ async fn status_line_setup_popup_hardcoded_only_snapshot() { ); } -#[tokio::test] -async fn status_line_setup_popup_workspace_headline_snapshot() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.status_line_workspace_headline = Some("Workspace maintenance starts at 5pm".to_string()); - chat.local_settings.tui.status_line = Some(vec!["workspace-headline".to_string()]); - - assert_chatwidget_snapshot!( - "status_line_setup_popup_workspace_headline", - status_line_popup_snapshot(&mut chat) - ); -} - #[tokio::test] async fn status_surface_preview_lines_mixed_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -287,109 +273,6 @@ async fn status_surface_preview_lines_rate_limits_snapshot() { assert_chatwidget_snapshot!("status_surface_previews_rate_limits", snapshot); } -#[tokio::test] -async fn status_surface_preview_lines_thread_usage_snapshot() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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 = Some(vec![ - "thread-credits".to_string(), - "estimated-thread-cost".to_string(), - ]); - chat.refresh_status_surfaces(); - - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected shared thread usage preview request, 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: 5_200_000, - estimated_usage_usd_micros: Some(210_000), - groups: Vec::new(), - })), - )); - - let snapshot = combined_preview_snapshot( - &mut chat, - &[ - StatusLineItem::ThreadCredits, - StatusLineItem::EstimatedThreadCost, - ], - &[ - TerminalTitleItem::ThreadCredits, - TerminalTitleItem::EstimatedThreadCost, - ], - ); - - assert_chatwidget_snapshot!("status_surface_previews_thread_usage", snapshot); -} - -#[tokio::test] -async fn status_surface_thread_usage_previews_omit_unavailable_usd_estimates() { - let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).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 = Some(vec![ - "thread-credits".to_string(), - "estimated-thread-cost".to_string(), - ]); - chat.refresh_status_surfaces(); - - let request_id = match rx.try_recv() { - Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id, - event => panic!("expected shared thread usage preview request, 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: 5_200_000, - estimated_usage_usd_micros: None, - groups: Vec::new(), - })), - )); - - assert_eq!( - status_preview_line( - &mut chat, - &[ - StatusLineItem::ThreadCredits, - StatusLineItem::EstimatedThreadCost, - ], - ), - "5.2 credits" - ); - assert_eq!( - title_preview_line( - &mut chat, - &[ - TerminalTitleItem::ThreadCredits, - TerminalTitleItem::EstimatedThreadCost, - ], - ), - "5.2 credits" - ); -} - #[tokio::test] async fn status_surface_preview_omits_unavailable_rate_limit_items() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -540,20 +423,6 @@ async fn terminal_title_setup_popup_rate_limits_snapshot() { ); } -#[tokio::test] -async fn terminal_title_setup_popup_thread_usage_snapshot() { - let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; - chat.local_settings.tui.terminal_title = Some(vec![ - "thread-credits".to_string(), - "estimated-thread-cost".to_string(), - ]); - - assert_chatwidget_snapshot!( - "terminal_title_setup_popup_thread_usage", - terminal_title_popup_snapshot(&mut chat) - ); -} - #[tokio::test] async fn missing_project_root_uses_different_status_and_title_preview_sources() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/chatwidget/turn_runtime.rs b/codex-rs/tui/src/chatwidget/turn_runtime.rs index d1acdfcc..506f0e7c 100644 --- a/codex-rs/tui/src/chatwidget/turn_runtime.rs +++ b/codex-rs/tui/src/chatwidget/turn_runtime.rs @@ -95,9 +95,7 @@ impl ChatWidget { self.turn_lifecycle.start(Instant::now()); self.transcript.reset_turn_flags(); self.adaptive_chunking.reset(); - if self.plan_stream_controller.take().is_some() { - self.request_pending_usage_output_insertion_after_stream_shutdown(); - } + self.plan_stream_controller = None; self.turn_runtime_metrics = RuntimeMetricsSummary::default(); self.session_telemetry.reset_runtime_metrics(); self.bottom_pane.clear_quit_shortcut_hint(); @@ -188,7 +186,6 @@ impl ChatWidget { if !from_replay { self.request_status_line_branch_refresh(); self.request_status_line_git_summary_refresh(); - self.refresh_thread_usage_after_turn(); } // Mark task stopped and request redraw now that all content is in history. self.clear_context_compaction(); @@ -372,7 +369,7 @@ impl ChatWidget { self.input_queue.user_turn_pending_start = false; self.clear_guardian_review_status(); self.turn_lifecycle.finish(); - self.status_state.program_status_after_turn = if self.thread_usage.replaying_turn_completion + self.status_state.program_status_after_turn = if self.replaying_turn_completion { crate::terminal_program_status::ProgramStatus::Idle } else { @@ -386,12 +383,10 @@ impl ChatWidget { self.adaptive_chunking.reset(); self.stream_controller = None; self.plan_stream_controller = None; - self.request_pending_usage_output_insertion_after_stream_shutdown(); self.status_state.pending_status_indicator_restore = false; self.safety_buffering_prompt = None; self.request_status_line_branch_refresh(); self.request_status_line_git_summary_refresh(); - self.refresh_thread_usage_after_turn(); self.maybe_show_pending_rate_limit_prompt(); } @@ -449,7 +444,7 @@ impl ChatWidget { self.finalize_turn(); self.add_to_history(history_cell::new_cyber_policy_error_event(notice)); if notice == crate::daybreak::Notice::Disabled - && !self.thread_usage.replaying_turn_completion + && !self.replaying_turn_completion && !self.blocks_direct_input && let Some(thread_id) = self.thread_id { @@ -484,9 +479,6 @@ impl ChatWidget { } pub(super) fn on_rate_limit_error(&mut self, error_kind: RateLimitErrorKind, message: String) { - self.invalidate_ordinary_usage_recovery(); - // on_error can drain queued input, before the asynchronous recovery read completes. - self.input_queue.rate_limit_recovery_pending = self.has_chatgpt_account; let usage_limit_error = matches!(error_kind, RateLimitErrorKind::UsageLimit); let rate_limit_reached_type = self.codex_rate_limit_reached_type.map(|kind| { if usage_limit_error { @@ -503,39 +495,8 @@ impl ChatWidget { kind } }); - if self.codex_rate_limit_reached_type != rate_limit_reached_type { - self.clear_backend_banner(); - } self.codex_rate_limit_reached_type = rate_limit_reached_type; - // Keep owner remediation in history even when the optional backend banner is unavailable. - let (message, nudge) = match rate_limit_reached_type { - Some(RateLimitReachedType::WorkspaceOwnerCreditsDepleted) => ( - "You're out of credits. Your workspace is out of credits. Add credits to continue using Codex." - .to_string(), - None, - ), - Some(RateLimitReachedType::WorkspaceOwnerUsageLimitReached) => ( - "Usage limit reached. You've reached your usage limit. Increase your limits to continue using codex." - .to_string(), - None, - ), - Some(RateLimitReachedType::WorkspaceMemberCreditsDepleted) => - (message, Some(AddCreditsNudgeCreditType::Credits)), - Some(RateLimitReachedType::WorkspaceMemberUsageLimitReached) => - (message, Some(AddCreditsNudgeCreditType::UsageLimit)), - Some(RateLimitReachedType::RateLimitReached) | None => (message, None), - }; self.on_error(message); - if !self.has_applicable_backend_banner() - && let Some(credit_type) = nudge - { - self.open_workspace_owner_nudge_prompt(credit_type); - } - if self.has_chatgpt_account { - self.app_event_tx.send(AppEvent::RefreshRateLimits { - origin: crate::app_event::RateLimitRefreshOrigin::Recovery, - }); - } } pub(super) fn handle_non_retry_error( @@ -549,7 +510,7 @@ impl ChatWidget { { return; } - let question_drafts = if self.thread_usage.replaying_turn_completion { + let question_drafts = if self.replaying_turn_completion { None } else { self.take_question_drafts() diff --git a/codex-rs/tui/src/chatwidget/usage_history.rs b/codex-rs/tui/src/chatwidget/usage_history.rs index 882211f4..08ff9f3d 100644 --- a/codex-rs/tui/src/chatwidget/usage_history.rs +++ b/codex-rs/tui/src/chatwidget/usage_history.rs @@ -1,23 +1,9 @@ -//! Defer reset hints until active transcript output and stream consolidation have settled. +//! Track stream consolidation barriers for transcript insertion ordering. use super::ChatWidget; -use crate::app_event::AppEvent; impl ChatWidget { - /// Reports whether completed asynchronous usage output must wait before insertion. - /// - /// Inserting while a stream, queued consolidation, or active transcript cell is - /// present can reorder output relative to visible work, so callers retry once - /// these barriers clear. - pub(crate) fn usage_history_insertion_blocked(&self) -> bool { - self.stream_controller.is_some() - || self.plan_stream_controller.is_some() - || self.pending_stream_consolidations > 0 - || self.transcript.active_cell.is_some() - || self.active_hook_cell.is_some() - } - - /// Records a stream consolidation barrier that delays reset hint insertion. + /// Records a stream consolidation barrier that delays transcript insertion. /// /// Each queued consolidation should eventually call /// [`ChatWidget::note_stream_consolidation_completed`]. @@ -34,21 +20,4 @@ impl ChatWidget { self.pending_stream_consolidations = self.pending_stream_consolidations.saturating_sub(/*rhs*/ 1); } - - /// Requests another insertion attempt when completed usage output is waiting. - /// - /// This is used after stream or history lifecycle events that may have cleared - /// the insertion barriers without directly owning the completed output. - pub(crate) fn request_pending_usage_output_insertion(&self) { - if self.pending_rate_limit_reset_hint().is_some() { - self.app_event_tx.send(AppEvent::CommitPendingUsageOutput); - } - } - - pub(crate) fn request_pending_usage_output_insertion_after_stream_shutdown(&self) { - if self.pending_rate_limit_reset_hint().is_some() { - self.app_event_tx - .send(AppEvent::CommitPendingUsageOutputAfterStreamShutdown); - } - } } diff --git a/codex-rs/tui/src/chatwidget/usage_notice.rs b/codex-rs/tui/src/chatwidget/usage_notice.rs index d5d575f0..e356f2d7 100644 --- a/codex-rs/tui/src/chatwidget/usage_notice.rs +++ b/codex-rs/tui/src/chatwidget/usage_notice.rs @@ -1,9 +1,8 @@ //! Account quota state and composer notice, independent of one-time warning history. -//! Rolling updates retain metadata; fresh account reads replace windows and confirm recovery. +//! Sparse app-server updates retain window metadata learned from earlier snapshots. //! Details target half the composer gap; the shortest notice may use its full width. use super::ChatWidget; -use super::rate_limits::RateLimitSnapshotSource; use super::rate_limits::is_approximate_window; use super::rate_limits::limit_label_for_window; use crate::clock_format::ClockFormat; @@ -22,9 +21,6 @@ pub(super) struct UsageNoticeState { secondary: Option, plan_type: Option, credits: Option, - latest_read_id: u64, - stale_through: Option, - applying_stale_read: bool, } impl UsageNoticeState { @@ -87,26 +83,14 @@ impl UsageNoticeState { pub(super) fn update( &mut self, snapshot: &RateLimitSnapshot, - source: RateLimitSnapshotSource, plan_type: Option, ) -> bool { - if matches!(source, RateLimitSnapshotSource::AccountUsage) && self.applying_stale_read { - return false; - } let previous = self.current(); - let rolling = matches!(source, RateLimitSnapshotSource::RollingUpdate); - if rolling { - self.stale_through = Some(self.latest_read_id); - } self.plan_type = snapshot.plan_type.or(self.plan_type).or(plan_type); for (current, incoming) in [ (&mut self.primary, &snapshot.primary), (&mut self.secondary, &snapshot.secondary), ] { - if !rolling { - *current = incoming.clone(); - continue; - } let Some(incoming) = incoming else { continue; }; @@ -116,14 +100,10 @@ impl UsageNoticeState { .window_duration_mins .or(previous.window_duration_mins); window.resets_at = window.resets_at.or(previous.resets_at); - let threshold = warning_threshold(self.plan_type, window.window_duration_mins); - if previous.used_percent >= threshold && window.used_percent < threshold { - continue; - } } *current = Some(window); } - if !rolling || snapshot.credits.is_some() { + if snapshot.credits.is_some() { self.credits = snapshot.credits.clone(); } self.current() != previous @@ -165,8 +145,7 @@ pub(super) fn warning_threshold(plan_type: Option, window_minutes: Opt impl ChatWidget { pub(crate) fn usage_notice(&self, width: u16) -> Option> { - if self.has_applicable_backend_banner() - || self.codex_rate_limit_reached_type.is_some() + if self.codex_rate_limit_reached_type.is_some() || self.codex_spend_control_reached == Some(true) { return None; @@ -175,18 +154,6 @@ impl ChatWidget { .line(width, Local::now(), self.clock_format) } - pub(crate) fn start_usage_notice_read(&mut self, request_id: u64) { - self.usage_notice_state.latest_read_id = request_id; - } - - pub(crate) fn apply_usage_notice_read(&mut self, request_id: u64) { - // A newer failed read does not invalidate an older successful one. Only rolling - // updates received since that read began make it too old to confirm recovery. - self.usage_notice_state.applying_stale_read = self - .usage_notice_state - .stale_through - .is_some_and(|id| request_id <= id); - } } #[cfg(test)] diff --git a/codex-rs/tui/src/chatwidget/usage_notice_tests.rs b/codex-rs/tui/src/chatwidget/usage_notice_tests.rs index 625bd6e3..8a5f1a53 100644 --- a/codex-rs/tui/src/chatwidget/usage_notice_tests.rs +++ b/codex-rs/tui/src/chatwidget/usage_notice_tests.rs @@ -1,8 +1,6 @@ -//! Quota selection, sparse updates, read ordering, and compact notice formatting. +//! Quota selection, sparse updates, and compact notice formatting. use super::*; -use crate::app_event::AppEvent; -use crate::app_event::RateLimitRefreshOrigin; use crate::chatwidget::tests::make_chatwidget_manual_with_sender; use crate::tui::FrameRequester; use chrono::TimeZone; @@ -145,7 +143,7 @@ fn notice_uses_existing_plan_and_window_thresholds() { let mut state = UsageNoticeState::default(); let mut update = snapshot(used); update.primary.as_mut().unwrap().window_duration_mins = minutes; - state.update(&update, RateLimitSnapshotSource::AccountUsage, plan); + state.update(&update, plan); assert_eq!( state.current(), visible.then(|| (update.primary.unwrap(), false)), @@ -165,11 +163,7 @@ fn most_constrained_window_wins_with_primary_tie_break() { }); for primary_used in [90, 95, 100] { update.primary.as_mut().unwrap().used_percent = primary_used; - state.update( - &update, - RateLimitSnapshotSource::AccountUsage, - /*plan_type*/ None, - ); + state.update(&update, /*plan_type*/ None); let expected = if primary_used < 95 { (update.secondary.clone().unwrap(), true) } else { @@ -179,74 +173,6 @@ fn most_constrained_window_wins_with_primary_tie_break() { } } -#[test] -fn sparse_updates_preserve_metadata_until_confirmed_recovery() { - let mut state = UsageNoticeState::default(); - let initial = snapshot(/*used_percent*/ 92); - state.update( - &initial, - RateLimitSnapshotSource::AccountUsage, - /*plan_type*/ None, - ); - let mut sparse = snapshot(/*used_percent*/ 94); - sparse.primary.as_mut().unwrap().window_duration_mins = None; - sparse.primary.as_mut().unwrap().resets_at = None; - state.update( - &sparse, - RateLimitSnapshotSource::RollingUpdate, - /*plan_type*/ None, - ); - let mut expected = initial.primary.unwrap(); - expected.used_percent = 94; - assert_eq!(state.current(), Some((expected.clone(), false))); - sparse.primary = None; - state.update( - &sparse, - RateLimitSnapshotSource::RollingUpdate, - /*plan_type*/ None, - ); - assert_eq!(state.current(), Some((expected.clone(), false))); - let healthy = snapshot(/*used_percent*/ 10); - state.update( - &healthy, - RateLimitSnapshotSource::RollingUpdate, - /*plan_type*/ None, - ); - assert_eq!(state.current(), Some((expected, false))); - state.update( - &healthy, - RateLimitSnapshotSource::AccountUsage, - /*plan_type*/ None, - ); - assert_eq!(state.current(), None); -} - -#[test] -fn authoritative_reads_replace_windows_and_metadata() { - let mut state = UsageNoticeState { - primary: snapshot(/*used_percent*/ 92).primary, - secondary: snapshot(/*used_percent*/ 95).primary, - ..Default::default() - }; - let mut update = snapshot(/*used_percent*/ 80); - update.primary.as_mut().unwrap().window_duration_mins = None; - update.primary.as_mut().unwrap().resets_at = None; - state.update( - &update, - RateLimitSnapshotSource::AccountUsage, - /*plan_type*/ None, - ); - assert_eq!(state.current(), Some((update.primary.unwrap(), false))); - let mut empty = snapshot(/*used_percent*/ 0); - empty.primary = None; - state.update( - &empty, - RateLimitSnapshotSource::AccountUsage, - /*plan_type*/ None, - ); - assert_eq!(state.current(), None); -} - #[test] fn usable_credits_suppress_notices_and_survive_sparse_updates() { for (has_credits, unlimited) in [(true, false), (false, true)] { @@ -257,24 +183,10 @@ fn usable_credits_suppress_notices_and_survive_sparse_updates() { unlimited, balance: None, }); - state.update( - &funded, - RateLimitSnapshotSource::AccountUsage, - /*plan_type*/ None, - ); + state.update(&funded, /*plan_type*/ None); let sparse = snapshot(/*used_percent*/ 96); - state.update( - &sparse, - RateLimitSnapshotSource::RollingUpdate, - /*plan_type*/ None, - ); + state.update(&sparse, /*plan_type*/ None); assert_eq!(state.current(), None); - state.update( - &sparse, - RateLimitSnapshotSource::AccountUsage, - /*plan_type*/ None, - ); - assert_eq!(state.current(), Some((sparse.primary.unwrap(), false))); } } @@ -303,7 +215,7 @@ async fn notice_redraws_when_only_limit_blockers_change() { blocked.limit_id = limit_id; blocked.spend_control_reached = spend_control_reached; blocked.rate_limit_reached_type = rate_limit_reached_type; - chat.on_rolling_rate_limit_snapshot(blocked); + chat.on_rate_limit_snapshot(Some(blocked)); assert_eq!(chat.usage_notice(/*width*/ 80), None); assert!(draw_rx.try_recv().is_ok()); while draw_rx.try_recv().is_ok() {} @@ -313,105 +225,17 @@ async fn notice_redraws_when_only_limit_blockers_change() { } } -#[tokio::test] -async fn overlapping_reads_keep_older_success_when_newer_read_fails() -> color_eyre::Result<()> { - let mut app = crate::app::test_support::make_test_app().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()?; - let low = snapshot(/*used_percent*/ 92); - let healthy = snapshot(/*used_percent*/ 10); - for (first_id, rolling, update, expected) in [ - ( - 1, - None, - low.clone(), - Some((low.primary.clone().unwrap(), false)), - ), - ( - 3, - Some(low.clone()), - healthy.clone(), - Some((low.primary.clone().unwrap(), false)), - ), - (5, None, healthy, None), - ] { - for request_id in first_id..=first_id + 1 { - app.chat_widget - .add_status_output(/*refreshing_rate_limits*/ true, Some(request_id)); - app.refresh_rate_limits( - &session, - RateLimitRefreshOrigin::StatusCommand { request_id }, - ); - } - if let Some(rolling) = rolling { - app.chat_widget.on_rolling_rate_limit_snapshot(rolling); - } - let before = app.chat_widget.usage_notice_state.current(); - for (request_id, result, expected) in [ - (first_id + 1, Err("transient failure".into()), before), - (first_id, Ok(update), expected), - ] { - app.handle_event( - &mut tui, - &mut session, - AppEvent::RateLimitsLoaded { - request_id, - origin: RateLimitRefreshOrigin::StatusCommand { request_id }, - hard_stop_generation: 0, - result: result.map(|update| { - serde_json::from_value(serde_json::json!({"rateLimits": update})).unwrap() - }), - }, - ) - .await?; - assert_eq!(app.chat_widget.usage_notice_state.current(), expected); - } - } - session.shutdown().await?; - Ok(()) -} - -#[tokio::test] -async fn rolling_updates_invalidate_only_reads_already_started() { - let (mut chat, _, _, _) = make_chatwidget_manual_with_sender().await; - let mut low = snapshot(/*used_percent*/ 50); - low.plan_type = Some(PlanType::Plus); - let healthy = snapshot(/*used_percent*/ 10); - chat.start_usage_notice_read(/*request_id*/ 1); - chat.on_rolling_rate_limit_snapshot(low.clone()); - chat.start_usage_notice_read(/*request_id*/ 2); - chat.start_usage_notice_read(/*request_id*/ 3); - // Read 3 fails; read 1 is stale, but read 2 began after the rolling update. - chat.apply_usage_notice_read(/*request_id*/ 1); - let mut stale = healthy.clone(); - stale.plan_type = Some(PlanType::Pro); - // A legacy response can include the same quota both at the top level and in its map. - for _ in 0..2 { - chat.on_rate_limit_snapshot(Some(stale.clone())); - assert_eq!( - chat.usage_notice_state.current(), - Some((low.primary.clone().unwrap(), false)) - ); - } - chat.apply_usage_notice_read(/*request_id*/ 2); - chat.on_rate_limit_snapshot(Some(healthy)); - assert_eq!(chat.usage_notice_state.current(), None); -} - #[tokio::test] async fn notice_follows_threads_and_clears_on_account_change() { let (mut previous, _, _, _) = make_chatwidget_manual_with_sender().await; let low = snapshot(/*used_percent*/ 92); previous.on_rate_limit_snapshot(Some(low.clone())); - previous.start_usage_notice_read(/*request_id*/ 1); - previous.on_rolling_rate_limit_snapshot(low.clone()); + previous.on_rate_limit_snapshot(Some(low.clone())); let (mut chat, _, _, _) = make_chatwidget_manual_with_sender().await; - chat.inherit_backend_banner_state(&mut previous); - chat.apply_usage_notice_read(/*request_id*/ 1); - chat.on_rate_limit_snapshot(Some(snapshot(/*used_percent*/ 10))); + chat.inherit_rate_limit_state(&mut previous); let mut other = snapshot(/*used_percent*/ 99); other.limit_id = Some("codex_other".into()); - chat.on_rolling_rate_limit_snapshot(other); + chat.on_rate_limit_snapshot(Some(other)); chat.on_rate_limit_snapshot(/*snapshot*/ None); assert_eq!( chat.usage_notice_state.current(), diff --git a/codex-rs/tui/src/clock_format.rs b/codex-rs/tui/src/clock_format.rs index 8c4977a8..984d5328 100644 --- a/codex-rs/tui/src/clock_format.rs +++ b/codex-rs/tui/src/clock_format.rs @@ -15,13 +15,6 @@ impl ClockFormat { *FORMAT.get_or_init(|| detect().unwrap_or(Self::TwelveHour)) } - pub(crate) fn date_time_format(self) -> &'static str { - match self { - Self::TwelveHour => "%b %-d %-I:%M %p", - Self::TwentyFourHour => "%b %-d %H:%M", - } - } - pub(crate) fn time_format(self) -> &'static str { match self { Self::TwelveHour => "%-I:%M %p", diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 57081724..3926fbfd 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -8,7 +8,6 @@ use crate::legacy_core::config::Config; use crate::legacy_core::config::ConfigBuilder; use crate::legacy_core::config::ConfigOverrides; use crate::legacy_core::config::ConfigTomlLoadResult; -use crate::legacy_core::config::bootstrap_auth_config; use crate::legacy_core::config::edit::ConfigEdit; use crate::legacy_core::config::edit::ConfigEditsBuilder; use crate::legacy_core::config::load_config_toml_with_layer_stack; @@ -55,7 +54,6 @@ use codex_config::types::ResumeCwdMode; use codex_exec_server::EnvironmentManager; use codex_exec_server::ExecServerRuntimeOptions; use codex_features::Feature; -use codex_login::AuthConfig; use codex_login::default_client::originator; use codex_login::default_client::set_default_client_residency_requirement; use codex_login::enforce_login_restrictions; @@ -104,7 +102,6 @@ pub(crate) use worktree_startup::ManagedTuiWorktree; mod activation_key_guard; mod additional_dirs; -mod analytics; mod app; mod app_backtrack; mod app_command; @@ -116,7 +113,6 @@ mod app_server_connection; mod app_server_session; mod approval_events; mod async_question_reply; -mod backend_banners; mod backend_id; mod bottom_pane; mod branch_summary; @@ -267,7 +263,6 @@ mod vim_search; mod width; mod windows_sandbox; mod workspace_command; -mod workspace_messages; mod wrapping; @@ -388,17 +383,6 @@ impl AppServerTarget { } } - fn auth_config_for_cloud_loader(&self, mut auth_config: AuthConfig) -> AuthConfig { - if matches!(self, Self::Remote { .. }) { - // Remove local auth restrictions before loading credentials for a remote - // workspace; the remote app server enforces its own authentication policy. - auth_config.forced_login_method = None; - auth_config.forced_chatgpt_workspace_id = None; - auth_config.managed_auth_policy = Default::default(); - } - auth_config - } - fn thread_params_mode(&self) -> ThreadParamsMode { match self { Self::Embedded | Self::LocalDaemon { .. } => ThreadParamsMode::Embedded, @@ -1254,7 +1238,6 @@ async fn run_ratatui_app( ); let backend_id = crate::backend_id::BackendId::new(); let uses_remote_workspace = app_server_target.uses_remote_workspace(); - let workload_identity_selected = is_workload_identity_selected(); color_eyre::install()?; // aKode: no remote announcement-tip prewarm. diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index 6f0d2f40..36c8881e 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -44,7 +44,6 @@ use scrolling::render_offset_content; pub(crate) enum Overlay { Transcript(TranscriptOverlay), Static(StaticOverlay), - Analytics(Box), } impl Overlay { @@ -86,14 +85,13 @@ impl Overlay { pub(crate) fn handle_event(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> { let mouse_capture = match self { - Overlay::Transcript(_) | Overlay::Analytics(_) => tui::MouseCapture::Enabled, + Overlay::Transcript(_) => tui::MouseCapture::Enabled, Overlay::Static(_) => tui::MouseCapture::Disabled, }; tui.set_mouse_capture(mouse_capture)?; let result = match self { Overlay::Transcript(o) => o.handle_event(tui, event).map(drop), Overlay::Static(o) => o.handle_event(tui, event), - Overlay::Analytics(o) => o.handle_event(tui, event), }; if result.is_err() || self.is_done() { let restore = tui.set_mouse_capture(tui::MouseCapture::Inherit); @@ -106,7 +104,6 @@ impl Overlay { match self { Overlay::Transcript(o) => o.is_done(), Overlay::Static(o) => o.is_done(), - Overlay::Analytics(o) => o.is_done, } } } diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index dd614df0..0e51ae10 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -59,7 +59,6 @@ pub enum SlashCommand { Cd, #[strum(to_string = "pwd", serialize = "cwd")] Pwd, - Usage, DebugConfig, Title, Statusline, @@ -122,7 +121,6 @@ impl SlashCommand { SlashCommand::Status => "show current session configuration and token usage", SlashCommand::Cd => "change the current working directory", SlashCommand::Pwd => "show the current working directory", - SlashCommand::Usage => "view account usage or use a usage limit reset", SlashCommand::DebugConfig => "show config layers and requirement sources for debugging", SlashCommand::Title => "configure which items appear in the terminal title", SlashCommand::Statusline => "configure which items appear in the status line", @@ -189,7 +187,6 @@ impl SlashCommand { | SlashCommand::Raw | SlashCommand::Cd | SlashCommand::Pwd - | SlashCommand::Usage | SlashCommand::Pets | SlashCommand::Side | SlashCommand::Btw @@ -211,7 +208,6 @@ impl SlashCommand { | SlashCommand::Daemon | SlashCommand::Warnings | SlashCommand::Pwd - | SlashCommand::Usage | SlashCommand::Ide | SlashCommand::Rename ) @@ -286,7 +282,6 @@ impl SlashCommand { | SlashCommand::Daemon | SlashCommand::Warnings | SlashCommand::Pwd - | SlashCommand::Usage | SlashCommand::DebugConfig | SlashCommand::Ps | SlashCommand::Stop diff --git a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_dates_distinguish_zero_missing_and_exact_details.snap b/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_dates_distinguish_zero_missing_and_exact_details.snap deleted file mode 100644 index d391919f..00000000 --- a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_dates_distinguish_zero_missing_and_exact_details.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: tui/src/analytics_tests.rs -expression: "screens.join(\"\\n\\n\")" ---- -13.1K credits - 12,746.44 - 15K β–„β–„β–„β–„ - β–ˆβ–ˆβ–ˆβ–ˆ 85.00 75.00 109.00 64.00 - 0.00 β–ˆβ–ˆβ–ˆβ–ˆ β€” ▁▁▁▁ ▁▁▁▁ ▁▁▁▁ ▁▁▁▁ - 0 ──────────────────────────────────────────────── - β–² - 27 28 29 30 31 1 2 - -────────────────────────────────────────────────────── -Aug 27 Β· No activity (0) -Product Credits -● Desktop app 0.00 -● CLI 0.00 -● IDE extension 0.00 -● Web 0.00 - -13.1K credits - 12,746.44 - 15K β–„β–„β–„β–„ - β–ˆβ–ˆβ–ˆβ–ˆ 85.00 75.00 109.00 64.00 - 0 β–ˆβ–ˆβ–ˆβ–ˆ β€” ▁▁▁▁ ▁▁▁▁ ▁▁▁▁ ▁▁▁▁ - 0 ──────────────────────────────────────────────── - β–² - 27 28 29 30 31 1 2 - -────────────────────────────────────────────────────── -Aug 28 Β· 12746.441206 credits -Product Credits -● Desktop app 12746.441206 -● CLI 0 -● IDE extension 0 -● Web 0 - -13.1K credits - 12,746.44 - 15K β–„β–„β–„β–„ - β–ˆβ–ˆβ–ˆβ–ˆ 85.00 75.00 109.00 64.00 - 0 β–ˆβ–ˆβ–ˆβ–ˆ β€” ▁▁▁▁ ▁▁▁▁ ▁▁▁▁ ▁▁▁▁ - 0 ──────────────────────────────────────────────── - β–² - 27 28 29 30 31 1 2 - -────────────────────────────────────────────────────── -Aug 29 Β· Not reported -Product Credits -● Desktop app β€” -● CLI β€” -● IDE extension β€” -● Web β€” - -0.00 credits -No activity reported in this range. - -────────────────────────────────────────────────────── -Aug 29 Β· Not reported -Product Credits - -No data reported for this range. diff --git a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_loading_errors_and_empty_reports_stay_independent.snap b/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_loading_errors_and_empty_reports_stay_independent.snap deleted file mode 100644 index b9da1ace..00000000 --- a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_loading_errors_and_empty_reports_stay_independent.snap +++ /dev/null @@ -1,11 +0,0 @@ ---- -source: tui/src/analytics_tests.rs -expression: panels ---- -Loading… - -No history has been reported. - -Couldn't load credits. Press R to retry. - -No data reported for this range. diff --git a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_maximized_refunds_leave_room_for_both_bands.snap b/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_maximized_refunds_leave_room_for_both_bands.snap deleted file mode 100644 index 0dc2b422..00000000 --- a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_maximized_refunds_leave_room_for_both_bands.snap +++ /dev/null @@ -1,36 +0,0 @@ ---- -source: tui/src/analytics_tests.rs -expression: output ---- -" Usage Β· Enterprise " -" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills 6 Chats " -" ────────────────────────────────────────────────────────────────────────────────────────────────── " -" r 7d/30d Β· Aug 27–Sep 2, 2026 " -" " -" " -" 367.00 credits " -" " -" 150 109.00 " -" 85.00 75.00 β–…β–…β–…β–…β–…β–…β–…β–… " -" 75 41.00 57.00 β–†β–†β–†β–†β–†β–†β–†β–† β–„β–„β–„β–„β–„β–„β–„β–„ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ " -" β–‚β–‚β–‚β–‚β–‚β–‚β–‚β–‚ β–‡β–‡β–‡β–‡β–‡β–‡β–‡β–‡ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ " -" 0 β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ " -" 0 ──────────────────────────────────────────────────────────────────────────────────────────── " -" β–‡β–‡β–‡β–‡β–‡β–‡β–‡β–‡β–‡ " -" -0.000004 " -" " -" " -" -150 " -" " -" β–² " -" Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 " -" " -" ──────────────────────────────────────────────────────── " -" Sep 2 Β· -0.000004 credits " -" Product Credits " -" ● CLI -0.000004 " -" ● Desktop app 0.00 " -" ● IDE extension 0.00 " -" ● Web 0.00 " -" ←/β†’ day Β· enter details Β· esc back " -" tab/1–6 report Β· z dashboard Β· ? help Β· R refresh " diff --git a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_preserves_full_denominators_and_signed_small_credits.snap b/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_preserves_full_denominators_and_signed_small_credits.snap deleted file mode 100644 index ba9e5098..00000000 --- a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_preserves_full_denominators_and_signed_small_credits.snap +++ /dev/null @@ -1,33 +0,0 @@ ---- -source: tui/src/analytics_tests.rs -expression: "task.into_iter().chain(credits).map(|line|\nline.to_string()).collect::>().join(\"\\n\")" ---- -Total usage Β· relative units -Approximate Β· may be delayed up to 6 hours -All usage by how each turn started - - 100 100 - β€” β€” β€” β€” β€” β€” β–„β–„β–„β–„ - 0 ───────────────────────────────────────────────── - β–² - Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 - -────────────────────────────────────────────────────── -Sep 2 Β· 100 usage units -Turn start Share -● Goals 30.0% --0.000004 credits - - 0.000004 - β€” β€” β€” β€” β€” β€” - 0 ─────────────────────────────────────────── - β–ˆβ–ˆβ–ˆβ–ˆ - -0.000004 β–ˆβ–ˆβ–ˆβ–ˆ - -0.000004 - β–² - 27 28 29 30 31 1 2 - -────────────────────────────────────────────────────── -Sep 2 Β· -0.000004 credits -Product Credits -● CLI -0.000004 diff --git a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_series_rank_by_range_and_keep_calendar_ticks_stable.snap b/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_series_rank_by_range_and_keep_calendar_ticks_stable.snap deleted file mode 100644 index a8a0fb7e..00000000 --- a/codex-rs/tui/src/snapshots/codex_tui__analytics__tests__analytics_series_rank_by_range_and_keep_calendar_ticks_stable.snap +++ /dev/null @@ -1,18 +0,0 @@ ---- -source: tui/src/analytics_tests.rs -expression: crowded ---- - - 600 0.4 β–„β–ƒ β–† β–…β–ˆ β–† - β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β”Šβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–… β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ - β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β”Šβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ - β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β”Šβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ - β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β”Šβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ - 300 β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β”Šβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ - β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β”Šβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ - β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β”Šβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ - β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β”Šβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ - β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ β–ˆβ–ˆ β–ˆ - 0 ───────────────────────────────────────────────── - β–² - Aug 4 Aug 11 Aug 18 Aug 25 Sep 2 diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index 8145011f..7e390dec 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -4,7 +4,6 @@ use crate::history_cell::PlainHistoryCell; use crate::history_cell::plain_lines; use crate::legacy_core::config::Config; use crate::line_truncation::line_width; -use crate::style::accent_color; use crate::token_usage::TokenUsage; use crate::token_usage::TokenUsageInfo; use crate::version::CODEX_CLI_VERSION; @@ -46,14 +45,11 @@ use super::rate_limits::compose_rate_limit_data_many; use super::rate_limits::format_status_limit_summary; use super::rate_limits::render_status_limit_progress_bar; use super::remote_connection::RemoteConnectionStatus; -use super::thread_usage::StatusThreadUsage; use crate::wrapping::RtOptions; use crate::wrapping::word_wrap_lines; use std::sync::Arc; use std::sync::RwLock; -const CHATGPT_USAGE_URL: &str = "https://chatgpt.com/settings/usage"; - #[derive(Debug, Clone)] struct StatusContextWindowData { percent_remaining: i64, @@ -72,7 +68,6 @@ pub(crate) struct StatusTokenUsageData { #[derive(Debug)] struct StatusRateLimitState { rate_limits: StatusRateLimitData, - refreshing_rate_limits: bool, } #[derive(Debug, Clone)] @@ -91,37 +86,6 @@ impl StatusHistoryHandle { .trim() .to_string() } - - pub(crate) fn reserve_thread_usage_label_width(&self) { - self.card.thread_usage.reserve_label_width(); - } - - pub(crate) fn finish_rate_limit_refresh( - &self, - rate_limits: &[RateLimitSnapshotDisplay], - now: DateTime, - ) { - let rate_limits = if rate_limits.len() <= 1 { - compose_rate_limit_data(rate_limits.first(), now) - } else { - compose_rate_limit_data_many(rate_limits, now) - }; - #[expect(clippy::expect_used)] - let mut state = self - .card - .rate_limit_state - .write() - .expect("status history rate-limit state poisoned"); - state.rate_limits = rate_limits; - state.refreshing_rate_limits = false; - } - - pub(crate) fn set_thread_usage( - &self, - estimate: Option, - ) { - self.card.thread_usage.set_estimate(estimate); - } } #[derive(Debug)] @@ -134,15 +98,12 @@ struct StatusHistoryCell { collaboration_mode: Option, model_provider: Option, remote_connection: Option, - show_chatgpt_usage_link: bool, account: Option, thread_name: Option, session_id: Option, forked_from: Option, token_usage: StatusTokenUsageData, rate_limit_state: Arc>, - thread_usage: StatusThreadUsage, - plan_type: Option, } #[cfg(test)] @@ -177,7 +138,6 @@ pub(crate) fn new_status_output( model_name, collaboration_mode, reasoning_effort_override, - /*refreshing_rate_limits*/ false, ) } @@ -197,11 +157,9 @@ pub(crate) fn new_status_output_with_rate_limits( model_name: &str, collaboration_mode: Option<&str>, reasoning_effort_override: Option>, - refreshing_rate_limits: bool, ) -> CompositeHistoryCell { new_status_output_with_rate_limits_handle( config, - config.model_provider.requires_openai_auth, /*model_provider_id*/ None, /*remote_connection*/ None, account_display, @@ -217,7 +175,6 @@ pub(crate) fn new_status_output_with_rate_limits( collaboration_mode, reasoning_effort_override, "".to_string(), - refreshing_rate_limits, ) .0 } @@ -225,7 +182,6 @@ pub(crate) fn new_status_output_with_rate_limits( #[allow(clippy::too_many_arguments)] pub(crate) fn new_status_output_with_rate_limits_handle( config: &Config, - requires_openai_auth: bool, model_provider_id: Option<&str>, remote_connection: Option<&RemoteConnectionStatus>, account_display: Option<&StatusAccountDisplay>, @@ -241,12 +197,10 @@ pub(crate) fn new_status_output_with_rate_limits_handle( collaboration_mode: Option<&str>, reasoning_effort_override: Option>, agents_summary: String, - refreshing_rate_limits: bool, ) -> (CompositeHistoryCell, StatusHistoryHandle) { let command = PlainHistoryCell::new(vec!["/status".magenta().into()]); let card = Arc::new(StatusHistoryCell::new( config, - requires_openai_auth, model_provider_id, remote_connection, account_display, @@ -262,7 +216,6 @@ pub(crate) fn new_status_output_with_rate_limits_handle( collaboration_mode, reasoning_effort_override, agents_summary, - refreshing_rate_limits, )); let handle = StatusHistoryHandle { card: Arc::clone(&card), @@ -278,8 +231,7 @@ impl StatusHistoryCell { #[allow(clippy::too_many_arguments)] fn new( config: &Config, - requires_openai_auth: bool, - model_provider_id: Option<&str>, + model_provider_id: Option<&str>, remote_connection: Option<&RemoteConnectionStatus>, account_display: Option<&StatusAccountDisplay>, token_info: Option<&TokenUsageInfo>, @@ -294,8 +246,7 @@ impl StatusHistoryCell { collaboration_mode: Option<&str>, reasoning_effort_override: Option>, agents_summary: String, - refreshing_rate_limits: bool, - ) -> Self { + ) -> Self { let approval_policy = AskForApproval::from(config.permissions.approval_policy.value()); let permission_profile = config.permissions.effective_permission_profile(); let workspace_roots = config.effective_workspace_roots(); @@ -352,7 +303,6 @@ impl StatusHistoryCell { &approval, workspace_root_suffix.as_deref(), ); - let show_chatgpt_usage_link = requires_openai_auth; let mut account = compose_account_display(account_display); let workspace_matches_provider = if remote_connection.is_some() { // A connected server owns the provider definitions; only the built-in ID is certain. @@ -400,10 +350,8 @@ impl StatusHistoryCell { }; let rate_limit_state = Arc::new(RwLock::new(StatusRateLimitState { rate_limits, - refreshing_rate_limits, - })); + })); let agents_summary = Arc::new(RwLock::new(agents_summary)); - let thread_usage = StatusThreadUsage::default(); Self { model_name, @@ -413,7 +361,6 @@ impl StatusHistoryCell { collaboration_mode: collaboration_mode.map(ToString::to_string), model_provider, remote_connection: remote_connection.cloned(), - show_chatgpt_usage_link, account, thread_name, session_id, @@ -421,8 +368,6 @@ impl StatusHistoryCell { token_usage, agents_summary, rate_limit_state, - thread_usage, - plan_type: _plan_type, } } @@ -482,12 +427,7 @@ impl StatusHistoryCell { self.rate_limit_row_lines(rows_data, available_inner_width, formatter); lines.push(formatter.line( "Warning", - vec![Span::from(if state.refreshing_rate_limits { - "limits may be stale - run /status again shortly." - } else { - "limits may be stale - start new turn to refresh." - }) - .dim()], + vec![Span::from("limits may be stale - start new turn to refresh.").dim()], )); lines } @@ -497,17 +437,8 @@ impl StatusHistoryCell { vec![Span::from("not available for this account").dim()], )] } - StatusRateLimitData::Missing => { - vec![formatter.line( - "Limits", - vec![Span::from(if state.refreshing_rate_limits { - "refresh requested; run /status again shortly." - } else { - "data not available yet" - }) - .dim()], - )] - } + // Providers without rate-limit data have no limits section. + StatusRateLimitData::Missing => Vec::new(), } } @@ -622,7 +553,7 @@ impl StatusHistoryCell { push_label(labels, seen, "Warning"); } StatusRateLimitData::Unavailable => push_label(labels, seen, "Limits"), - StatusRateLimitData::Missing => push_label(labels, seen, "Limits"), + StatusRateLimitData::Missing => {} } } } @@ -822,7 +753,6 @@ impl StatusHistoryCell { push_label(&mut labels, &mut seen, "Context window"); } self.collect_rate_limit_labels(&rate_limit_state, &mut seen, &mut labels); - self.thread_usage.push_labels(&mut labels, &mut seen); let formatter = FieldFormatter::from_labels(labels.iter().map(String::as_str)); let value_width = formatter.value_width(available_width); @@ -887,23 +817,13 @@ impl StatusHistoryCell { } lines.push(Line::from(Vec::>::new())); - // Hide token usage only for ChatGPT subscribers - if !matches!(self.account, Some(StatusAccountDisplay::ChatGpt { .. })) { - lines.push(formatter.line("Token usage", self.token_usage_spans())); - } + lines.push(formatter.line("Token usage", self.token_usage_spans())); if let Some(spans) = self.context_window_spans() { lines.push(formatter.line("Context window", spans)); } lines.extend(self.rate_limit_lines(&rate_limit_state, available_width, &formatter)); - let thread_usage_lines = self - .thread_usage - .lines(&formatter, value_width, self.plan_type); - if !thread_usage_lines.is_empty() { - lines.push(Line::from(Vec::>::new())); - lines.extend(thread_usage_lines); - } // Leave room for the two-column title mark even in a tiny terminal. let indent = if available_width >= FieldFormatter::INDENT.len() + 2 { @@ -918,27 +838,6 @@ impl StatusHistoryCell { RtOptions::new(available_width).subsequent_indent(indent.into()), ); rendered.push(Line::default()); - // Providers such as Bedrock manage limits and billing elsewhere. - if self.show_chatgpt_usage_link { - rendered.extend(word_wrap_lines( - [ - Line::from(vec![ - "Visit ".fg(accent_color()), - CHATGPT_USAGE_URL.fg(accent_color()).underlined(), - " for up-to-date".fg(accent_color()), - ]), - "information on rate limits and credits" - .fg(accent_color()) - .into(), - ], - RtOptions::new(available_width) - .initial_indent(indent.into()) - .subsequent_indent(indent.into()) - .word_separator(textwrap::WordSeparator::AsciiSpace) - .word_splitter(textwrap::WordSplitter::NoHyphenation), - )); - rendered.push(Line::default()); - } // Keep every value, including long paths and IDs, aligned beneath its first line. // At widths too small for the label column, use the outer indent instead. let continuation = if value_width > 0 { @@ -979,37 +878,4 @@ impl HistoryCell for Arc { plain_lines(self.display_lines(u16::MAX)) } - fn display_hyperlink_lines( - &self, - width: u16, - ) -> Vec { - let mut lines = - crate::terminal_hyperlinks::plain_hyperlink_lines(self.display_lines(width)); - // The usage URL has a known destination; wrapping preserves its underlined spans. - // Attach that destination to every fragment instead of searching for the full URL. - if self.show_chatgpt_usage_link { - for line in &mut lines { - let mut column = 0; - for span in &line.line.spans { - let end = column + span.width(); - if span.style.add_modifier.contains(Modifier::UNDERLINED) { - line.hyperlinks - .push(crate::terminal_hyperlinks::TerminalHyperlink::web( - column..end, - CHATGPT_USAGE_URL.to_string(), - )); - } - column = end; - } - } - } - lines - } - - fn transcript_hyperlink_lines( - &self, - width: u16, - ) -> Vec { - self.display_hyperlink_lines(width) - } } diff --git a/codex-rs/tui/src/status/mod.rs b/codex-rs/tui/src/status/mod.rs index a79c95da..aea44d63 100644 --- a/codex-rs/tui/src/status/mod.rs +++ b/codex-rs/tui/src/status/mod.rs @@ -12,14 +12,11 @@ mod format; mod helpers; mod rate_limits; pub(crate) mod remote_connection; -mod thread_usage; pub(crate) use account::StatusAccountDisplay; pub(crate) use card::StatusHistoryHandle; #[cfg(test)] pub(crate) use card::new_status_output; -#[cfg(test)] -pub(crate) use card::new_status_output_with_rate_limits; pub(crate) use card::new_status_output_with_rate_limits_handle; pub(crate) use helpers::compose_agents_summary; pub(crate) use helpers::format_directory_display; @@ -31,9 +28,6 @@ pub(crate) use rate_limits::RateLimitWindowDisplay; #[cfg(test)] pub(crate) use rate_limits::rate_limit_snapshot_display; pub(crate) use rate_limits::rate_limit_snapshot_display_for_limit; -pub(crate) use thread_usage::format_credit_micros; -pub(crate) use thread_usage::format_estimated_usd_micros; -pub(crate) use thread_usage::thread_cost_micros; #[cfg(test)] mod tests; diff --git a/codex-rs/tui/src/status/rate_limits.rs b/codex-rs/tui/src/status/rate_limits.rs index c22868b6..a2379266 100644 --- a/codex-rs/tui/src/status/rate_limits.rs +++ b/codex-rs/tui/src/status/rate_limits.rs @@ -15,11 +15,8 @@ use chrono::DateTime; use chrono::Duration as ChronoDuration; use chrono::Local; use chrono::Utc; -use codex_app_server_protocol::CreditsSnapshot as CoreCreditsSnapshot; use codex_app_server_protocol::RateLimitSnapshot; use codex_app_server_protocol::RateLimitWindow; -use codex_app_server_protocol::SpendControlLimitSnapshot as CoreSpendControlLimitSnapshot; -use codex_protocol::num_format::format_with_separators; const STATUS_LIMIT_BAR_SEGMENTS: usize = 20; const STATUS_LIMIT_BAR_FILLED: &str = "β–ˆ"; @@ -101,40 +98,12 @@ impl RateLimitWindowDisplay { pub(crate) struct RateLimitSnapshotDisplay { /// Canonical limit identifier (for example: `codex` or `codex_other`). pub limit_name: String, - /// Optional normal model associated with this account-read quota alias. - pub normal_model_slug: Option, /// Local timestamp representing when this display snapshot was captured. pub captured_at: DateTime, /// Primary usage window. pub primary: Option, /// Secondary usage window. pub secondary: Option, - /// Optional credits metadata when available. - pub credits: Option, - /// Optional effective monthly credit limit from workspace spend controls. - pub individual_limit: Option, -} - -/// Display-ready credits state extracted from protocol snapshots. -#[derive(Debug, Clone)] -pub(crate) struct CreditsSnapshotDisplay { - /// Whether credits tracking is enabled for the account. - pub has_credits: bool, - /// Whether the account has unlimited credits. - pub unlimited: bool, - /// Raw balance text as provided by the backend. - pub balance: Option, -} - -/// Display-ready effective monthly limit extracted from spend controls. -#[derive(Debug, Clone)] -pub(crate) struct SpendControlLimitSnapshotDisplay { - /// Local timestamp representing when this monthly usage value was captured. - pub captured_at: DateTime, - pub percent_remaining: f64, - pub used: String, - pub limit: String, - pub resets_at: Option, } /// Converts a protocol snapshot into UI-friendly display data. @@ -161,7 +130,6 @@ pub(crate) fn rate_limit_snapshot_display_for_limit( clock_format: ClockFormat, ) -> RateLimitSnapshotDisplay { RateLimitSnapshotDisplay { - normal_model_slug: snapshot.normal_model_slug.clone(), limit_name, captured_at, primary: snapshot @@ -172,38 +140,6 @@ pub(crate) fn rate_limit_snapshot_display_for_limit( .secondary .as_ref() .map(|window| RateLimitWindowDisplay::from_window(window, captured_at, clock_format)), - credits: snapshot.credits.as_ref().map(CreditsSnapshotDisplay::from), - individual_limit: snapshot.individual_limit.as_ref().and_then(|limit| { - SpendControlLimitSnapshotDisplay::from_limit(limit, captured_at, clock_format) - }), - } -} - -impl From<&CoreCreditsSnapshot> for CreditsSnapshotDisplay { - fn from(value: &CoreCreditsSnapshot) -> Self { - Self { - has_credits: value.has_credits, - unlimited: value.unlimited, - balance: value.balance.clone(), - } - } -} - -impl SpendControlLimitSnapshotDisplay { - fn from_limit( - value: &CoreSpendControlLimitSnapshot, - captured_at: DateTime, - clock_format: ClockFormat, - ) -> Option { - Some(Self { - captured_at, - percent_remaining: f64::from(value.remaining_percent.clamp(0, 100)), - used: format_credit_amount(&value.used)?, - limit: format_credit_amount(&value.limit)?, - resets_at: DateTime::::from_timestamp(value.resets_at, 0).map(|dt| { - format_reset_timestamp(dt.with_timezone(&Local), captured_at, clock_format) - }), - }) } } @@ -236,25 +172,12 @@ pub(crate) fn compose_rate_limit_data_many( let mut ordered_snapshots = snapshots.iter().collect::>(); ordered_snapshots.sort_by_key(|snapshot| !snapshot.limit_name.eq_ignore_ascii_case("codex")); for snapshot in ordered_snapshots { - let credit_row = snapshot.credits.as_ref().and_then(credit_status_row); // Metadata-only buckets have no visible values and should not leave an empty heading. - if snapshot.primary.is_none() - && snapshot.secondary.is_none() - && credit_row.is_none() - && snapshot.individual_limit.is_none() - { + if snapshot.primary.is_none() && snapshot.secondary.is_none() { continue; } stale |= now.signed_duration_since(snapshot.captured_at) > ChronoDuration::minutes(RATE_LIMIT_STALE_THRESHOLD_MINUTES); - stale |= snapshot - .individual_limit - .as_ref() - .map(|limit| { - now.signed_duration_since(limit.captured_at) - > ChronoDuration::minutes(RATE_LIMIT_STALE_THRESHOLD_MINUTES) - }) - .unwrap_or(false); let limit_bucket_label = crate::model_catalog::model_display_name(&snapshot.limit_name); let show_limit_prefix = !limit_bucket_label.eq_ignore_ascii_case("codex"); @@ -335,22 +258,6 @@ pub(crate) fn compose_rate_limit_data_many( }); } - if let Some(row) = credit_row { - rows.push(row); - } - if let Some(individual_limit) = snapshot.individual_limit.as_ref() { - rows.push(StatusRateLimitRow { - label: "Monthly credit limit".to_string(), - value: StatusRateLimitValue::Window { - percent_used: 100.0 - individual_limit.percent_remaining, - resets_at: individual_limit.resets_at.clone(), - details: Some(format!( - "{} of {} credits used", - individual_limit.used, individual_limit.limit - )), - }, - }); - } } if rows.is_empty() { @@ -388,67 +295,8 @@ pub(crate) fn format_status_limit_summary(percent_remaining: f64) -> String { format!("{percent_remaining:.0}% left") } -/// Builds a single `StatusRateLimitRow` when workspace credits are available. -/// Unlimited credits are shown explicitly; finite credits show their rounded -/// balance or `Available` when the balance is hidden. -fn credit_status_row(credits: &CreditsSnapshotDisplay) -> Option { - if credits.unlimited { - return Some(StatusRateLimitRow { - label: "Credits".to_string(), - value: StatusRateLimitValue::Text("Unlimited".to_string()), - }); - } - if !credits.has_credits { - return None; - } - let value = credits - .balance - .as_deref() - .and_then(format_credit_balance) - .map_or_else( - || "Available".to_string(), - |display_balance| format!("{display_balance} credits"), - ); - Some(StatusRateLimitRow { - label: "Credits".to_string(), - value: StatusRateLimitValue::Text(value), - }) -} - -fn format_credit_balance(raw: &str) -> Option { - let trimmed = raw.trim(); - if trimmed.is_empty() { - return None; - } - - if let Ok(int_value) = trimmed.parse::() - && int_value > 0 - { - return Some(int_value.to_string()); - } - - if let Ok(value) = trimmed.parse::() - && value.is_finite() - && value > 0.0 - { - let rounded = value.round() as i64; - return Some(rounded.to_string()); - } - - None -} - -fn format_credit_amount(raw: &str) -> Option { - let value = raw.trim().parse::().ok()?; - if !value.is_finite() || value < 0.0 { - return None; - } - Some(format_with_separators(value.round() as i64)) -} - #[cfg(test)] mod tests { - use super::CreditsSnapshotDisplay; use super::RateLimitSnapshotDisplay; use super::RateLimitWindowDisplay; use super::StatusRateLimitData; @@ -469,29 +317,15 @@ mod tests { let now = Local::now(); let codex = RateLimitSnapshotDisplay { limit_name: "codex".to_string(), - normal_model_slug: None, captured_at: now, primary: Some(window(/*used_percent*/ 10.0)), secondary: None, - credits: Some(CreditsSnapshotDisplay { - has_credits: true, - unlimited: false, - balance: Some("25".to_string()), - }), - individual_limit: None, }; let other = RateLimitSnapshotDisplay { limit_name: "codex-other".to_string(), - normal_model_slug: None, captured_at: now, primary: Some(window(/*used_percent*/ 20.0)), secondary: None, - credits: Some(CreditsSnapshotDisplay { - has_credits: true, - unlimited: false, - balance: Some("99".to_string()), - }), - individual_limit: None, }; let rows = match compose_rate_limit_data_many(&[codex, other], now) { @@ -504,12 +338,9 @@ mod tests { labels, vec![ "5h limit".to_string(), - "Credits".to_string(), "codex-other 5h limit".to_string(), - "Credits".to_string(), ] ); - assert_eq!(rows.iter().filter(|row| row.label == "Credits").count(), 2); } #[test] @@ -517,7 +348,6 @@ mod tests { let now = Local::now(); let other = RateLimitSnapshotDisplay { limit_name: "codex-other".to_string(), - normal_model_slug: None, captured_at: now, primary: Some(RateLimitWindowDisplay { used_percent: 20.0, @@ -529,8 +359,6 @@ mod tests { resets_at: Some("later".to_string()), window_minutes: Some(2 * 60), }), - credits: None, - individual_limit: None, }; let rows = match compose_rate_limit_data_many(&[other], now) { diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_server_auth_not_required.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_server_auth_not_required.snap deleted file mode 100644 index a00c3ae0..00000000 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_server_auth_not_required.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: tui/src/status/tests.rs -expression: rendered ---- -/status - - >_ OpenAI Codex (v0.0.0) - - Model: gpt-5.6-sol (reasoning none, summaries auto) - Model provider: server-ollama - Directory: [[workspace]] - Permissions: Custom (workspace with network access, Ask for approval) - Agents.md: - - Token usage: 0 total (0 input + 0 output) - Limits: data not available yet diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_server_auth_required.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_server_auth_required.snap deleted file mode 100644 index f7be0da3..00000000 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_server_auth_required.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: tui/src/status/tests.rs -expression: rendered ---- -/status - - >_ OpenAI Codex (v0.0.0) - - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - - Model: gpt-5.6-sol (reasoning none, summaries auto) - Model provider: server-openai - Directory: [[workspace]] - Permissions: Custom (workspace with network access, Ask for approval) - Agents.md: - - Token usage: 0 total (0 input + 0 output) - Limits: data not available yet diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap index 0f7605b3..eafcec80 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for approval) diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap index 6783811c..9d910e7c 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap @@ -6,16 +6,13 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for approval) Agents.md: Account: user@example.com (Pro 200) + Token usage: 2K total (1.4K input + 600 output) Context window: 100% left (2.2K used / 272K) 5h limit: [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘] 55% left (resets 09:25) Weekly limit: [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘] 70% left (resets 09:55) - Credits: Available diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_enterprise_monthly_credit_limit.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_enterprise_monthly_credit_limit.snap deleted file mode 100644 index 92686ae3..00000000 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_enterprise_monthly_credit_limit.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: tui/src/status/tests.rs -expression: sanitized ---- -/status - - >_ OpenAI Codex (v0.0.0) - - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - - Model: gpt-5.1-codex-max (reasoning none, summaries auto) - Directory: [[workspace]] - Permissions: Custom (workspace with network access, Ask for approval) - Agents.md: - - Token usage: 1.2K total (800 input + 400 output) - Context window: 100% left (1.2K used / 272K) - Monthly credit limit: [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘] 68% left (resets 07:08 on 7 May) - 8,000 of 25,000 credits used diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_enterprise_monthly_credit_limit.snap.new b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_enterprise_monthly_credit_limit.snap.new deleted file mode 100644 index 5b64e5f8..00000000 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_enterprise_monthly_credit_limit.snap.new +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: tui/src/status/tests.rs -assertion_line: 1155 -expression: sanitized ---- -/status - - >_ OpenAI Codex (v0.0.0) - - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - - Model: gpt-5.1-codex-max (reasoning none, summaries auto) - Directory: [[workspace]] - Permissions: Custom (workspace with network access, Ask for approval) - Agents.md: - - Token usage: 1.2K total (800 input + 400 output) - Context window: 100% left (1.2K used / 272K) - Monthly credit limit: [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘] 68% left (resets 07:08 on 7 May) - 8000 of 25.000 credits used diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_forked_from.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_forked_from.snap index 9e2dde99..e5f82621 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_forked_from.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_forked_from.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for approval) @@ -18,4 +15,3 @@ expression: sanitized Token usage: 1.2K total (800 input + 400 output) Context window: 100% left (1.2K used / 272K) - Limits: data not available yet diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap index bdf79abd..85f3b1aa 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for approval) diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap index db8ba4ca..324f5418 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning high, summaries detailed) Directory: [[workspace]] Permissions: Workspace (Ask for approval) diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_local_background_server.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_local_background_server.snap index c20a5328..1b51580d 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_local_background_server.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_local_background_server.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Server: Local background server Model: gpt-5.1-codex-max (reasoning medium) @@ -18,4 +15,3 @@ expression: sanitized Token usage: 750 total (500 input + 250 output) Context window: 100% left (750 used / 272K) - Limits: data not available yet diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_remote_server.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_remote_server.snap index 57c04829..6305455c 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_remote_server.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_remote_server.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Server: unix:///tmp/codex-home/app-server-control/app-server- control.sock (v0.133.0) @@ -19,4 +16,3 @@ expression: sanitized Token usage: 750 total (500 input + 250 output) Context window: 100% left (750 used / 272K) - Limits: data not available yet diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_active_user_defined_profile.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_active_user_defined_profile.snap index e21309d2..4915f627 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_active_user_defined_profile.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_active_user_defined_profile.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Profile locked (read-only, Ask for approval) @@ -16,4 +13,3 @@ expression: sanitized Token usage: 0 total (0 input + 0 output) Context window: 100% left (0 used / 272K) - Limits: data not available yet diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_auto_review_permissions.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_auto_review_permissions.snap index a5c7c21c..abf08763 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_auto_review_permissions.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_auto_review_permissions.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Workspace (Approve for me) @@ -16,4 +13,3 @@ expression: sanitized Token usage: 0 total (0 input + 0 output) Context window: 100% left (0 used / 272K) - Limits: data not available yet diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_chatgpt_plan_without_email.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_chatgpt_plan_without_email.snap index df0b8002..5dfc014f 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_chatgpt_plan_without_email.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_chatgpt_plan_without_email.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for approval) @@ -16,4 +13,4 @@ expression: sanitized Account: Enterprise (Automation) ChatGPT workspace: Example workspace (account-123) - Limits: data not available yet + Token usage: 0 total (0 input + 0 output) diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap index 8899e4ee..96303e39 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for approval) @@ -16,4 +13,3 @@ expression: sanitized Token usage: 750 total (500 input + 250 output) Context window: 100% left (750 used / 272K) - Limits: data not available yet diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_refreshing_limits_notice.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_refreshing_limits_notice.snap deleted file mode 100644 index af4953d8..00000000 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_refreshing_limits_notice.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: tui/src/status/tests.rs -expression: sanitized ---- -/status - - >_ OpenAI Codex (v0.0.0) - - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - - Model: gpt-5.1-codex-max (reasoning none, summaries auto) - Directory: [[workspace]] - Permissions: Custom (workspace with network access, Ask for approval) - Agents.md: - - Token usage: 750 total (500 input + 250 output) - Context window: 100% left (750 used / 272K) - 5h limit: [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘] 55% left (resets 08:24) - Weekly limit: [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘] 70% left (resets 08:54) diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap index 2ec2677a..cc65af67 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for approval) diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_unavailable_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_unavailable_limits_message.snap index d83ee6f2..b2a36826 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_unavailable_limits_message.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_unavailable_limits_message.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for approval) diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_halfwidth_kana_in_narrow_terminal.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_halfwidth_kana_in_narrow_terminal.snap index 593ffd20..dd5bde67 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_halfwidth_kana_in_narrow_terminal.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_halfwidth_kana_in_narrow_terminal.snap @@ -6,10 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage - for up-to-date - information on rate limits and credits - Model: 「゙パ「゙パ「゙パ「゙ パ-model (reasoning none, summaries @@ -28,5 +24,5 @@ expression: sanitized Collaboration mode: 「゙パ collaboration mode - Limits: data not available - yet + Token usage: 0 total (0 input + + 0 output) diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap index be5c100e..92185e0d 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning high, summaries detailed) Directory: [[workspace]] diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_default_reasoning_when_config_empty.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_default_reasoning_when_config_empty.snap index 8661643e..21a71985 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_default_reasoning_when_config_empty.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_default_reasoning_when_config_empty.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning medium, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for approval) @@ -16,4 +13,3 @@ expression: sanitized Token usage: 750 total (500 input + 250 output) Context window: 100% left (750 used / 272K) - Limits: data not available yet diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_generic_limit_labels_for_unsupported_windows.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_generic_limit_labels_for_unsupported_windows.snap index 1ba1146d..1534bf0d 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_generic_limit_labels_for_unsupported_windows.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_generic_limit_labels_for_unsupported_windows.snap @@ -6,9 +6,6 @@ expression: sanitized >_ OpenAI Codex (v0.0.0) - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - Model: gpt-5.1-codex-max (reasoning none, summaries auto) Directory: [[workspace]] Permissions: Custom (workspace with network access, Ask for diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_wraps_enterprise_monthly_credit_details_in_narrow_terminal.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_wraps_enterprise_monthly_credit_details_in_narrow_terminal.snap deleted file mode 100644 index 29cf7973..00000000 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_wraps_enterprise_monthly_credit_details_in_narrow_terminal.snap +++ /dev/null @@ -1,30 +0,0 @@ ---- -source: tui/src/status/tests.rs -expression: sanitized ---- -/status - - >_ OpenAI Codex (v0.0.0) - - Visit https://chatgpt.com/settings/usage for - up-to-date - information on rate limits and credits - - Model: gpt-5.1-codex-max - (reasoning none, - summaries auto) - Directory: [[workspace]] - Permissions: Custom (workspace - with network access, - Ask for approval) - Agents.md: - - Token usage: 1.2K total (800 - input + 400 output) - Context window: 100% left (1.2K - used / 272K) - Monthly credit limit: 68% left - (resets 07:08 on - 7 May) - 8,000 of 25,000 - credits used diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__transcript_overlay_status_rate_limit_refresh.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__transcript_overlay_status_rate_limit_refresh.snap deleted file mode 100644 index 51fbff67..00000000 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__transcript_overlay_status_rate_limit_refresh.snap +++ /dev/null @@ -1,66 +0,0 @@ ---- -source: tui/src/status/tests.rs -expression: "format!(\"before:\\n{before}\\n\\nafter:\\n{after}\")" ---- -before: -/ T R A N S C R I P T / / / / / / / / / / / / / / / / / / / / / / / / / / / / / -/status - - >_ OpenAI Codex (v0.0.0) - - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - - Model: gpt-5.1-codex-max (reasoning none, summaries auto) - Directory: [[workspace]] - Permissions: Custom (workspace with network access, Ask for approval) - Agents.md: - - Token usage: 0 total (0 input + 0 output) - Limits: refresh requested; run /status again shortly. - - - - - - - - - - - -βŒƒspace select - ↑/↓ to scroll Β· pgup/pgdn to page Β· home/end to jump - q close Β· f3 find Β· esc browse prompts - - -after: -/ T R A N S C R I P T / / / / / / / / / / / / / / / / / / / / / / / / / / / / / -/status - - >_ OpenAI Codex (v0.0.0) - - Visit https://chatgpt.com/settings/usage for up-to-date - information on rate limits and credits - - Model: gpt-5.1-codex-max (reasoning none, summaries auto) - Directory: [[workspace]] - Permissions: Custom (workspace with network access, Ask for approval) - Agents.md: - - Token usage: 0 total (0 input + 0 output) - spark limit: - 5h limit: [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘] 55% left (resets soon) - Weekly limit: [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘] 70% left (resets later) - -next message - - - - - - - -βŒƒspace select - ↑/↓ to scroll Β· pgup/pgdn to page Β· home/end to jump - q close Β· f3 find Β· esc browse prompts diff --git a/codex-rs/tui/src/status/tests.rs b/codex-rs/tui/src/status/tests.rs index c51f429d..4c1f0a26 100644 --- a/codex-rs/tui/src/status/tests.rs +++ b/codex-rs/tui/src/status/tests.rs @@ -1,20 +1,11 @@ use super::new_status_output; -use super::new_status_output_with_rate_limits; use super::new_status_output_with_rate_limits_handle; use super::rate_limit_snapshot_display; -use super::rate_limits::RateLimitSnapshotDisplay; -use super::rate_limits::RateLimitWindowDisplay; -use super::rate_limits::SpendControlLimitSnapshotDisplay; -use super::rate_limits::StatusRateLimitData; -use super::rate_limits::compose_rate_limit_data_many; use crate::clock_format::ClockFormat; use crate::history_cell::HistoryCell; -use crate::history_cell::PlainHistoryCell; -use crate::keymap::RuntimeKeymap; use crate::legacy_core::config::Config; use crate::legacy_core::config::ConfigBuilder; use crate::legacy_core::config::PermissionProfileSnapshot; -use crate::pager_overlay::TranscriptOverlay; use crate::status::StatusAccountDisplay; use crate::status::remote_connection::RemoteConnectionStatus; use crate::test_support::PathBufExt; @@ -32,11 +23,8 @@ use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::CreditsSnapshot; use codex_app_server_protocol::RateLimitSnapshot; use codex_app_server_protocol::RateLimitWindow; -use codex_app_server_protocol::SpendControlLimitSnapshot; use codex_config::LoaderOverrides; use codex_config::types::AuthCredentialsStoreMode; -use codex_model_provider_info::ModelProviderAwsAuthInfo; -use codex_model_provider_info::ModelProviderInfo; use codex_models_manager::test_support::construct_model_info_offline_for_tests; use codex_models_manager::test_support::get_model_offline_for_tests; use codex_protocol::ThreadId; @@ -60,35 +48,6 @@ use ratatui::prelude::*; use std::sync::Arc; use tempfile::TempDir; -#[test] -fn stale_monthly_limit_marks_fresh_rolling_snapshot_stale() { - let now = Local::now(); - let snapshot = RateLimitSnapshotDisplay { - limit_name: "codex".to_string(), - normal_model_slug: None, - captured_at: now, - primary: Some(RateLimitWindowDisplay { - used_percent: 20.0, - resets_at: Some("soon".to_string()), - window_minutes: Some(300), - }), - secondary: None, - credits: None, - individual_limit: Some(SpendControlLimitSnapshotDisplay { - captured_at: now - ChronoDuration::minutes(20), - percent_remaining: 68.0, - used: "8,000".to_string(), - limit: "25,000".to_string(), - resets_at: Some("later".to_string()), - }), - }; - - assert!(matches!( - compose_rate_limit_data_many(&[snapshot], now), - StatusRateLimitData::Stale(_) - )); -} - fn app_server_workspace_write_profile(network_enabled: bool) -> PermissionProfile { PermissionProfile::Managed { network: if network_enabled { @@ -199,28 +158,6 @@ fn sanitize_directory(lines: Vec) -> Vec { .collect() } -fn buffer_to_text(buffer: &Buffer, width: u16) -> String { - let lines = buffer - .content - .chunks(usize::from(width)) - .map(|row| { - row.iter() - .map(|cell| { - let symbol = cell.symbol(); - symbol - .strip_prefix("\x1b]8;;") - .and_then(|symbol| symbol.split_once('\x07')) - .and_then(|(_, symbol)| symbol.strip_suffix("\x1b]8;;\x07")) - .unwrap_or(symbol) - }) - .collect::() - .trim_end() - .to_string() - }) - .collect::>(); - sanitize_directory(lines).join("\n") -} - fn reset_at_from(captured_at: &chrono::DateTime, seconds: i64) -> i64 { (*captured_at + ChronoDuration::seconds(seconds)) .with_timezone(&Utc) @@ -767,114 +704,6 @@ async fn status_snapshot_shows_active_user_defined_profile() { assert_snapshot!(sanitized); } -#[tokio::test] -async fn status_uses_server_provider_id_and_auth_requirement() { - let temp_home = TempDir::new().expect("temp home"); - let mut config = test_config(&temp_home).await; - config.model = Some("gpt-5.6-sol".to_string()); - set_workspace_cwd(&mut config, test_path_buf("/workspace/tests").abs()); - config.model_provider_id = "amazon-bedrock".to_string(); - config.model_provider = - ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo { - profile: None, - region: Some("eu-west-1".to_string()), - credential_export: None, - auth_refresh: None, - })); - config.model_provider.base_url = - Some("https://bedrock-mantle.us-east-1.api.aws/openai/v1".to_string()); - let usage = TokenUsage::default(); - let captured_at = chrono::Local - .with_ymd_and_hms(2024, 1, 2, 3, 4, 5) - .single() - .expect("timestamp"); - let model_slug = get_model_offline_for_tests(config.model.as_deref()); - - config.model_provider.requires_openai_auth = true; - let (composite, _handle) = new_status_output_with_rate_limits_handle( - &config, - /*requires_openai_auth*/ false, - Some("server-ollama"), - /*remote_connection*/ None, - test_status_account_display().as_ref(), - /*token_info*/ None, - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - /*rate_limits*/ &[], - None, - captured_at, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - "".to_string(), - /*refreshing_rate_limits*/ false, - ); - let rendered = - sanitize_directory(render_lines(&composite.display_lines(/*width*/ 120))).join("\n"); - assert_snapshot!("status_server_auth_not_required", rendered); - - config.model_provider_id = "openai-proxy".to_string(); - config.model_provider = ModelProviderInfo { - name: "OpenAI Proxy".to_string(), - base_url: Some("https://openai-proxy.example/v1".to_string()), - requires_openai_auth: false, - ..ModelProviderInfo::default() - }; - let (composite, _handle) = new_status_output_with_rate_limits_handle( - &config, - /*requires_openai_auth*/ true, - Some("server-openai"), - /*remote_connection*/ None, - test_status_account_display().as_ref(), - /*token_info*/ None, - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - /*rate_limits*/ &[], - None, - captured_at, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - "".to_string(), - /*refreshing_rate_limits*/ false, - ); - let rendered = - sanitize_directory(render_lines(&composite.display_lines(/*width*/ 120))).join("\n"); - assert_snapshot!("status_server_auth_required", rendered); - - for width in [24, 42, 120] { - let lines = composite.display_hyperlink_lines(width); - let mut fragments = String::new(); - let mut destinations = Vec::new(); - for line in lines { - let visible = line.line.to_string(); - for link in line.hyperlinks { - fragments.extend( - visible - .chars() - .skip(link.columns.start) - .take(link.columns.len()), - ); - destinations.push(link.destination); - } - } - assert_eq!( - fragments, "https://chatgpt.com/settings/usage", - "width {width}" - ); - assert!(!destinations.is_empty()); - assert!( - destinations - .iter() - .all(|destination| destination == "https://chatgpt.com/settings/usage") - ); - } -} - #[tokio::test] async fn status_snapshot_shows_auto_review_permissions() { let temp_home = TempDir::new().expect("temp home"); @@ -1089,84 +918,6 @@ async fn status_snapshot_includes_monthly_limit() { assert_snapshot!(sanitized); } -#[tokio::test] -async fn status_snapshot_includes_enterprise_monthly_credit_limit() { - let temp_home = TempDir::new().expect("temp home"); - let mut config = test_config(&temp_home).await; - config.model = Some("gpt-5.1-codex-max".to_string()); - config.model_provider_id = "openai".to_string(); - set_workspace_cwd(&mut config, test_path_buf("/workspace/tests").abs()); - - let account_display = test_status_account_display(); - let usage = TokenUsage { - input_tokens: 800, - cached_input_tokens: 0, - output_tokens: 400, - reasoning_output_tokens: 0, - total_tokens: 1_200, - }; - let captured_at = chrono::Local - .with_ymd_and_hms(2024, 5, 6, 7, 8, 9) - .single() - .expect("timestamp"); - let snapshot = RateLimitSnapshot { - limit_id: None, - limit_name: None, - normal_model_slug: None, - primary: None, - secondary: None, - credits: None, - individual_limit: Some(SpendControlLimitSnapshot { - limit: "25000".to_string(), - used: "8000".to_string(), - remaining_percent: 68, - resets_at: reset_at_from(&captured_at, /*seconds*/ 86_400), - }), - spend_control_reached: None, - plan_type: None, - rate_limit_reached_type: None, - }; - let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - - let model_slug = get_model_offline_for_tests(config.model.as_deref()); - let token_info = token_info_for(&model_slug, &config, &usage); - let composite = new_status_output( - &config, - account_display.as_ref(), - Some(&token_info), - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - Some(&rate_display), - None, - captured_at, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - ); - let mut rendered_lines = render_lines(&composite.display_lines(/*width*/ 92)); - if cfg!(windows) { - for line in &mut rendered_lines { - *line = line.replace('\\', "/"); - } - } - let sanitized = sanitize_directory(rendered_lines).join("\n"); - assert_snapshot!(sanitized); - - let mut rendered_lines = render_lines(&composite.display_lines(/*width*/ 46)); - if cfg!(windows) { - for line in &mut rendered_lines { - *line = line.replace('\\', "/"); - } - } - let sanitized = sanitize_directory(rendered_lines).join("\n"); - assert_snapshot!( - "status_snapshot_wraps_enterprise_monthly_credit_details_in_narrow_terminal", - sanitized - ); -} - #[tokio::test] async fn status_snapshot_uses_generic_limit_labels_for_unsupported_windows() { let temp_home = TempDir::new().expect("temp home"); @@ -1237,226 +988,6 @@ async fn status_snapshot_uses_generic_limit_labels_for_unsupported_windows() { assert_snapshot!(sanitized); } -#[tokio::test] -async fn status_snapshot_shows_unlimited_credits() { - let temp_home = TempDir::new().expect("temp home"); - let config = test_config(&temp_home).await; - let account_display = test_status_account_display(); - let usage = TokenUsage::default(); - let captured_at = chrono::Local - .with_ymd_and_hms(2024, 2, 3, 4, 5, 6) - .single() - .expect("timestamp"); - let snapshot = RateLimitSnapshot { - limit_id: None, - limit_name: None, - normal_model_slug: None, - primary: None, - secondary: None, - credits: Some(CreditsSnapshot { - has_credits: true, - unlimited: true, - balance: None, - }), - individual_limit: None, - spend_control_reached: None, - plan_type: None, - rate_limit_reached_type: None, - }; - let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - let model_slug = get_model_offline_for_tests(config.model.as_deref()); - let token_info = token_info_for(&model_slug, &config, &usage); - let composite = new_status_output( - &config, - account_display.as_ref(), - Some(&token_info), - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - Some(&rate_display), - None, - captured_at, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - ); - let rendered = render_lines(&composite.display_lines(/*width*/ 120)); - assert!( - rendered - .iter() - .any(|line| line.contains("Credits:") && line.contains("Unlimited")), - "expected Credits: Unlimited line, got {rendered:?}" - ); -} - -#[tokio::test] -async fn status_snapshot_shows_positive_credits() { - let temp_home = TempDir::new().expect("temp home"); - let config = test_config(&temp_home).await; - let account_display = test_status_account_display(); - let usage = TokenUsage::default(); - let captured_at = chrono::Local - .with_ymd_and_hms(2024, 3, 4, 5, 6, 7) - .single() - .expect("timestamp"); - let snapshot = RateLimitSnapshot { - limit_id: None, - limit_name: None, - normal_model_slug: None, - primary: None, - secondary: None, - credits: Some(CreditsSnapshot { - has_credits: true, - unlimited: false, - balance: Some("12.5".to_string()), - }), - individual_limit: None, - spend_control_reached: None, - plan_type: None, - rate_limit_reached_type: None, - }; - let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - let model_slug = get_model_offline_for_tests(config.model.as_deref()); - let token_info = token_info_for(&model_slug, &config, &usage); - let composite = new_status_output( - &config, - account_display.as_ref(), - Some(&token_info), - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - Some(&rate_display), - None, - captured_at, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - ); - let rendered = render_lines(&composite.display_lines(/*width*/ 120)); - assert!( - rendered - .iter() - .any(|line| line.contains("Credits:") && line.contains("13 credits")), - "expected Credits line with rounded credits, got {rendered:?}" - ); -} - -#[tokio::test] -async fn status_snapshot_shows_available_credits_without_display_balance() { - let temp_home = TempDir::new().expect("temp home"); - let config = test_config(&temp_home).await; - let account_display = test_status_account_display(); - let usage = TokenUsage::default(); - let captured_at = chrono::Local - .with_ymd_and_hms(2024, 4, 5, 6, 7, 8) - .single() - .expect("timestamp"); - let model_slug = get_model_offline_for_tests(config.model.as_deref()); - let token_info = token_info_for(&model_slug, &config, &usage); - for balance in [ - None, - Some(String::new()), - Some("0".to_string()), - Some("not-a-number".to_string()), - Some("inf".to_string()), - ] { - let snapshot = RateLimitSnapshot { - limit_id: None, - limit_name: None, - normal_model_slug: None, - primary: None, - secondary: None, - credits: Some(CreditsSnapshot { - has_credits: true, - unlimited: false, - balance, - }), - individual_limit: None, - spend_control_reached: None, - plan_type: None, - rate_limit_reached_type: None, - }; - let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - let composite = new_status_output( - &config, - account_display.as_ref(), - Some(&token_info), - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - Some(&rate_display), - None, - captured_at, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - ); - let rendered = render_lines(&composite.display_lines(/*width*/ 120)); - assert!( - rendered - .iter() - .any(|line| line.contains("Credits:") && line.contains("Available")), - "expected Credits: Available line, got {rendered:?}" - ); - } -} - -#[tokio::test] -async fn status_snapshot_respects_unlimited_without_has_credits_flag() { - let temp_home = TempDir::new().expect("temp home"); - let config = test_config(&temp_home).await; - let account_display = test_status_account_display(); - let usage = TokenUsage::default(); - let captured_at = chrono::Local - .with_ymd_and_hms(2024, 5, 6, 7, 8, 9) - .single() - .expect("timestamp"); - let snapshot = RateLimitSnapshot { - limit_id: None, - limit_name: None, - normal_model_slug: None, - primary: None, - secondary: None, - credits: Some(CreditsSnapshot { - has_credits: false, - unlimited: true, - balance: None, - }), - individual_limit: None, - spend_control_reached: None, - plan_type: None, - rate_limit_reached_type: None, - }; - let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - let model_slug = get_model_offline_for_tests(config.model.as_deref()); - let token_info = token_info_for(&model_slug, &config, &usage); - let composite = new_status_output( - &config, - account_display.as_ref(), - Some(&token_info), - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - Some(&rate_display), - None, - captured_at, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - ); - let rendered = render_lines(&composite.display_lines(/*width*/ 120)); - assert!( - rendered - .iter() - .any(|line| line.contains("Credits:") && line.contains("Unlimited")), - "expected Credits: Unlimited line, got {rendered:?}" - ); -} - #[tokio::test] async fn status_card_token_usage_excludes_cached_tokens() { let temp_home = TempDir::new().expect("temp home"); @@ -1514,7 +1045,6 @@ async fn status_wraps_long_paths_and_session_ids_without_losing_text() { let usage = TokenUsage::default(); let (status, handle) = new_status_output_with_rate_limits_handle( &config, - /*requires_openai_auth*/ true, /*model_provider_id*/ None, /*remote_connection*/ None, /*account_display*/ None, @@ -1530,7 +1060,6 @@ async fn status_wraps_long_paths_and_session_ids_without_losing_text() { /*collaboration_mode*/ None, /*reasoning_effort_override*/ None, "".to_string(), - /*refreshing_rate_limits*/ false, ); let directory = directory.to_string_lossy(); for width in [7, 12, 17, 18, 24, 25, 40, 80] { @@ -1754,8 +1283,7 @@ async fn status_snapshot_uses_default_reasoning_when_config_empty() { let token_info = token_info_for(&model_slug, &config, &usage); let (composite, _) = new_status_output_with_rate_limits_handle( &config, - /*requires_openai_auth*/ true, - /*model_provider_id*/ None, + /*model_provider_id*/ None, remote_connection.as_ref(), account_display.as_ref(), Some(&token_info), @@ -1770,8 +1298,7 @@ async fn status_snapshot_uses_default_reasoning_when_config_empty() { /*collaboration_mode*/ None, /*reasoning_effort_override*/ Some(Some(ReasoningEffort::Medium)), "".to_string(), - /*refreshing_rate_limits*/ false, - ); + ); let mut rendered_lines = render_lines(&composite.display_lines(/*width*/ 80)); if cfg!(windows) { for line in &mut rendered_lines { @@ -1783,159 +1310,6 @@ async fn status_snapshot_uses_default_reasoning_when_config_empty() { } } -#[tokio::test] -async fn status_snapshot_shows_refreshing_limits_notice() { - let temp_home = TempDir::new().expect("temp home"); - let mut config = test_config(&temp_home).await; - config.model = Some("gpt-5.1-codex-max".to_string()); - set_workspace_cwd(&mut config, test_path_buf("/workspace/tests").abs()); - - let usage = TokenUsage { - input_tokens: 500, - cached_input_tokens: 0, - output_tokens: 250, - reasoning_output_tokens: 0, - total_tokens: 750, - }; - let captured_at = chrono::Local - .with_ymd_and_hms(2024, 6, 7, 8, 9, 10) - .single() - .expect("timestamp"); - let snapshot = RateLimitSnapshot { - limit_id: None, - limit_name: None, - normal_model_slug: None, - primary: Some(RateLimitWindow { - used_percent: 45, - window_duration_mins: Some(300), - resets_at: Some(reset_at_from(&captured_at, /*seconds*/ 900)), - }), - secondary: Some(RateLimitWindow { - used_percent: 30, - window_duration_mins: Some(10_080), - resets_at: Some(reset_at_from(&captured_at, /*seconds*/ 2_700)), - }), - credits: None, - individual_limit: None, - spend_control_reached: None, - plan_type: None, - rate_limit_reached_type: None, - }; - let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - - let model_slug = get_model_offline_for_tests(config.model.as_deref()); - let token_info = token_info_for(&model_slug, &config, &usage); - let composite = new_status_output_with_rate_limits( - &config, - /*account_display*/ None, - Some(&token_info), - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - std::slice::from_ref(&rate_display), - None, - captured_at, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - /*refreshing_rate_limits*/ true, - ); - let mut rendered_lines = render_lines(&composite.display_lines(/*width*/ 80)); - if cfg!(windows) { - for line in &mut rendered_lines { - *line = line.replace('\\', "/"); - } - } - let sanitized = sanitize_directory(rendered_lines).join("\n"); - assert_snapshot!(sanitized); -} - -#[tokio::test] -async fn transcript_overlay_remeasures_status_after_rate_limit_refresh() { - let temp_home = TempDir::new().expect("temp home"); - let mut config = test_config(&temp_home).await; - config.model = Some("gpt-5.1-codex-max".to_string()); - set_workspace_cwd(&mut config, test_path_buf("/workspace/tests").abs()); - let usage = TokenUsage::default(); - let now = Local - .with_ymd_and_hms(2024, 6, 7, 8, 9, 10) - .single() - .expect("timestamp"); - let model_slug = get_model_offline_for_tests(config.model.as_deref()); - - let (status, handle) = new_status_output_with_rate_limits_handle( - &config, - /*requires_openai_auth*/ true, - /*model_provider_id*/ None, - /*remote_connection*/ None, - /*account_display*/ None, - /*token_info*/ None, - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - /*rate_limits*/ &[], - None, - now, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - "".to_string(), - /*refreshing_rate_limits*/ true, - ); - let mut overlay = - TranscriptOverlay::new(vec![Arc::new(status)], RuntimeKeymap::defaults().pager); - let area = Rect::new( - /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 30, - ); - let mut buffer = Buffer::empty(area); - overlay.render(area, &mut buffer); - let before = buffer_to_text(&buffer, area.width); - - handle.finish_rate_limit_refresh( - &[RateLimitSnapshotDisplay { - limit_name: "spark".to_string(), - normal_model_slug: None, - captured_at: now, - primary: Some(RateLimitWindowDisplay { - used_percent: 45.0, - resets_at: Some("soon".to_string()), - window_minutes: Some(300), - }), - secondary: Some(RateLimitWindowDisplay { - used_percent: 30.0, - resets_at: Some("later".to_string()), - window_minutes: Some(10_080), - }), - credits: None, - individual_limit: None, - }], - now, - ); - overlay.insert_cell(Arc::new(PlainHistoryCell::new(vec!["next message".into()]))); - buffer = Buffer::empty(area); - overlay.render(area, &mut buffer); - let after = buffer_to_text(&buffer, area.width); - - assert!( - after.contains("spark limit"), - "status output was clipped: {after:?}" - ); - assert!( - after.contains("5h limit"), - "status output was clipped: {after:?}" - ); - assert!( - after.contains("Weekly limit"), - "status output was clipped: {after:?}" - ); - insta::assert_snapshot!( - "transcript_overlay_status_rate_limit_refresh", - format!("before:\n{before}\n\nafter:\n{after}") - ); -} - #[tokio::test] async fn status_snapshot_includes_credits_and_limits() { let temp_home = TempDir::new().expect("temp home"); @@ -2074,67 +1448,6 @@ async fn status_snapshot_shows_unavailable_limits_message() { assert_snapshot!(sanitized); } -#[tokio::test] -async fn status_snapshot_treats_refreshing_empty_limits_as_unavailable() { - let temp_home = TempDir::new().expect("temp home"); - let mut config = test_config(&temp_home).await; - config.model = Some("gpt-5.1-codex-max".to_string()); - set_workspace_cwd(&mut config, test_path_buf("/workspace/tests").abs()); - - let usage = TokenUsage { - input_tokens: 500, - cached_input_tokens: 0, - output_tokens: 250, - reasoning_output_tokens: 0, - total_tokens: 750, - }; - - let snapshot = RateLimitSnapshot { - limit_id: None, - limit_name: None, - normal_model_slug: None, - primary: None, - secondary: None, - credits: None, - individual_limit: None, - spend_control_reached: None, - plan_type: None, - rate_limit_reached_type: None, - }; - let captured_at = chrono::Local - .with_ymd_and_hms(2024, 6, 7, 8, 9, 10) - .single() - .expect("timestamp"); - let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - - let model_slug = get_model_offline_for_tests(config.model.as_deref()); - let token_info = token_info_for(&model_slug, &config, &usage); - let composite = new_status_output_with_rate_limits( - &config, - /*account_display*/ None, - Some(&token_info), - &usage, - &None, - /*thread_name*/ None, - /*forked_from*/ None, - std::slice::from_ref(&rate_display), - None, - captured_at, - &model_slug, - /*collaboration_mode*/ None, - /*reasoning_effort_override*/ None, - /*refreshing_rate_limits*/ true, - ); - let mut rendered_lines = render_lines(&composite.display_lines(/*width*/ 80)); - if cfg!(windows) { - for line in &mut rendered_lines { - *line = line.replace('\\', "/"); - } - } - let sanitized = sanitize_directory(rendered_lines).join("\n"); - assert!(sanitized.contains("Limits: not available for this account")); -} - #[tokio::test] async fn status_snapshot_shows_stale_limits_message() { let temp_home = TempDir::new().expect("temp home"); diff --git a/codex-rs/tui/src/subscription.rs b/codex-rs/tui/src/subscription.rs index 1add0a93..c8656b33 100644 --- a/codex-rs/tui/src/subscription.rs +++ b/codex-rs/tui/src/subscription.rs @@ -5,7 +5,6 @@ use codex_protocol::auth::KnownPlan; pub(crate) enum SubscriptionDisplay { Status, - Analytics, } impl SubscriptionDisplay { @@ -20,22 +19,16 @@ impl SubscriptionDisplay { (PlanType::Team | PlanType::SelfServeBusinessUsageBased, _) => "Business", (PlanType::Business, Self::Status) => "Enterprise", (PlanType::SelfServeBusinessProLite, Self::Status) => "Business Premium", - (PlanType::Business | PlanType::SelfServeBusinessProLite, Self::Analytics) => { - "Business" - } (PlanType::EnterpriseCbpAutomation, Self::Status) => "Enterprise (Automation)", - (PlanType::EnterpriseCbpAutomation, Self::Analytics) - | (PlanType::Enterprise | PlanType::Ent26 | PlanType::EnterpriseCbpUsageBased, _) => { + (PlanType::Enterprise | PlanType::Ent26 | PlanType::EnterpriseCbpUsageBased, _) => { "Enterprise" } (PlanType::Edu, Self::Status) => "Edu", (PlanType::EduPlus, Self::Status) => "Edu Plus", (PlanType::EduPro, Self::Status) => "Edu Pro", - (PlanType::Edu | PlanType::EduPlus | PlanType::EduPro, Self::Analytics) => "Education", (PlanType::Sci, _) => KnownPlan::Sci.display_name(), (PlanType::SciPlus, _) => KnownPlan::SciPlus.display_name(), (PlanType::Unknown, Self::Status) => "Unknown", - (PlanType::Unknown, Self::Analytics) => "Account", } } } diff --git a/codex-rs/tui/src/tui/history_tail.rs b/codex-rs/tui/src/tui/history_tail.rs index f9a2c9b8..aef2968f 100644 --- a/codex-rs/tui/src/tui/history_tail.rs +++ b/codex-rs/tui/src/tui/history_tail.rs @@ -1,17 +1,8 @@ -//! Update visible terminal-history tails without discarding terminal scrollback. -//! When the existing tail is an unchanged prefix, append only the new rows. +//! Test access to terminal-history lines queued for insertion. use super::Tui; -use crate::custom_terminal::Terminal as CustomTerminal; -use crate::insert_history::HistoryLineWrapPolicy; -use crate::insert_history::InsertHistoryMode; -use crate::insert_history::insert_history_hyperlink_lines_with_mode_and_wrap_policy; -use crate::insert_history::wrap_history_hyperlink_lines; +#[cfg(test)] use crate::terminal_hyperlinks::HyperlinkLine; -use ratatui::backend::Backend; -use ratatui::layout::Position; -use std::io; -use std::io::Write; impl Tui { #[cfg(test)] @@ -21,70 +12,4 @@ impl Tui { .flat_map(|batch| batch.lines.iter().cloned()) .collect() } - - pub(crate) fn replace_visible_history_tail( - &mut self, - previous_lines: &[HyperlinkLine], - replacement: &[HyperlinkLine], - wrap_policy: HistoryLineWrapPolicy, - ) -> io::Result { - let screen_size = self.terminal.last_known_screen_size; - Self::flush_pending_history_lines( - &mut self.terminal, - &mut self.pending_history_lines, - self.scrollback, - screen_size, - )?; - let mode = self.scrollback.history_insertion_mode(wrap_policy); - let replaced = replace_visible_terminal_history_tail( - &mut self.terminal, - previous_lines, - replacement, - mode, - wrap_policy, - )?; - if replaced { - self.frame_requester().schedule_frame(); - } - Ok(replaced) - } } - -fn replace_visible_terminal_history_tail( - terminal: &mut CustomTerminal, - previous_lines: &[HyperlinkLine], - replacement: &[HyperlinkLine], - mode: InsertHistoryMode, - wrap_policy: HistoryLineWrapPolicy, -) -> io::Result -where - B: Backend + Write, -{ - let screen_size = terminal.last_known_screen_size; - let mut viewport = terminal.viewport_area; - let wrap_width = usize::from(viewport.width.max(/*other*/ 1)); - let (_, previous_rows) = wrap_history_hyperlink_lines(previous_lines, wrap_width, wrap_policy); - let Ok(previous_rows) = u16::try_from(previous_rows) else { - return Ok(false); - }; - if previous_rows > viewport.top() { - return Ok(false); - } - - viewport.y -= previous_rows; - terminal.clear_after_position(Position::new(/*x*/ 0, viewport.y))?; - terminal.set_viewport_area(viewport); - terminal.invalidate_viewport(); - insert_history_hyperlink_lines_with_mode_and_wrap_policy( - terminal, - replacement, - mode, - wrap_policy, - screen_size, - )?; - Ok(true) -} - -#[cfg(test)] -#[path = "history_tail_tests.rs"] -mod tests; diff --git a/codex-rs/tui/src/tui/history_tail_tests.rs b/codex-rs/tui/src/tui/history_tail_tests.rs deleted file mode 100644 index 9c1c3b07..00000000 --- a/codex-rs/tui/src/tui/history_tail_tests.rs +++ /dev/null @@ -1,178 +0,0 @@ -use super::replace_visible_terminal_history_tail; -use crate::custom_terminal::Terminal; -use crate::insert_history::HistoryLineWrapPolicy; -use crate::insert_history::InsertHistoryMode; -use crate::insert_history::insert_history_lines; -use crate::terminal_hyperlinks::plain_hyperlink_lines; -use crate::test_backend::VT100Backend; -use pretty_assertions::assert_eq; -use ratatui::layout::Rect; -use ratatui::text::Line; -use std::io::Write; - -#[test] -fn replacing_visible_history_tail_preserves_existing_terminal_scrollback() { - let width = 52; - let height = 8; - let backend = VT100Backend::with_scrollback(width, height, /*scrollback_len*/ 32); - let mut terminal = Terminal::with_options(backend).expect("terminal"); - for line in [ - "shell history that predates Codex", - "shell output one", - "shell output two", - "shell output three", - "shell output four", - "shell output five", - "shell output six", - "shell output seven", - ] { - writeln!(terminal.backend_mut(), "{line}\r").expect("seed shell history"); - } - terminal.set_viewport_area(Rect::new( - /*x*/ 0, - /*y*/ height - 2, - width, - /*height*/ 2, - )); - insert_history_lines( - &mut terminal, - vec![ - Line::from("/status"), - Line::from("Account: business"), - Line::from("old closing border"), - ], - ) - .expect("insert initial status card"); - - let previous_lines = plain_hyperlink_lines(vec![Line::from("old closing border")]); - let replacement = plain_hyperlink_lines(vec![ - Line::from("Thread usage: 50 credits"), - Line::from("new closing border"), - ]); - assert!( - replace_visible_terminal_history_tail( - &mut terminal, - &previous_lines, - &replacement, - InsertHistoryMode::Standard, - HistoryLineWrapPolicy::PreWrap, - ) - .expect("replace status-card tail") - ); - - let contents = terminal.backend().vt100().screen().contents(); - assert!(contents.contains("/status"), "{contents}"); - assert!(contents.contains("Account: business"), "{contents}"); - assert!(contents.contains("Thread usage: 50 credits"), "{contents}"); - assert!(!contents.contains("old closing border"), "{contents}"); - - let mut screen_with_scrollback = terminal.backend().vt100().screen().clone(); - screen_with_scrollback.set_scrollback(/*rows*/ usize::MAX); - let scrollback = screen_with_scrollback.contents(); - assert!( - scrollback.contains("shell history that predates Codex"), - "existing terminal scrollback was discarded: {scrollback}" - ); -} - -#[test] -fn inaccessible_history_tail_is_preserved_for_non_destructive_append() { - let width = 36; - let height = 6; - let backend = VT100Backend::with_scrollback(width, height, /*scrollback_len*/ 16); - let mut terminal = Terminal::with_options(backend).expect("terminal"); - terminal.set_viewport_area(Rect::new( - /*x*/ 0, - /*y*/ 1, - width, - /*height*/ height - 1, - )); - let before = terminal.backend().vt100().screen().contents(); - let previous_lines = - plain_hyperlink_lines(vec![Line::from("first line"), Line::from("second line")]); - let replacement = plain_hyperlink_lines(vec![Line::from("Thread usage: 50 credits")]); - - assert!( - !replace_visible_terminal_history_tail( - &mut terminal, - &previous_lines, - &replacement, - InsertHistoryMode::Standard, - HistoryLineWrapPolicy::PreWrap, - ) - .expect("leave inaccessible history untouched") - ); - assert_eq!(terminal.backend().vt100().screen().contents(), before); -} - -#[test] -fn appending_to_unchanged_history_tail_preserves_existing_rows() { - let width = 52; - let height = 8; - let backend = VT100Backend::new(width, height); - let mut terminal = Terminal::with_options(backend).expect("terminal"); - terminal.set_viewport_area(Rect::new( - /*x*/ 0, /*y*/ 0, width, /*height*/ 2, - )); - insert_history_lines( - &mut terminal, - vec![Line::from("/status"), Line::from("Account: business")], - ) - .expect("insert initial status card"); - let replacement = plain_hyperlink_lines(vec![Line::from("Thread usage: 50 credits")]); - - assert!( - replace_visible_terminal_history_tail( - &mut terminal, - /*previous_lines*/ &[], - &replacement, - InsertHistoryMode::Standard, - HistoryLineWrapPolicy::PreWrap, - ) - .expect("append late billing details") - ); - assert_eq!( - terminal.backend().vt100().screen().contents(), - "/status\nAccount: business\nThread usage: 50 credits" - ); -} - -#[test] -fn replacing_soft_wrapped_history_counts_physical_terminal_rows() { - let width = 12; - let height = 8; - let backend = VT100Backend::new(width, height); - let mut terminal = Terminal::with_options(backend).expect("terminal"); - terminal.set_viewport_area(Rect::new( - /*x*/ 0, - /*y*/ height - 2, - width, - /*height*/ 2, - )); - let previous_lines = plain_hyperlink_lines(vec![Line::from("old-long-line-spanning-two-rows")]); - let screen_size = terminal.last_known_screen_size; - crate::insert_history::insert_history_hyperlink_lines_with_mode_and_wrap_policy( - &mut terminal, - &previous_lines, - InsertHistoryMode::Standard, - HistoryLineWrapPolicy::Terminal, - screen_size, - ) - .expect("insert soft-wrapped history"); - let replacement = plain_hyperlink_lines(vec![Line::from("new billing")]); - - assert!( - replace_visible_terminal_history_tail( - &mut terminal, - &previous_lines, - &replacement, - InsertHistoryMode::Standard, - HistoryLineWrapPolicy::Terminal, - ) - .expect("replace physically wrapped rows") - ); - let contents = terminal.backend().vt100().screen().contents(); - assert!(contents.contains("new billing"), "{contents}"); - assert!(!contents.contains("old-long"), "{contents}"); - assert!(!contents.contains("spanning"), "{contents}"); -}