diff --git a/README.md b/README.md
index 06b02fce..5dbbec95 100644
--- a/README.md
+++ b/README.md
@@ -1,81 +1,87 @@
-
Codex CLI is a coding agent from OpenAI that runs locally on your computer.
-
-
-
-
-If you want Codex in your code editor (VS Code, Cursor, Windsurf), install in your IDE.
-If you want the desktop app experience, run codex app or visit the Codex App page.
-If you are looking for the cloud-based agent from OpenAI, Codex Web, go to chatgpt.com/codex.
+# aKode
+
+**aKode** è un agente di coding da terminale, privato e a uso personale, che lavora **solo con modelli scelti da te**: il tuo server locale o qualsiasi endpoint compatibile con OpenAI. Non contatta mai OpenAI o ChatGPT.
+
+È un fork di [OpenAI Codex CLI](https://github.com/openai/codex) (Apache-2.0). Da Codex eredita l'interfaccia a terminale, l'esecuzione dei comandi in sandbox, la modifica dei file con patch, MCP, skill, plugin locali e la modalità non interattiva `exec`. Ha però tolto tutto ciò che dipende dai servizi di OpenAI.
+
+> **Uso privato.** Questo repository (`git.difonzo.net/andrea/aKode`) non è distribuito né pubblicato.
---
-## Quickstart
+## Stato del lavoro
-### Installing and running Codex CLI
+| Fase | Contenuto | Stato |
+|---|---|---|
+| 1 | Telemetria e chiamate automatiche: Statsig, analytics, invio a Sentry, controllo aggiornamenti, suggerimento del giorno, sincronizzazione plugin OpenAI, CDN dei pets, CIMD `chatgpt.com` | ✅ |
+| 2a | Funzioni periferiche ChatGPT: `cloud`, `apply`, `app`, `remote-control`, proxy Responses verso OpenAI, decisions di guardian, sonde di `doctor` verso OpenAI. Il vocale non ha più fallback verso OpenAI | ✅ |
+| 2b-1 | Backend ChatGPT: utilizzo, limiti e crediti, configurazione cloud, app e connettori ChatGPT, plugin remoti, upload di file, attribuzione git remota | 🟡 in corso |
+| 2b-2 | Login ChatGPT/OAuth, identità agente, token personali: resta solo l'autenticazione con chiave API | ⏳ |
+| 3 | Provider: nessun default OpenAI; Ollama, LM Studio ed endpoint personalizzati; elenco modelli letto dal server; unione dei messaggi di sistema per i modelli locali | ⏳ |
+| 4 | Primo avvio: una schermata per URL, chiave API e modello, con test della connessione | ⏳ |
+| 5 | Rebranding completo: comando `akode`, `~/.akode`, variabili `AKODE_*`, crate `akode-*` | ⏳ |
+| 6 | Verifica finale e installatore locale | ⏳ |
-Run the following on Mac or Linux to install Codex CLI:
+Finché la fase 5 non è completa, il binario, la cartella di configurazione e le variabili d'ambiente usano ancora i nomi di Codex: `codex`, `~/.codex`, `CODEX_*`.
-```shell
-curl -fsSL https://chatgpt.com/codex/install.sh | sh
+---
+
+## Requisiti
+
+- macOS (Apple Silicon) o Linux.
+- Rust tramite `rustup`: la toolchain richiesta (`codex-rs/rust-toolchain.toml`) viene installata automaticamente.
+- `git`.
+- Un endpoint LLM che supporti la **Responses API** (`POST /v1/responses`). Codex/aKode non usa più `/chat/completions`.
+
+## Compilazione
+
+```bash
+cd codex-rs
+
+# build leggera: meno spazio su disco, niente debuginfo
+export CARGO_NET_GIT_FETCH_WITH_CLI=true
+export CARGO_PROFILE_DEV_DEBUG=0
+export CARGO_INCREMENTAL=0
+
+cargo build -p codex-cli --bin codex # debug
+cargo build -p codex-cli --bin codex --release # release
```
-Run the following on Windows to install Codex CLI:
+Per i test serve uno stack più grande: `export RUST_MIN_STACK=8388608`. Testa un crate alla volta (`cargo test -p --lib`). La cartella `codex-rs/target` può superare i 50 GB: cancellala quando non serve.
-```shell
-powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"
+## Configurazione di un modello
+
+In `~/.codex/config.toml` (dopo la fase 5 diventerà `~/.akode/config.toml`):
+
+```toml
+model_provider = "imeai"
+model = "qwen3.6-35b-a3b"
+model_context_window = 131072
+
+[model_providers.imeai]
+name = "imeAI (Qwen3.6 su ik_llama.cpp)"
+base_url = "http://192.168.40.25:8080/v1"
+env_key = "IMEAI_API_KEY" # la chiave si legge da questa variabile d'ambiente
+wire_api = "responses"
```
-The standalone installers download from `https://releases.openai.com/codex` by default and fall back to GitHub Releases if a metadata or asset download is unavailable. To force GitHub Releases, set `CODEX_INSTALLER_USE_RELEASES_OPENAI_COM` to `false` (`0` and `no` are also accepted):
-
-```shell
-curl -fsSL https://chatgpt.com/codex/install.sh | CODEX_INSTALLER_USE_RELEASES_OPENAI_COM=false sh
+```bash
+export IMEAI_API_KEY="..." # chiave del server
+codex exec "descrivi questo progetto"
```
-```powershell
-$env:CODEX_INSTALLER_USE_RELEASES_OPENAI_COM='false'; irm https://chatgpt.com/codex/install.ps1 | iex
-```
+**Server llama.cpp / ik_llama.cpp con Qwen3.x:** aKode invia più messaggi di sistema/developer. Il template originale di Qwen li rifiuta ("System message must be at the beginning"), quindi va usato un template che li accetti (`--chat-template-file`). Il server imeAI usa `/etc/llama/qwen36-multisys.jinja`. Con la fase 3 aKode li unirà da solo.
-Codex CLI can also be installed via the following package managers:
+**Interfaccia interattiva:** in questa fase la TUI richiede un'installazione impacchettata. Lanciata da `target/` funziona solo `codex exec`, oppure `codex --no-daemon`. L'installatore locale arriva con la fase 6.
-```shell
-# Install using npm
-npm install -g @openai/codex
-```
+---
-```shell
-# Install using Homebrew
-brew install --cask codex
-```
+## Cosa è stato tolto rispetto a Codex
-Then simply run `codex` to get started.
+- **Telemetria e analytics:** nessun invio. L'export OpenTelemetry funziona solo se lo configuri tu esplicitamente.
+- **Login e servizi ChatGPT:** niente login con l'account ChatGPT, niente attività cloud, app, connettori, plugin remoti, utilizzo e crediti, configurazione gestita dal cloud.
+- **Rete in automatico:** nessun controllo aggiornamenti, annuncio, download di asset o sincronizzazione di plugin all'avvio.
+- **Feedback:** nessun upload a Sentry; resta solo il salvataggio locale.
-
-You can also go to the latest GitHub Release and download the appropriate binary for your platform.
+## Licenza
-Each GitHub Release contains many executables, but in practice, you likely want one of these:
-
-- macOS
- - Apple Silicon/arm64: `codex-aarch64-apple-darwin.tar.gz`
- - x86_64 (older Mac hardware): `codex-x86_64-apple-darwin.tar.gz`
-- Linux
- - x86_64: `codex-x86_64-unknown-linux-musl.tar.gz`
- - arm64: `codex-aarch64-unknown-linux-musl.tar.gz`
-
-Each archive contains a single entry with the platform baked into the name (e.g., `codex-x86_64-unknown-linux-musl`), so you likely want to rename it to `codex` after extracting it.
-
-
-
-### Using Codex with your ChatGPT plan
-
-Run `codex` and select **Sign in with ChatGPT**. We recommend signing into your ChatGPT account to use Codex as part of your Plus, Pro, Business, Edu, or Enterprise plan. [Learn more about what's included in your ChatGPT plan](https://help.openai.com/en/articles/11369540-codex-in-chatgpt).
-
-You can also use Codex with an API key, but this requires [additional setup](https://developers.openai.com/codex/auth#sign-in-with-an-api-key).
-
-## Docs
-
-- [**Codex Documentation**](https://developers.openai.com/codex)
-- [**Contributing**](./docs/contributing.md)
-- [**Installing & building**](./docs/install.md)
-- [**Open source fund**](./docs/open-source-fund.md)
-
-This repository is licensed under the [Apache-2.0 License](LICENSE).
+aKode deriva da OpenAI Codex CLI ed è rilasciato sotto la stessa [licenza Apache-2.0](LICENSE); vedi anche [NOTICE](NOTICE). Il codice è stato modificato in modo esteso: la cronologia git del repository documenta ogni modifica rispetto al commit di base `7874033`. "OpenAI" e "Codex" sono marchi dei rispettivi proprietari. aKode non è affiliato né approvato da OpenAI.
diff --git a/codex-rs/core-plugins/src/remote/share/checkout.rs b/codex-rs/core-plugins/src/remote/share/checkout.rs
deleted file mode 100644
index 223c667b..00000000
--- a/codex-rs/core-plugins/src/remote/share/checkout.rs
+++ /dev/null
@@ -1,472 +0,0 @@
-use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
-use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME;
-use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME;
-use super::super::RemotePluginCatalogError;
-use super::super::RemotePluginServiceConfig;
-use super::local_paths;
-use codex_app_server_protocol::PluginAuthPolicy;
-use codex_app_server_protocol::PluginInstallPolicy;
-use codex_login::CodexAuth;
-use codex_plugin::PluginId;
-use codex_plugin::validate_plugin_segment;
-use codex_utils_absolute_path::AbsolutePathBuf;
-use serde_json::Value as JsonValue;
-use serde_json::json;
-use std::collections::BTreeMap;
-use std::fs;
-use std::io;
-use std::io::Write;
-use std::path::Component;
-use std::path::Path;
-
-const PERSONAL_MARKETPLACE_NAME: &str = "codex-curated";
-const PERSONAL_MARKETPLACE_DISPLAY_NAME: &str = "Personal";
-const PERSONAL_MARKETPLACE_RELATIVE_PATH: &str = ".agents/plugins/marketplace.json";
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct RemotePluginShareCheckoutResult {
- pub remote_plugin_id: String,
- pub plugin_id: String,
- pub plugin_name: String,
- pub plugin_path: AbsolutePathBuf,
- pub marketplace_name: String,
- pub marketplace_path: AbsolutePathBuf,
- pub remote_version: Option,
-}
-
-pub async fn checkout_remote_plugin_share(
- config: &RemotePluginServiceConfig,
- auth: Option<&CodexAuth>,
- codex_home: &Path,
- remote_plugin_id: &str,
-) -> Result {
- let config = &config.for_current_account();
- let detail = super::super::fetch_remote_plugin_detail_with_download_urls(
- config,
- auth,
- REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME,
- remote_plugin_id,
- )
- .await?;
- let plugin_name = detail.summary.name.clone();
- let remote_version = detail.release_version.clone();
- validate_plugin_segment(&plugin_name, "plugin name").map_err(|reason| {
- RemotePluginCatalogError::UnexpectedResponse(format!(
- "remote plugin `{remote_plugin_id}` returned invalid plugin name: {reason}"
- ))
- })?;
- if !is_checkout_supported_share_marketplace(&detail.marketplace_name)
- || detail.summary.share_context.is_none()
- {
- return Err(RemotePluginCatalogError::PluginShareCheckoutNotAvailable {
- remote_plugin_id: remote_plugin_id.to_string(),
- });
- }
-
- let home = crate::marketplace::home_dir().ok_or_else(|| {
- RemotePluginCatalogError::UnexpectedResponse(
- "could not determine home directory for personal plugin marketplace".to_string(),
- )
- })?;
- let home = AbsolutePathBuf::try_from(home).map_err(|err| {
- RemotePluginCatalogError::UnexpectedResponse(format!(
- "failed to resolve home directory for personal plugin marketplace: {err}"
- ))
- })?;
-
- let local_paths = load_share_local_paths_for_checkout(codex_home)?;
- let (local_plugin_path, already_checked_out) =
- editable_plugin_path_for_checkout(&home, &plugin_name, remote_plugin_id, &local_paths)?;
-
- let mut created_checkout_path = false;
- if !already_checked_out {
- let bundle = crate::remote_bundle::validate_remote_plugin_bundle(
- remote_plugin_id,
- &detail.marketplace_name,
- &plugin_name,
- detail.release_version.as_deref(),
- detail.bundle_download_url.as_deref(),
- /*app_manifest*/ None,
- )
- .map_err(|err| {
- RemotePluginCatalogError::UnexpectedResponse(format!(
- "failed to prepare remote plugin bundle checkout: {err}"
- ))
- })?;
- crate::remote_bundle::download_and_extract_remote_plugin_bundle_to_path(
- config,
- bundle,
- local_plugin_path.clone(),
- )
- .await
- .map_err(|err| {
- RemotePluginCatalogError::UnexpectedResponse(format!(
- "failed to check out remote plugin bundle: {err}"
- ))
- })?;
- created_checkout_path = true;
- }
-
- let marketplace = match update_personal_marketplace(
- &home,
- &plugin_name,
- &local_plugin_path,
- detail.summary.install_policy,
- detail.summary.auth_policy,
- detail
- .summary
- .interface
- .as_ref()
- .and_then(|interface| interface.category.clone()),
- ) {
- Ok(marketplace) => marketplace,
- Err(err) => {
- return Err(clean_up_created_checkout_path(
- created_checkout_path,
- &local_plugin_path,
- err,
- ));
- }
- };
-
- if let Err(err) = local_paths::record_plugin_share_local_path(
- codex_home,
- remote_plugin_id,
- local_plugin_path.clone(),
- ) {
- let err = RemotePluginCatalogError::UnexpectedResponse(format!(
- "failed to record plugin share local path mapping: {err}"
- ));
- return Err(clean_up_created_checkout_path(
- created_checkout_path,
- &local_plugin_path,
- err,
- ));
- }
-
- let plugin_id = PluginId::new(plugin_name.clone(), marketplace.name.clone())
- .map_err(|err| {
- RemotePluginCatalogError::UnexpectedResponse(format!(
- "failed to build checked out plugin id: {err}"
- ))
- })?
- .as_key();
-
- Ok(RemotePluginShareCheckoutResult {
- remote_plugin_id: remote_plugin_id.to_string(),
- plugin_id,
- plugin_name,
- plugin_path: local_plugin_path,
- marketplace_name: marketplace.name,
- marketplace_path: marketplace.path,
- remote_version,
- })
-}
-
-fn is_checkout_supported_share_marketplace(marketplace_name: &str) -> bool {
- matches!(
- marketplace_name,
- REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME
- | REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME
- | REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME
- )
-}
-
-fn load_share_local_paths_for_checkout(
- codex_home: &Path,
-) -> Result, RemotePluginCatalogError> {
- match local_paths::load_plugin_share_local_paths(codex_home) {
- Ok(paths) => Ok(paths),
- Err(err) if err.kind() == io::ErrorKind::InvalidData => Ok(BTreeMap::new()),
- Err(err) => Err(RemotePluginCatalogError::UnexpectedResponse(format!(
- "failed to load plugin share local path mapping: {err}"
- ))),
- }
-}
-
-fn editable_plugin_path_for_checkout(
- home: &AbsolutePathBuf,
- plugin_name: &str,
- remote_plugin_id: &str,
- local_paths: &BTreeMap,
-) -> Result<(AbsolutePathBuf, bool), RemotePluginCatalogError> {
- if let Some(existing_path) = local_paths.get(remote_plugin_id)
- && existing_path.as_path().exists()
- {
- ensure_path_can_be_listed_in_personal_marketplace(home, existing_path)?;
- return Ok((existing_path.clone(), true));
- }
-
- let local_plugin_path = local_paths
- .get(remote_plugin_id)
- .cloned()
- .unwrap_or_else(|| home.join("plugins").join(plugin_name));
- ensure_path_can_be_listed_in_personal_marketplace(home, &local_plugin_path)?;
-
- if local_plugin_path.as_path().exists() {
- return Err(RemotePluginCatalogError::InvalidPluginPath {
- path: local_plugin_path.to_path_buf(),
- reason: format!(
- "cannot check out remote plugin `{remote_plugin_id}` because the local plugin path already exists"
- ),
- });
- }
-
- Ok((local_plugin_path, false))
-}
-
-fn clean_up_created_checkout_path(
- created_checkout_path: bool,
- local_plugin_path: &AbsolutePathBuf,
- original_err: RemotePluginCatalogError,
-) -> RemotePluginCatalogError {
- if !created_checkout_path {
- return original_err;
- }
-
- match remove_created_checkout_path(local_plugin_path) {
- Ok(()) => original_err,
- Err(cleanup_err) => RemotePluginCatalogError::UnexpectedResponse(format!(
- "{original_err}; additionally failed to clean up checked out plugin path `{}`: {cleanup_err}",
- local_plugin_path.display()
- )),
- }
-}
-
-fn remove_created_checkout_path(local_plugin_path: &AbsolutePathBuf) -> io::Result<()> {
- if local_plugin_path.as_path().is_dir() {
- fs::remove_dir_all(local_plugin_path.as_path())
- } else {
- fs::remove_file(local_plugin_path.as_path())
- }
-}
-
-fn ensure_path_can_be_listed_in_personal_marketplace(
- home: &AbsolutePathBuf,
- path: &AbsolutePathBuf,
-) -> Result<(), RemotePluginCatalogError> {
- personal_marketplace_relative_plugin_path(home, path).map(|_| ())
-}
-
-struct PersonalMarketplaceUpdate {
- name: String,
- path: AbsolutePathBuf,
-}
-
-fn update_personal_marketplace(
- home: &AbsolutePathBuf,
- plugin_name: &str,
- local_plugin_path: &AbsolutePathBuf,
- install_policy: PluginInstallPolicy,
- auth_policy: PluginAuthPolicy,
- category: Option,
-) -> Result {
- let marketplace_path = home.join(PERSONAL_MARKETPLACE_RELATIVE_PATH);
- let relative_plugin_path = personal_marketplace_relative_plugin_path(home, local_plugin_path)?;
- let mut marketplace = read_or_create_personal_marketplace(marketplace_path.as_path())?;
- let Some(marketplace_object) = marketplace.as_object_mut() else {
- return Err(invalid_marketplace_file(
- marketplace_path.as_path(),
- "personal marketplace file must contain a JSON object",
- ));
- };
- let marketplace_name = marketplace_object
- .entry("name")
- .or_insert_with(|| json!(PERSONAL_MARKETPLACE_NAME))
- .as_str()
- .ok_or_else(|| {
- invalid_marketplace_file(
- marketplace_path.as_path(),
- "marketplace name must be a string",
- )
- })?
- .to_string();
- validate_plugin_segment(&marketplace_name, "marketplace name").map_err(|reason| {
- invalid_marketplace_file(
- marketplace_path.as_path(),
- &format!("marketplace name is invalid: {reason}"),
- )
- })?;
-
- let plugins = marketplace_object
- .entry("plugins")
- .or_insert_with(|| json!([]))
- .as_array_mut()
- .ok_or_else(|| {
- invalid_marketplace_file(
- marketplace_path.as_path(),
- "marketplace plugins must be an array",
- )
- })?;
-
- let new_entry = personal_marketplace_plugin_entry(
- plugin_name,
- &relative_plugin_path,
- install_policy,
- auth_policy,
- category,
- );
-
- if let Some(existing_entry) = plugins
- .iter_mut()
- .find(|entry| entry.get("name").and_then(JsonValue::as_str) == Some(plugin_name))
- {
- let existing_path = existing_entry
- .get("source")
- .and_then(|source| source.get("path"))
- .and_then(JsonValue::as_str);
- if existing_path != Some(relative_plugin_path.as_str()) {
- return Err(invalid_marketplace_file(
- marketplace_path.as_path(),
- &format!(
- "marketplace already contains plugin `{plugin_name}` with a different source path"
- ),
- ));
- }
- *existing_entry = new_entry;
- } else {
- plugins.push(new_entry);
- }
-
- let contents = serde_json::to_string_pretty(&marketplace)
- .map_err(|err| RemotePluginCatalogError::UnexpectedResponse(err.to_string()))?;
- write_json_atomically(marketplace_path.as_path(), &format!("{contents}\n")).map_err(|err| {
- RemotePluginCatalogError::UnexpectedResponse(format!(
- "failed to update personal plugin marketplace: {err}"
- ))
- })?;
-
- Ok(PersonalMarketplaceUpdate {
- name: marketplace_name,
- path: marketplace_path,
- })
-}
-
-fn read_or_create_personal_marketplace(
- marketplace_path: &Path,
-) -> Result {
- match std::fs::read_to_string(marketplace_path) {
- Ok(contents) => serde_json::from_str(&contents).map_err(|err| {
- invalid_marketplace_file(
- marketplace_path,
- &format!("failed to parse personal marketplace file: {err}"),
- )
- }),
- Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(json!({
- "name": PERSONAL_MARKETPLACE_NAME,
- "interface": {
- "displayName": PERSONAL_MARKETPLACE_DISPLAY_NAME,
- },
- "plugins": [],
- })),
- Err(err) => Err(RemotePluginCatalogError::UnexpectedResponse(format!(
- "failed to read personal plugin marketplace: {err}"
- ))),
- }
-}
-
-fn personal_marketplace_plugin_entry(
- plugin_name: &str,
- relative_plugin_path: &str,
- install_policy: PluginInstallPolicy,
- auth_policy: PluginAuthPolicy,
- category: Option,
-) -> JsonValue {
- let mut entry = json!({
- "name": plugin_name,
- "source": {
- "source": "local",
- "path": relative_plugin_path,
- },
- "policy": {
- "installation": plugin_install_policy_value(install_policy),
- "authentication": plugin_auth_policy_value(auth_policy),
- },
- });
- if let Some(category) = category
- && !category.trim().is_empty()
- && let Some(object) = entry.as_object_mut()
- {
- object.insert("category".to_string(), json!(category));
- }
- entry
-}
-
-fn plugin_install_policy_value(policy: PluginInstallPolicy) -> &'static str {
- match policy {
- PluginInstallPolicy::NotAvailable => "NOT_AVAILABLE",
- PluginInstallPolicy::Available => "AVAILABLE",
- PluginInstallPolicy::InstalledByDefault => "INSTALLED_BY_DEFAULT",
- }
-}
-
-fn plugin_auth_policy_value(policy: PluginAuthPolicy) -> &'static str {
- match policy {
- PluginAuthPolicy::OnInstall => "ON_INSTALL",
- PluginAuthPolicy::OnUse => "ON_USE",
- }
-}
-
-fn personal_marketplace_relative_plugin_path(
- home: &AbsolutePathBuf,
- local_plugin_path: &AbsolutePathBuf,
-) -> Result {
- let relative = local_plugin_path
- .as_path()
- .strip_prefix(home.as_path())
- .map_err(|_| RemotePluginCatalogError::InvalidPluginPath {
- path: local_plugin_path.to_path_buf(),
- reason: "local plugin path must be inside the home directory to be listed in the personal marketplace".to_string(),
- })?;
- let mut segments = Vec::new();
- for component in relative.components() {
- match component {
- Component::Normal(segment) => {
- let segment = segment.to_str().ok_or_else(|| {
- RemotePluginCatalogError::InvalidPluginPath {
- path: local_plugin_path.to_path_buf(),
- reason: "local plugin path contains non-UTF-8 segments".to_string(),
- }
- })?;
- segments.push(segment.to_string());
- }
- Component::CurDir => {}
- Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
- return Err(RemotePluginCatalogError::InvalidPluginPath {
- path: local_plugin_path.to_path_buf(),
- reason:
- "local plugin path cannot be represented as a personal marketplace path"
- .to_string(),
- });
- }
- }
- }
- if segments.is_empty() {
- return Err(RemotePluginCatalogError::InvalidPluginPath {
- path: local_plugin_path.to_path_buf(),
- reason: "local plugin path must not be the home directory".to_string(),
- });
- }
- Ok(format!("./{}", segments.join("/")))
-}
-
-fn invalid_marketplace_file(path: &Path, message: &str) -> RemotePluginCatalogError {
- RemotePluginCatalogError::InvalidPluginPath {
- path: path.to_path_buf(),
- reason: message.to_string(),
- }
-}
-
-fn write_json_atomically(write_path: &Path, contents: &str) -> io::Result<()> {
- let parent = write_path.parent().ok_or_else(|| {
- io::Error::new(
- io::ErrorKind::InvalidInput,
- format!("path {} has no parent directory", write_path.display()),
- )
- })?;
- std::fs::create_dir_all(parent)?;
- let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
- tmp.write_all(contents.as_bytes())?;
- tmp.persist(write_path).map_err(|err| err.error)?;
- Ok(())
-}
diff --git a/codex-rs/core-plugins/src/remote_bundle.rs b/codex-rs/core-plugins/src/remote_bundle.rs
deleted file mode 100644
index 8cf9ad2b..00000000
--- a/codex-rs/core-plugins/src/remote_bundle.rs
+++ /dev/null
@@ -1,995 +0,0 @@
-use crate::error_subtype::http_status_sub_error_type;
-use crate::plugin_bundle_archive::PluginBundleUnpackError;
-use crate::plugin_bundle_archive::unpack_plugin_bundle_tar_gz;
-use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
-use crate::remote::RemotePluginServiceConfig;
-use crate::store::PluginInstallResult;
-use crate::store::PluginStore;
-use crate::store::PluginStoreError;
-use crate::store::error_context_sub_error_type;
-use crate::store::validate_plugin_version_segment;
-use codex_http_client::RouteAwareRequestError;
-use codex_plugin::PluginId;
-use codex_plugin::PluginIdError;
-use codex_utils_absolute_path::AbsolutePathBuf;
-use codex_utils_plugins::AGENT_PLUGIN_MANIFEST_RELATIVE_PATH;
-use codex_utils_plugins::AgentPluginSchemaStatus;
-use codex_utils_plugins::agent_plugin_schema_status;
-use codex_utils_plugins::find_plugin_manifest_path;
-use http::StatusCode;
-use serde_json::Value as JsonValue;
-use std::fs;
-use std::io;
-use std::path::Path;
-use std::path::PathBuf;
-use url::Host;
-use url::Url;
-
-const REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES: u64 = 100 * 1024 * 1024;
-const REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES: u64 = 512 * 1024 * 1024;
-const REMOTE_PLUGIN_INSTALL_STAGING_DIR: &str = "plugins/.remote-plugin-install-staging";
-#[cfg(debug_assertions)]
-const TEST_ALLOW_LOOPBACK_HTTP_REMOTE_PLUGIN_BUNDLES_ENV: &str =
- "CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS";
-
-#[derive(Clone)]
-pub struct ValidatedRemotePluginBundle {
- pub plugin_id: PluginId,
- pub plugin_version: String,
- remote_plugin_id: String,
- app_manifest: Option,
- bundle_download_url: String,
-}
-
-impl std::fmt::Debug for ValidatedRemotePluginBundle {
- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- formatter
- .debug_struct("ValidatedRemotePluginBundle")
- .field("plugin_id", &self.plugin_id)
- .field("plugin_version", &self.plugin_version)
- .field("remote_plugin_id", &self.remote_plugin_id)
- .finish_non_exhaustive()
- }
-}
-
-#[derive(Debug, thiserror::Error)]
-pub enum RemotePluginBundleInstallError {
- #[error("remote plugin bundles are not available in aKode")]
- Unavailable,
-
- #[error("backend did not return a release version for remote plugin `{remote_plugin_id}`")]
- MissingReleaseVersion { remote_plugin_id: String },
-
- #[error(
- "backend returned an invalid release version for remote plugin `{remote_plugin_id}`: {message}"
- )]
- InvalidReleaseVersion {
- remote_plugin_id: String,
- message: String,
- },
-
- #[error("backend did not return a download URL for remote plugin `{remote_plugin_id}`")]
- MissingBundleDownloadUrl { remote_plugin_id: String },
-
- #[error(
- "backend returned an invalid download URL for remote plugin `{remote_plugin_id}`: {source}"
- )]
- InvalidBundleDownloadUrl {
- remote_plugin_id: String,
- #[source]
- source: url::ParseError,
- },
-
- #[error(
- "backend returned an unsupported download URL scheme for remote plugin `{remote_plugin_id}`: {scheme}"
- )]
- UnsupportedBundleDownloadUrlScheme {
- remote_plugin_id: String,
- scheme: String,
- },
-
- #[error(
- "backend returned an invalid local plugin id for remote plugin `{remote_plugin_id}`: {source}"
- )]
- InvalidPluginId {
- remote_plugin_id: String,
- #[source]
- source: PluginIdError,
- },
-
- #[error("failed to send remote plugin bundle download request to {host}: {source}")]
- DownloadRequest {
- host: String,
- #[source]
- source: RouteAwareRequestError,
- },
-
- #[error("remote plugin bundle download from {host} failed with status {status}: {body}")]
- DownloadStatus {
- host: String,
- status: StatusCode,
- body: String,
- },
-
- #[error("failed to read remote plugin bundle download response from {host}: {source}")]
- DownloadBody {
- host: String,
- #[source]
- source: codex_http_client::HttpError,
- },
-
- #[error("remote plugin bundle download from {host} exceeded maximum size of {max_bytes} bytes")]
- DownloadTooLarge { host: String, max_bytes: u64 },
-
- #[error(
- "remote plugin bundle download from {host} resolved to unsupported URL scheme {scheme}"
- )]
- UnsupportedBundleDownloadFinalUrl { host: String, scheme: String },
-
- #[error(
- "remote plugin bundle extracted size would be {bytes} bytes, exceeding the maximum total size of {max_bytes} bytes"
- )]
- ExtractedBundleTooLarge { bytes: u64, max_bytes: u64 },
-
- #[error("{context}: {source}")]
- Io {
- context: &'static str,
- #[source]
- source: io::Error,
- },
-
- #[error("{0}")]
- InvalidBundle(String),
-
- #[error("{0}")]
- Store(#[from] PluginStoreError),
-}
-
-impl RemotePluginBundleInstallError {
- fn io(context: &'static str, source: io::Error) -> Self {
- Self::Io { context, source }
- }
-
- pub fn sub_error_type(&self) -> Option {
- match self {
- Self::Io { context, .. } => Some(error_context_sub_error_type(context)),
- Self::Store(err) => err.sub_error_type(),
- Self::DownloadStatus { status, .. } => {
- Some(http_status_sub_error_type(*status).to_string())
- }
- Self::Unavailable
- | Self::MissingReleaseVersion { .. }
- | Self::InvalidReleaseVersion { .. }
- | Self::MissingBundleDownloadUrl { .. }
- | Self::InvalidBundleDownloadUrl { .. }
- | Self::UnsupportedBundleDownloadUrlScheme { .. }
- | Self::InvalidPluginId { .. }
- | Self::DownloadRequest { .. }
- | Self::DownloadBody { .. }
- | Self::DownloadTooLarge { .. }
- | Self::UnsupportedBundleDownloadFinalUrl { .. }
- | Self::ExtractedBundleTooLarge { .. }
- | Self::InvalidBundle(_) => None,
- }
- }
-}
-
-pub fn validate_remote_plugin_bundle(
- remote_plugin_id: &str,
- remote_marketplace_name: &str,
- plugin_name: &str,
- release_version: Option<&str>,
- bundle_download_url: Option<&str>,
- app_manifest: Option,
-) -> Result {
- let plugin_id = PluginId::new(plugin_name.to_string(), remote_marketplace_name.to_string())
- .map_err(|source| RemotePluginBundleInstallError::InvalidPluginId {
- remote_plugin_id: remote_plugin_id.to_string(),
- source,
- })?;
- let plugin_version = release_version
- .map(str::trim)
- .filter(|version| !version.is_empty())
- .ok_or_else(|| RemotePluginBundleInstallError::MissingReleaseVersion {
- remote_plugin_id: remote_plugin_id.to_string(),
- })?
- .to_string();
- validate_plugin_version_segment(&plugin_version).map_err(|message| {
- RemotePluginBundleInstallError::InvalidReleaseVersion {
- remote_plugin_id: remote_plugin_id.to_string(),
- message,
- }
- })?;
- let bundle_download_url = bundle_download_url
- .map(str::trim)
- .filter(|url| !url.is_empty())
- .ok_or_else(
- || RemotePluginBundleInstallError::MissingBundleDownloadUrl {
- remote_plugin_id: remote_plugin_id.to_string(),
- },
- )?
- .to_string();
- let parsed_bundle_url = Url::parse(&bundle_download_url).map_err(|source| {
- RemotePluginBundleInstallError::InvalidBundleDownloadUrl {
- remote_plugin_id: remote_plugin_id.to_string(),
- source,
- }
- })?;
- if !is_allowed_bundle_download_url(
- &parsed_bundle_url,
- allow_test_loopback_http_bundle_downloads(),
- ) {
- return Err(
- RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme {
- remote_plugin_id: remote_plugin_id.to_string(),
- scheme: parsed_bundle_url.scheme().to_string(),
- },
- );
- }
-
- Ok(ValidatedRemotePluginBundle {
- plugin_id,
- plugin_version,
- remote_plugin_id: remote_plugin_id.to_string(),
- app_manifest,
- bundle_download_url,
- })
-}
-
-fn allow_test_loopback_http_bundle_downloads() -> bool {
- #[cfg(debug_assertions)]
- {
- if let Ok(value) = std::env::var(TEST_ALLOW_LOOPBACK_HTTP_REMOTE_PLUGIN_BUNDLES_ENV) {
- return value == "1";
- }
- }
-
- false
-}
-
-fn is_allowed_bundle_download_url(url: &Url, allow_loopback_http: bool) -> bool {
- match url.scheme() {
- "https" => true,
- "http" => allow_loopback_http && is_loopback_url(url),
- _ => false,
- }
-}
-
-fn is_loopback_url(url: &Url) -> bool {
- match url.host() {
- Some(Host::Ipv4(addr)) => addr.is_loopback(),
- Some(Host::Ipv6(addr)) => addr.is_loopback(),
- Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
- None => false,
- }
-}
-
-pub async fn download_and_install_remote_plugin_bundle(
- config: &RemotePluginServiceConfig,
- codex_home: PathBuf,
- bundle: ValidatedRemotePluginBundle,
-) -> Result {
- let bundle_bytes = download_remote_plugin_bundle(config, &bundle).await?;
- tokio::task::spawn_blocking(move || {
- install_remote_plugin_bundle(codex_home, bundle, bundle_bytes)
- })
- .await
- .map_err(|err| {
- RemotePluginBundleInstallError::InvalidBundle(format!(
- "failed to join remote plugin bundle install task: {err}"
- ))
- })?
-}
-
-pub(crate) async fn download_and_extract_remote_plugin_bundle_to_path(
- config: &RemotePluginServiceConfig,
- bundle: ValidatedRemotePluginBundle,
- destination: AbsolutePathBuf,
-) -> Result {
- let bundle_bytes = download_remote_plugin_bundle(config, &bundle).await?;
- tokio::task::spawn_blocking(move || {
- extract_remote_plugin_bundle_to_path(bundle, bundle_bytes, destination)
- })
- .await
- .map_err(|err| {
- RemotePluginBundleInstallError::InvalidBundle(format!(
- "failed to join remote plugin bundle extraction task: {err}"
- ))
- })?
-}
-
-pub(crate) async fn download_remote_plugin_bundle(
- config: &RemotePluginServiceConfig,
- bundle: &ValidatedRemotePluginBundle,
-) -> Result, RemotePluginBundleInstallError> {
- download_remote_plugin_bundle_with_limit(
- config,
- &bundle.bundle_download_url,
- /*max_bytes*/ REMOTE_PLUGIN_BUNDLE_MAX_DOWNLOAD_BYTES,
- )
- .await
-}
-
-async fn download_remote_plugin_bundle_with_limit(
- config: &RemotePluginServiceConfig,
- bundle_download_url: &str,
- max_bytes: u64,
-) -> Result, RemotePluginBundleInstallError> {
- let _ = (config, bundle_download_url, max_bytes);
- Err(RemotePluginBundleInstallError::Unavailable)
-}
-
-pub(crate) fn install_remote_plugin_bundle(
- codex_home: PathBuf,
- bundle: ValidatedRemotePluginBundle,
- bundle_bytes: Vec,
-) -> Result {
- let staging_root = codex_home.join(REMOTE_PLUGIN_INSTALL_STAGING_DIR);
- fs::create_dir_all(&staging_root).map_err(|source| {
- RemotePluginBundleInstallError::io(
- "failed to create remote plugin bundle staging directory",
- source,
- )
- })?;
- let extract_dir = tempfile::Builder::new()
- .prefix("remote-plugin-bundle-")
- .tempdir_in(&staging_root)
- .map_err(|source| {
- RemotePluginBundleInstallError::io(
- "failed to create remote plugin bundle extraction directory",
- source,
- )
- })?;
-
- extract_plugin_bundle_tar_gz(&bundle_bytes, extract_dir.path())?;
- let plugin_root = find_extracted_plugin_root(extract_dir.path())?;
- prepare_extracted_remote_plugin_root(&plugin_root, &bundle)?;
- let plugin_root = AbsolutePathBuf::try_from(plugin_root).map_err(|err| {
- RemotePluginBundleInstallError::InvalidBundle(format!(
- "failed to resolve extracted remote plugin bundle root: {err}"
- ))
- })?;
-
- let store = PluginStore::try_new(codex_home)?;
- let remote_plugin_id = bundle.remote_plugin_id;
- let result = store
- .install_with_version(plugin_root, bundle.plugin_id, bundle.plugin_version)
- .map_err(RemotePluginBundleInstallError::from)?;
- store.write_remote_plugin_id(&result.plugin_id, &remote_plugin_id)?;
- Ok(result)
-}
-
-fn extract_remote_plugin_bundle_to_path(
- bundle: ValidatedRemotePluginBundle,
- bundle_bytes: Vec,
- destination: AbsolutePathBuf,
-) -> Result {
- if destination.as_path().exists() {
- return Err(RemotePluginBundleInstallError::InvalidBundle(format!(
- "plugin checkout destination already exists: {}",
- destination.display()
- )));
- }
-
- let parent = destination.as_path().parent().ok_or_else(|| {
- RemotePluginBundleInstallError::InvalidBundle(format!(
- "plugin checkout destination has no parent: {}",
- destination.display()
- ))
- })?;
- fs::create_dir_all(parent).map_err(|source| {
- RemotePluginBundleInstallError::io("failed to create plugin checkout directory", source)
- })?;
-
- let extract_dir = tempfile::Builder::new()
- .prefix("remote-plugin-checkout-")
- .tempdir_in(parent)
- .map_err(|source| {
- RemotePluginBundleInstallError::io(
- "failed to create remote plugin bundle extraction directory",
- source,
- )
- })?;
-
- extract_plugin_bundle_tar_gz(&bundle_bytes, extract_dir.path())?;
- let plugin_root = find_extracted_plugin_root(extract_dir.path())?;
- let manifest = crate::manifest::load_plugin_manifest(&plugin_root).ok_or_else(|| {
- RemotePluginBundleInstallError::InvalidBundle(
- "remote plugin bundle did not contain a valid plugin.json".to_string(),
- )
- })?;
- if manifest.name != bundle.plugin_id.plugin_name {
- return Err(RemotePluginBundleInstallError::InvalidBundle(format!(
- "plugin.json name `{}` does not match remote plugin name `{}`",
- manifest.name, bundle.plugin_id.plugin_name
- )));
- }
-
- let staged_path = extract_dir.keep();
- fs::rename(&staged_path, destination.as_path()).map_err(|source| {
- RemotePluginBundleInstallError::io(
- "failed to activate checked out plugin directory",
- source,
- )
- })?;
-
- Ok(destination)
-}
-
-fn prepare_extracted_remote_plugin_root(
- plugin_root: &Path,
- bundle: &ValidatedRemotePluginBundle,
-) -> Result<(), RemotePluginBundleInstallError> {
- if bundle.plugin_id.marketplace_name != REMOTE_GLOBAL_MARKETPLACE_NAME {
- return Ok(());
- }
-
- overwrite_plugin_manifest_version(plugin_root, &bundle.plugin_version)?;
- if let Some(app_manifest) = &bundle.app_manifest {
- overwrite_plugin_app_manifest(plugin_root, app_manifest)?;
- }
- Ok(())
-}
-
-fn overwrite_plugin_manifest_version(
- plugin_root: &Path,
- plugin_version: &str,
-) -> Result<(), RemotePluginBundleInstallError> {
- let manifest_path = find_plugin_manifest_path(plugin_root).ok_or_else(|| {
- RemotePluginBundleInstallError::InvalidBundle(
- "remote plugin bundle did not contain a valid plugin.json".to_string(),
- )
- })?;
- let contents = fs::read_to_string(&manifest_path).map_err(|source| {
- RemotePluginBundleInstallError::io("failed to read remote plugin manifest", source)
- })?;
- if manifest_path == plugin_root.join(AGENT_PLUGIN_MANIFEST_RELATIVE_PATH)
- && agent_plugin_schema_status(&contents) == AgentPluginSchemaStatus::Supported
- {
- return Ok(());
- }
- let mut manifest: JsonValue = serde_json::from_str(&contents).map_err(|err| {
- RemotePluginBundleInstallError::InvalidBundle(format!(
- "failed to parse remote plugin manifest: {err}"
- ))
- })?;
- let Some(manifest_object) = manifest.as_object_mut() else {
- return Err(RemotePluginBundleInstallError::InvalidBundle(
- "remote plugin manifest must be a JSON object".to_string(),
- ));
- };
- manifest_object.insert(
- "version".to_string(),
- JsonValue::String(plugin_version.to_string()),
- );
- write_json_file(
- &manifest_path,
- &manifest,
- "failed to write remote plugin manifest",
- )
-}
-
-fn overwrite_plugin_app_manifest(
- plugin_root: &Path,
- app_manifest: &JsonValue,
-) -> Result<(), RemotePluginBundleInstallError> {
- let app_manifest_path = crate::manifest::load_plugin_manifest(plugin_root)
- .and_then(|manifest| manifest.paths.apps.map(|path| path.to_path_buf()))
- .unwrap_or_else(|| plugin_root.join(".app.json"));
- write_json_file(
- &app_manifest_path,
- app_manifest,
- "failed to write remote plugin app manifest",
- )
-}
-
-fn write_json_file(
- path: &Path,
- value: &JsonValue,
- context: &'static str,
-) -> Result<(), RemotePluginBundleInstallError> {
- let parent = path.parent().ok_or_else(|| {
- RemotePluginBundleInstallError::InvalidBundle(format!(
- "remote plugin output path has no parent: {}",
- path.display()
- ))
- })?;
- fs::create_dir_all(parent)
- .map_err(|source| RemotePluginBundleInstallError::io(context, source))?;
- let mut contents = serde_json::to_vec_pretty(value).map_err(|err| {
- RemotePluginBundleInstallError::InvalidBundle(format!(
- "failed to serialize remote plugin JSON override: {err}"
- ))
- })?;
- contents.push(b'\n');
- fs::write(path, contents).map_err(|source| RemotePluginBundleInstallError::io(context, source))
-}
-
-fn extract_plugin_bundle_tar_gz(
- bytes: &[u8],
- destination: &Path,
-) -> Result<(), RemotePluginBundleInstallError> {
- extract_plugin_bundle_tar_gz_with_limits(
- bytes,
- destination,
- REMOTE_PLUGIN_BUNDLE_MAX_EXTRACTED_BYTES,
- )
-}
-
-fn extract_plugin_bundle_tar_gz_with_limits(
- bytes: &[u8],
- destination: &Path,
- max_total_bytes: u64,
-) -> Result<(), RemotePluginBundleInstallError> {
- unpack_plugin_bundle_tar_gz(bytes, destination, max_total_bytes).map_err(|err| match err {
- PluginBundleUnpackError::ExtractedBundleTooLarge { bytes, max_bytes } => {
- RemotePluginBundleInstallError::ExtractedBundleTooLarge { bytes, max_bytes }
- }
- PluginBundleUnpackError::Io { context, source } => {
- RemotePluginBundleInstallError::io(context, source)
- }
- PluginBundleUnpackError::InvalidBundle(message) => {
- RemotePluginBundleInstallError::InvalidBundle(message)
- }
- })
-}
-
-fn find_extracted_plugin_root(
- extraction_root: &Path,
-) -> Result {
- if is_standard_plugin_root(extraction_root) {
- return Ok(extraction_root.to_path_buf());
- }
-
- Err(RemotePluginBundleInstallError::InvalidBundle(
- "remote plugin bundle did not contain a standard plugin root with plugin.json".to_string(),
- ))
-}
-
-fn is_standard_plugin_root(path: &Path) -> bool {
- find_plugin_manifest_path(path).is_some()
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use flate2::Compression;
- use flate2::write::GzEncoder;
- use pretty_assertions::assert_eq;
- use std::io::Write;
- use tempfile::tempdir;
-
- const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000";
-
- #[test]
- fn remote_version_normalization_preserves_portable_root_manifest() {
- let temp_dir = tempdir().expect("tempdir");
- let manifest_path = temp_dir.path().join("plugin.json");
- let original = r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"portable","version":"release-2026-07"}"#;
- fs::write(&manifest_path, original).expect("write portable manifest");
-
- overwrite_plugin_manifest_version(temp_dir.path(), "1.2.3")
- .expect("prepare portable remote plugin");
-
- assert_eq!(
- fs::read_to_string(manifest_path).expect("read portable manifest"),
- original
- );
- }
-
- #[test]
- fn validate_remote_plugin_bundle_uses_detail_name_for_local_plugin_id() {
- let bundle = validate_remote_plugin_bundle(
- REMOTE_PLUGIN_ID,
- "openai-curated-remote",
- "linear",
- Some("1.2.3"),
- Some("https://example.com/linear.tar.gz?sig=signed-token"),
- /*app_manifest*/ None,
- )
- .expect("valid install plan");
-
- assert_eq!(bundle.plugin_id.plugin_name, "linear");
- assert_eq!(bundle.plugin_id.marketplace_name, "openai-curated-remote");
- assert_eq!(bundle.plugin_version, "1.2.3");
- assert_eq!(
- bundle.bundle_download_url.as_str(),
- "https://example.com/linear.tar.gz?sig=signed-token"
- );
- assert!(!format!("{bundle:?}").contains("signed-token"));
- }
-
- #[test]
- fn validate_remote_plugin_bundle_rejects_missing_release_version() {
- let err = validate_remote_plugin_bundle(
- REMOTE_PLUGIN_ID,
- "openai-curated-remote",
- "linear",
- /*release_version*/ None,
- Some("https://example.com/linear.tar.gz"),
- /*app_manifest*/ None,
- )
- .expect_err("missing release version should be rejected");
-
- assert!(matches!(
- err,
- RemotePluginBundleInstallError::MissingReleaseVersion { .. }
- ));
- }
-
- #[test]
- fn validate_remote_plugin_bundle_rejects_invalid_release_version() {
- let err = validate_remote_plugin_bundle(
- REMOTE_PLUGIN_ID,
- "openai-curated-remote",
- "linear",
- Some("../1.2.3"),
- Some("https://example.com/linear.tar.gz"),
- /*app_manifest*/ None,
- )
- .expect_err("invalid release version should be rejected");
-
- assert!(matches!(
- err,
- RemotePluginBundleInstallError::InvalidReleaseVersion { .. }
- ));
- }
-
- #[test]
- fn validate_remote_plugin_bundle_rejects_missing_download_url() {
- let err = validate_remote_plugin_bundle(
- REMOTE_PLUGIN_ID,
- "openai-curated-remote",
- "linear",
- Some("1.2.3"),
- /*bundle_download_url*/ None,
- /*app_manifest*/ None,
- )
- .expect_err("missing bundle download URL should be rejected");
-
- assert!(matches!(
- err,
- RemotePluginBundleInstallError::MissingBundleDownloadUrl { .. }
- ));
- }
-
- #[test]
- fn validate_remote_plugin_bundle_rejects_unsupported_download_url_scheme() {
- let err = validate_remote_plugin_bundle(
- REMOTE_PLUGIN_ID,
- "openai-curated-remote",
- "linear",
- Some("1.2.3"),
- Some("http://example.com/linear.tar.gz"),
- /*app_manifest*/ None,
- )
- .expect_err("plain HTTP URLs should be rejected before cloud install");
-
- assert!(matches!(
- err,
- RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme { .. }
- ));
- }
-
- #[test]
- fn install_rejects_invalid_tar_gz_bundle() {
- let codex_home = tempdir().expect("tempdir");
- let bundle = valid_remote_plugin_bundle();
-
- let err = install_remote_plugin_bundle(
- codex_home.path().to_path_buf(),
- bundle,
- b"not a tar.gz".to_vec(),
- )
- .expect_err("invalid tar.gz should be rejected");
-
- assert!(format!("{err}").contains("failed to read plugin bundle tar"));
- }
-
- #[test]
- fn install_rejects_bundle_without_standard_plugin_root() {
- let codex_home = tempdir().expect("tempdir");
- let bundle = valid_remote_plugin_bundle();
-
- let err = install_remote_plugin_bundle(
- codex_home.path().to_path_buf(),
- bundle,
- tar_gz_bytes(&[("README.md", b"missing plugin manifest", /*mode*/ 0o644)]),
- )
- .expect_err("bundle without plugin root should be rejected");
-
- assert!(
- format!("{err}").contains("did not contain a standard plugin root with plugin.json")
- );
- }
-
- #[test]
- fn install_persists_remote_plugin_install_metadata() {
- let codex_home = tempdir().expect("tempdir");
- let bundle = valid_remote_plugin_bundle();
-
- let result = install_remote_plugin_bundle(
- codex_home.path().to_path_buf(),
- bundle,
- tar_gz_bytes(&[(
- ".codex-plugin/plugin.json",
- br#"{"name":"linear","version":"1.2.3"}"#,
- /*mode*/ 0o644,
- )]),
- )
- .expect("install bundle");
- let store = PluginStore::new(codex_home.path().to_path_buf());
-
- assert_eq!(
- store.remote_plugin_id(&result.plugin_id).unwrap(),
- Some(REMOTE_PLUGIN_ID.to_string())
- );
- let metadata_path = store
- .plugin_base_root(&result.plugin_id)
- .join(".codex-remote-plugin-install.json");
- assert_eq!(
- serde_json::from_str::(
- &std::fs::read_to_string(metadata_path.as_path())
- .expect("read remote plugin install metadata")
- )
- .expect("parse remote plugin install metadata"),
- serde_json::json!({
- "schema_version": 1,
- "remote_plugin_id": REMOTE_PLUGIN_ID,
- })
- );
- }
-
- #[test]
- fn install_preserves_non_global_bundle_manifest_metadata() {
- let codex_home = tempdir().expect("tempdir");
- let bundle = validate_remote_plugin_bundle(
- REMOTE_PLUGIN_ID,
- "workspace-shared-with-me",
- "linear",
- Some("backend-version"),
- Some("https://example.com/linear.tar.gz"),
- Some(serde_json::json!({
- "apps": {
- "remote": {
- "id": "remote-app"
- }
- }
- })),
- )
- .expect("valid install plan");
-
- let result = install_remote_plugin_bundle(
- codex_home.path().to_path_buf(),
- bundle,
- tar_gz_bytes(&[
- (
- ".codex-plugin/plugin.json",
- br#"{"name":"linear","version":"bundle-version"}"#,
- /*mode*/ 0o644,
- ),
- (
- ".app.json",
- br#"{"apps":{"bundled":{"id":"bundled-app"}}}"#,
- /*mode*/ 0o644,
- ),
- ]),
- )
- .expect("install bundle");
-
- assert_eq!(result.plugin_version, "backend-version");
- let installed_manifest: JsonValue = serde_json::from_str(
- &std::fs::read_to_string(
- result
- .installed_path
- .join(".codex-plugin/plugin.json")
- .as_path(),
- )
- .expect("read installed plugin manifest"),
- )
- .expect("parse installed plugin manifest");
- assert_eq!(
- installed_manifest,
- serde_json::json!({
- "name": "linear",
- "version": "bundle-version",
- })
- );
- let installed_app_manifest: JsonValue = serde_json::from_str(
- &std::fs::read_to_string(result.installed_path.join(".app.json").as_path())
- .expect("read installed app manifest"),
- )
- .expect("parse installed app manifest");
- assert_eq!(
- installed_app_manifest,
- serde_json::json!({
- "apps": {
- "bundled": {
- "id": "bundled-app",
- },
- },
- })
- );
- }
-
- #[test]
- fn find_extracted_plugin_root_uses_local_manifest_discovery() {
- let extraction_root = tempdir().expect("tempdir");
- std::fs::create_dir_all(extraction_root.path().join(".codex-plugin"))
- .expect("create manifest dir");
- std::fs::write(
- extraction_root.path().join(".codex-plugin/plugin.json"),
- r#"{"name":"linear"}"#,
- )
- .expect("write manifest");
-
- assert_eq!(
- find_extracted_plugin_root(extraction_root.path()).expect("plugin root"),
- extraction_root.path()
- );
- }
-
- #[test]
- fn find_extracted_plugin_root_rejects_nested_plugin_root() {
- let extraction_root = tempdir().expect("tempdir");
- let plugin_root = extraction_root.path().join("linear");
- std::fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create manifest dir");
- std::fs::write(
- plugin_root.join(".codex-plugin/plugin.json"),
- r#"{"name":"linear"}"#,
- )
- .expect("write manifest");
-
- let err = find_extracted_plugin_root(extraction_root.path())
- .expect_err("nested plugin root should be rejected");
-
- assert!(
- format!("{err}").contains("did not contain a standard plugin root with plugin.json")
- );
- }
-
- #[test]
- fn extraction_rejects_tar_path_traversal() {
- let destination = tempdir().expect("tempdir");
- let err = extract_plugin_bundle_tar_gz(
- &tar_gz_bytes_with_raw_path("../evil.txt", b"evil", /*mode*/ 0o644),
- destination.path(),
- )
- .expect_err("tar path traversal should be rejected");
-
- assert!(format!("{err}").contains("escapes extraction root"));
- }
-
- #[test]
- fn extraction_rejects_total_size_over_limit() {
- let destination = tempdir().expect("tempdir");
- let err = extract_plugin_bundle_tar_gz_with_limits(
- &tar_gz_bytes(&[
- ("a.txt", b"1234", /*mode*/ 0o644),
- ("b.txt", b"5678", /*mode*/ 0o644),
- ]),
- destination.path(),
- /*max_total_bytes*/ 6,
- )
- .expect_err("oversized extracted bundle should be rejected");
-
- assert!(matches!(
- err,
- RemotePluginBundleInstallError::ExtractedBundleTooLarge { .. }
- ));
- }
-
- #[test]
- fn extraction_supports_gnu_long_name_entries() {
- let destination = tempdir().expect("tempdir");
- let long_path = format!("{}/file.txt", ["segment"; 40].join("/"));
-
- extract_plugin_bundle_tar_gz(
- &tar_gz_bytes(&[(long_path.as_str(), b"long", /*mode*/ 0o644)]),
- destination.path(),
- )
- .expect("extract bundle with GNU long name entry");
-
- assert_eq!(
- std::fs::read(destination.path().join(long_path)).expect("read extracted file"),
- b"long"
- );
- }
-
- #[cfg(unix)]
- #[test]
- fn extraction_preserves_executable_permissions() {
- use std::os::unix::fs::PermissionsExt;
-
- let destination = tempdir().expect("tempdir");
- extract_plugin_bundle_tar_gz(
- &tar_gz_bytes(&[
- (
- ".codex-plugin/plugin.json",
- b"{\"name\":\"linear\"}",
- /*mode*/ 0o644,
- ),
- ("bin/helper", b"#!/bin/sh\n", /*mode*/ 0o755),
- ]),
- destination.path(),
- )
- .expect("extract bundle");
-
- let mode = std::fs::metadata(destination.path().join("bin/helper"))
- .expect("helper metadata")
- .permissions()
- .mode()
- & 0o777;
- assert_eq!(mode, 0o755);
- }
-
- fn valid_remote_plugin_bundle() -> ValidatedRemotePluginBundle {
- validate_remote_plugin_bundle(
- REMOTE_PLUGIN_ID,
- "openai-curated-remote",
- "linear",
- Some("1.2.3"),
- Some("https://example.com/linear.tar.gz"),
- /*app_manifest*/ None,
- )
- .expect("valid install plan")
- }
-
- fn tar_gz_bytes(entries: &[(&str, &[u8], u32)]) -> Vec {
- let encoder = GzEncoder::new(Vec::new(), Compression::default());
- let mut tar = tar::Builder::new(encoder);
- for (path, contents, mode) in entries {
- append_tar_entry(&mut tar, tar::EntryType::Regular, path, contents, *mode);
- }
- finish_tar_gz(tar)
- }
-
- fn tar_gz_bytes_with_raw_path(path: &str, contents: &[u8], mode: u32) -> Vec {
- let mut header = tar::Header::new_gnu();
- header.set_entry_type(tar::EntryType::Regular);
- header.set_size(contents.len() as u64);
- header.set_mode(mode);
- header.as_mut_bytes()[..path.len()].copy_from_slice(path.as_bytes());
- header.set_cksum();
-
- let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
- encoder
- .write_all(header.as_bytes())
- .expect("write tar header");
- encoder.write_all(contents).expect("write tar contents");
- let padding = (512 - (contents.len() % 512)) % 512;
- encoder
- .write_all(&vec![0; padding])
- .expect("write tar padding");
- encoder.write_all(&[0; 1024]).expect("write tar terminator");
- encoder.finish().expect("finish gzip")
- }
-
- fn append_tar_entry(
- tar: &mut tar::Builder,
- entry_type: tar::EntryType,
- path: &str,
- contents: &[u8],
- mode: u32,
- ) {
- let mut header = tar::Header::new_gnu();
- header.set_entry_type(entry_type);
- header.set_size(contents.len() as u64);
- header.set_mode(mode);
- header.set_cksum();
- if let Err(error) = tar.append_data(&mut header, path, contents) {
- panic!("failed to append tar test data: {error}");
- }
- }
-
- fn finish_tar_gz(tar: tar::Builder>>) -> Vec {
- let encoder = match tar.into_inner() {
- Ok(encoder) => encoder,
- Err(error) => panic!("failed to finish tar test data: {error}"),
- };
- match encoder.finish() {
- Ok(bytes) => bytes,
- Err(error) => panic!("failed to finish gzip test data: {error}"),
- }
- }
-}
diff --git a/codex-rs/tui/src/analytics.rs b/codex-rs/tui/src/analytics.rs
deleted file mode 100644
index fe83268a..00000000
--- a/codex-rs/tui/src/analytics.rs
+++ /dev/null
@@ -1,536 +0,0 @@
-//! Authenticated account analytics dashboard.
-//! Stable report tabs share bounded account loads, selection, and inline details.
-
-mod activity_chart;
-mod chart;
-mod summary;
-mod summary_panel;
-pub(crate) use activity_chart::TokenActivityView;
-mod chat_panel;
-mod chats;
-mod chrome;
-mod client;
-mod controls;
-mod dashboard;
-mod data;
-#[cfg(test)]
-#[path = "analytics/test_fixtures.rs"]
-mod fixture;
-mod hints;
-mod models;
-mod mouse;
-mod normalize;
-mod panels;
-mod plan;
-mod plan_panel;
-mod plot;
-mod render;
-mod report_data;
-mod sections;
-mod styles;
-mod task_panel;
-mod tasks;
-#[cfg(test)]
-#[path = "analytics/test_support.rs"]
-mod test_support;
-mod tokens;
-mod tool_panel;
-
-#[cfg(test)]
-#[path = "analytics_tests.rs"]
-mod tests;
-
-use crate::key_hint;
-use crate::keymap::ListAction;
-use crate::keymap::ListKeymap;
-use crate::tui;
-use crate::tui::FrameRequester;
-use crate::tui::TuiEvent;
-use codex_app_server_client::AppServerRequestHandle;
-use crossterm::event::KeyCode;
-use crossterm::event::KeyEvent;
-use crossterm::event::KeyEventKind;
-use crossterm::event::MouseButton;
-use crossterm::event::MouseEventKind;
-use data::Load;
-use sections::Section;
-use sections::SectionState;
-use sections::SectionStates;
-
-pub(crate) struct AnalyticsView {
- clock_format: crate::clock_format::ClockFormat,
- model_names: std::collections::HashMap,
- sections: SectionStates,
- chats: Load,
- tasks: Load,
- chat_metric: usize,
- profile: Load,
- plan: plan::State,
- show_zero_credit_groups: bool,
- account: Load,
- reports_started: bool,
- connection: Option<(
- std::sync::Arc,
- AppServerRequestHandle,
- FrameRequester,
- )>,
- live: Option>,
- pub(crate) keymap: ListKeymap,
- section: Section,
- show_help: bool,
- zoomed: bool,
- dashboard_scroll: usize,
- body_area: ratatui::layout::Rect,
- report_area: ratatui::layout::Rect,
- tab_hits: Vec<(Section, ratatui::layout::Rect)>,
- control_hits: Vec<(controls::Control, ratatui::layout::Rect)>,
- mouse_context: Option<(Section, bool, bool)>,
- max_scroll: usize,
- selection_visible: bool,
- help_scroll: usize,
- follow_selection: bool,
- viewport_height: usize,
- ranges: [usize; 3],
- end_date: chrono::NaiveDate,
- token_model: Option,
- pub(crate) is_done: bool,
-}
-
-impl AnalyticsView {
- pub(crate) fn new(keymap: ListKeymap) -> Self {
- let mut view = Self {
- clock_format: crate::clock_format::ClockFormat::system(),
- model_names: std::collections::HashMap::new(),
- sections: SectionStates(std::array::from_fn(|_| SectionState::default())),
- chats: Load::Unavailable,
- tasks: Load::Unavailable,
- chat_metric: 0,
- profile: Load::Unavailable,
- plan: plan::State::default(),
- show_zero_credit_groups: false,
- account: Load::Unavailable,
- reports_started: false,
- connection: None,
- live: None,
- keymap,
- section: Section::Summary,
- show_help: false,
- zoomed: true,
- dashboard_scroll: 0,
- body_area: ratatui::layout::Rect::default(),
- report_area: ratatui::layout::Rect::default(),
- tab_hits: Vec::new(),
- control_hits: Vec::new(),
- mouse_context: None,
- max_scroll: 0,
- selection_visible: false,
- help_scroll: 0,
- follow_selection: true,
- viewport_height: 1,
- ranges: [0; 3],
- end_date: chrono::Utc::now().date_naive(),
- token_model: None,
- is_done: false,
- };
- view.sections[Section::Usage].group = 1;
- view.sections[Section::Plan].group = 1;
- view.sections[Section::Chats].cursor = 0;
- view.sections[Section::Activity].group = 2;
- view.refresh();
- view
- }
-
- pub(crate) fn open(
- &mut self,
- handle: AppServerRequestHandle,
- frame: FrameRequester,
- models: Vec,
- config: std::sync::Arc,
- ) {
- self.model_names = models
- .into_iter()
- .map(|model| (model.model, model.display_name))
- .collect();
- self.plan.enabled = config
- .features
- .enabled(codex_features::Feature::AnalyticsPlanHistory);
- self.connection = Some((config, handle, frame));
- self.is_done = false;
- self.show_help = false;
- self.refresh();
- }
-
- pub(crate) fn refresh(&mut self) {
- self.invalidate_mouse_targets();
- self.end_date = chrono::Utc::now().date_naive();
- self.live = self.connection.as_ref().map(|(config, _, _)| {
- std::sync::Arc::new(client::Live::new(
- std::sync::Arc::clone(config),
- self.end_date,
- ))
- });
- for section in &mut self.sections.0 {
- section.history = Load::Unavailable;
- }
- self.sections[Section::Chats].detail = None;
- self.chats = Load::Unavailable;
- self.tasks = Load::Unavailable;
- self.profile = Load::Unavailable;
- self.plan.report = Load::Unavailable;
- self.reports_started = false;
- self.token_model = None;
- self.account = if let (Some((_, _, frame)), Some(live)) = (&self.connection, &self.live) {
- let live = std::sync::Arc::clone(live);
- Load::start(
- async move {
- live.session().await.map(|session| {
- Some(
- session
- .backend
- .account()
- .plan_type
- .unwrap_or(codex_protocol::account::PlanType::Unknown),
- )
- })
- },
- frame.clone(),
- )
- } else {
- Load::Unavailable
- };
- self.start_reports();
- }
-
- /// Abort work when closing or invalidating a retained view; reopening starts fresh requests.
- pub(crate) fn cancel_loads(&mut self) {
- self.invalidate_mouse_targets();
- for section in &mut self.sections.0 {
- section.history = Load::Unavailable;
- }
- self.chats = Load::Unavailable;
- self.tasks = Load::Unavailable;
- self.profile = Load::Unavailable;
- self.plan.report = Load::Unavailable;
- self.account = Load::Unavailable;
- self.live = None;
- self.connection = None;
- }
-
- fn load_report(&mut self, section: Section) {
- let Some(report) = section.report() else {
- return;
- };
- let group = self.sections[section].group;
- let range = self.ranges[self.range_group(section) as usize];
- self.sections[section].history =
- if let (Some((_, _, frame)), Some(live)) = (&self.connection, &self.live) {
- let live = std::sync::Arc::clone(live);
- let days = if range == 0 { 7 } else { 30 };
- let model = self.token_model.clone();
- Load::start(
- async move {
- if let Some(model) = model
- .as_deref()
- .filter(|_| report == models::AccountAnalyticsReport::Usage)
- {
- live.filtered_history(report, days, data::GROUPINGS[group], Some(model))
- .await
- } else {
- live.history(report, days, data::GROUPINGS[group]).await
- }
- },
- frame.clone(),
- )
- } else {
- Load::Unavailable
- };
- }
-
- fn group_options(&self) -> &[usize] {
- if self.visible_sections().is_empty() {
- return &[];
- }
- match self.section {
- Section::Summary => &[0, 1, 2],
- Section::Plan => &[1, 2, 0, 3],
- Section::Usage if self.business() => &[6, 2],
- Section::Usage if self.consumer_attribution() => &[1, 2, 0, 3],
- Section::Usage => &[0, 2],
- Section::Credits => self.live.as_ref().map_or(&[0], |live| live.credit_groups()),
- Section::Activity => &[2, 0],
- Section::Plugins | Section::Skills | Section::Chats => &[],
- }
- }
-
- fn consumer_attribution(&self) -> bool {
- !self.business()
- && self
- .live
- .as_ref()
- .is_none_or(|live| live.attributed_usage())
- }
-
- fn model_name<'a>(&'a self, model: &'a str) -> &'a str {
- self.model_names
- .get(model)
- .filter(|name| !name.is_empty())
- .map(String::as_str)
- .unwrap_or(model)
- }
-
- fn row_count(&self) -> usize {
- if self.section == Section::Chats && !self.business() {
- self.tasks
- .ready()
- .map_or(/*default*/ 0, |chats| chats.rows.len())
- } else if self.section == Section::Chats {
- self.chats
- .ready()
- .map_or(/*default*/ 0, |chats| chats.rows.len())
- } else if self.ranges[self.range_group(self.section) as usize] == 0 {
- 7
- } else {
- 30
- }
- }
-
- fn handle_key(&mut self, key: KeyEvent) {
- if key.kind == KeyEventKind::Release {
- return;
- }
- if key_hint::plain(KeyCode::Char('q')).is_press(key)
- || key_hint::ctrl(KeyCode::Char('c')).is_press(key)
- {
- self.is_done = true;
- return;
- }
- let action = if key_hint::plain(KeyCode::Char(' ')).is_press(key) {
- Some(ListAction::Accept)
- } else {
- self.keymap.action_for(key).or_else(|| {
- if !key.modifiers.is_empty() {
- return None;
- }
- // Keep explicit bindings first and honor remapped or unbound arrows.
- let code = match key.code {
- KeyCode::Char('h') => KeyCode::Left,
- KeyCode::Char('l') => KeyCode::Right,
- _ => return None,
- };
- self.keymap.action_for(KeyEvent { code, ..key })
- })
- };
-
- self.follow_selection = matches!(
- action,
- Some(
- ListAction::Accept
- | ListAction::Cancel
- | ListAction::MoveLeft
- | ListAction::MoveRight
- | ListAction::MoveUp
- | ListAction::MoveDown
- | ListAction::JumpTop
- | ListAction::JumpBottom
- )
- );
- if self.help_shortcut_available()
- && (key_hint::plain(KeyCode::Char('?')).is_press(key)
- || key_hint::shift(KeyCode::Char('?')).is_press(key))
- {
- self.show_help = !self.show_help;
- self.help_scroll = 0;
- self.follow_selection = false;
- return;
- }
- if self.show_help && action == Some(ListAction::Cancel) {
- self.show_help = false;
- self.follow_selection = false;
- return;
- }
- if self.show_help {
- self.summary_action(action);
- return;
- }
- if key_hint::plain(KeyCode::Char('z')).is_press(key)
- && self.control_available(controls::Control::Dashboard)
- {
- self.activate_control(controls::Control::Dashboard);
- return;
- }
- if !self.zoomed && action == Some(ListAction::Accept) {
- self.toggle_dashboard();
- return;
- }
- if key_hint::plain(KeyCode::Char('R')).is_press(key) {
- self.refresh();
- return;
- }
- if self.control_available(controls::Control::ZeroCreditGroups)
- && key_hint::plain(KeyCode::Char('a')).is_press(key)
- {
- self.activate_control(controls::Control::ZeroCreditGroups);
- return;
- }
- if self.control_available(controls::Control::Model)
- && key_hint::plain(KeyCode::Char('m')).is_press(key)
- {
- self.activate_control(controls::Control::Model);
- return;
- }
- if key_hint::plain(KeyCode::Char('r')).is_press(key)
- && self.control_available(controls::Control::Range)
- {
- self.activate_control(controls::Control::Range);
- return;
- }
- if key_hint::plain(KeyCode::Char('g')).is_press(key)
- && self.control_available(controls::Control::Group)
- {
- self.activate_control(controls::Control::Group);
- return;
- }
- let visible = self.visible_sections();
- if visible.is_empty() {
- self.is_done |= action == Some(ListAction::Cancel);
- return;
- }
- let current = visible
- .iter()
- .position(|section| *section == self.section)
- .unwrap_or_default();
- let target = match key.code {
- KeyCode::Char(n @ '1'..='7') if key.modifiers.is_empty() => {
- visible.get(n as usize - '1' as usize).copied()
- }
- KeyCode::Tab => Some(visible[(current + 1) % visible.len()]),
- KeyCode::BackTab => Some(visible[(current + visible.len() - 1) % visible.len()]),
- _ => None,
- };
- if let Some(section) = target {
- self.select_section(section);
- return;
- }
- if !self.zoomed && action == Some(ListAction::Cancel) {
- self.is_done = true;
- return;
- }
- if self.section == Section::Summary {
- self.summary_action(action);
- return;
- }
- if self.section == Section::Plan {
- self.plan_action(action);
- return;
- }
- if self.control_available(controls::Control::TaskMetric)
- && key_hint::plain(KeyCode::Char('s')).is_press(key)
- {
- self.activate_control(controls::Control::TaskMetric);
- return;
- }
- if matches!(
- self.section,
- Section::Plugins | Section::Activity | Section::Skills
- ) && action == Some(ListAction::Accept)
- && !self.day_has_details(self.section, self.sections[self.section].cursor)
- {
- return;
- }
- if self.section == Section::Chats
- && matches!(action, Some(ListAction::Accept | ListAction::MoveRight))
- && !self.chat_has_details()
- {
- return;
- }
- let chart = self.section != Section::Chats;
- let count = self.row_count().max(/*other*/ 1);
- let mut scroll_offset = self.scroll_offset();
- let SectionState {
- cursor,
- detail,
- follow_selection_on_focus,
- ..
- } = &mut self.sections[self.section];
- let previous_cursor = *cursor;
- match action {
- Some(ListAction::MoveUp) => *cursor = cursor.saturating_sub(/*rhs*/ 1),
- Some(ListAction::MoveDown) => *cursor = (*cursor + 1).min(count - 1),
- Some(ListAction::MoveLeft) if chart => *cursor = cursor.saturating_sub(/*rhs*/ 1),
- Some(ListAction::MoveRight) if chart => *cursor = (*cursor + 1).min(count - 1),
- Some(ListAction::JumpTop) => *cursor = 0,
- Some(ListAction::JumpBottom) => *cursor = count - 1,
- Some(ListAction::Accept | ListAction::MoveRight) => {
- *detail = if *detail == Some(*cursor) {
- None
- } else {
- Some(*cursor)
- };
- }
- Some(ListAction::MoveLeft) => *detail = None,
- Some(ListAction::Cancel) => {
- self.is_done |= detail.take().is_none();
- }
- Some(ListAction::PageDown) => {
- scroll_offset += self.viewport_height;
- self.follow_selection = false;
- }
- Some(ListAction::PageUp) => {
- scroll_offset = scroll_offset.saturating_sub(self.viewport_height);
- self.follow_selection = false;
- }
- None => {}
- }
- if chart && detail.is_some() {
- *detail = Some(*cursor);
- } else if !chart && *cursor != previous_cursor {
- *detail = None;
- }
- *follow_selection_on_focus |= !self.zoomed && *cursor != previous_cursor;
- *self.scroll_offset_mut() = scroll_offset;
- }
-
- pub(crate) fn handle_event(
- &mut self,
- tui: &mut tui::Tui,
- event: TuiEvent,
- ) -> std::io::Result<()> {
- match event {
- TuiEvent::Key(key) => {
- self.handle_key(key);
- if self.is_done {
- for section in &mut self.sections.0 {
- if matches!(section.history, Load::Loading(_)) {
- section.history = Load::Unavailable;
- }
- }
- self.chats = Load::Unavailable;
- self.tasks = Load::Unavailable;
- self.profile = Load::Unavailable;
- self.plan.report = Load::Unavailable;
- self.account = Load::Unavailable;
- self.connection = None;
- }
- tui.frame_requester().schedule_frame();
- }
- TuiEvent::Mouse(mouse)
- if matches!(
- mouse.kind,
- MouseEventKind::Down(MouseButton::Left)
- | MouseEventKind::ScrollUp
- | MouseEventKind::ScrollDown
- ) =>
- {
- self.handle_mouse(mouse);
- tui.frame_requester().schedule_frame();
- }
- TuiEvent::Draw | TuiEvent::Resume | TuiEvent::Resize(_) | TuiEvent::FocusGained => {
- // Rendering follows a selection on resize only when it was visible before
- // reflow. Preserve an intentional reading position away from that selection.
- tui.draw(u16::MAX, |frame| self.render(frame.area(), frame.buffer))?;
- }
- _ => {}
- }
- Ok(())
- }
-}
diff --git a/codex-rs/tui/src/analytics/account_layout_tests.rs b/codex-rs/tui/src/analytics/account_layout_tests.rs
deleted file mode 100644
index aec8e865..00000000
--- a/codex-rs/tui/src/analytics/account_layout_tests.rs
+++ /dev/null
@@ -1,477 +0,0 @@
-//! Account layouts, authenticated report loading, independent ranges, and model filters.
-use super::*;
-use codex_config::types::KeybindingSpec;
-use codex_config::types::KeybindingsSpec;
-use codex_config::types::TuiKeymap;
-use pretty_assertions::assert_eq;
-
-use crate::analytics::sections::Section;
-#[test]
-fn account_layouts_show_reports_and_wrap_navigation() {
- for (kind, expected) in [
- (
- models::AccountKind::Consumer,
- vec![
- Section::Summary,
- Section::Usage,
- Section::Activity,
- Section::Plugins,
- Section::Skills,
- Section::Chats,
- ],
- ),
- (
- models::AccountKind::Enterprise,
- vec![
- Section::Summary,
- Section::Credits,
- Section::Usage,
- Section::Plugins,
- Section::Skills,
- Section::Chats,
- ],
- ),
- ] {
- let mut view = fixture::view(kind);
- for (index, section) in expected.iter().enumerate() {
- press(
- &mut view,
- KeyCode::Char(char::from_digit(index as u32 + 1, /*radix*/ 10).unwrap()),
- );
- assert_eq!(view.section, *section);
- }
- press(&mut view, KeyCode::Tab);
- assert_eq!(view.section, expected[0]);
- press(&mut view, KeyCode::BackTab);
- assert_eq!(view.section, *expected.last().unwrap());
- }
-}
-
-#[tokio::test]
-async fn changing_ranges_and_grouping_preserves_other_reports_and_focus() {
- let server = test_support::server().await;
- let (_home, _app_server, mut view) = client::tests::connected_view(&server, "plus").await;
- test_support::settle(&mut view).await;
- view.section = Section::Usage;
- press(&mut view, KeyCode::Left);
- press(&mut view, KeyCode::Enter);
- press(&mut view, KeyCode::Char('r'));
- test_support::settle(&mut view).await;
- press(&mut view, KeyCode::Char('g'));
- test_support::settle(&mut view).await;
- assert_eq!(
- (
- view.ranges,
- view.sections.0.each_ref().map(|state| state.cursor),
- view.sections[Section::Usage].detail,
- view.sections[Section::Usage].group
- ),
- ([1, 0, 0], [28, 6, 6, 0, 6, 6, 6, 6], Some(28), 2)
- );
- let context = (
- view.ranges,
- view.sections.0.each_ref().map(|state| state.cursor),
- view.sections.0.each_ref().map(|state| state.detail),
- view.sections.0.each_ref().map(|state| state.group),
- );
- screen(&mut view, /*width*/ 58, /*height*/ 25);
- assert_eq!(
- (
- view.ranges,
- view.sections.0.each_ref().map(|state| state.cursor),
- view.sections.0.each_ref().map(|state| state.detail),
- view.sections.0.each_ref().map(|state| state.group)
- ),
- context
- );
- press(&mut view, KeyCode::Char('3'));
- press(&mut view, KeyCode::Char('r'));
- test_support::settle(&mut view).await;
- assert_eq!(view.ranges, [1, 1, 0]);
- assert_eq!(
- view.sections
- .0
- .each_ref()
- .map(|state| state.history.ready().map(|history| history.data.len())),
- [Some(30), Some(7), None, None, Some(30), Some(7), None, None]
- );
- let server = test_support::server().await;
- let (_business_home, _business_server, mut view) =
- client::tests::connected_view(&server, "business").await;
- test_support::settle(&mut view).await;
- view.ranges = [1, 1, 0];
- view.load_report(Section::Usage);
- press(&mut view, KeyCode::Char('2'));
- press(&mut view, KeyCode::Char('r'));
- test_support::settle(&mut view).await;
- assert_eq!(view.ranges, [0, 1, 0]);
- assert_eq!(
- view.sections
- .0
- .each_ref()
- .map(|state| state.history.ready().map(|history| history.data.len())),
- [Some(30), Some(7), Some(7), None, None, Some(7), None, None]
- );
-}
-
-#[tokio::test]
-async fn business_tokens_filter_models() {
- let server = test_support::server().await;
- let (_home, _app_server, mut view) = client::tests::connected_view(&server, "business").await;
- test_support::settle(&mut view).await;
- view.end_date = fixture::END_DATE;
- fixture::seed_reports(&mut view);
- press(&mut view, KeyCode::Char('3'));
- let all = screen(&mut view, /*width*/ 100, /*height*/ 30);
- assert!(all.contains("All models") && all.contains("Cached input"));
- press(&mut view, KeyCode::Char('m'));
- test_support::settle(&mut view).await;
- assert_eq!(
- view.sections[Section::Usage]
- .history
- .ready()
- .unwrap()
- .data
- .iter()
- .map(|day| day.total)
- .sum::(),
- 420.0
- );
- fixture::seed_reports(&mut view);
- assert_eq!(view.token_model.as_deref(), Some("GPT-5.5"));
- screen(&mut view, /*width*/ 100, /*height*/ 30);
- let (_, target) = view
- .control_hits
- .iter()
- .find(|(control, _)| *control == crate::analytics::controls::Control::Model)
- .unwrap();
- view.handle_mouse(crossterm::event::MouseEvent {
- kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
- column: target.x,
- row: target.y,
- modifiers: KeyModifiers::NONE,
- });
- test_support::settle(&mut view).await;
- fixture::seed_reports(&mut view);
- assert_eq!(view.token_model, None);
-}
-
-#[tokio::test]
-async fn account_pending_and_error_do_not_start_reports() {
- let mut view = AnalyticsView::new(RuntimeKeymap::defaults().list);
- let (send, receive) = tokio::sync::oneshot::channel();
- view.account = Load::start(
- async move { receive.await.unwrap() },
- FrameRequester::test_dummy(),
- );
- screen(&mut view, /*width*/ 80, /*height*/ 24);
- assert!(
- view.sections
- .0
- .iter()
- .all(|state| matches!(state.history, Load::Unavailable))
- );
- send.send(Err("Sign in again to view Analytics.".to_string()))
- .unwrap();
- tokio::task::yield_now().await;
- let error = screen(&mut view, /*width*/ 80, /*height*/ 24);
- assert!(error.contains("Sign in again"));
- assert!(
- view.sections
- .0
- .iter()
- .all(|state| matches!(state.history, Load::Unavailable))
- );
-}
-
-#[tokio::test]
-async fn account_reports_request_only_eligible_endpoints_and_refresh() {
- for (plan, usage, activity) in [
- (
- "plus",
- "usage/daily-token-usage-breakdown",
- "analytics/daily-workspace-usage-counts",
- ),
- (
- "business",
- "usage/daily-workspace-user-token-usage-breakdown",
- "usage/daily-workspace-user-credit-usage",
- ),
- ] {
- let server = test_support::server().await;
- wiremock::Mock::given(wiremock::matchers::method("GET"))
- .and(wiremock::matchers::path("/backend-api/wham/profiles/me"))
- .respond_with(
- wiremock::ResponseTemplate::new(/*s*/ 200)
- .set_body_json(serde_json::json!({"stats":{}})),
- )
- .mount(&server)
- .await;
- let (_home, _app_server, mut view) = client::tests::connected_view(&server, plan).await;
- test_support::settle(&mut view).await;
- let mut expected = [
- "accounts/check",
- usage,
- activity,
- "analytics/daily-plugin-usage-metrics",
- "analytics/daily-skill-usage-metrics",
- "profiles/me",
- ]
- .map(|endpoint| format!("/backend-api/wham/{endpoint}"));
- expected.sort();
- let mut paths = server
- .received_requests()
- .await
- .unwrap()
- .into_iter()
- .filter(|request| request.url.path().starts_with("/backend-api/wham/"))
- .map(|request| request.url.path().to_string())
- .collect::>();
- paths.sort();
- assert_eq!(paths, expected);
- let ready = view
- .sections
- .0
- .each_ref()
- .map(|state| state.history.ready().is_some());
- assert_eq!(
- ready,
- if plan == "plus" {
- [true, true, false, false, true, true, false, false]
- } else {
- [true, true, true, false, false, true, false, false]
- }
- );
- press(&mut view, KeyCode::Char('R'));
- test_support::settle(&mut view).await;
- assert_eq!(
- view.sections
- .0
- .each_ref()
- .map(|state| state.history.ready().is_some()),
- ready
- );
- assert_eq!(
- server
- .received_requests()
- .await
- .unwrap()
- .iter()
- .filter(|request| request.url.path().starts_with("/backend-api/wham/"))
- .count(),
- 12
- );
- view.cancel_loads();
- }
-}
-
-#[tokio::test]
-async fn grouping_cycle_uses_current_server_capabilities() {
- let server = test_support::server().await;
- let (_home, _app_server, mut view) = client::tests::connected_view(&server, "plus").await;
- view.section = Section::Usage;
- view.account = Load::Ready(codex_protocol::account::PlanType::Plus);
- view.sections[Section::Usage].group = 3;
- view.start_reports();
- test_support::settle(&mut view).await;
- assert_eq!(
- (view.group_options(), view.sections[Section::Usage].group),
- (&[0, 2][..], 0)
- );
- press(&mut view, KeyCode::Char('g'));
- assert_eq!(view.sections[Section::Usage].group, 2);
- press(&mut view, KeyCode::Char('g'));
- assert_eq!(view.sections[Section::Usage].group, 0);
-}
-
-#[test]
-fn ungrouped_sections_preserve_configured_g_jump_top() {
- let mut config = TuiKeymap::default();
- config.list.jump_top = Some(KeybindingsSpec::One(KeybindingSpec("g".into())));
- let keymap = RuntimeKeymap::from_config(&config).expect("valid list keymap");
- let mut view = fixture::view(models::AccountKind::Enterprise);
- view.keymap = keymap.list;
- for section in [
- Section::Chats,
- Section::Plugins,
- Section::Skills,
- Section::Credits,
- ] {
- view.section = section;
- press(&mut view, KeyCode::End);
- assert!(view.sections[section].cursor > 0, "{section:?}");
- press(&mut view, KeyCode::Char('g'));
- assert_eq!(view.sections[section].cursor, 0, "{section:?}");
- }
-}
-
-#[test]
-fn business_chats_display_only_supplied_dollars() {
- let mut view = fixture::view(models::AccountKind::Enterprise);
- let chats = match &mut view.chats {
- Load::Ready(chats) => chats,
- _ => panic!("fixture chats"),
- };
- for chat in &mut chats.rows {
- if let Some(usage) = &mut chat.usage {
- usage.estimated_usage_usd_micros = None;
- }
- }
- press(&mut view, KeyCode::Char('6'));
- assert!(!screen(&mut view, /*width*/ 100, /*height*/ 30).contains("Est. $ spent"));
- if let Load::Ready(chats) = &mut view.chats {
- chats.rows[0]
- .usage
- .as_mut()
- .unwrap()
- .estimated_usage_usd_micros = Some(123_450_000);
- }
- let dollars = screen(&mut view, /*width*/ 100, /*height*/ 30);
- assert!(dollars.contains("$123.45") && dollars.contains("Est. $ spent"));
- assert!(screen(&mut view, /*width*/ 42, /*height*/ 30).contains("$123.45"));
-}
-
-#[tokio::test]
-async fn unsupported_workspace_plans_hide_top_chats_and_skip_loading() {
- for plan in [
- "team",
- "self_serve_business_prolite",
- "self_serve_business_usage_based",
- "enterprise",
- "ent26",
- "edu",
- "edu_plus",
- "edu_pro",
- ] {
- let server = test_support::server().await;
- let (_home, _app_server, mut view) = client::tests::connected_view(&server, plan).await;
- test_support::settle(&mut view).await;
- assert_eq!(
- view.visible_sections(),
- &[
- Section::Summary,
- Section::Credits,
- Section::Usage,
- Section::Plugins,
- Section::Skills
- ],
- "{plan}"
- );
- assert!(matches!(view.chats, Load::Unavailable), "{plan}");
- let selected = view.section;
- press(&mut view, KeyCode::Char('6'));
- assert_eq!(view.section, selected);
- }
- for plan in [
- "business",
- "enterprise_cbp_usage_based",
- "enterprise_cbp_automation",
- ] {
- let server = test_support::server().await;
- let (_home, _app_server, mut view) = client::tests::connected_view(&server, plan).await;
- test_support::settle(&mut view).await;
- assert!(view.visible_sections().contains(&Section::Chats), "{plan}");
- press(&mut view, KeyCode::Char('6'));
- assert_eq!(view.section, Section::Chats);
- }
-}
-
-#[tokio::test]
-async fn unknown_plan_keeps_summary_available_without_billing_reports() {
- let server = test_support::server().await;
- wiremock::Mock::given(wiremock::matchers::method("GET"))
- .and(wiremock::matchers::path("/backend-api/wham/profiles/me"))
- .respond_with(
- wiremock::ResponseTemplate::new(/*s*/ 200)
- .set_body_json(serde_json::json!({"stats":{"lifetime_tokens":12345}})),
- )
- .expect(/*r*/ 1)
- .mount(&server)
- .await;
- let (_home, _app_server, mut view) =
- client::tests::connected_view(&server, "future-plan").await;
- test_support::settle(&mut view).await;
- assert_eq!(view.visible_sections(), &[Section::Summary]);
- assert_eq!(
- view.profile.ready().unwrap().stats.tokens.lifetime_tokens,
- Some(12345)
- );
- assert!(
- view.sections
- .0
- .iter()
- .all(|section| matches!(section.history, Load::Unavailable))
- );
- let paths = server
- .received_requests()
- .await
- .unwrap()
- .into_iter()
- .filter(|request| request.url.path().starts_with("/backend-api/wham/"))
- .map(|request| request.url.path().to_owned())
- .collect::>();
- assert_eq!(
- paths,
- [
- "/backend-api/wham/accounts/check",
- "/backend-api/wham/profiles/me"
- ]
- );
-}
-
-#[test]
-fn navigation_keeps_its_row_when_sections_change() {
- for width in [64, 120] {
- let mut view = fixture::view(models::AccountKind::Consumer);
- let mut positions = Vec::new();
- for section in [
- Section::Summary,
- Section::Usage,
- Section::Chats,
- Section::Summary,
- ] {
- view.section = section;
- let rendered = screen(&mut view, width, /*height*/ 40);
- positions.push(
- rendered
- .lines()
- .position(|line| line.contains("Overview") && line.contains("Usage"))
- .unwrap(),
- );
- }
- assert_eq!(positions, vec![positions[0]; 4]);
- }
-}
-
-#[test]
-fn taller_report_reveals_more_legend_rows_and_keeps_timestamp_in_controls() {
- let mut view = fixture::view(models::AccountKind::Consumer);
- view.section = Section::Usage;
- let mut history = fixture::history(/*report*/ 0, /*range*/ 0, /*group*/ 1);
- history.updated_at = Some(1_788_364_800);
- for day in &mut history.data {
- day.values = (0..10)
- .map(|index| models::AccountAnalyticsValue {
- key: format!("feature-{index}"),
- label: format!("Feature {}", index + 1),
- value: day.total / 10.0,
- })
- .collect();
- }
- view.sections[Section::Usage].history = data::Load::Ready(history);
- let short = screen(&mut view, /*width*/ 120, /*height*/ 30);
- let tall = screen(&mut view, /*width*/ 120, /*height*/ 60);
- assert!(
- tall.lines().filter(|line| line.contains('●')).count()
- > short.lines().filter(|line| line.contains('●')).count()
- );
- assert!(
- tall.lines()
- .take(usize::from(view.body_area.y))
- .any(|line| line.contains("Updated"))
- );
- for width in [24, 40, 64] {
- let narrow = screen(&mut view, width, /*height*/ 60);
- assert!(narrow.lines().nth(/*n*/ 3).unwrap().contains("7d/30d"));
- }
-}
diff --git a/codex-rs/tui/src/analytics/account_plan_tests.rs b/codex-rs/tui/src/analytics/account_plan_tests.rs
deleted file mode 100644
index 8795e2e9..00000000
--- a/codex-rs/tui/src/analytics/account_plan_tests.rs
+++ /dev/null
@@ -1,167 +0,0 @@
-//! Server plan discovery survives stale token claims and remains bound to the local identity.
-
-use super::tests::live;
-use super::tests::sign_in;
-use super::*;
-use pretty_assertions::assert_eq;
-use serde_json::json;
-use std::sync::atomic::AtomicUsize;
-use std::sync::atomic::Ordering;
-use wiremock::Mock;
-use wiremock::MockServer;
-use wiremock::ResponseTemplate;
-use wiremock::matchers::header;
-use wiremock::matchers::method;
-use wiremock::matchers::path;
-
-#[tokio::test]
-async fn refresh_uses_server_plan_and_routes_with_unchanged_local_credentials() {
- let server = MockServer::start().await;
- let (_home, client) = live(&server, "plus").await;
- let reads = Arc::new(AtomicUsize::new(/*v*/ 0));
- let plan_reads = Arc::clone(&reads);
- Mock::given(method("GET"))
- .and(path("/backend-api/wham/accounts/check"))
- .and(header("chatgpt-account-id", "account-a"))
- .respond_with(move |_: &wiremock::Request| {
- let plan = if plan_reads.fetch_add(/*val*/ 1, Ordering::SeqCst) == 0 {
- "team"
- } else {
- "enterprise"
- };
- ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
- "accounts": [
- {"id": "other-account", "plan_type": "free"},
- {"id": "account-a", "plan_type": plan}
- ],
- "account_ordering": ["other-account", "account-a"]
- }))
- })
- .with_priority(/*p*/ 1)
- .expect(/*r*/ 2)
- .mount(&server)
- .await;
- for endpoint in [
- "/backend-api/wham/usage/daily-workspace-user-token-usage-breakdown",
- "/backend-api/wham/usage/daily-workspace-user-credit-usage",
- ] {
- Mock::given(method("GET"))
- .and(path(endpoint))
- .and(header("chatgpt-account-id", "account-a"))
- .respond_with(
- ResponseTemplate::new(/*s*/ 200)
- .set_body_json(json!({"breakdown": "product", "series": [], "data": []})),
- )
- .expect(/*r*/ 1)
- .mount(&server)
- .await;
- }
- let first = client
- .history(Report::Credits, /*days*/ 7, Grouping::Surface)
- .await
- .unwrap();
- assert_eq!(client.session().await.unwrap().kind, AccountKind::Business);
- assert_eq!(
- client
- .history(Report::Credits, /*days*/ 7, Grouping::Surface)
- .await
- .unwrap(),
- first
- );
- assert_eq!(reads.load(Ordering::SeqCst), 1);
- let refreshed = Live::new(Arc::clone(&client.config), client.end_date);
- refreshed
- .history(Report::Credits, /*days*/ 7, Grouping::Surface)
- .await
- .unwrap();
- assert_eq!(
- refreshed.session().await.unwrap().kind,
- AccountKind::Enterprise
- );
- server.verify().await;
-}
-
-#[tokio::test]
-async fn account_plan_lookup_recovers_from_unauthorized() {
- let server = MockServer::start().await;
- let (_home, client) = live(&server, "plus").await;
- let reads = AtomicUsize::new(/*v*/ 0);
- Mock::given(method("GET"))
- .and(path("/backend-api/wham/accounts/check"))
- .and(header("chatgpt-account-id", "account-a"))
- .respond_with(move |_: &wiremock::Request| {
- if reads.fetch_add(/*val*/ 1, Ordering::SeqCst) == 0 {
- ResponseTemplate::new(/*s*/ 401)
- } else {
- ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
- "accounts": {"account-a": {"account": {
- "account_id": "account-a", "plan_type": "enterprise"
- }}},
- "account_ordering": ["account-a"]
- }))
- }
- })
- .with_priority(/*p*/ 1)
- .expect(/*r*/ 2)
- .mount(&server)
- .await;
- assert_eq!(
- client.session().await.unwrap().kind,
- AccountKind::Enterprise
- );
- server.verify().await;
-}
-
-#[tokio::test]
-async fn failed_plan_discovery_can_retry_without_using_token_plan() {
- for response in [
- ResponseTemplate::new(/*s*/ 503),
- ResponseTemplate::new(/*s*/ 200).set_body_string("invalid account response"),
- ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"accounts": [{"id": "account-a"}]})),
- ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
- "accounts": [{"id": "other-account", "plan_type": "enterprise"}]
- })),
- ] {
- let server = MockServer::start().await;
- let (_home, client) = live(&server, "plus").await;
- Mock::given(method("GET"))
- .and(path("/backend-api/wham/accounts/check"))
- .respond_with(response)
- .with_priority(/*p*/ 1)
- .expect(/*r*/ 1)
- .up_to_n_times(/*n*/ 1)
- .mount(&server)
- .await;
- assert_eq!(
- client.session().await.err().unwrap(),
- "Couldn't load account plan. Press R to retry Analytics."
- );
- assert_eq!(client.session().await.unwrap().kind, AccountKind::Consumer);
- server.verify().await;
- }
-}
-
-#[tokio::test]
-async fn account_plan_lookup_rejects_account_and_user_switches() {
- for (account, user) in [("account-b", "user-a"), ("account-a", "user-b")] {
- let server = MockServer::start().await;
- let (home, client) = live(&server, "plus").await;
- Mock::given(method("GET"))
- .and(path("/backend-api/wham/accounts/check"))
- .respond_with(move |_: &wiremock::Request| {
- sign_in(home.path(), account, user, "plus");
- ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
- "accounts": [{"id": "account-a", "plan_type": "enterprise"}]
- }))
- })
- .with_priority(/*p*/ 1)
- .expect(/*r*/ 1)
- .mount(&server)
- .await;
- assert_eq!(
- client.session().await.err().unwrap(),
- "Account changed. Press R to refresh Analytics."
- );
- server.verify().await;
- }
-}
diff --git a/codex-rs/tui/src/analytics/activity_chart.rs b/codex-rs/tui/src/analytics/activity_chart.rs
deleted file mode 100644
index 8bfb704b..00000000
--- a/codex-rs/tui/src/analytics/activity_chart.rs
+++ /dev/null
@@ -1,319 +0,0 @@
-//! Calendar and weekly token charts for the account Summary. Bucketing is independent of view state.
-
-mod palette;
-
-use std::collections::BTreeMap;
-
-use chrono::Datelike;
-use chrono::Duration;
-use chrono::NaiveDate;
-use ratatui::style::Style;
-use ratatui::style::Stylize;
-use ratatui::text::Line;
-use ratatui::text::Span;
-
-use crate::render::highlight::foreground_style_for_scopes;
-use palette::TokenActivityPalette;
-
-const WEEK_COUNT: usize = 52;
-const DAY_COUNT: usize = 7;
-const CELL_COUNT: usize = WEEK_COUNT * DAY_COUNT;
-const CHART_LEFT_WIDTH: usize = 4;
-
-/// Selects the aggregation represented by the token activity chart.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(crate) enum TokenActivityView {
- Daily,
- Weekly,
- Cumulative,
-}
-
-impl TokenActivityView {
- /// Parses the optional `/usage` argument into a supported chart view.
- ///
- /// An empty argument selects Daily when a mode is requested. The bare `/usage`
- /// command opens its menu. Returning `None` lets the slash-command dispatcher
- /// report unsupported arguments instead of silently choosing a view.
- pub(crate) fn parse(value: &str) -> Option {
- match value.trim().to_ascii_lowercase().as_str() {
- "" | "day" | "daily" => Some(Self::Daily),
- "week" | "weekly" => Some(Self::Weekly),
- "cumulative" => Some(Self::Cumulative),
- _ => None,
- }
- }
-
- pub(crate) fn label(self) -> &'static str {
- match self {
- Self::Daily => "Daily",
- Self::Weekly => "Weekly",
- Self::Cumulative => "Cumulative",
- }
- }
-}
-
-pub(super) fn chart_lines(
- view: TokenActivityView,
- buckets: &[codex_backend_client::TokenUsageProfileDailyBucket],
- today: NaiveDate,
- width: u16,
-) -> Vec> {
- let mut lines = Vec::new();
- let values = daily_values(buckets, today);
- let shown_columns = shown_columns(width);
- if shown_columns == 0 {
- lines.push(" Widen terminal to show activity graph".dim().into());
- return lines;
- }
-
- let palette = TokenActivityPalette::current();
- let levels = levels_for_view(&values, view);
- let first_column = WEEK_COUNT - shown_columns;
- lines.push(month_labels(today, first_column, shown_columns));
- for row in 0..DAY_COUNT {
- let mut spans = vec![weekday_label(view, row)];
- for column in first_column..WEEK_COUNT {
- if column > first_column {
- spans.push(" ".into());
- }
- let index = column * DAY_COUNT + row;
- if view == TokenActivityView::Daily
- && cell_date(today, index).is_some_and(|date| date > today)
- {
- spans.push(" ".into());
- } else {
- let style = if view == TokenActivityView::Daily {
- palette.for_level(levels[index])
- } else {
- palette.for_bar_level(levels[index])
- };
- spans.push(Span::styled(palette.glyph(view, levels[index]), style));
- }
- }
- lines.push(spans.into());
- }
- // Separate the calendar from the legend/footer below.
- lines.push(Line::default());
- match view {
- TokenActivityView::Daily => lines.push(legend_line(&palette)),
- TokenActivityView::Weekly | TokenActivityView::Cumulative => {
- lines.push(bar_caption(view, &values))
- }
- }
- lines
-}
-
-fn shown_columns(width: u16) -> usize {
- (usize::from(width)
- .saturating_sub(CHART_LEFT_WIDTH)
- .saturating_add(/*rhs*/ 1)
- / 2)
- .min(WEEK_COUNT)
-}
-
-fn numeric_style() -> Style {
- foreground_style_for_scopes(&["constant.numeric", "constant"])
- .unwrap_or_else(|| Style::default().green())
-}
-
-fn label_style() -> Style {
- foreground_style_for_scopes(&["comment"]).unwrap_or_else(|| Style::default().dim())
-}
-
-fn weekday_label(view: TokenActivityView, row: usize) -> Span<'static> {
- if view != TokenActivityView::Daily {
- // Bar views fill from the bottom (row 6) upward, so the gutter doubles
- // as a coarse Y-axis: peak at the top, baseline at the bottom.
- return Span::styled(
- match row {
- 0 => "max ",
- 6 => " 0 ",
- _ => " ",
- },
- label_style(),
- );
- }
- Span::styled(
- match row {
- 0 => " Su ",
- 1 => " Mo ",
- 2 => " Tu ",
- 3 => " We ",
- 4 => " Th ",
- 5 => " Fr ",
- 6 => " Sa ",
- _ => " ",
- },
- label_style(),
- )
-}
-
-fn legend_line(palette: &TokenActivityPalette) -> Line<'static> {
- let mut spans = vec![Span::styled(" Less ", label_style())];
- for level in 0..=4 {
- if level > 0 {
- spans.push(" ".into());
- }
- spans.push(Span::styled(
- palette.glyph(TokenActivityView::Daily, level),
- palette.for_level(level),
- ));
- }
- spans.push(Span::styled(" More", label_style()));
- spans.into()
-}
-
-/// Caption for the bar-chart views, where the 5-step daily legend would be
-/// misleading. States what each bar represents and the peak it is scaled to.
-fn bar_caption(view: TokenActivityView, values: &[i64]) -> Line<'static> {
- let weeks = weekly_totals(values);
- let (lead, peak) = match view {
- TokenActivityView::Weekly => (
- "Each column = 1 week · tallest ",
- weeks.iter().copied().max().unwrap_or(/*default*/ 0),
- ),
- TokenActivityView::Cumulative => (
- "Running total · top ",
- weeks
- .iter()
- .fold(/*init*/ 0_i64, |sum, value| sum.saturating_add(*value)),
- ),
- TokenActivityView::Daily => ("", 0),
- };
- if peak <= 0 {
- return Span::styled(" No token activity in the last 12 months", label_style()).into();
- }
- vec![
- Span::styled(format!(" {lead}"), label_style()),
- Span::styled(super::data::compact_amount(peak as f64), numeric_style()),
- ]
- .into()
-}
-
-fn month_labels(today: NaiveDate, first_column: usize, shown_columns: usize) -> Line<'static> {
- let mut cells = vec![' '; shown_columns * 2 - 1];
- let start = chart_start(today);
- let mut last_end = 0;
- for column in first_column..WEEK_COUNT {
- let date = start + Duration::days((column * DAY_COUNT) as i64);
- if date.day() > 7 {
- continue;
- }
- let label = date.format("%b").to_string();
- let offset = (column - first_column) * 2;
- if offset < last_end || offset + label.len() > cells.len() {
- continue;
- }
- for (index, ch) in label.chars().enumerate() {
- cells[offset + index] = ch;
- }
- last_end = offset + label.len() + 1;
- }
- vec![
- " ".into(),
- Span::styled(cells.into_iter().collect::(), label_style()),
- ]
- .into()
-}
-
-/// Normalizes backend daily buckets into the fixed 52-week display window.
-///
-/// The returned vector is ordered by chart cell, starting with the oldest Sunday.
-/// Invalid, out-of-window, and future dates are ignored. Duplicate dates are
-/// accumulated and negative token values do not reduce activity.
-fn daily_values(
- buckets: &[codex_backend_client::TokenUsageProfileDailyBucket],
- today: NaiveDate,
-) -> Vec {
- let start = chart_start(today);
- let end = start + Duration::days(CELL_COUNT as i64);
- let mut by_date = BTreeMap::new();
- for bucket in buckets {
- let Ok(date) = NaiveDate::parse_from_str(&bucket.start_date, "%Y-%m-%d") else {
- continue;
- };
- if date < start || date >= end || date > today {
- continue;
- }
- let value: &mut i64 = by_date.entry(date).or_insert(/*default*/ 0);
- *value = value.saturating_add(bucket.tokens.max(/*other*/ 0));
- }
- (0..CELL_COUNT)
- .map(|offset| {
- by_date
- .get(&(start + Duration::days(offset as i64)))
- .copied()
- .unwrap_or(/*default*/ 0)
- })
- .collect()
-}
-
-fn levels_for_view(values: &[i64], view: TokenActivityView) -> Vec {
- match view {
- TokenActivityView::Daily => graded_levels(values),
- TokenActivityView::Weekly => bar_levels(&weekly_totals(values)),
- TokenActivityView::Cumulative => {
- let cumulative = weekly_totals(values)
- .into_iter()
- .scan(/*initial_state*/ 0, |sum, value| {
- *sum = i64::saturating_add(*sum, value);
- Some(*sum)
- })
- .collect::>();
- bar_levels(&cumulative)
- }
- }
-}
-
-fn graded_levels(values: &[i64]) -> Vec {
- let max = values.iter().copied().max().unwrap_or(/*default*/ 0);
- values
- .iter()
- .map(|value| match (*value, max) {
- (0, _) | (_, 0) => 0,
- (value, max) if i128::from(value) * 4 > i128::from(max) * 3 => 4,
- (value, max) if i128::from(value) * 2 > i128::from(max) => 3,
- (value, max) if i128::from(value) * 4 > i128::from(max) => 2,
- _ => 1,
- })
- .collect()
-}
-
-fn weekly_totals(values: &[i64]) -> Vec {
- values
- .chunks(DAY_COUNT)
- .map(|week| {
- week.iter()
- .fold(/*init*/ 0_i64, |sum, value| sum.saturating_add(*value))
- })
- .collect()
-}
-
-fn bar_levels(totals: &[i64]) -> Vec {
- let max = totals.iter().copied().max().unwrap_or(/*default*/ 0);
- totals
- .iter()
- .flat_map(|value| {
- let height = if *value <= 0 || max <= 0 {
- 0
- } else {
- ((i128::from(*value) * DAY_COUNT as i128 + i128::from(max) - 1) / i128::from(max))
- as usize
- };
- (0..DAY_COUNT).map(move |row| if DAY_COUNT - row <= height { 4 } else { 0 })
- })
- .collect()
-}
-
-fn chart_start(today: NaiveDate) -> NaiveDate {
- let week_start = today - Duration::days(i64::from(today.weekday().num_days_from_sunday()));
- week_start - Duration::weeks((WEEK_COUNT - 1) as i64)
-}
-
-fn cell_date(today: NaiveDate, index: usize) -> Option {
- chart_start(today).checked_add_signed(Duration::days(index as i64))
-}
-
-#[cfg(test)]
-#[path = "activity_chart_tests.rs"]
-mod tests;
diff --git a/codex-rs/tui/src/analytics/activity_chart/palette.rs b/codex-rs/tui/src/analytics/activity_chart/palette.rs
deleted file mode 100644
index 5ac415d5..00000000
--- a/codex-rs/tui/src/analytics/activity_chart/palette.rs
+++ /dev/null
@@ -1,151 +0,0 @@
-//! Builds terminal-aware styles and glyph choices for token activity charts.
-//!
-//! The palette adapts theme colors to the active terminal color level while
-//! keeping chart-specific glyph policy local to the token activity renderer.
-
-use ratatui::style::Color;
-use ratatui::style::Style;
-
-use super::TokenActivityView;
-use crate::color::blend;
-use crate::render::highlight::foreground_style_for_scopes;
-use crate::style::accent_style;
-use crate::terminal_palette::StdoutColorLevel;
-use crate::terminal_palette::best_color_for_level;
-use crate::terminal_palette::default_bg;
-use crate::terminal_palette::default_fg;
-use crate::terminal_palette::effective_stdout_color_level;
-
-// In low-color terminals we distinguish empty vs active cells by glyph (a
-// width-matched filled/hollow pair). In truecolor terminals the grid uses a
-// single glyph and lets color carry the intensity (GitHub-style), which keeps
-// the grid perfectly aligned and free of texture noise.
-const EMPTY_CELL_GLYPH: &str = "□";
-const ACTIVE_CELL_GLYPH: &str = "■";
-const BAR_CELL_GLYPH: &str = "█";
-
-/// Stores the terminal-specific styles and glyph strategy for token activity cells.
-pub(super) struct TokenActivityPalette {
- styles: [Style; 5],
- bar_style: Style,
- /// True when the terminal supports a truecolor gradient, so the grid can
- /// encode intensity purely by color and render every cell with a single
- /// glyph. False on low-color terminals, where we fall back to a
- /// filled/hollow glyph pair so empty and active cells stay distinguishable.
- uses_color: bool,
-}
-
-impl TokenActivityPalette {
- pub(super) fn current() -> Self {
- Self::from_parts(
- default_fg(),
- default_bg(),
- effective_stdout_color_level(),
- theme_activity_style(),
- )
- }
-
- fn from_parts(
- default_fg: Option<(u8, u8, u8)>,
- default_bg: Option<(u8, u8, u8)>,
- color_level: StdoutColorLevel,
- active_style: Style,
- ) -> Self {
- let fallback_palette = || Self::fallback(active_style);
- let (Some(fg), Some(bg), Some(anchor)) =
- (default_fg, default_bg, activity_anchor_rgb(active_style))
- else {
- return fallback_palette();
- };
- if matches!(
- color_level,
- StdoutColorLevel::Ansi16 | StdoutColorLevel::Unknown
- ) {
- return fallback_palette();
- }
-
- let empty_alpha = if crate::color::is_light(bg) {
- 0.18
- } else {
- 0.14
- };
- let alphas = [empty_alpha, 0.22, 0.42, 0.68, 1.00];
- let styles = std::array::from_fn(|index| {
- let color = if index == 0 {
- blend(fg, bg, alphas[index])
- } else {
- blend(anchor, bg, alphas[index])
- };
- Style::default().fg(best_color_for_level(color, color_level))
- });
- let bar_style = Style::default().fg(best_color_for_level(
- blend(anchor, bg, /*alpha*/ 0.78),
- color_level,
- ));
- Self {
- styles,
- bar_style,
- uses_color: true,
- }
- }
-
- fn fallback(active_style: Style) -> Self {
- let empty_style = Style::default().dim();
- Self {
- styles: [
- empty_style,
- active_style,
- active_style,
- active_style,
- active_style,
- ],
- bar_style: active_style,
- uses_color: false,
- }
- }
-
- pub(super) fn for_level(&self, level: usize) -> Style {
- self.styles[level.min(/*other*/ 4)]
- }
-
- pub(super) fn for_bar_level(&self, level: usize) -> Style {
- if level == 0 {
- self.for_level(/*level*/ 0)
- } else {
- self.bar_style
- }
- }
-
- /// The glyph for a cell at `level`. Daily truecolor renders every visible
- /// cell with the same square glyph and lets color carry the intensity; in
- /// low-color we use the hollow glyph for empty cells so they remain visible
- /// without a color gradient. Bar views use full blocks for filled height and
- /// spaces for empty height so the silhouette reads as a column chart.
- pub(super) fn glyph(&self, view: TokenActivityView, level: usize) -> &'static str {
- if view != TokenActivityView::Daily {
- return if level == 0 { " " } else { BAR_CELL_GLYPH };
- }
- if self.uses_color || level > 0 {
- ACTIVE_CELL_GLYPH
- } else {
- EMPTY_CELL_GLYPH
- }
- }
-}
-
-fn theme_activity_style() -> Style {
- foreground_style_for_scopes(&["entity.name.type", "support.type", "variable"])
- .unwrap_or_else(accent_style)
- .bold()
-}
-
-fn activity_anchor_rgb(style: Style) -> Option<(u8, u8, u8)> {
- match style.fg? {
- Color::Rgb(r, g, b) => Some((r, g, b)),
- _ => None,
- }
-}
-
-#[cfg(test)]
-#[path = "palette_tests.rs"]
-mod tests;
diff --git a/codex-rs/tui/src/analytics/activity_chart/palette_tests.rs b/codex-rs/tui/src/analytics/activity_chart/palette_tests.rs
deleted file mode 100644
index e46bd0ad..00000000
--- a/codex-rs/tui/src/analytics/activity_chart/palette_tests.rs
+++ /dev/null
@@ -1,143 +0,0 @@
-use super::*;
-use crate::terminal_palette::rgb_color;
-use pretty_assertions::assert_eq;
-use ratatui::style::Modifier;
-
-#[test]
-fn current_palette_uses_effective_terminal_color_level() {
- let theme =
- crate::render::highlight::resolve_theme_by_name("ada", /*codex_home*/ None).unwrap();
- crate::render::highlight::set_syntax_theme(theme);
- crate::terminal_palette::with_test_default_colors(
- crate::terminal_probe::DefaultColors {
- fg: (240, 240, 240),
- bg: (0, 0, 0),
- },
- || {
- let palette = TokenActivityPalette::current();
- assert!(palette.uses_color);
- let legend = (0..5)
- .map(|level| {
- format!(
- "{} {:?}",
- palette.glyph(TokenActivityView::Daily, level),
- palette.for_level(level).fg,
- )
- })
- .collect::>()
- .join("\n");
- insta::assert_snapshot!(legend);
- },
- );
-}
-
-#[test]
-fn truecolor_palette_blends_theme_accent_against_dark_background() {
- let default_fg = Some((240, 240, 240));
- let default_bg = Some((0, 0, 0));
- let active_style = Style::default().fg(rgb_color((100, 200, 50))).bold();
- let palette = TokenActivityPalette::from_parts(
- default_fg,
- default_bg,
- StdoutColorLevel::TrueColor,
- active_style,
- );
-
- assert_eq!(
- palette.for_level(/*level*/ 0).fg,
- Some(rgb_color((33, 33, 33)))
- );
- assert_eq!(
- palette.for_level(/*level*/ 1).fg,
- Some(rgb_color((22, 44, 11)))
- );
- assert_eq!(
- palette.for_level(/*level*/ 4).fg,
- Some(rgb_color((100, 200, 50)))
- );
- assert_eq!(
- palette.for_bar_level(/*level*/ 4).fg,
- Some(rgb_color((78, 156, 39)))
- );
- assert!(palette.uses_color);
-}
-
-#[test]
-fn truecolor_palette_blends_empty_cell_for_light_background() {
- let default_fg = Some((0, 0, 0));
- let default_bg = Some((255, 255, 255));
- let active_style = Style::default().fg(rgb_color((0, 95, 135))).bold();
- let palette = TokenActivityPalette::from_parts(
- default_fg,
- default_bg,
- StdoutColorLevel::TrueColor,
- active_style,
- );
-
- assert_eq!(
- palette.for_level(/*level*/ 0).fg,
- Some(rgb_color((209, 209, 209)))
- );
- assert_eq!(
- palette.for_level(/*level*/ 4).fg,
- Some(rgb_color((0, 95, 135)))
- );
- assert!(palette.uses_color);
-}
-
-#[test]
-fn ansi16_palette_uses_theme_accent_without_green_fallback() {
- let default_fg = Some((240, 240, 240));
- let default_bg = Some((0, 0, 0));
- let active_style = Style::default().fg(Color::Magenta).bold();
- let palette = TokenActivityPalette::from_parts(
- default_fg,
- default_bg,
- StdoutColorLevel::Ansi16,
- active_style,
- );
-
- assert_eq!(palette.for_level(/*level*/ 0), Style::default().dim());
- assert_eq!(palette.for_level(/*level*/ 1), active_style);
- assert_eq!(palette.for_bar_level(/*level*/ 4), active_style);
- assert!(!palette.uses_color);
-}
-
-#[test]
-fn non_rgb_theme_accent_remains_active_fallback() {
- let default_fg = Some((240, 240, 240));
- let default_bg = Some((0, 0, 0));
- let active_style = Style::default().fg(Color::Cyan).bold();
- let palette = TokenActivityPalette::from_parts(
- default_fg,
- default_bg,
- StdoutColorLevel::TrueColor,
- active_style,
- );
-
- assert_eq!(palette.for_level(/*level*/ 1), active_style);
- assert!(
- palette
- .for_level(/*level*/ 1)
- .add_modifier
- .contains(Modifier::BOLD)
- );
- assert!(!palette.uses_color);
-}
-
-#[test]
-fn missing_terminal_colors_use_theme_accent_fallback() {
- let default_fg = None;
- let default_bg = Some((0, 0, 0));
- let active_style = Style::default().fg(Color::Blue).bold();
- let palette = TokenActivityPalette::from_parts(
- default_fg,
- default_bg,
- StdoutColorLevel::TrueColor,
- active_style,
- );
-
- assert_eq!(palette.for_level(/*level*/ 0), Style::default().dim());
- assert_eq!(palette.for_level(/*level*/ 4), active_style);
- assert!(!palette.uses_color);
-}
diff --git a/codex-rs/tui/src/analytics/activity_chart/snapshots/codex_tui__analytics__activity_chart__palette__tests__current_palette_uses_effective_terminal_color_level.snap b/codex-rs/tui/src/analytics/activity_chart/snapshots/codex_tui__analytics__activity_chart__palette__tests__current_palette_uses_effective_terminal_color_level.snap
deleted file mode 100644
index bd5ed35e..00000000
--- a/codex-rs/tui/src/analytics/activity_chart/snapshots/codex_tui__analytics__activity_chart__palette__tests__current_palette_uses_effective_terminal_color_level.snap
+++ /dev/null
@@ -1,10 +0,0 @@
----
-source: tui/src/analytics/activity_chart/palette_tests.rs
-assertion_line: 29
-expression: legend
----
-■ Some(Rgb(33, 33, 33))
-■ Some(Rgb(20, 47, 56))
-■ Some(Rgb(39, 90, 107))
-■ Some(Rgb(64, 146, 173))
-■ Some(Rgb(95, 215, 255))
diff --git a/codex-rs/tui/src/analytics/activity_chart_tests.rs b/codex-rs/tui/src/analytics/activity_chart_tests.rs
deleted file mode 100644
index 35faaa7c..00000000
--- a/codex-rs/tui/src/analytics/activity_chart_tests.rs
+++ /dev/null
@@ -1,239 +0,0 @@
-//! Calendar, aggregation, and chart rendering regressions.
-use super::*;
-use codex_backend_client::TokenUsageProfileDailyBucket as AccountTokenUsageDailyBucket;
-use insta::assert_snapshot;
-use pretty_assertions::assert_eq;
-
-fn graph_width(width: u16) -> u16 {
- if width == u16::MAX {
- return width;
- }
- (CHART_LEFT_WIDTH + shown_columns(width) * 2 - 1) as u16
-}
-
-#[test]
-fn duplicate_dates_sum_and_negative_values_clamp() {
- let today =
- NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date");
- let buckets = vec![
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-29".to_string(),
- tokens: 10,
- },
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-29".to_string(),
- tokens: 5,
- },
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-28".to_string(),
- tokens: -4,
- },
- ];
-
- let values = daily_values(&buckets, today);
-
- assert_eq!(values.iter().sum::(), 15);
-}
-
-#[test]
-fn bar_levels_fill_from_bottom() {
- let levels = bar_levels(&[0, 10]);
-
- assert_eq!(&levels[..DAY_COUNT], &[0; DAY_COUNT]);
- assert_eq!(&levels[DAY_COUNT..], &[4; DAY_COUNT]);
-}
-
-#[test]
-fn token_activity_view_aliases_parse() {
- assert_eq!(TokenActivityView::parse(""), Some(TokenActivityView::Daily));
- assert_eq!(
- TokenActivityView::parse("day"),
- Some(TokenActivityView::Daily)
- );
- assert_eq!(
- TokenActivityView::parse("week"),
- Some(TokenActivityView::Weekly)
- );
- assert_eq!(
- TokenActivityView::parse("cumulative"),
- Some(TokenActivityView::Cumulative)
- );
- assert_eq!(TokenActivityView::parse("year"), None);
-}
-
-#[test]
-fn daily_graph_snapshot_uses_distinct_empty_and_active_cells() {
- let today =
- NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date");
- let buckets = vec![
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-25".to_string(),
- tokens: 1,
- },
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-29".to_string(),
- tokens: 4,
- },
- ];
-
- let rendered = chart_lines(TokenActivityView::Daily, &buckets, today, /*width*/ 22)
- .into_iter()
- .map(|line| line.to_string().trim_end().to_string())
- .collect::>()
- .join("\n");
-
- assert_snapshot!(rendered, @r"
- Apr May
- Su □ □ □ □ □ □ □ □ □
- Mo □ □ □ □ □ □ □ □ ■
- Tu □ □ □ □ □ □ □ □ □
- We □ □ □ □ □ □ □ □ □
- Th □ □ □ □ □ □ □ □ □
- Fr □ □ □ □ □ □ □ □ ■
- Sa □ □ □ □ □ □ □ □
-
- Less □ ■ ■ ■ ■ More
- ");
-}
-
-#[test]
-fn daily_graph_snapshot_stays_left_aligned_in_wide_terminal() {
- assert_eq!(graph_width(/*width*/ 160), 107);
- assert_eq!(graph_width(/*width*/ u16::MAX), u16::MAX);
-
- let today =
- NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date");
- let lines = chart_lines(TokenActivityView::Daily, &[], today, /*width*/ 160);
- let rendered = [&lines[0], &lines[1], lines.last().expect("legend line")]
- .into_iter()
- .map(|line| line.to_string().trim_end().to_string())
- .collect::>()
- .join("\n");
-
- assert_snapshot!(rendered, @"
- Jun Jul Aug Sep Oct Nov Dec Jan Feb Mar Apr May
- Su □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □
- Less □ ■ ■ ■ ■ More
- ");
-}
-
-#[test]
-fn weekly_graph_snapshot_renders_bar_chart_and_caption() {
- let today =
- NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date");
- let buckets = vec![
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-11".to_string(),
- tokens: 3,
- },
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-18".to_string(),
- tokens: 6,
- },
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-25".to_string(),
- tokens: 9,
- },
- ];
-
- let rendered = chart_lines(
- TokenActivityView::Weekly,
- &buckets,
- today,
- /*width*/ 22,
- )
- .into_iter()
- .map(|line| line.to_string().trim_end().to_string())
- .collect::>()
- .join("\n");
-
- assert_snapshot!(rendered, @"
- Apr May
- max █
- █
- █ █
- █ █
- █ █ █
- █ █ █
- 0 █ █ █
-
- Each column = 1 week · tallest 9
- ");
-}
-
-#[test]
-fn cumulative_graph_snapshot_renders_running_total_bar_chart_and_caption() {
- let today =
- NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 5, /*day*/ 29).expect("valid date");
- let buckets = vec![
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-11".to_string(),
- tokens: 3,
- },
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-18".to_string(),
- tokens: 6,
- },
- AccountTokenUsageDailyBucket {
- start_date: "2026-05-25".to_string(),
- tokens: 9,
- },
- ];
-
- let rendered = chart_lines(
- TokenActivityView::Cumulative,
- &buckets,
- today,
- /*width*/ 22,
- )
- .into_iter()
- .map(|line| line.to_string().trim_end().to_string())
- .collect::>()
- .join("\n");
-
- assert_snapshot!(rendered, @"
- Apr May
- max █
- █
- █
- █ █
- █ █
- █ █ █
- 0 █ █ █
-
- Running total · top 18
- ");
-}
-
-#[test]
-fn year_window_ignores_other_dates_and_saturates_extreme_totals() {
- let today: NaiveDate = "2026-09-09".parse().unwrap();
- let buckets = [
- ("2025-01-01", 100),
- ("2026-09-10", 100),
- ("invalid", 100),
- ("2026-09-08", i64::MAX),
- ("2026-09-08", i64::MAX),
- ("2026-09-09", i64::MAX),
- ]
- .map(|(date, tokens)| AccountTokenUsageDailyBucket {
- start_date: date.into(),
- tokens,
- });
- let values = daily_values(&buckets, today);
- let mut expected = vec![0; CELL_COUNT];
- let index = (today - chart_start(today)).num_days() as usize;
- expected[index - 1] = i64::MAX;
- expected[index] = i64::MAX;
- assert_eq!(values, expected);
- for view in [
- TokenActivityView::Daily,
- TokenActivityView::Weekly,
- TokenActivityView::Cumulative,
- ] {
- let levels = levels_for_view(&values, view);
- assert!(levels.iter().all(|level| *level <= 4));
- assert!(levels.contains(&4));
- assert!(!chart_lines(view, &buckets, today, /*width*/ 110).is_empty());
- }
-}
diff --git a/codex-rs/tui/src/analytics/chart.rs b/codex-rs/tui/src/analytics/chart.rs
deleted file mode 100644
index b4ffd4f2..00000000
--- a/codex-rs/tui/src/analytics/chart.rs
+++ /dev/null
@@ -1,353 +0,0 @@
-//! Daily history with a stable chart and a compact, separated breakdown table.
-//! Chart series rank by the full range; table rows rank by the selected day and retain series colors.
-//! Wide focused reports place their breakdown beside the plot; narrow reports stack it.
-//! Missing and zero days retain the same row count; only viewport changes and explicit expansion change height.
-
-use super::AnalyticsView;
-use super::data;
-use super::plot;
-use super::render::categories;
-use super::render::columns;
-use super::styles::number;
-use super::styles::secondary_style;
-use super::styles::series_colors;
-use crate::analytics::models::AccountAnalyticsUnit;
-use crate::analytics::models::AccountAnalyticsValue;
-use crate::analytics::sections::Section;
-use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
-use ratatui::style::Styled;
-use ratatui::style::Stylize;
-use ratatui::text::Line;
-
-impl AnalyticsView {
- pub(super) fn day_has_details(&self, section: Section, day_index: usize) -> bool {
- let Some(history) = self.sections[section].history.ready() else {
- return false;
- };
- let date = self
- .section_date_range(section)
- .start()
- .iter_days()
- .nth(day_index);
- history.data.iter().any(|day| {
- date.is_some_and(|date| day.date == date)
- && day.values.iter().any(|value| value.value != 0.0)
- })
- }
-
- pub(super) fn history_lines(
- &self,
- section: Section,
- width: usize,
- height: usize,
- ) -> plot::Chart {
- let state = &self.sections[section].history;
- let Some(history) = state.ready() else {
- return plot::Chart {
- lines: state
- .message()
- .into_iter()
- .map(|message| message.to_string().set_style(secondary_style()).into())
- .collect(),
- bands: 0,
- };
- };
- if history.data.is_empty() {
- return plot::Chart {
- lines: vec![
- "No data reported for this range."
- .set_style(secondary_style())
- .into(),
- ],
- bands: 0,
- };
- }
- let range = self.section_date_range(section);
- // At most 30 daily slots; index by date if report ranges grow.
- let days = range
- .start()
- .iter_days()
- .take_while(|date| date <= range.end())
- .map(|date| {
- let day = history.data.iter().find(|day| day.date == date);
- (date, day)
- })
- .collect::>();
- let cursor = self.sections[section].cursor.min(days.len() - 1);
- let selected_date = days[cursor].0.format("%b %-d").to_string();
- let day = days[cursor].1;
- let expanded = self.zoomed && self.sections[section].detail.is_some();
- let colors = series_colors();
- let mut categories = categories(history);
- if matches!(section, Section::Plugins | Section::Skills) {
- for category in &mut categories {
- category.label = super::tool_panel::tool_name(&category.label);
- }
- }
- if self.sections[section].group == 2 {
- for category in &mut categories {
- category.label = self.model_name(&category.label).to_string();
- }
- }
- let unit = match section {
- Section::Usage if history.unit == AccountAnalyticsUnit::Tokens => "tokens",
- Section::Summary => "tokens",
- Section::Activity => "messages",
- Section::Plugins => "calls",
- Section::Skills => "uses",
- Section::Usage | Section::Credits | Section::Chats | Section::Plan => "credits",
- };
- let empty_breakdown = matches!(
- section,
- Section::Plugins | Section::Activity | Section::Skills
- ) && day.is_none_or(|day| {
- day.total == 0.0 && day.values.iter().all(|value| value.value == 0.0)
- });
- let relative = history.unit == AccountAnalyticsUnit::RelativeUsage;
- let format_amount = if history.unit == AccountAnalyticsUnit::Credits {
- data::credit_amount
- } else {
- data::amount
- };
- let total: f64 = history.data.iter().map(|day| day.total).sum();
- let formatted_total = if total.abs() >= 1_000.0 {
- data::compact_amount(total)
- } else {
- format_amount(total)
- };
- let mut lines = vec![if relative {
- "Total usage · relative units"
- .set_style(secondary_style())
- .into()
- } else {
- number(format!(
- "{} {}{unit}",
- formatted_total,
- if section == Section::Activity {
- "reported "
- } else {
- ""
- }
- ))
- .into()
- }];
- if section == Section::Usage && !self.business() && self.zoomed {
- lines.push(
- "Approximate · may be delayed up to 6 hours"
- .set_style(secondary_style())
- .into(),
- );
- }
- if self.sections[section].group == 3 {
- lines.push(
- "All usage by how each turn started"
- .set_style(secondary_style())
- .into(),
- );
- }
- let has_activity = history
- .data
- .iter()
- .any(|day| day.total != 0.0 || day.values.iter().any(|value| value.value != 0.0));
- let side_by_side = self.zoomed && width >= 140 && height > 0;
- let plot_width = if side_by_side { width - 48 } else { width };
- let mut bands = 0;
- if has_activity && height > 0 {
- let chart = plot::chart(&days, &categories, cursor, plot_width, height, history.unit);
- bands = chart.bands;
- lines.extend(chart.lines);
- } else if !has_activity {
- lines.push(
- if matches!(
- section,
- Section::Plugins | Section::Activity | Section::Skills
- ) {
- format!("No {unit} reported in this range.")
- .set_style(secondary_style())
- .into()
- } else {
- "No activity reported in this range."
- .set_style(secondary_style())
- .into()
- },
- );
- }
-
- let chart_end = lines.len();
- let table_width = if side_by_side {
- 44
- } else {
- width.min(/*other*/ 56)
- };
- lines.push(Line::default());
- if self.zoomed {
- lines.push("─".repeat(table_width).dim().into());
- }
- let table_start = lines.len();
- let summary = match day {
- None => " · Not reported".set_style(secondary_style()),
- Some(day) if day.total == 0.0 && day.values.iter().all(|value| value.value == 0.0) => {
- " · No activity (0)".set_style(secondary_style())
- }
- Some(day) if relative => number(format!(" · {} usage units", data::amount(day.total))),
- Some(day) => number(format!(
- " · {} {unit}",
- if expanded {
- day.total.to_string()
- } else {
- format_amount(day.total)
- }
- )),
- };
- lines.push(truncate_line_with_ellipsis_if_overflow(
- vec![selected_date.clone().bold(), summary].into(),
- table_width,
- ));
- if self.zoomed {
- lines.push(columns(
- match section {
- Section::Plugins => "Plugin",
- Section::Skills => "Skill",
- Section::Chats => "Chat",
- Section::Summary
- | Section::Usage
- | Section::Credits
- | Section::Activity
- | Section::Plan => self.group_label(section, self.sections[section].group),
- }
- .bold()
- .into(),
- if history.unit == AccountAnalyticsUnit::Tokens {
- "Tokens"
- } else if section == Section::Usage {
- "Share"
- } else if section == Section::Activity {
- "Messages"
- } else if section == Section::Plugins {
- "Calls"
- } else if section == Section::Skills {
- "Uses"
- } else {
- "Credits"
- }
- .bold()
- .into(),
- table_width,
- ));
- }
- let mut values = categories
- .iter()
- .enumerate()
- .map(|(index, category)| {
- (
- index,
- AccountAnalyticsValue {
- value: day
- .and_then(|day| {
- day.values.iter().find(|value| value.key == category.key)
- })
- .map_or(/*default*/ 0.0, |value| value.value),
- ..category.clone()
- },
- )
- })
- .collect::>();
- values.sort_by(|(_, a), (_, b)| b.value.abs().total_cmp(&a.value.abs()));
- let row_budget = if self.zoomed {
- (self.viewport_height / 4).max(/*other*/ 4)
- } else {
- 4
- };
- let remainder = if !expanded && values.len() > row_budget {
- let remaining = values.split_off(row_budget - 1);
- Some((
- format!("{} more", remaining.len()),
- remaining.iter().map(|(_, value)| value.value).sum::(),
- ))
- } else {
- None
- };
- let rows = values
- .iter()
- .map(|(index, value)| {
- (
- Line::from(vec![
- "● ".fg(colors[(*index).min(/*other*/ 3)]),
- value.label.clone().into(),
- ]),
- value.value,
- )
- })
- .chain(
- remainder.map(|(label, value)| (Line::from(vec!["… ".dim(), label.dim()]), value)),
- );
- for (label, value) in rows.take(if self.zoomed { usize::MAX } else { 2 }) {
- let amount = match day {
- None => "—".into(),
- Some(day)
- if section == Section::Usage
- && history.unit != AccountAnalyticsUnit::Tokens =>
- {
- format!(
- "{:.1}%",
- if day.total == 0.0 {
- 0.0
- } else {
- value / day.total * 100.0
- }
- )
- }
- Some(_) if expanded => value.to_string(),
- Some(_) => format_amount(value),
- };
- lines.push(columns(
- truncate_line_with_ellipsis_if_overflow(
- label,
- table_width.saturating_sub(amount.len() + 2),
- ),
- if day.is_none() || value == 0.0 {
- amount.dim()
- } else {
- amount.into()
- }
- .into(),
- table_width,
- ));
- }
- if empty_breakdown {
- // Preserve the measured table allocation when the selected day has no breakdown.
- let table_end = lines.len();
- lines.truncate(table_start);
- lines.push(truncate_line_with_ellipsis_if_overflow(
- if day.is_none() {
- format!("Data not reported for {selected_date}.")
- } else {
- format!("No {unit} reported for {selected_date}.")
- }
- .set_style(secondary_style())
- .into(),
- table_width,
- ));
- lines.resize(table_end, Line::default());
- }
- if !self.zoomed
- && let Some(updated) = history
- .updated_at
- .and_then(|value| chrono::DateTime::from_timestamp(value, /*nsecs*/ 0))
- {
- lines.push(
- format!(
- "Updated {} UTC",
- updated.format(self.clock_format.date_time_format())
- )
- .set_style(secondary_style())
- .into(),
- );
- }
- if side_by_side {
- let table = lines.split_off(chart_end);
- lines = super::render::join_columns(&lines, &table[1..], plot_width);
- }
- plot::Chart { lines, bands }
- }
-}
diff --git a/codex-rs/tui/src/analytics/chat_panel.rs b/codex-rs/tui/src/analytics/chat_panel.rs
deleted file mode 100644
index 133ff6b5..00000000
--- a/codex-rs/tui/src/analytics/chat_panel.rs
+++ /dev/null
@@ -1,325 +0,0 @@
-//! Bounded chat tables with inline credit breakdowns and a viewport-sized row window.
-//! Zero-credit groups are optional; missing dimensions and signed adjustments stay distinct.
-
-use super::AnalyticsView;
-use super::data;
-use super::render::columns;
-use super::styles::number;
-use super::styles::secondary_style;
-use crate::analytics::sections::Section;
-use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
-use crate::style::accent_style;
-use crate::wrapping::RtOptions;
-use crate::wrapping::word_wrap_lines;
-use ratatui::style::Styled;
-use ratatui::style::Stylize;
-use ratatui::text::Line;
-use std::ops::Range;
-
-impl AnalyticsView {
- pub(super) fn chat_lines(&self, width: usize) -> (Vec>, Range) {
- let row_width = width.clamp(/*min*/ 1, /*max*/ 97);
- let width = row_width.saturating_sub(/*rhs*/ 1).max(/*other*/ 1);
- let wrap = |lines: Vec>| word_wrap_lines(lines, RtOptions::new(width));
- let mut lines = wrap(vec![
- "Active in past 30 days · sorted by lifetime credits"
- .set_style(secondary_style())
- .into(),
- ]);
- if let Some(message) = self.chats.message() {
- lines.extend(wrap(vec![
- message.to_string().set_style(secondary_style()).into(),
- ]));
- }
- let Some(chats) = self.chats.ready() else {
- return (lines, 0..1);
- };
- if chats.rows.is_empty() {
- lines.extend(wrap(vec![
- "No recent local chats.".set_style(secondary_style()).into(),
- ]));
- return (lines, 0..1);
- }
- let missing = chats.rows.iter().filter(|row| row.usage.is_none()).count();
- if missing > 0 {
- lines.extend(wrap(vec![
- format!(
- "{missing} chat estimate{} unavailable",
- if missing == 1 { "" } else { "s" }
- )
- .set_style(secondary_style())
- .into(),
- ]));
- }
- lines.push(Line::default());
- let show_usd = chats.rows.iter().any(|chat| {
- chat.usage
- .as_ref()
- .is_some_and(|usage| usage.estimated_usage_usd_micros.is_some())
- });
- let stacked_amounts = show_usd && width < 70;
- lines.extend(wrap(vec![columns(
- " Chat".bold().into(),
- if stacked_amounts {
- "Est. $ / credits"
- } else if show_usd {
- "Est. $ spent Lifetime credits"
- } else {
- "Lifetime credits"
- }
- .bold()
- .into(),
- width,
- )]));
- let rows = chats
- .rows
- .iter()
- .enumerate()
- .map(|(index, chat)| {
- let selected =
- self.section == Section::Chats && index == self.sections[Section::Chats].cursor;
- let amount = chat.usage.as_ref().map_or_else(
- || "—".into(),
- |usage| data::credits(usage.estimated_usage_credits_micros),
- );
- let amount = if show_usd {
- let usd = chat
- .usage
- .as_ref()
- .and_then(|usage| usage.estimated_usage_usd_micros)
- .map(|micros| format!("${:.2}", micros as f64 / 1_000_000.0))
- .unwrap_or_else(|| "—".into());
- format!("{usd:>12} {amount:>16}")
- } else {
- amount
- };
- let label = format!(
- "{} {}",
- if selected { "›" } else { " " },
- chat.display_title()
- );
- let label: Line<'static> = if selected {
- label.set_style(accent_style()).into()
- } else {
- label.into()
- };
- let label_width = if stacked_amounts {
- width
- } else {
- width.saturating_sub(amount.len() + 1)
- };
- let truncated = label.width() > label_width;
- let mut row = if stacked_amounts {
- vec![
- truncate_line_with_ellipsis_if_overflow(label, label_width),
- format!(" {}", amount.trim()).into(),
- ]
- } else {
- vec![columns(
- truncate_line_with_ellipsis_if_overflow(label, label_width),
- if chat.usage.is_none() {
- amount.set_style(secondary_style()).into()
- } else if selected {
- number(amount).into()
- } else {
- amount.into()
- },
- width,
- )]
- };
- let header_len = row.len();
- if self.sections[Section::Chats].detail == Some(index)
- && let Some(usage) = &chat.usage
- {
- row.push(
- format!(" {}", "─".repeat(width.saturating_sub(/*rhs*/ 2)))
- .dim()
- .into(),
- );
- if truncated {
- row.extend(word_wrap_lines(
- [chat.display_title().to_string().bold()],
- RtOptions::new(width)
- .initial_indent(" ".into())
- .subsequent_indent(" ".into()),
- ));
- }
- let zeros = usage
- .groups
- .iter()
- .filter(|group| group.estimated_usage_credits_micros == 0)
- .count();
- let mut groups = usage
- .groups
- .iter()
- .filter(|group| {
- self.show_zero_credit_groups
- || group.estimated_usage_credits_micros != 0
- })
- .collect::>();
- groups.sort_by_key(|group| {
- std::cmp::Reverse(group.estimated_usage_credits_micros)
- });
- // On narrow terminals, retain every dimension on a second line.
- let table = width >= 70;
- if !groups.is_empty() {
- row.push(columns(
- if table {
- format!(
- " {: width {
- row.push(label);
- " ".into()
- } else {
- label
- }
- };
- row.push(columns(label, amount.into(), width));
- if !table {
- row.push(
- format!(" {effort} · {speed}")
- .set_style(secondary_style())
- .into(),
- );
- }
- }
- if usage.groups.is_empty() {
- row.push(
- " Breakdown unavailable"
- .set_style(secondary_style())
- .into(),
- );
- }
- if zeros > 0 {
- row.push(
- format!(
- " {zeros} zero-credit {}{} · a {}",
- if zeros == 1 { "group" } else { "groups" },
- if self.show_zero_credit_groups {
- ""
- } else {
- " hidden"
- },
- if self.show_zero_credit_groups {
- "hide zeros"
- } else {
- "show all"
- },
- )
- .set_style(secondary_style())
- .into(),
- );
- }
- row.push(Line::default());
- }
- let details = row.split_off(header_len);
- let mut row = wrap(row);
- // Wrap first: wrapping trims the highlighted trailing blank otherwise.
- if selected {
- for line in &mut row {
- super::styles::select_row(line, row_width);
- }
- }
- row.extend(wrap(details));
- row
- })
- .collect::>();
- let coverage = wrap(vec![
- "Local chats · excludes archived chats and subagent usage"
- .set_style(secondary_style())
- .into(),
- ]);
- self.chat_window(lines, rows, coverage, width)
- }
-
- pub(super) fn chat_window(
- &self,
- mut lines: Vec>,
- rows: Vec>>,
- coverage: Vec>,
- width: usize,
- ) -> (Vec>, Range) {
- let wrap = |lines: Vec>| word_wrap_lines(lines, RtOptions::new(width));
- let count = rows.len();
- let range_height = wrap(vec![
- format!("Showing {count}–{count} of {count} chats").into(),
- ])
- .len();
- // Measure wrapped details before choosing neighbors so the range describes the rendered rows.
- let budget = self
- .viewport_height
- .saturating_sub(lines.len() + coverage.len() + range_height + 2);
- let row_limit = count;
- let cursor = self.sections[Section::Chats].cursor.min(count - 1);
- let mut first = cursor;
- let mut end = cursor + 1;
- let mut used = rows[cursor].len();
- while first > 0 && end - first < row_limit && used + rows[first - 1].len() <= budget {
- first -= 1;
- used += rows[first].len();
- }
- while end < count && end - first < row_limit && used + rows[end].len() <= budget {
- used += rows[end].len();
- end += 1;
- }
- let mut selection = 0..1;
- for (index, row) in rows.into_iter().enumerate().take(end).skip(first) {
- if index == cursor {
- selection = lines.len()..lines.len() + row.len();
- }
- lines.extend(row);
- }
- lines.push(Line::default());
- lines.extend(wrap(vec![
- format!("Showing {}–{end} of {count} chats", first + 1)
- .set_style(secondary_style())
- .into(),
- ]));
- lines.extend(coverage);
- (lines, selection)
- }
-}
diff --git a/codex-rs/tui/src/analytics/chat_panel_tests.rs b/codex-rs/tui/src/analytics/chat_panel_tests.rs
deleted file mode 100644
index ff50868b..00000000
--- a/codex-rs/tui/src/analytics/chat_panel_tests.rs
+++ /dev/null
@@ -1,212 +0,0 @@
-//! Chat list coverage, responsive expansion, and controls for fixed-period data.
-
-use super::*;
-use pretty_assertions::assert_eq;
-
-#[test]
-fn chats_range_controls_and_visible_rows() {
- let mut view = fixture::view(models::AccountKind::Enterprise);
- let mut chats = fixture::chats();
- let usage = chats.rows[0].usage.clone();
- chats.rows = (1..=30)
- .map(|index| chats::Chat {
- title: format!("Chat {index:02}"),
- usage: usage.clone(),
- })
- .collect();
- view.chats = Load::Ready(chats);
- press(&mut view, KeyCode::Char('6'));
- let before = (
- view.ranges,
- view.sections.0.each_ref().map(|state| state.cursor),
- view.sections.0.each_ref().map(|state| state.detail),
- );
- press(&mut view, KeyCode::Char('r'));
- assert_eq!(
- (
- view.ranges,
- view.sections.0.each_ref().map(|state| state.cursor),
- view.sections.0.each_ref().map(|state| state.detail)
- ),
- before
- );
- for key in [KeyCode::Home, KeyCode::End, KeyCode::Enter] {
- press(&mut view, key);
- let output = screen(&mut view, /*width*/ 110, /*height*/ 24);
- assert!(!output.contains("7d") && !output.contains("r 7/30d"));
- let visible = (1..=30)
- .filter(|index| output.contains(&format!("Chat {index:02}")))
- .collect::>();
- assert!(output.contains(&format!(
- "Showing {}–{} of 30 chats",
- visible.first().unwrap(),
- visible.last().unwrap()
- )));
- }
- press(&mut view, KeyCode::Char('r'));
- assert_eq!(view.ranges, [0; 3]);
- press(&mut view, KeyCode::Char('2'));
- press(&mut view, KeyCode::Char('r'));
- assert_eq!(view.ranges[view.range_group(Section::Credits) as usize], 1);
- assert!(screen(&mut view, /*width*/ 110, /*height*/ 24).contains("r 7d/30d"));
-}
-
-#[test]
-fn chats_breakdown_ranks_nonzero_groups_and_reflows() {
- let mut view = fixture::view(models::AccountKind::Enterprise);
- let mut chats = fixture::chats();
- let usage = chats.rows[0].usage.as_mut().unwrap();
- let seed = usage.groups[0].clone();
- usage.groups = [
- ("Zero model", 0),
- ("Small model", 215_610_920),
- ("Top model", 19_134_430_635),
- ("Refund model", -4),
- ]
- .map(
- |(model, credits)| codex_backend_client::ThreadUsageBreakdownGroup {
- model: Some(model.into()),
- speed: (credits != 19_134_430_635).then(|| "standard".into()),
- estimated_usage_credits_micros: credits,
- ..seed.clone()
- },
- )
- .to_vec();
- usage.estimated_usage_credits_micros = usage
- .groups
- .iter()
- .map(|group| group.estimated_usage_credits_micros)
- .sum();
- view.chats = Load::Ready(chats);
- press(&mut view, KeyCode::Char('6'));
- press(&mut view, KeyCode::Enter);
- let mut screens = Vec::new();
- for width in [110, 58] {
- view.follow_selection = true;
- let output = screen(&mut view, width, /*height*/ 32);
- assert!(output.find("Top model").unwrap() < output.find("Small model").unwrap());
- assert!(output.find("Small model").unwrap() < output.find("Refund model").unwrap());
- assert!(!output.contains("Zero model"));
- assert!(output.contains("-0.000004") && output.contains("Not reported"));
- assert!(output.contains("19,350.04") && output.contains("19,134.43"));
- assert!(output.contains("1 zero-credit group hidden · a show all"));
- assert!(output.contains("Refactor billing usage"));
- screens.push(output);
- }
- press(&mut view, KeyCode::Char('a'));
- let expanded = screen(&mut view, /*width*/ 110, /*height*/ 32);
- assert!(expanded.contains("Zero model") && expanded.contains("a hide zeros"));
- screens.push(expanded);
- press(&mut view, KeyCode::Char('a'));
- assert!(!view.show_zero_credit_groups);
- let wide = view.chat_lines(/*width*/ 220).0;
- // The content stays within 96 columns, plus one highlighted trailing blank.
- assert!(wide.iter().all(|line| line.width() <= 97));
- insta::assert_snapshot!(screens.join("\n"));
-}
-
-#[test]
-fn chats_long_title_keeps_detail_indent_and_counts_missing_estimates() {
- let mut view = fixture::view(models::AccountKind::Enterprise);
- let mut chats = fixture::chats();
- chats.rows[0].title = "Create a comprehensive list of areas to investigate across the runtime and describe how each area affects performance in a long conversation".into();
- chats.rows[1].usage = None;
- chats.rows[2].usage = None;
- view.chats = Load::Ready(chats);
- press(&mut view, KeyCode::Char('6'));
- press(&mut view, KeyCode::Enter);
- let output = screen(&mut view, /*width*/ 110, /*height*/ 30);
- assert!(output.contains("2 chat estimates unavailable"));
- insta::assert_snapshot!(output);
-}
-
-#[tokio::test]
-async fn unavailable_chats_do_not_open_invisible_details() {
- for key in [KeyCode::Enter, KeyCode::Right] {
- for state in 0..5 {
- let mut view = fixture::view(models::AccountKind::Enterprise);
- view.section = Section::Chats;
- view.chats = match state {
- 0 => Load::Unavailable,
- 1 => Load::Error("Temporary failure".into()),
- 2 => Load::Ready(chats::Chats::default()),
- 3 => Load::Ready(chats::Chats {
- rows: vec![chats::Chat {
- title: "Another workspace's private title".into(),
- usage: None,
- }],
- }),
- _ => Load::start(std::future::pending(), FrameRequester::test_dummy()),
- };
- press(&mut view, key);
- assert_eq!(view.sections[Section::Chats].detail, None);
- press(&mut view, KeyCode::Esc);
- assert!(view.is_done);
- }
- }
-}
-
-#[test]
-fn unavailable_chat_titles_are_hidden_in_panel_and_overview() {
- let mut view = fixture::view(models::AccountKind::Enterprise);
- view.section = Section::Chats;
- view.chats = Load::Ready(chats::Chats {
- rows: vec![chats::Chat {
- title: "Another workspace's private title".into(),
- usage: None,
- }],
- });
-
- view.follow_selection = true;
- let output = screen(&mut view, /*width*/ 110, /*height*/ 28);
- assert!(!output.contains("Another workspace's private title"));
- assert!(output.contains("Chat usage unavailable"));
-}
-
-#[test]
-fn moving_chat_selection_collapses_details_before_they_leave_the_viewport() {
- for (start, key) in [
- (0, KeyCode::Down),
- (1, KeyCode::Up),
- (0, KeyCode::End),
- (2, KeyCode::Home),
- ] {
- let mut view = fixture::view(models::AccountKind::Enterprise);
- view.section = Section::Chats;
- view.sections[Section::Chats].cursor = start;
- press(&mut view, KeyCode::Enter);
- assert_eq!(view.sections[Section::Chats].detail, Some(start));
- press(&mut view, key);
- assert_eq!(view.sections[Section::Chats].detail, None);
- press(&mut view, KeyCode::Esc);
- assert!(view.is_done);
- }
-}
-
-#[test]
-fn chat_help_and_zero_credit_action_follow_account_and_detail_state() {
- for kind in [models::AccountKind::Consumer, models::AccountKind::Business] {
- let mut view = fixture::view(kind);
- fixture::seed_reports(&mut view);
- view.section = Section::Chats;
- view.sections[Section::Chats].detail = Some(0);
- let help = view
- .help_lines(/*width*/ 100)
- .iter()
- .map(ToString::to_string)
- .collect::>()
- .join("\n");
- let business = kind == models::AccountKind::Business;
- assert_eq!(help.contains("a · show zero-credit"), business);
- assert_eq!(help.contains("s · change chat sort metric"), !business);
- press(&mut view, KeyCode::Char('a'));
- assert_eq!(view.show_zero_credit_groups, business);
- view.sections[Section::Chats].detail = None;
- assert!(
- !view
- .help_lines(/*width*/ 100)
- .iter()
- .any(|line| line.to_string().contains("a · show zero-credit"))
- );
- }
-}
diff --git a/codex-rs/tui/src/analytics/chats.rs b/codex-rs/tui/src/analytics/chats.rs
deleted file mode 100644
index f9dd8c68..00000000
--- a/codex-rs/tui/src/analytics/chats.rs
+++ /dev/null
@@ -1,200 +0,0 @@
-//! Discover recent local roots and load business chat credit estimates.
-
-use super::client::Live;
-use super::client::Session;
-use super::data;
-use codex_app_server_client::AppServerRequestHandle;
-use codex_app_server_protocol::ClientRequest;
-use codex_app_server_protocol::RequestId;
-use codex_app_server_protocol::SortDirection;
-use codex_app_server_protocol::ThreadListParams;
-use codex_app_server_protocol::ThreadListResponse;
-use codex_app_server_protocol::ThreadSortKey;
-use codex_backend_client::ThreadUsage;
-use std::collections::HashMap;
-use std::collections::HashSet;
-use std::sync::Arc;
-
-pub(super) struct Chat {
- pub title: String,
- pub usage: Option,
-}
-
-impl Chat {
- /// Local history can span accounts; expose titles only with a returned account estimate.
- pub(super) fn display_title(&self) -> &str {
- if self.usage.is_some() {
- &self.title
- } else {
- "Chat usage unavailable"
- }
- }
-}
-
-#[derive(Default)]
-pub(super) struct Chats {
- pub rows: Vec,
-}
-
-pub(super) async fn read(
- handle: AppServerRequestHandle,
- live: Arc,
-) -> Result