README: aKode (stato del lavoro, build, configurazione endpoint locale, licenza)
Some checks failed
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
Some checks failed
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled
This commit is contained in:
130
README.md
130
README.md
@@ -1,81 +1,87 @@
|
|||||||
<p align="center"><strong>Codex CLI</strong> is a coding agent from OpenAI that runs locally on your computer.
|
# aKode
|
||||||
<p align="center">
|
|
||||||
<img src="https://github.com/openai/codex/blob/main/.github/codex-cli-splash.png" alt="Codex CLI splash" width="80%" />
|
**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.
|
||||||
</p>
|
|
||||||
</br>
|
È 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.
|
||||||
If you want Codex in your code editor (VS Code, Cursor, Windsurf), <a href="https://developers.openai.com/codex/ide">install in your IDE.</a>
|
|
||||||
</br>If you want the desktop app experience, run <code>codex app</code> or visit <a href="https://chatgpt.com/codex?app-landing-page=true">the Codex App page</a>.
|
> **Uso privato.** Questo repository (`git.difonzo.net/andrea/aKode`) non è distribuito né pubblicato.
|
||||||
</br>If you are looking for the <em>cloud-based agent</em> from OpenAI, <strong>Codex Web</strong>, go to <a href="https://chatgpt.com/codex">chatgpt.com/codex</a>.</p>
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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 <crate> --lib`). La cartella `codex-rs/target` può superare i 50 GB: cancellala quando non serve.
|
||||||
|
|
||||||
```shell
|
## Configurazione di un modello
|
||||||
powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"
|
|
||||||
|
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):
|
```bash
|
||||||
|
export IMEAI_API_KEY="..." # chiave del server
|
||||||
```shell
|
codex exec "descrivi questo progetto"
|
||||||
curl -fsSL https://chatgpt.com/codex/install.sh | CODEX_INSTALLER_USE_RELEASES_OPENAI_COM=false sh
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```powershell
|
**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.
|
||||||
$env:CODEX_INSTALLER_USE_RELEASES_OPENAI_COM='false'; irm https://chatgpt.com/codex/install.ps1 | iex
|
|
||||||
```
|
|
||||||
|
|
||||||
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
|
## Cosa è stato tolto rispetto a Codex
|
||||||
# Install using Homebrew
|
|
||||||
brew install --cask 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.
|
||||||
|
|
||||||
<details>
|
## Licenza
|
||||||
<summary>You can also go to the <a href="https://github.com/openai/codex/releases/latest">latest GitHub Release</a> and download the appropriate binary for your platform.</summary>
|
|
||||||
|
|
||||||
Each GitHub Release contains many executables, but in practice, you likely want one of these:
|
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.
|
||||||
|
|
||||||
- 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.
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
### 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).
|
|
||||||
|
|||||||
@@ -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<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn checkout_remote_plugin_share(
|
|
||||||
config: &RemotePluginServiceConfig,
|
|
||||||
auth: Option<&CodexAuth>,
|
|
||||||
codex_home: &Path,
|
|
||||||
remote_plugin_id: &str,
|
|
||||||
) -> Result<RemotePluginShareCheckoutResult, RemotePluginCatalogError> {
|
|
||||||
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<BTreeMap<String, AbsolutePathBuf>, 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<String, AbsolutePathBuf>,
|
|
||||||
) -> 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<String>,
|
|
||||||
) -> Result<PersonalMarketplaceUpdate, RemotePluginCatalogError> {
|
|
||||||
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<JsonValue, RemotePluginCatalogError> {
|
|
||||||
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<String>,
|
|
||||||
) -> 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<String, RemotePluginCatalogError> {
|
|
||||||
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(())
|
|
||||||
}
|
|
||||||
@@ -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<JsonValue>,
|
|
||||||
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<String> {
|
|
||||||
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<JsonValue>,
|
|
||||||
) -> Result<ValidatedRemotePluginBundle, RemotePluginBundleInstallError> {
|
|
||||||
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<PluginInstallResult, RemotePluginBundleInstallError> {
|
|
||||||
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<AbsolutePathBuf, RemotePluginBundleInstallError> {
|
|
||||||
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<Vec<u8>, 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<Vec<u8>, 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<u8>,
|
|
||||||
) -> Result<PluginInstallResult, RemotePluginBundleInstallError> {
|
|
||||||
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<u8>,
|
|
||||||
destination: AbsolutePathBuf,
|
|
||||||
) -> Result<AbsolutePathBuf, RemotePluginBundleInstallError> {
|
|
||||||
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<PathBuf, RemotePluginBundleInstallError> {
|
|
||||||
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::<serde_json::Value>(
|
|
||||||
&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<u8> {
|
|
||||||
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<u8> {
|
|
||||||
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<W: std::io::Write>(
|
|
||||||
tar: &mut tar::Builder<W>,
|
|
||||||
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<GzEncoder<Vec<u8>>>) -> Vec<u8> {
|
|
||||||
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}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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<String, String>,
|
|
||||||
sections: SectionStates,
|
|
||||||
chats: Load<chats::Chats>,
|
|
||||||
tasks: Load<tasks::Chats>,
|
|
||||||
chat_metric: usize,
|
|
||||||
profile: Load<codex_backend_client::AccountProfile>,
|
|
||||||
plan: plan::State,
|
|
||||||
show_zero_credit_groups: bool,
|
|
||||||
account: Load<codex_protocol::account::PlanType>,
|
|
||||||
reports_started: bool,
|
|
||||||
connection: Option<(
|
|
||||||
std::sync::Arc<crate::legacy_core::config::Config>,
|
|
||||||
AppServerRequestHandle,
|
|
||||||
FrameRequester,
|
|
||||||
)>,
|
|
||||||
live: Option<std::sync::Arc<client::Live>>,
|
|
||||||
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<String>,
|
|
||||||
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<codex_protocol::openai_models::ModelPreset>,
|
|
||||||
config: std::sync::Arc<crate::legacy_core::config::Config>,
|
|
||||||
) {
|
|
||||||
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(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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::<f64>(),
|
|
||||||
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::<Vec<_>>();
|
|
||||||
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::<Vec<_>>();
|
|
||||||
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"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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<Self> {
|
|
||||||
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<Line<'static>> {
|
|
||||||
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::<String>(), 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<i64> {
|
|
||||||
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<usize> {
|
|
||||||
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::<Vec<_>>();
|
|
||||||
bar_levels(&cumulative)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn graded_levels(values: &[i64]) -> Vec<usize> {
|
|
||||||
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<i64> {
|
|
||||||
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<usize> {
|
|
||||||
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<NaiveDate> {
|
|
||||||
chart_start(today).checked_add_signed(Duration::days(index as i64))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "activity_chart_tests.rs"]
|
|
||||||
mod tests;
|
|
||||||
@@ -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;
|
|
||||||
@@ -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::<Vec<_>>()
|
|
||||||
.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);
|
|
||||||
}
|
|
||||||
@@ -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))
|
|
||||||
@@ -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::<i64>(), 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::<Vec<_>>()
|
|
||||||
.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::<Vec<_>>()
|
|
||||||
.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::<Vec<_>>()
|
|
||||||
.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::<Vec<_>>()
|
|
||||||
.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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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::<Vec<_>>();
|
|
||||||
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::<Vec<_>>();
|
|
||||||
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::<f64>(),
|
|
||||||
))
|
|
||||||
} 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 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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<Line<'static>>, Range<usize>) {
|
|
||||||
let row_width = width.clamp(/*min*/ 1, /*max*/ 97);
|
|
||||||
let width = row_width.saturating_sub(/*rhs*/ 1).max(/*other*/ 1);
|
|
||||||
let wrap = |lines: Vec<Line<'static>>| 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::<Vec<_>>();
|
|
||||||
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!(
|
|
||||||
" {:<model_width$} {:<12} {:<12}",
|
|
||||||
"Model",
|
|
||||||
"Effort",
|
|
||||||
"Speed",
|
|
||||||
model_width = width - 46
|
|
||||||
)
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into()
|
|
||||||
} else {
|
|
||||||
" Model / effort / speed"
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into()
|
|
||||||
},
|
|
||||||
"Credits".bold().into(),
|
|
||||||
width,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
for group in groups {
|
|
||||||
let model =
|
|
||||||
self.model_name(group.model.as_deref().unwrap_or("Not reported"));
|
|
||||||
let effort = group.reasoning_effort.as_deref().unwrap_or("Not reported");
|
|
||||||
let speed = group.speed.as_deref().unwrap_or("Not reported");
|
|
||||||
let amount = data::credits(group.estimated_usage_credits_micros);
|
|
||||||
let label = if table {
|
|
||||||
// Wrap long model names instead of hiding distinctions between groups.
|
|
||||||
let model_width = width - 46;
|
|
||||||
let models = textwrap::wrap(model, model_width);
|
|
||||||
for model in models.iter().take(models.len().saturating_sub(/*rhs*/ 1))
|
|
||||||
{
|
|
||||||
row.push(format!(" {model}").bold().into());
|
|
||||||
}
|
|
||||||
vec![
|
|
||||||
format!(
|
|
||||||
" {:<model_width$}",
|
|
||||||
models
|
|
||||||
.last()
|
|
||||||
.map(std::convert::AsRef::as_ref)
|
|
||||||
.unwrap_or_default()
|
|
||||||
)
|
|
||||||
.bold(),
|
|
||||||
format!(" {effort:<12} {speed:<12}").set_style(secondary_style()),
|
|
||||||
]
|
|
||||||
.into()
|
|
||||||
} else {
|
|
||||||
let label = Line::from(format!(" {model}").bold());
|
|
||||||
if label.width() + amount.len() + 1 > 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::<Vec<_>>();
|
|
||||||
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<Line<'static>>,
|
|
||||||
rows: Vec<Vec<Line<'static>>>,
|
|
||||||
coverage: Vec<Line<'static>>,
|
|
||||||
width: usize,
|
|
||||||
) -> (Vec<Line<'static>>, Range<usize>) {
|
|
||||||
let wrap = |lines: Vec<Line<'static>>| 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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::<Vec<_>>();
|
|
||||||
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::<Vec<_>>()
|
|
||||||
.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"))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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<ThreadUsage>,
|
|
||||||
}
|
|
||||||
|
|
||||||
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<Chat>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn read(
|
|
||||||
handle: AppServerRequestHandle,
|
|
||||||
live: Arc<Live>,
|
|
||||||
) -> Result<Option<Chats>, String> {
|
|
||||||
let session = live.session().await?;
|
|
||||||
if !super::models::thread_usage_supported(session.backend.account().plan_type) {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
live.ensure_identity().await?;
|
|
||||||
let threads = tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 60), roots(&handle))
|
|
||||||
.await
|
|
||||||
.map_err(|_| "Chat listing timed out. Press R to retry.".to_string());
|
|
||||||
live.ensure_identity().await?;
|
|
||||||
let threads = threads??;
|
|
||||||
if threads.is_empty() {
|
|
||||||
return Ok(Some(Chats { rows: Vec::new() }));
|
|
||||||
}
|
|
||||||
let ids = threads
|
|
||||||
.iter()
|
|
||||||
.map(|thread| thread.id.as_str())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
// Repairing local history has its own budget; it must not consume estimate time.
|
|
||||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(/*secs*/ 25);
|
|
||||||
let mut data = Vec::new();
|
|
||||||
for pair in ids.chunks(/*chunk_size*/ 200) {
|
|
||||||
let midpoint = pair.len().min(/*other*/ 100);
|
|
||||||
let (first, second) = tokio::join!(
|
|
||||||
tokio::time::timeout_at(deadline, estimates(session, &pair[..midpoint])),
|
|
||||||
tokio::time::timeout_at(deadline, estimates(session, &pair[midpoint..])),
|
|
||||||
);
|
|
||||||
live.ensure_identity().await?;
|
|
||||||
for batch in [first, second].into_iter().flatten() {
|
|
||||||
data.extend(batch?);
|
|
||||||
}
|
|
||||||
if tokio::time::Instant::now() >= deadline {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
live.ensure_identity().await?;
|
|
||||||
let mut usage: HashMap<_, _> = data
|
|
||||||
.into_iter()
|
|
||||||
.map(|row| (row.thread_id.clone(), row))
|
|
||||||
.collect();
|
|
||||||
let mut rows = threads
|
|
||||||
.into_iter()
|
|
||||||
.map(|thread| Chat {
|
|
||||||
usage: usage.remove(&thread.id),
|
|
||||||
title: thread
|
|
||||||
.name
|
|
||||||
.filter(|name| !name.trim().is_empty())
|
|
||||||
.unwrap_or_else(|| {
|
|
||||||
if thread.preview.trim().is_empty() {
|
|
||||||
"Untitled chat".into()
|
|
||||||
} else {
|
|
||||||
thread.preview
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
rows.sort_by_key(|row| {
|
|
||||||
std::cmp::Reverse(
|
|
||||||
row.usage
|
|
||||||
.as_ref()
|
|
||||||
.map(|usage| usage.estimated_usage_credits_micros),
|
|
||||||
)
|
|
||||||
});
|
|
||||||
Ok(Some(Chats { rows }))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Recent local roots are shared by consumer task and business credit reporting.
|
|
||||||
pub(super) async fn roots(
|
|
||||||
handle: &AppServerRequestHandle,
|
|
||||||
) -> Result<Vec<codex_app_server_protocol::Thread>, String> {
|
|
||||||
let cutoff = chrono::Utc::now().timestamp() - 30 * 24 * 60 * 60;
|
|
||||||
let mut threads = Vec::new();
|
|
||||||
let mut cursor = None;
|
|
||||||
let mut seen_cursors = HashSet::new();
|
|
||||||
loop {
|
|
||||||
let page: ThreadListResponse = handle
|
|
||||||
.request_typed(ClientRequest::ThreadList {
|
|
||||||
request_id: RequestId::String(uuid::Uuid::new_v4().to_string()),
|
|
||||||
params: ThreadListParams {
|
|
||||||
cursor,
|
|
||||||
..list_params()
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(data::error)?;
|
|
||||||
let reached_cutoff = page.data.iter().any(|thread| thread.updated_at < cutoff);
|
|
||||||
threads.extend(page.data.into_iter().filter(|thread| {
|
|
||||||
thread.updated_at >= cutoff && !thread.ephemeral && thread.parent_thread_id.is_none()
|
|
||||||
}));
|
|
||||||
match page.next_cursor {
|
|
||||||
Some(next) if !seen_cursors.insert(next.clone()) => {
|
|
||||||
return Err("Chat listing repeated a cursor. Press R to retry.".into());
|
|
||||||
}
|
|
||||||
Some(next) if !reached_cutoff => cursor = Some(next),
|
|
||||||
_ => break,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Keep repeated rows from overlapping pages out of the backend's distinct-ID batches.
|
|
||||||
let mut seen_ids = HashSet::new();
|
|
||||||
threads.retain(|thread| seen_ids.insert(thread.id.clone()));
|
|
||||||
Ok(threads)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn list_params() -> ThreadListParams {
|
|
||||||
ThreadListParams {
|
|
||||||
current_account_only: true,
|
|
||||||
excluded_thread_ids: None,
|
|
||||||
attached_to_thread_id: None,
|
|
||||||
limit: Some(100),
|
|
||||||
sort_key: Some(ThreadSortKey::UpdatedAt),
|
|
||||||
sort_direction: Some(SortDirection::Desc),
|
|
||||||
model_providers: Some(Vec::new()),
|
|
||||||
source_kinds: None,
|
|
||||||
originators: None,
|
|
||||||
archived: Some(false),
|
|
||||||
cursor: None,
|
|
||||||
section_id: None,
|
|
||||||
project_id: None,
|
|
||||||
cwd: None,
|
|
||||||
use_state_db_only: false,
|
|
||||||
search_term: None,
|
|
||||||
parent_thread_id: None,
|
|
||||||
ancestor_thread_id: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Isolate unavailable estimates within the existing concurrency slot; keep healthy rows.
|
|
||||||
async fn estimates(session: &Session, ids: &[&str]) -> Result<Vec<ThreadUsage>, String> {
|
|
||||||
let mut pending = if ids.is_empty() {
|
|
||||||
Vec::new()
|
|
||||||
} else {
|
|
||||||
vec![ids]
|
|
||||||
};
|
|
||||||
let mut rows = Vec::new();
|
|
||||||
// At most 15 requests per batch; leave remaining estimates unavailable during an outage.
|
|
||||||
for _ in 0..15 {
|
|
||||||
let Some(ids) = pending.pop() else { break };
|
|
||||||
match session
|
|
||||||
.backend
|
|
||||||
.request(|client| async move { client.get_threads_usage(ids).await })
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(batch) => rows.extend(batch),
|
|
||||||
Err(error) if error.status().is_some_and(|status| status.as_u16() == 503) => {
|
|
||||||
if ids.len() > 1 {
|
|
||||||
let midpoint = ids.len().div_ceil(/*rhs*/ 2);
|
|
||||||
pending.push(&ids[midpoint..]);
|
|
||||||
pending.push(&ids[..midpoint]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(error) => return Err(super::client::request_error(error)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(rows)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "chats_tests.rs"]
|
|
||||||
mod tests;
|
|
||||||
@@ -1,180 +0,0 @@
|
|||||||
//! Verify bounded chat discovery, account eligibility, and partial estimate handling.
|
|
||||||
|
|
||||||
use super::super::client::tests::live;
|
|
||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::MockServer;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn incomplete_chat_batches_retain_available_estimates_without_inventing_zeroes() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "enterprise_cbp_usage_based").await;
|
|
||||||
Mock::given(method("POST")).and(path("/backend-api/wham/usage/thread_usage/query"))
|
|
||||||
.respond_with(|request: &wiremock::Request| {
|
|
||||||
let body: serde_json::Value = request.body_json().unwrap();
|
|
||||||
let ids = body["thread_ids"].as_array().unwrap();
|
|
||||||
if ids.len() > 1 || ids[0] == "incomplete" {
|
|
||||||
ResponseTemplate::new(/*s*/ 503).set_body_json(json!({"detail": "Thread usage is temporarily unavailable."}))
|
|
||||||
} else {
|
|
||||||
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"threads": [{
|
|
||||||
"thread_id": ids[0], "estimated_usage_credits_micros": if ids[0] == "missing" { None } else { Some(1250000) },
|
|
||||||
"estimated_usage_usd_micros": null, "groups": null,
|
|
||||||
}]}))
|
|
||||||
}
|
|
||||||
}).expect(/*r*/ 5).mount(&server).await;
|
|
||||||
let session = live.session().await.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
estimates(session, &["available", "incomplete", "missing"])
|
|
||||||
.await
|
|
||||||
.unwrap(),
|
|
||||||
vec![ThreadUsage {
|
|
||||||
thread_id: "available".into(),
|
|
||||||
estimated_usage_credits_micros: 1250000,
|
|
||||||
estimated_usage_usd_micros: None,
|
|
||||||
native_usage_usd_micros: None,
|
|
||||||
groups: Vec::new(),
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn slow_repairing_chat_listing_keeps_estimate_budget_and_ranks_across_pages() {
|
|
||||||
use codex_app_server_client::RemoteAppServerClient;
|
|
||||||
use codex_app_server_client::RemoteAppServerConnectArgs;
|
|
||||||
use codex_app_server_client::RemoteAppServerEndpoint;
|
|
||||||
use futures::SinkExt;
|
|
||||||
use futures::StreamExt;
|
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
|
||||||
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "enterprise_cbp_usage_based").await;
|
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
||||||
let websocket_url = format!("ws://{}", listener.local_addr().unwrap());
|
|
||||||
let rpc = tokio::spawn(async move {
|
|
||||||
let (stream, _) = listener.accept().await.unwrap();
|
|
||||||
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
|
|
||||||
let mut pages = Vec::new();
|
|
||||||
while let Some(Ok(Message::Text(text))) = socket.next().await {
|
|
||||||
let request: serde_json::Value = serde_json::from_str(&text).unwrap();
|
|
||||||
let result = match request["method"].as_str() {
|
|
||||||
Some("initialize") => {
|
|
||||||
json!({"userAgent": "analytics-test", "codexHome": "/unused"})
|
|
||||||
}
|
|
||||||
Some("thread/list") => {
|
|
||||||
let params = &request["params"];
|
|
||||||
pages.push(json!([
|
|
||||||
params["cursor"],
|
|
||||||
params["limit"],
|
|
||||||
params["useStateDbOnly"].as_bool().unwrap_or_default(),
|
|
||||||
params["modelProviders"]
|
|
||||||
]));
|
|
||||||
if pages.len() == 1 {
|
|
||||||
// Simulate repair exceeding the HTTP estimate budget without a wall-clock wait.
|
|
||||||
tokio::time::pause();
|
|
||||||
tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 26)).await;
|
|
||||||
tokio::time::resume();
|
|
||||||
}
|
|
||||||
let range = if pages.len() == 1 { 0..100 } else { 100..101 };
|
|
||||||
let data = range.map(|index| json!({
|
|
||||||
"id": format!("chat-{index}"), "sessionId": format!("chat-{index}"),
|
|
||||||
"preview": "", "name": format!("Chat {index}"), "ephemeral": false,
|
|
||||||
"modelProvider": "openai", "createdAt": 0,
|
|
||||||
"updatedAt": chrono::Utc::now().timestamp(), "status": {"type": "idle"},
|
|
||||||
"cwd": std::env::temp_dir(), "cliVersion": "test", "source": "cli", "turns": [],
|
|
||||||
})).collect::<Vec<_>>();
|
|
||||||
json!({"data": data, "nextCursor": if pages.len() == 1 { Some("next") } else { None }})
|
|
||||||
}
|
|
||||||
_ => continue,
|
|
||||||
};
|
|
||||||
socket
|
|
||||||
.send(Message::Text(
|
|
||||||
json!({"jsonrpc": "2.0", "id": request["id"], "result": result})
|
|
||||||
.to_string()
|
|
||||||
.into(),
|
|
||||||
))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
if pages.len() == 2 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pages
|
|
||||||
});
|
|
||||||
let remote = RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
|
|
||||||
required_human_approval: true,
|
|
||||||
endpoint: RemoteAppServerEndpoint::WebSocket {
|
|
||||||
websocket_url,
|
|
||||||
auth_token: None,
|
|
||||||
},
|
|
||||||
client_name: "analytics-test".into(),
|
|
||||||
client_version: "test".into(),
|
|
||||||
experimental_api: false,
|
|
||||||
mcp_server_openai_form_elicitation: false,
|
|
||||||
opt_out_notification_methods: Vec::new(),
|
|
||||||
channel_capacity: 16,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
Mock::given(method("POST")).and(path("/backend-api/wham/usage/thread_usage/query"))
|
|
||||||
.respond_with(|request: &wiremock::Request| {
|
|
||||||
let body: serde_json::Value = request.body_json().unwrap();
|
|
||||||
let ids = body["thread_ids"].as_array().unwrap();
|
|
||||||
assert!(ids.len() <= 100);
|
|
||||||
if ids.iter().any(|id| id == "chat-35") {
|
|
||||||
return ResponseTemplate::new(/*s*/ 503)
|
|
||||||
.set_body_json(json!({"detail": "Thread usage is temporarily unavailable."}));
|
|
||||||
}
|
|
||||||
let threads = ids.iter().map(|id| json!({
|
|
||||||
"thread_id": id,
|
|
||||||
"estimated_usage_credits_micros": id.as_str().unwrap().strip_prefix("chat-").unwrap().parse::<i64>().unwrap(),
|
|
||||||
})).collect::<Vec<_>>();
|
|
||||||
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"threads": threads}))
|
|
||||||
}).expect(/*r*/ 2..=16).mount(&server).await;
|
|
||||||
let chats = read(
|
|
||||||
AppServerRequestHandle::Remote(remote.request_handle()),
|
|
||||||
Arc::new(live),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
chats.rows.len(),
|
|
||||||
chats.rows[0].title.as_str(),
|
|
||||||
chats.rows.last().unwrap().title.as_str(),
|
|
||||||
chats.rows.last().unwrap().usage.clone()
|
|
||||||
),
|
|
||||||
(101, "Chat 100", "Chat 35", None)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
rpc.await.unwrap(),
|
|
||||||
vec![
|
|
||||||
json!([null, 100, false, []]),
|
|
||||||
json!(["next", 100, false, []])
|
|
||||||
]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn unavailable_chat_batches_bound_requests_during_an_outage() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "enterprise_cbp_usage_based").await;
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 503))
|
|
||||||
.expect(/*r*/ 15)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let ids = (0..100).map(|i| format!("chat-{i}")).collect::<Vec<_>>();
|
|
||||||
let ids = ids.iter().map(String::as_str).collect::<Vec<_>>();
|
|
||||||
assert_eq!(
|
|
||||||
estimates(live.session().await.unwrap(), &ids)
|
|
||||||
.await
|
|
||||||
.unwrap(),
|
|
||||||
Vec::<ThreadUsage>::new()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,180 +0,0 @@
|
|||||||
//! Report navigation and bounded keyboard/mouse help for the full-screen usage view.
|
|
||||||
//! Each report retains its own reading position; help never replaces its selection or draft.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::controls::Control;
|
|
||||||
use super::sections::Section;
|
|
||||||
use crate::keymap::ListAction;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn tab_label(&self, section: Section) -> &'static str {
|
|
||||||
match section {
|
|
||||||
Section::Summary => "Overview",
|
|
||||||
Section::Usage if self.business() => "Tokens",
|
|
||||||
Section::Usage => "Usage",
|
|
||||||
Section::Credits => "Credits",
|
|
||||||
Section::Activity => "Messages",
|
|
||||||
Section::Plugins => "Plugins",
|
|
||||||
Section::Skills => "Skills",
|
|
||||||
Section::Chats => "Chats",
|
|
||||||
Section::Plan => "Plan",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each surface owns its reading position; switching surfaces never copies it.
|
|
||||||
pub(super) fn scroll_offset(&self) -> usize {
|
|
||||||
if self.show_help {
|
|
||||||
self.help_scroll
|
|
||||||
} else if self.zoomed {
|
|
||||||
self.sections[self.section].scroll_offset
|
|
||||||
} else {
|
|
||||||
self.dashboard_scroll
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn scroll_offset_mut(&mut self) -> &mut usize {
|
|
||||||
if self.show_help {
|
|
||||||
&mut self.help_scroll
|
|
||||||
} else if self.zoomed {
|
|
||||||
&mut self.sections[self.section].scroll_offset
|
|
||||||
} else {
|
|
||||||
&mut self.dashboard_scroll
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn toggle_dashboard(&mut self) {
|
|
||||||
self.zoomed = !self.zoomed;
|
|
||||||
self.follow_selection = !self.zoomed;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn select_section(&mut self, section: Section) {
|
|
||||||
if section != self.section {
|
|
||||||
self.section = section;
|
|
||||||
self.follow_selection = !self.zoomed;
|
|
||||||
self.show_help = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn chat_has_details(&self) -> bool {
|
|
||||||
let cursor = self.sections[Section::Chats].cursor;
|
|
||||||
if self.business() {
|
|
||||||
self.chats
|
|
||||||
.ready()
|
|
||||||
.and_then(|chats| chats.rows.get(cursor))
|
|
||||||
.and_then(|chat| chat.usage.as_ref())
|
|
||||||
.is_some()
|
|
||||||
} else {
|
|
||||||
self.task_rows()
|
|
||||||
.get(cursor)
|
|
||||||
.and_then(|chat| super::task_panel::available(chat))
|
|
||||||
.is_some()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn hint(&self, action: ListAction) -> String {
|
|
||||||
self.keymap
|
|
||||||
.primary_hint(action)
|
|
||||||
.map(crate::key_hint::ShortcutHint::display_label)
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn help_shortcut_available(&self) -> bool {
|
|
||||||
[
|
|
||||||
crossterm::event::KeyModifiers::NONE,
|
|
||||||
crossterm::event::KeyModifiers::SHIFT,
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.all(|modifiers| {
|
|
||||||
self.keymap
|
|
||||||
.action_for(crossterm::event::KeyEvent::new(
|
|
||||||
crossterm::event::KeyCode::Char('?'),
|
|
||||||
modifiers,
|
|
||||||
))
|
|
||||||
.is_none()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn help_lines(&self, width: usize) -> Vec<Line<'static>> {
|
|
||||||
let mut controls = vec![
|
|
||||||
format!(
|
|
||||||
"Tab / {} · next / previous report",
|
|
||||||
crate::key_hint::shift(crossterm::event::KeyCode::Tab).display_label()
|
|
||||||
),
|
|
||||||
format!(
|
|
||||||
"1–{} · open a report directly",
|
|
||||||
self.visible_sections().len()
|
|
||||||
),
|
|
||||||
format!(
|
|
||||||
"{} / {} · select chart day or plan window",
|
|
||||||
self.hint(ListAction::MoveLeft),
|
|
||||||
self.hint(ListAction::MoveRight)
|
|
||||||
),
|
|
||||||
format!(
|
|
||||||
"{} / {} · select chat or plan period; scroll Overview",
|
|
||||||
self.hint(ListAction::MoveUp),
|
|
||||||
self.hint(ListAction::MoveDown)
|
|
||||||
),
|
|
||||||
format!(
|
|
||||||
"{} · expand or collapse details",
|
|
||||||
self.hint(ListAction::Accept)
|
|
||||||
),
|
|
||||||
format!(
|
|
||||||
"{} / {} · scroll report",
|
|
||||||
self.hint(ListAction::PageUp),
|
|
||||||
self.hint(ListAction::PageDown)
|
|
||||||
),
|
|
||||||
"In alternate screen: mouse wheel · scroll; click tabs or report controls".into(),
|
|
||||||
];
|
|
||||||
if self.control_available(Control::Range) {
|
|
||||||
controls.push("r · switch between 7 and 30 days".into());
|
|
||||||
}
|
|
||||||
if self.control_available(Control::Group) {
|
|
||||||
controls.push("g · change grouping / Overview aggregation".into());
|
|
||||||
}
|
|
||||||
if self.control_available(Control::Model) {
|
|
||||||
controls.push("m · cycle model filter".into());
|
|
||||||
}
|
|
||||||
if self.control_available(Control::TaskMetric) {
|
|
||||||
controls.push("s · change chat sort metric".into());
|
|
||||||
}
|
|
||||||
if self.control_available(Control::ZeroCreditGroups) {
|
|
||||||
controls.push("a · show zero-credit groups in expanded details".into());
|
|
||||||
}
|
|
||||||
controls.extend([
|
|
||||||
"R · refresh all reports".into(),
|
|
||||||
format!(
|
|
||||||
"z · dashboard / focused report; {} · focus dashboard card",
|
|
||||||
self.hint(ListAction::Accept)
|
|
||||||
),
|
|
||||||
format!(
|
|
||||||
"{} · back; q / {} · close usage",
|
|
||||||
self.hint(ListAction::Cancel),
|
|
||||||
crate::key_hint::ctrl(crossterm::event::KeyCode::Char('c')).display_label()
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
if self.help_shortcut_available() {
|
|
||||||
controls.insert(controls.len() - 1, "? · toggle this help".into());
|
|
||||||
}
|
|
||||||
if let Some(updated) = self.sections[self.section]
|
|
||||||
.history
|
|
||||||
.ready()
|
|
||||||
.and_then(|report| report.updated_at)
|
|
||||||
.and_then(|timestamp| chrono::DateTime::from_timestamp(timestamp, /*nsecs*/ 0))
|
|
||||||
{
|
|
||||||
controls.push(format!(
|
|
||||||
"Report updated {} UTC",
|
|
||||||
updated.format(self.clock_format.date_time_format())
|
|
||||||
));
|
|
||||||
}
|
|
||||||
controls
|
|
||||||
.into_iter()
|
|
||||||
.flat_map(|line| {
|
|
||||||
textwrap::wrap(&line, width)
|
|
||||||
.into_iter()
|
|
||||||
.map(|line| Line::from(line.into_owned()))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,291 +0,0 @@
|
|||||||
//! Local account report loading with backend-owned authentication and identity checks.
|
|
||||||
//! Cached responses belong to one local account and user, independently of the connected server.
|
|
||||||
//! Every report uses the view's captured end date until refresh replaces the session.
|
|
||||||
|
|
||||||
use super::models::AccountAnalyticsGrouping as Grouping;
|
|
||||||
use super::models::AccountAnalyticsReport as Report;
|
|
||||||
use super::models::AccountKind;
|
|
||||||
use super::report_data::AnalyticsData;
|
|
||||||
use crate::legacy_core::config::Config;
|
|
||||||
use codex_backend_client::AnalyticsReport;
|
|
||||||
use codex_backend_client::AnalyticsSession;
|
|
||||||
use codex_backend_client::RequestError;
|
|
||||||
use codex_features::Feature;
|
|
||||||
use codex_protocol::account::PlanType;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use tokio::sync::Mutex;
|
|
||||||
use tokio::sync::OnceCell;
|
|
||||||
|
|
||||||
pub(super) struct Live {
|
|
||||||
pub(super) identity_invalidated: std::sync::atomic::AtomicBool,
|
|
||||||
config: Arc<Config>,
|
|
||||||
end_date: chrono::NaiveDate,
|
|
||||||
session: OnceCell<Session>,
|
|
||||||
token_models: std::sync::RwLock<Vec<String>>,
|
|
||||||
attributed_usage: std::sync::atomic::AtomicBool,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) struct Session {
|
|
||||||
pub(super) kind: AccountKind,
|
|
||||||
pub(super) backend: AnalyticsSession,
|
|
||||||
credit_groups: Vec<usize>,
|
|
||||||
cache: Mutex<HashMap<(AnalyticsReport, String, String), AnalyticsData>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Live {
|
|
||||||
pub(super) fn new(config: Arc<Config>, end_date: chrono::NaiveDate) -> Self {
|
|
||||||
Self {
|
|
||||||
identity_invalidated: std::sync::atomic::AtomicBool::new(/*v*/ false),
|
|
||||||
config,
|
|
||||||
end_date,
|
|
||||||
session: OnceCell::new(),
|
|
||||||
token_models: std::sync::RwLock::new(Vec::new()),
|
|
||||||
attributed_usage: std::sync::atomic::AtomicBool::new(/*v*/ true),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn account_label(&self) -> Option<String> {
|
|
||||||
let session = self.session.get()?;
|
|
||||||
session.backend.account().email.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn credit_groups(&self) -> &[usize] {
|
|
||||||
self.session
|
|
||||||
.get()
|
|
||||||
.map_or(&[0], |session| &session.credit_groups)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn attributed_usage(&self) -> bool {
|
|
||||||
self.attributed_usage
|
|
||||||
.load(std::sync::atomic::Ordering::Relaxed)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn token_models(&self) -> Vec<String> {
|
|
||||||
self.token_models
|
|
||||||
.read()
|
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
|
||||||
.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn session(&self) -> Result<&Session, String> {
|
|
||||||
self.session
|
|
||||||
.get_or_try_init(|| async {
|
|
||||||
let session = AnalyticsSession::from_config(
|
|
||||||
self.config.as_ref(),
|
|
||||||
self.config.http_client_factory(),
|
|
||||||
self.config
|
|
||||||
.features
|
|
||||||
.enabled(Feature::RuntimeAgentInstances)
|
|
||||||
.then_some(self.config.runtime_auth_mode),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let credit_groups = Grouping::credit_groupings(session.account().plan_type)
|
|
||||||
.iter()
|
|
||||||
.filter_map(|group| {
|
|
||||||
super::data::GROUPINGS
|
|
||||||
.iter()
|
|
||||||
.position(|candidate| candidate == group)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
Ok(Session {
|
|
||||||
kind: AccountKind::from(session.account().plan_type),
|
|
||||||
credit_groups,
|
|
||||||
backend: session,
|
|
||||||
cache: Mutex::new(HashMap::new()),
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every report shares the same privacy boundary, including cached report loads.
|
|
||||||
pub(super) async fn ensure_identity(&self) -> Result<(), String> {
|
|
||||||
let identity = match self.session().await {
|
|
||||||
Ok(session) => session.backend.ensure_identity().await,
|
|
||||||
Err(error) => Err(error),
|
|
||||||
};
|
|
||||||
if identity.is_err() {
|
|
||||||
self.identity_invalidated
|
|
||||||
.store(/*val*/ true, std::sync::atomic::Ordering::Relaxed);
|
|
||||||
}
|
|
||||||
identity
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn plan_history(&self) -> Result<Option<super::plan::Report>, String> {
|
|
||||||
let session = self.session().await?;
|
|
||||||
if session.kind != AccountKind::Consumer {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
let history = session
|
|
||||||
.backend
|
|
||||||
.request(|client| async move { client.get_plan_limit_history().await })
|
|
||||||
.await;
|
|
||||||
self.ensure_identity().await?;
|
|
||||||
history
|
|
||||||
.map_err(request_error)?
|
|
||||||
.map(super::plan::Report::parse)
|
|
||||||
.transpose()
|
|
||||||
.map(Option::flatten)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn history(
|
|
||||||
&self,
|
|
||||||
report: Report,
|
|
||||||
days: u32,
|
|
||||||
grouping: Grouping,
|
|
||||||
) -> Result<Option<super::models::AccountAnalyticsHistory>, String> {
|
|
||||||
self.filtered_history(report, days, grouping, /*model_filter*/ None)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn filtered_history(
|
|
||||||
&self,
|
|
||||||
report: Report,
|
|
||||||
days: u32,
|
|
||||||
grouping: Grouping,
|
|
||||||
model_filter: Option<&str>,
|
|
||||||
) -> Result<Option<super::models::AccountAnalyticsHistory>, String> {
|
|
||||||
let end = self.end_date;
|
|
||||||
let start = days
|
|
||||||
.checked_sub(/*rhs*/ 1)
|
|
||||||
.and_then(|offset| end.checked_sub_days(chrono::Days::new(u64::from(offset))))
|
|
||||||
.ok_or("Invalid analytics date range.")?;
|
|
||||||
let session = self.session().await?;
|
|
||||||
self.ensure_identity().await?;
|
|
||||||
let enterprise_tokens = report == Report::Usage
|
|
||||||
&& matches!(
|
|
||||||
session.kind,
|
|
||||||
AccountKind::Enterprise | AccountKind::Business
|
|
||||||
);
|
|
||||||
let grouping =
|
|
||||||
if enterprise_tokens && !matches!(grouping, Grouping::Model | Grouping::TokenType) {
|
|
||||||
Grouping::TokenType
|
|
||||||
} else {
|
|
||||||
grouping
|
|
||||||
};
|
|
||||||
let route =
|
|
||||||
route(report, grouping, session.backend.account().plan_type).ok_or_else(|| {
|
|
||||||
"This credit breakdown is not supported for this account type.".to_string()
|
|
||||||
})?;
|
|
||||||
// Credit events have no range parameters. Other grouping changes reuse the same payload.
|
|
||||||
let key = if route == AnalyticsReport::Credits {
|
|
||||||
(route, String::new(), String::new())
|
|
||||||
} else {
|
|
||||||
(route, start.to_string(), end.to_string())
|
|
||||||
};
|
|
||||||
let cached = session.cache.lock().await.get(&key).cloned();
|
|
||||||
let response = if let Some(response) = cached {
|
|
||||||
Ok(response)
|
|
||||||
} else {
|
|
||||||
session
|
|
||||||
.backend
|
|
||||||
.request(|client| {
|
|
||||||
let (_, start, end) = key.clone();
|
|
||||||
async move { client.get_account_analytics(route, &start, &end).await }
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map(AnalyticsData::from)
|
|
||||||
};
|
|
||||||
self.ensure_identity().await?;
|
|
||||||
let response = response.map_err(request_error)?;
|
|
||||||
let history = (|| {
|
|
||||||
if enterprise_tokens {
|
|
||||||
let models = super::tokens::history(response.clone(), Grouping::Model, start, end)?;
|
|
||||||
*self
|
|
||||||
.token_models
|
|
||||||
.write()
|
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner) =
|
|
||||||
super::render::categories(&models)
|
|
||||||
.into_iter()
|
|
||||||
.map(|model| model.key)
|
|
||||||
.collect();
|
|
||||||
super::tokens::filtered_history(
|
|
||||||
response.clone(),
|
|
||||||
grouping,
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
model_filter,
|
|
||||||
)
|
|
||||||
.map(Some)
|
|
||||||
} else {
|
|
||||||
let grouping = if report == Report::Usage {
|
|
||||||
let attributed =
|
|
||||||
super::normalize::has_complete_attribution(&response, start, end)?;
|
|
||||||
self.attributed_usage
|
|
||||||
.store(attributed, std::sync::atomic::Ordering::Relaxed);
|
|
||||||
if !attributed && matches!(grouping, Grouping::Feature | Grouping::TaskStart) {
|
|
||||||
Grouping::Surface
|
|
||||||
} else {
|
|
||||||
grouping
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
grouping
|
|
||||||
};
|
|
||||||
super::normalize::history(response.clone(), report, grouping, start, end)
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
let mut cache = session.cache.lock().await;
|
|
||||||
if history.is_ok() {
|
|
||||||
cache.insert(key, response);
|
|
||||||
} else {
|
|
||||||
cache.remove(&key);
|
|
||||||
}
|
|
||||||
history
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Account type selects billing semantics, never activity-report eligibility.
|
|
||||||
fn route(report: Report, grouping: Grouping, plan: Option<PlanType>) -> Option<AnalyticsReport> {
|
|
||||||
let kind = AccountKind::from(plan);
|
|
||||||
let enterprise = kind == AccountKind::Enterprise;
|
|
||||||
Some(match report {
|
|
||||||
Report::Usage if enterprise => AnalyticsReport::EnterpriseTokens,
|
|
||||||
Report::Usage if kind == AccountKind::Business => AnalyticsReport::WorkspaceCredits,
|
|
||||||
Report::Usage => AnalyticsReport::Usage,
|
|
||||||
Report::Messages => AnalyticsReport::Messages,
|
|
||||||
Report::Credits if !Grouping::credit_groupings(plan).contains(&grouping) => return None,
|
|
||||||
Report::Credits if enterprise => AnalyticsReport::EnterpriseCredits {
|
|
||||||
breakdown: match grouping {
|
|
||||||
Grouping::Surface => "product",
|
|
||||||
Grouping::Model => "model",
|
|
||||||
Grouping::Speed => "speed",
|
|
||||||
Grouping::Reasoning => "reasoning_effort",
|
|
||||||
Grouping::Feature | Grouping::TaskStart | Grouping::TokenType => return None,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Report::Credits if kind == AccountKind::Business => AnalyticsReport::WorkspaceCredits,
|
|
||||||
Report::Credits => AnalyticsReport::Credits,
|
|
||||||
Report::Plugins => AnalyticsReport::Plugins {
|
|
||||||
limit: if enterprise { 8 } else { 10 },
|
|
||||||
},
|
|
||||||
Report::Skills => AnalyticsReport::Skills {
|
|
||||||
limit: if enterprise { 6 } else { 10 },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn request_error(error: RequestError) -> String {
|
|
||||||
match error.status().map(|status| status.as_u16()) {
|
|
||||||
Some(401) => "Sign in again to load this report.",
|
|
||||||
Some(403) => "Access denied for this report.",
|
|
||||||
Some(404) => "This report endpoint is unavailable. Press R to retry.",
|
|
||||||
_ => "Report request failed. Press R to retry.",
|
|
||||||
}
|
|
||||||
.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "client_tests.rs"]
|
|
||||||
pub(super) mod tests;
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "connection_tests.rs"]
|
|
||||||
mod connection_tests;
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "account_plan_tests.rs"]
|
|
||||||
mod account_plan_tests;
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "runtime_auth_tests.rs"]
|
|
||||||
mod runtime_auth_tests;
|
|
||||||
@@ -1,858 +0,0 @@
|
|||||||
//! Account-scoped authentication and request identity regression coverage.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
use crate::legacy_core::config::ConfigBuilder;
|
|
||||||
use base64::Engine;
|
|
||||||
use codex_config::LoaderOverrides;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::MockServer;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::header;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
|
|
||||||
pub(in crate::analytics) fn sign_in(home: &std::path::Path, account: &str, user: &str, plan: &str) {
|
|
||||||
let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(
|
|
||||||
json!({
|
|
||||||
"exp": 4102444800_i64, "email": "analytics@example.test",
|
|
||||||
"https://api.openai.com/auth": {
|
|
||||||
"chatgpt_account_id": account, "chatgpt_user_id": user, "chatgpt_plan_type": plan,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.to_string(),
|
|
||||||
);
|
|
||||||
let token = format!("e30.{claims}.test");
|
|
||||||
let auth = serde_json::from_value(json!({
|
|
||||||
"auth_mode": "chatgpt", "tokens": {"id_token": token, "access_token": token,
|
|
||||||
"refresh_token": "test-refresh", "account_id": account},
|
|
||||||
"last_refresh": chrono::Utc::now(),
|
|
||||||
}))
|
|
||||||
.unwrap();
|
|
||||||
codex_login::save_auth(
|
|
||||||
home,
|
|
||||||
&auth,
|
|
||||||
codex_login::AuthCredentialsStoreMode::File,
|
|
||||||
codex_login::AuthKeyringBackendKind::default(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(in crate::analytics) async fn live(
|
|
||||||
server: &MockServer,
|
|
||||||
plan: &str,
|
|
||||||
) -> (tempfile::TempDir, Live) {
|
|
||||||
let home = tempfile::tempdir().unwrap();
|
|
||||||
let mut config = ConfigBuilder::default()
|
|
||||||
.codex_home(home.path().to_path_buf())
|
|
||||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
|
||||||
.build()
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
|
|
||||||
config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File;
|
|
||||||
sign_in(home.path(), "account-a", "user-a", plan);
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/backend-api/wham/accounts/check"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
|
||||||
"accounts": [{"id": "account-a", "plan_type": plan}],
|
|
||||||
"account_ordering": ["account-a"]
|
|
||||||
})))
|
|
||||||
.with_priority(/*p*/ 2)
|
|
||||||
.mount(server)
|
|
||||||
.await;
|
|
||||||
(
|
|
||||||
home,
|
|
||||||
Live::new(Arc::new(config), "2026-01-15".parse().unwrap()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn report_requests(server: &MockServer) -> Vec<wiremock::Request> {
|
|
||||||
server
|
|
||||||
.received_requests()
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.into_iter()
|
|
||||||
.filter(|request| request.url.path() != "/backend-api/wham/accounts/check")
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_rejects_identity_changes_during_requests() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (home, live) = live(&server, "business").await;
|
|
||||||
let session = live.session().await.unwrap();
|
|
||||||
let authenticated = &session.backend;
|
|
||||||
let result = authenticated
|
|
||||||
.request(|_| async {
|
|
||||||
sign_in(home.path(), "account-b", "user-a", "business");
|
|
||||||
Ok(123)
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert_eq!(
|
|
||||||
result.unwrap_err().to_string(),
|
|
||||||
"Account changed. Press R to refresh Analytics."
|
|
||||||
);
|
|
||||||
assert!(report_requests(&server).await.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_rejects_account_and_user_changes_before_requests() {
|
|
||||||
for (account, user) in [("account-b", "user-a"), ("account-a", "user-b")] {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (home, live) = live(&server, "plus").await;
|
|
||||||
let session = live.session().await.unwrap();
|
|
||||||
let authenticated = &session.backend;
|
|
||||||
sign_in(home.path(), account, user, "plus");
|
|
||||||
let requested = std::cell::Cell::new(/*value*/ false);
|
|
||||||
let result = authenticated
|
|
||||||
.request(|_| async {
|
|
||||||
requested.set(/*val*/ true);
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert!(!requested.get());
|
|
||||||
assert_eq!(
|
|
||||||
result.unwrap_err().to_string(),
|
|
||||||
"Account changed. Press R to refresh Analytics."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_requires_local_chatgpt_authentication() {
|
|
||||||
for auth in [None, Some(json!({"OPENAI_API_KEY": "sk-test-only"}))] {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (home, live) = live(&server, "plus").await;
|
|
||||||
let path = home.path().join("auth.json");
|
|
||||||
match auth {
|
|
||||||
Some(auth) => std::fs::write(path, serde_json::to_vec(&auth).unwrap()).unwrap(),
|
|
||||||
None => std::fs::remove_file(path).unwrap(),
|
|
||||||
}
|
|
||||||
assert_eq!(
|
|
||||||
live.session().await.err(),
|
|
||||||
Some("Sign in locally with ChatGPT to view Analytics.".to_string())
|
|
||||||
);
|
|
||||||
assert!(report_requests(&server).await.is_empty());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_requests_use_reloaded_credentials_for_the_same_identity() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (home, live) = live(&server, "plus").await;
|
|
||||||
let session = live.session().await.unwrap();
|
|
||||||
let authenticated = &session.backend;
|
|
||||||
assert_eq!(
|
|
||||||
live.account_label().as_deref(),
|
|
||||||
Some("analytics@example.test")
|
|
||||||
);
|
|
||||||
let auth_path = home.path().join("auth.json");
|
|
||||||
let mut auth: serde_json::Value =
|
|
||||||
serde_json::from_slice(&std::fs::read(&auth_path).unwrap()).unwrap();
|
|
||||||
auth["tokens"]["access_token"] = json!("refreshed-access-token");
|
|
||||||
std::fs::write(auth_path, serde_json::to_vec(&auth).unwrap()).unwrap();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/backend-api/wham/usage/daily-token-usage-breakdown"))
|
|
||||||
.and(header("chatgpt-account-id", "account-a"))
|
|
||||||
.and(header("authorization", "Bearer refreshed-access-token"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": []})))
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let result = authenticated
|
|
||||||
.request(|client| async move {
|
|
||||||
client
|
|
||||||
.get_account_analytics(
|
|
||||||
codex_backend_client::AnalyticsReport::Usage,
|
|
||||||
"2026-09-01",
|
|
||||||
"2026-09-07",
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
result,
|
|
||||||
codex_backend_client::AnalyticsResponse::Usage(
|
|
||||||
codex_backend_client::analytics_models::DailyProductSurfaceUsageResponse::default()
|
|
||||||
)
|
|
||||||
);
|
|
||||||
server.verify().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_retries_unauthorized_requests_after_credentials_reload() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (home, live) = live(&server, "plus").await;
|
|
||||||
let session = live.session().await.unwrap();
|
|
||||||
let authenticated = &session.backend;
|
|
||||||
let auth_path = home.path().join("auth.json");
|
|
||||||
let mut auth: serde_json::Value =
|
|
||||||
serde_json::from_slice(&std::fs::read(&auth_path).unwrap()).unwrap();
|
|
||||||
let original_token = auth["tokens"]["access_token"].as_str().unwrap().to_owned();
|
|
||||||
auth["tokens"]["access_token"] = json!("recovered-access-token");
|
|
||||||
let updated_auth = serde_json::to_vec(&auth).unwrap();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(header("authorization", format!("Bearer {original_token}")))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
std::fs::write(&auth_path, &updated_auth).unwrap();
|
|
||||||
ResponseTemplate::new(/*s*/ 401)
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(header("authorization", "Bearer recovered-access-token"))
|
|
||||||
.and(header("chatgpt-account-id", "account-a"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": []})))
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let result = authenticated
|
|
||||||
.request(|client| async move {
|
|
||||||
client
|
|
||||||
.get_account_analytics(
|
|
||||||
codex_backend_client::AnalyticsReport::Usage,
|
|
||||||
"2026-09-01",
|
|
||||||
"2026-09-07",
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
result,
|
|
||||||
codex_backend_client::AnalyticsResponse::Usage(
|
|
||||||
codex_backend_client::analytics_models::DailyProductSurfaceUsageResponse::default()
|
|
||||||
)
|
|
||||||
);
|
|
||||||
server.verify().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_retries_session_initialization_after_sign_in() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (home, live) = live(&server, "plus").await;
|
|
||||||
std::fs::remove_file(home.path().join("auth.json")).unwrap();
|
|
||||||
assert!(live.session().await.is_err());
|
|
||||||
sign_in(home.path(), "account-a", "user-a", "plus");
|
|
||||||
assert_eq!(
|
|
||||||
live.session().await.unwrap().backend.account().id,
|
|
||||||
"account-a"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_matches_app_account_routes_and_parameters() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
for (plan, report, grouping, endpoint, extra) in [
|
|
||||||
(
|
|
||||||
"plus",
|
|
||||||
Report::Usage,
|
|
||||||
Grouping::Model,
|
|
||||||
"usage/daily-token-usage-breakdown",
|
|
||||||
vec![("group_by", "day")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"business",
|
|
||||||
Report::Usage,
|
|
||||||
Grouping::TokenType,
|
|
||||||
"usage/daily-workspace-user-token-usage-breakdown",
|
|
||||||
vec![
|
|
||||||
("group_by", "day"),
|
|
||||||
("breakdown_by", "model"),
|
|
||||||
("modes", "codex"),
|
|
||||||
("modes", "work"),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"business",
|
|
||||||
Report::Messages,
|
|
||||||
Grouping::Model,
|
|
||||||
"analytics/daily-workspace-usage-counts",
|
|
||||||
vec![("group_by", "day"), ("workspace_user", "true")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"unknown",
|
|
||||||
Report::Usage,
|
|
||||||
Grouping::Surface,
|
|
||||||
"usage/daily-token-usage-breakdown",
|
|
||||||
vec![("group_by", "day")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"unknown",
|
|
||||||
Report::Messages,
|
|
||||||
Grouping::Model,
|
|
||||||
"analytics/daily-workspace-usage-counts",
|
|
||||||
vec![("group_by", "day"), ("workspace_user", "true")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"unknown",
|
|
||||||
Report::Plugins,
|
|
||||||
Grouping::Feature,
|
|
||||||
"analytics/daily-plugin-usage-metrics",
|
|
||||||
vec![
|
|
||||||
("group_by", "day"),
|
|
||||||
("workspace_user", "true"),
|
|
||||||
("top_plugin_limit", "10"),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"unknown",
|
|
||||||
Report::Skills,
|
|
||||||
Grouping::Feature,
|
|
||||||
"analytics/daily-skill-usage-metrics",
|
|
||||||
vec![
|
|
||||||
("group_by", "day"),
|
|
||||||
("workspace_user", "true"),
|
|
||||||
("top_skill_limit", "10"),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"edu",
|
|
||||||
Report::Credits,
|
|
||||||
Grouping::Model,
|
|
||||||
"usage/daily-workspace-user-credit-usage",
|
|
||||||
vec![("breakdown", "model")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"plus",
|
|
||||||
Report::Credits,
|
|
||||||
Grouping::Surface,
|
|
||||||
"usage/credit-usage-events",
|
|
||||||
vec![],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"team",
|
|
||||||
Report::Usage,
|
|
||||||
Grouping::Model,
|
|
||||||
"usage/daily-workspace-user-token-usage-breakdown",
|
|
||||||
vec![("group_by", "day")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"sci_plus",
|
|
||||||
Report::Usage,
|
|
||||||
Grouping::Model,
|
|
||||||
"usage/daily-workspace-user-token-usage-breakdown",
|
|
||||||
vec![("group_by", "day")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"team",
|
|
||||||
Report::Credits,
|
|
||||||
Grouping::Speed,
|
|
||||||
"usage/daily-workspace-user-token-usage-breakdown",
|
|
||||||
vec![("group_by", "day")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"business",
|
|
||||||
Report::Credits,
|
|
||||||
Grouping::Reasoning,
|
|
||||||
"usage/daily-workspace-user-credit-usage",
|
|
||||||
vec![("breakdown", "reasoning_effort")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"plus",
|
|
||||||
Report::Messages,
|
|
||||||
Grouping::Model,
|
|
||||||
"analytics/daily-workspace-usage-counts",
|
|
||||||
vec![("group_by", "day"), ("workspace_user", "true")],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"plus",
|
|
||||||
Report::Plugins,
|
|
||||||
Grouping::Feature,
|
|
||||||
"analytics/daily-plugin-usage-metrics",
|
|
||||||
vec![
|
|
||||||
("group_by", "day"),
|
|
||||||
("workspace_user", "true"),
|
|
||||||
("top_plugin_limit", "10"),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"business",
|
|
||||||
Report::Plugins,
|
|
||||||
Grouping::Feature,
|
|
||||||
"analytics/daily-plugin-usage-metrics",
|
|
||||||
vec![
|
|
||||||
("group_by", "day"),
|
|
||||||
("workspace_user", "true"),
|
|
||||||
("top_plugin_limit", "8"),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"business",
|
|
||||||
Report::Skills,
|
|
||||||
Grouping::Feature,
|
|
||||||
"analytics/daily-skill-usage-metrics",
|
|
||||||
vec![
|
|
||||||
("group_by", "day"),
|
|
||||||
("workspace_user", "true"),
|
|
||||||
("top_skill_limit", "6"),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
server.reset().await;
|
|
||||||
let (_home, live) = live(&server, plan).await;
|
|
||||||
let today = live.end_date;
|
|
||||||
let start = (today - chrono::Days::new(/*num*/ 6)).to_string();
|
|
||||||
let response = if endpoint == "usage/daily-workspace-user-credit-usage" {
|
|
||||||
let breakdown = extra.iter().find(|(key, _)| *key == "breakdown").unwrap().1;
|
|
||||||
json!({"data": [], "series": [], "breakdown": breakdown})
|
|
||||||
} else {
|
|
||||||
json!({"data": []})
|
|
||||||
};
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path(format!("/backend-api/wham/{endpoint}")))
|
|
||||||
.and(header("chatgpt-account-id", "account-a"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(response))
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
assert!(
|
|
||||||
live.history(report, /*days*/ 7, grouping)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.is_some()
|
|
||||||
);
|
|
||||||
let requests = report_requests(&server).await;
|
|
||||||
let mut actual = requests[0]
|
|
||||||
.url
|
|
||||||
.query_pairs()
|
|
||||||
.map(|(key, value)| (key.into_owned(), value.into_owned()))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let mut expected = extra
|
|
||||||
.into_iter()
|
|
||||||
.map(|(key, value)| (key.to_string(), value.to_string()))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
if endpoint != "usage/credit-usage-events" {
|
|
||||||
expected.push(("start_date".into(), start.clone()));
|
|
||||||
expected.push(("end_date".into(), today.to_string()));
|
|
||||||
}
|
|
||||||
actual.sort();
|
|
||||||
expected.sort();
|
|
||||||
assert_eq!(actual, expected);
|
|
||||||
assert!(requests[0].headers.get("authorization").is_some());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_uses_api_response_for_usage_and_turns_availability() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
for report in [Report::Usage, Report::Messages] {
|
|
||||||
for status in [403, 404] {
|
|
||||||
server.reset().await;
|
|
||||||
let (_home, live) = live(&server, "business").await;
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.respond_with(ResponseTemplate::new(status))
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
assert_eq!(
|
|
||||||
live.history(report, /*days*/ 7, Grouping::Surface)
|
|
||||||
.await
|
|
||||||
.unwrap_err(),
|
|
||||||
if status == 403 {
|
|
||||||
"Access denied for this report."
|
|
||||||
} else {
|
|
||||||
"This report endpoint is unavailable. Press R to retry."
|
|
||||||
}
|
|
||||||
);
|
|
||||||
server.verify().await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_reuses_payload_for_grouping_and_rejects_account_changes() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (home, live) = live(&server, "team").await;
|
|
||||||
let today = live.end_date.to_string();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path(
|
|
||||||
"/backend-api/wham/usage/daily-workspace-user-token-usage-breakdown",
|
|
||||||
))
|
|
||||||
.respond_with(
|
|
||||||
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": [{
|
|
||||||
"date": today, "product_surface_usage_values": {}, "premium_usage_values": {
|
|
||||||
"credit_usage_credits": {"cli": 12.5}, "total_usage_credits": {},
|
|
||||||
"uncached_text_input_tokens_by_surface": {}, "cached_text_input_tokens_by_surface": {},
|
|
||||||
"text_output_tokens_by_surface": {}, "text_total_tokens_by_surface": {}
|
|
||||||
},
|
|
||||||
"models": [{"model": "model-a", "credits": 12.5, "speed": "fast", "on_demand_credits": 12.5}]
|
|
||||||
}]})),
|
|
||||||
)
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let surface = live
|
|
||||||
.history(Report::Credits, /*days*/ 7, Grouping::Surface)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
let model = live
|
|
||||||
.history(Report::Credits, /*days*/ 7, Grouping::Model)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
surface.data.last().unwrap().total,
|
|
||||||
model.data.last().unwrap().total
|
|
||||||
),
|
|
||||||
(12.5, 12.5)
|
|
||||||
);
|
|
||||||
sign_in(home.path(), "account-a", "user-b", "team");
|
|
||||||
assert_eq!(
|
|
||||||
live.history(Report::Credits, /*days*/ 7, Grouping::Model)
|
|
||||||
.await
|
|
||||||
.unwrap_err(),
|
|
||||||
"Account changed. Press R to refresh Analytics."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn token_model_filter_reuses_the_account_scoped_response() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "business").await;
|
|
||||||
let today = live.end_date.to_string();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/backend-api/wham/usage/daily-workspace-user-token-usage-breakdown"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data":[{
|
|
||||||
"date":today, "product_surface_usage_values": {}, "groups":[
|
|
||||||
{"dimensions":{"model":"alpha"}, "credits": 0, "uncached_text_input_tokens":10,"cached_text_input_tokens":20,"text_output_tokens":30},
|
|
||||||
{"dimensions":{"model":"beta"}, "credits": 0, "uncached_text_input_tokens":100,"cached_text_input_tokens":200,"text_output_tokens":300}
|
|
||||||
]
|
|
||||||
}]})))
|
|
||||||
.expect(/*r*/ 1).mount(&server).await;
|
|
||||||
let all = live
|
|
||||||
.history(Report::Usage, /*days*/ 7, Grouping::TokenType)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
let alpha = live
|
|
||||||
.filtered_history(
|
|
||||||
Report::Usage,
|
|
||||||
/*days*/ 7,
|
|
||||||
Grouping::TokenType,
|
|
||||||
Some("alpha"),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
let beta = live
|
|
||||||
.filtered_history(
|
|
||||||
Report::Usage,
|
|
||||||
/*days*/ 7,
|
|
||||||
Grouping::TokenType,
|
|
||||||
Some("beta"),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(all.data[0].total, alpha.data[0].total, beta.data[0].total),
|
|
||||||
(660.0, 60.0, 600.0)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
live.token_models(),
|
|
||||||
vec!["beta".to_string(), "alpha".to_string()]
|
|
||||||
);
|
|
||||||
assert_eq!(report_requests(&server).await.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn legacy_usage_falls_back_to_surface_for_attribution_only_groupings() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "plus").await;
|
|
||||||
let today = live.end_date.to_string();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.respond_with(
|
|
||||||
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": [{
|
|
||||||
"date": today, "product_surface_usage_values": {"cli": 12.5}
|
|
||||||
}]})),
|
|
||||||
)
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let surface = live
|
|
||||||
.history(Report::Usage, /*days*/ 7, Grouping::Surface)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
for grouping in [Grouping::Feature, Grouping::TaskStart] {
|
|
||||||
let history = live
|
|
||||||
.history(Report::Usage, /*days*/ 7, grouping)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!((live.attributed_usage(), history), (false, surface.clone()));
|
|
||||||
}
|
|
||||||
server.verify().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn invalid_ranges_fail_without_requesting_reports() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "plus").await;
|
|
||||||
for days in [0, u32::MAX] {
|
|
||||||
assert_eq!(
|
|
||||||
live.history(Report::Usage, days, Grouping::Surface)
|
|
||||||
.await
|
|
||||||
.unwrap_err(),
|
|
||||||
"Invalid analytics date range."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert!(report_requests(&server).await.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn unknown_plan_exposes_no_credit_breakdowns() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "unknown").await;
|
|
||||||
live.session().await.unwrap();
|
|
||||||
assert!(live.credit_groups().is_empty());
|
|
||||||
assert!(
|
|
||||||
live.history(Report::Credits, /*days*/ 7, Grouping::Surface)
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
assert!(report_requests(&server).await.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn in_flight_account_switch_retains_refresh_guidance() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (home, live) = live(&server, "plus").await;
|
|
||||||
let home_path = home.path().to_path_buf();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
sign_in(&home_path, "account-b", "user-a", "plus");
|
|
||||||
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": []}))
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
assert_eq!(
|
|
||||||
live.history(Report::Usage, /*days*/ 7, Grouping::Surface)
|
|
||||||
.await
|
|
||||||
.unwrap_err(),
|
|
||||||
"Account changed. Press R to refresh Analytics."
|
|
||||||
);
|
|
||||||
server.verify().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn missing_breakdowns_remain_unavailable() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "plus").await;
|
|
||||||
let today = live.end_date.to_string();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.respond_with(
|
|
||||||
ResponseTemplate::new(/*s*/ 200).set_body_json(
|
|
||||||
json!({"data": [{"date": today, "product_surface_usage_values": {}}]}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
assert_eq!(
|
|
||||||
live.history(Report::Usage, /*days*/ 7, Grouping::Model)
|
|
||||||
.await,
|
|
||||||
Ok(None)
|
|
||||||
);
|
|
||||||
server.verify().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn out_of_range_legacy_rows_do_not_disable_attribution() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "plus").await;
|
|
||||||
let today = live.end_date.to_string();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.respond_with(
|
|
||||||
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": [
|
|
||||||
{"date": "2000-01-01", "product_surface_usage_values": {}},
|
|
||||||
{"date": today, "product_surface_usage_values": {}, "attribution": [{"thread_source": "user", "turn_trigger": "composer", "model": "example", "surface": "cli", "value": 12.0}]}
|
|
||||||
]})),
|
|
||||||
)
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let history = live
|
|
||||||
.history(Report::Usage, /*days*/ 7, Grouping::Feature)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history.data,
|
|
||||||
vec![super::super::models::AccountAnalyticsDay {
|
|
||||||
date: live.end_date,
|
|
||||||
total: 12.0,
|
|
||||||
values: vec![super::super::models::AccountAnalyticsValue {
|
|
||||||
key: "user".into(),
|
|
||||||
label: "Tasks".into(),
|
|
||||||
value: 12.0,
|
|
||||||
}],
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
assert!(live.attributed_usage());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn invalid_reports_can_retry_without_recreating_the_session() {
|
|
||||||
for plan in ["plus", "business"] {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, plan).await;
|
|
||||||
let requests = Arc::new(std::sync::atomic::AtomicUsize::new(/*v*/ 0));
|
|
||||||
let count = Arc::clone(&requests);
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
let body = if count.fetch_add(/*val*/ 1, std::sync::atomic::Ordering::SeqCst) == 0 {
|
|
||||||
json!({"data": [{"date": "invalid"}]})
|
|
||||||
} else {
|
|
||||||
json!({"data": []})
|
|
||||||
};
|
|
||||||
ResponseTemplate::new(/*s*/ 200).set_body_json(body)
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 2)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
assert!(
|
|
||||||
live.history(Report::Usage, /*days*/ 7, Grouping::Surface)
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
live.history(Report::Usage, /*days*/ 7, Grouping::Surface)
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
);
|
|
||||||
assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 2);
|
|
||||||
server.verify().await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn invalid_cached_breakdowns_are_evicted_before_retry() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "plus").await;
|
|
||||||
let today = live.end_date.to_string();
|
|
||||||
let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(/*v*/ 0));
|
|
||||||
let count = Arc::clone(&attempts);
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
let model = if count.fetch_add(/*val*/ 1, std::sync::atomic::Ordering::SeqCst) == 0 {
|
|
||||||
json!({"model": "alpha", "credits": -1})
|
|
||||||
} else {
|
|
||||||
json!({"model": "alpha", "credits": 12})
|
|
||||||
};
|
|
||||||
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": [{
|
|
||||||
"date": today, "product_surface_usage_values": {"cli": 12}, "models": [model]
|
|
||||||
}]}))
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 2)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
live.history(Report::Usage, /*days*/ 7, Grouping::Surface)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert!(
|
|
||||||
live.history(Report::Usage, /*days*/ 7, Grouping::Model)
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
live.history(Report::Usage, /*days*/ 7, Grouping::Model)
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.is_some()
|
|
||||||
);
|
|
||||||
assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 2);
|
|
||||||
server.verify().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(in crate::analytics) async fn connected_view(
|
|
||||||
server: &MockServer,
|
|
||||||
plan: &str,
|
|
||||||
) -> (
|
|
||||||
tempfile::TempDir,
|
|
||||||
crate::AppServerSession,
|
|
||||||
crate::analytics::AnalyticsView,
|
|
||||||
) {
|
|
||||||
let (home, live) = live(server, plan).await;
|
|
||||||
let config = Arc::clone(&live.config);
|
|
||||||
let app_server = crate::start_embedded_app_server_for_picker(&config)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let mut view =
|
|
||||||
crate::analytics::AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list);
|
|
||||||
view.open(
|
|
||||||
app_server.request_handle(),
|
|
||||||
crate::tui::FrameRequester::test_dummy(),
|
|
||||||
Vec::new(),
|
|
||||||
config,
|
|
||||||
);
|
|
||||||
(home, app_server, view)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn live_account_identity_is_visible_and_closing_aborts_pending_loads() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (_home, live) = live(&server, "plus").await;
|
|
||||||
live.session().await.unwrap();
|
|
||||||
let mut view =
|
|
||||||
crate::analytics::AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list);
|
|
||||||
view.live = Some(Arc::new(live));
|
|
||||||
view.sections[Section::Usage].history =
|
|
||||||
super::super::data::Load::Error("Couldn't load usage. Press R to retry.".into());
|
|
||||||
let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(
|
|
||||||
/*width*/ 100, /*height*/ 24,
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
terminal
|
|
||||||
.draw(|frame| view.render(frame.area(), frame.buffer_mut()))
|
|
||||||
.unwrap();
|
|
||||||
insta::assert_snapshot!(terminal.backend().to_string());
|
|
||||||
let (draw_tx, _) = tokio::sync::broadcast::channel(/*capacity*/ 1);
|
|
||||||
let (cancelled_tx, cancelled_rx) = tokio::sync::oneshot::channel::<()>();
|
|
||||||
view.sections[Section::Usage].history = super::super::data::Load::start(
|
|
||||||
async move {
|
|
||||||
let _cancelled = cancelled_tx;
|
|
||||||
std::future::pending().await
|
|
||||||
},
|
|
||||||
crate::tui::FrameRequester::new(draw_tx),
|
|
||||||
);
|
|
||||||
view.cancel_loads();
|
|
||||||
assert!(cancelled_rx.await.is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn plan_history_rejects_account_change_during_response() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
for status in [200, 404, 503] {
|
|
||||||
server.reset().await;
|
|
||||||
let (home, live) = live(&server, "plus").await;
|
|
||||||
let home_path = home.path().to_path_buf();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/backend-api/wham/usage/plan_limit_history"))
|
|
||||||
.and(header("chatgpt-account-id", "account-a"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
sign_in(&home_path, "account-a", "user-b", "plus");
|
|
||||||
ResponseTemplate::new(status).set_body_json(json!({
|
|
||||||
"data_as_of":"2026-09-02T00:00:00Z", "coverage_start":null,
|
|
||||||
"coverage_complete":true, "periods":[]
|
|
||||||
}))
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
assert_eq!(
|
|
||||||
live.plan_history().await.err().unwrap(),
|
|
||||||
"Account changed. Press R to refresh Analytics."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[path = "profile_identity_tests.rs"]
|
|
||||||
mod profile_identity;
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
//! Large report totals and axes stay compact while selected-day details retain precision.
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn report_headlines_and_axes_compact_large_values() {
|
|
||||||
for (section, unit, total, headline) in [
|
|
||||||
(
|
|
||||||
Section::Usage,
|
|
||||||
models::AccountAnalyticsUnit::Tokens,
|
|
||||||
12_280_365_226.0,
|
|
||||||
"12.3B tokens",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
Section::Plugins,
|
|
||||||
models::AccountAnalyticsUnit::Count,
|
|
||||||
9_749.0,
|
|
||||||
"9.7K calls",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
Section::Skills,
|
|
||||||
models::AccountAnalyticsUnit::Count,
|
|
||||||
2_901.0,
|
|
||||||
"2.9K uses",
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Enterprise);
|
|
||||||
view.section = section;
|
|
||||||
view.sections[section].history = Load::Ready(models::AccountAnalyticsHistory {
|
|
||||||
unit,
|
|
||||||
updated_at: None,
|
|
||||||
data: vec![models::AccountAnalyticsDay {
|
|
||||||
date: view.end_date,
|
|
||||||
total,
|
|
||||||
values: vec![models::AccountAnalyticsValue {
|
|
||||||
key: "test".into(),
|
|
||||||
label: "Example".into(),
|
|
||||||
value: total,
|
|
||||||
}],
|
|
||||||
}],
|
|
||||||
});
|
|
||||||
let rendered = screen(&mut view, /*width*/ 100, /*height*/ 30);
|
|
||||||
assert!(rendered.contains(headline));
|
|
||||||
assert!(rendered.contains(&data::amount(total)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,260 +0,0 @@
|
|||||||
//! Exercise local Analytics plan discovery and report recovery while connected to an app-server.
|
|
||||||
|
|
||||||
use super::tests::live;
|
|
||||||
use super::tests::sign_in;
|
|
||||||
use codex_app_server_client::AppServerRequestHandle;
|
|
||||||
use codex_app_server_client::RemoteAppServerClient;
|
|
||||||
use codex_app_server_client::RemoteAppServerConnectArgs;
|
|
||||||
use codex_app_server_client::RemoteAppServerEndpoint;
|
|
||||||
use futures::SinkExt;
|
|
||||||
use futures::StreamExt;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::Value;
|
|
||||||
use serde_json::json;
|
|
||||||
use tokio::net::TcpListener;
|
|
||||||
use tokio::net::TcpStream;
|
|
||||||
use tokio_tungstenite::WebSocketStream;
|
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::header;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
|
|
||||||
async fn read(socket: &mut WebSocketStream<TcpStream>) -> Value {
|
|
||||||
let frame = socket.next().await.unwrap().unwrap();
|
|
||||||
serde_json::from_str(frame.to_text().unwrap()).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn remote() -> (RemoteAppServerClient, tokio::task::JoinHandle<()>) {
|
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
||||||
let address = listener.local_addr().unwrap();
|
|
||||||
let server = tokio::spawn(async move {
|
|
||||||
let (stream, _) = listener.accept().await.unwrap();
|
|
||||||
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
|
|
||||||
let initialize = read(&mut socket).await;
|
|
||||||
assert_eq!(initialize["method"], "initialize");
|
|
||||||
socket
|
|
||||||
.send(Message::Text(
|
|
||||||
json!({"id": initialize["id"], "result": {
|
|
||||||
"userAgent": "analytics-test", "codexHome": "/server/.codex",
|
|
||||||
}})
|
|
||||||
.to_string()
|
|
||||||
.into(),
|
|
||||||
))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(read(&mut socket).await["method"], "initialized");
|
|
||||||
// Analytics uses the local account without requesting connected-server account data.
|
|
||||||
assert!(socket.next().await.unwrap().unwrap().is_close());
|
|
||||||
});
|
|
||||||
let client = RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
|
|
||||||
required_human_approval: true,
|
|
||||||
endpoint: RemoteAppServerEndpoint::WebSocket {
|
|
||||||
websocket_url: format!("ws://{address}"),
|
|
||||||
auth_token: None,
|
|
||||||
},
|
|
||||||
client_name: "analytics-test".into(),
|
|
||||||
client_version: "0.0.0-test".into(),
|
|
||||||
experimental_api: true,
|
|
||||||
mcp_server_openai_form_elicitation: false,
|
|
||||||
opt_out_notification_methods: Vec::new(),
|
|
||||||
channel_capacity: 8,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
(client, server)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn local_reports_share_an_account_and_recover_profile_errors() {
|
|
||||||
use crate::analytics::AnalyticsView;
|
|
||||||
use crate::analytics::data::Load;
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
|
|
||||||
let http = crate::analytics::test_support::server().await;
|
|
||||||
let (home, local) = live(&http, "enterprise").await;
|
|
||||||
let (client, server) = remote().await;
|
|
||||||
let failed_profile = Mock::given(method("GET"))
|
|
||||||
.and(wiremock::matchers::path("/backend-api/wham/profiles/me"))
|
|
||||||
.and(header("chatgpt-account-id", "account-a"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 503))
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount_as_scoped(&http)
|
|
||||||
.await;
|
|
||||||
let mut view = AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list);
|
|
||||||
view.open(
|
|
||||||
AppServerRequestHandle::Remote(client.request_handle()),
|
|
||||||
crate::tui::FrameRequester::test_dummy(),
|
|
||||||
Vec::new(),
|
|
||||||
std::sync::Arc::clone(&local.config),
|
|
||||||
);
|
|
||||||
crate::analytics::test_support::settle(&mut view).await;
|
|
||||||
assert_eq!(
|
|
||||||
view.visible_sections(),
|
|
||||||
&[
|
|
||||||
Section::Summary,
|
|
||||||
Section::Credits,
|
|
||||||
Section::Usage,
|
|
||||||
Section::Plugins,
|
|
||||||
Section::Skills,
|
|
||||||
]
|
|
||||||
);
|
|
||||||
assert!(matches!(view.profile, Load::Error(_)));
|
|
||||||
for section in view.visible_sections() {
|
|
||||||
if section.report().is_some() {
|
|
||||||
assert!(view.sections[*section].history.ready().is_some());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
drop(failed_profile);
|
|
||||||
|
|
||||||
let profile = json!({
|
|
||||||
"profile":{"display_name":"Local account","username":"local-user"},
|
|
||||||
"stats":{"lifetime_tokens":12345,"peak_daily_tokens":12345,
|
|
||||||
"daily_usage_buckets":[{"start_date":"2026-09-09","tokens":12345}]}
|
|
||||||
});
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(wiremock::matchers::path("/backend-api/wham/profiles/me"))
|
|
||||||
.and(header("chatgpt-account-id", "account-a"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(profile.clone()))
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&http)
|
|
||||||
.await;
|
|
||||||
view.refresh();
|
|
||||||
crate::analytics::test_support::settle(&mut view).await;
|
|
||||||
assert_eq!(
|
|
||||||
view.profile.ready(),
|
|
||||||
Some(&serde_json::from_value(profile).unwrap())
|
|
||||||
);
|
|
||||||
for request in http.received_requests().await.unwrap() {
|
|
||||||
assert_eq!(
|
|
||||||
request.headers.get("chatgpt-account-id").unwrap(),
|
|
||||||
"account-a"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(wiremock::matchers::path("/backend-api/wham/accounts/check"))
|
|
||||||
.and(header("chatgpt-account-id", "account-b"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
|
||||||
"accounts": [{"id": "account-b", "plan_type": "enterprise"}]
|
|
||||||
})))
|
|
||||||
.with_priority(/*p*/ 1)
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&http)
|
|
||||||
.await;
|
|
||||||
sign_in(home.path(), "account-b", "user-b", "enterprise");
|
|
||||||
assert!(
|
|
||||||
view.live
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.history(
|
|
||||||
super::Report::Usage,
|
|
||||||
/*days*/ 7,
|
|
||||||
super::Grouping::Surface
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
view.poll_reports();
|
|
||||||
assert!(matches!(view.account, Load::Loading(_)));
|
|
||||||
assert!(matches!(view.profile, Load::Unavailable));
|
|
||||||
assert!(
|
|
||||||
view.sections
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.all(|section| matches!(section.history, Load::Unavailable))
|
|
||||||
);
|
|
||||||
crate::analytics::test_support::settle(&mut view).await;
|
|
||||||
assert_eq!(
|
|
||||||
view.account.ready(),
|
|
||||||
Some(&codex_protocol::account::PlanType::Enterprise)
|
|
||||||
);
|
|
||||||
for section in view.visible_sections() {
|
|
||||||
if section.report().is_some() {
|
|
||||||
assert!(view.sections[*section].history.ready().is_some());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
http.verify().await;
|
|
||||||
view.cancel_loads();
|
|
||||||
client.shutdown().await.unwrap();
|
|
||||||
server.await.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn account_lookup_failure_recovers_on_refresh_with_the_server_plan() {
|
|
||||||
use crate::analytics::AnalyticsView;
|
|
||||||
use crate::analytics::data::Load;
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
|
|
||||||
let http = crate::analytics::test_support::server().await;
|
|
||||||
let (_home, local) = live(&http, "plus").await;
|
|
||||||
let (client, server) = remote().await;
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(wiremock::matchers::path("/backend-api/wham/accounts/check"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 503))
|
|
||||||
.with_priority(/*p*/ 1)
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.up_to_n_times(/*n*/ 1)
|
|
||||||
.mount(&http)
|
|
||||||
.await;
|
|
||||||
let mut view = AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list);
|
|
||||||
view.open(
|
|
||||||
AppServerRequestHandle::Remote(client.request_handle()),
|
|
||||||
crate::tui::FrameRequester::test_dummy(),
|
|
||||||
Vec::new(),
|
|
||||||
std::sync::Arc::clone(&local.config),
|
|
||||||
);
|
|
||||||
crate::analytics::test_support::settle(&mut view).await;
|
|
||||||
assert!(matches!(view.account, Load::Error(_)));
|
|
||||||
assert_eq!(
|
|
||||||
http.received_requests()
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.map(|request| request.url.path())
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
["/backend-api/wham/accounts/check"]
|
|
||||||
);
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(wiremock::matchers::path("/backend-api/wham/accounts/check"))
|
|
||||||
.and(header("chatgpt-account-id", "account-a"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
|
||||||
"accounts": [{"id": "account-a", "plan_type": "enterprise"}]
|
|
||||||
})))
|
|
||||||
.with_priority(/*p*/ 1)
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&http)
|
|
||||||
.await;
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(wiremock::matchers::path("/backend-api/wham/profiles/me"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"stats": {}})))
|
|
||||||
.mount(&http)
|
|
||||||
.await;
|
|
||||||
view.handle_key(crossterm::event::KeyEvent::new(
|
|
||||||
crossterm::event::KeyCode::Char('R'),
|
|
||||||
crossterm::event::KeyModifiers::NONE,
|
|
||||||
));
|
|
||||||
crate::analytics::test_support::settle(&mut view).await;
|
|
||||||
assert_eq!(
|
|
||||||
view.visible_sections(),
|
|
||||||
&[
|
|
||||||
Section::Summary,
|
|
||||||
Section::Credits,
|
|
||||||
Section::Usage,
|
|
||||||
Section::Plugins,
|
|
||||||
Section::Skills,
|
|
||||||
]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
view.account.ready(),
|
|
||||||
Some(&codex_protocol::account::PlanType::Enterprise)
|
|
||||||
);
|
|
||||||
for section in view.visible_sections() {
|
|
||||||
if section.report().is_some() {
|
|
||||||
assert!(view.sections[*section].history.ready().is_some());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
http.verify().await;
|
|
||||||
view.cancel_loads();
|
|
||||||
client.shutdown().await.unwrap();
|
|
||||||
server.await.unwrap();
|
|
||||||
}
|
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
//! Consumer chat columns follow reported metrics without substituting billing estimates.
|
|
||||||
use super::*;
|
|
||||||
use crate::analytics::tasks::Chat;
|
|
||||||
use crate::analytics::tasks::Chats;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn consumer_chats_keep_missing_rows_and_only_offer_known_metrics() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
view.section = Section::Chats;
|
|
||||||
view.tasks = Load::Ready(Chats {
|
|
||||||
rows: vec![
|
|
||||||
Chat { title: "Private title from another account".into(), task: None },
|
|
||||||
Chat { title: "Unverified backend row".into(), task: Some(serde_json::from_value(json!({
|
|
||||||
"thread_id":"unavailable", "data_status":"unavailable", "usage_source":"unknown",
|
|
||||||
"weekly_limit_percent":null,"five_hour_limit_percent":null,"balance_usage_credits":null,"groups":[]
|
|
||||||
})).unwrap()) },
|
|
||||||
Chat { title: "Refunded task".into(), task: Some(serde_json::from_value(json!({
|
|
||||||
"thread_id":"refund", "data_status":"partial", "usage_source":"credits",
|
|
||||||
"weekly_limit_percent":null,"five_hour_limit_percent":null,"balance_usage_credits":"-0.000004","groups":[{
|
|
||||||
"product_experience":"codex", "model":"gpt-5.5", "reasoning_effort":"high", "speed":"fast",
|
|
||||||
"weekly_limit_percent":null,"five_hour_limit_percent":null,"balance_usage_credits":"-0.000004"
|
|
||||||
}]
|
|
||||||
})).unwrap()) },
|
|
||||||
], ..Chats::default()
|
|
||||||
});
|
|
||||||
assert_eq!(view.task_metrics(), vec![2]);
|
|
||||||
assert_eq!(
|
|
||||||
view.task_rows()
|
|
||||||
.iter()
|
|
||||||
.map(|row| row.title.as_str())
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
vec![
|
|
||||||
"Refunded task",
|
|
||||||
"Private title from another account",
|
|
||||||
"Unverified backend row"
|
|
||||||
]
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Down);
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert_eq!(view.sections[Section::Chats].detail, None);
|
|
||||||
let hidden = screen(&mut view, /*width*/ 90, /*height*/ 30);
|
|
||||||
assert!(!hidden.contains("Private title") && !hidden.contains("Unverified backend row"));
|
|
||||||
press(&mut view, KeyCode::Up);
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert!(screen(&mut view, /*width*/ 90, /*height*/ 30).contains("-0.000004"));
|
|
||||||
let chats = match &mut view.tasks {
|
|
||||||
Load::Ready(chats) => chats,
|
|
||||||
_ => unreachable!(),
|
|
||||||
};
|
|
||||||
chats.rows[2]
|
|
||||||
.task
|
|
||||||
.as_mut()
|
|
||||||
.unwrap()
|
|
||||||
.amounts
|
|
||||||
.five_hour_limit_percent = Some(0.0);
|
|
||||||
chats.rows[2]
|
|
||||||
.task
|
|
||||||
.as_mut()
|
|
||||||
.unwrap()
|
|
||||||
.amounts
|
|
||||||
.weekly_limit_percent = Some(125.0);
|
|
||||||
chats.rows.push(Chat {
|
|
||||||
title: "Plan-covered task".into(),
|
|
||||||
task: Some(serde_json::from_value(json!({
|
|
||||||
"thread_id":"plan", "data_status":"available", "usage_source":"included_plan",
|
|
||||||
"weekly_limit_percent":12.1,"five_hour_limit_percent":null,"balance_usage_credits":"0E-10","groups":[]
|
|
||||||
})).unwrap()),
|
|
||||||
});
|
|
||||||
for (raw, expected) in [
|
|
||||||
("0E-10", "0.00"),
|
|
||||||
("0.0000000000", "0.00"),
|
|
||||||
("-0e+10", "0.00"),
|
|
||||||
("1e-1000", "1e-1000"),
|
|
||||||
("-1e-1000", "-1e-1000"),
|
|
||||||
("1e1000", "1e1000"),
|
|
||||||
("12.3", "12.30"),
|
|
||||||
("12.3400000000", "12.34"),
|
|
||||||
("12.346", "12.35"),
|
|
||||||
("2.675", "2.68"),
|
|
||||||
("-2.675", "-2.68"),
|
|
||||||
("1.005", "1.01"),
|
|
||||||
("1.0049999999", "1.00"),
|
|
||||||
("9.999", "10.00"),
|
|
||||||
("0012.3", "12.30"),
|
|
||||||
("1.23e2", "123.00"),
|
|
||||||
("1234e-2", "12.34"),
|
|
||||||
("9007199254740993", "9007199254740993"),
|
|
||||||
("999999999999999999", "999999999999999999"),
|
|
||||||
("141436", "141,436.00"),
|
|
||||||
("0.01", "0.01"),
|
|
||||||
("-0.000004", "-0.000004"),
|
|
||||||
("1e-7", "1e-7"),
|
|
||||||
] {
|
|
||||||
let amounts = serde_json::from_value(json!({"balance_usage_credits":raw})).unwrap();
|
|
||||||
assert_eq!(task_panel::amount(Some(&amounts), /*metric*/ 2), expected);
|
|
||||||
}
|
|
||||||
assert_eq!(view.task_metrics(), vec![0, 1, 2]);
|
|
||||||
insta::assert_snapshot!(
|
|
||||||
"consumer_chat_all_metrics",
|
|
||||||
screen(&mut view, /*width*/ 110, /*height*/ 30)
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Char('s'));
|
|
||||||
assert_eq!(view.task_metric(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn consumer_chats_show_all_rows_and_collapse_details_before_closing() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
view.section = Section::Chats;
|
|
||||||
view.tasks = Load::Ready(Chats {
|
|
||||||
rows: (0..6).map(|index| Chat {
|
|
||||||
title: format!("Task {index}"),
|
|
||||||
task: Some(serde_json::from_value(json!({
|
|
||||||
"thread_id":format!("task-{index}"), "data_status":"available", "usage_source":"credits",
|
|
||||||
"balance_usage_credits":index.to_string(), "groups":[]
|
|
||||||
})).unwrap()),
|
|
||||||
}).collect(),
|
|
||||||
..Chats::default()
|
|
||||||
});
|
|
||||||
screen(&mut view, /*width*/ 120, /*height*/ 42);
|
|
||||||
press(&mut view, KeyCode::End);
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert_eq!(view.sections[Section::Chats].detail, Some(5));
|
|
||||||
let content = view
|
|
||||||
.task_lines(/*width*/ 70)
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.map(|line| line.to_string().trim_end().to_owned())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
assert!(content.contains("Task 5") && content.contains("Task 0"));
|
|
||||||
press(&mut view, KeyCode::Esc);
|
|
||||||
assert!(!view.is_done);
|
|
||||||
press(&mut view, KeyCode::Esc);
|
|
||||||
assert!(view.is_done);
|
|
||||||
}
|
|
||||||
@@ -1,292 +0,0 @@
|
|||||||
//! Visible report controls and update times. Mouse targets and keyboard shortcuts invoke the same semantic actions.
|
|
||||||
//! Their reserved rows depend only on terminal width, so loading never shifts the report body.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::sections::Section;
|
|
||||||
use super::styles::secondary_style;
|
|
||||||
use crate::key_hint;
|
|
||||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow as truncate;
|
|
||||||
use crate::style::accent_style;
|
|
||||||
use chrono::Datelike;
|
|
||||||
use crossterm::event::KeyCode;
|
|
||||||
use ratatui::buffer::Buffer;
|
|
||||||
use ratatui::layout::Rect;
|
|
||||||
use ratatui::style::Styled;
|
|
||||||
use ratatui::style::Stylize;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
use ratatui::widgets::Widget;
|
|
||||||
|
|
||||||
/// A mouse action is independent of a user's remapped or disabled arrow bindings.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub(super) enum Control {
|
|
||||||
Range,
|
|
||||||
Group,
|
|
||||||
Model,
|
|
||||||
TaskMetric,
|
|
||||||
Dashboard,
|
|
||||||
PlanWindow,
|
|
||||||
ZeroCreditGroups,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
/// Share action eligibility between painted controls, keyboard dispatch and help.
|
|
||||||
pub(super) fn control_available(&self, control: Control) -> bool {
|
|
||||||
if self.visible_sections().is_empty() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
match control {
|
|
||||||
Control::Range => self.section.report().is_some(),
|
|
||||||
Control::Group => self.group_options().len() > 1,
|
|
||||||
Control::Model => self.section == Section::Usage && self.business(),
|
|
||||||
Control::TaskMetric => self.section == Section::Chats && !self.business(),
|
|
||||||
Control::Dashboard => true,
|
|
||||||
Control::PlanWindow => self.section == Section::Plan,
|
|
||||||
Control::ZeroCreditGroups => {
|
|
||||||
self.section == Section::Chats
|
|
||||||
&& self.business()
|
|
||||||
&& self.sections[Section::Chats].detail.is_some()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Apply a visible report action without synthesizing a remappable keyboard event.
|
|
||||||
pub(super) fn activate_control(&mut self, control: Control) {
|
|
||||||
if !self.control_available(control) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Labels can change width; wait for their new painted positions before another click.
|
|
||||||
self.invalidate_mouse_targets();
|
|
||||||
match control {
|
|
||||||
Control::ZeroCreditGroups => {
|
|
||||||
self.show_zero_credit_groups = !self.show_zero_credit_groups
|
|
||||||
}
|
|
||||||
Control::Range => self.change_range(),
|
|
||||||
Control::Dashboard => self.toggle_dashboard(),
|
|
||||||
Control::PlanWindow => {
|
|
||||||
self.plan_action(Some(crate::keymap::ListAction::MoveRight));
|
|
||||||
self.follow_selection = true;
|
|
||||||
}
|
|
||||||
Control::Model => {
|
|
||||||
let models = self
|
|
||||||
.live
|
|
||||||
.as_ref()
|
|
||||||
.map_or_else(Vec::new, |live| live.token_models());
|
|
||||||
self.token_model = match self
|
|
||||||
.token_model
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|model| models.iter().position(|candidate| candidate == model))
|
|
||||||
{
|
|
||||||
Some(index) => models.get(index + 1).cloned(),
|
|
||||||
None => models.first().cloned(),
|
|
||||||
};
|
|
||||||
self.load_report(Section::Usage);
|
|
||||||
}
|
|
||||||
Control::Group => {
|
|
||||||
let options = self.group_options();
|
|
||||||
let next = options
|
|
||||||
.iter()
|
|
||||||
.position(|group| *group == self.sections[self.section].group)
|
|
||||||
.map_or(/*default*/ 0, |index| (index + 1) % options.len());
|
|
||||||
self.sections[self.section].group = options[next];
|
|
||||||
self.load_report(self.section);
|
|
||||||
}
|
|
||||||
Control::TaskMetric => {
|
|
||||||
let metrics = self.task_metrics();
|
|
||||||
let index = metrics
|
|
||||||
.iter()
|
|
||||||
.position(|metric| *metric == self.task_metric())
|
|
||||||
.unwrap_or_default();
|
|
||||||
self.chat_metric = metrics[(index + 1) % metrics.len()];
|
|
||||||
self.sections[Section::Chats].detail = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn render_controls(&mut self, area: Rect, buf: &mut Buffer) {
|
|
||||||
self.control_hits.clear();
|
|
||||||
if area.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if self.show_help {
|
|
||||||
"Usage shortcuts".bold().render(area, buf);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if self.visible_sections().is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let width = usize::from(area.width);
|
|
||||||
let mut rows = vec![Vec::new(), Vec::new()];
|
|
||||||
let report = self.control_available(Control::Range);
|
|
||||||
if report {
|
|
||||||
let range = self.ranges[self.range_group(self.section) as usize];
|
|
||||||
let dates = self.section_date_range(self.section);
|
|
||||||
let interval = if dates.start().year() != dates.end().year() && width < 50 {
|
|
||||||
format!(
|
|
||||||
"{}–{}",
|
|
||||||
dates.start().format("%m/%d/%Y"),
|
|
||||||
dates.end().format("%m/%d/%Y")
|
|
||||||
)
|
|
||||||
} else if dates.start().year() == dates.end().year() {
|
|
||||||
format!(
|
|
||||||
"{}–{}",
|
|
||||||
dates.start().format("%b %-d"),
|
|
||||||
dates.end().format("%b %-d, %Y")
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
format!(
|
|
||||||
"{}–{}",
|
|
||||||
dates.start().format("%b %-d, %Y"),
|
|
||||||
dates.end().format("%b %-d, %Y")
|
|
||||||
)
|
|
||||||
};
|
|
||||||
rows[0].push((
|
|
||||||
Control::Range,
|
|
||||||
Line::from(vec![
|
|
||||||
key_hint::plain(KeyCode::Char('r')).into(),
|
|
||||||
" ".dim(),
|
|
||||||
if range == 0 {
|
|
||||||
"7d".set_style(accent_style()).bold()
|
|
||||||
} else {
|
|
||||||
"7d".dim()
|
|
||||||
},
|
|
||||||
"/".dim(),
|
|
||||||
if range == 1 {
|
|
||||||
"30d".set_style(accent_style()).bold()
|
|
||||||
} else {
|
|
||||||
"30d".dim()
|
|
||||||
},
|
|
||||||
format!(" · {interval}").into(),
|
|
||||||
]),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let option_row = usize::from(width < 100 && report);
|
|
||||||
if self.control_available(Control::Group) {
|
|
||||||
rows[option_row].push((
|
|
||||||
Control::Group,
|
|
||||||
Line::from(vec![
|
|
||||||
key_hint::plain(KeyCode::Char('g')).into(),
|
|
||||||
" ".dim(),
|
|
||||||
self.group_label(self.section, self.sections[self.section].group)
|
|
||||||
.to_owned()
|
|
||||||
.into(),
|
|
||||||
]),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if self.control_available(Control::Model) {
|
|
||||||
rows[option_row].push((
|
|
||||||
Control::Model,
|
|
||||||
Line::from(vec![
|
|
||||||
key_hint::plain(KeyCode::Char('m')).into(),
|
|
||||||
" ".dim(),
|
|
||||||
self.token_model
|
|
||||||
.clone()
|
|
||||||
.unwrap_or_else(|| "All models".into())
|
|
||||||
.into(),
|
|
||||||
]),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if self.control_available(Control::TaskMetric) {
|
|
||||||
rows[0].push((
|
|
||||||
Control::TaskMetric,
|
|
||||||
Line::from(vec![
|
|
||||||
key_hint::plain(KeyCode::Char('s')).into(),
|
|
||||||
" sort: ".dim(),
|
|
||||||
super::task_panel::METRICS[self.task_metric()].into(),
|
|
||||||
]),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if self.control_available(Control::PlanWindow) {
|
|
||||||
let row = usize::from(width < 100);
|
|
||||||
let hints = [
|
|
||||||
crate::keymap::ListAction::MoveLeft,
|
|
||||||
crate::keymap::ListAction::MoveRight,
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|action| self.keymap.primary_hint(action))
|
|
||||||
.map(key_hint::ShortcutHint::display_label)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("/");
|
|
||||||
let mut plan_window = Line::default();
|
|
||||||
if !hints.is_empty() {
|
|
||||||
plan_window.spans = key_hint::key_label_spans(&format!("{hints} "));
|
|
||||||
}
|
|
||||||
plan_window.spans.extend([
|
|
||||||
if self.plan.window == 0 {
|
|
||||||
"5-hour".set_style(accent_style()).bold()
|
|
||||||
} else {
|
|
||||||
"5-hour".dim()
|
|
||||||
},
|
|
||||||
" / ".dim(),
|
|
||||||
if self.plan.window == 1 {
|
|
||||||
"Weekly".set_style(accent_style()).bold()
|
|
||||||
} else {
|
|
||||||
"Weekly".dim()
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
rows[row].push((Control::PlanWindow, plan_window));
|
|
||||||
}
|
|
||||||
if !self.zoomed {
|
|
||||||
let mut dashboard = Line::from("Dashboard".bold());
|
|
||||||
if let Some(hint) = self.keymap.primary_hint(crate::keymap::ListAction::Accept) {
|
|
||||||
dashboard.spans.push(" · ".dim());
|
|
||||||
dashboard.spans.extend(hint.spans());
|
|
||||||
dashboard.spans.push(" focus".dim());
|
|
||||||
}
|
|
||||||
rows[0].insert(/*index*/ 0, (Control::Dashboard, dashboard));
|
|
||||||
}
|
|
||||||
for (row, controls) in rows
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
.take(usize::from(area.height.saturating_sub(/*rhs*/ 1)))
|
|
||||||
{
|
|
||||||
let mut x = area.x;
|
|
||||||
for (key, line) in controls {
|
|
||||||
if x > area.x {
|
|
||||||
" · ".dim().render(
|
|
||||||
Rect::new(
|
|
||||||
x,
|
|
||||||
area.y + row as u16,
|
|
||||||
area.right().saturating_sub(x).min(/*other*/ 3),
|
|
||||||
/*height*/ 1,
|
|
||||||
),
|
|
||||||
buf,
|
|
||||||
);
|
|
||||||
x = x.saturating_add(/*rhs*/ 3);
|
|
||||||
}
|
|
||||||
let remaining = area.right().saturating_sub(x);
|
|
||||||
if remaining == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
let line = truncate(line, usize::from(remaining));
|
|
||||||
let hit = Rect::new(
|
|
||||||
x,
|
|
||||||
area.y + row as u16,
|
|
||||||
line.width() as u16,
|
|
||||||
/*height*/ 1,
|
|
||||||
);
|
|
||||||
line.render(hit, buf);
|
|
||||||
if !hit.is_empty() {
|
|
||||||
self.control_hits.push((key, hit));
|
|
||||||
}
|
|
||||||
x = hit.right();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let updated = self.sections[self.section]
|
|
||||||
.history
|
|
||||||
.ready()
|
|
||||||
.and_then(|report| report.updated_at)
|
|
||||||
.and_then(|value| chrono::DateTime::from_timestamp(value, /*nsecs*/ 0));
|
|
||||||
let metadata = updated
|
|
||||||
.map(|updated| {
|
|
||||||
format!(
|
|
||||||
"Updated · {} UTC",
|
|
||||||
updated.format(self.clock_format.date_time_format())
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.unwrap_or_default();
|
|
||||||
truncate(metadata.set_style(secondary_style()).into(), width).render(
|
|
||||||
Rect::new(area.x, area.bottom() - 1, area.width, /*height*/ 1),
|
|
||||||
buf,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,221 +0,0 @@
|
|||||||
//! Bordered, aligned overview cards. Detailed reports remain in maximized mode.
|
|
||||||
//! Card heights depend on the viewport, never on the selected day or load state.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::data;
|
|
||||||
use super::render::columns;
|
|
||||||
use super::render::join_columns;
|
|
||||||
use super::styles::number;
|
|
||||||
use super::styles::secondary_style;
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow as truncate;
|
|
||||||
use crate::style::accent_style;
|
|
||||||
use crate::wrapping::RtOptions;
|
|
||||||
use crate::wrapping::word_wrap_lines;
|
|
||||||
use ratatui::style::Styled;
|
|
||||||
use ratatui::style::Stylize;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
use std::ops::Range;
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn dashboard_lines(
|
|
||||||
&self,
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
) -> (Vec<Line<'static>>, Range<usize>) {
|
|
||||||
let count = if width >= 104 { 2 } else { 1 };
|
|
||||||
let card_width = if count == 2 { (width - 4) / 2 } else { width };
|
|
||||||
let visible = self.visible_sections();
|
|
||||||
let rows = visible.len().div_ceil(count).max(/*other*/ 1);
|
|
||||||
let card_height =
|
|
||||||
(height.saturating_sub(/*rhs*/ 2) / rows).clamp(/*min*/ 16, /*max*/ 24);
|
|
||||||
let inner_width = card_width.saturating_sub(/*rhs*/ 4).max(/*other*/ 1);
|
|
||||||
let inner_height = card_height - 4;
|
|
||||||
let mut lines = Vec::new();
|
|
||||||
let mut selected = 0..0;
|
|
||||||
for (row, chunk) in visible.chunks(count).enumerate() {
|
|
||||||
let mut cards = Vec::new();
|
|
||||||
for (column, section) in chunk.iter().copied().enumerate() {
|
|
||||||
let focused = self.section == section;
|
|
||||||
let border = if focused {
|
|
||||||
accent_style()
|
|
||||||
} else {
|
|
||||||
secondary_style().dim()
|
|
||||||
};
|
|
||||||
let mut content = Vec::new();
|
|
||||||
if !matches!(section, Section::Chats | Section::Plan | Section::Summary) {
|
|
||||||
content.push(
|
|
||||||
format!(
|
|
||||||
"{}d{}",
|
|
||||||
if self.ranges[self.range_group(section) as usize] == 0 {
|
|
||||||
7
|
|
||||||
} else {
|
|
||||||
30
|
|
||||||
},
|
|
||||||
if section == Section::Usage && self.business() {
|
|
||||||
format!(
|
|
||||||
" · {}",
|
|
||||||
self.token_model.as_deref().unwrap_or("All models")
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
String::new()
|
|
||||||
}
|
|
||||||
)
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if matches!(
|
|
||||||
section,
|
|
||||||
Section::Usage | Section::Credits | Section::Activity | Section::Plan
|
|
||||||
) {
|
|
||||||
content.push(
|
|
||||||
format!(
|
|
||||||
"By {}",
|
|
||||||
self.group_label(section, self.sections[section].group)
|
|
||||||
.to_lowercase()
|
|
||||||
)
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
match section {
|
|
||||||
Section::Summary => content.extend(self.summary_lines(inner_width)),
|
|
||||||
Section::Usage
|
|
||||||
| Section::Plugins
|
|
||||||
| Section::Credits
|
|
||||||
| Section::Activity
|
|
||||||
| Section::Skills => content.extend(
|
|
||||||
self.history_lines(
|
|
||||||
section,
|
|
||||||
inner_width,
|
|
||||||
inner_height.saturating_sub(/*rhs*/ 13).max(/*other*/ 1),
|
|
||||||
)
|
|
||||||
.lines,
|
|
||||||
),
|
|
||||||
Section::Plan => content.extend(self.plan_lines(inner_width).0),
|
|
||||||
Section::Chats if !self.business() => {
|
|
||||||
content.extend(self.task_lines(inner_width).0)
|
|
||||||
}
|
|
||||||
Section::Chats => {
|
|
||||||
content.push(
|
|
||||||
"30d active · lifetime credits"
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
content.push(Line::default());
|
|
||||||
if let Some(chats) = self.chats.ready() {
|
|
||||||
if chats.rows.is_empty() {
|
|
||||||
content.push(
|
|
||||||
"No recent local chats.".set_style(secondary_style()).into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
for chat in chats.rows.iter().take(/*n*/ 5) {
|
|
||||||
let amount = chat
|
|
||||||
.usage
|
|
||||||
.as_ref()
|
|
||||||
.map(|usage| {
|
|
||||||
data::credits(usage.estimated_usage_credits_micros)
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|| "—".into());
|
|
||||||
content.push(columns(
|
|
||||||
truncate(
|
|
||||||
chat.display_title().to_string().into(),
|
|
||||||
inner_width.saturating_sub(amount.len() + 1),
|
|
||||||
),
|
|
||||||
number(amount).into(),
|
|
||||||
inner_width,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
content.push(Line::default());
|
|
||||||
content.push(
|
|
||||||
"Local chats · excludes subagents"
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
if chats.rows.iter().any(|chat| chat.usage.is_none()) {
|
|
||||||
content.push(
|
|
||||||
"Some estimates unavailable"
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else if let Some(message) = self.chats.message() {
|
|
||||||
content.push(message.to_string().set_style(secondary_style()).into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut content = word_wrap_lines(content, RtOptions::new(inner_width));
|
|
||||||
if content.len() > inner_height {
|
|
||||||
content.truncate(inner_height);
|
|
||||||
content[inner_height - 1] =
|
|
||||||
"… z to maximize".set_style(secondary_style()).into();
|
|
||||||
}
|
|
||||||
content.resize(inner_height, Line::default());
|
|
||||||
let label = format!(" {} {} ", row * count + column + 1, self.tab_label(section));
|
|
||||||
let title = truncate(
|
|
||||||
Line::from(vec![
|
|
||||||
" ".into(),
|
|
||||||
if focused {
|
|
||||||
"▸".set_style(accent_style())
|
|
||||||
} else {
|
|
||||||
" ".into()
|
|
||||||
},
|
|
||||||
if focused {
|
|
||||||
label.bold()
|
|
||||||
} else {
|
|
||||||
label.set_style(secondary_style())
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
card_width.saturating_sub(/*rhs*/ 3),
|
|
||||||
);
|
|
||||||
let mut top = vec!["╭─".set_style(border)];
|
|
||||||
top.extend(title.spans.iter().cloned());
|
|
||||||
top.push(
|
|
||||||
"─"
|
|
||||||
.repeat(card_width.saturating_sub(title.width() + 3))
|
|
||||||
.set_style(border),
|
|
||||||
);
|
|
||||||
top.push("╮".set_style(border));
|
|
||||||
let blank = columns(
|
|
||||||
"│".set_style(border).into(),
|
|
||||||
"│".set_style(border).into(),
|
|
||||||
card_width,
|
|
||||||
);
|
|
||||||
let mut card = vec![Line::from(top), blank.clone()];
|
|
||||||
card.extend(content.into_iter().map(|line| {
|
|
||||||
let line = truncate(line, inner_width);
|
|
||||||
let padding = card_width.saturating_sub(line.width() + 3);
|
|
||||||
let mut padded = vec!["│".set_style(border), " ".into()];
|
|
||||||
padded.extend(line.spans);
|
|
||||||
padded.push(" ".repeat(padding).into());
|
|
||||||
padded.push("│".set_style(border));
|
|
||||||
Line::from(padded)
|
|
||||||
}));
|
|
||||||
card.push(blank);
|
|
||||||
card.push(
|
|
||||||
format!("╰{}╯", "─".repeat(card_width.saturating_sub(/*rhs*/ 2)))
|
|
||||||
.set_style(border)
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
cards.push(
|
|
||||||
card.into_iter()
|
|
||||||
.map(|line| truncate(line, card_width))
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if chunk.contains(&self.section) {
|
|
||||||
selected = lines.len()..lines.len() + card_height;
|
|
||||||
}
|
|
||||||
lines.extend(if cards.len() == 2 {
|
|
||||||
join_columns(&cards[0], &cards[1], card_width)
|
|
||||||
} else {
|
|
||||||
cards.remove(/*index*/ 0)
|
|
||||||
});
|
|
||||||
if (row + 1) * count < visible.len() {
|
|
||||||
lines.push(Line::default());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(lines, selected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
//! Overview cards retain alignment and geometry while selection and report states change.
|
|
||||||
use super::*;
|
|
||||||
use crate::style::accent_style;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use ratatui::style::Modifier;
|
|
||||||
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
#[test]
|
|
||||||
fn dashboard_focus_uses_marker_and_default_foreground_title() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
view.zoomed = false;
|
|
||||||
for section in [Section::Usage, Section::Activity] {
|
|
||||||
view.section = section;
|
|
||||||
let (lines, _) = view.dashboard_lines(/*width*/ 140, /*height*/ 56);
|
|
||||||
let title = lines
|
|
||||||
.iter()
|
|
||||||
.find(|line| line.spans.iter().any(|span| span.content == "▸"))
|
|
||||||
.unwrap();
|
|
||||||
let marker = title.spans.iter().find(|span| span.content == "▸").unwrap();
|
|
||||||
assert_eq!(marker.style, accent_style());
|
|
||||||
let focused_title = title
|
|
||||||
.spans
|
|
||||||
.iter()
|
|
||||||
.find(|span| span.content.contains(view.tab_label(section)))
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(focused_title.style.fg, None);
|
|
||||||
assert!(focused_title.style.add_modifier.contains(Modifier::BOLD));
|
|
||||||
assert_eq!(title.to_string().matches('▸').count(), 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn dashboard_cards_align_and_keep_stable_summary_heights() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
press(&mut view, KeyCode::Char('z'));
|
|
||||||
let wide = screen(&mut view, /*width*/ 144, /*height*/ 64);
|
|
||||||
for (left, right) in [
|
|
||||||
("1 Overview", "2 Usage"),
|
|
||||||
("3 Messages", "4 Plugins"),
|
|
||||||
("5 Skills", "6 Chats"),
|
|
||||||
] {
|
|
||||||
assert!(
|
|
||||||
wide.lines()
|
|
||||||
.any(|line| line.contains(left) && line.contains(right))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert!(!wide.contains("Coverage from"));
|
|
||||||
let before = view.dashboard_lines(/*width*/ 140, /*height*/ 56);
|
|
||||||
press(&mut view, KeyCode::Left);
|
|
||||||
view.sections[Section::Plugins].history = Load::Error("Access denied for this report.".into());
|
|
||||||
let after = view.dashboard_lines(/*width*/ 140, /*height*/ 56);
|
|
||||||
assert_eq!((before.0.len(), before.1), (after.0.len(), after.1));
|
|
||||||
let edges = |lines: &[ratatui::text::Line<'_>]| {
|
|
||||||
lines
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.filter(|(_, line)| line.to_string().starts_with(['╭', '╰']))
|
|
||||||
.map(|(index, _)| index)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
};
|
|
||||||
assert_eq!(edges(&before.0), edges(&after.0));
|
|
||||||
for width in [1, 4, 40, 100, 140] {
|
|
||||||
assert!(
|
|
||||||
view.dashboard_lines(width, /*height*/ 56)
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.all(|line| line.width() <= width)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let narrow = screen(&mut view, /*width*/ 72, /*height*/ 48);
|
|
||||||
assert!(narrow.contains("1 Overview"));
|
|
||||||
let context = (
|
|
||||||
view.section,
|
|
||||||
view.sections.0.each_ref().map(|state| state.cursor),
|
|
||||||
view.sections.0.each_ref().map(|state| state.group),
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert!(view.zoomed);
|
|
||||||
assert_eq!(
|
|
||||||
context,
|
|
||||||
(
|
|
||||||
view.section,
|
|
||||||
view.sections.0.each_ref().map(|state| state.cursor),
|
|
||||||
view.sections.0.each_ref().map(|state| state.group)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
insta::assert_snapshot!(format!("{wide}\n{narrow}"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn overview_closes_on_escape_with_retained_day_details() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert_eq!(view.sections[Section::Usage].detail, Some(6));
|
|
||||||
press(&mut view, KeyCode::Char('z'));
|
|
||||||
assert!(!view.zoomed);
|
|
||||||
press(&mut view, KeyCode::Esc);
|
|
||||||
assert!(view.is_done);
|
|
||||||
}
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
//! Report loading and grouping metadata for the account dashboard.
|
|
||||||
//! Replacing a pending load aborts it; its response cannot populate a newer range or account.
|
|
||||||
|
|
||||||
use super::models::AccountAnalyticsGrouping as Grouping;
|
|
||||||
use crate::tui::FrameRequester;
|
|
||||||
use futures::FutureExt;
|
|
||||||
use std::panic::AssertUnwindSafe;
|
|
||||||
use tokio::sync::oneshot;
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
|
|
||||||
pub(super) const GROUPINGS: [Grouping; 7] = [
|
|
||||||
Grouping::Surface,
|
|
||||||
Grouping::Feature,
|
|
||||||
Grouping::Model,
|
|
||||||
Grouping::TaskStart,
|
|
||||||
Grouping::Speed,
|
|
||||||
Grouping::Reasoning,
|
|
||||||
Grouping::TokenType,
|
|
||||||
];
|
|
||||||
|
|
||||||
pub(super) const GROUP_LABELS: [&str; 7] = [
|
|
||||||
"Surface",
|
|
||||||
"Feature",
|
|
||||||
"Model",
|
|
||||||
"Turn start",
|
|
||||||
"Speed",
|
|
||||||
"Reasoning",
|
|
||||||
"Token type",
|
|
||||||
];
|
|
||||||
|
|
||||||
pub(super) struct Pending<T> {
|
|
||||||
receiver: oneshot::Receiver<Result<Option<T>, String>>,
|
|
||||||
task: JoinHandle<()>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Drop for Pending<T> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.task.abort();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) enum Load<T> {
|
|
||||||
Loading(Pending<T>),
|
|
||||||
Ready(T),
|
|
||||||
Unavailable,
|
|
||||||
Error(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Send + 'static> Load<T> {
|
|
||||||
pub(super) fn start(
|
|
||||||
future: impl std::future::Future<Output = Result<Option<T>, String>> + Send + 'static,
|
|
||||||
frame: FrameRequester,
|
|
||||||
) -> Self {
|
|
||||||
Self::start_with_timeout(future, frame, std::time::Duration::from_secs(/*secs*/ 30))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn start_with_timeout(
|
|
||||||
future: impl std::future::Future<Output = Result<Option<T>, String>> + Send + 'static,
|
|
||||||
frame: FrameRequester,
|
|
||||||
timeout: std::time::Duration,
|
|
||||||
) -> Self {
|
|
||||||
let (sender, receiver) = oneshot::channel();
|
|
||||||
let task =
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let result =
|
|
||||||
match tokio::time::timeout(timeout, AssertUnwindSafe(future).catch_unwind())
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(Ok(result)) => result,
|
|
||||||
Ok(Err(_)) => Err("Request interrupted. Press R to retry.".into()),
|
|
||||||
Err(_) => Err("Request timed out. Press R to retry.".into()),
|
|
||||||
};
|
|
||||||
let _ = sender.send(result);
|
|
||||||
frame.schedule_frame();
|
|
||||||
});
|
|
||||||
Self::Loading(Pending { receiver, task })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn poll(&mut self) {
|
|
||||||
if let Self::Loading(pending) = self {
|
|
||||||
*self = match pending.receiver.try_recv() {
|
|
||||||
Ok(Ok(Some(data))) => Self::Ready(data),
|
|
||||||
Ok(Ok(None)) => Self::Unavailable,
|
|
||||||
Ok(Err(message)) => Self::Error(message),
|
|
||||||
Err(oneshot::error::TryRecvError::Closed) => {
|
|
||||||
Self::Error("Request interrupted. Press R to retry.".into())
|
|
||||||
}
|
|
||||||
Err(oneshot::error::TryRecvError::Empty) => return,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn ready(&self) -> Option<&T> {
|
|
||||||
if let Self::Ready(value) = self {
|
|
||||||
Some(value)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn message(&self) -> Option<&str> {
|
|
||||||
match self {
|
|
||||||
Self::Ready(_) => None,
|
|
||||||
Self::Loading(_) => Some("Loading…"),
|
|
||||||
Self::Unavailable => Some("No history has been reported."),
|
|
||||||
Self::Error(message) => Some(message),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Keep untyped server and transport diagnostics out of account reports.
|
|
||||||
pub(super) fn error(_error: codex_app_server_client::TypedRequestError) -> String {
|
|
||||||
"Couldn't load analytics. Press R to retry.".into()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Keep tiny refunds visible while avoiding noise on ordinary credit amounts.
|
|
||||||
pub(super) fn amount(value: f64) -> String {
|
|
||||||
if value == 0.0 {
|
|
||||||
return "0".into();
|
|
||||||
}
|
|
||||||
if value.abs() < 0.000001 {
|
|
||||||
return format!("{value:.2e}");
|
|
||||||
}
|
|
||||||
let rounded = if value.abs() < 0.01 {
|
|
||||||
format!("{value:.6}")
|
|
||||||
} else {
|
|
||||||
format!("{value:.2}")
|
|
||||||
};
|
|
||||||
let (whole, fraction) = rounded.split_once('.').unwrap_or((&rounded, ""));
|
|
||||||
let mut grouped = String::new();
|
|
||||||
for (index, ch) in whole.chars().enumerate() {
|
|
||||||
if index > 0
|
|
||||||
&& ch.is_ascii_digit()
|
|
||||||
&& (whole.len() - index).is_multiple_of(/*rhs*/ 3)
|
|
||||||
&& !grouped.ends_with('-')
|
|
||||||
{
|
|
||||||
grouped.push(',');
|
|
||||||
}
|
|
||||||
grouped.push(ch);
|
|
||||||
}
|
|
||||||
let fraction = fraction.trim_end_matches('0');
|
|
||||||
if !fraction.is_empty() {
|
|
||||||
grouped.push('.');
|
|
||||||
grouped.push_str(fraction);
|
|
||||||
}
|
|
||||||
grouped
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Compact headline and axis labels to one decimal, preserving small signed adjustments.
|
|
||||||
pub(super) fn compact_amount(value: f64) -> String {
|
|
||||||
if value.abs() < 1_000.0 || !value.is_finite() {
|
|
||||||
return amount(value);
|
|
||||||
}
|
|
||||||
let units = ["K", "M", "B", "T"];
|
|
||||||
let mut scaled = value / 1_000.0;
|
|
||||||
let mut unit = 0;
|
|
||||||
// Promote before rounding would produce a label such as 1000K.
|
|
||||||
while scaled.abs() >= 999.95 && unit + 1 < units.len() {
|
|
||||||
scaled /= 1_000.0;
|
|
||||||
unit += 1;
|
|
||||||
}
|
|
||||||
let rounded = format!("{:.1}", (scaled * 10.0).round() / 10.0);
|
|
||||||
format!(
|
|
||||||
"{}{}",
|
|
||||||
rounded.trim_end_matches('0').trim_end_matches('.'),
|
|
||||||
units[unit]
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Align ordinary credit amounts to two decimals without hiding tiny adjustments.
|
|
||||||
pub(super) fn credit_amount(value: f64) -> String {
|
|
||||||
let formatted = amount(value);
|
|
||||||
if value != 0.0 && value.abs() < 0.01 {
|
|
||||||
return formatted;
|
|
||||||
}
|
|
||||||
match formatted.split_once('.') {
|
|
||||||
None => format!("{formatted}.00"),
|
|
||||||
Some((_, fraction)) if fraction.len() == 1 => format!("{formatted}0"),
|
|
||||||
Some(_) => formatted,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn credits(micros: i64) -> String {
|
|
||||||
let magnitude = micros.unsigned_abs();
|
|
||||||
if magnitude > 0 && magnitude < 10_000 {
|
|
||||||
let fractional = format!("{magnitude:06}");
|
|
||||||
return format!(
|
|
||||||
"{}0.{}",
|
|
||||||
if micros < 0 { "-" } else { "" },
|
|
||||||
fractional.trim_end_matches('0')
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let cents = (magnitude + 5_000) / 10_000;
|
|
||||||
let mut whole = (cents / 100).to_string();
|
|
||||||
let digits = whole.len();
|
|
||||||
for index in (1..digits).rev() {
|
|
||||||
if (digits - index).is_multiple_of(/*rhs*/ 3) {
|
|
||||||
whole.insert(index, ',');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
format!(
|
|
||||||
"{}{whole}.{:02}",
|
|
||||||
if micros < 0 { "-" } else { "" },
|
|
||||||
cents % 100
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "data_tests.rs"]
|
|
||||||
mod tests;
|
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
//! Loading transitions and cancellation when a view replaces pending work.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn completed_loads_publish_data_unavailability_and_errors() {
|
|
||||||
for (result, expected) in [
|
|
||||||
(Ok(Some(7)), (Some(7), None)),
|
|
||||||
(Ok(None), (None, Some("No history has been reported."))),
|
|
||||||
(
|
|
||||||
Err("temporary failure".to_string()),
|
|
||||||
(None, Some("temporary failure")),
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
let mut load = Load::start(async move { result }, FrameRequester::test_dummy());
|
|
||||||
let Load::Loading(pending) = &mut load else {
|
|
||||||
unreachable!()
|
|
||||||
};
|
|
||||||
(&mut pending.task).await.unwrap();
|
|
||||||
load.poll();
|
|
||||||
assert_eq!((load.ready().copied(), load.message()), expected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn replacing_a_pending_load_cancels_its_request() {
|
|
||||||
let (cancelled_tx, cancelled_rx) = oneshot::channel::<()>();
|
|
||||||
let load = Load::<()>::start(
|
|
||||||
async move {
|
|
||||||
let _cancelled = cancelled_tx;
|
|
||||||
std::future::pending().await
|
|
||||||
},
|
|
||||||
FrameRequester::test_dummy(),
|
|
||||||
);
|
|
||||||
tokio::task::yield_now().await;
|
|
||||||
drop(load);
|
|
||||||
assert!(cancelled_rx.await.is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn panicking_loads_request_a_frame_and_report_interruption() {
|
|
||||||
let (draw, mut frames) = tokio::sync::broadcast::channel(/*capacity*/ 1);
|
|
||||||
let frame = FrameRequester::new(draw);
|
|
||||||
let mut load = Load::<()>::start(async { panic!("report task failed") }, frame.clone());
|
|
||||||
let Load::Loading(pending) = &mut load else {
|
|
||||||
unreachable!()
|
|
||||||
};
|
|
||||||
let _ = (&mut pending.task).await;
|
|
||||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 1), frames.recv())
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
load.poll();
|
|
||||||
assert_eq!(
|
|
||||||
load.message(),
|
|
||||||
Some("Request interrupted. Press R to retry.")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rpc_errors_do_not_expose_server_diagnostics() {
|
|
||||||
let error = codex_app_server_client::TypedRequestError::Server {
|
|
||||||
method: "thread/list".into(),
|
|
||||||
source: codex_app_server_protocol::JSONRPCErrorError {
|
|
||||||
code: -32603,
|
|
||||||
message: "Failed opening /private/workspace: token=secret".into(),
|
|
||||||
data: Some(serde_json::json!({"credential": "secret"})),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
super::error(error),
|
|
||||||
"Couldn't load analytics. Press R to retry."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn extended_chat_load_budget_still_times_out_and_can_be_cancelled() {
|
|
||||||
let (cancelled_tx, cancelled_rx) = oneshot::channel::<()>();
|
|
||||||
let mut load = Load::<()>::start_with_timeout(
|
|
||||||
async move {
|
|
||||||
let _cancelled = cancelled_tx;
|
|
||||||
std::future::pending().await
|
|
||||||
},
|
|
||||||
FrameRequester::test_dummy(),
|
|
||||||
std::time::Duration::from_secs(/*secs*/ 90),
|
|
||||||
);
|
|
||||||
tokio::task::yield_now().await;
|
|
||||||
tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 31)).await;
|
|
||||||
load.poll();
|
|
||||||
assert!(matches!(load, Load::Loading(_)));
|
|
||||||
tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 60)).await;
|
|
||||||
assert!(cancelled_rx.await.is_err());
|
|
||||||
load.poll();
|
|
||||||
assert_eq!(load.message(), Some("Request timed out. Press R to retry."));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn compact_counts_round_promote_units_and_preserve_small_adjustments() {
|
|
||||||
let values = [
|
|
||||||
0.0,
|
|
||||||
959.0,
|
|
||||||
1_000.0,
|
|
||||||
9_749.0,
|
|
||||||
2_901.0,
|
|
||||||
12_280_365_226.0,
|
|
||||||
142_300_000_000.0,
|
|
||||||
999_999.0,
|
|
||||||
999_999_999.0,
|
|
||||||
-1_250.0,
|
|
||||||
-0.000004,
|
|
||||||
1_200_000_000_000.0,
|
|
||||||
];
|
|
||||||
assert_eq!(
|
|
||||||
values.map(compact_amount),
|
|
||||||
[
|
|
||||||
"0",
|
|
||||||
"959",
|
|
||||||
"1K",
|
|
||||||
"9.7K",
|
|
||||||
"2.9K",
|
|
||||||
"12.3B",
|
|
||||||
"142.3B",
|
|
||||||
"1M",
|
|
||||||
"1B",
|
|
||||||
"-1.3K",
|
|
||||||
"-0.000004",
|
|
||||||
"1.2T"
|
|
||||||
]
|
|
||||||
.map(str::to_string)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
//! Two fixed hint rows keep report actions visible without changing chart geometry.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::sections::Section;
|
|
||||||
use crate::key_hint::key_label_spans;
|
|
||||||
use crate::keymap::ListAction;
|
|
||||||
use ratatui::style::Stylize;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn footer_lines(&self, width: usize, scrollable: bool) -> Vec<Line<'static>> {
|
|
||||||
let pair = |a, b| format!("{}/{}", self.hint(a), self.hint(b));
|
|
||||||
let mut actions = Vec::new();
|
|
||||||
if self.show_help {
|
|
||||||
actions.push((self.hint(ListAction::Cancel), "back"));
|
|
||||||
} else if !self.zoomed {
|
|
||||||
actions.push((self.hint(ListAction::Accept), "focus"));
|
|
||||||
actions.push(("tab".into(), "card"));
|
|
||||||
} else {
|
|
||||||
match self.section {
|
|
||||||
Section::Summary => {}
|
|
||||||
Section::Plan => {
|
|
||||||
actions.push((pair(ListAction::MoveUp, ListAction::MoveDown), "period"));
|
|
||||||
}
|
|
||||||
Section::Chats => {
|
|
||||||
actions.push((pair(ListAction::MoveUp, ListAction::MoveDown), "row"));
|
|
||||||
}
|
|
||||||
Section::Usage
|
|
||||||
| Section::Credits
|
|
||||||
| Section::Activity
|
|
||||||
| Section::Plugins
|
|
||||||
| Section::Skills => {
|
|
||||||
actions.push((pair(ListAction::MoveLeft, ListAction::MoveRight), "day"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let plan_details = self.section == Section::Plan
|
|
||||||
&& self
|
|
||||||
.plan
|
|
||||||
.report
|
|
||||||
.ready()
|
|
||||||
.and_then(|report| {
|
|
||||||
report.periods[self.plan.window].get(self.plan.cursor[self.plan.window])
|
|
||||||
})
|
|
||||||
.is_some();
|
|
||||||
if plan_details
|
|
||||||
|| self.day_has_details(self.section, self.sections[self.section].cursor)
|
|
||||||
|| (self.section == Section::Chats && self.chat_has_details())
|
|
||||||
{
|
|
||||||
actions.push((self.hint(ListAction::Accept), "details"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if scrollable {
|
|
||||||
actions.push((pair(ListAction::PageUp, ListAction::PageDown), "scroll"));
|
|
||||||
}
|
|
||||||
if !self.show_help {
|
|
||||||
actions.push((self.hint(ListAction::Cancel), "back"));
|
|
||||||
}
|
|
||||||
let mut navigation = if self.show_help {
|
|
||||||
vec![("?".into(), "close help")]
|
|
||||||
} else if self.visible_sections().is_empty() {
|
|
||||||
vec![("R".into(), "retry")]
|
|
||||||
} else {
|
|
||||||
vec![
|
|
||||||
(
|
|
||||||
if width >= 80 {
|
|
||||||
format!("tab/1–{}", self.visible_sections().len())
|
|
||||||
} else {
|
|
||||||
"tab".into()
|
|
||||||
},
|
|
||||||
"report",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"z".into(),
|
|
||||||
if !self.zoomed {
|
|
||||||
"focus"
|
|
||||||
} else if width < 50 {
|
|
||||||
"all"
|
|
||||||
} else {
|
|
||||||
"dashboard"
|
|
||||||
},
|
|
||||||
),
|
|
||||||
("?".into(), if width < 50 { "" } else { "help" }),
|
|
||||||
("R".into(), "refresh"),
|
|
||||||
]
|
|
||||||
};
|
|
||||||
if !self.help_shortcut_available() {
|
|
||||||
navigation.retain(|(key, _)| key != "?");
|
|
||||||
}
|
|
||||||
[actions, navigation]
|
|
||||||
.into_iter()
|
|
||||||
.map(|hints| {
|
|
||||||
let mut line = Line::default();
|
|
||||||
for (key, label) in hints {
|
|
||||||
if key.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let separator = if line.spans.is_empty() { "" } else { " · " };
|
|
||||||
let mut part = Line::from(separator.dim());
|
|
||||||
part.spans.extend(key_label_spans(&key));
|
|
||||||
if !label.is_empty() {
|
|
||||||
part.spans.push(format!(" {label}").dim());
|
|
||||||
}
|
|
||||||
if line.width() + part.width() <= width {
|
|
||||||
line.spans.extend(part.spans);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
line
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
//! Private analytics display types, independent of the app-server wire protocol.
|
|
||||||
|
|
||||||
use codex_protocol::account::PlanType;
|
|
||||||
|
|
||||||
/// Billing families match the App's consumer, business, and workspace scopes.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(super) enum AccountKind {
|
|
||||||
Consumer,
|
|
||||||
Business,
|
|
||||||
Enterprise,
|
|
||||||
Unknown,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Option<PlanType>> for AccountKind {
|
|
||||||
fn from(plan: Option<PlanType>) -> Self {
|
|
||||||
match plan {
|
|
||||||
None | Some(PlanType::Unknown) => Self::Unknown,
|
|
||||||
Some(PlanType::Sci | PlanType::SciPlus) => Self::Business,
|
|
||||||
Some(plan) if plan.is_team_like() => Self::Business,
|
|
||||||
Some(plan) if plan.is_workspace_account() => Self::Enterprise,
|
|
||||||
Some(_) => Self::Consumer,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Match the existing CLI thread-usage capability without widening other workspace reports.
|
|
||||||
pub(super) fn thread_usage_supported(plan: Option<PlanType>) -> bool {
|
|
||||||
matches!(
|
|
||||||
plan,
|
|
||||||
Some(
|
|
||||||
PlanType::Business
|
|
||||||
| PlanType::EnterpriseCbpUsageBased
|
|
||||||
| PlanType::EnterpriseCbpAutomation
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(crate) enum AccountAnalyticsReport {
|
|
||||||
Usage,
|
|
||||||
Credits,
|
|
||||||
Messages,
|
|
||||||
Plugins,
|
|
||||||
Skills,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(crate) enum AccountAnalyticsGrouping {
|
|
||||||
Feature,
|
|
||||||
Model,
|
|
||||||
Surface,
|
|
||||||
TaskStart,
|
|
||||||
Speed,
|
|
||||||
Reasoning,
|
|
||||||
TokenType,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AccountAnalyticsGrouping {
|
|
||||||
/// Credit breakdowns supported by the account's billing report.
|
|
||||||
pub(crate) fn credit_groupings(plan: Option<PlanType>) -> &'static [Self] {
|
|
||||||
match AccountKind::from(plan) {
|
|
||||||
AccountKind::Business => &[Self::Surface, Self::Model, Self::Speed],
|
|
||||||
AccountKind::Enterprise => &[Self::Surface, Self::Model, Self::Speed, Self::Reasoning],
|
|
||||||
AccountKind::Consumer => &[Self::Surface],
|
|
||||||
AccountKind::Unknown => &[],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(crate) enum AccountAnalyticsUnit {
|
|
||||||
RelativeUsage,
|
|
||||||
Credits,
|
|
||||||
Count,
|
|
||||||
Tokens,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub(crate) struct AccountAnalyticsHistory {
|
|
||||||
pub(crate) unit: AccountAnalyticsUnit,
|
|
||||||
/// Source freshness in Unix seconds, when provided. Not a completeness watermark.
|
|
||||||
pub(crate) updated_at: Option<i64>,
|
|
||||||
pub(crate) data: Vec<AccountAnalyticsDay>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub(crate) struct AccountAnalyticsDay {
|
|
||||||
/// Source reporting date; display formatting belongs to the UI.
|
|
||||||
pub(crate) date: chrono::NaiveDate,
|
|
||||||
/// Full daily denominator, including non-task usage when grouped by task start.
|
|
||||||
pub(crate) total: f64,
|
|
||||||
pub(crate) values: Vec<AccountAnalyticsValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub(crate) struct AccountAnalyticsValue {
|
|
||||||
pub(crate) key: String,
|
|
||||||
pub(crate) label: String,
|
|
||||||
pub(crate) value: f64,
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
//! Mouse actions use the most recently painted Usage layout and semantic report controls.
|
|
||||||
//! Wheel input belongs only to the body, with bounded independent report/help/dashboard offsets.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use crossterm::event::MouseButton;
|
|
||||||
use crossterm::event::MouseEvent;
|
|
||||||
use crossterm::event::MouseEventKind;
|
|
||||||
use ratatui::layout::Position;
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn invalidate_mouse_targets(&mut self) {
|
|
||||||
self.mouse_context = None;
|
|
||||||
self.tab_hits.clear();
|
|
||||||
self.control_hits.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn handle_mouse(&mut self, event: MouseEvent) {
|
|
||||||
// A report/help/dashboard transition can happen before its scheduled redraw. Old
|
|
||||||
// rectangles must not activate controls belonging to the surface being replaced.
|
|
||||||
if self.mouse_context != Some((self.section, self.show_help, self.zoomed)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let point = Position::new(event.column, event.row);
|
|
||||||
match event.kind {
|
|
||||||
MouseEventKind::ScrollDown | MouseEventKind::ScrollUp
|
|
||||||
if self.body_area.contains(point) =>
|
|
||||||
{
|
|
||||||
let offset = self.scroll_offset().min(self.max_scroll);
|
|
||||||
*self.scroll_offset_mut() = match event.kind {
|
|
||||||
MouseEventKind::ScrollDown => {
|
|
||||||
offset.saturating_add(/*rhs*/ 3).min(self.max_scroll)
|
|
||||||
}
|
|
||||||
_ => offset.saturating_sub(/*rhs*/ 3),
|
|
||||||
};
|
|
||||||
self.follow_selection = false;
|
|
||||||
}
|
|
||||||
MouseEventKind::Down(MouseButton::Left) => {
|
|
||||||
if let Some((section, _)) =
|
|
||||||
self.tab_hits.iter().find(|(_, rect)| rect.contains(point))
|
|
||||||
{
|
|
||||||
self.select_section(*section);
|
|
||||||
} else if let Some((control, _)) = self
|
|
||||||
.control_hits
|
|
||||||
.iter()
|
|
||||||
.find(|(_, rect)| rect.contains(point))
|
|
||||||
{
|
|
||||||
let control = *control;
|
|
||||||
self.follow_selection = false;
|
|
||||||
self.activate_control(control);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
//! Mouse routing, painted control bounds, and scrolling across retained report surfaces.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::analytics::controls::Control;
|
|
||||||
use codex_config::types::KeybindingSpec;
|
|
||||||
use codex_config::types::KeybindingsSpec;
|
|
||||||
use codex_config::types::TuiKeymap;
|
|
||||||
use crossterm::event::MouseButton;
|
|
||||||
use crossterm::event::MouseEvent;
|
|
||||||
use crossterm::event::MouseEventKind;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use ratatui::layout::Rect;
|
|
||||||
|
|
||||||
fn mouse_at(view: &mut AnalyticsView, kind: MouseEventKind, area: Rect) {
|
|
||||||
view.handle_mouse(MouseEvent {
|
|
||||||
kind,
|
|
||||||
column: area.x,
|
|
||||||
row: area.y,
|
|
||||||
modifiers: KeyModifiers::NONE,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn mouse_routing_keeps_clipped_tabs_and_refresh_targets_account_scoped() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
screen(&mut view, /*width*/ 100, /*height*/ 24);
|
|
||||||
let (_, tab) = view
|
|
||||||
.tab_hits
|
|
||||||
.iter()
|
|
||||||
.find(|(section, _)| *section == Section::Plugins)
|
|
||||||
.unwrap();
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui().unwrap();
|
|
||||||
view.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
TuiEvent::Mouse(MouseEvent {
|
|
||||||
kind: MouseEventKind::Down(MouseButton::Left),
|
|
||||||
column: tab.x,
|
|
||||||
row: tab.y,
|
|
||||||
modifiers: KeyModifiers::NONE,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(view.section, Section::Plugins);
|
|
||||||
screen(&mut view, /*width*/ 20, /*height*/ 12);
|
|
||||||
let (_, tab) = view.tab_hits[0];
|
|
||||||
mouse_at(&mut view, MouseEventKind::Down(MouseButton::Left), tab);
|
|
||||||
assert_eq!(view.section, Section::Plugins);
|
|
||||||
|
|
||||||
screen(&mut view, /*width*/ 100, /*height*/ 24);
|
|
||||||
let targets = view.control_hits.clone();
|
|
||||||
assert!(!targets.is_empty());
|
|
||||||
let before = (view.section, view.ranges);
|
|
||||||
press(&mut view, KeyCode::Char('R'));
|
|
||||||
for (_, rect) in targets {
|
|
||||||
mouse_at(&mut view, MouseEventKind::Down(MouseButton::Left), rect);
|
|
||||||
}
|
|
||||||
assert_eq!((view.section, view.ranges), before);
|
|
||||||
assert!(matches!(view.account, Load::Unavailable));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn clipped_controls_ignore_remapped_keys_and_obsolete_frames() {
|
|
||||||
let mut config = TuiKeymap::default();
|
|
||||||
config.list.cancel = Some(KeybindingsSpec::One(KeybindingSpec("r".into())));
|
|
||||||
config.list.accept = Some(KeybindingsSpec::Many(Vec::new()));
|
|
||||||
config.list.move_left = Some(KeybindingsSpec::Many(Vec::new()));
|
|
||||||
config.list.move_right = Some(KeybindingsSpec::Many(Vec::new()));
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
view.keymap = RuntimeKeymap::from_config(&config).unwrap().list;
|
|
||||||
screen(&mut view, /*width*/ 100, /*height*/ 24);
|
|
||||||
let (_, range) = *view
|
|
||||||
.control_hits
|
|
||||||
.iter()
|
|
||||||
.find(|(control, _)| *control == Control::Range)
|
|
||||||
.unwrap();
|
|
||||||
mouse_at(&mut view, MouseEventKind::Down(MouseButton::Left), range);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.ranges[view.range_group(Section::Usage) as usize],
|
|
||||||
view.is_done
|
|
||||||
),
|
|
||||||
(1, false)
|
|
||||||
);
|
|
||||||
|
|
||||||
press(&mut view, KeyCode::Char('z'));
|
|
||||||
screen(&mut view, /*width*/ 100, /*height*/ 24);
|
|
||||||
let (_, dashboard) = *view
|
|
||||||
.control_hits
|
|
||||||
.iter()
|
|
||||||
.find(|(control, _)| *control == Control::Dashboard)
|
|
||||||
.unwrap();
|
|
||||||
mouse_at(
|
|
||||||
&mut view,
|
|
||||||
MouseEventKind::Down(MouseButton::Left),
|
|
||||||
dashboard,
|
|
||||||
);
|
|
||||||
assert!(view.zoomed);
|
|
||||||
|
|
||||||
view.plan.enabled = true;
|
|
||||||
view.select_section(Section::Plan);
|
|
||||||
view.plan.cursor = [2, 4];
|
|
||||||
let retained = view.plan.cursor;
|
|
||||||
for width in [58, 14] {
|
|
||||||
view.plan.window = 0;
|
|
||||||
screen(&mut view, width, /*height*/ 20);
|
|
||||||
let (_, hit) = *view
|
|
||||||
.control_hits
|
|
||||||
.iter()
|
|
||||||
.find(|(control, _)| *control == Control::PlanWindow)
|
|
||||||
.unwrap();
|
|
||||||
mouse_at(
|
|
||||||
&mut view,
|
|
||||||
MouseEventKind::Down(MouseButton::Left),
|
|
||||||
Rect {
|
|
||||||
x: hit.right(),
|
|
||||||
..hit
|
|
||||||
},
|
|
||||||
);
|
|
||||||
assert_eq!(view.plan.window, 0);
|
|
||||||
let last_painted = Rect {
|
|
||||||
x: hit.right() - 1,
|
|
||||||
..hit
|
|
||||||
};
|
|
||||||
mouse_at(
|
|
||||||
&mut view,
|
|
||||||
MouseEventKind::Down(MouseButton::Left),
|
|
||||||
last_painted,
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
(view.plan.window, view.plan.cursor, view.is_done),
|
|
||||||
(1, retained, false)
|
|
||||||
);
|
|
||||||
mouse_at(
|
|
||||||
&mut view,
|
|
||||||
MouseEventKind::Down(MouseButton::Left),
|
|
||||||
last_painted,
|
|
||||||
);
|
|
||||||
assert_eq!(view.plan.window, 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn wheel_scrolls_only_the_painted_body_within_its_bounds() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
view.follow_selection = false;
|
|
||||||
screen(&mut view, /*width*/ 58, /*height*/ 12);
|
|
||||||
assert!(view.max_scroll > 3);
|
|
||||||
let body = view.body_area;
|
|
||||||
let tab = view.tab_hits[0].1;
|
|
||||||
mouse_at(&mut view, MouseEventKind::ScrollDown, tab);
|
|
||||||
assert_eq!(view.scroll_offset(), 0);
|
|
||||||
mouse_at(&mut view, MouseEventKind::ScrollDown, body);
|
|
||||||
assert_eq!(view.scroll_offset(), 3);
|
|
||||||
*view.scroll_offset_mut() = view.max_scroll;
|
|
||||||
mouse_at(&mut view, MouseEventKind::ScrollDown, body);
|
|
||||||
assert_eq!(view.scroll_offset(), view.max_scroll);
|
|
||||||
mouse_at(&mut view, MouseEventKind::ScrollUp, body);
|
|
||||||
assert_eq!(view.scroll_offset(), view.max_scroll - 3);
|
|
||||||
assert!(!view.follow_selection);
|
|
||||||
let reading = view.scroll_offset();
|
|
||||||
|
|
||||||
press(&mut view, KeyCode::Char('?'));
|
|
||||||
mouse_at(&mut view, MouseEventKind::ScrollDown, body);
|
|
||||||
assert_eq!(view.scroll_offset(), 0);
|
|
||||||
screen(&mut view, /*width*/ 58, /*height*/ 12);
|
|
||||||
let help_body = view.body_area;
|
|
||||||
mouse_at(&mut view, MouseEventKind::ScrollDown, help_body);
|
|
||||||
assert_eq!(view.scroll_offset(), 3);
|
|
||||||
press(&mut view, KeyCode::Esc);
|
|
||||||
assert_eq!(view.scroll_offset(), reading);
|
|
||||||
}
|
|
||||||
@@ -1,326 +0,0 @@
|
|||||||
//! Vim navigation aliases share arrow behavior while preserving configured bindings.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::analytics::models::AccountKind;
|
|
||||||
use codex_config::types::KeybindingSpec;
|
|
||||||
use codex_config::types::KeybindingsSpec;
|
|
||||||
use codex_config::types::TuiKeymap;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
fn navigate(views: &mut [AnalyticsView; 2], keys: &[(char, KeyCode)], size: (u16, u16)) -> String {
|
|
||||||
let mut output = String::new();
|
|
||||||
for &(alias, arrow) in keys {
|
|
||||||
press(&mut views[0], KeyCode::Char(alias));
|
|
||||||
press(&mut views[1], arrow);
|
|
||||||
output = screen(&mut views[0], size.0, size.1);
|
|
||||||
assert_eq!(output, screen(&mut views[1], size.0, size.1), "{alias}");
|
|
||||||
}
|
|
||||||
output
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vim_chart_navigation_matches_arrows_in_focused_and_dashboard_views() {
|
|
||||||
for (kind, section) in [
|
|
||||||
(AccountKind::Consumer, Section::Usage),
|
|
||||||
(AccountKind::Consumer, Section::Activity),
|
|
||||||
(AccountKind::Consumer, Section::Plugins),
|
|
||||||
(AccountKind::Consumer, Section::Skills),
|
|
||||||
(AccountKind::Business, Section::Usage),
|
|
||||||
(AccountKind::Business, Section::Credits),
|
|
||||||
] {
|
|
||||||
for zoomed in [true, false] {
|
|
||||||
let mut views = [fixture::view(kind), fixture::view(kind)];
|
|
||||||
for view in &mut views {
|
|
||||||
view.section = section;
|
|
||||||
view.zoomed = zoomed;
|
|
||||||
view.sections[section].cursor = 3;
|
|
||||||
view.sections[section].detail = Some(3);
|
|
||||||
}
|
|
||||||
navigate(
|
|
||||||
&mut views,
|
|
||||||
&[
|
|
||||||
('h', KeyCode::Left),
|
|
||||||
('h', KeyCode::Left),
|
|
||||||
('l', KeyCode::Right),
|
|
||||||
('j', KeyCode::Down),
|
|
||||||
('k', KeyCode::Up),
|
|
||||||
],
|
|
||||||
/*size*/ (96, 32),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
views[0].section,
|
|
||||||
views[0].sections[section].cursor,
|
|
||||||
views[0].sections[section].detail
|
|
||||||
),
|
|
||||||
(section, 2, Some(2))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vim_plan_navigation_preserves_independent_windows_and_collapses_old_details() {
|
|
||||||
let mut views = [
|
|
||||||
fixture::view(AccountKind::Consumer),
|
|
||||||
fixture::view(AccountKind::Consumer),
|
|
||||||
];
|
|
||||||
for view in &mut views {
|
|
||||||
let as_of = "2026-09-02T12:00:00Z"
|
|
||||||
.parse::<chrono::DateTime<chrono::Utc>>()
|
|
||||||
.unwrap();
|
|
||||||
view.plan.enabled = true;
|
|
||||||
view.plan.report = Load::Ready(plan::Report {
|
|
||||||
as_of,
|
|
||||||
coverage_start: None,
|
|
||||||
coverage_complete: true,
|
|
||||||
approximate: false,
|
|
||||||
periods: std::array::from_fn(|window| {
|
|
||||||
let length = if window == 0 {
|
|
||||||
chrono::Duration::hours(/*hours*/ 5)
|
|
||||||
} else {
|
|
||||||
chrono::Duration::days(/*days*/ 7)
|
|
||||||
};
|
|
||||||
(0..2)
|
|
||||||
.map(|index| plan::Period {
|
|
||||||
id: format!("{window}-{index}"),
|
|
||||||
start: as_of - length * index,
|
|
||||||
end: as_of - length * index + length,
|
|
||||||
complete: true,
|
|
||||||
used: Some(2500.0),
|
|
||||||
breakdowns: None,
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
view.plan.poll();
|
|
||||||
view.plan.expanded = [Some("0-0".into()), Some("1-0".into())];
|
|
||||||
view.section = Section::Plan;
|
|
||||||
}
|
|
||||||
navigate(
|
|
||||||
&mut views,
|
|
||||||
&[
|
|
||||||
('l', KeyCode::Right),
|
|
||||||
('j', KeyCode::Down),
|
|
||||||
('k', KeyCode::Up),
|
|
||||||
('h', KeyCode::Left),
|
|
||||||
('j', KeyCode::Down),
|
|
||||||
],
|
|
||||||
/*size*/ (120, 30),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
views[0].plan.window,
|
|
||||||
views[0].plan.cursor,
|
|
||||||
&views[0].plan.expanded
|
|
||||||
),
|
|
||||||
(0, [1, 0], &[None, None])
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vim_summary_navigation_scrolls_like_arrows() {
|
|
||||||
let mut views = [
|
|
||||||
fixture::view(AccountKind::Consumer),
|
|
||||||
fixture::view(AccountKind::Consumer),
|
|
||||||
];
|
|
||||||
for view in &mut views {
|
|
||||||
view.section = Section::Summary;
|
|
||||||
view.profile = Load::Ready(
|
|
||||||
serde_json::from_value(json!({
|
|
||||||
"stats": {"lifetime_tokens": 123, "daily_usage_buckets": [
|
|
||||||
{"start_date": "2026-09-02", "tokens": 123}
|
|
||||||
]}
|
|
||||||
}))
|
|
||||||
.unwrap(),
|
|
||||||
);
|
|
||||||
assert!(screen(view, /*width*/ 64, /*height*/ 18).contains("scroll"));
|
|
||||||
}
|
|
||||||
navigate(
|
|
||||||
&mut views,
|
|
||||||
&[
|
|
||||||
('h', KeyCode::Left),
|
|
||||||
('l', KeyCode::Right),
|
|
||||||
('j', KeyCode::Down),
|
|
||||||
('j', KeyCode::Down),
|
|
||||||
('k', KeyCode::Up),
|
|
||||||
],
|
|
||||||
/*size*/ (64, 18),
|
|
||||||
);
|
|
||||||
assert_eq!(views[0].scroll_offset(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vim_chat_navigation_expands_collapses_and_moves_like_arrows() {
|
|
||||||
for kind in [AccountKind::Consumer, AccountKind::Business] {
|
|
||||||
let mut views = [fixture::view(kind), fixture::view(kind)];
|
|
||||||
for view in &mut views {
|
|
||||||
view.section = Section::Chats;
|
|
||||||
if kind == AccountKind::Consumer {
|
|
||||||
view.tasks = Load::Ready(tasks::Chats {
|
|
||||||
rows: (0..2)
|
|
||||||
.map(|index| tasks::Chat {
|
|
||||||
title: format!("Example chat {index}"),
|
|
||||||
task: Some(
|
|
||||||
serde_json::from_value(json!({
|
|
||||||
"thread_id": format!("chat-{index}"),
|
|
||||||
"data_status": "available", "usage_source": "accounting",
|
|
||||||
"weekly_limit_percent": 20 - index,
|
|
||||||
"five_hour_limit_percent": null, "balance_usage_credits": null,
|
|
||||||
"groups": []
|
|
||||||
}))
|
|
||||||
.unwrap(),
|
|
||||||
),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
..tasks::Chats::default()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
navigate(
|
|
||||||
&mut views,
|
|
||||||
&[
|
|
||||||
('l', KeyCode::Right),
|
|
||||||
('h', KeyCode::Left),
|
|
||||||
('l', KeyCode::Right),
|
|
||||||
('j', KeyCode::Down),
|
|
||||||
('l', KeyCode::Right),
|
|
||||||
('k', KeyCode::Up),
|
|
||||||
],
|
|
||||||
/*size*/ (96, 32),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
views[0].sections[Section::Chats].cursor,
|
|
||||||
views[0].sections[Section::Chats].detail
|
|
||||||
),
|
|
||||||
(0, None)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn configured_dashboard_accept_precedes_report_shortcuts() {
|
|
||||||
for binding in ["r", "g", "m", "R", "tab", "1"] {
|
|
||||||
let mut config = TuiKeymap::default();
|
|
||||||
config.list.accept = Some(KeybindingsSpec::One(KeybindingSpec(binding.into())));
|
|
||||||
let mut view = fixture::view(AccountKind::Business);
|
|
||||||
view.keymap = RuntimeKeymap::from_config(&config).unwrap().list;
|
|
||||||
view.section = Section::Usage;
|
|
||||||
view.zoomed = false;
|
|
||||||
let previous = (
|
|
||||||
view.section,
|
|
||||||
view.ranges,
|
|
||||||
view.sections[Section::Usage].group,
|
|
||||||
);
|
|
||||||
let key = if binding == "tab" {
|
|
||||||
KeyCode::Tab
|
|
||||||
} else {
|
|
||||||
KeyCode::Char(binding.chars().next().unwrap())
|
|
||||||
};
|
|
||||||
press(&mut view, key);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.zoomed,
|
|
||||||
view.section,
|
|
||||||
view.ranges,
|
|
||||||
view.sections[Section::Usage].group
|
|
||||||
),
|
|
||||||
(true, previous.0, previous.1, previous.2),
|
|
||||||
"{binding}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn configured_question_mark_keeps_its_action_and_hides_help_hint() {
|
|
||||||
for (binding, modifiers) in [("?", KeyModifiers::NONE), ("shift-?", KeyModifiers::SHIFT)] {
|
|
||||||
let mut config = TuiKeymap::default();
|
|
||||||
config.list.cancel = Some(KeybindingsSpec::One(KeybindingSpec(binding.into())));
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.keymap = RuntimeKeymap::from_config(&config).unwrap().list;
|
|
||||||
let footer = view.footer_lines(/*width*/ 120, /*scrollable*/ false);
|
|
||||||
assert!(
|
|
||||||
!footer
|
|
||||||
.iter()
|
|
||||||
.any(|line| line.to_string().contains("? help"))
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
!view
|
|
||||||
.help_lines(/*width*/ 120)
|
|
||||||
.iter()
|
|
||||||
.any(|line| line.to_string().contains("toggle this help"))
|
|
||||||
);
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Char('?'), modifiers));
|
|
||||||
assert_eq!((view.is_done, view.show_help), (true, false));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn configured_vim_keys_win_over_horizontal_aliases() {
|
|
||||||
let mut config = TuiKeymap::default();
|
|
||||||
config.list.jump_top = Some(KeybindingsSpec::Many(vec![
|
|
||||||
KeybindingSpec("h".into()),
|
|
||||||
KeybindingSpec("l".into()),
|
|
||||||
]));
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.keymap = RuntimeKeymap::from_config(&config).unwrap().list;
|
|
||||||
for alias in ['h', 'l'] {
|
|
||||||
view.sections[Section::Usage].cursor = 3;
|
|
||||||
press(&mut view, KeyCode::Char(alias));
|
|
||||||
assert_eq!(view.sections[Section::Usage].cursor, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vim_aliases_respect_removed_and_remapped_arrows() {
|
|
||||||
let mut config = TuiKeymap::default();
|
|
||||||
config.list.move_left = Some(KeybindingsSpec::Many(Vec::new()));
|
|
||||||
config.list.move_right = Some(KeybindingsSpec::Many(Vec::new()));
|
|
||||||
config.list.move_up = Some(KeybindingsSpec::One(KeybindingSpec("up".into())));
|
|
||||||
config.list.move_down = Some(KeybindingsSpec::One(KeybindingSpec("down".into())));
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.keymap = RuntimeKeymap::from_config(&config).unwrap().list;
|
|
||||||
view.sections[Section::Usage].cursor = 3;
|
|
||||||
for alias in ['h', 'j', 'k', 'l'] {
|
|
||||||
press(&mut view, KeyCode::Char(alias));
|
|
||||||
assert_eq!(view.sections[Section::Usage].cursor, 3);
|
|
||||||
}
|
|
||||||
|
|
||||||
config.list.move_up = Some(KeybindingsSpec::One(KeybindingSpec("right".into())));
|
|
||||||
config.list.move_down = Some(KeybindingsSpec::One(KeybindingSpec("left".into())));
|
|
||||||
view.keymap = RuntimeKeymap::from_config(&config).unwrap().list;
|
|
||||||
press(&mut view, KeyCode::Char('h'));
|
|
||||||
assert_eq!(view.sections[Section::Usage].cursor, 4);
|
|
||||||
press(&mut view, KeyCode::Char('l'));
|
|
||||||
assert_eq!(view.sections[Section::Usage].cursor, 3);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn horizontal_aliases_ignore_modifiers_and_release_but_accept_repeat() {
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.sections[Section::Usage].cursor = 3;
|
|
||||||
for alias in ['h', 'l'] {
|
|
||||||
for modifiers in [
|
|
||||||
KeyModifiers::ALT,
|
|
||||||
KeyModifiers::SHIFT,
|
|
||||||
KeyModifiers::CONTROL | KeyModifiers::ALT,
|
|
||||||
] {
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Char(alias), modifiers));
|
|
||||||
assert_eq!(view.sections[Section::Usage].cursor, 3);
|
|
||||||
}
|
|
||||||
view.handle_key(KeyEvent {
|
|
||||||
kind: KeyEventKind::Release,
|
|
||||||
..KeyEvent::new(KeyCode::Char(alias), KeyModifiers::NONE)
|
|
||||||
});
|
|
||||||
assert_eq!(view.sections[Section::Usage].cursor, 3);
|
|
||||||
}
|
|
||||||
for (alias, cursor) in [('h', 2), ('l', 3)] {
|
|
||||||
view.handle_key(KeyEvent {
|
|
||||||
kind: KeyEventKind::Repeat,
|
|
||||||
..KeyEvent::new(KeyCode::Char(alias), KeyModifiers::NONE)
|
|
||||||
});
|
|
||||||
assert_eq!(view.sections[Section::Usage].cursor, cursor);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,364 +0,0 @@
|
|||||||
//! Converts backend reports into display data while preserving missing values and full denominators.
|
|
||||||
|
|
||||||
use super::models::AccountAnalyticsGrouping as Grouping;
|
|
||||||
use super::models::AccountAnalyticsReport as Report;
|
|
||||||
use super::models::*;
|
|
||||||
use super::report_data::AnalyticsData;
|
|
||||||
use chrono::DateTime;
|
|
||||||
use chrono::NaiveDate;
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
/// Out-of-range legacy rows do not change attribution semantics for the requested period.
|
|
||||||
pub(super) fn has_complete_attribution(
|
|
||||||
response: &AnalyticsData,
|
|
||||||
start: NaiveDate,
|
|
||||||
end: NaiveDate,
|
|
||||||
) -> Result<bool, String> {
|
|
||||||
response
|
|
||||||
.data
|
|
||||||
.iter()
|
|
||||||
.try_fold(/*init*/ true, |complete, record| {
|
|
||||||
let date = NaiveDate::parse_from_str(
|
|
||||||
record.date.get(..10).unwrap_or(&record.date),
|
|
||||||
"%Y-%m-%d",
|
|
||||||
)
|
|
||||||
.map_err(|_| String::from("Analytics returned an invalid date."))?;
|
|
||||||
Ok(complete && (date < start || date > end || record.attribution.is_some()))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn history(
|
|
||||||
response: AnalyticsData,
|
|
||||||
report: Report,
|
|
||||||
grouping: Grouping,
|
|
||||||
start: NaiveDate,
|
|
||||||
end: NaiveDate,
|
|
||||||
) -> Result<Option<AccountAnalyticsHistory>, String> {
|
|
||||||
if report == Report::Messages {
|
|
||||||
match grouping {
|
|
||||||
Grouping::Model | Grouping::Surface => {}
|
|
||||||
Grouping::Feature
|
|
||||||
| Grouping::TaskStart
|
|
||||||
| Grouping::Speed
|
|
||||||
| Grouping::Reasoning
|
|
||||||
| Grouping::TokenType => {
|
|
||||||
return Err(String::from("Unsupported message count grouping."));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let attributed = has_complete_attribution(&response, start, end)?;
|
|
||||||
let series = response.series.as_ref();
|
|
||||||
let mut days: BTreeMap<NaiveDate, (f64, BTreeMap<String, f64>)> = BTreeMap::new();
|
|
||||||
for record in response.data {
|
|
||||||
let date =
|
|
||||||
NaiveDate::parse_from_str(record.date.get(..10).unwrap_or(&record.date), "%Y-%m-%d")
|
|
||||||
.map_err(|_| String::from("Analytics returned an invalid date."))?;
|
|
||||||
if date < start || date > end {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let (total, values) = days.entry(date).or_default();
|
|
||||||
match report {
|
|
||||||
Report::Usage => {
|
|
||||||
let daily = if attributed {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
match grouping {
|
|
||||||
Grouping::Surface => record.product_surface_usage_values,
|
|
||||||
Grouping::Model => record
|
|
||||||
.models
|
|
||||||
.map(|models| -> Result<_, String> {
|
|
||||||
let mut values = BTreeMap::new();
|
|
||||||
for model in models {
|
|
||||||
let amount = model
|
|
||||||
.credits
|
|
||||||
.ok_or("Plan usage amount was not reported.")?;
|
|
||||||
*values.entry(model.model).or_insert(/*default*/ 0.0) += amount;
|
|
||||||
}
|
|
||||||
Ok(values)
|
|
||||||
})
|
|
||||||
.transpose()?,
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Some(daily) = daily {
|
|
||||||
for (key, amount) in daily {
|
|
||||||
if !amount.is_finite() || amount < 0.0 {
|
|
||||||
return Err(String::from("Analytics returned an invalid amount."));
|
|
||||||
}
|
|
||||||
let key = if grouping == Grouping::Surface {
|
|
||||||
if key.starts_with("work_") {
|
|
||||||
"work"
|
|
||||||
} else {
|
|
||||||
"codex"
|
|
||||||
}
|
|
||||||
.to_string()
|
|
||||||
} else if key.eq_ignore_ascii_case("other") {
|
|
||||||
"other".to_string()
|
|
||||||
} else {
|
|
||||||
key
|
|
||||||
};
|
|
||||||
*total += amount;
|
|
||||||
*values.entry(key).or_default() += amount;
|
|
||||||
}
|
|
||||||
} else if let Some(attribution) = record.attribution.filter(|_| attributed) {
|
|
||||||
for entry in attribution {
|
|
||||||
if !entry.value.is_finite() || entry.value < 0.0 {
|
|
||||||
return Err(String::from("Analytics returned an invalid amount."));
|
|
||||||
}
|
|
||||||
*total += entry.value;
|
|
||||||
let key = match grouping {
|
|
||||||
Grouping::Feature => entry.thread_source,
|
|
||||||
Grouping::Model => entry.model,
|
|
||||||
Grouping::Surface => entry.surface,
|
|
||||||
Grouping::TaskStart => {
|
|
||||||
entry.turn_trigger.map(|trigger| format!("start-{trigger}"))
|
|
||||||
}
|
|
||||||
Grouping::Speed | Grouping::Reasoning | Grouping::TokenType => {
|
|
||||||
return Err(String::from("unsupported analytics grouping"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.unwrap_or_else(|| "unknown".to_string());
|
|
||||||
*values.entry(key).or_default() += entry.value;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Report::Credits => {
|
|
||||||
if series.is_some() {
|
|
||||||
let Some(credits) = record.values else {
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
for (key, amount) in credits {
|
|
||||||
*values.entry(key).or_default() += amount;
|
|
||||||
*total += amount;
|
|
||||||
}
|
|
||||||
} else if matches!(grouping, Grouping::Model | Grouping::Speed) {
|
|
||||||
let Some(models) = record.models else {
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
for model in models {
|
|
||||||
let amount = model.on_demand_credits.unwrap_or(/*default*/ 0.0);
|
|
||||||
let key = if grouping == Grouping::Speed {
|
|
||||||
model.speed.unwrap_or_else(|| "unknown".to_string())
|
|
||||||
} else {
|
|
||||||
model.model
|
|
||||||
};
|
|
||||||
*values.entry(key).or_default() += amount;
|
|
||||||
*total += amount;
|
|
||||||
}
|
|
||||||
} else if let Some(premium) = record.premium_usage_values {
|
|
||||||
for (surface, amount) in premium.credit_usage_credits {
|
|
||||||
if !amount.is_finite() {
|
|
||||||
return Err(String::from("Analytics returned an invalid amount."));
|
|
||||||
}
|
|
||||||
*values.entry(surface).or_default() += amount;
|
|
||||||
*total += amount;
|
|
||||||
}
|
|
||||||
} else if let (Some(amount), Some(surface)) =
|
|
||||||
(record.credit_amount, record.product_surface)
|
|
||||||
{
|
|
||||||
*values.entry(surface).or_default() += amount;
|
|
||||||
*total += amount;
|
|
||||||
} else {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Report::Messages => {
|
|
||||||
let authoritative = record
|
|
||||||
.totals
|
|
||||||
.ok_or_else(|| String::from("Message count is unavailable."))?
|
|
||||||
.turns;
|
|
||||||
if !authoritative.is_finite() || authoritative < 0.0 {
|
|
||||||
return Err(String::from("Analytics returned an invalid amount."));
|
|
||||||
}
|
|
||||||
let mut record_values = BTreeMap::<String, f64>::new();
|
|
||||||
if grouping == Grouping::Model {
|
|
||||||
for model in record.models.unwrap_or_default() {
|
|
||||||
let key = if model.model.eq_ignore_ascii_case("codex-auto-review")
|
|
||||||
|| model.model.eq_ignore_ascii_case("other")
|
|
||||||
{
|
|
||||||
"other".to_string()
|
|
||||||
} else {
|
|
||||||
model.model
|
|
||||||
};
|
|
||||||
let count = model
|
|
||||||
.turns
|
|
||||||
.ok_or_else(|| String::from("Turn count is unavailable."))?;
|
|
||||||
if !count.is_finite() || count < 0.0 {
|
|
||||||
return Err(String::from("Analytics returned an invalid amount."));
|
|
||||||
}
|
|
||||||
*record_values.entry(key).or_default() += count;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for client in record.clients.unwrap_or_default() {
|
|
||||||
if !client.turns.is_finite() || client.turns < 0.0 {
|
|
||||||
return Err(String::from("Analytics returned an invalid amount."));
|
|
||||||
}
|
|
||||||
let key = match client.client_id.as_str() {
|
|
||||||
"CODEX_CLI" => "cli",
|
|
||||||
"CODEX_IDE_VSCODE" => "vscode",
|
|
||||||
"CODEX_WEB" => "web",
|
|
||||||
"CODEX_DESKTOP_APP" | "CODEX_WORK_DESKTOP" => "desktop_app",
|
|
||||||
"CODEX_WORK_WEB" => "work_web",
|
|
||||||
"CODEX_WORK_MOBILE" => "mobile",
|
|
||||||
"CODEX_GITHUB" => "github_code_review",
|
|
||||||
_ => "other",
|
|
||||||
};
|
|
||||||
*record_values.entry(key.to_string()).or_default() += client.turns;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let remainder =
|
|
||||||
(authoritative - record_values.values().sum::<f64>()).max(/*other*/ 0.0);
|
|
||||||
if remainder > 0.0 {
|
|
||||||
*record_values.entry("other".to_string()).or_default() += remainder;
|
|
||||||
}
|
|
||||||
for (key, count) in record_values {
|
|
||||||
*values.entry(key).or_default() += count;
|
|
||||||
}
|
|
||||||
*total += authoritative;
|
|
||||||
}
|
|
||||||
Report::Plugins | Report::Skills => {
|
|
||||||
let overviews = if report == Report::Skills {
|
|
||||||
record.skill_usage_overviews
|
|
||||||
} else {
|
|
||||||
record.plugin_usage_overviews
|
|
||||||
}
|
|
||||||
.ok_or_else(|| String::from("Tool activity is unavailable."))?;
|
|
||||||
for tool in overviews {
|
|
||||||
if !tool.invocation_counts.is_finite() || tool.invocation_counts < 0.0 {
|
|
||||||
return Err(String::from("Analytics returned an invalid amount."));
|
|
||||||
}
|
|
||||||
*values.entry(tool.display_name).or_default() += tool.invocation_counts;
|
|
||||||
*total += tool.invocation_counts;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !total.is_finite()
|
|
||||||
|| values
|
|
||||||
.values()
|
|
||||||
.any(|value| !value.is_finite() || (report != Report::Credits && *value < 0.0))
|
|
||||||
{
|
|
||||||
return Err(String::from("Analytics returned an invalid amount."));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if report == Report::Usage
|
|
||||||
&& !attributed
|
|
||||||
&& grouping == Grouping::Model
|
|
||||||
&& response.units.as_deref() != Some("credits")
|
|
||||||
{
|
|
||||||
let mut totals = BTreeMap::<String, f64>::new();
|
|
||||||
for (_, values) in days.values() {
|
|
||||||
for (key, value) in values {
|
|
||||||
*totals.entry(key.clone()).or_default() += value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let total: f64 = totals.values().sum();
|
|
||||||
for (_, values) in days.values_mut() {
|
|
||||||
let mut other = 0.0;
|
|
||||||
values.retain(|key, value| {
|
|
||||||
let amount = totals[key];
|
|
||||||
if key.eq_ignore_ascii_case("other") || (amount > 0.0 && amount < total * 0.01) {
|
|
||||||
other += *value;
|
|
||||||
false
|
|
||||||
} else {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if other > 0.0 {
|
|
||||||
values.insert("other".to_string(), other);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if report == Report::Credits {
|
|
||||||
for date in start.iter_days().take_while(|date| *date <= end) {
|
|
||||||
days.entry(date).or_default();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(Some(AccountAnalyticsHistory {
|
|
||||||
unit: match report {
|
|
||||||
Report::Usage if !attributed && response.units.as_deref() == Some("credits") => {
|
|
||||||
AccountAnalyticsUnit::Credits
|
|
||||||
}
|
|
||||||
Report::Usage => AccountAnalyticsUnit::RelativeUsage,
|
|
||||||
Report::Credits => AccountAnalyticsUnit::Credits,
|
|
||||||
Report::Messages | Report::Plugins | Report::Skills => AccountAnalyticsUnit::Count,
|
|
||||||
},
|
|
||||||
updated_at: response
|
|
||||||
.data_freshness_ts
|
|
||||||
.as_deref()
|
|
||||||
.and_then(|timestamp| DateTime::parse_from_rfc3339(timestamp).ok())
|
|
||||||
.map(|timestamp| timestamp.timestamp()),
|
|
||||||
data: days
|
|
||||||
.into_iter()
|
|
||||||
.map(|(date, (total, values))| AccountAnalyticsDay {
|
|
||||||
date,
|
|
||||||
total,
|
|
||||||
values: values
|
|
||||||
.into_iter()
|
|
||||||
.map(|(key, value)| AccountAnalyticsValue {
|
|
||||||
label: series
|
|
||||||
.and_then(|series| series.iter().find(|series| series.key == key))
|
|
||||||
.map(|series| series.label.clone())
|
|
||||||
.unwrap_or_else(|| label(&key).to_string()),
|
|
||||||
key,
|
|
||||||
value,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn label(key: &str) -> &str {
|
|
||||||
match key {
|
|
||||||
"user" => "Tasks",
|
|
||||||
"subagent" => "Subagents",
|
|
||||||
"image_generation" => "Image generation",
|
|
||||||
"automation" => "Automations",
|
|
||||||
"guardian_review" => "Auto review",
|
|
||||||
"guardian_classifier" => "Auto review classifier",
|
|
||||||
"thread_title" => "Thread title",
|
|
||||||
"system" => "System",
|
|
||||||
"automated_review" => "Auto review",
|
|
||||||
"agent_identity" => "Workspace agents",
|
|
||||||
"memory_consolidation" => "Memory consolidation",
|
|
||||||
"cli" => "CLI",
|
|
||||||
"desktop_app" => "Desktop app",
|
|
||||||
"vscode" => "VS Code",
|
|
||||||
"web" => "Web",
|
|
||||||
"work_web" => "Work web",
|
|
||||||
"work_desktop" => "Work desktop",
|
|
||||||
"work_mobile" => "Work mobile",
|
|
||||||
"mobile" => "Mobile",
|
|
||||||
"slack" => "Slack",
|
|
||||||
"linear" => "Linear",
|
|
||||||
"jetbrains" => "JetBrains",
|
|
||||||
"sdk" => "SDK",
|
|
||||||
"exec" => "Exec",
|
|
||||||
"github" => "GitHub",
|
|
||||||
"codex" => "Codex",
|
|
||||||
"work" => "Work",
|
|
||||||
"code_review" | "github_code_review" => "Code review",
|
|
||||||
"start-user" | "start-composer" => "User messages",
|
|
||||||
"start-goal" => "Goals",
|
|
||||||
"start-composer_queue" => "Queued messages",
|
|
||||||
"start-composer_queue_run_now" => "Queued messages run now",
|
|
||||||
"start-automation_cron_scheduled" => "Scheduled automations",
|
|
||||||
"start-automation_cron_run_now" => "Automations run now",
|
|
||||||
"start-automation_heartbeat_scheduled" => "Scheduled follow-ups",
|
|
||||||
"start-automation_heartbeat_run_now" => "Follow-ups run now",
|
|
||||||
"start-app_tool_create_thread" => "Agent-created tasks",
|
|
||||||
"start-app_tool_send_message" => "Agent follow-ups",
|
|
||||||
"unknown" | "start-unknown" => "Unknown",
|
|
||||||
"fast" => "Fast",
|
|
||||||
"standard" => "Standard",
|
|
||||||
"other" | "start-other" => "Other",
|
|
||||||
_ => key,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "normalize_tests.rs"]
|
|
||||||
mod tests;
|
|
||||||
@@ -1,358 +0,0 @@
|
|||||||
//! Regression coverage for daily report normalization and billing semantics.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn turn_start_includes_all_features_and_missing_attribution_is_unavailable() {
|
|
||||||
let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap();
|
|
||||||
let response = serde_json::from_value(json!({"data": [{"date": "2026-01-09", "attribution": [
|
|
||||||
{"thread_source": "user", "turn_trigger": "composer", "value": 30},
|
|
||||||
{"thread_source": "subagent", "value": 70}
|
|
||||||
]}]}))
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(response, Report::Usage, Grouping::TaskStart, date, date).unwrap(),
|
|
||||||
Some(AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::RelativeUsage,
|
|
||||||
updated_at: None,
|
|
||||||
data: vec![AccountAnalyticsDay {
|
|
||||||
date: "2026-01-09".parse().unwrap(),
|
|
||||||
total: 100.0,
|
|
||||||
values: vec![
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "start-composer".to_string(),
|
|
||||||
label: "User messages".to_string(),
|
|
||||||
value: 30.0
|
|
||||||
},
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "unknown".to_string(),
|
|
||||||
label: "Unknown".to_string(),
|
|
||||||
value: 70.0
|
|
||||||
}
|
|
||||||
],
|
|
||||||
}],
|
|
||||||
})
|
|
||||||
);
|
|
||||||
let response = serde_json::from_value(json!({"data": [{"date": "2026-01-09"}]})).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(response, Report::Usage, Grouping::Feature, date, date).unwrap(),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn signed_credits_keep_daily_activity_when_the_period_nets_to_zero() {
|
|
||||||
let start = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 8).unwrap();
|
|
||||||
let end = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap();
|
|
||||||
let response = serde_json::from_value(json!({"data": [
|
|
||||||
{"date": "2026-01-08", "product_surface": "cli", "credit_amount": 0.004},
|
|
||||||
{"date": "2026-01-09", "product_surface": "desktop_app", "credit_amount": -0.004}
|
|
||||||
]}))
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(response, Report::Credits, Grouping::Surface, start, end).unwrap(),
|
|
||||||
Some(AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::Credits,
|
|
||||||
updated_at: None,
|
|
||||||
data: [
|
|
||||||
("2026-01-08", 0.004, "cli", "CLI"),
|
|
||||||
("2026-01-09", -0.004, "desktop_app", "Desktop app")
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.map(|(date, amount, key, label)| AccountAnalyticsDay {
|
|
||||||
date: date.parse().unwrap(),
|
|
||||||
total: amount,
|
|
||||||
values: vec![AccountAnalyticsValue {
|
|
||||||
key: key.to_string(),
|
|
||||||
label: label.to_string(),
|
|
||||||
value: amount
|
|
||||||
}],
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn message_surfaces_include_both_desktop_clients_and_unmapped_counts() {
|
|
||||||
let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap();
|
|
||||||
let response = serde_json::from_value(
|
|
||||||
json!({"data": [{"date": "2026-01-09", "totals": {"turns": 10}, "clients": [
|
|
||||||
{"client_id": "CODEX_DESKTOP_APP", "turns": 2},
|
|
||||||
{"client_id": "CODEX_WORK_DESKTOP", "turns": 3},
|
|
||||||
{"client_id": "new_client", "turns": 1}
|
|
||||||
]}]}),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(response, Report::Messages, Grouping::Surface, date, date)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap()
|
|
||||||
.data,
|
|
||||||
vec![AccountAnalyticsDay {
|
|
||||||
date: "2026-01-09".parse().unwrap(),
|
|
||||||
total: 10.0,
|
|
||||||
values: vec![
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "desktop_app".to_string(),
|
|
||||||
label: "Desktop app".to_string(),
|
|
||||||
value: 5.0
|
|
||||||
},
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "other".to_string(),
|
|
||||||
label: "Other".to_string(),
|
|
||||||
value: 5.0
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn enterprise_credit_series_keep_labels_signed_values_and_freshness() {
|
|
||||||
let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap();
|
|
||||||
let response = serde_json::from_value(json!({
|
|
||||||
"series": [{"key": "medium", "label": "Medium", "total": 12.5}, {"key": "high", "label": "High", "total": -0.004}],
|
|
||||||
"data_freshness_ts": "2026-01-09T10:00:00Z",
|
|
||||||
"data": [{"date": "2026-01-09", "values": {"medium": 12.5, "high": -0.004}}]
|
|
||||||
})).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(response, Report::Credits, Grouping::Reasoning, date, date).unwrap(),
|
|
||||||
Some(AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::Credits,
|
|
||||||
updated_at: Some(1767952800),
|
|
||||||
data: vec![AccountAnalyticsDay {
|
|
||||||
date,
|
|
||||||
total: 12.496,
|
|
||||||
values: vec![
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "high".into(),
|
|
||||||
label: "High".into(),
|
|
||||||
value: -0.004
|
|
||||||
},
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "medium".into(),
|
|
||||||
label: "Medium".into(),
|
|
||||||
value: 12.5
|
|
||||||
}
|
|
||||||
],
|
|
||||||
}],
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn credit_timestamps_and_legacy_model_usage_follow_app_fallbacks() {
|
|
||||||
let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap();
|
|
||||||
let credits = serde_json::from_value(json!({"data": [{"date": "2026-01-09T05:00:00Z", "product_surface": "cli", "credit_amount": 12.5}]})).unwrap();
|
|
||||||
let usage = serde_json::from_value(json!({"data": [{"date": "2026-01-09", "models": [{"model": "model-a", "credits": 12.5}]}]})).unwrap();
|
|
||||||
let credits = history(credits, Report::Credits, Grouping::Surface, date, date)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
let usage = history(usage, Report::Usage, Grouping::Model, date, date)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
credits.data[0].total,
|
|
||||||
usage.data[0].total,
|
|
||||||
usage.data[0].values[0].key.as_str()
|
|
||||||
),
|
|
||||||
(12.5, 12.5, "model-a")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn count_reports_preserve_explicit_zero_and_omit_unreported_days() {
|
|
||||||
let start = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 8).unwrap();
|
|
||||||
let end = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 10).unwrap();
|
|
||||||
for (report, field) in [
|
|
||||||
(Report::Messages, "totals"),
|
|
||||||
(Report::Plugins, "plugin_usage_overviews"),
|
|
||||||
(Report::Skills, "skill_usage_overviews"),
|
|
||||||
] {
|
|
||||||
let value = if report == Report::Messages {
|
|
||||||
json!({"turns": 0})
|
|
||||||
} else {
|
|
||||||
json!([])
|
|
||||||
};
|
|
||||||
let response =
|
|
||||||
serde_json::from_value(json!({"data": [{"date": "2026-01-08", (field): value}]}))
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(response, report, Grouping::Surface, start, end).unwrap(),
|
|
||||||
Some(AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::Count,
|
|
||||||
updated_at: None,
|
|
||||||
data: vec![AccountAnalyticsDay {
|
|
||||||
date: start,
|
|
||||||
total: 0.0,
|
|
||||||
values: Vec::new()
|
|
||||||
}],
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn legacy_consumer_history_keeps_daily_products_and_models() {
|
|
||||||
let date = "2026-09-01".parse().unwrap();
|
|
||||||
let response: AnalyticsData = serde_json::from_value(json!({"units":"relative", "data":[{
|
|
||||||
"date":"2026-09-01",
|
|
||||||
"product_surface_usage_values":{"work_desktop":12,"work_web":8,"cli":30,"desktop_app":50},
|
|
||||||
"models":[{"model":"major","credits":98.5},{"model":"one-percent","credits":1},{"model":"tiny","credits":0.3},{"model":"OTHER","credits":0.2}]
|
|
||||||
}]})).unwrap();
|
|
||||||
for (grouping, expected) in [
|
|
||||||
(
|
|
||||||
Grouping::Surface,
|
|
||||||
vec![("codex", "Codex", 80.0), ("work", "Work", 20.0)],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
Grouping::Model,
|
|
||||||
vec![
|
|
||||||
("major", "major", 98.5),
|
|
||||||
("one-percent", "one-percent", 1.0),
|
|
||||||
("other", "Other", 0.5),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
assert_eq!(
|
|
||||||
history(response.clone(), Report::Usage, grouping, date, date).unwrap(),
|
|
||||||
Some(AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::RelativeUsage,
|
|
||||||
updated_at: None,
|
|
||||||
data: vec![AccountAnalyticsDay {
|
|
||||||
date,
|
|
||||||
total: 100.0,
|
|
||||||
values: expected
|
|
||||||
.into_iter()
|
|
||||||
.map(|(key, label, value)| AccountAnalyticsValue {
|
|
||||||
key: key.into(),
|
|
||||||
label: label.into(),
|
|
||||||
value
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}],
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut credits = response;
|
|
||||||
credits.units = Some("credits".into());
|
|
||||||
let model = history(credits, Report::Usage, Grouping::Model, date, date)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(model.unit, model.data[0].values.len()),
|
|
||||||
(AccountAnalyticsUnit::Credits, 4)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn complete_attribution_wins_consistently_and_incomplete_attribution_is_not_mixed() {
|
|
||||||
let date = "2026-09-01".parse().unwrap();
|
|
||||||
let response: AnalyticsData = serde_json::from_value(json!({"units":"credits", "data":[{
|
|
||||||
"date":"2026-09-01", "product_surface_usage_values":{"cli":999},
|
|
||||||
"models":[{"model":"legacy","credits":999}],
|
|
||||||
"attribution":[
|
|
||||||
{"thread_source":"user","turn_trigger":"composer","surface":"desktop_app","model":"alpha","value":30},
|
|
||||||
{"thread_source":"subagent","turn_trigger":"goal","surface":"cli","model":"tiny","value":0.1}
|
|
||||||
]
|
|
||||||
}]})).unwrap();
|
|
||||||
for grouping in [
|
|
||||||
Grouping::Feature,
|
|
||||||
Grouping::Model,
|
|
||||||
Grouping::Surface,
|
|
||||||
Grouping::TaskStart,
|
|
||||||
] {
|
|
||||||
let normalized = history(response.clone(), Report::Usage, grouping, date, date)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
normalized.unit,
|
|
||||||
normalized.data[0].total,
|
|
||||||
normalized.data[0].values.len()
|
|
||||||
),
|
|
||||||
(AccountAnalyticsUnit::RelativeUsage, 30.1, 2)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let incomplete = serde_json::from_value(json!({"data":[
|
|
||||||
{"date":"2026-09-01", "attribution":[]}, {"date":"2026-09-02"}
|
|
||||||
]}))
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(
|
|
||||||
incomplete,
|
|
||||||
Report::Usage,
|
|
||||||
Grouping::Feature,
|
|
||||||
date,
|
|
||||||
"2026-09-02".parse().unwrap()
|
|
||||||
)
|
|
||||||
.unwrap(),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn duplicate_message_dates_preserve_each_records_other_remainder() {
|
|
||||||
let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap();
|
|
||||||
for grouping in [Grouping::Model, Grouping::Surface] {
|
|
||||||
let response = serde_json::from_value(json!({"data": [
|
|
||||||
{"date": "2026-01-09", "totals": {"turns": 10}, "models": [{"model": "example", "turns": 8}], "clients": [{"client_id": "CODEX_CLI", "turns": 8}]},
|
|
||||||
{"date": "2026-01-09", "totals": {"turns": 10}, "models": [{"model": "example", "turns": 8}], "clients": [{"client_id": "CODEX_CLI", "turns": 8}]}
|
|
||||||
]})).unwrap();
|
|
||||||
let (key, label) = if grouping == Grouping::Model {
|
|
||||||
("example", "example")
|
|
||||||
} else {
|
|
||||||
("cli", "CLI")
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
history(response, Report::Messages, grouping, date, date).unwrap(),
|
|
||||||
Some(AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::Count,
|
|
||||||
updated_at: None,
|
|
||||||
data: vec![AccountAnalyticsDay {
|
|
||||||
date,
|
|
||||||
total: 20.0,
|
|
||||||
values: vec![
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: key.into(),
|
|
||||||
label: label.into(),
|
|
||||||
value: 16.0
|
|
||||||
},
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "other".into(),
|
|
||||||
label: "Other".into(),
|
|
||||||
value: 4.0
|
|
||||||
},
|
|
||||||
]
|
|
||||||
}],
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unsupported_message_groupings_fail_even_without_records() {
|
|
||||||
let date = NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 1, /*day*/ 9).unwrap();
|
|
||||||
for grouping in [
|
|
||||||
Grouping::Feature,
|
|
||||||
Grouping::TaskStart,
|
|
||||||
Grouping::Speed,
|
|
||||||
Grouping::Reasoning,
|
|
||||||
Grouping::TokenType,
|
|
||||||
] {
|
|
||||||
for data in [
|
|
||||||
json!([]),
|
|
||||||
json!([{"date": "2026-01-09", "totals": {"turns": 10}, "clients": []}]),
|
|
||||||
] {
|
|
||||||
let response = serde_json::from_value(json!({"data": data})).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(response, Report::Messages, grouping, date, date),
|
|
||||||
Err("Unsupported message count grouping.".into())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
//! Responsive panels with consistent category colors and signed daily amounts.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
use crate::wrapping::RtOptions;
|
|
||||||
use crate::wrapping::word_wrap_lines;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
use std::ops::Range;
|
|
||||||
|
|
||||||
/// Panel content and measured geometry shared by layout and scrolling.
|
|
||||||
pub(super) struct Panel {
|
|
||||||
pub(super) lines: Vec<Line<'static>>,
|
|
||||||
pub(super) selection: Range<usize>,
|
|
||||||
pub(super) chart_bands: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn panel(&self, section: Section, width: usize, chart_height: usize) -> Panel {
|
|
||||||
let mut lines = Vec::new();
|
|
||||||
let selection;
|
|
||||||
let mut chart_bands = 0;
|
|
||||||
|
|
||||||
if section == Section::Summary {
|
|
||||||
selection = 0..1;
|
|
||||||
lines.extend(self.summary_lines(width));
|
|
||||||
} else if section == Section::Plan {
|
|
||||||
let (plan, detail) = self.plan_lines(width);
|
|
||||||
selection = lines.len() + detail.start..lines.len() + detail.end;
|
|
||||||
lines.extend(plan);
|
|
||||||
} else if section == Section::Chats {
|
|
||||||
let (chats, detail) = if self.business() {
|
|
||||||
self.chat_lines(width)
|
|
||||||
} else {
|
|
||||||
self.task_lines(width)
|
|
||||||
};
|
|
||||||
selection = lines.len() + detail.start..lines.len() + detail.end;
|
|
||||||
lines.extend(chats);
|
|
||||||
} else {
|
|
||||||
let history = self.history_lines(section, width, chart_height);
|
|
||||||
chart_bands = history.bands;
|
|
||||||
lines.extend(history.lines);
|
|
||||||
selection = 0..lines.len();
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut wrapped = Vec::new();
|
|
||||||
let mut wrapped_selection = 0..0;
|
|
||||||
for (index, line) in lines.into_iter().enumerate() {
|
|
||||||
if index == selection.start {
|
|
||||||
wrapped_selection.start = wrapped.len();
|
|
||||||
}
|
|
||||||
if line.style.bg.is_some() && line.width() <= width {
|
|
||||||
// Keep highlighted padding on selected rows that already fit the panel.
|
|
||||||
wrapped.push(line);
|
|
||||||
} else {
|
|
||||||
wrapped.extend(word_wrap_lines(
|
|
||||||
[line],
|
|
||||||
RtOptions::new(width.max(/*other*/ 1)),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if index + 1 == selection.end {
|
|
||||||
wrapped_selection.end = wrapped.len();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Panel {
|
|
||||||
lines: wrapped,
|
|
||||||
selection: wrapped_selection,
|
|
||||||
chart_bands,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
//! Historical allowance snapshots, separate from daily usage and current chat allowances.
|
|
||||||
//! Period IDs are snapshot-scoped; unknown accounting is never converted to zero.
|
|
||||||
use super::data::Load;
|
|
||||||
use chrono::DateTime;
|
|
||||||
use chrono::Utc;
|
|
||||||
use codex_backend_client::PlanLimitBreakdown;
|
|
||||||
use codex_backend_client::PlanLimitHistory;
|
|
||||||
|
|
||||||
pub(super) struct Period {
|
|
||||||
pub id: String,
|
|
||||||
pub start: DateTime<Utc>,
|
|
||||||
pub end: DateTime<Utc>,
|
|
||||||
pub complete: bool,
|
|
||||||
pub used: Option<f64>,
|
|
||||||
pub breakdowns: Option<Vec<PlanLimitBreakdown>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) struct Report {
|
|
||||||
pub as_of: DateTime<Utc>,
|
|
||||||
pub coverage_start: Option<DateTime<Utc>>,
|
|
||||||
pub coverage_complete: bool,
|
|
||||||
pub approximate: bool,
|
|
||||||
pub periods: [Vec<Period>; 2],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Report {
|
|
||||||
pub(super) fn parse(history: PlanLimitHistory) -> Result<Option<Self>, String> {
|
|
||||||
let parse = |value: &str| {
|
|
||||||
DateTime::parse_from_rfc3339(value)
|
|
||||||
.map(|date| date.with_timezone(&Utc))
|
|
||||||
.map_err(|_| "Invalid plan history timestamp.".to_string())
|
|
||||||
};
|
|
||||||
let Some(as_of) = history.data_as_of.as_deref().map(parse).transpose()? else {
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
let mut periods = [Vec::new(), Vec::new()];
|
|
||||||
let mut ids = std::collections::HashSet::new();
|
|
||||||
if history.periods.len() > 1_000 {
|
|
||||||
return Err("Plan history contains too many periods.".into());
|
|
||||||
}
|
|
||||||
for period in history.periods {
|
|
||||||
let window = match period.window_minutes {
|
|
||||||
300 => 0,
|
|
||||||
10080 => 1,
|
|
||||||
_ => return Err("Unsupported plan history window.".into()),
|
|
||||||
};
|
|
||||||
let start = parse(&period.starts_at)?;
|
|
||||||
let end = parse(&period.ends_at)?;
|
|
||||||
if start >= end
|
|
||||||
|| !ids.insert(period.id.clone())
|
|
||||||
|| period
|
|
||||||
.used_basis_points
|
|
||||||
.is_some_and(|amount| !amount.is_finite())
|
|
||||||
|| period
|
|
||||||
.breakdowns
|
|
||||||
.iter()
|
|
||||||
.flatten()
|
|
||||||
.flat_map(|group| &group.rows)
|
|
||||||
.any(|row| !row.basis_points.is_finite())
|
|
||||||
{
|
|
||||||
return Err("Invalid plan history period.".into());
|
|
||||||
}
|
|
||||||
periods[window].push(Period {
|
|
||||||
id: period.id,
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
complete: period.accounting_complete,
|
|
||||||
used: period.used_basis_points,
|
|
||||||
breakdowns: period.breakdowns,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
for window in &mut periods {
|
|
||||||
window.sort_by_key(|period| std::cmp::Reverse(period.start));
|
|
||||||
}
|
|
||||||
Ok(Some(Self {
|
|
||||||
as_of,
|
|
||||||
coverage_start: history.coverage_start.as_deref().map(parse).transpose()?,
|
|
||||||
coverage_complete: history.coverage_complete,
|
|
||||||
approximate: history.approximate,
|
|
||||||
periods,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) struct State {
|
|
||||||
pub enabled: bool,
|
|
||||||
pub report: Load<Report>,
|
|
||||||
pub window: usize,
|
|
||||||
pub cursor: [usize; 2],
|
|
||||||
pub expanded: [Option<String>; 2],
|
|
||||||
snapshot: Option<DateTime<Utc>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for State {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
enabled: false,
|
|
||||||
report: Load::Unavailable,
|
|
||||||
window: 0,
|
|
||||||
cursor: [0; 2],
|
|
||||||
expanded: [None, None],
|
|
||||||
snapshot: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl State {
|
|
||||||
pub(super) fn poll(&mut self) {
|
|
||||||
self.report.poll();
|
|
||||||
let snapshot = self.report.ready().map(|report| report.as_of);
|
|
||||||
if snapshot != self.snapshot {
|
|
||||||
self.snapshot = snapshot;
|
|
||||||
self.cursor = [0; 2];
|
|
||||||
self.expanded = [None, None];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "plan_tests.rs"]
|
|
||||||
mod tests;
|
|
||||||
@@ -1,255 +0,0 @@
|
|||||||
//! Five-hour and weekly period tables share grouping, with independent row expansion.
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::data;
|
|
||||||
use super::plan;
|
|
||||||
use super::render::columns;
|
|
||||||
use super::render::join_columns;
|
|
||||||
use super::sections::Section;
|
|
||||||
use super::styles::secondary_style;
|
|
||||||
use crate::keymap::ListAction;
|
|
||||||
use codex_backend_client::PlanLimitDimension;
|
|
||||||
use ratatui::style::Styled;
|
|
||||||
use ratatui::style::Stylize;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
use std::ops::Range;
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn plan_action(&mut self, action: Option<ListAction>) {
|
|
||||||
let window = self.plan.window;
|
|
||||||
let periods = self
|
|
||||||
.plan
|
|
||||||
.report
|
|
||||||
.ready()
|
|
||||||
.map(|report| &report.periods[window]);
|
|
||||||
let count = periods.map_or(/*default*/ 0, Vec::len);
|
|
||||||
let mut scroll_offset = self.scroll_offset();
|
|
||||||
let cursor = &mut self.plan.cursor[window];
|
|
||||||
let previous_cursor = *cursor;
|
|
||||||
match action {
|
|
||||||
Some(ListAction::MoveLeft | ListAction::MoveRight) => self.plan.window ^= 1,
|
|
||||||
Some(ListAction::MoveUp) => *cursor = cursor.saturating_sub(/*rhs*/ 1),
|
|
||||||
Some(ListAction::MoveDown) => {
|
|
||||||
*cursor = (*cursor + 1).min(count.saturating_sub(/*rhs*/ 1))
|
|
||||||
}
|
|
||||||
Some(ListAction::JumpTop) => *cursor = 0,
|
|
||||||
Some(ListAction::JumpBottom) => *cursor = count.saturating_sub(/*rhs*/ 1),
|
|
||||||
Some(ListAction::Accept) => {
|
|
||||||
if let Some(period) = periods.and_then(|periods| periods.get(*cursor)) {
|
|
||||||
self.plan.expanded[window] =
|
|
||||||
if self.plan.expanded[window].as_ref() == Some(&period.id) {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(period.id.clone())
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(ListAction::Cancel) => {
|
|
||||||
self.is_done |= self.plan.expanded[window].take().is_none();
|
|
||||||
}
|
|
||||||
Some(ListAction::PageDown) => {
|
|
||||||
scroll_offset += self.viewport_height;
|
|
||||||
self.follow_selection = false;
|
|
||||||
}
|
|
||||||
Some(ListAction::PageUp) => {
|
|
||||||
scroll_offset = scroll_offset.saturating_sub(self.viewport_height);
|
|
||||||
self.follow_selection = false;
|
|
||||||
}
|
|
||||||
None => {}
|
|
||||||
}
|
|
||||||
if *cursor != previous_cursor {
|
|
||||||
self.plan.expanded[window] = None;
|
|
||||||
}
|
|
||||||
self.sections[Section::Plan].follow_selection_on_focus |=
|
|
||||||
!self.zoomed && (self.plan.window != window || *cursor != previous_cursor);
|
|
||||||
*self.scroll_offset_mut() = scroll_offset;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn plan_lines(&self, width: usize) -> (Vec<Line<'static>>, Range<usize>) {
|
|
||||||
let side_by_side = width >= 100;
|
|
||||||
let table_width = if side_by_side { (width - 4) / 2 } else { width };
|
|
||||||
let group = self.sections[Section::Plan].group;
|
|
||||||
let dimension = match group {
|
|
||||||
1 => PlanLimitDimension::ThreadSource,
|
|
||||||
2 => PlanLimitDimension::Model,
|
|
||||||
3 => PlanLimitDimension::TurnTrigger,
|
|
||||||
_ => PlanLimitDimension::Surface,
|
|
||||||
};
|
|
||||||
let mut tables = Vec::new();
|
|
||||||
let mut selections = Vec::new();
|
|
||||||
for (window, title) in ["5-hour limits", "Weekly limits"].into_iter().enumerate() {
|
|
||||||
let heading = format!(
|
|
||||||
"{} {title}",
|
|
||||||
if self.plan.window == window {
|
|
||||||
"›"
|
|
||||||
} else {
|
|
||||||
" "
|
|
||||||
}
|
|
||||||
);
|
|
||||||
let mut lines = vec![heading.bold().into(), Line::default()];
|
|
||||||
let mut selection = 0..2;
|
|
||||||
if let Some(report) = self.plan.report.ready() {
|
|
||||||
if report.periods[window].is_empty() {
|
|
||||||
lines.push(
|
|
||||||
if report.coverage_complete {
|
|
||||||
"No limit periods in this date range"
|
|
||||||
} else {
|
|
||||||
"Limit history isn't available yet"
|
|
||||||
}
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
for (index, period) in report.periods[window]
|
|
||||||
.iter()
|
|
||||||
.take(if self.zoomed { usize::MAX } else { 1 })
|
|
||||||
.enumerate()
|
|
||||||
{
|
|
||||||
let start = lines.len();
|
|
||||||
let selected = self.plan.cursor[window] == index;
|
|
||||||
let label = format!(
|
|
||||||
"{} {} – {}{}",
|
|
||||||
if selected { "›" } else { " " },
|
|
||||||
period.start.format(self.clock_format.date_time_format()),
|
|
||||||
period.end.format(self.clock_format.date_time_format()),
|
|
||||||
if period.start <= report.as_of && period.end > report.as_of {
|
|
||||||
" *"
|
|
||||||
} else {
|
|
||||||
""
|
|
||||||
}
|
|
||||||
);
|
|
||||||
let amount = period
|
|
||||||
.used
|
|
||||||
.map(|value| format!("{}%", data::amount(value / 100.0)))
|
|
||||||
.unwrap_or_else(|| "Not available".into());
|
|
||||||
let mut row = columns(label.into(), amount.into(), table_width);
|
|
||||||
if selected && self.plan.window == window {
|
|
||||||
super::styles::select_row(&mut row, table_width);
|
|
||||||
}
|
|
||||||
lines.push(row);
|
|
||||||
if self.zoomed && self.plan.expanded[window].as_ref() == Some(&period.id) {
|
|
||||||
if !period.complete {
|
|
||||||
lines.push(
|
|
||||||
" Some usage is unavailable; this period may be incomplete"
|
|
||||||
.dim()
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if let Some(breakdown) = period.breakdowns.as_ref().and_then(|groups| {
|
|
||||||
groups.iter().find(|group| group.dimension == dimension)
|
|
||||||
}) {
|
|
||||||
for row in &breakdown.rows {
|
|
||||||
let key = if dimension == PlanLimitDimension::TurnTrigger {
|
|
||||||
format!("start-{}", row.key)
|
|
||||||
} else {
|
|
||||||
row.key.clone()
|
|
||||||
};
|
|
||||||
let label = if dimension == PlanLimitDimension::Model {
|
|
||||||
self.model_name(&key)
|
|
||||||
} else {
|
|
||||||
super::normalize::label(&key)
|
|
||||||
};
|
|
||||||
lines.push(columns(
|
|
||||||
format!(" {label}").into(),
|
|
||||||
format!("{}%", data::amount(row.basis_points / 100.0)).into(),
|
|
||||||
table_width,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
lines.push(" Breakdown isn't available for this period".dim().into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if selected {
|
|
||||||
selection = start..lines.len();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
lines.push(
|
|
||||||
match &self.plan.report {
|
|
||||||
data::Load::Unavailable => "Limit history isn't available yet",
|
|
||||||
state => state
|
|
||||||
.message()
|
|
||||||
.unwrap_or("Limit history isn't available yet"),
|
|
||||||
}
|
|
||||||
.to_string()
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// Wrap each column before joining so long timestamps never collide with its neighbor.
|
|
||||||
let mut wrapped = Vec::new();
|
|
||||||
let mut wrapped_selection = 0..0;
|
|
||||||
for (index, line) in lines.into_iter().enumerate() {
|
|
||||||
if index == selection.start {
|
|
||||||
wrapped_selection.start = wrapped.len();
|
|
||||||
}
|
|
||||||
wrapped.extend(crate::wrapping::word_wrap_lines(
|
|
||||||
[line],
|
|
||||||
crate::wrapping::RtOptions::new(table_width.max(/*other*/ 1)),
|
|
||||||
));
|
|
||||||
if index + 1 == selection.end {
|
|
||||||
wrapped_selection.end = wrapped.len();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
tables.push(wrapped);
|
|
||||||
selections.push(wrapped_selection);
|
|
||||||
}
|
|
||||||
let mut selection = selections[self.plan.window].clone();
|
|
||||||
let mut lines = if side_by_side {
|
|
||||||
join_columns(&tables[0], &tables[1], table_width)
|
|
||||||
} else {
|
|
||||||
if self.plan.window == 1 {
|
|
||||||
selection =
|
|
||||||
selection.start + tables[0].len() + 1..selection.end + tables[0].len() + 1;
|
|
||||||
}
|
|
||||||
let mut lines = std::mem::take(&mut tables[0]);
|
|
||||||
lines.push(Line::default());
|
|
||||||
lines.append(&mut tables[1]);
|
|
||||||
lines
|
|
||||||
};
|
|
||||||
if group == 3 {
|
|
||||||
lines.push(
|
|
||||||
"By turn start includes Tasks only; percentages use the full period limit"
|
|
||||||
.dim()
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if let Some(plan::Report {
|
|
||||||
as_of,
|
|
||||||
coverage_start,
|
|
||||||
coverage_complete,
|
|
||||||
approximate,
|
|
||||||
..
|
|
||||||
}) = self.plan.report.ready()
|
|
||||||
{
|
|
||||||
if !*coverage_complete {
|
|
||||||
lines.push("Some periods aren't available yet".dim().into());
|
|
||||||
}
|
|
||||||
lines.push(
|
|
||||||
format!(
|
|
||||||
"Usage as of {} UTC · * current at last update",
|
|
||||||
as_of.format(self.clock_format.date_time_format())
|
|
||||||
)
|
|
||||||
.dim()
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
if let Some(start) = coverage_start {
|
|
||||||
lines.push(
|
|
||||||
format!(
|
|
||||||
"Available since {} UTC",
|
|
||||||
start.format(self.clock_format.date_time_format())
|
|
||||||
)
|
|
||||||
.dim()
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if *approximate {
|
|
||||||
lines.push(
|
|
||||||
"Amounts and period boundaries are approximate; recent activity may be delayed"
|
|
||||||
.dim()
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(lines, selection)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,362 +0,0 @@
|
|||||||
//! Snapshot semantics and independent plan-period navigation without a live billing service.
|
|
||||||
use super::*;
|
|
||||||
use crate::analytics::AnalyticsView;
|
|
||||||
use crate::analytics::fixture;
|
|
||||||
use crate::analytics::models::AccountKind;
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
use crossterm::event::KeyCode;
|
|
||||||
use crossterm::event::KeyEvent;
|
|
||||||
use crossterm::event::KeyModifiers;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
fn response() -> PlanLimitHistory {
|
|
||||||
serde_json::from_value(json!({
|
|
||||||
"data_as_of":"2026-09-02T12:00:00Z", "coverage_start":"2026-09-01T00:00:00Z",
|
|
||||||
"coverage_complete":false, "boundary_tolerance_seconds":60,
|
|
||||||
"periods":[
|
|
||||||
{"id":"five", "window_minutes":300,"plan_type":"plus",
|
|
||||||
"starts_at":"2026-09-02T10:00:00Z","ends_at":"2026-09-02T15:00:00Z",
|
|
||||||
"accounting_complete":false,"used_basis_points":12500,
|
|
||||||
"breakdowns":[
|
|
||||||
{"dimension":"future_dimension","rows":[{"key":"future","basis_points":500}]},
|
|
||||||
{"dimension":"thread_source","rows":[{"key":"user","basis_points":12500}]}]},
|
|
||||||
{"id":"weekly", "window_minutes":10080,"plan_type":"plus",
|
|
||||||
"starts_at":"2026-09-01T00:00:00Z","ends_at":"2026-09-08T00:00:00Z",
|
|
||||||
"accounting_complete":true,"used_basis_points":null,"breakdowns":null}
|
|
||||||
]
|
|
||||||
}))
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn resize_keeps_visible_weekly_selection_and_respects_manual_scroll() {
|
|
||||||
let mut history = response();
|
|
||||||
for index in 0..12 {
|
|
||||||
let mut period = history.periods[0].clone();
|
|
||||||
period.id = format!("five-{index}");
|
|
||||||
history.periods.push(period);
|
|
||||||
}
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.plan.enabled = true;
|
|
||||||
view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap());
|
|
||||||
view.plan.poll();
|
|
||||||
view.section = Section::Plan;
|
|
||||||
view.zoomed = false;
|
|
||||||
view.plan.expanded[0] = Some("five".into());
|
|
||||||
let dashboard = view.dashboard_lines(/*width*/ 120, /*height*/ 60).0;
|
|
||||||
assert!(
|
|
||||||
dashboard
|
|
||||||
.iter()
|
|
||||||
.any(|line| line.to_string().contains("Weekly limits"))
|
|
||||||
);
|
|
||||||
view.zoomed = true;
|
|
||||||
view.plan.expanded[0] = None;
|
|
||||||
let render = |view: &mut AnalyticsView, width, height| {
|
|
||||||
let mut terminal =
|
|
||||||
ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height)).unwrap();
|
|
||||||
terminal
|
|
||||||
.draw(|frame| view.render(frame.area(), frame.buffer_mut()))
|
|
||||||
.unwrap();
|
|
||||||
terminal.backend().to_string()
|
|
||||||
};
|
|
||||||
render(&mut view, /*width*/ 80, /*height*/ 24);
|
|
||||||
for code in [KeyCode::Char('z'), KeyCode::Right] {
|
|
||||||
view.handle_key(KeyEvent::new(code, KeyModifiers::NONE));
|
|
||||||
render(&mut view, /*width*/ 80, /*height*/ 24);
|
|
||||||
}
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
||||||
assert!(render(&mut view, /*width*/ 80, /*height*/ 24).contains("Sep 1 00:00 – Sep 8 00:00"));
|
|
||||||
render(&mut view, /*width*/ 120, /*height*/ 36);
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
|
|
||||||
render(&mut view, /*width*/ 40, /*height*/ 16);
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
|
||||||
let narrow = render(&mut view, /*width*/ 40, /*height*/ 16);
|
|
||||||
assert!(view.scroll_offset() > 0);
|
|
||||||
assert!(narrow.contains("Sep 1 00:00 – Sep 8 00:00"));
|
|
||||||
assert!(narrow.contains("↑/↓ period · enter details"));
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::PageUp, KeyModifiers::NONE));
|
|
||||||
render(&mut view, /*width*/ 40, /*height*/ 16);
|
|
||||||
let reading_position = view.scroll_offset();
|
|
||||||
assert!(!view.selection_visible);
|
|
||||||
for code in [KeyCode::Char('z'), KeyCode::Enter] {
|
|
||||||
view.handle_key(KeyEvent::new(code, KeyModifiers::NONE));
|
|
||||||
render(&mut view, /*width*/ 40, /*height*/ 16);
|
|
||||||
}
|
|
||||||
assert_eq!(view.scroll_offset(), reading_position);
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
|
|
||||||
render(&mut view, /*width*/ 50, /*height*/ 16);
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
|
||||||
render(&mut view, /*width*/ 50, /*height*/ 16);
|
|
||||||
assert_eq!(view.scroll_offset(), reading_position);
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui().unwrap();
|
|
||||||
let event = crate::tui::TuiEvent::Resize(ratatui::layout::Size {
|
|
||||||
width: 55,
|
|
||||||
height: 16,
|
|
||||||
});
|
|
||||||
tui.screen_size_for_event(&event).unwrap();
|
|
||||||
view.handle_event(&mut tui, event).unwrap();
|
|
||||||
assert_eq!(view.scroll_offset(), reading_position);
|
|
||||||
|
|
||||||
let mut history = response();
|
|
||||||
let breakdown = &mut history.periods[0].breakdowns.as_mut().unwrap()[1];
|
|
||||||
breakdown.rows = vec![breakdown.rows[0].clone(); 20];
|
|
||||||
view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap());
|
|
||||||
view.plan.poll();
|
|
||||||
view.plan.window = 0;
|
|
||||||
view.sections[Section::Plan].group = 1;
|
|
||||||
view.plan.expanded[0] = Some("five".into());
|
|
||||||
view.follow_selection = true;
|
|
||||||
render(&mut view, /*width*/ 58, /*height*/ 16);
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE));
|
|
||||||
render(&mut view, /*width*/ 58, /*height*/ 16);
|
|
||||||
let reading_position = view.scroll_offset();
|
|
||||||
assert!(reading_position > 0);
|
|
||||||
render(&mut view, /*width*/ 60, /*height*/ 16);
|
|
||||||
assert_eq!(view.scroll_offset(), reading_position);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn period_navigation_preserves_unknowns_and_resets_on_new_snapshot() {
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.plan.enabled = true;
|
|
||||||
view.plan.report = Load::Ready(Report::parse(response()).unwrap().unwrap());
|
|
||||||
view.plan.poll();
|
|
||||||
view.section = Section::Plan;
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE));
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
||||||
assert_eq!(
|
|
||||||
view.plan.expanded,
|
|
||||||
[Some("five".into()), Some("weekly".into())]
|
|
||||||
);
|
|
||||||
let mut output = Vec::new();
|
|
||||||
for width in [120, 58] {
|
|
||||||
let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(
|
|
||||||
width, /*height*/ 30,
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
terminal
|
|
||||||
.draw(|frame| view.render(frame.area(), frame.buffer_mut()))
|
|
||||||
.unwrap();
|
|
||||||
output.push(terminal.backend().to_string());
|
|
||||||
}
|
|
||||||
insta::assert_snapshot!(output.join("\n"));
|
|
||||||
let mut next = response();
|
|
||||||
next.data_as_of = Some("2026-09-02T13:00:00Z".into());
|
|
||||||
view.plan.report = Load::Ready(Report::parse(next).unwrap().unwrap());
|
|
||||||
view.plan.poll();
|
|
||||||
assert_eq!(
|
|
||||||
(view.plan.cursor, view.plan.expanded),
|
|
||||||
([0, 0], [None, None])
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unavailable_empty_and_zero_history_are_distinct() {
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.plan.enabled = true;
|
|
||||||
view.section = Section::Plan;
|
|
||||||
let mut states = Vec::new();
|
|
||||||
states.push(
|
|
||||||
view.plan_lines(/*width*/ 100)
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.map(ToString::to_string)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
);
|
|
||||||
let mut history = response();
|
|
||||||
history.coverage_complete = true;
|
|
||||||
history.periods.clear();
|
|
||||||
view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap());
|
|
||||||
states.push(
|
|
||||||
view.plan_lines(/*width*/ 100)
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.map(ToString::to_string)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
);
|
|
||||||
let mut history = response();
|
|
||||||
history.periods[0].used_basis_points = Some(0.0);
|
|
||||||
view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap());
|
|
||||||
states.push(
|
|
||||||
view.plan_lines(/*width*/ 100)
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.map(ToString::to_string)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
);
|
|
||||||
let mut future = response();
|
|
||||||
future.periods[0].starts_at = "2026-09-02T13:00:00Z".into();
|
|
||||||
view.plan.report = Load::Ready(Report::parse(future).unwrap().unwrap());
|
|
||||||
states.push(
|
|
||||||
view.plan_lines(/*width*/ 100)
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.map(ToString::to_string)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
);
|
|
||||||
let snapshot = states.join("\n\n");
|
|
||||||
let snapshot = snapshot
|
|
||||||
.lines()
|
|
||||||
.map(str::trim_end)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
insta::assert_snapshot!(snapshot);
|
|
||||||
let mut missing = response();
|
|
||||||
missing.data_as_of = None;
|
|
||||||
assert!(Report::parse(missing).unwrap().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn plan_gate_prevents_requests_and_unavailable_plan_does_not_block_other_reports() {
|
|
||||||
use crate::analytics::client;
|
|
||||||
use crate::analytics::test_support;
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
let server = test_support::server().await;
|
|
||||||
let (_home, _server, mut view) = client::tests::connected_view(&server, "plus").await;
|
|
||||||
test_support::settle(&mut view).await;
|
|
||||||
assert!(
|
|
||||||
!server
|
|
||||||
.received_requests()
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.any(|request| request.url.path().ends_with("plan_limit_history"))
|
|
||||||
);
|
|
||||||
assert!(!view.visible_sections().contains(&Section::Plan));
|
|
||||||
Mock::given(path("/backend-api/wham/usage/plan_limit_history"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 404))
|
|
||||||
.with_priority(/*p*/ 1)
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let (mut config, handle, frame) = view.connection.clone().unwrap();
|
|
||||||
std::sync::Arc::make_mut(&mut config)
|
|
||||||
.features
|
|
||||||
.enable(codex_features::Feature::AnalyticsPlanHistory)
|
|
||||||
.unwrap();
|
|
||||||
view.open(handle, frame, Vec::new(), config);
|
|
||||||
test_support::settle(&mut view).await;
|
|
||||||
assert!(matches!(view.plan.report, Load::Unavailable));
|
|
||||||
assert!(view.sections[Section::Usage].history.ready().is_some());
|
|
||||||
assert!(view.visible_sections().contains(&Section::Plan));
|
|
||||||
// Closing cancels the pending plan task along with the other account-owned work.
|
|
||||||
let (sender, receiver) = tokio::sync::oneshot::channel::<()>();
|
|
||||||
view.plan.report = Load::start(
|
|
||||||
async move {
|
|
||||||
let _sender = sender;
|
|
||||||
std::future::pending().await
|
|
||||||
},
|
|
||||||
crate::tui::FrameRequester::test_dummy(),
|
|
||||||
);
|
|
||||||
view.cancel_loads();
|
|
||||||
assert!(receiver.await.is_err());
|
|
||||||
server.verify().await;
|
|
||||||
let server = test_support::server().await;
|
|
||||||
let (_home, _server, mut business) = client::tests::connected_view(&server, "business").await;
|
|
||||||
let (mut config, handle, frame) = business.connection.clone().unwrap();
|
|
||||||
std::sync::Arc::make_mut(&mut config)
|
|
||||||
.features
|
|
||||||
.enable(codex_features::Feature::AnalyticsPlanHistory)
|
|
||||||
.unwrap();
|
|
||||||
business.open(handle, frame, Vec::new(), config);
|
|
||||||
test_support::settle(&mut business).await;
|
|
||||||
assert!(!business.visible_sections().contains(&Section::Plan));
|
|
||||||
assert!(matches!(business.plan.report, Load::Unavailable));
|
|
||||||
server.verify().await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn plan_escape_collapses_details_before_closing() {
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.plan.enabled = true;
|
|
||||||
view.plan.report = Load::Ready(Report::parse(response()).unwrap().unwrap());
|
|
||||||
view.plan.poll();
|
|
||||||
view.section = Section::Plan;
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
|
||||||
assert!(!view.is_done);
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
|
||||||
assert!(view.is_done);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn moving_period_selection_collapses_its_previous_details() {
|
|
||||||
let mut history = response();
|
|
||||||
let mut older = history.periods[0].clone();
|
|
||||||
older.starts_at = "2026-09-02T05:00:00Z".into();
|
|
||||||
older.ends_at = "2026-09-02T10:00:00Z".into();
|
|
||||||
for index in 0..13 {
|
|
||||||
older.id = format!("older-five-{index}");
|
|
||||||
history.periods.push(older.clone());
|
|
||||||
}
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.plan.enabled = true;
|
|
||||||
view.plan.report = Load::Ready(Report::parse(history).unwrap().unwrap());
|
|
||||||
view.plan.poll();
|
|
||||||
view.section = Section::Plan;
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
|
|
||||||
assert_eq!(
|
|
||||||
(&view.plan.cursor, &view.plan.expanded),
|
|
||||||
(&[1, 0], &[None, None])
|
|
||||||
);
|
|
||||||
let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(
|
|
||||||
/*width*/ 80, /*height*/ 24,
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
for code in [KeyCode::Right, KeyCode::Tab, KeyCode::BackTab] {
|
|
||||||
view.handle_key(KeyEvent::new(code, KeyModifiers::NONE));
|
|
||||||
terminal
|
|
||||||
.draw(|frame| view.render(frame.area(), frame.buffer_mut()))
|
|
||||||
.unwrap();
|
|
||||||
if view.section == Section::Plan {
|
|
||||||
assert!(
|
|
||||||
terminal
|
|
||||||
.backend()
|
|
||||||
.to_string()
|
|
||||||
.contains("Sep 1 00:00 – Sep 8 00:00")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invalid_history_returns_safe_errors() {
|
|
||||||
for invalid in 0..5 {
|
|
||||||
let mut history = response();
|
|
||||||
match invalid {
|
|
||||||
0 => history.periods[0].starts_at = "private wire value".into(),
|
|
||||||
1 => history.periods[0].ends_at = history.periods[0].starts_at.clone(),
|
|
||||||
2 => history.periods.push(history.periods[0].clone()),
|
|
||||||
3 => history.periods[0].window_minutes = 1,
|
|
||||||
_ => history.periods[0].used_basis_points = Some(f64::INFINITY),
|
|
||||||
}
|
|
||||||
let error = Report::parse(history).err().unwrap();
|
|
||||||
assert!(!error.contains("private wire value"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn plan_clocks_follow_preference_and_keep_utc() {
|
|
||||||
let mut view = fixture::view(AccountKind::Consumer);
|
|
||||||
view.clock_format = crate::clock_format::ClockFormat::TwelveHour;
|
|
||||||
view.plan.enabled = true;
|
|
||||||
view.section = Section::Plan;
|
|
||||||
view.plan.report = Load::Ready(Report::parse(response()).unwrap().unwrap());
|
|
||||||
let rendered = view
|
|
||||||
.plan_lines(/*width*/ 80)
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.map(ToString::to_string)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
insta::assert_snapshot!("plan_clocks_twelve_hour", rendered);
|
|
||||||
}
|
|
||||||
@@ -1,176 +0,0 @@
|
|||||||
//! Daily stacked bars with fixed calendar ticks, a selection cursor, and an anchored value.
|
|
||||||
//! Relative usage retains the server's scale; signed credits keep both bands.
|
|
||||||
|
|
||||||
mod annotations;
|
|
||||||
mod layout;
|
|
||||||
mod painting;
|
|
||||||
|
|
||||||
use self::layout::Layout;
|
|
||||||
use self::painting::Band;
|
|
||||||
use super::data;
|
|
||||||
use super::data::compact_amount as tick;
|
|
||||||
use super::render::parts;
|
|
||||||
use crate::analytics::models::AccountAnalyticsDay;
|
|
||||||
use crate::analytics::models::AccountAnalyticsUnit;
|
|
||||||
use crate::analytics::models::AccountAnalyticsValue;
|
|
||||||
use chrono::NaiveDate;
|
|
||||||
use ratatui::buffer::Buffer;
|
|
||||||
use ratatui::layout::Rect;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
use ratatui::text::Span;
|
|
||||||
use unicode_width::UnicodeWidthStr;
|
|
||||||
|
|
||||||
/// Share the chart's scale with the selected-day summary, including signed values.
|
|
||||||
pub(super) fn peak(
|
|
||||||
days: &[(NaiveDate, Option<&AccountAnalyticsDay>)],
|
|
||||||
categories: &[AccountAnalyticsValue],
|
|
||||||
) -> f64 {
|
|
||||||
days.iter()
|
|
||||||
.filter_map(|(_, day)| *day)
|
|
||||||
.map(|day| {
|
|
||||||
parts(&day.values, categories)
|
|
||||||
.iter()
|
|
||||||
.map(|value| value.abs())
|
|
||||||
.sum::<f64>()
|
|
||||||
.max(day.total.abs())
|
|
||||||
})
|
|
||||||
.fold(/*init*/ 0.0, f64::max)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Two readable intervals cover the range; counts never use fractional ticks.
|
|
||||||
pub(super) fn axis_max(peak: f64, unit: AccountAnalyticsUnit) -> f64 {
|
|
||||||
if peak == 0.0 {
|
|
||||||
return if matches!(
|
|
||||||
unit,
|
|
||||||
AccountAnalyticsUnit::Count | AccountAnalyticsUnit::Tokens
|
|
||||||
) {
|
|
||||||
2.0
|
|
||||||
} else {
|
|
||||||
1.0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
let step = if matches!(
|
|
||||||
unit,
|
|
||||||
AccountAnalyticsUnit::Count | AccountAnalyticsUnit::Tokens
|
|
||||||
) {
|
|
||||||
(peak / 2.0).max(/*other*/ 1.0)
|
|
||||||
} else {
|
|
||||||
peak / 2.0
|
|
||||||
};
|
|
||||||
let magnitude = 10.0_f64.powf(step.log10().floor());
|
|
||||||
let normalized = step / magnitude;
|
|
||||||
let multiple = [1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 7.5, 10.0]
|
|
||||||
.into_iter()
|
|
||||||
.find(|multiple| {
|
|
||||||
*multiple >= normalized
|
|
||||||
&& (!matches!(
|
|
||||||
unit,
|
|
||||||
AccountAnalyticsUnit::Count | AccountAnalyticsUnit::Tokens
|
|
||||||
) || (multiple * magnitude).fract() == 0.0)
|
|
||||||
})
|
|
||||||
.unwrap_or(/*default*/ 10.0);
|
|
||||||
let ceiling = multiple * magnitude * 2.0;
|
|
||||||
if ceiling.is_finite() && ceiling >= peak {
|
|
||||||
ceiling
|
|
||||||
} else {
|
|
||||||
peak
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Rendered chart geometry exposes its positive and optional negative value bands.
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(super) struct Chart {
|
|
||||||
pub(super) lines: Vec<Line<'static>>,
|
|
||||||
pub(super) bands: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Render a calendar selection; the cursor must index days and dimensions fit the terminal.
|
|
||||||
pub(super) fn chart(
|
|
||||||
days: &[(NaiveDate, Option<&AccountAnalyticsDay>)],
|
|
||||||
categories: &[AccountAnalyticsValue],
|
|
||||||
cursor: usize,
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
unit: AccountAnalyticsUnit,
|
|
||||||
) -> Chart {
|
|
||||||
if days.is_empty() || width == 0 {
|
|
||||||
return Chart::default();
|
|
||||||
}
|
|
||||||
let values = days
|
|
||||||
.iter()
|
|
||||||
.map(|(_, day)| {
|
|
||||||
day.map_or(
|
|
||||||
/*default*/ [0.0; 4],
|
|
||||||
|day| parts(&day.values, categories),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let bands = if values.iter().flatten().any(|value| *value < 0.0) {
|
|
||||||
&[Band::Positive, Band::Negative][..]
|
|
||||||
} else {
|
|
||||||
&[Band::Positive][..]
|
|
||||||
};
|
|
||||||
let peak = axis_max(peak(days, categories), unit);
|
|
||||||
let label_width = tick(peak).width().max(tick(peak / 2.0).width()) + bands.len() - 1 + 2;
|
|
||||||
let layout = Layout::new(days.len(), cursor, width, height, label_width, bands);
|
|
||||||
let renderer = Renderer {
|
|
||||||
days,
|
|
||||||
values,
|
|
||||||
cursor,
|
|
||||||
peak,
|
|
||||||
unit,
|
|
||||||
bands,
|
|
||||||
layout,
|
|
||||||
};
|
|
||||||
let mut buf = Buffer::empty(Rect::new(
|
|
||||||
/*x*/ 0,
|
|
||||||
/*y*/ 0,
|
|
||||||
width as u16,
|
|
||||||
(layout.marker_row + 2) as u16,
|
|
||||||
));
|
|
||||||
renderer.paint_bars(&mut buf);
|
|
||||||
renderer.annotate_missing(&mut buf);
|
|
||||||
renderer.paint_axis(&mut buf);
|
|
||||||
renderer.annotate_selection(&mut buf);
|
|
||||||
renderer.annotate_calendar(&mut buf);
|
|
||||||
let lines = buf
|
|
||||||
.content
|
|
||||||
.chunks(width)
|
|
||||||
.map(|row| {
|
|
||||||
Line::from(
|
|
||||||
row.iter()
|
|
||||||
.map(|cell| Span::styled(cell.symbol().to_owned(), cell.style()))
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
Chart {
|
|
||||||
lines,
|
|
||||||
bands: bands.len(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Shared inputs for painting and annotations; all phases use the same calendar geometry.
|
|
||||||
struct Renderer<'a> {
|
|
||||||
days: &'a [(NaiveDate, Option<&'a AccountAnalyticsDay>)],
|
|
||||||
values: Vec<[f64; 4]>,
|
|
||||||
cursor: usize,
|
|
||||||
peak: f64,
|
|
||||||
unit: AccountAnalyticsUnit,
|
|
||||||
bands: &'static [Band],
|
|
||||||
layout: Layout,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn amount(value: f64, unit: AccountAnalyticsUnit) -> String {
|
|
||||||
match unit {
|
|
||||||
AccountAnalyticsUnit::RelativeUsage => data::amount(value),
|
|
||||||
AccountAnalyticsUnit::Count | AccountAnalyticsUnit::Tokens => {
|
|
||||||
data::compact_amount(value.round())
|
|
||||||
}
|
|
||||||
AccountAnalyticsUnit::Credits => data::credit_amount(value),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "plot_tests.rs"]
|
|
||||||
mod tests;
|
|
||||||
@@ -1,213 +0,0 @@
|
|||||||
//! Missing-day markers, daily-value callouts, and stable calendar labels.
|
|
||||||
|
|
||||||
use super::Renderer;
|
|
||||||
use super::amount;
|
|
||||||
use super::layout::Layout;
|
|
||||||
use super::painting::Band;
|
|
||||||
use crate::analytics::styles::secondary_style;
|
|
||||||
use crate::color::is_light;
|
|
||||||
use crate::style::accent_style;
|
|
||||||
use crate::terminal_palette::default_bg;
|
|
||||||
use ratatui::buffer::Buffer;
|
|
||||||
use ratatui::style::Style;
|
|
||||||
use ratatui::style::Styled;
|
|
||||||
use ratatui::style::Stylize;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
use unicode_width::UnicodeWidthStr;
|
|
||||||
|
|
||||||
impl Renderer<'_> {
|
|
||||||
pub(super) fn annotate_missing(&self, buf: &mut Buffer) {
|
|
||||||
let Layout {
|
|
||||||
count,
|
|
||||||
height,
|
|
||||||
start,
|
|
||||||
..
|
|
||||||
} = self.layout;
|
|
||||||
for (index, parts) in self.values[start..start + count].iter().enumerate() {
|
|
||||||
// The selected zero/missing value gets its own callout below; avoid repeating it.
|
|
||||||
if start + index != self.cursor {
|
|
||||||
let marker = match self.days[start + index].1 {
|
|
||||||
None => Some('—'),
|
|
||||||
Some(day) if day.total == 0.0 && parts.iter().all(|value| *value == 0.0) => {
|
|
||||||
Some('0')
|
|
||||||
}
|
|
||||||
Some(_) => None,
|
|
||||||
};
|
|
||||||
if let Some(marker) = marker {
|
|
||||||
buf[(self.layout.center(index) as u16, height as u16)]
|
|
||||||
.set_char(marker)
|
|
||||||
.set_style(Style::default().dim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn annotate_selection(&self, buf: &mut Buffer) {
|
|
||||||
let Layout {
|
|
||||||
axis_width,
|
|
||||||
baseline,
|
|
||||||
height,
|
|
||||||
marker_row,
|
|
||||||
plot_width,
|
|
||||||
start,
|
|
||||||
width,
|
|
||||||
..
|
|
||||||
} = self.layout;
|
|
||||||
// Give the selected value first choice of space; the other labels never overwrite it.
|
|
||||||
for index in
|
|
||||||
std::iter::once(self.cursor).chain((start..start + self.layout.count).filter(|index| {
|
|
||||||
self.days.len() <= 7
|
|
||||||
&& *index != self.cursor
|
|
||||||
&& self.days[*index].1.is_some_and(|day| {
|
|
||||||
day.total != 0.0 || self.values[*index].iter().any(|value| *value != 0.0)
|
|
||||||
})
|
|
||||||
}))
|
|
||||||
{
|
|
||||||
let total = self.days[index].1.map_or(/*default*/ 0.0, |day| day.total);
|
|
||||||
let label = self.days[index]
|
|
||||||
.1
|
|
||||||
.map_or_else(|| "—".into(), |_| amount(total, self.unit));
|
|
||||||
// A partial number can mean a different amount; leave the cursor when the value cannot fit.
|
|
||||||
if label.width() > plot_width {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let x = self.layout.center(index - start);
|
|
||||||
let label_width = label.width();
|
|
||||||
let label_x = x
|
|
||||||
.saturating_sub(label_width / 2)
|
|
||||||
.clamp(axis_width, width - label_width);
|
|
||||||
let occupied = label_x.saturating_sub(/*rhs*/ 1).max(axis_width)
|
|
||||||
..(label_x + label_width + 1).min(width);
|
|
||||||
let below = total < 0.0;
|
|
||||||
let band = if below {
|
|
||||||
Band::Negative
|
|
||||||
} else {
|
|
||||||
Band::Positive
|
|
||||||
};
|
|
||||||
let extent = self.values[index]
|
|
||||||
.iter()
|
|
||||||
.map(|value| band.amount(*value))
|
|
||||||
.sum::<f64>();
|
|
||||||
let rows = ((extent * height as f64 / self.peak).ceil() as usize).min(height);
|
|
||||||
let cap = if below {
|
|
||||||
baseline + rows
|
|
||||||
} else {
|
|
||||||
baseline - rows
|
|
||||||
};
|
|
||||||
let mut label_y = if below {
|
|
||||||
cap + 1
|
|
||||||
} else {
|
|
||||||
cap.saturating_sub(/*rhs*/ 1)
|
|
||||||
};
|
|
||||||
// Keep the callout close without painting over a neighboring bar. A guide connects any gap.
|
|
||||||
while occupied
|
|
||||||
.clone()
|
|
||||||
.any(|col| buf[(col as u16, label_y as u16)].symbol() != " ")
|
|
||||||
{
|
|
||||||
if below && label_y + 1 < marker_row {
|
|
||||||
label_y += 1;
|
|
||||||
} else if !below && label_y > 0 {
|
|
||||||
label_y -= 1;
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if occupied
|
|
||||||
.clone()
|
|
||||||
.any(|col| buf[(col as u16, label_y as u16)].symbol() != " ")
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// Use white on dark backgrounds and the terminal foreground on light backgrounds.
|
|
||||||
let style = if index == self.cursor {
|
|
||||||
let selected = Style::default().bold().not_dim();
|
|
||||||
if default_bg().is_some_and(is_light) {
|
|
||||||
selected
|
|
||||||
} else {
|
|
||||||
selected.white()
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Style::default().dim()
|
|
||||||
};
|
|
||||||
let guide = if below {
|
|
||||||
cap + 1..label_y
|
|
||||||
} else {
|
|
||||||
label_y + 1..cap
|
|
||||||
};
|
|
||||||
for y in guide {
|
|
||||||
let cell = &mut buf[(x as u16, y as u16)];
|
|
||||||
if cell.symbol() == " " {
|
|
||||||
cell.set_char('┊').set_style(style);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
buf.set_line(
|
|
||||||
label_x as u16,
|
|
||||||
label_y as u16,
|
|
||||||
&Line::from(label.set_style(style)),
|
|
||||||
label_width as u16,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let x = self.layout.center(self.cursor - start);
|
|
||||||
buf[(x as u16, marker_row as u16)]
|
|
||||||
.set_char('▲')
|
|
||||||
.set_style(accent_style());
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn annotate_calendar(&self, buf: &mut Buffer) {
|
|
||||||
let Layout {
|
|
||||||
axis_width,
|
|
||||||
count,
|
|
||||||
marker_row,
|
|
||||||
plot_width,
|
|
||||||
start,
|
|
||||||
width,
|
|
||||||
..
|
|
||||||
} = self.layout;
|
|
||||||
// Calendar ticks depend only on the range/width, never on the current selection.
|
|
||||||
let mut occupied = vec![false; width];
|
|
||||||
// Give the two range endpoints priority over intermediate weekly ticks.
|
|
||||||
for index in std::iter::once(/*value*/ 0).chain((1..count).rev()) {
|
|
||||||
if self.days.len() > 7
|
|
||||||
&& !(start + index).is_multiple_of(/*rhs*/ 7)
|
|
||||||
&& index + 1 != count
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let format = if self.days.len() <= 7 && plot_width / count < 7 {
|
|
||||||
"%-d"
|
|
||||||
} else {
|
|
||||||
"%b %-d"
|
|
||||||
};
|
|
||||||
let mut label = self.days[start + index].0.format(format).to_string();
|
|
||||||
if label.width() > plot_width {
|
|
||||||
label = self.days[start + index].0.format("%-d").to_string();
|
|
||||||
}
|
|
||||||
if label.width() > plot_width {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let offset = self
|
|
||||||
.layout
|
|
||||||
.center(index)
|
|
||||||
.saturating_sub(label.len() / 2)
|
|
||||||
.clamp(axis_width, width - label.len());
|
|
||||||
if occupied[offset.saturating_sub(/*rhs*/ 1)..(offset + label.len() + 1).min(width)]
|
|
||||||
.iter()
|
|
||||||
.any(|used| *used)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
occupied[offset..offset + label.len()].fill(/*value*/ true);
|
|
||||||
let label = if start + index == self.cursor {
|
|
||||||
label.set_style(accent_style()).underlined()
|
|
||||||
} else {
|
|
||||||
label.set_style(secondary_style())
|
|
||||||
};
|
|
||||||
buf.set_line(
|
|
||||||
offset as u16,
|
|
||||||
(marker_row + 1) as u16,
|
|
||||||
&Line::from(label),
|
|
||||||
(width - offset) as u16,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
//! Calendar viewport and shared coordinates for bars, axes, and annotations.
|
|
||||||
|
|
||||||
use super::painting::Band;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub(super) struct Layout {
|
|
||||||
pub(super) width: usize,
|
|
||||||
pub(super) height: usize,
|
|
||||||
pub(super) axis_width: usize,
|
|
||||||
pub(super) plot_width: usize,
|
|
||||||
pub(super) count: usize,
|
|
||||||
pub(super) start: usize,
|
|
||||||
pub(super) baseline: usize,
|
|
||||||
pub(super) marker_row: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Layout {
|
|
||||||
pub(super) fn new(
|
|
||||||
day_count: usize,
|
|
||||||
cursor: usize,
|
|
||||||
width: usize,
|
|
||||||
height: usize,
|
|
||||||
label_width: usize,
|
|
||||||
bands: &[Band],
|
|
||||||
) -> Self {
|
|
||||||
// Hide the axis when a complete label would crowd out the bars.
|
|
||||||
let axis_width = if width >= 30 && label_width <= width / 3 {
|
|
||||||
label_width
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
};
|
|
||||||
let plot_width = width - axis_width;
|
|
||||||
let count = day_count.min(plot_width);
|
|
||||||
let start = cursor.saturating_sub(count - 1).min(day_count - count);
|
|
||||||
let baseline = height + 1;
|
|
||||||
let marker_row = baseline + if bands.len() == 2 { height + 2 } else { 1 };
|
|
||||||
Self {
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
axis_width,
|
|
||||||
plot_width,
|
|
||||||
count,
|
|
||||||
start,
|
|
||||||
baseline,
|
|
||||||
marker_row,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn center(self, index: usize) -> usize {
|
|
||||||
self.axis_width
|
|
||||||
+ (index * self.plot_width / self.count + (index + 1) * self.plot_width / self.count
|
|
||||||
- 1)
|
|
||||||
/ 2
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
//! Paint signed bar cells and numeric axes using the shared layout and scale.
|
|
||||||
|
|
||||||
use super::Renderer;
|
|
||||||
use super::layout::Layout;
|
|
||||||
use super::tick;
|
|
||||||
use crate::analytics::styles::secondary_style;
|
|
||||||
use crate::analytics::styles::series_colors;
|
|
||||||
use ratatui::buffer::Buffer;
|
|
||||||
use ratatui::style::Style;
|
|
||||||
use ratatui::style::Styled;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
|
|
||||||
/// A signed stack grows away from the baseline; amounts are nonnegative within each band.
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub(super) enum Band {
|
|
||||||
Positive,
|
|
||||||
Negative,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Band {
|
|
||||||
pub(super) fn amount(self, value: f64) -> f64 {
|
|
||||||
match self {
|
|
||||||
Self::Positive => value,
|
|
||||||
Self::Negative => -value,
|
|
||||||
}
|
|
||||||
.max(/*other*/ 0.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn row_y(self, baseline: usize, row: usize) -> usize {
|
|
||||||
match self {
|
|
||||||
Self::Positive => baseline - row - 1,
|
|
||||||
Self::Negative => baseline + row + 1,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn partial_glyph(self, level: usize) -> char {
|
|
||||||
// Reversing the complementary lower block paints a top-anchored partial refund.
|
|
||||||
let index = match self {
|
|
||||||
Self::Negative if level < 8 => 8 - level,
|
|
||||||
Self::Positive | Self::Negative => level,
|
|
||||||
};
|
|
||||||
[' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'][index]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Renderer<'_> {
|
|
||||||
pub(super) fn paint_bars(&self, buf: &mut Buffer) {
|
|
||||||
let Layout {
|
|
||||||
axis_width,
|
|
||||||
baseline,
|
|
||||||
count,
|
|
||||||
height,
|
|
||||||
plot_width,
|
|
||||||
start,
|
|
||||||
..
|
|
||||||
} = self.layout;
|
|
||||||
let colors = series_colors();
|
|
||||||
for (index, parts) in self.values[start..start + count].iter().enumerate() {
|
|
||||||
let left = axis_width + index * plot_width / count;
|
|
||||||
let step = (index + 1) * plot_width / count - index * plot_width / count;
|
|
||||||
let bar_width = (step * 2 / 3).clamp(/*min*/ 1, /*max*/ 12);
|
|
||||||
let x = left + (step - bar_width) / 2;
|
|
||||||
for band in self.bands {
|
|
||||||
let plotted = parts.iter().map(|value| band.amount(*value)).sum::<f64>();
|
|
||||||
let scaled = ((plotted * (height * 8) as f64 / self.peak) as usize)
|
|
||||||
.max(usize::from(plotted > 0.0));
|
|
||||||
for row in 0..height {
|
|
||||||
let level = scaled.saturating_sub(row * 8).min(/*other*/ 8);
|
|
||||||
if level == 0 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let reverse = matches!(band, Band::Negative) && level < 8;
|
|
||||||
let glyph = band.partial_glyph(level);
|
|
||||||
let bottom = (row * 8) as f64 * self.peak / (height * 8) as f64;
|
|
||||||
let top =
|
|
||||||
((row * 8 + level) as f64 * self.peak / (height * 8) as f64).min(plotted);
|
|
||||||
let sample = bottom + (top - bottom) / 2.0;
|
|
||||||
let mut cumulative = 0.0;
|
|
||||||
let color = parts
|
|
||||||
.iter()
|
|
||||||
.position(|value| {
|
|
||||||
cumulative += band.amount(*value);
|
|
||||||
sample < cumulative
|
|
||||||
})
|
|
||||||
.unwrap_or(/*default*/ 3);
|
|
||||||
let y = band.row_y(baseline, row);
|
|
||||||
for col in x..x + bar_width {
|
|
||||||
let cell = &mut buf[(col as u16, y as u16)];
|
|
||||||
cell.set_char(glyph).set_fg(colors[color]);
|
|
||||||
if reverse {
|
|
||||||
cell.set_style(Style::default().reversed());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn paint_axis(&self, buf: &mut Buffer) {
|
|
||||||
let Layout {
|
|
||||||
axis_width,
|
|
||||||
baseline,
|
|
||||||
height,
|
|
||||||
width,
|
|
||||||
..
|
|
||||||
} = self.layout;
|
|
||||||
for x in axis_width..width {
|
|
||||||
buf[(x as u16, baseline as u16)]
|
|
||||||
.set_char('─')
|
|
||||||
.set_style(Style::default().dim());
|
|
||||||
}
|
|
||||||
if axis_width > 0 {
|
|
||||||
let mut ticks = vec![(1, self.peak), (baseline, 0.0)];
|
|
||||||
if height >= 4 {
|
|
||||||
ticks.push((1 + height / 2, self.peak / 2.0));
|
|
||||||
}
|
|
||||||
if self.bands.len() == 2 {
|
|
||||||
ticks.push((baseline + height, -self.peak));
|
|
||||||
}
|
|
||||||
for (y, value) in ticks {
|
|
||||||
let label = tick(value);
|
|
||||||
let x = axis_width.saturating_sub(label.len() + 1);
|
|
||||||
buf.set_line(
|
|
||||||
x as u16,
|
|
||||||
y as u16,
|
|
||||||
&Line::from(label.set_style(secondary_style())),
|
|
||||||
axis_width as u16,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,535 +0,0 @@
|
|||||||
//! Chart scales, signed bands, missing days, narrow viewports, and terminal palettes.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::analytics::models::AccountAnalyticsHistory;
|
|
||||||
use crate::analytics::render::categories;
|
|
||||||
use crate::analytics::styles::series_colors;
|
|
||||||
use crate::terminal_palette::with_test_default_colors;
|
|
||||||
use crate::terminal_probe::DefaultColors;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
|
|
||||||
fn value(key: &str, value: f64) -> AccountAnalyticsValue {
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: key.into(),
|
|
||||||
label: key.into(),
|
|
||||||
value,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn display(chart: &Chart) -> String {
|
|
||||||
let text = chart
|
|
||||||
.lines
|
|
||||||
.iter()
|
|
||||||
.map(|line| line.to_string().trim_end().to_owned())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
let mut palette = Vec::new();
|
|
||||||
let mut rows = Vec::new();
|
|
||||||
for (row, line) in chart.lines.iter().enumerate() {
|
|
||||||
let mut previous = None;
|
|
||||||
let mut runs = Vec::new();
|
|
||||||
let mut column = 0;
|
|
||||||
for span in &line.spans {
|
|
||||||
let style = format!("{:?}", span.style);
|
|
||||||
let index = palette
|
|
||||||
.iter()
|
|
||||||
.position(|candidate| *candidate == style)
|
|
||||||
.unwrap_or_else(|| {
|
|
||||||
palette.push(style);
|
|
||||||
palette.len() - 1
|
|
||||||
});
|
|
||||||
if previous != Some(index) {
|
|
||||||
runs.push(format!("{column}:{index}"));
|
|
||||||
previous = Some(index);
|
|
||||||
}
|
|
||||||
column += span.width();
|
|
||||||
}
|
|
||||||
rows.push(format!("{row}: {}", runs.join(" ")));
|
|
||||||
}
|
|
||||||
let palette = palette
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(index, style)| format!("{index}: {style}"))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
format!(
|
|
||||||
"{text}\n\nPalette:\n{palette}\nRows (column:palette):\n{}",
|
|
||||||
rows.join("\n")
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn numeric_axes_use_readable_intervals() {
|
|
||||||
use AccountAnalyticsUnit::Count;
|
|
||||||
use AccountAnalyticsUnit::Credits;
|
|
||||||
use AccountAnalyticsUnit::RelativeUsage;
|
|
||||||
use AccountAnalyticsUnit::Tokens;
|
|
||||||
let cases = [
|
|
||||||
(82.0, Count, 100.0),
|
|
||||||
(4_400.0, Credits, 5_000.0),
|
|
||||||
(4_999.0, Credits, 5_000.0),
|
|
||||||
(5_001.0, Credits, 6_000.0),
|
|
||||||
(49.0, Count, 50.0),
|
|
||||||
(1.0, Count, 2.0),
|
|
||||||
(3.0, Count, 4.0),
|
|
||||||
(1_337.0, Credits, 1_500.0),
|
|
||||||
(0.07, Credits, 0.08),
|
|
||||||
(0.000004, Credits, 0.000004),
|
|
||||||
(82.0, RelativeUsage, 100.0),
|
|
||||||
(1.0, Tokens, 2.0),
|
|
||||||
];
|
|
||||||
assert_eq!(
|
|
||||||
cases.map(|(peak, unit, _)| axis_max(peak, unit)),
|
|
||||||
cases.map(|(_, _, expected)| expected)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stacked_parts_keep_the_remainder_and_full_denominator() {
|
|
||||||
let values = vec![
|
|
||||||
value("a", /*value*/ 4.0),
|
|
||||||
value("b", /*value*/ 2.0),
|
|
||||||
value("c", /*value*/ 1.0),
|
|
||||||
value("d", /*value*/ 6.0),
|
|
||||||
value("e", /*value*/ -1.0),
|
|
||||||
];
|
|
||||||
let categories = vec![values[1].clone(), values[0].clone(), values[2].clone()];
|
|
||||||
assert_eq!(parts(&values, &categories), [2.0, 4.0, 1.0, 5.0]);
|
|
||||||
let day = AccountAnalyticsDay {
|
|
||||||
date: "2026-01-15".parse().unwrap(),
|
|
||||||
total: 20.0,
|
|
||||||
values,
|
|
||||||
};
|
|
||||||
let date = day.date;
|
|
||||||
assert_eq!(peak(&[(date, Some(&day))], &categories), 20.0);
|
|
||||||
let refund = AccountAnalyticsDay {
|
|
||||||
total: -1.0,
|
|
||||||
values: vec![value("a", /*value*/ 4.0), value("b", /*value*/ -5.0)],
|
|
||||||
..day
|
|
||||||
};
|
|
||||||
assert_eq!(peak(&[(date, Some(&refund))], &categories), 9.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn signed_chart_on_light_terminal() {
|
|
||||||
signed_chart(
|
|
||||||
"light",
|
|
||||||
DefaultColors {
|
|
||||||
fg: (0, 0, 0),
|
|
||||||
bg: (255, 255, 255),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn signed_chart_on_dark_terminal() {
|
|
||||||
signed_chart(
|
|
||||||
"dark",
|
|
||||||
DefaultColors {
|
|
||||||
fg: (230, 230, 230),
|
|
||||||
bg: (16, 16, 16),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn signed_chart(theme: &str, colors: DefaultColors) {
|
|
||||||
let history = AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::Credits,
|
|
||||||
updated_at: None,
|
|
||||||
data: vec![
|
|
||||||
AccountAnalyticsDay {
|
|
||||||
date: "2026-01-13".parse().unwrap(),
|
|
||||||
total: 8.0,
|
|
||||||
values: vec![value("a", /*value*/ 10.0), value("b", /*value*/ -2.0)],
|
|
||||||
},
|
|
||||||
AccountAnalyticsDay {
|
|
||||||
date: "2026-01-14".parse().unwrap(),
|
|
||||||
total: -3.0,
|
|
||||||
values: vec![value("a", /*value*/ 1.0), value("b", /*value*/ -4.0)],
|
|
||||||
},
|
|
||||||
AccountAnalyticsDay {
|
|
||||||
date: "2026-01-15".parse().unwrap(),
|
|
||||||
total: 0.0,
|
|
||||||
values: vec![value("a", /*value*/ 3.0), value("b", /*value*/ -3.0)],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
let days = history
|
|
||||||
.data
|
|
||||||
.iter()
|
|
||||||
.map(|day| (day.date, Some(day)))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let categories = categories(&history);
|
|
||||||
with_test_default_colors(colors, || {
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&categories,
|
|
||||||
/*cursor*/ 1,
|
|
||||||
/*width*/ 44,
|
|
||||||
/*height*/ 4,
|
|
||||||
history.unit,
|
|
||||||
);
|
|
||||||
assert_eq!(rendered.bands, 2);
|
|
||||||
insta::assert_snapshot!(format!("signed_chart_{theme}"), display(&rendered));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn missing_zero_and_narrow_charts_keep_the_selection_visible() {
|
|
||||||
let zero = AccountAnalyticsDay {
|
|
||||||
date: "2026-01-14".parse().unwrap(),
|
|
||||||
total: 0.0,
|
|
||||||
values: vec![value("a", /*value*/ 0.0)],
|
|
||||||
};
|
|
||||||
let used = AccountAnalyticsDay {
|
|
||||||
date: "2026-01-15".parse().unwrap(),
|
|
||||||
total: 5.0,
|
|
||||||
values: vec![value("a", /*value*/ 5.0)],
|
|
||||||
};
|
|
||||||
let days = [
|
|
||||||
("2026-01-13".parse().unwrap(), None),
|
|
||||||
(zero.date, Some(&zero)),
|
|
||||||
(used.date, Some(&used)),
|
|
||||||
];
|
|
||||||
with_test_default_colors(
|
|
||||||
DefaultColors {
|
|
||||||
fg: (230, 230, 230),
|
|
||||||
bg: (16, 16, 16),
|
|
||||||
},
|
|
||||||
|| {
|
|
||||||
let mut snapshots = Vec::new();
|
|
||||||
for (width, cursor) in [(36, 0), (36, 1), (8, 2), (1, 2)] {
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&used.values,
|
|
||||||
cursor,
|
|
||||||
width,
|
|
||||||
/*height*/ 3,
|
|
||||||
AccountAnalyticsUnit::Count,
|
|
||||||
);
|
|
||||||
assert_eq!(rendered.bands, 1);
|
|
||||||
assert!(rendered.lines.iter().all(|line| line.width() <= width));
|
|
||||||
assert_eq!(
|
|
||||||
rendered
|
|
||||||
.lines
|
|
||||||
.iter()
|
|
||||||
.flat_map(|line| &line.spans)
|
|
||||||
.filter(|span| span.content == "▲")
|
|
||||||
.count(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
if cursor == 0 {
|
|
||||||
let dash = rendered
|
|
||||||
.lines
|
|
||||||
.iter()
|
|
||||||
.find_map(|line| line.to_string().find('—'));
|
|
||||||
let cursor = rendered
|
|
||||||
.lines
|
|
||||||
.iter()
|
|
||||||
.find_map(|line| line.to_string().find('▲'));
|
|
||||||
assert_eq!(dash, cursor);
|
|
||||||
}
|
|
||||||
snapshots.push(format!(
|
|
||||||
"width={width}, cursor={cursor}\n{}",
|
|
||||||
display(&rendered)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn zero_credit_history_uses_a_readable_scale() {
|
|
||||||
let history = crate::analytics::normalize::history(
|
|
||||||
serde_json::from_str(r#"{"data":[]}"#).unwrap(),
|
|
||||||
crate::analytics::models::AccountAnalyticsReport::Credits,
|
|
||||||
crate::analytics::models::AccountAnalyticsGrouping::Surface,
|
|
||||||
"2026-01-09".parse().unwrap(),
|
|
||||||
"2026-01-15".parse().unwrap(),
|
|
||||||
)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
let days = history
|
|
||||||
.data
|
|
||||||
.iter()
|
|
||||||
.map(|day| (day.date, Some(day)))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&[],
|
|
||||||
/*cursor*/ 6,
|
|
||||||
/*width*/ 44,
|
|
||||||
/*height*/ 4,
|
|
||||||
history.unit,
|
|
||||||
);
|
|
||||||
assert_eq!(axis_max(peak(&days, &[]), history.unit), 1.0);
|
|
||||||
insta::assert_snapshot!(display(&rendered));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn partial_cells_use_the_midpoint_and_descend_from_the_baseline() {
|
|
||||||
let categories = vec![value("a", /*value*/ 0.8), value("b", /*value*/ 0.95)];
|
|
||||||
let mut snapshots = Vec::new();
|
|
||||||
for sign in [1.0, -1.0] {
|
|
||||||
let day = AccountAnalyticsDay {
|
|
||||||
date: "2026-01-14".parse().unwrap(),
|
|
||||||
total: 1.75 * sign,
|
|
||||||
values: categories
|
|
||||||
.iter()
|
|
||||||
.map(|value| AccountAnalyticsValue {
|
|
||||||
value: value.value * sign,
|
|
||||||
..value.clone()
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
};
|
|
||||||
let days = [
|
|
||||||
(day.date, Some(&day)),
|
|
||||||
("2026-01-15".parse().unwrap(), None),
|
|
||||||
];
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&categories,
|
|
||||||
/*cursor*/ 1,
|
|
||||||
/*width*/ 12,
|
|
||||||
/*height*/ 1,
|
|
||||||
AccountAnalyticsUnit::Credits,
|
|
||||||
);
|
|
||||||
let cell = &rendered.lines[if sign > 0.0 { 1 } else { 3 }].spans[1];
|
|
||||||
assert_eq!(cell.style.fg, Some(series_colors()[1]));
|
|
||||||
assert_eq!(cell.content.as_ref(), if sign > 0.0 { "▇" } else { "▁" });
|
|
||||||
assert_eq!(
|
|
||||||
cell.style
|
|
||||||
.add_modifier
|
|
||||||
.contains(ratatui::style::Modifier::REVERSED),
|
|
||||||
sign < 0.0
|
|
||||||
);
|
|
||||||
snapshots.push(format!("sign={sign}\n{}", display(&rendered)));
|
|
||||||
}
|
|
||||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn oversized_axes_are_hidden_instead_of_truncated() {
|
|
||||||
let mut snapshots = Vec::new();
|
|
||||||
for (width, total) in [
|
|
||||||
(8, 100_000_000.0),
|
|
||||||
(30, 100_000_000.0),
|
|
||||||
(35, 100_000_000.0),
|
|
||||||
(44, 100_000_000.0),
|
|
||||||
(30, 1e30),
|
|
||||||
] {
|
|
||||||
let day = AccountAnalyticsDay {
|
|
||||||
date: "2026-01-15".parse().unwrap(),
|
|
||||||
total,
|
|
||||||
values: vec![value("a", total)],
|
|
||||||
};
|
|
||||||
let days = [(day.date, Some(&day))];
|
|
||||||
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&day.values,
|
|
||||||
/*cursor*/ 0,
|
|
||||||
width,
|
|
||||||
/*height*/ 4,
|
|
||||||
AccountAnalyticsUnit::Tokens,
|
|
||||||
);
|
|
||||||
let baseline = rendered.lines[5].to_string();
|
|
||||||
assert_eq!(baseline.starts_with('─'), width < 30 || total == 1e30);
|
|
||||||
if width == 8 {
|
|
||||||
assert!(rendered.lines[0].to_string().contains("100M"));
|
|
||||||
}
|
|
||||||
snapshots.push(format!("width={width}\n{}", display(&rendered)));
|
|
||||||
}
|
|
||||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn selected_callout_keeps_the_authoritative_daily_total() {
|
|
||||||
let day = AccountAnalyticsDay {
|
|
||||||
date: "2026-01-15".parse().unwrap(),
|
|
||||||
total: 20.0,
|
|
||||||
values: vec![value("a", /*value*/ 8.0), value("b", /*value*/ 4.0)],
|
|
||||||
};
|
|
||||||
let days = [(day.date, Some(&day))];
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&day.values,
|
|
||||||
/*cursor*/ 0,
|
|
||||||
/*width*/ 44,
|
|
||||||
/*height*/ 4,
|
|
||||||
AccountAnalyticsUnit::Credits,
|
|
||||||
);
|
|
||||||
assert!(display(&rendered).contains("20.00"));
|
|
||||||
assert!(!display(&rendered).contains("12.00"));
|
|
||||||
insta::assert_snapshot!(display(&rendered));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn narrow_long_range_charts_never_truncate_dates() {
|
|
||||||
let start: NaiveDate = "2026-01-01".parse().unwrap();
|
|
||||||
let history = start
|
|
||||||
.iter_days()
|
|
||||||
.take(/*n*/ 30)
|
|
||||||
.map(|date| AccountAnalyticsDay {
|
|
||||||
date,
|
|
||||||
total: 1.0,
|
|
||||||
values: vec![value("a", /*value*/ 1.0)],
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let days = history
|
|
||||||
.iter()
|
|
||||||
.map(|day| (day.date, Some(day)))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let mut snapshots = Vec::new();
|
|
||||||
for (width, expected) in [(1, ""), (2, "15"), (5, "15"), (6, "Jan 15")] {
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&history[0].values,
|
|
||||||
/*cursor*/ 14,
|
|
||||||
width,
|
|
||||||
/*height*/ 3,
|
|
||||||
AccountAnalyticsUnit::Count,
|
|
||||||
);
|
|
||||||
assert_eq!(rendered.lines.last().unwrap().to_string().trim(), expected);
|
|
||||||
snapshots.push(format!("width={width}\n{}", display(&rendered)));
|
|
||||||
}
|
|
||||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tiny_segments_keep_their_series_color_beside_a_large_day() {
|
|
||||||
let large = AccountAnalyticsDay {
|
|
||||||
date: "2026-01-14".parse().unwrap(),
|
|
||||||
total: 100.0,
|
|
||||||
values: vec![value("a", /*value*/ 100.0)],
|
|
||||||
};
|
|
||||||
let mut snapshots = Vec::new();
|
|
||||||
for sign in [1.0, -1.0] {
|
|
||||||
let tiny = AccountAnalyticsDay {
|
|
||||||
date: "2026-01-15".parse().unwrap(),
|
|
||||||
total: 0.01 * sign,
|
|
||||||
values: vec![value("a", 0.01 * sign)],
|
|
||||||
};
|
|
||||||
let days = [(large.date, Some(&large)), (tiny.date, Some(&tiny))];
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&large.values,
|
|
||||||
/*cursor*/ 0,
|
|
||||||
/*width*/ 44,
|
|
||||||
/*height*/ 4,
|
|
||||||
AccountAnalyticsUnit::Credits,
|
|
||||||
);
|
|
||||||
let glyph = if sign > 0.0 { "▁" } else { "▇" };
|
|
||||||
let cells = rendered
|
|
||||||
.lines
|
|
||||||
.iter()
|
|
||||||
.flat_map(|line| &line.spans)
|
|
||||||
.filter(|span| span.content == glyph)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
assert!(!cells.is_empty());
|
|
||||||
assert!(
|
|
||||||
cells
|
|
||||||
.iter()
|
|
||||||
.all(|cell| cell.style.fg == Some(series_colors()[0]))
|
|
||||||
);
|
|
||||||
snapshots.push(format!("sign={sign}\n{}", display(&rendered)));
|
|
||||||
}
|
|
||||||
insta::assert_snapshot!(snapshots.join("\n\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn duplicate_message_dates_render_the_full_other_remainder() {
|
|
||||||
use crate::analytics::models::AccountAnalyticsGrouping;
|
|
||||||
use crate::analytics::models::AccountAnalyticsReport;
|
|
||||||
let date = "2026-01-15".parse().unwrap();
|
|
||||||
let response = serde_json::from_value(serde_json::json!({"data": [
|
|
||||||
{"date": "2026-01-15", "totals": {"turns": 10}, "clients": [{"client_id": "CODEX_CLI", "turns": 8}]},
|
|
||||||
{"date": "2026-01-15", "totals": {"turns": 10}, "clients": [{"client_id": "CODEX_CLI", "turns": 8}]}
|
|
||||||
]})).unwrap();
|
|
||||||
let history = crate::analytics::normalize::history(
|
|
||||||
response,
|
|
||||||
AccountAnalyticsReport::Messages,
|
|
||||||
AccountAnalyticsGrouping::Surface,
|
|
||||||
date,
|
|
||||||
date,
|
|
||||||
)
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
let day = &history.data[0];
|
|
||||||
let rendered = chart(
|
|
||||||
&[(date, Some(day))],
|
|
||||||
&day.values,
|
|
||||||
/*cursor*/ 0,
|
|
||||||
/*width*/ 44,
|
|
||||||
/*height*/ 10,
|
|
||||||
AccountAnalyticsUnit::Count,
|
|
||||||
);
|
|
||||||
insta::assert_snapshot!(display(&rendered));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn seven_day_totals_render_without_selecting_each_bar() {
|
|
||||||
let start: NaiveDate = "2026-01-01".parse().unwrap();
|
|
||||||
let rows = (0..7)
|
|
||||||
.map(|index| AccountAnalyticsDay {
|
|
||||||
date: start + chrono::Duration::days(index),
|
|
||||||
total: 111.0 + index as f64 * 100.0,
|
|
||||||
values: vec![value("a", 111.0 + index as f64 * 100.0)],
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let days = rows
|
|
||||||
.iter()
|
|
||||||
.map(|day| (day.date, Some(day)))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&rows[0].values,
|
|
||||||
/*cursor*/ 3,
|
|
||||||
/*width*/ 100,
|
|
||||||
/*height*/ 8,
|
|
||||||
AccountAnalyticsUnit::Count,
|
|
||||||
);
|
|
||||||
let text = display(&rendered);
|
|
||||||
for day in &rows {
|
|
||||||
assert!(text.contains(&day.total.to_string()));
|
|
||||||
}
|
|
||||||
insta::assert_snapshot!("seven_day_totals", text);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn narrow_equal_height_totals_remain_separate_numbers() {
|
|
||||||
let start: NaiveDate = "2026-01-01".parse().unwrap();
|
|
||||||
let rows = (0..7)
|
|
||||||
.map(|index| AccountAnalyticsDay {
|
|
||||||
date: start + chrono::Duration::days(index),
|
|
||||||
total: 111.0,
|
|
||||||
values: vec![value("a", /*value*/ 111.0)],
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let days = rows
|
|
||||||
.iter()
|
|
||||||
.map(|day| (day.date, Some(day)))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let mut screens = Vec::new();
|
|
||||||
for width in [21, 28, 35] {
|
|
||||||
let rendered = chart(
|
|
||||||
&days,
|
|
||||||
&rows[0].values,
|
|
||||||
/*cursor*/ 3,
|
|
||||||
width,
|
|
||||||
/*height*/ 4,
|
|
||||||
AccountAnalyticsUnit::Count,
|
|
||||||
);
|
|
||||||
let text = rendered
|
|
||||||
.lines
|
|
||||||
.iter()
|
|
||||||
.map(|line| line.to_string().trim_end().to_owned())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
assert!(text.contains("111"));
|
|
||||||
assert!(!text.contains("111111"));
|
|
||||||
screens.push(text);
|
|
||||||
}
|
|
||||||
insta::assert_snapshot!(screens.join("\n\n"));
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
//! In-flight profile responses cannot expose data after the active account changes.
|
|
||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn profile_rejects_account_change_during_success_or_error_response() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
for status in [200, 404, 503] {
|
|
||||||
server.reset().await;
|
|
||||||
let (home, live) = live(&server, "plus").await;
|
|
||||||
let home_path = home.path().to_path_buf();
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/backend-api/wham/profiles/me"))
|
|
||||||
.and(header("chatgpt-account-id", "account-a"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
sign_in(&home_path, "account-a", "user-b", "plus");
|
|
||||||
ResponseTemplate::new(status)
|
|
||||||
.set_body_json(json!({"stats":{"lifetime_tokens":123}}))
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
assert_eq!(
|
|
||||||
live.profile().await.err().unwrap(),
|
|
||||||
"Account changed. Press R to refresh Analytics."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
//! Restored dashboard, visible controls, and responsive report regression coverage.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn report_controls_show_dates_and_update_time() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Business);
|
|
||||||
view.section = Section::Usage;
|
|
||||||
view.sections[Section::Usage].group = 6;
|
|
||||||
fixture::seed_reports(&mut view);
|
|
||||||
view.end_date = "2027-01-02".parse().unwrap();
|
|
||||||
let output = screen(&mut view, /*width*/ 40, /*height*/ 16);
|
|
||||||
assert!(output.contains("12/27/2026–01/02/2027"));
|
|
||||||
assert!(output.contains("g Token type · m All models"));
|
|
||||||
assert!(output.contains("Updated · Sep 2 16:00 UTC"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn twelve_hour_metadata_keeps_utc_across_renderers() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Business);
|
|
||||||
view.clock_format = crate::clock_format::ClockFormat::TwelveHour;
|
|
||||||
view.section = Section::Usage;
|
|
||||||
let controls = screen(&mut view, /*width*/ 40, /*height*/ 16);
|
|
||||||
view.zoomed = false;
|
|
||||||
view.tasks = Load::Ready(tasks::Chats {
|
|
||||||
rows: vec![tasks::Chat {
|
|
||||||
title: "Clock fixture".into(),
|
|
||||||
task: None,
|
|
||||||
}],
|
|
||||||
updated_at: Some("2026-09-02T16:00:00Z".parse().unwrap()),
|
|
||||||
..tasks::Chats::default()
|
|
||||||
});
|
|
||||||
let mut output = controls
|
|
||||||
.lines()
|
|
||||||
.filter(|line| line.contains("Updated"))
|
|
||||||
.map(str::to_owned)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
for lines in [
|
|
||||||
view.history_lines(Section::Usage, /*width*/ 40, /*height*/ 16)
|
|
||||||
.lines,
|
|
||||||
view.help_lines(/*width*/ 40),
|
|
||||||
view.task_lines(/*width*/ 80).0,
|
|
||||||
] {
|
|
||||||
output.extend(
|
|
||||||
lines
|
|
||||||
.iter()
|
|
||||||
.map(ToString::to_string)
|
|
||||||
.filter(|line| line.contains("Updated") || line.contains("Report updated")),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
insta::assert_snapshot!(output.join("\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tall_reports_use_available_height_and_wide_reports_put_details_beside_plot() {
|
|
||||||
for (width, height) in [(80, 60), (180, 60)] {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Business);
|
|
||||||
view.section = Section::Usage;
|
|
||||||
let output = screen(&mut view, width, height);
|
|
||||||
let plot_rows = output.lines().filter(|line| line.contains('█')).count();
|
|
||||||
assert!(
|
|
||||||
plot_rows > 14,
|
|
||||||
"only {plot_rows} plot rows at {width} columns"
|
|
||||||
);
|
|
||||||
assert!(output.contains("731,000 tokens"));
|
|
||||||
assert!(!output.contains("scroll"));
|
|
||||||
if width == 180 {
|
|
||||||
assert!(
|
|
||||||
output
|
|
||||||
.lines()
|
|
||||||
.any(|line| line.contains("4.4M tokens") && line.contains('─'))
|
|
||||||
);
|
|
||||||
insta::assert_snapshot!(output);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
//! Responsive navigation and report loading regression coverage.
|
|
||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn reports_keep_tabs_fixed_and_expose_data_on_small_screens() {
|
|
||||||
for (width, height) in [(120, 36), (80, 24), (40, 16)] {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Business);
|
|
||||||
view.section = Section::Usage;
|
|
||||||
let tokens = screen(&mut view, width, height);
|
|
||||||
assert!(tokens.contains("tokens"));
|
|
||||||
assert!(tokens.contains("Sep 2"));
|
|
||||||
let tabs = tokens.lines().take(3).collect::<Vec<_>>();
|
|
||||||
view.sections[Section::Usage].history = Load::Error("Couldn't load tokens.".into());
|
|
||||||
let failed = screen(&mut view, width, height);
|
|
||||||
assert_eq!(tabs, failed.lines().take(3).collect::<Vec<_>>());
|
|
||||||
assert!(failed.contains("Couldn't load tokens."));
|
|
||||||
if width == 40 {
|
|
||||||
insta::assert_snapshot!(format!("{tokens}\n{failed}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keyboard_tabs_and_help_preserve_report_reading_position() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Business);
|
|
||||||
view.section = Section::Usage;
|
|
||||||
view.sections[Section::Usage].detail = Some(6);
|
|
||||||
screen(&mut view, /*width*/ 80, /*height*/ 16);
|
|
||||||
press(&mut view, KeyCode::PageDown);
|
|
||||||
screen(&mut view, /*width*/ 80, /*height*/ 16);
|
|
||||||
let offset = view.scroll_offset();
|
|
||||||
press(&mut view, KeyCode::BackTab);
|
|
||||||
assert_eq!(view.section, Section::Credits);
|
|
||||||
screen(&mut view, /*width*/ 80, /*height*/ 16);
|
|
||||||
press(&mut view, KeyCode::PageDown);
|
|
||||||
screen(&mut view, /*width*/ 80, /*height*/ 16);
|
|
||||||
press(&mut view, KeyCode::Tab);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.section,
|
|
||||||
view.scroll_offset(),
|
|
||||||
view.sections[Section::Usage].detail
|
|
||||||
),
|
|
||||||
(Section::Usage, offset, Some(6))
|
|
||||||
);
|
|
||||||
view.handle_key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::SHIFT));
|
|
||||||
let help = screen(&mut view, /*width*/ 40, /*height*/ 16);
|
|
||||||
assert!(help.contains("Usage shortcuts"));
|
|
||||||
assert!(help.lines().nth_back(/*n*/ 1).unwrap().contains("scroll"));
|
|
||||||
assert!(!help.lines().last().unwrap().contains("tab report"));
|
|
||||||
insta::assert_snapshot!("narrow_help", help);
|
|
||||||
press(&mut view, KeyCode::PageDown);
|
|
||||||
screen(&mut view, /*width*/ 40, /*height*/ 16);
|
|
||||||
assert!(view.scroll_offset() > 0);
|
|
||||||
press(&mut view, KeyCode::Esc);
|
|
||||||
assert_eq!(
|
|
||||||
(view.show_help, view.is_done, view.scroll_offset()),
|
|
||||||
(false, false, offset)
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Char('?'));
|
|
||||||
assert_eq!(view.scroll_offset(), 0);
|
|
||||||
press(&mut view, KeyCode::Char('?'));
|
|
||||||
assert_eq!(view.scroll_offset(), offset);
|
|
||||||
press(&mut view, KeyCode::Char('z'));
|
|
||||||
screen(&mut view, /*width*/ 80, /*height*/ 16);
|
|
||||||
let dashboard_offset = view.scroll_offset();
|
|
||||||
press(&mut view, KeyCode::Char('?'));
|
|
||||||
press(&mut view, KeyCode::Esc);
|
|
||||||
assert_eq!(
|
|
||||||
(view.zoomed, view.scroll_offset()),
|
|
||||||
(false, dashboard_offset)
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
screen(&mut view, /*width*/ 80, /*height*/ 16);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.zoomed,
|
|
||||||
view.scroll_offset(),
|
|
||||||
view.sections[Section::Usage].detail
|
|
||||||
),
|
|
||||||
(true, offset, Some(6))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn dashboard_navigation_scrolls_to_selected_card() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
press(&mut view, KeyCode::Char('z'));
|
|
||||||
screen(&mut view, /*width*/ 80, /*height*/ 24);
|
|
||||||
press(&mut view, KeyCode::Char('6'));
|
|
||||||
let output = screen(&mut view, /*width*/ 80, /*height*/ 24);
|
|
||||||
assert!(view.scroll_offset() > 0);
|
|
||||||
assert!(
|
|
||||||
output
|
|
||||||
.lines()
|
|
||||||
.any(|line| line.contains('▸') && line.contains("Chats"))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,230 +0,0 @@
|
|||||||
//! Fixed analytics navigation and responsive report space.
|
|
||||||
//! Tabs and hints never wrap or move when a report loads, changes range, or becomes empty.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::styles::secondary_style;
|
|
||||||
use crate::analytics::models::AccountAnalyticsHistory;
|
|
||||||
use crate::analytics::models::AccountAnalyticsValue;
|
|
||||||
use ratatui::buffer::Buffer;
|
|
||||||
use ratatui::layout::Constraint;
|
|
||||||
use ratatui::layout::Layout;
|
|
||||||
use ratatui::layout::Rect;
|
|
||||||
use ratatui::style::Styled;
|
|
||||||
use ratatui::style::Stylize;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
use ratatui::widgets::Paragraph;
|
|
||||||
use ratatui::widgets::Widget;
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
pub(super) fn columns(left: Line<'static>, right: Line<'static>, width: usize) -> Line<'static> {
|
|
||||||
let padding = width
|
|
||||||
.saturating_sub(left.width() + right.width())
|
|
||||||
.max(/*other*/ 1);
|
|
||||||
let mut spans = left.spans;
|
|
||||||
spans.push(" ".repeat(padding).into());
|
|
||||||
spans.extend(right.spans);
|
|
||||||
Line::from(spans)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Join independently stacked panels without leaving holes below shorter sections.
|
|
||||||
pub(super) fn join_columns(
|
|
||||||
left: &[Line<'static>],
|
|
||||||
right: &[Line<'static>],
|
|
||||||
column_width: usize,
|
|
||||||
) -> Vec<Line<'static>> {
|
|
||||||
(0..left.len().max(right.len()))
|
|
||||||
.map(|row| {
|
|
||||||
let left = left.get(row).cloned().unwrap_or_default();
|
|
||||||
let mut line = columns(left, Line::default(), column_width + 4);
|
|
||||||
if let Some(right) = right.get(row) {
|
|
||||||
line.spans.extend(right.spans.iter().cloned());
|
|
||||||
}
|
|
||||||
line
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn categories(history: &AccountAnalyticsHistory) -> Vec<AccountAnalyticsValue> {
|
|
||||||
let mut totals = BTreeMap::<String, AccountAnalyticsValue>::new();
|
|
||||||
for value in history.data.iter().flat_map(|day| &day.values) {
|
|
||||||
totals
|
|
||||||
.entry(value.key.clone())
|
|
||||||
.or_insert_with(|| AccountAnalyticsValue {
|
|
||||||
value: 0.0,
|
|
||||||
..value.clone()
|
|
||||||
})
|
|
||||||
.value += value.value;
|
|
||||||
}
|
|
||||||
let mut values = totals.into_values().collect::<Vec<_>>();
|
|
||||||
values.sort_by(|a, b| {
|
|
||||||
b.value
|
|
||||||
.abs()
|
|
||||||
.total_cmp(&a.value.abs())
|
|
||||||
.then_with(|| a.key.cmp(&b.key))
|
|
||||||
});
|
|
||||||
values
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The last plotted category collects all remaining values without renormalizing them.
|
|
||||||
pub(super) fn parts(
|
|
||||||
values: &[AccountAnalyticsValue],
|
|
||||||
categories: &[AccountAnalyticsValue],
|
|
||||||
) -> [f64; 4] {
|
|
||||||
let mut parts = [0.0; 4];
|
|
||||||
for value in values {
|
|
||||||
let index = categories
|
|
||||||
.iter()
|
|
||||||
.take(/*n*/ 3)
|
|
||||||
.position(|category| category.key == value.key)
|
|
||||||
.unwrap_or(/*default*/ 3);
|
|
||||||
parts[index] += value.value;
|
|
||||||
}
|
|
||||||
parts
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn render(&mut self, area: Rect, buf: &mut Buffer) {
|
|
||||||
self.poll_reports();
|
|
||||||
let inset = u16::from(area.width > 2);
|
|
||||||
let inner = Rect {
|
|
||||||
x: area.x + inset,
|
|
||||||
width: area.width.saturating_sub(inset * 2),
|
|
||||||
..area
|
|
||||||
};
|
|
||||||
let width = usize::from(inner.width).max(/*other*/ 1);
|
|
||||||
let [title, tabs, rule, controls, body, hints] = Layout::vertical([
|
|
||||||
Constraint::Length(1),
|
|
||||||
Constraint::Length(1),
|
|
||||||
Constraint::Length(1),
|
|
||||||
Constraint::Length(if width >= 100 { 2 } else { 3 }),
|
|
||||||
Constraint::Min(1),
|
|
||||||
Constraint::Length(2),
|
|
||||||
])
|
|
||||||
.areas(inner);
|
|
||||||
let account = self.live.as_ref().and_then(|live| live.account_label());
|
|
||||||
let plan = self
|
|
||||||
.account
|
|
||||||
.ready()
|
|
||||||
.map(|plan| crate::subscription::SubscriptionDisplay::Analytics.label(*plan));
|
|
||||||
let heading = Line::from(vec![
|
|
||||||
plan.map(|plan| format!("Usage · {plan}"))
|
|
||||||
.unwrap_or_else(|| "Usage".into())
|
|
||||||
.bold(),
|
|
||||||
account
|
|
||||||
.map(|account| format!(" · {account}"))
|
|
||||||
.unwrap_or_default()
|
|
||||||
.set_style(secondary_style()),
|
|
||||||
]);
|
|
||||||
crate::line_truncation::truncate_line_with_ellipsis_if_overflow(heading, width)
|
|
||||||
.render(title, buf);
|
|
||||||
let visible = self.visible_sections();
|
|
||||||
let labels = visible
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(index, section)| {
|
|
||||||
if width >= 80 {
|
|
||||||
format!("{} {}", index + 1, self.tab_label(*section))
|
|
||||||
} else {
|
|
||||||
self.tab_label(*section).to_owned()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let selected = visible
|
|
||||||
.iter()
|
|
||||||
.position(|section| *section == self.section)
|
|
||||||
.unwrap_or_default();
|
|
||||||
self.tab_hits = crate::bottom_pane::render_filled_tab_bar(
|
|
||||||
&labels.iter().map(String::as_str).collect::<Vec<_>>(),
|
|
||||||
selected,
|
|
||||||
tabs,
|
|
||||||
buf,
|
|
||||||
)
|
|
||||||
.into_iter()
|
|
||||||
.map(|(index, rect)| (visible[index], rect))
|
|
||||||
.collect();
|
|
||||||
// Keep a visible selection on screen across reflow, while retaining intentional
|
|
||||||
// reading positions when the user has scrolled away from that selection.
|
|
||||||
if !self.show_help && self.report_area != body && self.selection_visible {
|
|
||||||
self.follow_selection = true;
|
|
||||||
}
|
|
||||||
self.body_area = body;
|
|
||||||
Line::from("─".repeat(width)).dim().render(rule, buf);
|
|
||||||
self.render_controls(controls, buf);
|
|
||||||
self.viewport_height = usize::from(body.height).max(/*other*/ 1);
|
|
||||||
let (lines, selection) = if self.show_help {
|
|
||||||
(self.help_lines(width), 0..1)
|
|
||||||
} else if visible.is_empty() {
|
|
||||||
let message = self
|
|
||||||
.account
|
|
||||||
.message()
|
|
||||||
.unwrap_or("Analytics is not available for this account type.");
|
|
||||||
(
|
|
||||||
textwrap::wrap(message, width)
|
|
||||||
.into_iter()
|
|
||||||
.map(|line| Line::from(line.into_owned()))
|
|
||||||
.collect(),
|
|
||||||
0..1,
|
|
||||||
)
|
|
||||||
} else if !self.zoomed {
|
|
||||||
self.dashboard_lines(width, self.viewport_height)
|
|
||||||
} else {
|
|
||||||
let mut height = (self.viewport_height / 3).clamp(/*min*/ 2, /*max*/ 10);
|
|
||||||
if body.height < 15 || width < 50 {
|
|
||||||
height = 0;
|
|
||||||
}
|
|
||||||
let mut panel = self.panel(self.section, width, height);
|
|
||||||
if panel.chart_bands > 0 {
|
|
||||||
let overhead = panel.lines.len().saturating_sub(height * panel.chart_bands);
|
|
||||||
let available = self.viewport_height.saturating_sub(overhead) / panel.chart_bands;
|
|
||||||
height = available.max(/*other*/ 2);
|
|
||||||
panel = self.panel(self.section, width, height);
|
|
||||||
}
|
|
||||||
if self.section == super::sections::Section::Summary && self.profile.ready().is_some() {
|
|
||||||
let padding = self.viewport_height.saturating_sub(panel.lines.len()) / 2;
|
|
||||||
panel
|
|
||||||
.lines
|
|
||||||
.splice(0..0, std::iter::repeat_n(Line::default(), padding));
|
|
||||||
}
|
|
||||||
(panel.lines, panel.selection)
|
|
||||||
};
|
|
||||||
if self.zoomed && !self.show_help {
|
|
||||||
self.follow_selection |=
|
|
||||||
std::mem::take(&mut self.sections[self.section].follow_selection_on_focus);
|
|
||||||
}
|
|
||||||
let mut scroll_offset = self.scroll_offset();
|
|
||||||
if self.follow_selection {
|
|
||||||
if selection.start < scroll_offset {
|
|
||||||
scroll_offset = selection.start;
|
|
||||||
} else {
|
|
||||||
let end = selection.start + selection.len().min(self.viewport_height);
|
|
||||||
if end > scroll_offset + self.viewport_height {
|
|
||||||
scroll_offset = end - self.viewport_height;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let scrollable = lines.len() > self.viewport_height;
|
|
||||||
self.max_scroll = lines.len().saturating_sub(self.viewport_height);
|
|
||||||
scroll_offset = scroll_offset.min(self.max_scroll);
|
|
||||||
*self.scroll_offset_mut() = scroll_offset;
|
|
||||||
self.follow_selection = false;
|
|
||||||
if !self.show_help {
|
|
||||||
self.report_area = body;
|
|
||||||
self.selection_visible = (!self.zoomed
|
|
||||||
|| matches!(
|
|
||||||
self.section,
|
|
||||||
super::sections::Section::Chats | super::sections::Section::Plan
|
|
||||||
))
|
|
||||||
&& selection.start < scroll_offset + self.viewport_height
|
|
||||||
&& selection.start >= scroll_offset;
|
|
||||||
}
|
|
||||||
Paragraph::new(lines)
|
|
||||||
.scroll(
|
|
||||||
/*offset*/ (scroll_offset.min(usize::from(u16::MAX)) as u16, 0),
|
|
||||||
)
|
|
||||||
.render(body, buf);
|
|
||||||
self.mouse_context = Some((self.section, self.show_help, self.zoomed));
|
|
||||||
Paragraph::new(self.footer_lines(width, scrollable))
|
|
||||||
.style(secondary_style())
|
|
||||||
.render(hints, buf);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,289 +0,0 @@
|
|||||||
//! Projects endpoint-specific backend models into inputs for display normalization.
|
|
||||||
//! This representation is never used to deserialize HTTP responses.
|
|
||||||
//! Optional fields select the inputs used by each report; missing backend values stay missing.
|
|
||||||
|
|
||||||
use codex_backend_client::AnalyticsResponse;
|
|
||||||
use codex_backend_client::analytics_models as backend;
|
|
||||||
|
|
||||||
/// Report values projected for normalization after endpoint-specific decoding.
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct AnalyticsData {
|
|
||||||
pub(super) data: Vec<AnalyticsRecord>,
|
|
||||||
pub(super) units: Option<String>,
|
|
||||||
pub(super) data_freshness_ts: Option<String>,
|
|
||||||
pub(super) series: Option<Vec<AnalyticsSeries>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct AnalyticsSeries {
|
|
||||||
pub(super) key: String,
|
|
||||||
pub(super) label: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct AnalyticsRecord {
|
|
||||||
pub(super) date: String,
|
|
||||||
pub(super) values: Option<std::collections::BTreeMap<String, f64>>,
|
|
||||||
pub(super) product_surface_usage_values: Option<std::collections::BTreeMap<String, f64>>,
|
|
||||||
pub(super) premium_usage_values: Option<PremiumUsage>,
|
|
||||||
pub(super) attribution: Option<Vec<UsageAttribution>>,
|
|
||||||
pub(super) credit_amount: Option<f64>,
|
|
||||||
pub(super) product_surface: Option<String>,
|
|
||||||
pub(super) totals: Option<AnalyticsCount>,
|
|
||||||
pub(super) models: Option<Vec<AnalyticsModel>>,
|
|
||||||
pub(super) groups: Option<Vec<AnalyticsTokenGroup>>,
|
|
||||||
pub(super) clients: Option<Vec<AnalyticsClient>>,
|
|
||||||
pub(super) plugin_usage_overviews: Option<Vec<AnalyticsTool>>,
|
|
||||||
pub(super) skill_usage_overviews: Option<Vec<AnalyticsTool>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct PremiumUsage {
|
|
||||||
pub(super) credit_usage_credits: std::collections::BTreeMap<String, f64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct UsageAttribution {
|
|
||||||
pub(super) thread_source: Option<String>,
|
|
||||||
pub(super) turn_trigger: Option<String>,
|
|
||||||
pub(super) model: Option<String>,
|
|
||||||
pub(super) surface: Option<String>,
|
|
||||||
pub(super) value: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct AnalyticsCount {
|
|
||||||
pub(super) turns: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct AnalyticsModel {
|
|
||||||
pub(super) model: String,
|
|
||||||
pub(super) credits: Option<f64>,
|
|
||||||
pub(super) uncached_text_input_tokens: Option<f64>,
|
|
||||||
pub(super) cached_text_input_tokens: Option<f64>,
|
|
||||||
pub(super) text_output_tokens: Option<f64>,
|
|
||||||
pub(super) text_total_tokens: Option<f64>,
|
|
||||||
pub(super) turns: Option<f64>,
|
|
||||||
pub(super) on_demand_credits: Option<f64>,
|
|
||||||
pub(super) speed: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enterprise model groups carry text token counts independently of billing amounts.
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct AnalyticsTokenGroup {
|
|
||||||
pub(super) dimensions: std::collections::BTreeMap<String, String>,
|
|
||||||
#[cfg_attr(test, serde(default))]
|
|
||||||
pub(super) is_other: bool,
|
|
||||||
pub(super) uncached_text_input_tokens: Option<f64>,
|
|
||||||
pub(super) cached_text_input_tokens: Option<f64>,
|
|
||||||
pub(super) text_output_tokens: Option<f64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct AnalyticsClient {
|
|
||||||
pub(super) client_id: String,
|
|
||||||
pub(super) turns: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
|
||||||
#[cfg_attr(test, derive(serde::Deserialize))]
|
|
||||||
pub(super) struct AnalyticsTool {
|
|
||||||
pub(super) display_name: String,
|
|
||||||
pub(super) invocation_counts: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<AnalyticsResponse> for AnalyticsData {
|
|
||||||
fn from(response: AnalyticsResponse) -> Self {
|
|
||||||
match response {
|
|
||||||
AnalyticsResponse::Usage(response) => Self {
|
|
||||||
units: response.units,
|
|
||||||
data_freshness_ts: response.data_freshness_ts,
|
|
||||||
data: response
|
|
||||||
.data
|
|
||||||
.into_iter()
|
|
||||||
.map(|record| AnalyticsRecord {
|
|
||||||
date: record.date,
|
|
||||||
product_surface_usage_values: Some(record.product_surface_usage_values),
|
|
||||||
premium_usage_values: record.premium_usage_values.map(|value| {
|
|
||||||
PremiumUsage {
|
|
||||||
credit_usage_credits: value.credit_usage_credits,
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
attribution: record.attribution.map(|values| {
|
|
||||||
values
|
|
||||||
.into_iter()
|
|
||||||
.map(|value| UsageAttribution {
|
|
||||||
thread_source: Some(value.thread_source),
|
|
||||||
turn_trigger: Some(value.turn_trigger),
|
|
||||||
model: Some(value.model),
|
|
||||||
surface: Some(value.surface),
|
|
||||||
value: value.value,
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}),
|
|
||||||
models: record
|
|
||||||
.models
|
|
||||||
.map(|values| values.into_iter().map(AnalyticsModel::from).collect()),
|
|
||||||
groups: record.groups.map(|values| {
|
|
||||||
values
|
|
||||||
.into_iter()
|
|
||||||
.map(|value| AnalyticsTokenGroup {
|
|
||||||
dimensions: value.dimensions,
|
|
||||||
is_other: value.is_other.unwrap_or(/*default*/ false),
|
|
||||||
uncached_text_input_tokens: value
|
|
||||||
.uncached_text_input_tokens
|
|
||||||
.map(|count| count as f64),
|
|
||||||
cached_text_input_tokens: value
|
|
||||||
.cached_text_input_tokens
|
|
||||||
.map(|count| count as f64),
|
|
||||||
text_output_tokens: value
|
|
||||||
.text_output_tokens
|
|
||||||
.map(|count| count as f64),
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
AnalyticsResponse::Credits(response) => Self {
|
|
||||||
data: response
|
|
||||||
.data
|
|
||||||
.into_iter()
|
|
||||||
.map(|record| AnalyticsRecord {
|
|
||||||
date: record.date,
|
|
||||||
credit_amount: Some(record.credit_amount),
|
|
||||||
product_surface: Some(record.product_surface),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
AnalyticsResponse::EnterpriseCredits(response) => Self {
|
|
||||||
data_freshness_ts: response.data_freshness_ts,
|
|
||||||
series: Some(
|
|
||||||
response
|
|
||||||
.series
|
|
||||||
.into_iter()
|
|
||||||
.map(|value| AnalyticsSeries {
|
|
||||||
key: value.key,
|
|
||||||
label: value.label,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
),
|
|
||||||
data: response
|
|
||||||
.data
|
|
||||||
.into_iter()
|
|
||||||
.map(|record| AnalyticsRecord {
|
|
||||||
date: record.date,
|
|
||||||
values: Some(record.values),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
AnalyticsResponse::Messages(response) => Self {
|
|
||||||
data: response
|
|
||||||
.data
|
|
||||||
.into_iter()
|
|
||||||
.map(|record| AnalyticsRecord {
|
|
||||||
date: record.date,
|
|
||||||
totals: Some(AnalyticsCount {
|
|
||||||
turns: record.totals.turns as f64,
|
|
||||||
}),
|
|
||||||
clients: Some(
|
|
||||||
record
|
|
||||||
.clients
|
|
||||||
.into_iter()
|
|
||||||
.map(|value| AnalyticsClient {
|
|
||||||
client_id: value.client_id,
|
|
||||||
turns: value.turns as f64,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
),
|
|
||||||
models: record
|
|
||||||
.models
|
|
||||||
.map(|values| values.into_iter().map(AnalyticsModel::from).collect()),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
AnalyticsResponse::Plugins(response) => Self {
|
|
||||||
data_freshness_ts: response.data_freshness_ts,
|
|
||||||
data: response
|
|
||||||
.data
|
|
||||||
.into_iter()
|
|
||||||
.map(|record| AnalyticsRecord {
|
|
||||||
date: record.date,
|
|
||||||
plugin_usage_overviews: Some(
|
|
||||||
record
|
|
||||||
.plugin_usage_overviews
|
|
||||||
.into_iter()
|
|
||||||
.map(|value| AnalyticsTool {
|
|
||||||
display_name: value.display_name,
|
|
||||||
invocation_counts: value.invocation_counts as f64,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
AnalyticsResponse::Skills(response) => Self {
|
|
||||||
data_freshness_ts: response.data_freshness_ts,
|
|
||||||
data: response
|
|
||||||
.data
|
|
||||||
.into_iter()
|
|
||||||
.map(|record| AnalyticsRecord {
|
|
||||||
date: record.date,
|
|
||||||
skill_usage_overviews: Some(
|
|
||||||
record
|
|
||||||
.skill_usage_overviews
|
|
||||||
.into_iter()
|
|
||||||
.map(|value| AnalyticsTool {
|
|
||||||
display_name: value.display_name,
|
|
||||||
invocation_counts: value.invocation_counts as f64,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<backend::ModelUsage> for AnalyticsModel {
|
|
||||||
fn from(value: backend::ModelUsage) -> Self {
|
|
||||||
Self {
|
|
||||||
model: value.model,
|
|
||||||
credits: Some(value.credits),
|
|
||||||
uncached_text_input_tokens: value.uncached_text_input_tokens.map(|count| count as f64),
|
|
||||||
cached_text_input_tokens: value.cached_text_input_tokens.map(|count| count as f64),
|
|
||||||
text_output_tokens: value.text_output_tokens.map(|count| count as f64),
|
|
||||||
text_total_tokens: value.text_total_tokens.map(|count| count as f64),
|
|
||||||
turns: value.turns.map(|count| count as f64),
|
|
||||||
on_demand_credits: value.on_demand_credits,
|
|
||||||
speed: value.speed,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "report_data_tests.rs"]
|
|
||||||
mod tests;
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn typed_usage_preserves_missing_counts_and_supplied_zero() {
|
|
||||||
let input = backend::DailyProductSurfaceUsageResponse {
|
|
||||||
data: vec![backend::DailyProductSurfaceUsage {
|
|
||||||
date: "2026-01-09".into(),
|
|
||||||
models: Some(vec![backend::ModelUsage {
|
|
||||||
model: "example".into(),
|
|
||||||
credits: 1.5,
|
|
||||||
cached_text_input_tokens: Some(0),
|
|
||||||
text_output_tokens: Some(42),
|
|
||||||
..Default::default()
|
|
||||||
}]),
|
|
||||||
..Default::default()
|
|
||||||
}],
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let actual = AnalyticsData::from(AnalyticsResponse::Usage(input));
|
|
||||||
let model = &actual.data[0].models.as_ref().unwrap()[0];
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
model.credits,
|
|
||||||
model.uncached_text_input_tokens,
|
|
||||||
model.cached_text_input_tokens,
|
|
||||||
model.text_output_tokens
|
|
||||||
),
|
|
||||||
(Some(1.5), None, Some(0.0), Some(42.0))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn typed_message_records_keep_independent_daily_remainders() {
|
|
||||||
use super::super::models::*;
|
|
||||||
let date = "2026-01-09".parse().unwrap();
|
|
||||||
let row = backend::DailyWorkspaceUsageCount {
|
|
||||||
date: "2026-01-09".into(),
|
|
||||||
totals: backend::WorkspaceUsageCount {
|
|
||||||
turns: 10,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
clients: vec![backend::ClientWorkspaceUsageCount {
|
|
||||||
client_id: "CODEX_CLI".into(),
|
|
||||||
turns: 8,
|
|
||||||
..Default::default()
|
|
||||||
}],
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let response = AnalyticsResponse::Messages(backend::DailyWorkspaceUsageCountResponse {
|
|
||||||
data: vec![row.clone(), row],
|
|
||||||
..Default::default()
|
|
||||||
});
|
|
||||||
assert_eq!(
|
|
||||||
super::super::normalize::history(
|
|
||||||
response.into(),
|
|
||||||
AccountAnalyticsReport::Messages,
|
|
||||||
AccountAnalyticsGrouping::Surface,
|
|
||||||
date,
|
|
||||||
date
|
|
||||||
)
|
|
||||||
.unwrap(),
|
|
||||||
Some(AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::Count,
|
|
||||||
updated_at: None,
|
|
||||||
data: vec![AccountAnalyticsDay {
|
|
||||||
date,
|
|
||||||
total: 20.0,
|
|
||||||
values: vec![
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "cli".into(),
|
|
||||||
label: "CLI".into(),
|
|
||||||
value: 16.0
|
|
||||||
},
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "other".into(),
|
|
||||||
label: "Other".into(),
|
|
||||||
value: 4.0
|
|
||||||
},
|
|
||||||
]
|
|
||||||
}],
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,241 +0,0 @@
|
|||||||
//! Exercise Analytics construction and reauthentication through production HTTPS routes.
|
|
||||||
|
|
||||||
#![cfg(test)]
|
|
||||||
|
|
||||||
use super::Live;
|
|
||||||
use super::tests::sign_in;
|
|
||||||
use crate::legacy_core::config::ConfigBuilder;
|
|
||||||
use anyhow::Context;
|
|
||||||
use anyhow::Result;
|
|
||||||
use base64::Engine;
|
|
||||||
use codex_backend_client::AnalyticsReport;
|
|
||||||
use codex_backend_client::AnalyticsResponse;
|
|
||||||
use codex_config::LoaderOverrides;
|
|
||||||
use codex_features::Feature;
|
|
||||||
use codex_features::RuntimeAuthMode;
|
|
||||||
use codex_protocol::account::PlanType;
|
|
||||||
use core_test_support::runtime_auth::PROBE_SERVER;
|
|
||||||
use core_test_support::runtime_auth::run_harness_through_proxy;
|
|
||||||
use core_test_support::skip_if_no_network;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::Value;
|
|
||||||
use serde_json::json;
|
|
||||||
use std::collections::BTreeSet;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::MockServer;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
|
|
||||||
async fn runtime_client(
|
|
||||||
base_url: &str,
|
|
||||||
mode: RuntimeAuthMode,
|
|
||||||
) -> Result<(tempfile::TempDir, Live)> {
|
|
||||||
let home = tempfile::tempdir()?;
|
|
||||||
let mut config = ConfigBuilder::default()
|
|
||||||
.codex_home(home.path().to_path_buf())
|
|
||||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
|
||||||
.build()
|
|
||||||
.await?;
|
|
||||||
config.chatgpt_base_url = base_url.to_string();
|
|
||||||
config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File;
|
|
||||||
config.features.enable(Feature::RuntimeAgentInstances)?;
|
|
||||||
config.runtime_auth_mode = mode;
|
|
||||||
sign_in(home.path(), "account-a", "user-a", "plus");
|
|
||||||
Ok((home, Live::new(Arc::new(config), "2026-01-15".parse()?)))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
||||||
#[ignore = "aKode: runtime registration with auth.openai.com is disabled"]
|
|
||||||
async fn analytics_runtime_covers_regional_account_and_report_requests() -> Result<()> {
|
|
||||||
skip_if_no_network!(Ok(()));
|
|
||||||
let bases = [
|
|
||||||
"https://chatgpt.com/backend-api",
|
|
||||||
"https://us.chatgpt.com/backend-api",
|
|
||||||
"https://chatgpt-staging.com/backend-api",
|
|
||||||
"https://us.chatgpt-staging.com/backend-api",
|
|
||||||
];
|
|
||||||
let modes = [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly];
|
|
||||||
if std::env::var(PROBE_SERVER).is_ok() {
|
|
||||||
for base in bases {
|
|
||||||
for mode in modes {
|
|
||||||
let (_home, live) = runtime_client(base, mode).await?;
|
|
||||||
let session = live
|
|
||||||
.session()
|
|
||||||
.await
|
|
||||||
.map_err(anyhow::Error::msg)
|
|
||||||
.with_context(|| format!("{base} {mode:?}"))?;
|
|
||||||
assert_eq!(session.backend.account().plan_type, Some(PlanType::Pro));
|
|
||||||
let response = session
|
|
||||||
.backend
|
|
||||||
.request(|client| async move {
|
|
||||||
client
|
|
||||||
.get_account_analytics(
|
|
||||||
AnalyticsReport::Usage,
|
|
||||||
"2026-01-01",
|
|
||||||
"2026-01-15",
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
assert_eq!(
|
|
||||||
response,
|
|
||||||
AnalyticsResponse::Usage(
|
|
||||||
codex_backend_client::analytics_models::DailyProductSurfaceUsageResponse::default(),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/agent/register"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
|
||||||
"runtime_agent_instance_id": "runtime-analytics", "agent_host_id": "host-a",
|
|
||||||
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "account-a"},
|
|
||||||
})))
|
|
||||||
.expect(/*r*/ 8)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/backend-api/wham/accounts/check"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
|
||||||
"accounts": [{"id": "account-a", "plan_type": "pro"}],
|
|
||||||
"account_ordering": ["account-a"],
|
|
||||||
})))
|
|
||||||
.expect(/*r*/ 8)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/backend-api/wham/usage/daily-token-usage-breakdown"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({"data": []})))
|
|
||||||
.expect(/*r*/ 8)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
run_harness_through_proxy(
|
|
||||||
&server,
|
|
||||||
"analytics::client::runtime_auth_tests::analytics_runtime_covers_regional_account_and_report_requests",
|
|
||||||
/*realtime_target*/ None,
|
|
||||||
).await?;
|
|
||||||
server.verify().await;
|
|
||||||
let requests = server
|
|
||||||
.received_requests()
|
|
||||||
.await
|
|
||||||
.context("captured requests")?;
|
|
||||||
assert_eq!(requests.len(), 24);
|
|
||||||
let mut proofs = BTreeSet::new();
|
|
||||||
for (index, requests) in requests.as_chunks::<3>().0.iter().enumerate() {
|
|
||||||
let base = bases[index / modes.len()];
|
|
||||||
let mode = modes[index % modes.len()];
|
|
||||||
let registration = &requests[0];
|
|
||||||
assert_eq!(registration.url.path(), "/agent/register");
|
|
||||||
assert_eq!(
|
|
||||||
registration.headers["host"],
|
|
||||||
if base.contains("staging") {
|
|
||||||
"auth.api.openai.org"
|
|
||||||
} else {
|
|
||||||
"auth.openai.com"
|
|
||||||
},
|
|
||||||
);
|
|
||||||
let body: Value = registration.body_json()?;
|
|
||||||
let credential = body["actor_auth"]["credential"]
|
|
||||||
.as_str()
|
|
||||||
.context("actor credential")?;
|
|
||||||
for request in &requests[1..] {
|
|
||||||
assert_eq!(
|
|
||||||
request.headers["host"],
|
|
||||||
base.strip_prefix("https://")
|
|
||||||
.expect("HTTPS test URL")
|
|
||||||
.strip_suffix("/backend-api")
|
|
||||||
.expect("test API path"),
|
|
||||||
);
|
|
||||||
assert_eq!(request.headers["chatgpt-account-id"], "account-a");
|
|
||||||
let authorization = request.headers["authorization"].to_str()?;
|
|
||||||
let proof = match mode {
|
|
||||||
RuntimeAuthMode::DualHeader => {
|
|
||||||
assert_eq!(authorization, format!("Bearer {credential}"));
|
|
||||||
request.headers["x-openai-agent-assertion"].to_str()?
|
|
||||||
}
|
|
||||||
RuntimeAuthMode::AssertionOnly => {
|
|
||||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
|
||||||
authorization
|
|
||||||
.strip_prefix("AgentAssertion ")
|
|
||||||
.context("runtime authorization")?
|
|
||||||
}
|
|
||||||
};
|
|
||||||
assert!(
|
|
||||||
proofs.insert(proof.to_owned()),
|
|
||||||
"every request needs a fresh assertion"
|
|
||||||
);
|
|
||||||
let payload = proof
|
|
||||||
.strip_prefix("1.")
|
|
||||||
.context("runtime assertion version")?
|
|
||||||
.split('.')
|
|
||||||
.nth(/*n*/ 1)
|
|
||||||
.context("assertion payload")?;
|
|
||||||
let claims: Value = serde_json::from_slice(
|
|
||||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload)?,
|
|
||||||
)?;
|
|
||||||
assert_eq!(claims["runtime_agent_instance"], "runtime-analytics");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
||||||
#[ignore = "aKode: runtime registration with auth.openai.com is disabled"]
|
|
||||||
async fn analytics_runtime_bootstrap_preserves_sign_in_guidance() -> Result<()> {
|
|
||||||
skip_if_no_network!(Ok(()));
|
|
||||||
if std::env::var(PROBE_SERVER).is_ok() {
|
|
||||||
let (_home, live) = runtime_client(
|
|
||||||
"https://chatgpt.com/backend-api",
|
|
||||||
RuntimeAuthMode::DualHeader,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
assert_eq!(
|
|
||||||
live.session().await.err().as_deref(),
|
|
||||||
Some("Sign in again to load Analytics."),
|
|
||||||
);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/agent/register"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 401).set_body_json(json!({
|
|
||||||
"error": {"code": "token_expired"},
|
|
||||||
})))
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/oauth/token"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 401).set_body_json(json!({
|
|
||||||
"error": {"code": "refresh_token_expired"},
|
|
||||||
})))
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
run_harness_through_proxy(
|
|
||||||
&server,
|
|
||||||
"analytics::client::runtime_auth_tests::analytics_runtime_bootstrap_preserves_sign_in_guidance",
|
|
||||||
/*realtime_target*/ None,
|
|
||||||
).await?;
|
|
||||||
server.verify().await;
|
|
||||||
let requests = server
|
|
||||||
.received_requests()
|
|
||||||
.await
|
|
||||||
.context("captured requests")?;
|
|
||||||
assert!(
|
|
||||||
requests
|
|
||||||
.iter()
|
|
||||||
.any(|request| request.url.path() == "/agent/register")
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
requests
|
|
||||||
.iter()
|
|
||||||
.all(|request| { matches!(request.url.path(), "/agent/register" | "/oauth/token") })
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -1,305 +0,0 @@
|
|||||||
//! Account-specific section order, request eligibility, and independent report ranges.
|
|
||||||
//! Resolving the account precedes report loading; reopening drops all account-owned data.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::chats;
|
|
||||||
use super::data::Load;
|
|
||||||
use super::models::AccountKind;
|
|
||||||
|
|
||||||
/// Stable identities preserve selections while account layouts change their order.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(super) enum Section {
|
|
||||||
Usage,
|
|
||||||
Plugins,
|
|
||||||
Credits,
|
|
||||||
Chats,
|
|
||||||
Activity,
|
|
||||||
Skills,
|
|
||||||
Plan,
|
|
||||||
Summary,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Section {
|
|
||||||
pub(super) fn report(self) -> Option<super::models::AccountAnalyticsReport> {
|
|
||||||
use super::models::AccountAnalyticsReport as Report;
|
|
||||||
match self {
|
|
||||||
Self::Usage => Some(Report::Usage),
|
|
||||||
Self::Plugins => Some(Report::Plugins),
|
|
||||||
Self::Credits => Some(Report::Credits),
|
|
||||||
Self::Chats | Self::Plan | Self::Summary => None,
|
|
||||||
Self::Activity => Some(Report::Messages),
|
|
||||||
Self::Skills => Some(Report::Skills),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Section-only indexing keeps report identity separate from array positions.
|
|
||||||
pub(super) struct SectionStates(pub(super) [SectionState; 8]);
|
|
||||||
|
|
||||||
impl std::ops::Index<Section> for SectionStates {
|
|
||||||
type Output = SectionState;
|
|
||||||
fn index(&self, section: Section) -> &Self::Output {
|
|
||||||
&self.0[section as usize]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::ops::IndexMut<Section> for SectionStates {
|
|
||||||
fn index_mut(&mut self, section: Section) -> &mut Self::Output {
|
|
||||||
&mut self.0[section as usize]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A report and its selection are replaced independently of the other sections.
|
|
||||||
pub(super) struct SectionState {
|
|
||||||
pub(super) history: Load<super::models::AccountAnalyticsHistory>,
|
|
||||||
pub(super) cursor: usize,
|
|
||||||
pub(super) detail: Option<usize>,
|
|
||||||
pub(super) group: usize,
|
|
||||||
pub(super) scroll_offset: usize,
|
|
||||||
pub(super) follow_selection_on_focus: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for SectionState {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
history: Load::Unavailable,
|
|
||||||
cursor: 6,
|
|
||||||
detail: None,
|
|
||||||
group: 0,
|
|
||||||
scroll_offset: 0,
|
|
||||||
follow_selection_on_focus: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Usage, product activity, and tools each share one range across their related sections.
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(super) enum RangeGroup {
|
|
||||||
Usage,
|
|
||||||
Activity,
|
|
||||||
Tools,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn poll_reports(&mut self) {
|
|
||||||
if self.live.as_ref().is_some_and(|live| {
|
|
||||||
live.identity_invalidated
|
|
||||||
.load(std::sync::atomic::Ordering::Relaxed)
|
|
||||||
}) {
|
|
||||||
self.refresh();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for section in &mut self.sections.0 {
|
|
||||||
section.history.poll();
|
|
||||||
}
|
|
||||||
self.chats.poll();
|
|
||||||
self.tasks.poll();
|
|
||||||
self.profile.poll();
|
|
||||||
self.plan.poll();
|
|
||||||
self.account.poll();
|
|
||||||
self.start_reports();
|
|
||||||
if !self.business()
|
|
||||||
&& !self.consumer_attribution()
|
|
||||||
&& ![0, 2].contains(&self.sections[Section::Usage].group)
|
|
||||||
{
|
|
||||||
self.sections[Section::Usage].group = 0;
|
|
||||||
}
|
|
||||||
if let Some(chats) = self.tasks.ready() {
|
|
||||||
self.sections[Section::Chats].cursor = self.sections[Section::Chats]
|
|
||||||
.cursor
|
|
||||||
.min(chats.rows.len().saturating_sub(/*rhs*/ 1));
|
|
||||||
}
|
|
||||||
if let Some(chats) = self.chats.ready() {
|
|
||||||
self.sections[Section::Chats].cursor = self.sections[Section::Chats]
|
|
||||||
.cursor
|
|
||||||
.min(chats.rows.len().saturating_sub(/*rhs*/ 1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn range_group(&self, section: Section) -> RangeGroup {
|
|
||||||
match section {
|
|
||||||
Section::Usage if self.business() => RangeGroup::Activity,
|
|
||||||
Section::Usage
|
|
||||||
| Section::Credits
|
|
||||||
| Section::Chats
|
|
||||||
| Section::Plan
|
|
||||||
| Section::Summary => RangeGroup::Usage,
|
|
||||||
Section::Activity => RangeGroup::Activity,
|
|
||||||
Section::Plugins | Section::Skills => RangeGroup::Tools,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn group_label(&self, section: Section, group: usize) -> &'static str {
|
|
||||||
if section == Section::Summary {
|
|
||||||
return super::summary::VIEWS[group].label();
|
|
||||||
}
|
|
||||||
if group == 0
|
|
||||||
&& (section == Section::Credits
|
|
||||||
|| (section == Section::Usage && !self.consumer_attribution()))
|
|
||||||
{
|
|
||||||
"Product"
|
|
||||||
} else {
|
|
||||||
super::data::GROUP_LABELS[group]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn account_kind(&self) -> Option<AccountKind> {
|
|
||||||
self.account
|
|
||||||
.ready()
|
|
||||||
.copied()
|
|
||||||
.map(|plan| AccountKind::from(Some(plan)))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn business(&self) -> bool {
|
|
||||||
matches!(
|
|
||||||
self.account_kind(),
|
|
||||||
Some(AccountKind::Business | AccountKind::Enterprise)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn visible_sections(&self) -> &'static [Section] {
|
|
||||||
match self.account_kind() {
|
|
||||||
Some(AccountKind::Consumer) if self.plan.enabled => &[
|
|
||||||
Section::Summary,
|
|
||||||
Section::Usage,
|
|
||||||
Section::Plan,
|
|
||||||
Section::Activity,
|
|
||||||
Section::Plugins,
|
|
||||||
Section::Skills,
|
|
||||||
Section::Chats,
|
|
||||||
],
|
|
||||||
Some(AccountKind::Consumer) => &[
|
|
||||||
Section::Summary,
|
|
||||||
Section::Usage,
|
|
||||||
Section::Activity,
|
|
||||||
Section::Plugins,
|
|
||||||
Section::Skills,
|
|
||||||
Section::Chats,
|
|
||||||
],
|
|
||||||
Some(AccountKind::Business | AccountKind::Enterprise)
|
|
||||||
if super::models::thread_usage_supported(self.account.ready().copied()) =>
|
|
||||||
{
|
|
||||||
&[
|
|
||||||
Section::Summary,
|
|
||||||
Section::Credits,
|
|
||||||
Section::Usage,
|
|
||||||
Section::Plugins,
|
|
||||||
Section::Skills,
|
|
||||||
Section::Chats,
|
|
||||||
]
|
|
||||||
}
|
|
||||||
Some(AccountKind::Business | AccountKind::Enterprise) => &[
|
|
||||||
Section::Summary,
|
|
||||||
Section::Credits,
|
|
||||||
Section::Usage,
|
|
||||||
Section::Plugins,
|
|
||||||
Section::Skills,
|
|
||||||
],
|
|
||||||
Some(AccountKind::Unknown) => &[Section::Summary],
|
|
||||||
None => &[],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn start_reports(&mut self) {
|
|
||||||
if self.reports_started || self.account.ready().is_none() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.reports_started = true;
|
|
||||||
let visible = self.visible_sections();
|
|
||||||
let Some(first) = visible.first() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
if !visible.contains(&self.section) {
|
|
||||||
self.section = *first;
|
|
||||||
}
|
|
||||||
let usage_groups: &[usize] = if self.business() {
|
|
||||||
&[6, 2]
|
|
||||||
} else {
|
|
||||||
&[1, 2, 0, 3]
|
|
||||||
};
|
|
||||||
if !usage_groups.contains(&self.sections[Section::Usage].group) {
|
|
||||||
self.sections[Section::Usage].group =
|
|
||||||
if matches!(self.account_kind(), Some(AccountKind::Business)) {
|
|
||||||
2
|
|
||||||
} else {
|
|
||||||
usage_groups[0]
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if visible.contains(&Section::Credits)
|
|
||||||
&& let Some(live) = &self.live
|
|
||||||
&& !live
|
|
||||||
.credit_groups()
|
|
||||||
.contains(&self.sections[Section::Credits].group)
|
|
||||||
{
|
|
||||||
self.sections[Section::Credits].group = live.credit_groups()[0];
|
|
||||||
}
|
|
||||||
self.load_summary();
|
|
||||||
for section in visible {
|
|
||||||
if section.report().is_some() {
|
|
||||||
self.load_report(*section);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if visible.contains(&Section::Plan)
|
|
||||||
&& let (Some((_, _, frame)), Some(live)) = (&self.connection, &self.live)
|
|
||||||
{
|
|
||||||
let live = std::sync::Arc::clone(live);
|
|
||||||
self.plan.report = Load::start(async move { live.plan_history().await }, frame.clone());
|
|
||||||
}
|
|
||||||
if visible.contains(&Section::Chats) && !self.business() {
|
|
||||||
if let (Some((_, handle, frame)), Some(live)) = (&self.connection, &self.live) {
|
|
||||||
self.tasks = Load::start_with_timeout(
|
|
||||||
super::tasks::read(handle.clone(), std::sync::Arc::clone(live)),
|
|
||||||
frame.clone(),
|
|
||||||
std::time::Duration::from_secs(/*secs*/ 120),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else if visible.contains(&Section::Chats) {
|
|
||||||
self.chats =
|
|
||||||
if let (Some((_, handle, frame)), Some(live)) = (&self.connection, &self.live) {
|
|
||||||
Load::start_with_timeout(
|
|
||||||
chats::read(handle.clone(), std::sync::Arc::clone(live)),
|
|
||||||
frame.clone(),
|
|
||||||
std::time::Duration::from_secs(/*secs*/ 90),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Load::Unavailable
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn section_date_range(
|
|
||||||
&self,
|
|
||||||
section: Section,
|
|
||||||
) -> std::ops::RangeInclusive<chrono::NaiveDate> {
|
|
||||||
let end = self.end_date;
|
|
||||||
let range = self.ranges[self.range_group(section) as usize];
|
|
||||||
(end - chrono::Days::new(if range == 0 { 6 } else { 29 }))..=end
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn change_range(&mut self) {
|
|
||||||
let index = self.range_group(self.section);
|
|
||||||
self.ranges[index as usize] ^= 1;
|
|
||||||
for section in self.visible_sections() {
|
|
||||||
if matches!(section, Section::Chats | Section::Plan | Section::Summary)
|
|
||||||
|| self.range_group(*section) != index
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
self.sections[*section].cursor = if self.ranges[index as usize] == 1 {
|
|
||||||
self.sections[*section].cursor + 23
|
|
||||||
} else {
|
|
||||||
self.sections[*section].cursor.saturating_sub(/*rhs*/ 23)
|
|
||||||
};
|
|
||||||
self.sections[*section].detail = self.sections[*section].detail.and_then(|day| {
|
|
||||||
if self.ranges[index as usize] == 1 {
|
|
||||||
Some(day + 23)
|
|
||||||
} else {
|
|
||||||
day.checked_sub(/*rhs*/ 23)
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if section.report().is_some() {
|
|
||||||
self.load_report(*section);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/client_tests.rs
|
|
||||||
expression: terminal.backend().to_string()
|
|
||||||
---
|
|
||||||
" Usage · analytics@example.test "
|
|
||||||
" "
|
|
||||||
" ────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" No history has been reported. "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" esc back "
|
|
||||||
" R retry "
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plan_tests.rs
|
|
||||||
expression: "output.join(\"\\n\")"
|
|
||||||
---
|
|
||||||
" Usage · Plus "
|
|
||||||
" 1 Overview 2 Usage 3 Plan 4 Messages 5 Plugins 6 Skills 7 Chats "
|
|
||||||
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" g Feature · ←/→ 5-hour / Weekly "
|
|
||||||
" "
|
|
||||||
" 5-hour limits › Weekly limits "
|
|
||||||
" "
|
|
||||||
" › Sep 2 10:00 – Sep 2 15:00 * 125% › Sep 1 00:00 – Sep 8 00:00 * Not available "
|
|
||||||
" Some usage is unavailable; this period may be Breakdown isn't available for this period "
|
|
||||||
" incomplete "
|
|
||||||
" Tasks 125% "
|
|
||||||
" Some periods aren't available yet "
|
|
||||||
" Usage as of Sep 2 12:00 UTC · * current at last update "
|
|
||||||
" Available since Sep 1 00:00 UTC "
|
|
||||||
" Amounts and period boundaries are approximate; recent activity may be delayed "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" ↑/↓ period · enter details · esc back "
|
|
||||||
" tab/1–7 report · z dashboard · ? help · R refresh "
|
|
||||||
|
|
||||||
" Usage · Plus "
|
|
||||||
" Overview Usage Plan Messages Plugins › "
|
|
||||||
" ──────────────────────────────────────────────────────── "
|
|
||||||
" g Feature "
|
|
||||||
" ←/→ 5-hour / Weekly "
|
|
||||||
" "
|
|
||||||
" 5-hour limits "
|
|
||||||
" "
|
|
||||||
" › Sep 2 10:00 – Sep 2 15:00 * 125% "
|
|
||||||
" Some usage is unavailable; this period may be "
|
|
||||||
" incomplete "
|
|
||||||
" Tasks 125% "
|
|
||||||
" "
|
|
||||||
" › Weekly limits "
|
|
||||||
" "
|
|
||||||
" › Sep 1 00:00 – Sep 8 00:00 * Not available "
|
|
||||||
" Breakdown isn't available for this period "
|
|
||||||
" Some periods aren't available yet "
|
|
||||||
" Usage as of Sep 2 12:00 UTC · * current at last update "
|
|
||||||
" Available since Sep 1 00:00 UTC "
|
|
||||||
" Amounts and period boundaries are approximate; recent "
|
|
||||||
" activity may be delayed "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" ↑/↓ period · enter details · esc back "
|
|
||||||
" tab report · z dashboard · ? help · R refresh "
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plan_tests.rs
|
|
||||||
expression: rendered
|
|
||||||
---
|
|
||||||
› 5-hour limits
|
|
||||||
|
|
||||||
› Sep 2 10:00 AM – Sep 2 3:00 PM * 125%
|
|
||||||
|
|
||||||
Weekly limits
|
|
||||||
|
|
||||||
› Sep 1 12:00 AM – Sep 8 12:00 AM * Not available
|
|
||||||
Some periods aren't available yet
|
|
||||||
Usage as of Sep 2 12:00 PM UTC · * current at last update
|
|
||||||
Available since Sep 1 12:00 AM UTC
|
|
||||||
Amounts and period boundaries are approximate; recent activity may be delayed
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plan_tests.rs
|
|
||||||
assertion_line: 105
|
|
||||||
expression: snapshot
|
|
||||||
---
|
|
||||||
› 5-hour limits Weekly limits
|
|
||||||
|
|
||||||
Limit history isn't available yet Limit history isn't available yet
|
|
||||||
|
|
||||||
› 5-hour limits Weekly limits
|
|
||||||
|
|
||||||
No limit periods in this date range No limit periods in this date range
|
|
||||||
Usage as of Sep 2 12:00 UTC · * current at last update
|
|
||||||
Available since Sep 1 00:00 UTC
|
|
||||||
Amounts and period boundaries are approximate; recent activity may be delayed
|
|
||||||
|
|
||||||
› 5-hour limits Weekly limits
|
|
||||||
|
|
||||||
› Sep 2 10:00 – Sep 2 15:00 * 0% › Sep 1 00:00 – Sep 8 00:00 * Not available
|
|
||||||
Some periods aren't available yet
|
|
||||||
Usage as of Sep 2 12:00 UTC · * current at last update
|
|
||||||
Available since Sep 1 00:00 UTC
|
|
||||||
Amounts and period boundaries are approximate; recent activity may be delayed
|
|
||||||
|
|
||||||
› 5-hour limits Weekly limits
|
|
||||||
|
|
||||||
› Sep 2 13:00 – Sep 2 15:00 125% › Sep 1 00:00 – Sep 8 00:00 * Not available
|
|
||||||
Some periods aren't available yet
|
|
||||||
Usage as of Sep 2 12:00 UTC · * current at last update
|
|
||||||
Available since Sep 1 00:00 UTC
|
|
||||||
Amounts and period boundaries are approximate; recent activity may be delayed
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: display(&rendered)
|
|
||||||
---
|
|
||||||
20
|
|
||||||
20 ████████████
|
|
||||||
████████████
|
|
||||||
████████████
|
|
||||||
████████████
|
|
||||||
████████████
|
|
||||||
10 ████████████
|
|
||||||
████████████
|
|
||||||
████████████
|
|
||||||
████████████
|
|
||||||
████████████
|
|
||||||
0 ────────────────────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
6: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 22:1 24:0
|
|
||||||
1: 0:0 1:2 3:0 18:3 30:0
|
|
||||||
2: 0:0 18:3 30:0
|
|
||||||
3: 0:0 18:4 30:0
|
|
||||||
4: 0:0 18:4 30:0
|
|
||||||
5: 0:0 18:4 30:0
|
|
||||||
6: 0:0 1:2 3:0 18:4 30:0
|
|
||||||
7: 0:0 18:4 30:0
|
|
||||||
8: 0:0 18:4 30:0
|
|
||||||
9: 0:0 18:4 30:0
|
|
||||||
10: 0:0 18:4 30:0
|
|
||||||
11: 0:0 2:2 3:0 4:2
|
|
||||||
12: 0:0 23:5 24:0
|
|
||||||
13: 0:0 20:6 26:0
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: "snapshots.join(\"\\n\\n\")"
|
|
||||||
---
|
|
||||||
width=36, cursor=0
|
|
||||||
5
|
|
||||||
6 ▄▄▄▄▄▄▄
|
|
||||||
███████
|
|
||||||
— 0 ███████
|
|
||||||
0 ─────────────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 13 Jan 14 Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
2: Style::new().fg(Color::Rgb(165, 165, 165)).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
6: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 30:1 31:0
|
|
||||||
1: 0:0 1:2 2:0 27:3 34:0
|
|
||||||
2: 0:0 27:3 34:0
|
|
||||||
3: 0:0 8:4 9:0 19:1 20:0 27:3 34:0
|
|
||||||
4: 0:0 1:2 2:0 3:1
|
|
||||||
5: 0:0 8:5 9:0
|
|
||||||
6: 0:0 5:6 11:0 16:2 22:0 27:2 33:0
|
|
||||||
|
|
||||||
width=36, cursor=1
|
|
||||||
5
|
|
||||||
6 ▄▄▄▄▄▄▄
|
|
||||||
███████
|
|
||||||
— 0 ███████
|
|
||||||
0 ─────────────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 13 Jan 14 Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
2: Style::new().fg(Color::Rgb(165, 165, 165)).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
6: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 30:1 31:0
|
|
||||||
1: 0:0 1:2 2:0 27:3 34:0
|
|
||||||
2: 0:0 27:3 34:0
|
|
||||||
3: 0:0 8:1 9:0 19:4 20:0 27:3 34:0
|
|
||||||
4: 0:0 1:2 2:0 3:1
|
|
||||||
5: 0:0 19:5 20:0
|
|
||||||
6: 0:0 5:2 11:0 16:6 22:0 27:2 33:0
|
|
||||||
|
|
||||||
width=8, cursor=2
|
|
||||||
5
|
|
||||||
▄▄
|
|
||||||
██
|
|
||||||
— 0 ██
|
|
||||||
────────
|
|
||||||
▲
|
|
||||||
13 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
4: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Rgb(165, 165, 165)).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
6: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 6:1 7:0
|
|
||||||
1: 0:0 5:2 7:0
|
|
||||||
2: 0:0 5:2 7:0
|
|
||||||
3: 0:3 1:0 3:3 4:0 5:2 7:0
|
|
||||||
4: 0:3
|
|
||||||
5: 0:0 6:4 7:0
|
|
||||||
6: 0:5 2:0 5:6 7:0
|
|
||||||
|
|
||||||
width=1, cursor=2
|
|
||||||
5
|
|
||||||
▄
|
|
||||||
█
|
|
||||||
█
|
|
||||||
─
|
|
||||||
▲
|
|
||||||
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
1: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:1
|
|
||||||
2: 0:1
|
|
||||||
3: 0:1
|
|
||||||
4: 0:2
|
|
||||||
5: 0:3
|
|
||||||
6: 0:4
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: "screens.join(\"\\n\\n\")"
|
|
||||||
---
|
|
||||||
111 111 111
|
|
||||||
111 ┊ 111 ┊ 111 ┊
|
|
||||||
▇▇ ▇▇ ▇▇ ▇▇ ▇▇ ▇▇ ▇▇
|
|
||||||
██ ██ ██ ██ ██ ██ ██
|
|
||||||
██ ██ ██ ██ ██ ██ ██
|
|
||||||
─────────────────────
|
|
||||||
▲
|
|
||||||
1 2 3 4 5 6 7
|
|
||||||
|
|
||||||
|
|
||||||
111 111 111 111 111 111 111
|
|
||||||
▇▇ ▇▇ ▇▇ ▇▇ ▇▇ ▇▇ ▇▇
|
|
||||||
██ ██ ██ ██ ██ ██ ██
|
|
||||||
██ ██ ██ ██ ██ ██ ██
|
|
||||||
────────────────────────────
|
|
||||||
▲
|
|
||||||
1 2 3 4 5 6 7
|
|
||||||
|
|
||||||
|
|
||||||
150 111 111 111 111 111 111 111
|
|
||||||
▇▇ ▇▇ ▇▇ ▇▇▇ ▇▇ ▇▇ ▇▇▇
|
|
||||||
75 ██ ██ ██ ███ ██ ██ ███
|
|
||||||
██ ██ ██ ███ ██ ██ ███
|
|
||||||
0 ──────────────────────────────
|
|
||||||
▲
|
|
||||||
1 2 3 4 5 6 7
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: "snapshots.join(\"\\n\\n\")"
|
|
||||||
---
|
|
||||||
width=1
|
|
||||||
|
|
||||||
1
|
|
||||||
▄
|
|
||||||
█
|
|
||||||
─
|
|
||||||
▲
|
|
||||||
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:1
|
|
||||||
2: 0:2
|
|
||||||
3: 0:2
|
|
||||||
4: 0:3
|
|
||||||
5: 0:4
|
|
||||||
6: 0:0
|
|
||||||
|
|
||||||
width=2
|
|
||||||
|
|
||||||
1
|
|
||||||
▄▄
|
|
||||||
██
|
|
||||||
──
|
|
||||||
▲
|
|
||||||
15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:0 1:1
|
|
||||||
2: 0:2
|
|
||||||
3: 0:2
|
|
||||||
4: 0:3
|
|
||||||
5: 0:0 1:4
|
|
||||||
6: 0:5
|
|
||||||
|
|
||||||
width=5
|
|
||||||
|
|
||||||
1
|
|
||||||
▄▄▄▄▄
|
|
||||||
█████
|
|
||||||
─────
|
|
||||||
▲
|
|
||||||
15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:0 4:1
|
|
||||||
2: 0:2
|
|
||||||
3: 0:2
|
|
||||||
4: 0:3
|
|
||||||
5: 0:0 4:4
|
|
||||||
6: 0:0 3:5
|
|
||||||
|
|
||||||
width=6
|
|
||||||
|
|
||||||
1
|
|
||||||
▄▄▄▄▄▄
|
|
||||||
██████
|
|
||||||
──────
|
|
||||||
▲
|
|
||||||
Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:0 5:1
|
|
||||||
2: 0:2
|
|
||||||
3: 0:2
|
|
||||||
4: 0:3
|
|
||||||
5: 0:0 5:4
|
|
||||||
6: 0:5
|
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: "snapshots.join(\"\\n\\n\")"
|
|
||||||
---
|
|
||||||
width=8
|
|
||||||
100M
|
|
||||||
█████
|
|
||||||
█████
|
|
||||||
█████
|
|
||||||
█████
|
|
||||||
────────
|
|
||||||
▲
|
|
||||||
Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 1:1 5:0
|
|
||||||
1: 0:0 1:2 6:0
|
|
||||||
2: 0:0 1:2 6:0
|
|
||||||
3: 0:0 1:2 6:0
|
|
||||||
4: 0:0 1:2 6:0
|
|
||||||
5: 0:3
|
|
||||||
6: 0:0 3:4 4:0
|
|
||||||
7: 0:5 6:0
|
|
||||||
|
|
||||||
width=30
|
|
||||||
100M
|
|
||||||
100M ████████████
|
|
||||||
████████████
|
|
||||||
50M ████████████
|
|
||||||
████████████
|
|
||||||
0 ────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 15:1 19:0
|
|
||||||
1: 0:0 1:2 5:0 12:3 24:0
|
|
||||||
2: 0:0 12:3 24:0
|
|
||||||
3: 0:0 2:2 5:0 12:3 24:0
|
|
||||||
4: 0:0 12:3 24:0
|
|
||||||
5: 0:0 4:2 5:0 6:2
|
|
||||||
6: 0:0 17:4 18:0
|
|
||||||
7: 0:0 14:5 20:0
|
|
||||||
|
|
||||||
width=35
|
|
||||||
100M
|
|
||||||
100M ████████████
|
|
||||||
████████████
|
|
||||||
50M ████████████
|
|
||||||
████████████
|
|
||||||
0 ─────────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 18:1 22:0
|
|
||||||
1: 0:0 1:2 5:0 14:3 26:0
|
|
||||||
2: 0:0 14:3 26:0
|
|
||||||
3: 0:0 2:2 5:0 14:3 26:0
|
|
||||||
4: 0:0 14:3 26:0
|
|
||||||
5: 0:0 4:2 5:0 6:2
|
|
||||||
6: 0:0 20:4 21:0
|
|
||||||
7: 0:0 17:5 23:0
|
|
||||||
|
|
||||||
width=44
|
|
||||||
100M
|
|
||||||
100M ████████████
|
|
||||||
████████████
|
|
||||||
50M ████████████
|
|
||||||
████████████
|
|
||||||
0 ──────────────────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 22:1 26:0
|
|
||||||
1: 0:0 1:2 5:0 19:3 31:0
|
|
||||||
2: 0:0 19:3 31:0
|
|
||||||
3: 0:0 2:2 5:0 19:3 31:0
|
|
||||||
4: 0:0 19:3 31:0
|
|
||||||
5: 0:0 4:2 5:0 6:2
|
|
||||||
6: 0:0 24:4 25:0
|
|
||||||
7: 0:0 21:5 27:0
|
|
||||||
|
|
||||||
width=30
|
|
||||||
|
|
||||||
1000000000000000000T
|
|
||||||
▅▅▅▅▅▅▅▅▅▅▅▅
|
|
||||||
████████████
|
|
||||||
████████████
|
|
||||||
──────────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:0 4:1 24:0
|
|
||||||
2: 0:0 9:2 21:0
|
|
||||||
3: 0:0 9:2 21:0
|
|
||||||
4: 0:0 9:2 21:0
|
|
||||||
5: 0:3
|
|
||||||
6: 0:0 14:4 15:0
|
|
||||||
7: 0:0 11:5 17:0
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: "snapshots.join(\"\\n\\n\")"
|
|
||||||
---
|
|
||||||
sign=1
|
|
||||||
1.75
|
|
||||||
▇▇▇▇ —
|
|
||||||
────────────
|
|
||||||
▲
|
|
||||||
14 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
2: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 4:1
|
|
||||||
1: 0:1 1:2 5:1 8:3 9:1
|
|
||||||
2: 0:0
|
|
||||||
3: 0:1 8:4 9:1
|
|
||||||
4: 0:1 1:0 3:1 7:5 9:1
|
|
||||||
|
|
||||||
sign=-1
|
|
||||||
|
|
||||||
—
|
|
||||||
────────────
|
|
||||||
▁▁▁▁
|
|
||||||
-1.75
|
|
||||||
▲
|
|
||||||
14 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset).reversed()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:0 8:1 9:0
|
|
||||||
2: 0:2
|
|
||||||
3: 0:0 1:3 5:0
|
|
||||||
4: 0:2 5:0
|
|
||||||
5: 0:0 8:4 9:0
|
|
||||||
6: 0:0 1:2 3:0 7:5 9:0
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: display(&rendered)
|
|
||||||
---
|
|
||||||
|
|
||||||
20 20.00
|
|
||||||
▃▃▃▃▃▃▃▃▃▃▃▃
|
|
||||||
10 ████████████
|
|
||||||
████████████
|
|
||||||
0 ────────────────────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
2: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
3: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
6: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:0 1:1 3:0 21:2 26:0
|
|
||||||
2: 0:0 18:3 30:0
|
|
||||||
3: 0:0 1:1 3:0 18:4 30:0
|
|
||||||
4: 0:0 18:4 30:0
|
|
||||||
5: 0:0 2:1 3:0 4:1
|
|
||||||
6: 0:0 23:5 24:0
|
|
||||||
7: 0:0 20:6 26:0
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: text
|
|
||||||
---
|
|
||||||
711
|
|
||||||
800 611
|
|
||||||
511 █████████
|
|
||||||
411 █████████ █████████
|
|
||||||
311 ████████ █████████ █████████
|
|
||||||
400 211 █████████ ████████ █████████ █████████
|
|
||||||
111 ████████ █████████ ████████ █████████ █████████
|
|
||||||
█████████ ████████ █████████ ████████ █████████ █████████
|
|
||||||
████████ █████████ ████████ █████████ ████████ █████████ █████████
|
|
||||||
0 ───────────────────────────────────────────────────────────────────────────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 1 Jan 2 Jan 3 Jan 4 Jan 5 Jan 6 Jan 7
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
2: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
3: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 91:1 94:0
|
|
||||||
1: 0:0 1:1 4:0 77:1 80:0
|
|
||||||
2: 0:0 64:1 67:0 88:2 97:0
|
|
||||||
3: 0:0 50:3 53:0 74:2 83:0 88:2 97:0
|
|
||||||
4: 0:0 37:1 40:0 61:2 69:0 74:2 83:0 88:2 97:0
|
|
||||||
5: 0:0 1:1 4:0 23:1 26:0 47:2 56:0 61:2 69:0 74:2 83:0 88:2 97:0
|
|
||||||
6: 0:0 10:1 13:0 34:2 42:0 47:2 56:0 61:2 69:0 74:2 83:0 88:2 97:0
|
|
||||||
7: 0:0 20:2 29:0 34:2 42:0 47:2 56:0 61:2 69:0 74:2 83:0 88:2 97:0
|
|
||||||
8: 0:0 7:2 15:0 20:2 29:0 34:2 42:0 47:2 56:0 61:2 69:0 74:2 83:0 88:2 97:0
|
|
||||||
9: 0:0 3:1 4:0 5:1
|
|
||||||
10: 0:0 51:4 52:0
|
|
||||||
11: 0:0 9:1 14:0 22:1 27:0 36:1 41:0 49:5 54:0 63:1 68:0 76:1 81:0 90:1 95:0
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: display(&rendered)
|
|
||||||
---
|
|
||||||
|
|
||||||
15 8.00
|
|
||||||
▅▅▅▅▅▅▅▅
|
|
||||||
7.5 ████████ 0.00
|
|
||||||
████████ ▂▂▂▂▂▂▂▂ ▆▆▆▆▆▆▆▆
|
|
||||||
0 ──────────────────────────────────────
|
|
||||||
▄▄▄▄▄▄▄▄ ████████ ▂▂▂▂▂▂▂▂
|
|
||||||
|
|
||||||
-3.00
|
|
||||||
-15
|
|
||||||
|
|
||||||
▲
|
|
||||||
Jan 13 Jan 14 Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().fg(Color::Rgb(165, 165, 165)).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset).reversed()
|
|
||||||
5: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
6: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
7: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
8: Style::new().fg(Color::Rgb(99, 168, 248)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:0 3:1 5:0 9:2 13:0
|
|
||||||
2: 0:0 8:3 16:0
|
|
||||||
3: 0:0 2:1 5:0 8:3 16:0 35:2 39:0
|
|
||||||
4: 0:0 8:3 16:0 20:3 28:0 33:3 41:0
|
|
||||||
5: 0:0 4:1 5:0 6:2
|
|
||||||
6: 0:0 8:4 16:0 20:5 28:0 33:4 41:0
|
|
||||||
7: 0:0
|
|
||||||
8: 0:0 22:6 27:0
|
|
||||||
9: 0:0 2:1 5:0
|
|
||||||
10: 0:0
|
|
||||||
11: 0:0 24:7 25:0
|
|
||||||
12: 0:0 8:1 14:0 21:8 27:0 34:1 40:0
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: display(&rendered)
|
|
||||||
---
|
|
||||||
|
|
||||||
15 8.00
|
|
||||||
▅▅▅▅▅▅▅▅
|
|
||||||
7.5 ████████ 0.00
|
|
||||||
████████ ▂▂▂▂▂▂▂▂ ▆▆▆▆▆▆▆▆
|
|
||||||
0 ──────────────────────────────────────
|
|
||||||
▄▄▄▄▄▄▄▄ ████████ ▂▂▂▂▂▂▂▂
|
|
||||||
|
|
||||||
-3.00
|
|
||||||
-15
|
|
||||||
|
|
||||||
▲
|
|
||||||
Jan 13 Jan 14 Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().fg(Color::Rgb(76, 76, 76)).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset).reversed()
|
|
||||||
5: Style::new().magenta().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
6: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
7: Style::new().fg(Color::Rgb(28, 100, 200)).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
8: Style::new().fg(Color::Rgb(28, 100, 200)).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:0 3:1 5:0 9:2 13:0
|
|
||||||
2: 0:0 8:3 16:0
|
|
||||||
3: 0:0 2:1 5:0 8:3 16:0 35:2 39:0
|
|
||||||
4: 0:0 8:3 16:0 20:3 28:0 33:3 41:0
|
|
||||||
5: 0:0 4:1 5:0 6:2
|
|
||||||
6: 0:0 8:4 16:0 20:5 28:0 33:4 41:0
|
|
||||||
7: 0:0
|
|
||||||
8: 0:0 22:6 27:0
|
|
||||||
9: 0:0 2:1 5:0
|
|
||||||
10: 0:0
|
|
||||||
11: 0:0 24:7 25:0
|
|
||||||
12: 0:0 8:1 14:0 21:8 27:0 34:1 40:0
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: "snapshots.join(\"\\n\\n\")"
|
|
||||||
---
|
|
||||||
sign=1
|
|
||||||
100.00
|
|
||||||
100 ████████████
|
|
||||||
████████████
|
|
||||||
50 ████████████ 0.01
|
|
||||||
████████████ ▁▁▁▁▁▁▁▁▁▁▁▁
|
|
||||||
0 ───────────────────────────────────────
|
|
||||||
▲
|
|
||||||
Jan 14 Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 11:1 17:0
|
|
||||||
1: 0:0 1:2 4:0 8:3 20:0
|
|
||||||
2: 0:0 8:3 20:0
|
|
||||||
3: 0:0 2:2 4:0 8:3 20:0 31:2 35:0
|
|
||||||
4: 0:0 8:3 20:0 28:3 40:0
|
|
||||||
5: 0:0 3:2 4:0 5:2
|
|
||||||
6: 0:0 14:4 15:0
|
|
||||||
7: 0:0 11:5 17:0 30:2 36:0
|
|
||||||
|
|
||||||
sign=-1
|
|
||||||
100.00
|
|
||||||
100 ████████████
|
|
||||||
████████████
|
|
||||||
50 ████████████
|
|
||||||
████████████
|
|
||||||
0 ──────────────────────────────────────
|
|
||||||
▇▇▇▇▇▇▇▇▇▇▇▇
|
|
||||||
-0.01
|
|
||||||
|
|
||||||
-100
|
|
||||||
|
|
||||||
▲
|
|
||||||
Jan 14 Jan 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
2: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
3: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
4: Style::new().cyan().bg(Color::Reset).underline_color(Color::Reset).reversed()
|
|
||||||
5: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
6: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0 12:1 18:0
|
|
||||||
1: 0:0 2:2 5:0 9:3 21:0
|
|
||||||
2: 0:0 9:3 21:0
|
|
||||||
3: 0:0 3:2 5:0 9:3 21:0
|
|
||||||
4: 0:0 9:3 21:0
|
|
||||||
5: 0:0 4:2 5:0 6:2
|
|
||||||
6: 0:0 28:4 40:0
|
|
||||||
7: 0:0 32:2 37:0
|
|
||||||
8: 0:0
|
|
||||||
9: 0:0 1:2 5:0
|
|
||||||
10: 0:0
|
|
||||||
11: 0:0 15:5 16:0
|
|
||||||
12: 0:0 12:6 18:0 31:2 37:0
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/plot_tests.rs
|
|
||||||
expression: display(&rendered)
|
|
||||||
---
|
|
||||||
|
|
||||||
1
|
|
||||||
|
|
||||||
0.5
|
|
||||||
0 0 0 0 0 0 0.00
|
|
||||||
0 ───────────────────────────────────────
|
|
||||||
▲
|
|
||||||
9 10 11 12 13 14 15
|
|
||||||
|
|
||||||
Palette:
|
|
||||||
0: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset)
|
|
||||||
1: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).dim()
|
|
||||||
2: Style::new().white().bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
3: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold()
|
|
||||||
4: Style::new().fg(Color::Reset).bg(Color::Reset).underline_color(Color::Reset).bold().underlined()
|
|
||||||
Rows (column:palette):
|
|
||||||
0: 0:0
|
|
||||||
1: 0:0 3:1 4:0
|
|
||||||
2: 0:0
|
|
||||||
3: 0:0 1:1 4:0
|
|
||||||
4: 0:0 7:1 8:0 12:1 13:0 18:1 19:0 23:1 24:0 29:1 30:0 34:1 35:0 38:2 42:0
|
|
||||||
5: 0:0 3:1 4:0 5:1
|
|
||||||
6: 0:0 40:3 41:0
|
|
||||||
7: 0:0 7:1 8:0 11:1 13:0 17:1 19:0 22:1 24:0 28:1 30:0 33:1 35:0 39:4 41:0
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/chat_panel_tests.rs
|
|
||||||
expression: "screens.join(\"\\n\")"
|
|
||||||
---
|
|
||||||
" Usage · Enterprise "
|
|
||||||
" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills 6 Chats "
|
|
||||||
" ──────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" Active in past 30 days · sorted by lifetime credits "
|
|
||||||
" "
|
|
||||||
" Chat Lifetime credits "
|
|
||||||
" › Q3 planning analysis 19,350.04 "
|
|
||||||
" ────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" Model Effort Speed Credits "
|
|
||||||
" Top model high Not reported 19,134.43 "
|
|
||||||
" Small model high standard 215.61 "
|
|
||||||
" Refund model high standard -0.000004 "
|
|
||||||
" 1 zero-credit group hidden · a show all "
|
|
||||||
" "
|
|
||||||
" Refactor billing usage 113.00 "
|
|
||||||
" Other usage 109.00 "
|
|
||||||
" Launch readiness review 85.00 "
|
|
||||||
" Plan the week 0.00 "
|
|
||||||
" "
|
|
||||||
" Showing 1–5 of 5 chats "
|
|
||||||
" Local chats · excludes archived chats and subagent usage "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" ↑/↓ row · enter details · esc back "
|
|
||||||
" tab/1–6 report · z dashboard · ? help · R refresh "
|
|
||||||
|
|
||||||
" Usage · Enterprise "
|
|
||||||
" Overview Credits Tokens Plugins Skills Chats "
|
|
||||||
" ──────────────────────────────────────────────────────── "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" Active in past 30 days · sorted by lifetime credits "
|
|
||||||
" "
|
|
||||||
" Chat Lifetime credits "
|
|
||||||
" › Q3 planning analysis 19,350.04 "
|
|
||||||
" ───────────────────────────────────────────────────── "
|
|
||||||
" Model / effort / speed Credits "
|
|
||||||
" Top model 19,134.43 "
|
|
||||||
" high · Not reported "
|
|
||||||
" Small model 215.61 "
|
|
||||||
" high · standard "
|
|
||||||
" Refund model -0.000004 "
|
|
||||||
" high · standard "
|
|
||||||
" 1 zero-credit group hidden · a show all "
|
|
||||||
" "
|
|
||||||
" Refactor billing usage 113.00 "
|
|
||||||
" Other usage 109.00 "
|
|
||||||
" Launch readiness review 85.00 "
|
|
||||||
" Plan the week 0.00 "
|
|
||||||
" "
|
|
||||||
" Showing 1–5 of 5 chats "
|
|
||||||
" Local chats · excludes archived chats and subagent "
|
|
||||||
" usage "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" ↑/↓ row · enter details · esc back "
|
|
||||||
" tab report · z dashboard · ? help · R refresh "
|
|
||||||
|
|
||||||
" Usage · Enterprise "
|
|
||||||
" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills 6 Chats "
|
|
||||||
" ──────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" Active in past 30 days · sorted by lifetime credits "
|
|
||||||
" "
|
|
||||||
" Chat Lifetime credits "
|
|
||||||
" › Q3 planning analysis 19,350.04 "
|
|
||||||
" ────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" Model Effort Speed Credits "
|
|
||||||
" Top model high Not reported 19,134.43 "
|
|
||||||
" Small model high standard 215.61 "
|
|
||||||
" Zero model high standard 0.00 "
|
|
||||||
" Refund model high standard -0.000004 "
|
|
||||||
" 1 zero-credit group · a hide zeros "
|
|
||||||
" "
|
|
||||||
" Refactor billing usage 113.00 "
|
|
||||||
" Other usage 109.00 "
|
|
||||||
" Launch readiness review 85.00 "
|
|
||||||
" Plan the week 0.00 "
|
|
||||||
" "
|
|
||||||
" Showing 1–5 of 5 chats "
|
|
||||||
" Local chats · excludes archived chats and subagent usage "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" ↑/↓ row · enter details · esc back "
|
|
||||||
" tab/1–6 report · z dashboard · ? help · R refresh "
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/chat_panel_tests.rs
|
|
||||||
expression: output
|
|
||||||
---
|
|
||||||
" Usage · Enterprise "
|
|
||||||
" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills 6 Chats "
|
|
||||||
" ──────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" Active in past 30 days · sorted by lifetime credits "
|
|
||||||
" 2 chat estimates unavailable "
|
|
||||||
" "
|
|
||||||
" Chat Lifetime credits "
|
|
||||||
" › Create a comprehensive list of areas to investigate across the runtime and describe ho… 120.00 "
|
|
||||||
" ────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" Create a comprehensive list of areas to investigate across the runtime and describe how each "
|
|
||||||
" area affects performance in a long conversation "
|
|
||||||
" Model Effort Speed Credits "
|
|
||||||
" GPT-5.6-Sol high standard 120.00 "
|
|
||||||
" "
|
|
||||||
" Chat usage unavailable — "
|
|
||||||
" Chat usage unavailable — "
|
|
||||||
" Launch readiness review 85.00 "
|
|
||||||
" Plan the week 0.00 "
|
|
||||||
" "
|
|
||||||
" Showing 1–5 of 5 chats "
|
|
||||||
" Local chats · excludes archived chats and subagent usage "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" ↑/↓ row · enter details · esc back "
|
|
||||||
" tab/1–6 report · z dashboard · ? help · R refresh "
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/consumer_refresh_tests.rs
|
|
||||||
expression: "screen(&mut view, 110, 30)"
|
|
||||||
---
|
|
||||||
" Usage · Plus "
|
|
||||||
" 1 Overview 2 Usage 3 Messages 4 Plugins 5 Skills 6 Chats "
|
|
||||||
" ──────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" s sort: Weekly % "
|
|
||||||
" "
|
|
||||||
" Usage estimates · active in past 30 days · sorted by Weekly % "
|
|
||||||
" Recorded usage / current full limit · may exceed 100% "
|
|
||||||
" Partial ranking · 1 partial · 2 unavailable "
|
|
||||||
" "
|
|
||||||
" Chat Weekly % 5-hour % Balance credits "
|
|
||||||
" › Refunded task · partial 125.0% 0.0% -0.000004 "
|
|
||||||
" ─────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" Refunded task "
|
|
||||||
" Weekly % 125.0% "
|
|
||||||
" 5-hour % 0.0% "
|
|
||||||
" Balance credits -0.000004 "
|
|
||||||
" "
|
|
||||||
" Model / effort / speed Weekly % "
|
|
||||||
" gpt-5.5 — "
|
|
||||||
" high · fast · codex "
|
|
||||||
" "
|
|
||||||
" Plan-covered task 12.1% — 0.00 "
|
|
||||||
" Chat usage unavailable — — — "
|
|
||||||
" Chat usage unavailable — — — "
|
|
||||||
" "
|
|
||||||
" Showing 1–4 of 4 chats "
|
|
||||||
" Local chats · includes discovered descendants · excludes archived roots "
|
|
||||||
" "
|
|
||||||
" ↑/↓ row · enter details · esc back "
|
|
||||||
" tab/1–6 report · z dashboard · ? help · R refresh "
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/dashboard_tests.rs
|
|
||||||
expression: "format!(\"{wide}\\n{narrow}\")"
|
|
||||||
---
|
|
||||||
" Usage · Plus "
|
|
||||||
" 1 Overview 2 Usage 3 Messages 4 Plugins 5 Skills 6 Chats "
|
|
||||||
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" Dashboard · enter focus · r 7d/30d · Aug 27–Sep 2, 2026 · g Feature "
|
|
||||||
" "
|
|
||||||
" ╭─ 1 Overview ────────────────────────────────────────────────────╮ ╭─ ▸ 2 Usage ───────────────────────────────────────────────────────╮ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ No history has been reported. │ │ 7d │ "
|
|
||||||
" │ │ │ By feature │ "
|
|
||||||
" │ │ │ Total usage · relative units │ "
|
|
||||||
" │ │ │ 20 73 64 91 81 100 86 │ "
|
|
||||||
" │ │ │ 100 ▁▁▁▁▁ ▅▅▅▅▅▅ ▅▅▅▅▅ ▇▇▇▇▇▇ ▆▆▆▆▆ ██████ ▆▆▆▆▆▆ │ "
|
|
||||||
" │ │ │ 0 ──────────────────────────────────────────────────────────── │ "
|
|
||||||
" │ │ │ ▲ │ "
|
|
||||||
" │ │ │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ │ │ Sep 2 · 86 usage units │ "
|
|
||||||
" │ │ │ ● Tasks 64.0% │ "
|
|
||||||
" │ │ │ ● Code review 14.0% │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" ╰───────────────────────────────────────────────────────────────────╯ ╰───────────────────────────────────────────────────────────────────╯ "
|
|
||||||
" "
|
|
||||||
" ╭─ 3 Messages ────────────────────────────────────────────────────╮ ╭─ 4 Plugins ─────────────────────────────────────────────────────╮ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ 7d │ │ 7d │ "
|
|
||||||
" │ By model │ │ 186 calls │ "
|
|
||||||
" │ 574 reported messages │ │ 34 23 29 26 22 23 29 │ "
|
|
||||||
" │ 62 83 107 75 59 85 103 │ │ 40 ▆▆▆▆▆ ▄▄▄▄▄▄ ▅▅▅▅▅▅ ▅▅▅▅▅ ▄▄▄▄▄▄ ▄▄▄▄▄▄ ▅▅▅▅▅▅ │ "
|
|
||||||
" │ 150 ▃▃▃▃▃ ▄▄▄▄▄▄ ▅▅▅▅▅ ▄▄▄▄▄▄ ▃▃▃▃▃ ▄▄▄▄▄▄ ▅▅▅▅▅▅ │ │ 0 ───────────────────────────────────────────────────────────── │ "
|
|
||||||
" │ 0 ──────────────────────────────────────────────────────────── │ │ ▲ │ "
|
|
||||||
" │ ▲ │ │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ "
|
|
||||||
" │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ │ │ "
|
|
||||||
" │ │ │ Sep 2 · 29 calls │ "
|
|
||||||
" │ Sep 2 · 103 messages │ │ ● Slack 10 │ "
|
|
||||||
" │ ● GPT-5.6-Sol 61 │ │ ● Figma 10 │ "
|
|
||||||
" │ ● GPT-5.6-Terra 25 │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" ╰───────────────────────────────────────────────────────────────────╯ ╰───────────────────────────────────────────────────────────────────╯ "
|
|
||||||
" "
|
|
||||||
" ╭─ 5 Skills ──────────────────────────────────────────────────────╮ ╭─ 6 Chats ───────────────────────────────────────────────────────╮ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ 7d │ │ No history has been reported. │ "
|
|
||||||
" │ 54 uses │ │ │ "
|
|
||||||
" │ 8 6 9 8 7 5 11 │ │ │ "
|
|
||||||
" │ 20 ▃▃▃▃▃ ▂▂▂▂▂▂ ▃▃▃▃▃▃ ▃▃▃▃▃ ▂▂▂▂▂▂ ▂▂▂▂▂▂ ▄▄▄▄▄▄ │ │ │ "
|
|
||||||
" │ 0 ───────────────────────────────────────────────────────────── │ │ │ "
|
|
||||||
" │ ▲ │ │ │ "
|
|
||||||
" │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ Sep 2 · 11 uses │ │ │ "
|
|
||||||
" │ ● Testing 4 │ │ │ "
|
|
||||||
" │ ● Code review 3 │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" │ │ │ │ "
|
|
||||||
" ╰───────────────────────────────────────────────────────────────────╯ ╰───────────────────────────────────────────────────────────────────╯ "
|
|
||||||
" "
|
|
||||||
" enter focus · tab card · esc back "
|
|
||||||
" tab/1–6 report · z focus · ? help · R refresh "
|
|
||||||
|
|
||||||
" Usage · Plus "
|
|
||||||
" Overview Usage Messages Plugins Skills Chats "
|
|
||||||
" ────────────────────────────────────────────────────────────────────── "
|
|
||||||
" Dashboard · enter focus · r 7d/30d · Aug 27–Sep 2, 2026 "
|
|
||||||
" g Feature "
|
|
||||||
" "
|
|
||||||
" ╭─ 1 Overview ─────────────────────────────────────────────────────╮ "
|
|
||||||
" │ │ "
|
|
||||||
" │ No history has been reported. │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ │ "
|
|
||||||
" ╰────────────────────────────────────────────────────────────────────╯ "
|
|
||||||
" "
|
|
||||||
" ╭─ ▸ 2 Usage ────────────────────────────────────────────────────────╮ "
|
|
||||||
" │ │ "
|
|
||||||
" │ 7d │ "
|
|
||||||
" │ By feature │ "
|
|
||||||
" │ Total usage · relative units │ "
|
|
||||||
" │ 20 73 64 91 81 100 86 │ "
|
|
||||||
" │ 100 ▁▁▁▁▁ ▅▅▅▅▅▅ ▅▅▅▅▅▅ ▇▇▇▇▇ ▆▆▆▆▆▆ ██████ ▆▆▆▆▆▆ │ "
|
|
||||||
" │ 0 ───────────────────────────────────────────────────────────── │ "
|
|
||||||
" │ ▲ │ "
|
|
||||||
" │ Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 │ "
|
|
||||||
" │ │ "
|
|
||||||
" │ Sep 1 · 100 usage units │ "
|
|
||||||
" │ ● Tasks 65.0% │ "
|
|
||||||
" │ ● Code review 15.0% │ "
|
|
||||||
" │ │ "
|
|
||||||
" ╰────────────────────────────────────────────────────────────────────╯ "
|
|
||||||
" "
|
|
||||||
" ╭─ 3 Messages ─────────────────────────────────────────────────────╮ "
|
|
||||||
" │ │ "
|
|
||||||
" │ 7d │ "
|
|
||||||
" │ By model │ "
|
|
||||||
" │ 574 reported messages │ "
|
|
||||||
" │ 62 83 107 75 59 85 103 │ "
|
|
||||||
" enter focus · tab card · pgup/pgdn scroll · esc back "
|
|
||||||
" tab report · z focus · ? help · R refresh "
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/recovery_tests.rs
|
|
||||||
expression: output
|
|
||||||
---
|
|
||||||
" Usage · Business "
|
|
||||||
" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills "
|
|
||||||
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" r 7d/30d · Aug 27–Sep 2, 2026 · g Model · m All models "
|
|
||||||
" Updated · Sep 2 16:00 UTC "
|
|
||||||
" 4.4M tokens ──────────────────────────────────────────── "
|
|
||||||
" Sep 2 · 731,000 tokens "
|
|
||||||
" 1M Model Tokens "
|
|
||||||
" ● GPT-5.5 731,000 "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" 850K "
|
|
||||||
" ▆▆▆▆▆▆▆▆▆▆▆▆ "
|
|
||||||
" ████████████ "
|
|
||||||
" 773.5K ████████████ "
|
|
||||||
" ▁▁▁▁▁▁▁▁▁▁▁ ████████████ "
|
|
||||||
" ███████████ ████████████ 731K "
|
|
||||||
" ███████████ ████████████ "
|
|
||||||
" ███████████ 688.5K ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" 620.5K ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ▆▆▆▆▆▆▆▆▆▆▆▆ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ 544K ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" 500K ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" 170K ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ▁▁▁▁▁▁▁▁▁▁▁ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" ███████████ ████████████ ████████████ ███████████ ████████████ ████████████ ████████████ "
|
|
||||||
" 0 ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" ▲ "
|
|
||||||
" Aug 27 Aug 28 Aug 29 Aug 30 Aug 31 Sep 1 Sep 2 "
|
|
||||||
" ←/→ day · enter details · esc back "
|
|
||||||
" tab/1–5 report · z dashboard · ? help · R refresh "
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/recovery_tests.rs
|
|
||||||
expression: "output.join(\"\\n\")"
|
|
||||||
---
|
|
||||||
" Updated · Sep 2 4:00 PM UTC "
|
|
||||||
Updated Sep 2 4:00 PM UTC
|
|
||||||
Report updated Sep 2 4:00 PM UTC
|
|
||||||
Updated Sep 2 4:00 PM UTC · recent activity may be delayed
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/redesign_tests.rs
|
|
||||||
expression: help
|
|
||||||
---
|
|
||||||
" Usage · Business "
|
|
||||||
" Overview Credits Tokens › "
|
|
||||||
" ────────────────────────────────────── "
|
|
||||||
" Usage shortcuts "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" Tab / ⇧tab · next / previous report "
|
|
||||||
" 1–5 · open a report directly "
|
|
||||||
" ← / → · select chart day or plan "
|
|
||||||
" window "
|
|
||||||
" ↑ / ↓ · select chat or plan period; "
|
|
||||||
" scroll Overview "
|
|
||||||
" enter · expand or collapse details "
|
|
||||||
" pgup / pgdn · scroll report "
|
|
||||||
" esc back · pgup/pgdn scroll "
|
|
||||||
" ? close help "
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/redesign_tests.rs
|
|
||||||
expression: "format!(\"{tokens}\\n{failed}\")"
|
|
||||||
---
|
|
||||||
" Usage · Business "
|
|
||||||
" Overview Credits Tokens › "
|
|
||||||
" ────────────────────────────────────── "
|
|
||||||
" r 7d/30d · Aug 27–Sep 2, 2026 "
|
|
||||||
" g Model · m All models "
|
|
||||||
" Updated · Sep 2 16:00 UTC "
|
|
||||||
" 4.4M tokens "
|
|
||||||
" "
|
|
||||||
" ────────────────────────────────────── "
|
|
||||||
" Sep 2 · 731,000 tokens "
|
|
||||||
" Model Tokens "
|
|
||||||
" ● GPT-5.5 731,000 "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" ←/→ day · enter details · esc back "
|
|
||||||
" tab report · z all · ? · R refresh "
|
|
||||||
|
|
||||||
" Usage · Business "
|
|
||||||
" Overview Credits Tokens › "
|
|
||||||
" ────────────────────────────────────── "
|
|
||||||
" r 7d/30d · Aug 27–Sep 2, 2026 "
|
|
||||||
" g Model · m All models "
|
|
||||||
" "
|
|
||||||
" Couldn't load tokens. "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" ←/→ day · esc back "
|
|
||||||
" tab report · z all · ? · R refresh "
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/summary_tests.rs
|
|
||||||
expression: "screen(&mut view, 64, 60)"
|
|
||||||
---
|
|
||||||
" Usage · Plus "
|
|
||||||
" Overview Usage Messages Plugins Skills Chats "
|
|
||||||
" ────────────────────────────────────────────────────────────── "
|
|
||||||
" g Cumulative "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" Example User "
|
|
||||||
" @example.user "
|
|
||||||
" Plus "
|
|
||||||
" "
|
|
||||||
" 142.3B 7B 44h 7m "
|
|
||||||
" Lifetime tokens Peak tokens Longest chat "
|
|
||||||
" "
|
|
||||||
" 158 days 160 days "
|
|
||||||
" Current streak Longest streak "
|
|
||||||
" "
|
|
||||||
" Token activity "
|
|
||||||
" Last 12 months "
|
|
||||||
" "
|
|
||||||
" Mar Apr May Jun Jul Aug "
|
|
||||||
" max █ "
|
|
||||||
" █ "
|
|
||||||
" █ "
|
|
||||||
" █ "
|
|
||||||
" █ "
|
|
||||||
" █ "
|
|
||||||
" 0 █ "
|
|
||||||
" "
|
|
||||||
" Running total · top 300 "
|
|
||||||
" "
|
|
||||||
" Activity insights "
|
|
||||||
" "
|
|
||||||
" Fast Mode 37% "
|
|
||||||
" Most used reasoning high · 26% "
|
|
||||||
" Skills explored 147 "
|
|
||||||
" Total skills used 13,190 "
|
|
||||||
" Total chats 21,482 "
|
|
||||||
" "
|
|
||||||
" Most used plugins and skills "
|
|
||||||
" "
|
|
||||||
" $review 1,142 runs "
|
|
||||||
" @GitHub 1,059 runs "
|
|
||||||
" "
|
|
||||||
" Statistics as of Sep 9, 2026 "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" esc back "
|
|
||||||
" tab report · z dashboard · ? help · R refresh "
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/summary_tests.rs
|
|
||||||
expression: "screen(&mut view, 140, 44)"
|
|
||||||
---
|
|
||||||
" Usage · Plus "
|
|
||||||
" 1 Overview 2 Usage 3 Messages 4 Plugins 5 Skills 6 Chats "
|
|
||||||
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" g Daily "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" Example User "
|
|
||||||
" @example.user "
|
|
||||||
" Plus "
|
|
||||||
" "
|
|
||||||
" 142.3B 7B 44h 7m 158 days 160 days "
|
|
||||||
" Lifetime tokens Peak tokens Longest chat Current streak Longest streak "
|
|
||||||
" "
|
|
||||||
" Token activity "
|
|
||||||
" Last 12 months "
|
|
||||||
" "
|
|
||||||
" Oct Nov Dec Jan Feb Mar Apr May Jun Jul Aug "
|
|
||||||
" Su □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ "
|
|
||||||
" Mo □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ "
|
|
||||||
" Tu □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ ■ "
|
|
||||||
" We □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ ■ "
|
|
||||||
" Th □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ "
|
|
||||||
" Fr □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ "
|
|
||||||
" Sa □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ "
|
|
||||||
" "
|
|
||||||
" Less □ ■ ■ ■ ■ More "
|
|
||||||
" "
|
|
||||||
" Activity insights Most used plugins and skills "
|
|
||||||
" "
|
|
||||||
" Fast Mode 37% $review 1,142 runs "
|
|
||||||
" Most used reasoning high · 26% @GitHub 1,059 runs "
|
|
||||||
" Skills explored 147 "
|
|
||||||
" Total skills used 13,190 "
|
|
||||||
" Total chats 21,482 "
|
|
||||||
" "
|
|
||||||
" Statistics as of Sep 9, 2026 "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" esc back "
|
|
||||||
" tab/1–6 report · z dashboard · ? help · R refresh "
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/analytics/summary_tests.rs
|
|
||||||
expression: rendered
|
|
||||||
---
|
|
||||||
" Usage · Business "
|
|
||||||
" 1 Overview 2 Credits 3 Tokens 4 Plugins 5 Skills "
|
|
||||||
" ────────────────────────────────────────────────────────────────────────────────────────────────── "
|
|
||||||
" g Daily "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" Business "
|
|
||||||
" "
|
|
||||||
" 0 — — — — "
|
|
||||||
" Lifetime tokens Peak tokens Longest chat Current streak Longest streak "
|
|
||||||
" "
|
|
||||||
" Token activity "
|
|
||||||
" Last 12 months "
|
|
||||||
" "
|
|
||||||
" Token activity history unavailable "
|
|
||||||
" "
|
|
||||||
" Activity insights Most used plugins and skills "
|
|
||||||
" "
|
|
||||||
" Fast Mode 0% No reported plugins or skills. "
|
|
||||||
" Most used reasoning — "
|
|
||||||
" Skills explored — "
|
|
||||||
" Total skills used — "
|
|
||||||
" Total chats 0 "
|
|
||||||
" "
|
|
||||||
" Some profile statistics are unavailable. "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" "
|
|
||||||
" esc back "
|
|
||||||
" tab/1–5 report · z dashboard · ? help · R refresh "
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
//! Charts and legends share the terminal's ANSI palette.
|
|
||||||
//! Secondary text blends probed defaults only when the terminal supports that color depth.
|
|
||||||
|
|
||||||
use crate::color::blend;
|
|
||||||
use crate::style::accent_style;
|
|
||||||
use crate::terminal_palette::StdoutColorLevel;
|
|
||||||
use crate::terminal_palette::best_color;
|
|
||||||
use crate::terminal_palette::default_bg;
|
|
||||||
use crate::terminal_palette::default_fg;
|
|
||||||
use crate::terminal_palette::effective_stdout_color_level;
|
|
||||||
use ratatui::style::Color;
|
|
||||||
use ratatui::style::Style;
|
|
||||||
use ratatui::text::Span;
|
|
||||||
|
|
||||||
pub(super) fn series_colors() -> [Color; 4] {
|
|
||||||
[Color::Cyan, Color::Magenta, Color::Green, Color::Reset]
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn number(text: impl Into<String>) -> Span<'static> {
|
|
||||||
Span::styled(text.into(), accent_style())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Labels and instructions need more contrast than decorative rules or inactive values.
|
|
||||||
pub(super) fn secondary_style() -> Style {
|
|
||||||
if !matches!(
|
|
||||||
effective_stdout_color_level(),
|
|
||||||
StdoutColorLevel::TrueColor | StdoutColorLevel::Ansi256
|
|
||||||
) {
|
|
||||||
return Style::default().dim();
|
|
||||||
}
|
|
||||||
match (default_fg(), default_bg()) {
|
|
||||||
(Some(fg), Some(bg)) => {
|
|
||||||
Style::default().fg(best_color(blend(fg, bg, /*alpha*/ 0.70)))
|
|
||||||
}
|
|
||||||
_ => Style::default().dim(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Paint one selectable row, including its padding, using the shared picker accent.
|
|
||||||
pub(super) fn select_row(line: &mut ratatui::text::Line<'static>, width: usize) {
|
|
||||||
let style = crate::bottom_pane::selection_style();
|
|
||||||
line.spans
|
|
||||||
.push(" ".repeat(width.saturating_sub(line.width())).into());
|
|
||||||
line.style = style;
|
|
||||||
for span in &mut line.spans {
|
|
||||||
span.style = style;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
//! Render both account layouts with explicit terminal palettes, including color and selection styles.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
use crate::style::accent_style;
|
|
||||||
use crate::terminal_palette::with_test_default_colors;
|
|
||||||
use crate::terminal_probe::DefaultColors;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use ratatui::buffer::Buffer;
|
|
||||||
use ratatui::layout::Rect;
|
|
||||||
use ratatui::style::Color;
|
|
||||||
use ratatui::style::Modifier;
|
|
||||||
|
|
||||||
fn luminance(rgb: (u8, u8, u8)) -> f64 {
|
|
||||||
let [r, g, b] = [rgb.0, rgb.1, rgb.2].map(|channel| {
|
|
||||||
let value = f64::from(channel) / 255.0;
|
|
||||||
if value <= 0.04045 {
|
|
||||||
value / 12.92
|
|
||||||
} else {
|
|
||||||
((value + 0.055) / 1.055).powf(/*n*/ 2.4)
|
|
||||||
}
|
|
||||||
});
|
|
||||||
0.2126 * r + 0.7152 * g + 0.0722 * b
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_sections_adapt_to_terminal_colors() {
|
|
||||||
for (theme, colors) in [
|
|
||||||
(
|
|
||||||
"light",
|
|
||||||
DefaultColors {
|
|
||||||
fg: (0, 0, 0),
|
|
||||||
bg: (255, 255, 255),
|
|
||||||
},
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"dark",
|
|
||||||
DefaultColors {
|
|
||||||
fg: (230, 230, 230),
|
|
||||||
bg: (16, 16, 16),
|
|
||||||
},
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
with_test_default_colors(colors, || {
|
|
||||||
for kind in [
|
|
||||||
models::AccountKind::Consumer,
|
|
||||||
models::AccountKind::Enterprise,
|
|
||||||
] {
|
|
||||||
let mut view = fixture::view(kind);
|
|
||||||
view.sections[Section::Chats].detail = Some(0);
|
|
||||||
for section in view.visible_sections() {
|
|
||||||
let section = *section;
|
|
||||||
view.section = section;
|
|
||||||
let area = Rect::new(
|
|
||||||
/*x*/ 0, /*y*/ 0, /*width*/ 120, /*height*/ 42,
|
|
||||||
);
|
|
||||||
let mut buffer = Buffer::empty(area);
|
|
||||||
view.render(area, &mut buffer);
|
|
||||||
let label = view.tab_label(section);
|
|
||||||
let tab = buffer
|
|
||||||
.content
|
|
||||||
.chunks(usize::from(area.width))
|
|
||||||
.nth(/*n*/ 1)
|
|
||||||
.unwrap()
|
|
||||||
.windows(label.len())
|
|
||||||
.find(|cells| {
|
|
||||||
cells
|
|
||||||
.iter()
|
|
||||||
.map(ratatui::buffer::Cell::symbol)
|
|
||||||
.collect::<String>()
|
|
||||||
== label
|
|
||||||
})
|
|
||||||
.expect("the report tab is visible");
|
|
||||||
let heading = &tab[0];
|
|
||||||
let active = crate::bottom_pane::active_tab_style();
|
|
||||||
assert_eq!(heading.fg, active.fg.unwrap());
|
|
||||||
assert_eq!(heading.bg, active.bg.unwrap());
|
|
||||||
assert!(heading.modifier.contains(Modifier::BOLD));
|
|
||||||
for marker in buffer.content.iter().filter(|cell| cell.symbol() == "▲") {
|
|
||||||
assert_eq!(marker.fg, accent_style().fg.unwrap());
|
|
||||||
assert_eq!(marker.bg, Color::Reset);
|
|
||||||
assert!(marker.modifier.contains(Modifier::BOLD));
|
|
||||||
}
|
|
||||||
if theme == "light" {
|
|
||||||
for (index, cell) in buffer
|
|
||||||
.content
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.filter(|(_, cell)| !cell.symbol().trim().is_empty())
|
|
||||||
{
|
|
||||||
// Keyboard hints deliberately keep the requested white key style.
|
|
||||||
// Report text and chart colors still adapt to light backgrounds.
|
|
||||||
if cell.fg == Color::White {
|
|
||||||
let y = area.y + (index / usize::from(area.width)) as u16;
|
|
||||||
assert!(y >= area.bottom() - 2 || (3..5).contains(&y));
|
|
||||||
assert_eq!(cell.modifier, Modifier::BOLD);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let foreground = match cell.fg {
|
|
||||||
Color::Rgb(r, g, b) => (r, g, b),
|
|
||||||
Color::White => (255, 255, 255),
|
|
||||||
Color::Black => (0, 0, 0),
|
|
||||||
Color::Reset => colors.fg,
|
|
||||||
_ => continue,
|
|
||||||
};
|
|
||||||
let background = match cell.bg {
|
|
||||||
Color::Rgb(r, g, b) => (r, g, b),
|
|
||||||
Color::White => (255, 255, 255),
|
|
||||||
Color::Black => (0, 0, 0),
|
|
||||||
Color::Reset => colors.bg,
|
|
||||||
_ => continue,
|
|
||||||
};
|
|
||||||
let fg = luminance(foreground);
|
|
||||||
let bg = luminance(background);
|
|
||||||
let contrast = (fg.max(bg) + 0.05) / (fg.min(bg) + 0.05);
|
|
||||||
assert!(
|
|
||||||
contrast >= 4.5,
|
|
||||||
"{}: {:?} has contrast {contrast}",
|
|
||||||
cell.symbol(),
|
|
||||||
cell.fg
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn chat_selection_keeps_a_highlighted_trailing_blank_after_wrapping() {
|
|
||||||
with_test_default_colors(
|
|
||||||
DefaultColors {
|
|
||||||
fg: (30, 30, 30),
|
|
||||||
bg: (255, 255, 255),
|
|
||||||
},
|
|
||||||
|| {
|
|
||||||
for kind in [models::AccountKind::Business, models::AccountKind::Consumer] {
|
|
||||||
let mut view = fixture::view(kind);
|
|
||||||
view.section = Section::Chats;
|
|
||||||
view.tasks = Load::Ready(tasks::Chats {
|
|
||||||
rows: vec![tasks::Chat {
|
|
||||||
title: "Building Analytics".into(),
|
|
||||||
task: Some(
|
|
||||||
serde_json::from_value(serde_json::json!({
|
|
||||||
"thread_id": "padding-fixture",
|
|
||||||
"data_status": "available",
|
|
||||||
"usage_source": "credits",
|
|
||||||
"weekly_limit_percent": 42.0,
|
|
||||||
"five_hour_limit_percent": 15.0,
|
|
||||||
"balance_usage_credits": "35.83",
|
|
||||||
"groups": []
|
|
||||||
}))
|
|
||||||
.unwrap(),
|
|
||||||
),
|
|
||||||
}],
|
|
||||||
..tasks::Chats::default()
|
|
||||||
});
|
|
||||||
for width in [40, 120] {
|
|
||||||
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, /*height*/ 30);
|
|
||||||
let mut buffer = Buffer::empty(area);
|
|
||||||
view.render(area, &mut buffer);
|
|
||||||
let selection = crate::bottom_pane::selection_style().bg.unwrap();
|
|
||||||
let selected_rows = buffer
|
|
||||||
.content
|
|
||||||
.chunks(usize::from(width))
|
|
||||||
.skip(usize::from(view.body_area.y))
|
|
||||||
.take(usize::from(view.body_area.height))
|
|
||||||
.filter(|row| row.iter().any(|cell| cell.bg == selection))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
assert!(!selected_rows.is_empty());
|
|
||||||
for row in selected_rows {
|
|
||||||
let end = row.iter().rposition(|cell| cell.bg == selection).unwrap();
|
|
||||||
assert_eq!(row[end].symbol(), " ");
|
|
||||||
assert!(
|
|
||||||
row[..end]
|
|
||||||
.iter()
|
|
||||||
.any(|cell| !cell.symbol().trim().is_empty())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
//! Account profile loading and the Summary's year-view interaction.
|
|
||||||
//! Aggregation changes reuse the loaded profile; account refresh replaces all profile data.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::activity_chart::TokenActivityView;
|
|
||||||
use super::client::Live;
|
|
||||||
use super::data::Load;
|
|
||||||
use super::sections::Section;
|
|
||||||
use crate::keymap::ListAction;
|
|
||||||
use codex_backend_client::AccountProfile;
|
|
||||||
|
|
||||||
pub(super) const VIEWS: [TokenActivityView; 3] = [
|
|
||||||
TokenActivityView::Daily,
|
|
||||||
TokenActivityView::Weekly,
|
|
||||||
TokenActivityView::Cumulative,
|
|
||||||
];
|
|
||||||
|
|
||||||
impl Live {
|
|
||||||
pub(super) async fn profile(&self) -> Result<Option<AccountProfile>, String> {
|
|
||||||
let session = self.session().await?;
|
|
||||||
let profile = session
|
|
||||||
.backend
|
|
||||||
.request(|client| async move { client.get_account_profile().await })
|
|
||||||
.await;
|
|
||||||
self.ensure_identity().await?;
|
|
||||||
profile.map(Some).map_err(super::client::request_error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(crate) fn select_summary(&mut self, view: Option<TokenActivityView>) {
|
|
||||||
self.section = Section::Summary;
|
|
||||||
self.zoomed = true;
|
|
||||||
self.show_help = false;
|
|
||||||
*self.scroll_offset_mut() = 0;
|
|
||||||
if let Some(view) = view {
|
|
||||||
self.sections[Section::Summary].group = VIEWS
|
|
||||||
.iter()
|
|
||||||
.position(|item| *item == view)
|
|
||||||
.unwrap_or_default();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn load_summary(&mut self) {
|
|
||||||
if let (Some((_, _, frame)), Some(live)) = (&self.connection, &self.live) {
|
|
||||||
let live = std::sync::Arc::clone(live);
|
|
||||||
self.profile = Load::start(async move { live.profile().await }, frame.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn summary_action(&mut self, action: Option<ListAction>) {
|
|
||||||
let step = match action {
|
|
||||||
Some(ListAction::MoveUp) => Some(-1),
|
|
||||||
Some(ListAction::MoveDown) => Some(1),
|
|
||||||
Some(ListAction::PageUp) => Some(-(self.viewport_height as isize)),
|
|
||||||
Some(ListAction::PageDown) => Some(self.viewport_height as isize),
|
|
||||||
Some(ListAction::JumpTop) => {
|
|
||||||
*self.scroll_offset_mut() = 0;
|
|
||||||
Some(0)
|
|
||||||
}
|
|
||||||
Some(ListAction::JumpBottom) => {
|
|
||||||
*self.scroll_offset_mut() = usize::MAX;
|
|
||||||
Some(0)
|
|
||||||
}
|
|
||||||
Some(ListAction::Cancel) => {
|
|
||||||
self.is_done = true;
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Some(ListAction::MoveLeft | ListAction::MoveRight | ListAction::Accept) | None => None,
|
|
||||||
};
|
|
||||||
if let Some(step) = step {
|
|
||||||
*self.scroll_offset_mut() = self.scroll_offset().saturating_add_signed(step);
|
|
||||||
self.follow_selection = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,337 +0,0 @@
|
|||||||
//! Responsive profile summary using the Analytics container's typography and spacing.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::activity_chart;
|
|
||||||
use super::render::columns;
|
|
||||||
use super::render::join_columns;
|
|
||||||
use super::sections::Section;
|
|
||||||
use super::styles::secondary_style;
|
|
||||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow as truncate;
|
|
||||||
use crate::wrapping::RtOptions;
|
|
||||||
use crate::wrapping::word_wrap_lines;
|
|
||||||
use codex_backend_client::ProfileInvocationKind;
|
|
||||||
use ratatui::style::Styled;
|
|
||||||
use ratatui::style::Stylize;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn summary_lines(&self, width: usize) -> Vec<Line<'static>> {
|
|
||||||
let width = width.max(/*other*/ 1);
|
|
||||||
let inner_width = width.min(/*other*/ 110);
|
|
||||||
let mut lines = Vec::new();
|
|
||||||
let Some(profile) = self.profile.ready() else {
|
|
||||||
lines.push(
|
|
||||||
self.profile
|
|
||||||
.message()
|
|
||||||
.unwrap_or("Profile statistics unavailable.")
|
|
||||||
.to_owned()
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
return lines;
|
|
||||||
};
|
|
||||||
if let Some(identity) = &profile.profile {
|
|
||||||
if let Some(name) = identity
|
|
||||||
.display_name
|
|
||||||
.as_deref()
|
|
||||||
.filter(|name| !name.trim().is_empty())
|
|
||||||
{
|
|
||||||
lines.push(center(
|
|
||||||
truncate(name.trim().to_owned().bold().into(), inner_width),
|
|
||||||
inner_width,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if let Some(username) = identity
|
|
||||||
.username
|
|
||||||
.as_deref()
|
|
||||||
.filter(|name| !name.trim().is_empty())
|
|
||||||
{
|
|
||||||
lines.push(center(
|
|
||||||
truncate(
|
|
||||||
format!("@{}", username.trim().trim_start_matches('@'))
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
inner_width,
|
|
||||||
),
|
|
||||||
inner_width,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let plan = self
|
|
||||||
.account
|
|
||||||
.ready()
|
|
||||||
.map(|plan| crate::subscription::SubscriptionDisplay::Analytics.label(*plan));
|
|
||||||
if let Some(plan) = plan {
|
|
||||||
lines.push(center(
|
|
||||||
plan.set_style(secondary_style()).into(),
|
|
||||||
inner_width,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
lines.push(Line::default());
|
|
||||||
let tokens = &profile.stats.tokens;
|
|
||||||
let fields = [
|
|
||||||
(
|
|
||||||
"Lifetime tokens",
|
|
||||||
tokens
|
|
||||||
.lifetime_tokens
|
|
||||||
.map(|value| super::data::compact_amount(value as f64)),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Peak tokens",
|
|
||||||
tokens
|
|
||||||
.peak_daily_tokens
|
|
||||||
.map(|value| super::data::compact_amount(value as f64)),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Longest chat",
|
|
||||||
tokens.longest_running_turn_sec.map(duration),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Current streak",
|
|
||||||
tokens
|
|
||||||
.current_streak_days
|
|
||||||
.map(|days| format!("{days} days")),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Longest streak",
|
|
||||||
tokens
|
|
||||||
.longest_streak_days
|
|
||||||
.map(|days| format!("{days} days")),
|
|
||||||
),
|
|
||||||
];
|
|
||||||
if !self.zoomed {
|
|
||||||
lines.extend(fields.into_iter().map(|(label, value)| {
|
|
||||||
columns(
|
|
||||||
label.set_style(secondary_style()).into(),
|
|
||||||
value.unwrap_or_else(|| "—".into()).bold().into(),
|
|
||||||
inner_width,
|
|
||||||
)
|
|
||||||
}));
|
|
||||||
return lines;
|
|
||||||
}
|
|
||||||
let count = if inner_width >= 90 {
|
|
||||||
5
|
|
||||||
} else if inner_width >= 54 {
|
|
||||||
3
|
|
||||||
} else if inner_width >= 36 {
|
|
||||||
2
|
|
||||||
} else {
|
|
||||||
1
|
|
||||||
};
|
|
||||||
for chunk in fields.chunks(count) {
|
|
||||||
let cell_width = inner_width / chunk.len();
|
|
||||||
let mut values = Line::default();
|
|
||||||
let mut labels = Line::default();
|
|
||||||
for (index, (label, value)) in chunk.iter().enumerate() {
|
|
||||||
for (row, cell) in [
|
|
||||||
(
|
|
||||||
&mut values,
|
|
||||||
value.clone().unwrap_or_else(|| "—".into()).bold(),
|
|
||||||
),
|
|
||||||
(&mut labels, label.to_string().set_style(secondary_style())),
|
|
||||||
] {
|
|
||||||
let cell = center(truncate(cell.into(), cell_width), cell_width);
|
|
||||||
let padding = cell_width.saturating_sub(cell.width());
|
|
||||||
row.spans.extend(cell.spans);
|
|
||||||
if index + 1 < chunk.len() {
|
|
||||||
row.spans.push(" ".repeat(padding).into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
lines.extend([values, labels, Line::default()]);
|
|
||||||
}
|
|
||||||
let selected = self.sections[Section::Summary].group;
|
|
||||||
lines.push("Token activity".bold().into());
|
|
||||||
lines.push("Last 12 months".set_style(secondary_style()).into());
|
|
||||||
lines.push(Line::default());
|
|
||||||
if let Some(buckets) = &tokens.daily_usage_buckets {
|
|
||||||
lines.extend(activity_chart::chart_lines(
|
|
||||||
super::summary::VIEWS[selected],
|
|
||||||
buckets,
|
|
||||||
self.end_date,
|
|
||||||
inner_width as u16,
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
lines.push(
|
|
||||||
"Token activity history unavailable"
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
lines.push(Line::default());
|
|
||||||
let stats = &profile.stats;
|
|
||||||
let reasoning = stats
|
|
||||||
.most_used_reasoning_effort
|
|
||||||
.as_deref()
|
|
||||||
.map(|effort| {
|
|
||||||
let percentage = percent(stats.most_used_reasoning_effort_percentage.as_ref());
|
|
||||||
format!("{effort} · {percentage}")
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|| "—".into());
|
|
||||||
let metrics = [
|
|
||||||
(
|
|
||||||
"Fast Mode",
|
|
||||||
percent(stats.fast_mode_usage_percentage.as_ref()),
|
|
||||||
),
|
|
||||||
("Most used reasoning", reasoning),
|
|
||||||
("Skills explored", count_value(stats.unique_skills_used)),
|
|
||||||
("Total skills used", count_value(stats.total_skills_used)),
|
|
||||||
("Total chats", count_value(stats.total_threads)),
|
|
||||||
];
|
|
||||||
let two_columns = inner_width >= 76;
|
|
||||||
let column_width = if two_columns {
|
|
||||||
(inner_width - 4) / 2
|
|
||||||
} else {
|
|
||||||
inner_width
|
|
||||||
};
|
|
||||||
let mut insights = vec!["Activity insights".bold().into(), Line::default()];
|
|
||||||
for (label, value) in metrics {
|
|
||||||
insights.extend(word_wrap_lines(
|
|
||||||
[columns(
|
|
||||||
label.set_style(secondary_style()).into(),
|
|
||||||
value.into(),
|
|
||||||
column_width,
|
|
||||||
)],
|
|
||||||
RtOptions::new(column_width),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let mut plugins = vec![
|
|
||||||
"Most used plugins and skills".bold().into(),
|
|
||||||
Line::default(),
|
|
||||||
];
|
|
||||||
if let Some(invocations) = &stats.top_invocations {
|
|
||||||
let mut displayed = 0;
|
|
||||||
for invocation in invocations {
|
|
||||||
let (prefix, name) = match invocation.kind {
|
|
||||||
ProfileInvocationKind::Plugin => ("@", invocation.plugin_name.as_deref()),
|
|
||||||
ProfileInvocationKind::Skill => ("$", invocation.skill_name.as_deref()),
|
|
||||||
ProfileInvocationKind::Unknown => continue,
|
|
||||||
};
|
|
||||||
let Some(name) = name.filter(|name| !name.trim().is_empty()) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let value = invocation
|
|
||||||
.usage_count
|
|
||||||
.map(|count| {
|
|
||||||
format!(
|
|
||||||
"{} {}",
|
|
||||||
count_value(Some(count)),
|
|
||||||
if count == 1 { "run" } else { "runs" }
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|| "—".into());
|
|
||||||
plugins.extend(word_wrap_lines(
|
|
||||||
[columns(
|
|
||||||
truncate(
|
|
||||||
format!("{prefix}{}", name.trim()).into(),
|
|
||||||
column_width.saturating_sub(value.len() + 1),
|
|
||||||
),
|
|
||||||
value.set_style(secondary_style()).into(),
|
|
||||||
column_width,
|
|
||||||
)],
|
|
||||||
RtOptions::new(column_width),
|
|
||||||
));
|
|
||||||
displayed += 1;
|
|
||||||
if displayed == 5 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if displayed == 0 {
|
|
||||||
plugins.push(
|
|
||||||
"No reported plugins or skills."
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
plugins.push(
|
|
||||||
"Plugin and skill usage unavailable."
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if two_columns {
|
|
||||||
lines.extend(join_columns(&insights, &plugins, column_width));
|
|
||||||
} else {
|
|
||||||
lines.extend(insights);
|
|
||||||
lines.push(Line::default());
|
|
||||||
lines.extend(plugins);
|
|
||||||
}
|
|
||||||
if let Some(metadata) = &profile.metadata {
|
|
||||||
lines.push(Line::default());
|
|
||||||
if let Some(date) = metadata
|
|
||||||
.stats_as_of
|
|
||||||
.as_deref()
|
|
||||||
.and_then(|date| chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok())
|
|
||||||
{
|
|
||||||
lines.push(
|
|
||||||
format!("Statistics as of {}", date.format("%b %-d, %Y"))
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if metadata
|
|
||||||
.stats_error
|
|
||||||
.as_deref()
|
|
||||||
.is_some_and(|error| !error.trim().is_empty())
|
|
||||||
{
|
|
||||||
lines.push(
|
|
||||||
"Some profile statistics are unavailable."
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let padding = " ".repeat(width.saturating_sub(inner_width) / 2);
|
|
||||||
word_wrap_lines(lines, RtOptions::new(inner_width))
|
|
||||||
.into_iter()
|
|
||||||
.map(|mut line| {
|
|
||||||
line.spans.insert(/*index*/ 0, padding.clone().into());
|
|
||||||
line
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn center(mut line: Line<'static>, width: usize) -> Line<'static> {
|
|
||||||
line.spans.insert(
|
|
||||||
/*index*/ 0,
|
|
||||||
" ".repeat(width.saturating_sub(line.width()) / 2).into(),
|
|
||||||
);
|
|
||||||
line
|
|
||||||
}
|
|
||||||
|
|
||||||
fn percent(value: Option<&serde_json::Number>) -> String {
|
|
||||||
value
|
|
||||||
.and_then(serde_json::Number::as_f64)
|
|
||||||
.filter(|value| value.is_finite() && (0.0..=100.0).contains(value))
|
|
||||||
.map(|value| format!("{value:.0}%"))
|
|
||||||
.unwrap_or_else(|| "—".into())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn count_value(value: Option<u64>) -> String {
|
|
||||||
let Some(value) = value else {
|
|
||||||
return "—".into();
|
|
||||||
};
|
|
||||||
let digits = value.to_string();
|
|
||||||
digits
|
|
||||||
.chars()
|
|
||||||
.enumerate()
|
|
||||||
.fold(String::new(), |mut result, (index, ch)| {
|
|
||||||
if index > 0 && (digits.len() - index).is_multiple_of(/*rhs*/ 3) {
|
|
||||||
result.push(',');
|
|
||||||
}
|
|
||||||
result.push(ch);
|
|
||||||
result
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn duration(seconds: i64) -> String {
|
|
||||||
let seconds = seconds.max(/*other*/ 0);
|
|
||||||
let (hours, minutes) = (seconds / 3600, seconds % 3600 / 60);
|
|
||||||
match (hours, minutes) {
|
|
||||||
(0, 0) => format!("{seconds}s"),
|
|
||||||
(0, minutes) => format!("{minutes}m"),
|
|
||||||
(hours, 0) => format!("{hours}h"),
|
|
||||||
(hours, minutes) => format!("{hours}h {minutes}m"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
//! Summary reflow, aggregation selection, and independently unavailable profile sections.
|
|
||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
fn profile() -> codex_backend_client::AccountProfile {
|
|
||||||
serde_json::from_value(json!({
|
|
||||||
"profile":{"display_name":"Example User","username":"example.user"},
|
|
||||||
"metadata":{"stats_as_of":"2026-09-09"},
|
|
||||||
"stats":{"lifetime_tokens":142_300_000_000_i64,"peak_daily_tokens":7_000_000_000_i64,
|
|
||||||
"longest_running_turn_sec":158820,"current_streak_days":158,"longest_streak_days":160,
|
|
||||||
"daily_usage_buckets":[{"start_date":"2026-09-08","tokens":100},{"start_date":"2026-09-09","tokens":200}],
|
|
||||||
"fast_mode_usage_percentage":37.0,"most_used_reasoning_effort":"high","most_used_reasoning_effort_percentage":26.0,
|
|
||||||
"unique_skills_used":147,"total_skills_used":13190,"total_threads":21482,
|
|
||||||
"top_invocations":[{"type":"skill","skill_name":"review","usage_count":1142},{"type":"plugin","plugin_name":"GitHub","usage_count":1059},{"type":"future"}]}
|
|
||||||
})).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn summary_modes_reflow_and_keep_selection_across_tabs() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
view.profile = Load::Ready(profile());
|
|
||||||
view.end_date = "2026-09-09".parse().unwrap();
|
|
||||||
view.select_summary(Some(crate::analytics::TokenActivityView::Daily));
|
|
||||||
insta::assert_snapshot!(
|
|
||||||
"summary_daily_wide",
|
|
||||||
screen(&mut view, /*width*/ 140, /*height*/ 44)
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Char('g'));
|
|
||||||
assert_eq!(view.sections[Section::Summary].group, 1);
|
|
||||||
assert!(view.profile.ready().is_some());
|
|
||||||
press(&mut view, KeyCode::Tab);
|
|
||||||
press(&mut view, KeyCode::BackTab);
|
|
||||||
assert_eq!(view.sections[Section::Summary].group, 1);
|
|
||||||
press(&mut view, KeyCode::Char('g'));
|
|
||||||
insta::assert_snapshot!(
|
|
||||||
"summary_cumulative_narrow",
|
|
||||||
screen(&mut view, /*width*/ 64, /*height*/ 60)
|
|
||||||
);
|
|
||||||
for width in [1, 4, 28, 64] {
|
|
||||||
let lines = view.summary_lines(width);
|
|
||||||
assert!(lines.iter().all(|line| line.width() <= width));
|
|
||||||
}
|
|
||||||
screen(&mut view, /*width*/ 64, /*height*/ 18);
|
|
||||||
press(&mut view, KeyCode::End);
|
|
||||||
screen(&mut view, /*width*/ 64, /*height*/ 18);
|
|
||||||
assert!(view.scroll_offset() > 0);
|
|
||||||
press(&mut view, KeyCode::Home);
|
|
||||||
assert_eq!(view.scroll_offset(), 0);
|
|
||||||
press(&mut view, KeyCode::Esc);
|
|
||||||
assert!(view.is_done);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn partial_summary_keeps_missing_values_and_zero() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Business);
|
|
||||||
view.select_summary(/*view*/ None);
|
|
||||||
view.profile = Load::Ready(serde_json::from_value(json!({
|
|
||||||
"metadata":{"stats_error":"sensitive upstream error"},
|
|
||||||
"stats":{"lifetime_tokens":0,"fast_mode_usage_percentage":0,"total_threads":0,"top_invocations":[]}
|
|
||||||
})).unwrap());
|
|
||||||
let rendered = screen(&mut view, /*width*/ 100, /*height*/ 40);
|
|
||||||
assert!(!rendered.contains("sensitive upstream error"));
|
|
||||||
insta::assert_snapshot!("summary_partial", rendered);
|
|
||||||
view.refresh();
|
|
||||||
assert!(view.profile.ready().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn summary_loads_once_per_open_and_does_not_block_other_reports() {
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::header;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
let server = test_support::server().await;
|
|
||||||
let requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(/*v*/ 0));
|
|
||||||
let count = std::sync::Arc::clone(&requests);
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/backend-api/wham/profiles/me"))
|
|
||||||
.and(header("chatgpt-account-id", "account-a"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
if count.fetch_add(/*val*/ 1, std::sync::atomic::Ordering::SeqCst) == 0 {
|
|
||||||
ResponseTemplate::new(/*s*/ 503)
|
|
||||||
} else {
|
|
||||||
ResponseTemplate::new(/*s*/ 200)
|
|
||||||
.set_body_json(json!({"stats":{"lifetime_tokens":123}}))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 2)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let (_home, _app_server, mut view) = client::tests::connected_view(&server, "plus").await;
|
|
||||||
test_support::settle(&mut view).await;
|
|
||||||
assert_eq!(view.section, Section::Summary);
|
|
||||||
assert!(matches!(view.profile, Load::Error(_)));
|
|
||||||
assert!(view.sections[Section::Usage].history.ready().is_some());
|
|
||||||
press(&mut view, KeyCode::Char('g'));
|
|
||||||
press(&mut view, KeyCode::Tab);
|
|
||||||
test_support::settle(&mut view).await;
|
|
||||||
assert!(view.sections[Section::Usage].history.ready().is_some());
|
|
||||||
press(&mut view, KeyCode::BackTab);
|
|
||||||
test_support::settle(&mut view).await;
|
|
||||||
assert_eq!(requests.load(std::sync::atomic::Ordering::SeqCst), 1);
|
|
||||||
let (config, handle, frame) = view.connection.as_ref().unwrap().clone();
|
|
||||||
view.cancel_loads();
|
|
||||||
view.open(handle, frame, Vec::new(), config);
|
|
||||||
test_support::settle(&mut view).await;
|
|
||||||
assert_eq!(
|
|
||||||
view.profile.ready().unwrap().stats.tokens.lifetime_tokens,
|
|
||||||
Some(123)
|
|
||||||
);
|
|
||||||
assert_eq!(view.sections[Section::Summary].group, 1);
|
|
||||||
view.cancel_loads();
|
|
||||||
assert!(matches!(view.profile, Load::Unavailable));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn closing_summary_aborts_its_pending_profile() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
let (cancelled_tx, cancelled_rx) = tokio::sync::oneshot::channel::<()>();
|
|
||||||
view.profile = Load::start(
|
|
||||||
async move {
|
|
||||||
let _cancelled = cancelled_tx;
|
|
||||||
std::future::pending().await
|
|
||||||
},
|
|
||||||
crate::tui::FrameRequester::test_dummy(),
|
|
||||||
);
|
|
||||||
view.cancel_loads();
|
|
||||||
assert!(cancelled_rx.await.is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn summary_scroll_hints_follow_overflow_and_grouping_wraps() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
view.profile = Load::Ready(profile());
|
|
||||||
view.select_summary(Some(crate::analytics::TokenActivityView::Daily));
|
|
||||||
assert!(!screen(&mut view, /*width*/ 140, /*height*/ 60).contains("scroll"));
|
|
||||||
assert!(screen(&mut view, /*width*/ 80, /*height*/ 18).contains("scroll"));
|
|
||||||
let mut groups = Vec::new();
|
|
||||||
for _ in 0..4 {
|
|
||||||
groups.push(view.sections[Section::Summary].group);
|
|
||||||
press(&mut view, KeyCode::Char('g'));
|
|
||||||
}
|
|
||||||
assert_eq!(groups, vec![0, 1, 2, 0]);
|
|
||||||
assert!(!screen(&mut view, /*width*/ 140, /*height*/ 60).contains("scroll"));
|
|
||||||
}
|
|
||||||
@@ -1,399 +0,0 @@
|
|||||||
//! Consumer chat metrics retain actual balance debits, current-limit comparisons, and partial states.
|
|
||||||
|
|
||||||
use super::AnalyticsView;
|
|
||||||
use super::render::columns;
|
|
||||||
use super::sections::Section;
|
|
||||||
use super::styles::number;
|
|
||||||
use super::styles::secondary_style;
|
|
||||||
use super::tasks::Chat;
|
|
||||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow as truncate;
|
|
||||||
use crate::style::accent_style;
|
|
||||||
use crate::wrapping::RtOptions;
|
|
||||||
use crate::wrapping::word_wrap_lines;
|
|
||||||
use codex_backend_client::TaskUsageAmounts;
|
|
||||||
use codex_backend_client::TaskUsageStatus;
|
|
||||||
use ratatui::style::Styled;
|
|
||||||
use ratatui::style::Stylize;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
use std::cmp::Ordering;
|
|
||||||
use std::ops::Range;
|
|
||||||
|
|
||||||
pub(super) const METRICS: [&str; 3] = ["Weekly %", "5-hour %", "Balance credits"];
|
|
||||||
|
|
||||||
fn compare(a: Option<&TaskUsageAmounts>, b: Option<&TaskUsageAmounts>, metric: usize) -> Ordering {
|
|
||||||
if metric == 2 {
|
|
||||||
a.and_then(|a| a.balance_usage_credits.as_ref())
|
|
||||||
.cmp(&b.and_then(|b| b.balance_usage_credits.as_ref()))
|
|
||||||
} else {
|
|
||||||
let value = |amounts: &TaskUsageAmounts| {
|
|
||||||
if metric == 0 {
|
|
||||||
amounts.weekly_limit_percent
|
|
||||||
} else {
|
|
||||||
amounts.five_hour_limit_percent
|
|
||||||
}
|
|
||||||
};
|
|
||||||
a.and_then(value)
|
|
||||||
.partial_cmp(&b.and_then(value))
|
|
||||||
.unwrap_or(Ordering::Equal)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn amount(amounts: Option<&TaskUsageAmounts>, metric: usize) -> String {
|
|
||||||
let Some(amounts) = amounts else {
|
|
||||||
return "—".into();
|
|
||||||
};
|
|
||||||
if metric == 2 {
|
|
||||||
amounts
|
|
||||||
.balance_usage_credits
|
|
||||||
.as_ref()
|
|
||||||
.map(|amount| {
|
|
||||||
let value = amount.as_str();
|
|
||||||
let (mantissa, exponent) = value.split_once(['e', 'E']).unwrap_or((value, "0"));
|
|
||||||
let fraction = mantissa
|
|
||||||
.split_once('.')
|
|
||||||
.map_or("", |(_, fraction)| fraction);
|
|
||||||
let digits = mantissa.trim_start_matches(['+', '-']).replace('.', "");
|
|
||||||
let digits = digits.trim_start_matches('0');
|
|
||||||
if digits.is_empty() {
|
|
||||||
return "0.00".to_string();
|
|
||||||
}
|
|
||||||
let cent_digits = digits.len() as i64
|
|
||||||
+ exponent.parse::<i32>().unwrap_or_default() as i64
|
|
||||||
- fraction.len() as i64
|
|
||||||
+ 2;
|
|
||||||
// Retain tiny adjustments and bound the integer conversion before padding.
|
|
||||||
if !(1..=18).contains(¢_digits) {
|
|
||||||
return value.to_string();
|
|
||||||
}
|
|
||||||
let mut cents = digits
|
|
||||||
.bytes()
|
|
||||||
.chain(std::iter::repeat(b'0'))
|
|
||||||
.take(cent_digits as usize)
|
|
||||||
.fold(
|
|
||||||
/*init*/ 0_i64,
|
|
||||||
|cents, digit| cents * 10 + i64::from(digit - b'0'),
|
|
||||||
);
|
|
||||||
if digits
|
|
||||||
.as_bytes()
|
|
||||||
.get(cent_digits as usize)
|
|
||||||
.is_some_and(|digit| *digit >= b'5')
|
|
||||||
{
|
|
||||||
cents += 1;
|
|
||||||
}
|
|
||||||
cents
|
|
||||||
.checked_mul(/*rhs*/ 10_000)
|
|
||||||
.map(|micros| {
|
|
||||||
super::data::credits(if mantissa.starts_with('-') {
|
|
||||||
-micros
|
|
||||||
} else {
|
|
||||||
micros
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|| value.to_string())
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|| "—".into())
|
|
||||||
} else {
|
|
||||||
(if metric == 0 {
|
|
||||||
amounts.weekly_limit_percent
|
|
||||||
} else {
|
|
||||||
amounts.five_hour_limit_percent
|
|
||||||
})
|
|
||||||
.map(|value| format!("{value:.1}%"))
|
|
||||||
.unwrap_or_else(|| "—".into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn available(chat: &Chat) -> Option<&TaskUsageAmounts> {
|
|
||||||
chat.task
|
|
||||||
.as_ref()
|
|
||||||
.filter(|task| task.data_status != TaskUsageStatus::Unavailable)
|
|
||||||
.map(|task| &task.amounts)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnalyticsView {
|
|
||||||
pub(super) fn task_metrics(&self) -> Vec<usize> {
|
|
||||||
(0..3)
|
|
||||||
.filter(|metric| {
|
|
||||||
*metric == 2
|
|
||||||
|| self.tasks.ready().is_some_and(|chats| {
|
|
||||||
chats.rows.iter().any(|chat| {
|
|
||||||
available(chat).is_some_and(|amounts| {
|
|
||||||
if *metric == 0 {
|
|
||||||
amounts.weekly_limit_percent.is_some()
|
|
||||||
} else {
|
|
||||||
amounts.five_hour_limit_percent.is_some()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn task_metric(&self) -> usize {
|
|
||||||
let metrics = self.task_metrics();
|
|
||||||
if metrics.contains(&self.chat_metric) {
|
|
||||||
self.chat_metric
|
|
||||||
} else {
|
|
||||||
metrics[0]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn task_rows(&self) -> Vec<&Chat> {
|
|
||||||
let mut rows = self
|
|
||||||
.tasks
|
|
||||||
.ready()
|
|
||||||
.map(|chats| chats.rows.iter().collect::<Vec<_>>())
|
|
||||||
.unwrap_or_default();
|
|
||||||
rows.sort_by(|a, b| compare(available(b), available(a), self.task_metric()));
|
|
||||||
rows
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn task_lines(&self, width: usize) -> (Vec<Line<'static>>, Range<usize>) {
|
|
||||||
let row_width = width.clamp(/*min*/ 1, /*max*/ 111);
|
|
||||||
let width = row_width.saturating_sub(/*rhs*/ 1).max(/*other*/ 1);
|
|
||||||
let wrap = |lines| word_wrap_lines(lines, RtOptions::new(width));
|
|
||||||
let Some(chats) = self.tasks.ready() else {
|
|
||||||
return (
|
|
||||||
wrap(vec![
|
|
||||||
self.tasks
|
|
||||||
.message()
|
|
||||||
.unwrap_or("No task usage reported.")
|
|
||||||
.to_string()
|
|
||||||
.into(),
|
|
||||||
]),
|
|
||||||
0..1,
|
|
||||||
);
|
|
||||||
};
|
|
||||||
let metric = self.task_metric();
|
|
||||||
let mut lines = wrap(vec![
|
|
||||||
format!(
|
|
||||||
"Usage estimates · active in past 30 days · sorted by {}",
|
|
||||||
METRICS[metric]
|
|
||||||
)
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
if metric == 2 {
|
|
||||||
"Credits debited from balance · includes adjustments"
|
|
||||||
} else {
|
|
||||||
"Recorded usage / current full limit · may exceed 100%"
|
|
||||||
}
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
]);
|
|
||||||
if chats.rows.is_empty() {
|
|
||||||
lines.push("No recent local chats.".into());
|
|
||||||
return (lines, 0..1);
|
|
||||||
}
|
|
||||||
let missing = chats
|
|
||||||
.rows
|
|
||||||
.iter()
|
|
||||||
.filter(|chat| amount(available(chat), metric) == "—")
|
|
||||||
.count();
|
|
||||||
let partial = chats
|
|
||||||
.rows
|
|
||||||
.iter()
|
|
||||||
.filter(|chat| {
|
|
||||||
chat.task
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|task| task.data_status == TaskUsageStatus::Partial)
|
|
||||||
})
|
|
||||||
.count();
|
|
||||||
if missing + partial > 0 {
|
|
||||||
lines.extend(wrap(vec![
|
|
||||||
format!("Partial ranking · {partial} partial · {missing} unavailable")
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
]));
|
|
||||||
}
|
|
||||||
let metrics = self.task_metrics();
|
|
||||||
let widths = metrics
|
|
||||||
.iter()
|
|
||||||
.map(|index| {
|
|
||||||
chats
|
|
||||||
.rows
|
|
||||||
.iter()
|
|
||||||
.map(|chat| amount(available(chat), *index).len())
|
|
||||||
.max()
|
|
||||||
.unwrap_or_default()
|
|
||||||
.max(METRICS[*index].len())
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let show_all = widths.iter().sum::<usize>() + widths.len() * 2 + 24 <= width;
|
|
||||||
let metric_text = |chat: Option<&Chat>| {
|
|
||||||
if !show_all {
|
|
||||||
return chat.map_or_else(
|
|
||||||
|| METRICS[metric].to_string(),
|
|
||||||
|chat| amount(available(chat), metric),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
metrics
|
|
||||||
.iter()
|
|
||||||
.zip(&widths)
|
|
||||||
.map(|(index, column_width)| {
|
|
||||||
let value = chat.map_or_else(
|
|
||||||
|| METRICS[*index].to_string(),
|
|
||||||
|chat| amount(available(chat), *index),
|
|
||||||
);
|
|
||||||
format!("{value:>column_width$}")
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(" ")
|
|
||||||
};
|
|
||||||
lines.push(Line::default());
|
|
||||||
lines.push(columns(
|
|
||||||
" Chat".bold().into(),
|
|
||||||
metric_text(/*chat*/ None).bold().into(),
|
|
||||||
width,
|
|
||||||
));
|
|
||||||
let rows = self
|
|
||||||
.task_rows()
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(index, chat)| {
|
|
||||||
let selected =
|
|
||||||
self.section == Section::Chats && index == self.sections[Section::Chats].cursor;
|
|
||||||
let value = metric_text(Some(chat));
|
|
||||||
let status = if chat
|
|
||||||
.task
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|task| task.data_status == TaskUsageStatus::Partial)
|
|
||||||
{
|
|
||||||
" · partial"
|
|
||||||
} else {
|
|
||||||
""
|
|
||||||
};
|
|
||||||
let label = format!(
|
|
||||||
"{} {}{status}",
|
|
||||||
if selected { "›" } else { " " },
|
|
||||||
chat.display_title()
|
|
||||||
);
|
|
||||||
let label: Line<'static> = if selected {
|
|
||||||
label.set_style(accent_style()).into()
|
|
||||||
} else {
|
|
||||||
label.into()
|
|
||||||
};
|
|
||||||
let mut row = vec![columns(
|
|
||||||
truncate(label, width.saturating_sub(value.len() + 1)),
|
|
||||||
if value == "—" {
|
|
||||||
value.set_style(secondary_style()).into()
|
|
||||||
} else if selected {
|
|
||||||
number(value).into()
|
|
||||||
} else {
|
|
||||||
value.into()
|
|
||||||
},
|
|
||||||
width,
|
|
||||||
)];
|
|
||||||
let header_len = row.len();
|
|
||||||
if self.zoomed && self.sections[Section::Chats].detail == Some(index) {
|
|
||||||
row.push("─".repeat(width).dim().into());
|
|
||||||
row.extend(word_wrap_lines(
|
|
||||||
[chat.display_title().to_owned().bold()],
|
|
||||||
RtOptions::new(width)
|
|
||||||
.initial_indent(" ".into())
|
|
||||||
.subsequent_indent(" ".into()),
|
|
||||||
));
|
|
||||||
for index in self.task_metrics() {
|
|
||||||
let label = METRICS[index];
|
|
||||||
row.push(columns(
|
|
||||||
format!(" {label}").into(),
|
|
||||||
amount(available(chat), index).into(),
|
|
||||||
width,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if let Some(task) = &chat.task {
|
|
||||||
if task.data_status != TaskUsageStatus::Unavailable
|
|
||||||
&& !task.groups.is_empty()
|
|
||||||
{
|
|
||||||
let mut groups = task.groups.iter().collect::<Vec<_>>();
|
|
||||||
groups.sort_by(|a, b| {
|
|
||||||
compare(Some(&b.amounts), Some(&a.amounts), metric)
|
|
||||||
});
|
|
||||||
row.push(Line::default());
|
|
||||||
row.push(columns(
|
|
||||||
" Model / effort / speed".bold().into(),
|
|
||||||
METRICS[metric].bold().into(),
|
|
||||||
width,
|
|
||||||
));
|
|
||||||
for group in groups {
|
|
||||||
let model = self
|
|
||||||
.model_name(group.model.as_deref().unwrap_or("Not reported"));
|
|
||||||
let value = amount(Some(&group.amounts), metric);
|
|
||||||
row.push(columns(
|
|
||||||
truncate(
|
|
||||||
format!(" {model}").bold().into(),
|
|
||||||
width.saturating_sub(value.len() + 1),
|
|
||||||
),
|
|
||||||
value.into(),
|
|
||||||
width,
|
|
||||||
));
|
|
||||||
row.push(
|
|
||||||
format!(
|
|
||||||
" {} · {} · {}",
|
|
||||||
group.reasoning_effort.as_deref().unwrap_or("Not reported"),
|
|
||||||
group.speed.as_deref().unwrap_or("Not reported"),
|
|
||||||
group
|
|
||||||
.product_experience
|
|
||||||
.as_deref()
|
|
||||||
.unwrap_or("Not reported")
|
|
||||||
)
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
row.push(
|
|
||||||
" Task usage unavailable."
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
row.push(Line::default());
|
|
||||||
}
|
|
||||||
let details = row.split_off(header_len);
|
|
||||||
let mut row = wrap(row);
|
|
||||||
// Wrap first: wrapping trims the highlighted trailing blank otherwise.
|
|
||||||
if selected {
|
|
||||||
for line in &mut row {
|
|
||||||
super::styles::select_row(line, row_width);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
row.extend(wrap(details));
|
|
||||||
row
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let mut coverage = vec![
|
|
||||||
"Local chats · includes discovered descendants · excludes archived roots"
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
];
|
|
||||||
if chats.truncated {
|
|
||||||
coverage.push(
|
|
||||||
"Partial ranking · 100 most recently active chats"
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if let Some(time) = chats.updated_at {
|
|
||||||
coverage.push(
|
|
||||||
format!(
|
|
||||||
"Updated {} UTC · recent activity may be delayed",
|
|
||||||
time.format(self.clock_format.date_time_format())
|
|
||||||
)
|
|
||||||
.set_style(secondary_style())
|
|
||||||
.into(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if !self.zoomed {
|
|
||||||
let count = rows.len();
|
|
||||||
lines.extend(rows.into_iter().take(/*n*/ 5).flatten());
|
|
||||||
lines.push(Line::default());
|
|
||||||
lines.push(format!("Showing top {} of {count} chats", count.min(/*other*/ 5)).into());
|
|
||||||
lines.extend(wrap(coverage));
|
|
||||||
(lines, 0..1)
|
|
||||||
} else {
|
|
||||||
self.chat_window(lines, rows, wrap(coverage), width)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,248 +0,0 @@
|
|||||||
//! Consumer task queries preserve missing amounts and require complete descendant groups.
|
|
||||||
use super::client::Live;
|
|
||||||
use codex_app_server_client::AppServerRequestHandle;
|
|
||||||
use codex_app_server_protocol::ClientRequest;
|
|
||||||
use codex_app_server_protocol::RequestId;
|
|
||||||
use codex_app_server_protocol::Thread;
|
|
||||||
use codex_app_server_protocol::ThreadListParams;
|
|
||||||
use codex_app_server_protocol::ThreadListResponse;
|
|
||||||
use codex_backend_client::TaskUsage;
|
|
||||||
use codex_backend_client::TaskUsageThread;
|
|
||||||
use futures::StreamExt;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::collections::HashSet;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
pub(super) struct Chat {
|
|
||||||
pub title: String,
|
|
||||||
pub task: Option<TaskUsage>,
|
|
||||||
}
|
|
||||||
impl Chat {
|
|
||||||
/// Local history can span accounts; unavailable task data does not verify ownership.
|
|
||||||
pub(super) fn display_title(&self) -> &str {
|
|
||||||
if self.task.as_ref().is_some_and(|task| {
|
|
||||||
task.data_status != codex_backend_client::TaskUsageStatus::Unavailable
|
|
||||||
}) {
|
|
||||||
&self.title
|
|
||||||
} else {
|
|
||||||
"Chat usage unavailable"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(super) struct Chats {
|
|
||||||
pub rows: Vec<Chat>,
|
|
||||||
pub truncated: bool,
|
|
||||||
pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn read(
|
|
||||||
handle: AppServerRequestHandle,
|
|
||||||
live: Arc<Live>,
|
|
||||||
) -> Result<Option<Chats>, String> {
|
|
||||||
let session = live.session().await?;
|
|
||||||
if session.kind != super::models::AccountKind::Consumer {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
live.ensure_identity().await?;
|
|
||||||
let roots = tokio::time::timeout(
|
|
||||||
std::time::Duration::from_secs(/*secs*/ 60),
|
|
||||||
super::chats::roots(&handle),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(|_| "Chat listing timed out. Press R to retry.".to_string());
|
|
||||||
live.ensure_identity().await?;
|
|
||||||
let mut roots = roots??;
|
|
||||||
roots.sort_by(|a, b| {
|
|
||||||
b.updated_at
|
|
||||||
.cmp(&a.updated_at)
|
|
||||||
.then_with(|| a.id.cmp(&b.id))
|
|
||||||
});
|
|
||||||
let truncated = roots.len() > 100;
|
|
||||||
roots.truncate(/*len*/ 100);
|
|
||||||
let discoveries = roots
|
|
||||||
.iter()
|
|
||||||
.map(|root| descendants(&handle, root))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let mut pending = futures::stream::iter(discoveries).buffer_unordered(/*n*/ 2);
|
|
||||||
let mut queries = Vec::new();
|
|
||||||
// Keep complete groups collected before the deadline; never query partial descendants.
|
|
||||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(/*secs*/ 25);
|
|
||||||
while let Ok(Some(result)) = tokio::time::timeout_at(deadline, pending.next()).await {
|
|
||||||
if let Ok(query) = result {
|
|
||||||
queries.push(query);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
drop(pending);
|
|
||||||
live.ensure_identity().await?;
|
|
||||||
let mut seen = HashSet::new();
|
|
||||||
let mut batches = Vec::new();
|
|
||||||
let mut batch = Vec::new();
|
|
||||||
let mut count = 0;
|
|
||||||
for query in queries {
|
|
||||||
let ids = std::iter::once(&query.thread_id).chain(&query.descendant_thread_ids);
|
|
||||||
if ids.clone().any(|id| !seen.insert(id.clone())) {
|
|
||||||
return Err("Task descendant groups overlap.".into());
|
|
||||||
}
|
|
||||||
let size = 1 + query.descendant_thread_ids.len();
|
|
||||||
if count + size > 1_000 || batch.len() == 100 {
|
|
||||||
batches.push(std::mem::take(&mut batch));
|
|
||||||
count = 0;
|
|
||||||
}
|
|
||||||
count += size;
|
|
||||||
batch.push(query);
|
|
||||||
}
|
|
||||||
if !batch.is_empty() {
|
|
||||||
batches.push(batch);
|
|
||||||
}
|
|
||||||
let requests = batches
|
|
||||||
.into_iter()
|
|
||||||
.map(|threads| async move {
|
|
||||||
session
|
|
||||||
.backend
|
|
||||||
.request(|client| {
|
|
||||||
let threads = threads.clone();
|
|
||||||
async move { client.get_task_usage(&threads).await }
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let expected_batches = requests.len();
|
|
||||||
let mut completed_batches = 0;
|
|
||||||
let mut pending = futures::stream::iter(requests).buffer_unordered(/*n*/ 2);
|
|
||||||
let mut usage = HashMap::new();
|
|
||||||
let mut freshness = Vec::new();
|
|
||||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(/*secs*/ 25);
|
|
||||||
while let Ok(Some(result)) = tokio::time::timeout_at(deadline, pending.next()).await {
|
|
||||||
completed_batches += 1;
|
|
||||||
live.ensure_identity().await?;
|
|
||||||
match result {
|
|
||||||
Ok(response) => {
|
|
||||||
freshness.push(
|
|
||||||
response
|
|
||||||
.data_as_of
|
|
||||||
.as_deref()
|
|
||||||
.map(chrono::DateTime::parse_from_rfc3339)
|
|
||||||
.transpose()
|
|
||||||
.map_err(|_| "Invalid task usage timestamp.")?
|
|
||||||
.map(|time| time.with_timezone(&chrono::Utc)),
|
|
||||||
);
|
|
||||||
usage.extend(
|
|
||||||
response
|
|
||||||
.threads
|
|
||||||
.into_iter()
|
|
||||||
.map(|task| (task.thread_id.clone(), task)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(error)
|
|
||||||
if error
|
|
||||||
.status()
|
|
||||||
.is_some_and(|status| matches!(status.as_u16(), 404 | 503)) =>
|
|
||||||
{
|
|
||||||
freshness.push(/*value*/ None);
|
|
||||||
}
|
|
||||||
Err(error) => return Err(super::client::request_error(error)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if completed_batches < expected_batches {
|
|
||||||
freshness.push(/*value*/ None);
|
|
||||||
}
|
|
||||||
drop(pending);
|
|
||||||
live.ensure_identity().await?;
|
|
||||||
Ok(Some(Chats {
|
|
||||||
truncated,
|
|
||||||
updated_at: if freshness.iter().all(Option::is_some) {
|
|
||||||
freshness.into_iter().flatten().min()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
},
|
|
||||||
rows: roots
|
|
||||||
.into_iter()
|
|
||||||
.map(|thread| Chat {
|
|
||||||
task: usage.remove(&thread.id),
|
|
||||||
title: thread
|
|
||||||
.name
|
|
||||||
.filter(|name| !name.trim().is_empty())
|
|
||||||
.unwrap_or_else(|| {
|
|
||||||
if thread.preview.trim().is_empty() {
|
|
||||||
"Untitled chat".into()
|
|
||||||
} else {
|
|
||||||
thread.preview
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn descendants(
|
|
||||||
handle: &AppServerRequestHandle,
|
|
||||||
root: &Thread,
|
|
||||||
) -> Result<TaskUsageThread, String> {
|
|
||||||
let mut ids = HashSet::new();
|
|
||||||
let mut parents = HashMap::new();
|
|
||||||
for archived in [false, true] {
|
|
||||||
let mut cursor = None;
|
|
||||||
let mut seen = HashSet::new();
|
|
||||||
loop {
|
|
||||||
let page: ThreadListResponse = handle
|
|
||||||
.request_typed(ClientRequest::ThreadList {
|
|
||||||
request_id: RequestId::String(uuid::Uuid::new_v4().to_string()),
|
|
||||||
params: ThreadListParams {
|
|
||||||
current_account_only: false,
|
|
||||||
ancestor_thread_id: Some(root.id.clone()),
|
|
||||||
archived: Some(archived),
|
|
||||||
cursor,
|
|
||||||
limit: Some(100),
|
|
||||||
..super::chats::list_params()
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(super::data::error)?;
|
|
||||||
for thread in page.data {
|
|
||||||
let parent = thread
|
|
||||||
.parent_thread_id
|
|
||||||
.filter(|_| thread.id != root.id)
|
|
||||||
.ok_or("Task descendant discovery is unsupported.")?;
|
|
||||||
parents.insert(thread.id.clone(), parent);
|
|
||||||
ids.insert(thread.id);
|
|
||||||
}
|
|
||||||
if ids.len() >= 1_000 {
|
|
||||||
return Err("Task exceeds the reporting limit.".into());
|
|
||||||
}
|
|
||||||
match page.next_cursor {
|
|
||||||
Some(next) if seen.insert(next.clone()) => cursor = Some(next),
|
|
||||||
Some(_) => return Err("Task listing repeated a cursor.".into()),
|
|
||||||
None => break,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Older servers can ignore the ancestor filter. Prove every returned chain reaches this root.
|
|
||||||
for id in &ids {
|
|
||||||
let mut current = id;
|
|
||||||
let mut chain = HashSet::new();
|
|
||||||
while current != &root.id {
|
|
||||||
if !chain.insert(current) {
|
|
||||||
return Err("Task descendant cycle.".into());
|
|
||||||
}
|
|
||||||
current = parents
|
|
||||||
.get(current)
|
|
||||||
.ok_or("Task descendant discovery is incomplete.")?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut descendant_thread_ids = ids.into_iter().collect::<Vec<_>>();
|
|
||||||
descendant_thread_ids.sort();
|
|
||||||
Ok(TaskUsageThread {
|
|
||||||
thread_id: root.id.clone(),
|
|
||||||
created_at: (root.created_at > 0)
|
|
||||||
.then(|| chrono::DateTime::from_timestamp(root.created_at, /*nsecs*/ 0))
|
|
||||||
.flatten()
|
|
||||||
.map(|time| time.to_rfc3339()),
|
|
||||||
descendant_thread_ids,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "tasks_tests.rs"]
|
|
||||||
mod tests;
|
|
||||||
@@ -1,156 +0,0 @@
|
|||||||
//! Consumer HTTP contract, descendant discovery, and partial-result regression coverage.
|
|
||||||
|
|
||||||
use super::super::client::tests::live;
|
|
||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::MockServer;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn consumer_roots_include_paginated_archived_descendants_and_keep_missing_usage() {
|
|
||||||
for (unsupported, status, switch_account) in [
|
|
||||||
(false, 200, false),
|
|
||||||
(true, 200, false),
|
|
||||||
(false, 404, false),
|
|
||||||
(false, 503, false),
|
|
||||||
(false, 200, true),
|
|
||||||
] {
|
|
||||||
use codex_app_server_client::RemoteAppServerClient;
|
|
||||||
use codex_app_server_client::RemoteAppServerConnectArgs;
|
|
||||||
use codex_app_server_client::RemoteAppServerEndpoint;
|
|
||||||
use futures::SinkExt;
|
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
|
||||||
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let (home, live) = live(&server, "plus").await;
|
|
||||||
let home_path = home.path().to_path_buf();
|
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
||||||
let websocket_url = format!("ws://{}", listener.local_addr().unwrap());
|
|
||||||
let rpc = tokio::spawn(async move {
|
|
||||||
let (stream, _) = listener.accept().await.unwrap();
|
|
||||||
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
|
|
||||||
let mut pages = 0;
|
|
||||||
while let Some(Ok(Message::Text(text))) = socket.next().await {
|
|
||||||
let request: serde_json::Value = serde_json::from_str(&text).unwrap();
|
|
||||||
let result = match request["method"].as_str() {
|
|
||||||
Some("initialize") => {
|
|
||||||
json!({"userAgent":"analytics-test", "codexHome":"/unused"})
|
|
||||||
}
|
|
||||||
Some("thread/list") => {
|
|
||||||
pages += 1;
|
|
||||||
if pages == 1 {
|
|
||||||
tokio::time::pause();
|
|
||||||
tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 31)).await;
|
|
||||||
tokio::time::resume();
|
|
||||||
}
|
|
||||||
let params = &request["params"];
|
|
||||||
assert_eq!(params["modelProviders"], json!([]));
|
|
||||||
assert_ne!(params["useStateDbOnly"], json!(true));
|
|
||||||
let ancestor = params["ancestorThreadId"].as_str();
|
|
||||||
let archived = params["archived"] == true;
|
|
||||||
let cursor = params["cursor"].as_str();
|
|
||||||
let ids = match (ancestor, archived, cursor) {
|
|
||||||
(None, false, None) => vec!["root", "missing"],
|
|
||||||
(Some("root"), false, None) if unsupported => vec!["unrelated"],
|
|
||||||
(Some("root"), false, None) => vec!["child"],
|
|
||||||
(Some("root"), false, Some("next")) => vec!["grandchild"],
|
|
||||||
(Some("root"), true, None) => vec!["archived-child"],
|
|
||||||
(Some("missing"), _, None) => Vec::new(),
|
|
||||||
_ => panic!("Unexpected thread listing: {params}"),
|
|
||||||
};
|
|
||||||
let data = ids.into_iter().map(|id| json!({
|
|
||||||
"id":id, "sessionId":id, "parentThreadId":if id == "unrelated" { None } else if id == "grandchild" { Some("child") } else { ancestor }, "preview":id, "ephemeral":false,
|
|
||||||
"modelProvider":"openai", "createdAt":1788220800_i64,
|
|
||||||
"updatedAt":chrono::Utc::now().timestamp(), "status":{"type":"idle"},
|
|
||||||
"cwd":std::env::temp_dir(), "cliVersion":"test", "source":"cli", "turns":[]
|
|
||||||
})).collect::<Vec<_>>();
|
|
||||||
json!({"data":data, "nextCursor":if ancestor == Some("root") && !archived && cursor.is_none() { Some("next") } else { None }})
|
|
||||||
}
|
|
||||||
_ => continue,
|
|
||||||
};
|
|
||||||
socket
|
|
||||||
.send(Message::Text(
|
|
||||||
json!({"jsonrpc":"2.0", "id":request["id"], "result":result})
|
|
||||||
.to_string()
|
|
||||||
.into(),
|
|
||||||
))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
if pages == if unsupported { 4 } else { 6 } {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pages
|
|
||||||
});
|
|
||||||
let remote = RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
|
|
||||||
required_human_approval: true,
|
|
||||||
endpoint: RemoteAppServerEndpoint::WebSocket {
|
|
||||||
websocket_url,
|
|
||||||
auth_token: None,
|
|
||||||
},
|
|
||||||
client_name: "analytics-test".into(),
|
|
||||||
client_version: "test".into(),
|
|
||||||
experimental_api: false,
|
|
||||||
mcp_server_openai_form_elicitation: false,
|
|
||||||
opt_out_notification_methods: Vec::new(),
|
|
||||||
channel_capacity: 16,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
Mock::given(method("POST")).and(path("/backend-api/wham/usage/thread_usage/query_v2"))
|
|
||||||
.respond_with(move |request:&wiremock::Request| {
|
|
||||||
let mut body:serde_json::Value = request.body_json().unwrap();
|
|
||||||
body["threads"].as_array_mut().unwrap().sort_by_key(|thread| thread["thread_id"].as_str().unwrap().to_string());
|
|
||||||
let mut expected=json!({"threads":[
|
|
||||||
{"thread_id":"missing", "created_at":"2026-09-01T00:00:00+00:00", "descendant_thread_ids":[]},
|
|
||||||
{"thread_id":"root", "created_at":"2026-09-01T00:00:00+00:00", "descendant_thread_ids":["archived-child", "child", "grandchild"]}
|
|
||||||
]});
|
|
||||||
if unsupported { expected["threads"].as_array_mut().unwrap().retain(|thread| thread["thread_id"] == "missing"); }
|
|
||||||
assert_eq!(body, expected);
|
|
||||||
if switch_account {
|
|
||||||
super::super::client::tests::sign_in(&home_path, "account-b", "user-b", "plus");
|
|
||||||
}
|
|
||||||
let mut response=json!({"data_as_of":null,"threads":[]});
|
|
||||||
if !unsupported { response["threads"] = json!([{ "thread_id":"root", "data_status":"partial", "usage_source":"included_plan", "weekly_limit_percent":125, "five_hour_limit_percent":null, "balance_usage_credits":null, "groups":[] }]); }
|
|
||||||
ResponseTemplate::new(status).set_body_json(response)
|
|
||||||
}).expect(/*r*/ 1).mount(&server).await;
|
|
||||||
let handle = AppServerRequestHandle::Remote(remote.request_handle());
|
|
||||||
let live = Arc::new(live);
|
|
||||||
let result = read(handle, Arc::clone(&live)).await;
|
|
||||||
assert_eq!(rpc.await.unwrap(), if unsupported { 4 } else { 6 });
|
|
||||||
if switch_account {
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
result.is_err(),
|
|
||||||
live.identity_invalidated
|
|
||||||
.load(std::sync::atomic::Ordering::Relaxed),
|
|
||||||
),
|
|
||||||
(true, true)
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let chats = result.unwrap().unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
chats.rows.len(),
|
|
||||||
chats
|
|
||||||
.rows
|
|
||||||
.iter()
|
|
||||||
.filter_map(|chat| chat.task.as_ref().map(|task| task.data_status))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
),
|
|
||||||
(
|
|
||||||
2,
|
|
||||||
if unsupported || status != 200 {
|
|
||||||
vec![]
|
|
||||||
} else {
|
|
||||||
vec![codex_backend_client::TaskUsageStatus::Partial]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,242 +0,0 @@
|
|||||||
//! Bounded fictional dashboard data with raw daily units.
|
|
||||||
//! Charts and their totals share the same daily series; no account activity is read.
|
|
||||||
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
pub(super) const END_DATE: chrono::NaiveDate =
|
|
||||||
match chrono::NaiveDate::from_ymd_opt(/*year*/ 2026, /*month*/ 9, /*day*/ 2) {
|
|
||||||
Some(date) => date,
|
|
||||||
None => panic!("invalid test date"),
|
|
||||||
};
|
|
||||||
|
|
||||||
pub(super) const TOOL_DAILY: [[u32; 7]; 2] = [[34, 23, 29, 26, 22, 23, 29], [8, 6, 9, 8, 7, 5, 11]];
|
|
||||||
|
|
||||||
pub(super) const GROUPS: &[(&str, [&str; 4], [u32; 4])] = &[
|
|
||||||
(
|
|
||||||
"Surface",
|
|
||||||
["Desktop app", "CLI", "IDE extension", "Web"],
|
|
||||||
[35, 36, 17, 12],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Feature",
|
|
||||||
["Tasks", "Code review", "Images", "Other"],
|
|
||||||
[65, 15, 12, 8],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Model",
|
|
||||||
["GPT-5.6-Sol", "GPT-5.6-Terra", "GPT-5.5", "Other"],
|
|
||||||
[60, 25, 10, 5],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Task start",
|
|
||||||
["User messages", "Goals", "Automations", "Other"],
|
|
||||||
[29, 10, 5, 5],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Speed",
|
|
||||||
["Standard", "Fast", "Priority", "Unknown"],
|
|
||||||
[65, 30, 5, 0],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Reasoning",
|
|
||||||
["Low", "Medium", "High", "Other"],
|
|
||||||
[10, 30, 50, 10],
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"Token type",
|
|
||||||
["Uncached input", "Cached input", "Output", "Other"],
|
|
||||||
[20, 70, 10, 0],
|
|
||||||
),
|
|
||||||
];
|
|
||||||
|
|
||||||
pub(super) fn daily(section: Section, range: usize) -> Vec<u32> {
|
|
||||||
let (earlier, recent) = match section {
|
|
||||||
Section::Usage => (40, [20, 73, 64, 91, 81, 100, 86]),
|
|
||||||
Section::Credits => (35, [0, 41, 57, 85, 75, 109, 64]),
|
|
||||||
Section::Activity => (34, [62, 83, 107, 75, 59, 85, 103]),
|
|
||||||
_ => return Vec::new(),
|
|
||||||
};
|
|
||||||
let mut values = vec![earlier; if range == 0 { 0 } else { 23 }];
|
|
||||||
values.extend(recent);
|
|
||||||
values
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn breakdown(total: u32, group: usize) -> [u32; 4] {
|
|
||||||
let mut values = GROUPS[group].2.map(|weight| total * weight / 100);
|
|
||||||
if group != 3 {
|
|
||||||
values[3] = total - values[..3].iter().sum::<u32>();
|
|
||||||
}
|
|
||||||
values
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fixtures use the private report types and the same presentation path as live reports.
|
|
||||||
pub(super) fn history(
|
|
||||||
report: usize,
|
|
||||||
range: usize,
|
|
||||||
group: usize,
|
|
||||||
) -> crate::analytics::models::AccountAnalyticsHistory {
|
|
||||||
use crate::analytics::models::AccountAnalyticsDay;
|
|
||||||
use crate::analytics::models::AccountAnalyticsHistory;
|
|
||||||
use crate::analytics::models::AccountAnalyticsUnit;
|
|
||||||
use crate::analytics::models::AccountAnalyticsValue;
|
|
||||||
let section = [
|
|
||||||
Section::Usage,
|
|
||||||
Section::Credits,
|
|
||||||
Section::Activity,
|
|
||||||
Section::Plugins,
|
|
||||||
Section::Skills,
|
|
||||||
][report];
|
|
||||||
let series = if report < 3 {
|
|
||||||
daily(section, range)
|
|
||||||
} else {
|
|
||||||
let mut series = vec![if report == 3 { 20 } else { 5 }; if range == 0 { 0 } else { 23 }];
|
|
||||||
series.extend(TOOL_DAILY[report - 3]);
|
|
||||||
series
|
|
||||||
};
|
|
||||||
let start = END_DATE - chrono::Days::new(if range == 0 { 6 } else { 29 });
|
|
||||||
AccountAnalyticsHistory {
|
|
||||||
unit: if report == 0 {
|
|
||||||
AccountAnalyticsUnit::RelativeUsage
|
|
||||||
} else if report == 1 {
|
|
||||||
AccountAnalyticsUnit::Credits
|
|
||||||
} else {
|
|
||||||
AccountAnalyticsUnit::Count
|
|
||||||
},
|
|
||||||
updated_at: None,
|
|
||||||
data: series
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(day, total)| {
|
|
||||||
let labels = if report < 3 {
|
|
||||||
GROUPS[group].1
|
|
||||||
} else if report == 3 {
|
|
||||||
["Figma", "Slack", "Notion", "GitHub"]
|
|
||||||
} else {
|
|
||||||
["Code review", "Planning", "Debugging", "Testing"]
|
|
||||||
};
|
|
||||||
let values = breakdown(total, if report < 3 { group } else { 0 });
|
|
||||||
let pairs = if report == 0 && group == 0 {
|
|
||||||
vec![
|
|
||||||
("Codex", total * 65 / 100),
|
|
||||||
("Work", total - total * 65 / 100),
|
|
||||||
]
|
|
||||||
} else {
|
|
||||||
labels.into_iter().zip(values).collect()
|
|
||||||
};
|
|
||||||
AccountAnalyticsDay {
|
|
||||||
date: start + chrono::Days::new(day as u64),
|
|
||||||
total: f64::from(total),
|
|
||||||
values: pairs
|
|
||||||
.into_iter()
|
|
||||||
.map(|(label, value)| AccountAnalyticsValue {
|
|
||||||
key: label.into(),
|
|
||||||
label: label.into(),
|
|
||||||
value: f64::from(value),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn chats() -> super::chats::Chats {
|
|
||||||
use codex_backend_client::ThreadUsage;
|
|
||||||
use codex_backend_client::ThreadUsageBreakdownGroup;
|
|
||||||
super::chats::Chats {
|
|
||||||
rows: [
|
|
||||||
("Q3 planning analysis", 120),
|
|
||||||
("Refactor billing usage", 113),
|
|
||||||
("Other usage", 109),
|
|
||||||
("Launch readiness review", 85),
|
|
||||||
("Plan the week", 0),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(index, (title, credits))| super::chats::Chat {
|
|
||||||
title: title.into(),
|
|
||||||
usage: Some(ThreadUsage {
|
|
||||||
thread_id: format!("test-{index}"),
|
|
||||||
estimated_usage_credits_micros: credits * 1_000_000,
|
|
||||||
estimated_usage_usd_micros: None,
|
|
||||||
native_usage_usd_micros: None,
|
|
||||||
groups: vec![ThreadUsageBreakdownGroup {
|
|
||||||
model: Some("GPT-5.6-Sol".into()),
|
|
||||||
reasoning_effort: Some("high".into()),
|
|
||||||
speed: Some("standard".into()),
|
|
||||||
estimated_usage_credits_micros: credits * 1_000_000,
|
|
||||||
native_usage_usd_micros: None,
|
|
||||||
net_new_input_tokens: None,
|
|
||||||
cached_input_tokens: None,
|
|
||||||
input_tokens: None,
|
|
||||||
output_tokens: None,
|
|
||||||
total_tokens: None,
|
|
||||||
}],
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn tokens(range: usize, grouping: usize) -> super::models::AccountAnalyticsHistory {
|
|
||||||
let response = serde_json::json!({"data_freshness_ts":"2026-09-02T16:00:00Z", "data":
|
|
||||||
daily(Section::Usage, range).into_iter().enumerate().map(|(index, total)| serde_json::json!({
|
|
||||||
"date": (END_DATE - chrono::Days::new(if range == 0 { 6 } else { 29 }) + chrono::Days::new(index as u64)).to_string(),
|
|
||||||
"groups": [{"dimensions":{"model":"GPT-5.5"}, "uncached_text_input_tokens": total * 1000, "cached_text_input_tokens":total * 7000, "text_output_tokens":total * 500}]
|
|
||||||
})).collect::<Vec<_>>()
|
|
||||||
});
|
|
||||||
match super::tokens::history(
|
|
||||||
match serde_json::from_value(response) {
|
|
||||||
Ok(response) => response,
|
|
||||||
Err(_) => panic!("invalid test token response"),
|
|
||||||
},
|
|
||||||
super::data::GROUPINGS[grouping],
|
|
||||||
END_DATE - chrono::Days::new(if range == 0 { 6 } else { 29 }),
|
|
||||||
END_DATE,
|
|
||||||
) {
|
|
||||||
Ok(history) => history,
|
|
||||||
Err(_) => panic!("invalid test token history"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build a fixed account state for rendering tests; never opens a connection.
|
|
||||||
pub(super) fn view(kind: super::models::AccountKind) -> super::AnalyticsView {
|
|
||||||
let mut view = super::AnalyticsView::new(crate::keymap::RuntimeKeymap::defaults().list);
|
|
||||||
view.end_date = END_DATE;
|
|
||||||
view.account = super::data::Load::Ready(match kind {
|
|
||||||
super::models::AccountKind::Consumer => codex_protocol::account::PlanType::Plus,
|
|
||||||
super::models::AccountKind::Business => codex_protocol::account::PlanType::Team,
|
|
||||||
super::models::AccountKind::Enterprise => {
|
|
||||||
codex_protocol::account::PlanType::EnterpriseCbpUsageBased
|
|
||||||
}
|
|
||||||
super::models::AccountKind::Unknown => codex_protocol::account::PlanType::Unknown,
|
|
||||||
});
|
|
||||||
view.section = if view.business() {
|
|
||||||
super::sections::Section::Credits
|
|
||||||
} else {
|
|
||||||
super::sections::Section::Usage
|
|
||||||
};
|
|
||||||
view.start_reports();
|
|
||||||
seed_reports(&mut view);
|
|
||||||
view
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Populate explicit report state after a test chooses its account, period, and grouping.
|
|
||||||
pub(super) fn seed_reports(view: &mut super::AnalyticsView) {
|
|
||||||
use super::data::Load;
|
|
||||||
view.clock_format = crate::clock_format::ClockFormat::TwentyFourHour;
|
|
||||||
if view.business() {
|
|
||||||
view.chats = Load::Ready(chats());
|
|
||||||
}
|
|
||||||
for section in view.visible_sections() {
|
|
||||||
if let Some(report) = section.report() {
|
|
||||||
let range = view.ranges[view.range_group(*section) as usize];
|
|
||||||
let group = view.sections[*section].group;
|
|
||||||
view.sections[*section].history =
|
|
||||||
Load::Ready(if *section == Section::Usage && view.business() {
|
|
||||||
tokens(range, group)
|
|
||||||
} else {
|
|
||||||
history(report as usize, range, group)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
//! Mock HTTP reports for tests that exercise the authenticated dashboard loading path.
|
|
||||||
use super::data::Load;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
pub(super) async fn server() -> wiremock::MockServer {
|
|
||||||
let server = wiremock::MockServer::start().await;
|
|
||||||
wiremock::Mock::given(wiremock::matchers::method("GET"))
|
|
||||||
.and(wiremock::matchers::path_regex("^/backend-api/wham/(usage|analytics)/"))
|
|
||||||
.respond_with(|request: &wiremock::Request| {
|
|
||||||
let params = request.url.query_pairs().collect::<std::collections::HashMap<_, _>>();
|
|
||||||
let today = chrono::Utc::now().date_naive();
|
|
||||||
let start = params.get("start_date").map_or(today, |date| date.parse().unwrap());
|
|
||||||
let end = params.get("end_date").map_or(today, |date| date.parse().unwrap());
|
|
||||||
let route = request.url.path().rsplit('/').next().unwrap();
|
|
||||||
let data = start.iter_days().take_while(|date| *date <= end).map(|date| {
|
|
||||||
let date = date.to_string();
|
|
||||||
match route {
|
|
||||||
"daily-token-usage-breakdown" | "daily-workspace-user-token-usage-breakdown" => json!({
|
|
||||||
"date":date, "product_surface_usage_values":{"codex_cli":10.0},
|
|
||||||
"premium_usage_values":{
|
|
||||||
"credit_usage_credits":{"codex_cli":10.0}, "total_usage_credits":{},
|
|
||||||
"uncached_text_input_tokens_by_surface":{}, "cached_text_input_tokens_by_surface":{},
|
|
||||||
"text_output_tokens_by_surface":{}, "text_total_tokens_by_surface":{}
|
|
||||||
},
|
|
||||||
"models":[{"model":"GPT-5.5","credits":10.0,"on_demand_credits":10.0,"turns":10,"speed":"standard"}],
|
|
||||||
"groups":[{"dimensions":{"model":"GPT-5.5"},"credits":10.0,"uncached_text_input_tokens":10,"cached_text_input_tokens":20,"text_output_tokens":30}]
|
|
||||||
}),
|
|
||||||
"credit-usage-events" => json!({"date":date,"product_surface":"cli","credit_amount":10.0}),
|
|
||||||
"daily-workspace-user-credit-usage" => json!({"date":date,"values":{"codex":10.0}}),
|
|
||||||
"daily-workspace-usage-counts" => json!({
|
|
||||||
"date":date,"totals":{"users":1,"threads":1,"turns":10,"credits":10.0},"clients":[],
|
|
||||||
"models":[{"model":"GPT-5.5","credits":10.0,"turns":10}]
|
|
||||||
}),
|
|
||||||
"daily-plugin-usage-metrics" => json!({"date":date,"plugin_usage_overviews":[{
|
|
||||||
"plugin_id":null,"plugin_name":"test","marketplace":null,"display_name":"Test plugin","invocation_counts":10
|
|
||||||
}]}),
|
|
||||||
"daily-skill-usage-metrics" => json!({"date":date,"skill_usage_overviews":[{
|
|
||||||
"skill_name":"test","skill_ids":[],"display_name":"Test skill","invocation_counts":10
|
|
||||||
}]}),
|
|
||||||
_ => panic!("Unexpected mock analytics route: {route}"),
|
|
||||||
}
|
|
||||||
}).collect::<Vec<_>>();
|
|
||||||
let response = if route == "daily-workspace-user-credit-usage" {
|
|
||||||
json!({"breakdown":params["breakdown"],"series":[{"key":"codex","label":"Codex","total":data.len() as f64 * 10.0}],"data":data})
|
|
||||||
} else {
|
|
||||||
json!({"data":data})
|
|
||||||
};
|
|
||||||
wiremock::ResponseTemplate::new(/*s*/ 200).set_body_json(response)
|
|
||||||
})
|
|
||||||
.mount(&server).await;
|
|
||||||
server
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn settle(view: &mut super::AnalyticsView) {
|
|
||||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 10), async {
|
|
||||||
loop {
|
|
||||||
view.poll_reports();
|
|
||||||
if !matches!(view.account, Load::Loading(_))
|
|
||||||
&& !view
|
|
||||||
.sections
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.any(|state| matches!(state.history, Load::Loading(_)))
|
|
||||||
&& !matches!(view.chats, Load::Loading(_))
|
|
||||||
&& !matches!(view.tasks, Load::Loading(_))
|
|
||||||
&& !matches!(view.profile, Load::Loading(_))
|
|
||||||
&& !matches!(view.plan.report, Load::Loading(_))
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
tokio::time::sleep(std::time::Duration::from_millis(/*millis*/ 5)).await;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
//! Enterprise text token history, independent of credit and allowance accounting.
|
|
||||||
|
|
||||||
use super::models::*;
|
|
||||||
use super::report_data::AnalyticsData;
|
|
||||||
use chrono::NaiveDate;
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
pub(super) fn history(
|
|
||||||
response: AnalyticsData,
|
|
||||||
grouping: AccountAnalyticsGrouping,
|
|
||||||
start: NaiveDate,
|
|
||||||
end: NaiveDate,
|
|
||||||
) -> Result<AccountAnalyticsHistory, String> {
|
|
||||||
filtered_history(response, grouping, start, end, /*model_filter*/ None)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn filtered_history(
|
|
||||||
response: AnalyticsData,
|
|
||||||
grouping: AccountAnalyticsGrouping,
|
|
||||||
start: NaiveDate,
|
|
||||||
end: NaiveDate,
|
|
||||||
model_filter: Option<&str>,
|
|
||||||
) -> Result<AccountAnalyticsHistory, String> {
|
|
||||||
let mut days: BTreeMap<NaiveDate, BTreeMap<String, f64>> = BTreeMap::new();
|
|
||||||
for record in response.data {
|
|
||||||
let date = record
|
|
||||||
.date
|
|
||||||
.parse::<NaiveDate>()
|
|
||||||
.map_err(|_| "Invalid token report date.")?;
|
|
||||||
if date < start || date > end {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let groups = if let Some(groups) = record.groups {
|
|
||||||
groups
|
|
||||||
.into_iter()
|
|
||||||
.map(|group| {
|
|
||||||
(
|
|
||||||
if group.is_other {
|
|
||||||
"Other".into()
|
|
||||||
} else {
|
|
||||||
group
|
|
||||||
.dimensions
|
|
||||||
.get("model")
|
|
||||||
.cloned()
|
|
||||||
.unwrap_or_else(|| "Unknown".into())
|
|
||||||
},
|
|
||||||
[
|
|
||||||
group.uncached_text_input_tokens,
|
|
||||||
group.cached_text_input_tokens,
|
|
||||||
group.text_output_tokens,
|
|
||||||
],
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
} else if let Some(models) = record.models {
|
|
||||||
models
|
|
||||||
.into_iter()
|
|
||||||
.map(|model| {
|
|
||||||
(
|
|
||||||
model.model,
|
|
||||||
[
|
|
||||||
model.uncached_text_input_tokens,
|
|
||||||
model.cached_text_input_tokens,
|
|
||||||
model.text_output_tokens,
|
|
||||||
],
|
|
||||||
model.text_total_tokens,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
} else {
|
|
||||||
return Err("Token breakdown is not available in this report.".into());
|
|
||||||
};
|
|
||||||
let values = days.entry(date).or_default();
|
|
||||||
for (model, counts, total) in groups {
|
|
||||||
if model_filter.is_some_and(|selected| selected != model) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let missing_components = counts.iter().all(Option::is_none);
|
|
||||||
if grouping == AccountAnalyticsGrouping::Model
|
|
||||||
&& let Some(total) = total.filter(|total| *total != 0.0 || missing_components)
|
|
||||||
{
|
|
||||||
if !total.is_finite() || total < 0.0 || total.fract() != 0.0 {
|
|
||||||
return Err("Invalid token count.".into());
|
|
||||||
}
|
|
||||||
*values.entry(model).or_default() += total;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if missing_components {
|
|
||||||
return Err("Token counts were not reported.".into());
|
|
||||||
}
|
|
||||||
for (label, count) in ["Uncached input", "Cached input", "Output"]
|
|
||||||
.into_iter()
|
|
||||||
.zip(counts)
|
|
||||||
{
|
|
||||||
let count = count.unwrap_or(/*default*/ 0.0);
|
|
||||||
if !count.is_finite() || count < 0.0 || count.fract() != 0.0 {
|
|
||||||
return Err("Invalid token count.".into());
|
|
||||||
}
|
|
||||||
let key = if grouping == AccountAnalyticsGrouping::Model {
|
|
||||||
&model
|
|
||||||
} else {
|
|
||||||
label
|
|
||||||
};
|
|
||||||
*values.entry(key.to_string()).or_default() += count;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::Tokens,
|
|
||||||
updated_at: response
|
|
||||||
.data_freshness_ts
|
|
||||||
.and_then(|time| chrono::DateTime::parse_from_rfc3339(&time).ok())
|
|
||||||
.map(|time| time.timestamp()),
|
|
||||||
data: days
|
|
||||||
.into_iter()
|
|
||||||
.map(|(date, values)| AccountAnalyticsDay {
|
|
||||||
date,
|
|
||||||
total: values.values().sum(),
|
|
||||||
values: values
|
|
||||||
.into_iter()
|
|
||||||
.map(|(key, value)| AccountAnalyticsValue {
|
|
||||||
label: key.clone(),
|
|
||||||
key,
|
|
||||||
value,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[path = "tokens_tests.rs"]
|
|
||||||
mod tests;
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
//! Enterprise token normalization across supported groupings.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tokens_use_text_components_and_keep_daily_totals_across_groupings() {
|
|
||||||
let response: AnalyticsData = serde_json::from_value(json!({"units":"credits", "data":[{
|
|
||||||
"date":"2026-09-01", "groups":[{"dimensions":{"model":"gpt-5"}, "uncached_text_input_tokens":10, "cached_text_input_tokens":80, "text_output_tokens":10}]
|
|
||||||
}]})).unwrap();
|
|
||||||
let date = "2026-09-01".parse().unwrap();
|
|
||||||
let by_type = history(
|
|
||||||
response.clone(),
|
|
||||||
AccountAnalyticsGrouping::TokenType,
|
|
||||||
date,
|
|
||||||
date,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let by_model = history(response, AccountAnalyticsGrouping::Model, date, date).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(by_type.unit, by_type.data[0].total, by_model.data[0].total),
|
|
||||||
(AccountAnalyticsUnit::Tokens, 100.0, 100.0)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
by_type.data[0]
|
|
||||||
.values
|
|
||||||
.iter()
|
|
||||||
.map(|v| (v.label.as_str(), v.value))
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
vec![
|
|
||||||
("Cached input", 80.0),
|
|
||||||
("Output", 10.0),
|
|
||||||
("Uncached input", 10.0)
|
|
||||||
]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn token_model_filter_retains_components_and_freshness() {
|
|
||||||
let date = "2026-09-01".parse().unwrap();
|
|
||||||
let response: AnalyticsData = serde_json::from_value(json!({"data_freshness_ts":"2026-09-02T00:00:00Z", "data":[{
|
|
||||||
"date":"2026-09-01", "groups":[
|
|
||||||
{"dimensions":{"model":"alpha"}, "uncached_text_input_tokens":10,"cached_text_input_tokens":20,"text_output_tokens":30},
|
|
||||||
{"dimensions":{"model":"beta"}, "uncached_text_input_tokens":100,"cached_text_input_tokens":200,"text_output_tokens":300}
|
|
||||||
], "models":[{"model":"ignored", "text_total_tokens":1000}]
|
|
||||||
}]})).unwrap();
|
|
||||||
let selected = filtered_history(
|
|
||||||
response.clone(),
|
|
||||||
AccountAnalyticsGrouping::TokenType,
|
|
||||||
date,
|
|
||||||
date,
|
|
||||||
Some("alpha"),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let expected = history(serde_json::from_value(json!({"data_freshness_ts":"2026-09-02T00:00:00Z", "data":[{
|
|
||||||
"date":"2026-09-01", "models":[{"model":"alpha", "uncached_text_input_tokens":10,"cached_text_input_tokens":20,"text_output_tokens":30}]
|
|
||||||
}]})).unwrap(), AccountAnalyticsGrouping::TokenType, date, date).unwrap();
|
|
||||||
assert_eq!(selected, expected);
|
|
||||||
assert_eq!(
|
|
||||||
history(response, AccountAnalyticsGrouping::TokenType, date, date)
|
|
||||||
.unwrap()
|
|
||||||
.data[0]
|
|
||||||
.total,
|
|
||||||
660.0
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn model_totals_use_reported_total_and_missing_components_remain_unavailable() {
|
|
||||||
let date = "2026-09-01".parse().unwrap();
|
|
||||||
let response: AnalyticsData = serde_json::from_value(json!({"data":[{"date":"2026-09-01", "models":[{"model":"alpha", "text_total_tokens":123}]}]})).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(
|
|
||||||
response.clone(),
|
|
||||||
AccountAnalyticsGrouping::Model,
|
|
||||||
date,
|
|
||||||
date
|
|
||||||
)
|
|
||||||
.unwrap()
|
|
||||||
.data,
|
|
||||||
vec![AccountAnalyticsDay {
|
|
||||||
date: "2026-09-01".parse().unwrap(),
|
|
||||||
total: 123.0,
|
|
||||||
values: vec![AccountAnalyticsValue {
|
|
||||||
key: "alpha".into(),
|
|
||||||
label: "alpha".into(),
|
|
||||||
value: 123.0
|
|
||||||
}]
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
history(response, AccountAnalyticsGrouping::TokenType, date, date).unwrap_err(),
|
|
||||||
"Token counts were not reported."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn explicit_zero_model_total_is_reported_without_components() {
|
|
||||||
let date = "2026-09-01".parse().unwrap();
|
|
||||||
let response: AnalyticsData = serde_json::from_value(json!({
|
|
||||||
"data": [{"date": "2026-09-01", "models": [
|
|
||||||
{"model": "idle", "text_total_tokens": 0},
|
|
||||||
{"model": "active", "text_total_tokens": 0, "text_output_tokens": 5}
|
|
||||||
]}]
|
|
||||||
}))
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
history(response, AccountAnalyticsGrouping::Model, date, date).unwrap(),
|
|
||||||
AccountAnalyticsHistory {
|
|
||||||
unit: AccountAnalyticsUnit::Tokens,
|
|
||||||
updated_at: None,
|
|
||||||
data: vec![AccountAnalyticsDay {
|
|
||||||
date: "2026-09-01".parse().unwrap(),
|
|
||||||
total: 5.0,
|
|
||||||
values: vec![
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "active".into(),
|
|
||||||
label: "active".into(),
|
|
||||||
value: 5.0,
|
|
||||||
},
|
|
||||||
AccountAnalyticsValue {
|
|
||||||
key: "idle".into(),
|
|
||||||
label: "idle".into(),
|
|
||||||
value: 0.0,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}],
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
//! Human-readable plugin and skill labels.
|
|
||||||
|
|
||||||
pub(super) fn tool_name(label: &str) -> String {
|
|
||||||
let label = match label.split_once(':') {
|
|
||||||
Some((namespace, name)) if namespace.trim().eq_ignore_ascii_case(name.trim()) => {
|
|
||||||
name.trim()
|
|
||||||
}
|
|
||||||
_ => label,
|
|
||||||
};
|
|
||||||
label
|
|
||||||
.split_whitespace()
|
|
||||||
.map(|word| match word.to_ascii_lowercase().as_str() {
|
|
||||||
"pr" => "PR",
|
|
||||||
"cli" => "CLI",
|
|
||||||
"api" => "API",
|
|
||||||
"ide" => "IDE",
|
|
||||||
"mcp" => "MCP",
|
|
||||||
"sdk" => "SDK",
|
|
||||||
"ui" => "UI",
|
|
||||||
"tui" => "TUI",
|
|
||||||
"openai" => "OpenAI",
|
|
||||||
_ => word,
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(" ")
|
|
||||||
}
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
//! Tool chart layout, independent selection, naming, and partial report states.
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_tools_reflow_and_keep_independent_days() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
press(&mut view, KeyCode::Char('4'));
|
|
||||||
let wide = screen(&mut view, /*width*/ 140, /*height*/ 48);
|
|
||||||
assert!(wide.contains("186 calls"));
|
|
||||||
press(&mut view, KeyCode::Char('5'));
|
|
||||||
press(&mut view, KeyCode::Left);
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.sections[Section::Plugins].cursor,
|
|
||||||
view.sections[Section::Skills].cursor,
|
|
||||||
view.sections[Section::Skills].detail
|
|
||||||
),
|
|
||||||
(6, 5, Some(5))
|
|
||||||
);
|
|
||||||
let narrow = screen(&mut view, /*width*/ 58, /*height*/ 32);
|
|
||||||
assert!(narrow.contains("Sep 1 · 5 uses"));
|
|
||||||
press(&mut view, KeyCode::Char('r'));
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.sections[Section::Plugins].cursor,
|
|
||||||
view.sections[Section::Skills].cursor,
|
|
||||||
view.ranges
|
|
||||||
),
|
|
||||||
(29, 28, [0, 0, 1])
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Char('r'));
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.sections[Section::Plugins].cursor,
|
|
||||||
view.sections[Section::Skills].cursor,
|
|
||||||
view.sections[Section::Skills].detail
|
|
||||||
),
|
|
||||||
(6, 5, Some(5))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_tools_handle_empty_days_and_independent_failures() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
let mut history = fixture::history(/*report*/ 4, /*range*/ 0, /*group*/ 0);
|
|
||||||
history.data[6].total = 0.0;
|
|
||||||
for value in &mut history.data[6].values {
|
|
||||||
value.value = 0.0;
|
|
||||||
}
|
|
||||||
history.data.remove(/*index*/ 5);
|
|
||||||
view.sections[Section::Skills].history = Load::Ready(history);
|
|
||||||
press(&mut view, KeyCode::Char('5'));
|
|
||||||
let empty = screen(&mut view, /*width*/ 140, /*height*/ 44);
|
|
||||||
assert!(empty.contains("No uses reported for Sep 2."));
|
|
||||||
assert!(!empty.contains("details"));
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert_eq!(view.sections[Section::Skills].detail, None);
|
|
||||||
press(&mut view, KeyCode::Left);
|
|
||||||
let missing = screen(&mut view, /*width*/ 140, /*height*/ 44);
|
|
||||||
assert!(missing.contains("Data not reported for Sep 1."));
|
|
||||||
assert_eq!(
|
|
||||||
empty.lines().position(|line| line.contains('▲')),
|
|
||||||
missing.lines().position(|line| line.contains('▲')),
|
|
||||||
);
|
|
||||||
view.sections[Section::Skills].history =
|
|
||||||
Load::Error("Skills could not be loaded. Press R to retry.".into());
|
|
||||||
let partial = screen(&mut view, /*width*/ 140, /*height*/ 44);
|
|
||||||
assert!(partial.contains("Skills could not be loaded"));
|
|
||||||
press(&mut view, KeyCode::Char('4'));
|
|
||||||
assert!(screen(&mut view, /*width*/ 140, /*height*/ 44).contains("186 calls"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_tool_names_preserve_acronyms_and_distinct_namespaces() {
|
|
||||||
let labels = [
|
|
||||||
"Pr Reviewer",
|
|
||||||
"Slack Cli",
|
|
||||||
"Squatch: Squatch",
|
|
||||||
"Openai Docs",
|
|
||||||
"User Writing: Writing Style",
|
|
||||||
];
|
|
||||||
assert_eq!(
|
|
||||||
labels.map(tool_panel::tool_name),
|
|
||||||
[
|
|
||||||
"PR Reviewer",
|
|
||||||
"Slack CLI",
|
|
||||||
"Squatch",
|
|
||||||
"OpenAI Docs",
|
|
||||||
"User Writing: Writing Style"
|
|
||||||
]
|
|
||||||
.map(str::to_owned),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,667 +0,0 @@
|
|||||||
//! Dashboard layout, local detail, shared ranges, grouping, and scroll/focus retention.
|
|
||||||
|
|
||||||
use crate::analytics::sections::Section;
|
|
||||||
#[path = "analytics/compact_tests.rs"]
|
|
||||||
mod compact;
|
|
||||||
#[path = "analytics/recovery_tests.rs"]
|
|
||||||
mod recovery;
|
|
||||||
#[path = "analytics/redesign_tests.rs"]
|
|
||||||
mod redesign;
|
|
||||||
#[path = "analytics/summary_tests.rs"]
|
|
||||||
mod summary;
|
|
||||||
|
|
||||||
#[path = "analytics/account_layout_tests.rs"]
|
|
||||||
mod account_layout;
|
|
||||||
|
|
||||||
#[path = "analytics/navigation_tests.rs"]
|
|
||||||
mod navigation;
|
|
||||||
|
|
||||||
#[path = "analytics/consumer_refresh_tests.rs"]
|
|
||||||
mod consumer_refresh;
|
|
||||||
|
|
||||||
#[path = "analytics/tool_panel_tests.rs"]
|
|
||||||
mod tools_panel;
|
|
||||||
|
|
||||||
#[path = "analytics/styles_tests.rs"]
|
|
||||||
mod terminal_styles;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::keymap::RuntimeKeymap;
|
|
||||||
use crossterm::event::KeyModifiers;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use ratatui::Terminal;
|
|
||||||
use ratatui::backend::TestBackend;
|
|
||||||
|
|
||||||
fn press(view: &mut AnalyticsView, code: KeyCode) {
|
|
||||||
view.handle_key(KeyEvent::new(code, KeyModifiers::NONE));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn screen(view: &mut AnalyticsView, width: u16, height: u16) -> String {
|
|
||||||
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
|
|
||||||
terminal
|
|
||||||
.draw(|frame| view.render(frame.area(), frame.buffer_mut()))
|
|
||||||
.unwrap();
|
|
||||||
terminal.backend().to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_exact_fit_content_has_no_scroll_hint() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Enterprise);
|
|
||||||
view.section = Section::Chats;
|
|
||||||
screen(&mut view, /*width*/ 120, /*height*/ 60);
|
|
||||||
let chrome_height = 60 - view.viewport_height;
|
|
||||||
let content_height = view
|
|
||||||
.panel(Section::Chats, /*width*/ 116, /*chart_height*/ 4)
|
|
||||||
.lines
|
|
||||||
.len();
|
|
||||||
let exact_height = (chrome_height + content_height) as u16;
|
|
||||||
|
|
||||||
let exact = screen(&mut view, /*width*/ 120, exact_height);
|
|
||||||
assert!(!exact.contains("scroll"));
|
|
||||||
assert_eq!(view.viewport_height, content_height);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_narrow_charts_and_small_terminals_keep_valid_cursors() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
for section in ['2', '3', '4'] {
|
|
||||||
press(&mut view, KeyCode::Char(section));
|
|
||||||
press(&mut view, KeyCode::Char('r'));
|
|
||||||
fixture::seed_reports(&mut view);
|
|
||||||
press(&mut view, KeyCode::Home);
|
|
||||||
for _ in 0..30 {
|
|
||||||
screen(&mut view, /*width*/ 28, /*height*/ 12);
|
|
||||||
press(&mut view, KeyCode::Right);
|
|
||||||
}
|
|
||||||
assert_eq!(view.sections[view.section].cursor, 29);
|
|
||||||
}
|
|
||||||
for _ in 0..2 {
|
|
||||||
for width in [1, 4, 32, 107, 108] {
|
|
||||||
screen(&mut view, width, /*height*/ 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let empty = ratatui::layout::Rect::default();
|
|
||||||
view.render(empty, &mut ratatui::buffer::Buffer::empty(empty));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_credits_grouping_preserves_selected_day_and_total() {
|
|
||||||
let server = test_support::server().await;
|
|
||||||
let (_home, _app_server, mut view) = client::tests::connected_view(&server, "business").await;
|
|
||||||
test_support::settle(&mut view).await;
|
|
||||||
press(&mut view, KeyCode::Char('2'));
|
|
||||||
test_support::settle(&mut view).await;
|
|
||||||
press(&mut view, KeyCode::Left);
|
|
||||||
let before = view.sections[Section::Credits]
|
|
||||||
.history
|
|
||||||
.ready()
|
|
||||||
.unwrap()
|
|
||||||
.data
|
|
||||||
.iter()
|
|
||||||
.map(|day| day.total)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
for group in [2, 4, 5, 0] {
|
|
||||||
press(&mut view, KeyCode::Char('g'));
|
|
||||||
test_support::settle(&mut view).await;
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.sections[Section::Credits].group,
|
|
||||||
view.sections[Section::Credits].cursor
|
|
||||||
),
|
|
||||||
(group, 5)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
view.sections[Section::Credits]
|
|
||||||
.history
|
|
||||||
.ready()
|
|
||||||
.unwrap()
|
|
||||||
.data
|
|
||||||
.iter()
|
|
||||||
.map(|day| day.total)
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
before
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn analytics_loading_errors_and_empty_reports_stay_independent() {
|
|
||||||
let mut view = AnalyticsView::new(RuntimeKeymap::defaults().list);
|
|
||||||
let (send, receive) = tokio::sync::oneshot::channel();
|
|
||||||
view.sections[Section::Usage].history = Load::start(
|
|
||||||
async move { receive.await.unwrap() },
|
|
||||||
FrameRequester::test_dummy(),
|
|
||||||
);
|
|
||||||
view.sections[Section::Credits].history =
|
|
||||||
Load::Error("Couldn't load credits. Press R to retry.".into());
|
|
||||||
let mut empty = fixture::history(/*report*/ 2, /*range*/ 0, /*group*/ 2);
|
|
||||||
empty.data.clear();
|
|
||||||
view.sections[Section::Activity].history = Load::Ready(empty);
|
|
||||||
let panels = [
|
|
||||||
Section::Usage,
|
|
||||||
Section::Plugins,
|
|
||||||
Section::Credits,
|
|
||||||
Section::Activity,
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.map(|section| {
|
|
||||||
view.panel(section, /*width*/ 54, /*chart_height*/ 2)
|
|
||||||
.lines
|
|
||||||
.into_iter()
|
|
||||||
.map(|line| line.to_string())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n")
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n\n");
|
|
||||||
insta::assert_snapshot!(panels);
|
|
||||||
// Refresh drops pending work before a stale result can populate the retained view.
|
|
||||||
view.refresh();
|
|
||||||
tokio::task::yield_now().await;
|
|
||||||
assert!(send.is_closed());
|
|
||||||
assert!(matches!(
|
|
||||||
view.sections[Section::Usage].history,
|
|
||||||
Load::Unavailable
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_preserves_full_denominators_and_signed_small_credits() {
|
|
||||||
use crate::analytics::models::AccountAnalyticsDay;
|
|
||||||
use crate::analytics::models::AccountAnalyticsValue;
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
let mut history = fixture::history(/*report*/ 0, /*range*/ 0, /*group*/ 3);
|
|
||||||
history.data = vec![AccountAnalyticsDay {
|
|
||||||
date: "2026-09-02".parse().unwrap(),
|
|
||||||
total: 100.0,
|
|
||||||
values: vec![AccountAnalyticsValue {
|
|
||||||
key: "goal".into(),
|
|
||||||
label: "Goals".into(),
|
|
||||||
value: 30.0,
|
|
||||||
}],
|
|
||||||
}];
|
|
||||||
view.sections[Section::Usage].history = Load::Ready(history.clone());
|
|
||||||
view.sections[Section::Usage].group = 3;
|
|
||||||
view.sections[Section::Usage].cursor = 6;
|
|
||||||
let task = view
|
|
||||||
.panel(Section::Usage, /*width*/ 54, /*chart_height*/ 2)
|
|
||||||
.lines;
|
|
||||||
assert!(
|
|
||||||
task.iter()
|
|
||||||
.any(|line| line.to_string().contains("Goals") && line.to_string().contains("30.0%"))
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
task.iter()
|
|
||||||
.any(|line| line.to_string() == "Sep 2 · 100 usage units")
|
|
||||||
);
|
|
||||||
history.unit = crate::analytics::models::AccountAnalyticsUnit::Credits;
|
|
||||||
history.data[0].total = -0.000004;
|
|
||||||
history.data[0].values[0].value = -0.000004;
|
|
||||||
history.data[0].values[0].label = "CLI".into();
|
|
||||||
view.sections[Section::Credits].history = Load::Ready(history);
|
|
||||||
view.sections[Section::Credits].cursor = 6;
|
|
||||||
let credits = view
|
|
||||||
.panel(Section::Credits, /*width*/ 54, /*chart_height*/ 2)
|
|
||||||
.lines;
|
|
||||||
insta::assert_snapshot!(
|
|
||||||
task.into_iter()
|
|
||||||
.chain(credits)
|
|
||||||
.map(|line| line.to_string())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_credit_display_retains_integer_precision() {
|
|
||||||
assert_eq!(
|
|
||||||
[753.71, 411.12, 47.4, 0.0, 1_212.224, -0.004, -0.000004].map(data::credit_amount),
|
|
||||||
[
|
|
||||||
"753.71",
|
|
||||||
"411.12",
|
|
||||||
"47.40",
|
|
||||||
"0.00",
|
|
||||||
"1,212.22",
|
|
||||||
"-0.004",
|
|
||||||
"-0.000004"
|
|
||||||
]
|
|
||||||
.map(str::to_string)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
[0, -4, 999_999_999, 19_350_041_555, i64::MIN, i64::MAX].map(data::credits),
|
|
||||||
[
|
|
||||||
"0.00",
|
|
||||||
"-0.000004",
|
|
||||||
"1,000.00",
|
|
||||||
"19,350.04",
|
|
||||||
"-9,223,372,036,854.78",
|
|
||||||
"9,223,372,036,854.78"
|
|
||||||
]
|
|
||||||
.map(str::to_string)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
[
|
|
||||||
12_746.441206,
|
|
||||||
-1_000.125,
|
|
||||||
999.999,
|
|
||||||
0.0,
|
|
||||||
-0.000004,
|
|
||||||
0.009,
|
|
||||||
7.5
|
|
||||||
]
|
|
||||||
.map(data::amount),
|
|
||||||
[
|
|
||||||
"12,746.44",
|
|
||||||
"-1,000.12",
|
|
||||||
"1,000",
|
|
||||||
"0",
|
|
||||||
"-0.000004",
|
|
||||||
"0.009",
|
|
||||||
"7.5"
|
|
||||||
]
|
|
||||||
.map(str::to_string)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_dates_distinguish_zero_missing_and_exact_details() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Enterprise);
|
|
||||||
let mut history = fixture::history(/*report*/ 1, /*range*/ 0, /*group*/ 0);
|
|
||||||
history.data[1].total = 12_746.441206;
|
|
||||||
history.data[1].values[0].value = 12_746.441206;
|
|
||||||
history.data[1].values.truncate(/*len*/ 1);
|
|
||||||
history.data.remove(/*index*/ 2);
|
|
||||||
view.sections[Section::Credits].history = Load::Ready(history.clone());
|
|
||||||
press(&mut view, KeyCode::Char('2'));
|
|
||||||
press(&mut view, KeyCode::Home);
|
|
||||||
let mut screens = Vec::new();
|
|
||||||
for keys in [
|
|
||||||
vec![],
|
|
||||||
vec![KeyCode::Right, KeyCode::Enter],
|
|
||||||
vec![KeyCode::Right],
|
|
||||||
] {
|
|
||||||
for key in keys {
|
|
||||||
press(&mut view, key);
|
|
||||||
}
|
|
||||||
screens.push(
|
|
||||||
view.panel(Section::Credits, /*width*/ 54, /*chart_height*/ 3)
|
|
||||||
.lines
|
|
||||||
.into_iter()
|
|
||||||
.map(|line| line.to_string())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert!(screens[0].contains("No activity (0)"));
|
|
||||||
assert!(screens[1].contains("12746.441206 credits"));
|
|
||||||
assert!(screens[2].contains("Aug 29 · Not reported"));
|
|
||||||
for day in &mut history.data {
|
|
||||||
day.total = 0.0;
|
|
||||||
day.values.clear();
|
|
||||||
}
|
|
||||||
view.sections[Section::Credits].history = Load::Ready(history.clone());
|
|
||||||
screens.push(
|
|
||||||
view.panel(Section::Credits, /*width*/ 54, /*chart_height*/ 3)
|
|
||||||
.lines
|
|
||||||
.into_iter()
|
|
||||||
.map(|line| line.to_string())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
);
|
|
||||||
history.data.clear();
|
|
||||||
view.sections[Section::Credits].history = Load::Ready(history);
|
|
||||||
screens.push(
|
|
||||||
view.panel(Section::Credits, /*width*/ 54, /*chart_height*/ 3)
|
|
||||||
.lines
|
|
||||||
.into_iter()
|
|
||||||
.map(|line| line.to_string())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
);
|
|
||||||
insta::assert_snapshot!(screens.join("\n\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_model_labels_and_tool_remainders_are_unambiguous() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
view.model_names
|
|
||||||
.insert("GPT-5.6-Sol".into(), "Friendly model".into());
|
|
||||||
let mut tools = fixture::history(/*report*/ 4, /*range*/ 0, /*group*/ 0);
|
|
||||||
for day in &mut tools.data {
|
|
||||||
day.values[1].label = "Other".into();
|
|
||||||
}
|
|
||||||
view.sections[Section::Skills].history = Load::Ready(tools);
|
|
||||||
press(&mut view, KeyCode::Char('3'));
|
|
||||||
let overview = screen(&mut view, /*width*/ 140, /*height*/ 64);
|
|
||||||
assert!(overview.contains("Friendly model"));
|
|
||||||
assert!(overview.contains("Skills"));
|
|
||||||
press(&mut view, KeyCode::Char('5'));
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
let skills = screen(&mut view, /*width*/ 100, /*height*/ 32);
|
|
||||||
assert!(skills.contains("Other"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_maximized_refunds_leave_room_for_both_bands() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Enterprise);
|
|
||||||
let mut history = fixture::history(/*report*/ 1, /*range*/ 0, /*group*/ 0);
|
|
||||||
history.data[6].total = -0.000004;
|
|
||||||
history.data[6].values = vec![crate::analytics::models::AccountAnalyticsValue {
|
|
||||||
key: "CLI".into(),
|
|
||||||
label: "CLI".into(),
|
|
||||||
value: -0.000004,
|
|
||||||
}];
|
|
||||||
view.sections[Section::Credits].history = Load::Ready(history);
|
|
||||||
press(&mut view, KeyCode::Char('2'));
|
|
||||||
let output = screen(&mut view, /*width*/ 100, /*height*/ 32);
|
|
||||||
assert!(output.contains("Sep 2 · -0.000004 credits"));
|
|
||||||
assert!(
|
|
||||||
output
|
|
||||||
.lines()
|
|
||||||
.any(|line| line.contains("● CLI") && line.contains("-0.000004"))
|
|
||||||
);
|
|
||||||
insta::assert_snapshot!(output);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_day_navigation_keeps_geometry_and_legend() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Enterprise);
|
|
||||||
let mut history = fixture::history(/*report*/ 1, /*range*/ 0, /*group*/ 0);
|
|
||||||
history.data[1].values.truncate(/*len*/ 1);
|
|
||||||
history.data[1].total = history.data[1].values[0].value;
|
|
||||||
history.data.remove(/*index*/ 2);
|
|
||||||
view.sections[Section::Credits].history = Load::Ready(history);
|
|
||||||
press(&mut view, KeyCode::Char('2'));
|
|
||||||
for width in [58, 160] {
|
|
||||||
let mut terminal = Terminal::new(TestBackend::new(width, /*height*/ 38)).unwrap();
|
|
||||||
for expanded in [false, true] {
|
|
||||||
press(&mut view, KeyCode::Home);
|
|
||||||
if expanded {
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
}
|
|
||||||
let mut previous = None;
|
|
||||||
for _ in 0..7 {
|
|
||||||
terminal
|
|
||||||
.draw(|frame| view.render(frame.area(), frame.buffer_mut()))
|
|
||||||
.unwrap();
|
|
||||||
let buffer = terminal.backend().buffer();
|
|
||||||
let bars = buffer
|
|
||||||
.content
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.filter(|(_, cell)| {
|
|
||||||
matches!(cell.symbol(), "█" | "▁" | "▂" | "▃" | "▄" | "▅" | "▆" | "▇")
|
|
||||||
})
|
|
||||||
.map(|(index, cell)| (index, cell.clone()))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let output = terminal.backend().to_string();
|
|
||||||
let marker_row = output.lines().position(|line| line.contains('▲')).unwrap();
|
|
||||||
let table_row = output
|
|
||||||
.lines()
|
|
||||||
.position(|line| line.contains("Product"))
|
|
||||||
.unwrap();
|
|
||||||
let geometry = (bars, marker_row, table_row);
|
|
||||||
if let Some(previous) = &previous {
|
|
||||||
assert_eq!(&geometry, previous);
|
|
||||||
}
|
|
||||||
previous = Some(geometry);
|
|
||||||
assert!(output.contains("● CLI") && output.contains("● Desktop app"));
|
|
||||||
press(&mut view, KeyCode::Right);
|
|
||||||
}
|
|
||||||
if expanded {
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_series_rank_by_range_and_keep_calendar_ticks_stable() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
screen(&mut view, /*width*/ 100, /*height*/ 38);
|
|
||||||
press(&mut view, KeyCode::Char('r'));
|
|
||||||
let mut history = fixture::history(/*report*/ 0, /*range*/ 1, /*group*/ 2);
|
|
||||||
for day in &mut history.data {
|
|
||||||
day.values[3].value += 500.0;
|
|
||||||
day.total += 500.0;
|
|
||||||
}
|
|
||||||
view.sections[Section::Usage].history = Load::Ready(history.clone());
|
|
||||||
screen(&mut view, /*width*/ 100, /*height*/ 38);
|
|
||||||
let legend = view
|
|
||||||
.history_lines(Section::Usage, /*width*/ 96, /*height*/ 10)
|
|
||||||
.lines
|
|
||||||
.into_iter()
|
|
||||||
.filter(|line| line.spans.first().is_some_and(|span| span.content == "● "))
|
|
||||||
.take(/*n*/ 3)
|
|
||||||
.map(|line| (line.spans[1].content.to_string(), line.spans[0].style.fg))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
assert_eq!(
|
|
||||||
legend,
|
|
||||||
["Other", "GPT-5.6-Sol", "GPT-5.6-Terra"]
|
|
||||||
.into_iter()
|
|
||||||
.zip(styles::series_colors())
|
|
||||||
.map(|(label, color)| (label.to_string(), Some(color)))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
);
|
|
||||||
let series = render::categories(&history);
|
|
||||||
history.data[8].total = 0.4;
|
|
||||||
for value in &mut history.data[8].values {
|
|
||||||
value.value = 0.1;
|
|
||||||
}
|
|
||||||
let days = history
|
|
||||||
.data
|
|
||||||
.iter()
|
|
||||||
.map(|day| (day.date, Some(day)))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let mut ticks = None;
|
|
||||||
for cursor in [0, 7, 8, 25, 29] {
|
|
||||||
let chart = plot::chart(
|
|
||||||
&days,
|
|
||||||
&series,
|
|
||||||
cursor,
|
|
||||||
/*width*/ 96,
|
|
||||||
/*height*/ 10,
|
|
||||||
history.unit,
|
|
||||||
);
|
|
||||||
let labels = chart.lines.last().unwrap().to_string();
|
|
||||||
if let Some(ticks) = &ticks {
|
|
||||||
assert_eq!(&labels, ticks);
|
|
||||||
}
|
|
||||||
ticks = Some(labels);
|
|
||||||
assert_eq!(
|
|
||||||
chart
|
|
||||||
.lines
|
|
||||||
.iter()
|
|
||||||
.filter(|line| line.to_string().contains('▲'))
|
|
||||||
.count(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let crowded = plot::chart(
|
|
||||||
&days,
|
|
||||||
&series,
|
|
||||||
/*cursor*/ 8,
|
|
||||||
/*width*/ 54,
|
|
||||||
/*height*/ 10,
|
|
||||||
history.unit,
|
|
||||||
)
|
|
||||||
.lines
|
|
||||||
.iter()
|
|
||||||
.map(ToString::to_string)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
assert!(crowded.contains('┊'));
|
|
||||||
assert!(crowded.contains("0.4"));
|
|
||||||
insta::assert_snapshot!(crowded);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_usage_ranks_its_own_models_after_turns_load() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
screen(&mut view, /*width*/ 100, /*height*/ 38);
|
|
||||||
press(&mut view, KeyCode::Char('g'));
|
|
||||||
press(&mut view, KeyCode::Down);
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
let mut history = fixture::history(/*report*/ 0, /*range*/ 0, /*group*/ 2);
|
|
||||||
for day in &mut history.data {
|
|
||||||
for label in ["Model E", "Model F"] {
|
|
||||||
day.values
|
|
||||||
.push(crate::analytics::models::AccountAnalyticsValue {
|
|
||||||
key: label.into(),
|
|
||||||
label: label.into(),
|
|
||||||
value: 0.0,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
for value in &mut day.values {
|
|
||||||
value.key = format!("remote-{}", value.key);
|
|
||||||
value.label = format!("Remote {}", value.label);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
history.data[6].total = 100.0;
|
|
||||||
for (value, amount) in history.data[6]
|
|
||||||
.values
|
|
||||||
.iter_mut()
|
|
||||||
.zip([91.1, 0.0, 6.8, 2.1, 0.0, 0.0])
|
|
||||||
{
|
|
||||||
value.value = amount;
|
|
||||||
}
|
|
||||||
view.sections[Section::Usage].history = Load::Ready(history);
|
|
||||||
|
|
||||||
for _ in 0..7 {
|
|
||||||
screen(&mut view, /*width*/ 100, /*height*/ 38);
|
|
||||||
let expected = if view.sections[Section::Usage].cursor == 6 {
|
|
||||||
[
|
|
||||||
("Remote GPT-5.6-Sol", 0),
|
|
||||||
("Remote GPT-5.5", 2),
|
|
||||||
("Remote Other", 3),
|
|
||||||
]
|
|
||||||
} else {
|
|
||||||
[
|
|
||||||
("Remote GPT-5.6-Sol", 0),
|
|
||||||
("Remote GPT-5.6-Terra", 1),
|
|
||||||
("Remote GPT-5.5", 2),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
.into_iter()
|
|
||||||
.map(|(label, color)| (label.to_string(), Some(styles::series_colors()[color])))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let legend = view
|
|
||||||
.history_lines(Section::Usage, /*width*/ 96, /*height*/ 10)
|
|
||||||
.lines
|
|
||||||
.into_iter()
|
|
||||||
.filter(|line| line.spans.first().is_some_and(|span| span.content == "● "))
|
|
||||||
.take(/*n*/ 3)
|
|
||||||
.map(|line| (line.spans[1].content.to_string(), line.spans[0].style.fg))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
assert_eq!(legend, expected);
|
|
||||||
press(&mut view, KeyCode::Left);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_empty_turns_keep_geometry_and_disable_details() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Consumer);
|
|
||||||
let mut history = fixture::history(/*report*/ 2, /*range*/ 0, /*group*/ 2);
|
|
||||||
history.data[5].total = 0.0;
|
|
||||||
for value in &mut history.data[5].values {
|
|
||||||
value.value = 0.0;
|
|
||||||
}
|
|
||||||
history.data.remove(/*index*/ 6);
|
|
||||||
view.sections[Section::Activity].history = Load::Ready(history);
|
|
||||||
press(&mut view, KeyCode::Char('3'));
|
|
||||||
for width in [58, 100] {
|
|
||||||
view.sections[Section::Activity].cursor = 4;
|
|
||||||
let populated = screen(&mut view, width, /*height*/ 38);
|
|
||||||
assert!(populated.contains("reported messages"));
|
|
||||||
assert!(populated.contains("details"));
|
|
||||||
let marker_row = populated.lines().position(|line| line.contains('▲'));
|
|
||||||
for cursor in [5, 6] {
|
|
||||||
view.sections[Section::Activity].cursor = cursor;
|
|
||||||
let empty = screen(&mut view, width, /*height*/ 38);
|
|
||||||
assert!(empty.contains(if cursor == 5 {
|
|
||||||
"No messages reported for"
|
|
||||||
} else {
|
|
||||||
"Data not reported for"
|
|
||||||
}));
|
|
||||||
assert!(!empty.contains("details"));
|
|
||||||
assert!(!empty.contains('●'));
|
|
||||||
assert_eq!(
|
|
||||||
empty.lines().position(|line| line.contains('▲')),
|
|
||||||
marker_row
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert_eq!(view.sections[Section::Activity].detail, None);
|
|
||||||
}
|
|
||||||
view.sections[Section::Activity].cursor = 4;
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert_eq!(view.sections[Section::Activity].detail, Some(4));
|
|
||||||
let expanded = screen(&mut view, width, /*height*/ 38);
|
|
||||||
let marker_row = expanded.lines().position(|line| line.contains('▲'));
|
|
||||||
press(&mut view, KeyCode::Right);
|
|
||||||
let empty = screen(&mut view, width, /*height*/ 38);
|
|
||||||
assert_eq!(
|
|
||||||
empty.lines().position(|line| line.contains('▲')),
|
|
||||||
marker_row
|
|
||||||
);
|
|
||||||
let details = view.sections[Section::Activity].detail;
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
assert_eq!(view.sections[Section::Activity].detail, details);
|
|
||||||
view.sections[Section::Activity].detail = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[path = "analytics/chat_panel_tests.rs"]
|
|
||||||
mod chats_table;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn analytics_details_reflow_and_keep_focus() {
|
|
||||||
let mut view = fixture::view(models::AccountKind::Enterprise);
|
|
||||||
view.chats = Load::Ready(fixture::chats());
|
|
||||||
press(&mut view, KeyCode::Char('6'));
|
|
||||||
press(&mut view, KeyCode::Enter);
|
|
||||||
screen(&mut view, /*width*/ 120, /*height*/ 42);
|
|
||||||
view.follow_selection = true;
|
|
||||||
let narrow = screen(&mut view, /*width*/ 58, /*height*/ 20);
|
|
||||||
assert!(narrow.contains("Q3 planning analysis") && narrow.contains("GPT-5.6-Sol"));
|
|
||||||
let before = (
|
|
||||||
view.section,
|
|
||||||
view.sections.0.each_ref().map(|state| state.cursor),
|
|
||||||
view.sections.0.each_ref().map(|state| state.detail),
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::PageDown);
|
|
||||||
screen(&mut view, /*width*/ 58, /*height*/ 20);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.section,
|
|
||||||
view.sections.0.each_ref().map(|state| state.cursor),
|
|
||||||
view.sections.0.each_ref().map(|state| state.detail)
|
|
||||||
),
|
|
||||||
before
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Tab);
|
|
||||||
press(&mut view, KeyCode::Char('6'));
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.section,
|
|
||||||
view.sections.0.each_ref().map(|state| state.cursor),
|
|
||||||
view.sections.0.each_ref().map(|state| state.detail)
|
|
||||||
),
|
|
||||||
before
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Esc);
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
view.is_done,
|
|
||||||
view.sections.0.each_ref().map(|state| state.detail)
|
|
||||||
),
|
|
||||||
(false, [None; 8])
|
|
||||||
);
|
|
||||||
press(&mut view, KeyCode::Esc);
|
|
||||||
assert!(view.is_done);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[path = "analytics/dashboard_tests.rs"]
|
|
||||||
mod dashboard;
|
|
||||||
|
|
||||||
#[path = "analytics/mouse_tests.rs"]
|
|
||||||
mod mouse;
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
//! Demand-driven dashboard usage. Only the selected task is fetched on a one-minute
|
|
||||||
//! refresh cadence, including after failures. Account changes and reconnects invalidate
|
|
||||||
//! pending billing results and disabled capability state.
|
|
||||||
|
|
||||||
use super::App;
|
|
||||||
use super::agents_overview::AGENTS_OVERVIEW_VIEW_ID;
|
|
||||||
use super::background_requests::THREAD_USAGE_FETCH_TIMEOUT;
|
|
||||||
use super::background_requests::fetch_thread_usage;
|
|
||||||
use crate::app_event::AppEvent;
|
|
||||||
use crate::app_server_session::AppServerSession;
|
|
||||||
use crate::chatwidget::ThreadUsageOutcome;
|
|
||||||
use crate::status::format_credit_micros;
|
|
||||||
use crate::status::format_estimated_usd_micros;
|
|
||||||
use crate::status::format_tokens_compact;
|
|
||||||
use crate::status::thread_cost_micros;
|
|
||||||
use crate::tui::FrameRequester;
|
|
||||||
use codex_app_server_protocol::ThreadUsage;
|
|
||||||
use codex_app_server_protocol::ThreadUsageBreakdownGroup;
|
|
||||||
use codex_app_server_protocol::TokenUsageBreakdown;
|
|
||||||
use codex_protocol::ThreadId;
|
|
||||||
use codex_protocol::account::PlanType;
|
|
||||||
use ratatui::style::Stylize;
|
|
||||||
use ratatui::text::Line;
|
|
||||||
use std::time::Duration;
|
|
||||||
use std::time::Instant;
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
const REFRESH_INTERVAL: Duration = Duration::from_secs(/*secs*/ 60);
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(super) struct AgentsOverviewUsage {
|
|
||||||
pub(super) tokens: Option<TokenUsageBreakdown>,
|
|
||||||
pub(super) estimate: Option<ThreadUsage>,
|
|
||||||
fetched_at: Option<Instant>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl App {
|
|
||||||
pub(super) fn refresh_agents_overview_usage(
|
|
||||||
&mut self,
|
|
||||||
app_server: &AppServerSession,
|
|
||||||
frame_requester: FrameRequester,
|
|
||||||
) {
|
|
||||||
if self.reconnect.offline
|
|
||||||
|| self.agents_overview.usage_disabled
|
|
||||||
|| self.agents_overview.pending_usage.is_some()
|
|
||||||
|| !self.chat_widget.has_codex_backend_auth()
|
|
||||||
|| !matches!(
|
|
||||||
self.chat_widget.current_plan_type(),
|
|
||||||
Some(
|
|
||||||
PlanType::Ent26
|
|
||||||
| PlanType::Business
|
|
||||||
| PlanType::EnterpriseCbpUsageBased
|
|
||||||
| PlanType::EnterpriseCbpAutomation
|
|
||||||
)
|
|
||||||
)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let Some(thread_id) = self
|
|
||||||
.chat_widget
|
|
||||||
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)
|
|
||||||
.and_then(|index| self.agents_overview.visible_thread_ids.get(index))
|
|
||||||
.copied()
|
|
||||||
else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
if let Some(age) = self
|
|
||||||
.agents_overview
|
|
||||||
.usage
|
|
||||||
.get(&thread_id)
|
|
||||||
.and_then(|usage| usage.fetched_at)
|
|
||||||
.map(|fetched| fetched.elapsed())
|
|
||||||
&& age < REFRESH_INTERVAL
|
|
||||||
{
|
|
||||||
frame_requester.schedule_frame_in(REFRESH_INTERVAL - age);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let request_id = Uuid::new_v4();
|
|
||||||
self.agents_overview.pending_usage = Some((thread_id, request_id));
|
|
||||||
let request_handle = app_server.request_handle();
|
|
||||||
let app_event_tx = self.app_event_tx.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let result = tokio::time::timeout(
|
|
||||||
THREAD_USAGE_FETCH_TIMEOUT,
|
|
||||||
fetch_thread_usage(request_handle, thread_id),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(|_| "dashboard usage request timed out".to_string())
|
|
||||||
.and_then(|result| result.map_err(|error| error.to_string()));
|
|
||||||
app_event_tx.send(AppEvent::AgentsOverviewUsageLoaded {
|
|
||||||
thread_id,
|
|
||||||
request_id,
|
|
||||||
result,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn finish_agents_overview_usage(
|
|
||||||
&mut self,
|
|
||||||
thread_id: ThreadId,
|
|
||||||
request_id: Uuid,
|
|
||||||
result: Result<ThreadUsageOutcome, String>,
|
|
||||||
) {
|
|
||||||
if self.agents_overview.pending_usage != Some((thread_id, request_id)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.agents_overview.pending_usage = None;
|
|
||||||
if self.agents_overview.threads.contains_key(&thread_id)
|
|
||||||
|| self.agents_overview.search_matches.contains_key(&thread_id)
|
|
||||||
{
|
|
||||||
let usage = self.agents_overview.usage.entry(thread_id).or_default();
|
|
||||||
usage.fetched_at = Some(Instant::now());
|
|
||||||
match result {
|
|
||||||
Ok(ThreadUsageOutcome::Available(mut estimate))
|
|
||||||
if estimate.thread_id == thread_id.to_string() =>
|
|
||||||
{
|
|
||||||
if let Some(previous) = &usage.estimate {
|
|
||||||
let zero_credits = estimate.estimated_usage_credits_micros == 0
|
|
||||||
&& previous.estimated_usage_credits_micros > 0;
|
|
||||||
let zero_cost = estimate.estimated_usage_usd_micros == Some(0)
|
|
||||||
&& previous
|
|
||||||
.estimated_usage_usd_micros
|
|
||||||
.is_some_and(|cost| cost > 0);
|
|
||||||
if zero_credits {
|
|
||||||
estimate.estimated_usage_credits_micros =
|
|
||||||
previous.estimated_usage_credits_micros;
|
|
||||||
}
|
|
||||||
if zero_cost {
|
|
||||||
estimate.estimated_usage_usd_micros =
|
|
||||||
previous.estimated_usage_usd_micros;
|
|
||||||
}
|
|
||||||
if (zero_credits || zero_cost) && estimate.groups.is_empty() {
|
|
||||||
estimate.groups.clone_from(&previous.groups);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
usage.estimate = Some(estimate);
|
|
||||||
}
|
|
||||||
Ok(ThreadUsageOutcome::Disabled) => {
|
|
||||||
self.agents_overview.usage_disabled = true;
|
|
||||||
for usage in self.agents_overview.usage.values_mut() {
|
|
||||||
usage.estimate = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(ThreadUsageOutcome::Available(_)) | Err(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.repaint_agents_overview();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn usage_lines(
|
|
||||||
usage: &AgentsOverviewUsage,
|
|
||||||
plan_type: Option<PlanType>,
|
|
||||||
) -> Vec<Line<'static>> {
|
|
||||||
let sum = |count: fn(&ThreadUsageBreakdownGroup) -> Option<i64>| {
|
|
||||||
let groups = &usage.estimate.as_ref()?.groups;
|
|
||||||
if groups.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
groups.iter().try_fold(/*init*/ 0_i64, |total, group| {
|
|
||||||
count(group)
|
|
||||||
.filter(|tokens| *tokens >= 0)
|
|
||||||
.map(|tokens| total.saturating_add(tokens))
|
|
||||||
})
|
|
||||||
};
|
|
||||||
let input = usage
|
|
||||||
.tokens
|
|
||||||
.as_ref()
|
|
||||||
.map(|tokens| tokens.input_tokens)
|
|
||||||
.or_else(|| sum(|group| group.input_tokens));
|
|
||||||
let output = usage
|
|
||||||
.tokens
|
|
||||||
.as_ref()
|
|
||||||
.map(|tokens| tokens.output_tokens)
|
|
||||||
.or_else(|| sum(|group| group.output_tokens));
|
|
||||||
let mut lines = Vec::new();
|
|
||||||
let mut tokens = Vec::new();
|
|
||||||
if let Some(input) = input {
|
|
||||||
tokens.push(format!("{} in", format_tokens_compact(input)));
|
|
||||||
}
|
|
||||||
if let Some(output) = output {
|
|
||||||
tokens.push(format!("{} out", format_tokens_compact(output)));
|
|
||||||
}
|
|
||||||
if !tokens.is_empty() {
|
|
||||||
lines.push(vec!["Tokens: ".dim(), tokens.join(" · ").into()].into());
|
|
||||||
}
|
|
||||||
if let Some(estimate) = &usage.estimate {
|
|
||||||
let mut values = Vec::new();
|
|
||||||
if plan_type != Some(PlanType::Ent26) && estimate.estimated_usage_credits_micros >= 0 {
|
|
||||||
values.push(format!(
|
|
||||||
"{} credits",
|
|
||||||
format_credit_micros(estimate.estimated_usage_credits_micros)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if let Some(cost) =
|
|
||||||
thread_cost_micros(estimate, plan_type).and_then(format_estimated_usd_micros)
|
|
||||||
{
|
|
||||||
values.push(cost);
|
|
||||||
}
|
|
||||||
if !values.is_empty() {
|
|
||||||
lines.push(vec!["Est. usage: ".dim(), values.join(" · ").into()].into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
lines
|
|
||||||
}
|
|
||||||
@@ -1,281 +0,0 @@
|
|||||||
use super::*;
|
|
||||||
use crate::app::agents_overview_usage::AgentsOverviewUsage;
|
|
||||||
use crate::app::agents_overview_usage::usage_lines;
|
|
||||||
use crate::chatwidget::ThreadUsageOutcome;
|
|
||||||
use codex_app_server_protocol::AccountUpdatedNotification;
|
|
||||||
use codex_app_server_protocol::ThreadTokenUsage;
|
|
||||||
use codex_app_server_protocol::ThreadTokenUsageUpdatedNotification;
|
|
||||||
use codex_app_server_protocol::ThreadUsage;
|
|
||||||
use codex_app_server_protocol::TokenUsageBreakdown;
|
|
||||||
use codex_protocol::account::PlanType;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn selected_usage_is_cached_and_account_changes_discard_old_results() -> Result<()> {
|
|
||||||
let mut app = make_test_app_with_chat().await;
|
|
||||||
let app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
|
||||||
app.chat_widget.update_account_state(
|
|
||||||
/*status_account_display*/ None,
|
|
||||||
Some(PlanType::Business),
|
|
||||||
/*has_chatgpt_account*/ false,
|
|
||||||
/*has_codex_backend_auth*/ true,
|
|
||||||
);
|
|
||||||
let selected = ThreadId::from_u128(/*value*/ 1);
|
|
||||||
let other = ThreadId::new();
|
|
||||||
let threads = [(selected, "Review parser"), (other, "Other task")].map(|(id, name)| {
|
|
||||||
overview_thread(id, /*parent_thread_id*/ None, name, ThreadStatus::Idle)
|
|
||||||
});
|
|
||||||
app.agents_overview.threads = threads
|
|
||||||
.iter()
|
|
||||||
.cloned()
|
|
||||||
.map(|thread| (ThreadId::from_string(&thread.id).unwrap(), Some(thread)))
|
|
||||||
.collect();
|
|
||||||
let view = app.agents_overview_view(threads.to_vec(), Some(selected));
|
|
||||||
app.agents_overview.visible_thread_ids = view.thread_ids();
|
|
||||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
|
||||||
let thread_id = selected;
|
|
||||||
let request_id = Uuid::new_v4();
|
|
||||||
let result = ThreadUsageOutcome::Available(serde_json::from_value(serde_json::json!({
|
|
||||||
"threadId": selected.to_string(),
|
|
||||||
"estimatedUsageCreditsMicros": 3_400_000,
|
|
||||||
"estimatedUsageUsdMicros": 140_000,
|
|
||||||
"groups": [{"estimatedUsageCreditsMicros": 3_400_000, "inputTokens": 12_000, "outputTokens": 3_000}]
|
|
||||||
})).unwrap());
|
|
||||||
let tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
app.agents_overview.pending_usage = Some((thread_id, request_id));
|
|
||||||
app.refresh_agents_overview_usage(&app_server, tui.frame_requester());
|
|
||||||
assert_eq!(
|
|
||||||
app.agents_overview.pending_usage,
|
|
||||||
Some((thread_id, request_id))
|
|
||||||
);
|
|
||||||
app.finish_agents_overview_usage(thread_id, request_id, Ok(result.clone()));
|
|
||||||
app.refresh_agents_overview_usage(&app_server, tui.frame_requester());
|
|
||||||
assert_eq!(app.agents_overview.pending_usage, None);
|
|
||||||
|
|
||||||
let ThreadUsageOutcome::Available(mut expected) = result.clone() else {
|
|
||||||
panic!("expected usage estimate")
|
|
||||||
};
|
|
||||||
for (credits, cost, expected_credits) in [(0, 200_000, 3_400_000), (5_000_000, 0, 5_000_000)] {
|
|
||||||
let mut settlement = expected.clone();
|
|
||||||
settlement.estimated_usage_credits_micros = credits;
|
|
||||||
settlement.estimated_usage_usd_micros = Some(cost);
|
|
||||||
settlement.groups.clear();
|
|
||||||
expected.estimated_usage_credits_micros = expected_credits;
|
|
||||||
expected.estimated_usage_usd_micros = Some(200_000);
|
|
||||||
app.agents_overview.pending_usage = Some((thread_id, request_id));
|
|
||||||
app.finish_agents_overview_usage(
|
|
||||||
thread_id,
|
|
||||||
request_id,
|
|
||||||
Ok(ThreadUsageOutcome::Available(settlement)),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
app.agents_overview.usage[&selected].estimate,
|
|
||||||
Some(expected.clone())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let tokens = TokenUsageBreakdown {
|
|
||||||
total_tokens: 17_000,
|
|
||||||
input_tokens: 13_000,
|
|
||||||
cached_input_tokens: 1_000,
|
|
||||||
cache_write_input_tokens: 0,
|
|
||||||
output_tokens: 4_000,
|
|
||||||
reasoning_output_tokens: 0,
|
|
||||||
};
|
|
||||||
app.agents_overview.threads.remove(&selected);
|
|
||||||
app.agents_overview.request_id = Some(request_id);
|
|
||||||
app.track_agents_overview_notification(&ServerNotification::ThreadTokenUsageUpdated(
|
|
||||||
ThreadTokenUsageUpdatedNotification {
|
|
||||||
thread_id: selected.to_string(),
|
|
||||||
turn_id: "turn".into(),
|
|
||||||
token_usage: ThreadTokenUsage {
|
|
||||||
total: tokens.clone(),
|
|
||||||
last: tokens.clone(),
|
|
||||||
model_context_window: None,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
));
|
|
||||||
app.apply_agents_overview_thread_refresh(
|
|
||||||
&app_server,
|
|
||||||
request_id,
|
|
||||||
Ok(AgentsOverviewThreadRefresh {
|
|
||||||
cleared_unread: Vec::new(),
|
|
||||||
threads: HashMap::from([(selected, Some((threads[0].clone(), false, None)))]),
|
|
||||||
last_messages: HashMap::new(),
|
|
||||||
recent_seed_complete: true,
|
|
||||||
discovery: None,
|
|
||||||
pinned_thread_ids: None,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
app.agents_overview.usage[&selected].tokens,
|
|
||||||
Some(tokens.clone())
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
render_bottom_popup(&app.chat_widget, /*width*/ 96).contains("Tokens: 13K in · 4K out")
|
|
||||||
);
|
|
||||||
let mut view = app.agents_overview_view(threads.to_vec(), Some(selected));
|
|
||||||
let row = view
|
|
||||||
.rows
|
|
||||||
.iter_mut()
|
|
||||||
.find(|row| row.thread_id == selected)
|
|
||||||
.unwrap();
|
|
||||||
row.group = AgentsOverviewGroup::NeedsYou;
|
|
||||||
row.details.lines = vec![
|
|
||||||
Line::default(),
|
|
||||||
"Needs attention".into(),
|
|
||||||
"Which dependency version should I use?".into(),
|
|
||||||
"Open task to review.".into(),
|
|
||||||
];
|
|
||||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
|
||||||
let project = test_path_display("/tmp/project");
|
|
||||||
let group = format!(
|
|
||||||
"/tmp/project 2{}",
|
|
||||||
" ".repeat(project.len().saturating_sub("/tmp/project".len()))
|
|
||||||
);
|
|
||||||
insta::assert_snapshot!(
|
|
||||||
"agents_overview_usage",
|
|
||||||
render_bottom_popup(&app.chat_widget, /*width*/ 96)
|
|
||||||
.replace(&format!("{project} 2"), &group)
|
|
||||||
.replace(&project, "/tmp/project")
|
|
||||||
.replace("fwd del", "del")
|
|
||||||
);
|
|
||||||
for notification in [
|
|
||||||
ServerNotification::ThreadReverted(codex_app_server_protocol::ThreadRevertedNotification {
|
|
||||||
thread_id: selected.to_string(),
|
|
||||||
}),
|
|
||||||
ServerNotification::ThreadClosed(ThreadClosedNotification {
|
|
||||||
thread_id: selected.to_string(),
|
|
||||||
}),
|
|
||||||
] {
|
|
||||||
app.agents_overview.usage.get_mut(&selected).unwrap().tokens = Some(tokens.clone());
|
|
||||||
app.track_agents_overview_notification(¬ification);
|
|
||||||
assert_eq!(app.agents_overview.usage[&selected].tokens, None);
|
|
||||||
}
|
|
||||||
assert_eq!(
|
|
||||||
app.agents_overview.usage[&selected].estimate,
|
|
||||||
Some(expected.clone())
|
|
||||||
);
|
|
||||||
let other_usage = app.agents_overview.usage.entry(other).or_default();
|
|
||||||
other_usage.estimate = Some(expected.clone());
|
|
||||||
other_usage.tokens = Some(tokens.clone());
|
|
||||||
app.agents_overview.pending_usage = Some((thread_id, request_id));
|
|
||||||
app.finish_agents_overview_usage(thread_id, request_id, Ok(ThreadUsageOutcome::Disabled));
|
|
||||||
assert!(
|
|
||||||
app.agents_overview
|
|
||||||
.usage
|
|
||||||
.values()
|
|
||||||
.all(|usage| usage.estimate.is_none())
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
app.agents_overview.usage[&other].tokens,
|
|
||||||
Some(tokens.clone())
|
|
||||||
);
|
|
||||||
// A different selection must not retry an unavailable account-wide capability.
|
|
||||||
let view = app.agents_overview_view(threads.to_vec(), Some(other));
|
|
||||||
app.agents_overview.visible_thread_ids = view.thread_ids();
|
|
||||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
|
||||||
app.refresh_agents_overview_usage(&app_server, tui.frame_requester());
|
|
||||||
assert!(app.agents_overview.usage_disabled);
|
|
||||||
assert_eq!(app.agents_overview.pending_usage, None);
|
|
||||||
for event in [
|
|
||||||
AppServerEvent::Lagged { skipped: 1 },
|
|
||||||
AppServerEvent::ServerNotification(Box::new(ServerNotification::AccountUpdated(
|
|
||||||
AccountUpdatedNotification {
|
|
||||||
auth_mode: None,
|
|
||||||
plan_type: None,
|
|
||||||
},
|
|
||||||
))),
|
|
||||||
] {
|
|
||||||
app.agents_overview
|
|
||||||
.usage
|
|
||||||
.entry(selected)
|
|
||||||
.or_default()
|
|
||||||
.tokens = Some(tokens.clone());
|
|
||||||
app.agents_overview.pending_usage = Some((thread_id, request_id));
|
|
||||||
app.agents_overview.usage_disabled = true;
|
|
||||||
app.handle_app_server_event(&app_server, event).await;
|
|
||||||
app.finish_agents_overview_usage(thread_id, request_id, Ok(result.clone()));
|
|
||||||
assert!(app.agents_overview.usage.is_empty());
|
|
||||||
assert_eq!(app.agents_overview.pending_usage, None);
|
|
||||||
assert!(!app.agents_overview.usage_disabled);
|
|
||||||
}
|
|
||||||
app.chat_widget.update_account_state(
|
|
||||||
/*status_account_display*/ None,
|
|
||||||
Some(PlanType::Ent26),
|
|
||||||
/*has_chatgpt_account*/ false,
|
|
||||||
/*has_codex_backend_auth*/ true,
|
|
||||||
);
|
|
||||||
let view = app.agents_overview_view(threads.to_vec(), Some(selected));
|
|
||||||
app.agents_overview.visible_thread_ids = view.thread_ids();
|
|
||||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
|
||||||
app.refresh_agents_overview_usage(&app_server, tui.frame_requester());
|
|
||||||
let (thread_id, request_id) = app
|
|
||||||
.agents_overview
|
|
||||||
.pending_usage
|
|
||||||
.expect("request ENT26 usage");
|
|
||||||
assert_eq!(thread_id, selected);
|
|
||||||
let mut native_usage = expected.clone();
|
|
||||||
native_usage.estimated_usage_credits_micros = 0;
|
|
||||||
native_usage.estimated_usage_usd_micros = Some(0);
|
|
||||||
native_usage.native_usage_usd_micros = Some(750_000);
|
|
||||||
app.finish_agents_overview_usage(
|
|
||||||
thread_id,
|
|
||||||
request_id,
|
|
||||||
Ok(ThreadUsageOutcome::Available(native_usage)),
|
|
||||||
);
|
|
||||||
let view = app.agents_overview_view(threads.to_vec(), Some(selected));
|
|
||||||
let rendered = view
|
|
||||||
.rows
|
|
||||||
.iter()
|
|
||||||
.find(|row| row.thread_id == selected)
|
|
||||||
.unwrap()
|
|
||||||
.details
|
|
||||||
.usage_lines
|
|
||||||
.iter()
|
|
||||||
.map(ToString::to_string)
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
insta::assert_snapshot!(rendered, @"
|
|
||||||
Tokens: 12K in · 3K out
|
|
||||||
Est. usage: ~$0.75
|
|
||||||
");
|
|
||||||
|
|
||||||
app.agents_overview.usage_disabled = true;
|
|
||||||
app.agents_overview.pending_usage = Some((thread_id, request_id));
|
|
||||||
app.app_server_target = AppServerTarget::LocalDaemon {
|
|
||||||
allow_embedded_fallback: true,
|
|
||||||
endpoint: crate::RemoteAppServerEndpoint::UnixSocket {
|
|
||||||
socket_path: test_path_buf("/tmp/test.sock").abs(),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
assert!(app.begin_reconnect());
|
|
||||||
app.finish_agents_overview_usage(
|
|
||||||
thread_id,
|
|
||||||
request_id,
|
|
||||||
Ok(ThreadUsageOutcome::Available(expected)),
|
|
||||||
);
|
|
||||||
assert!(app.agents_overview.usage.is_empty());
|
|
||||||
assert_eq!(app.agents_overview.pending_usage, None);
|
|
||||||
assert!(!app.agents_overview.usage_disabled);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn incomplete_billing_groups_do_not_display_partial_token_totals() {
|
|
||||||
let estimate: ThreadUsage = serde_json::from_value(serde_json::json!({
|
|
||||||
"threadId": "thread", "estimatedUsageCreditsMicros": 0, "estimatedUsageUsdMicros": null,
|
|
||||||
"groups": [
|
|
||||||
{"estimatedUsageCreditsMicros": 0, "inputTokens": 100, "outputTokens": 10},
|
|
||||||
{"estimatedUsageCreditsMicros": 0, "inputTokens": null, "outputTokens": 20}
|
|
||||||
]
|
|
||||||
}))
|
|
||||||
.unwrap();
|
|
||||||
let mut usage = AgentsOverviewUsage::default();
|
|
||||||
usage.estimate = Some(estimate);
|
|
||||||
let text = usage_lines(&usage, Some(PlanType::Business))
|
|
||||||
.into_iter()
|
|
||||||
.map(|line| line.to_string())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
assert_eq!(text, vec!["Tokens: 30 out", "Est. usage: 0 credits"]);
|
|
||||||
}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
//! Apply backend-authorized fallback and task-local Reserve settings without saving defaults.
|
|
||||||
|
|
||||||
use super::App;
|
|
||||||
use crate::app_event::AppEvent;
|
|
||||||
use crate::app_server_session::AppServerSession;
|
|
||||||
use crate::chatwidget::AutomaticModelSwitchReason;
|
|
||||||
use crate::model_catalog::LUNA_RESERVE_MODEL;
|
|
||||||
use crate::model_catalog::model_display_name;
|
|
||||||
use crate::service_tier_resolution;
|
|
||||||
use codex_app_server_protocol::ThreadSettingsUpdateParams;
|
|
||||||
use codex_protocol::ThreadId;
|
|
||||||
use codex_protocol::config_types::ModeKind;
|
|
||||||
use codex_protocol::openai_models::ReasoningEffort;
|
|
||||||
|
|
||||||
impl App {
|
|
||||||
pub(super) async fn update_luna_reserve_reasoning(
|
|
||||||
&mut self,
|
|
||||||
app_server: &mut AppServerSession,
|
|
||||||
thread_id: ThreadId,
|
|
||||||
effort: Option<ReasoningEffort>,
|
|
||||||
) {
|
|
||||||
// A picker left open during recovery or a task switch must not affect the new model.
|
|
||||||
if self.active_thread_id != Some(thread_id)
|
|
||||||
|| self.chat_widget.thread_id() != Some(thread_id)
|
|
||||||
|| self.chat_widget.current_model() != LUNA_RESERVE_MODEL
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.app_event_tx.send(AppEvent::FollowTranscript);
|
|
||||||
let mut mode = self.chat_widget.effective_collaboration_mode();
|
|
||||||
mode.settings.reasoning_effort = effort.clone();
|
|
||||||
let params = ThreadSettingsUpdateParams {
|
|
||||||
thread_id: thread_id.to_string(),
|
|
||||||
effort: effort.clone(),
|
|
||||||
collaboration_mode: Some(mode.clone()),
|
|
||||||
..ThreadSettingsUpdateParams::default()
|
|
||||||
};
|
|
||||||
if self.send_thread_settings_update(app_server, params).await {
|
|
||||||
self.chat_widget.set_reasoning_effort(effort.clone());
|
|
||||||
if mode.mode == ModeKind::Plan {
|
|
||||||
self.chat_widget.set_plan_mode_reasoning_effort(effort);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn apply_backend_banner_fallback(
|
|
||||||
&mut self,
|
|
||||||
app_server: &mut AppServerSession,
|
|
||||||
) {
|
|
||||||
// Reattached tasks must wait for the read that supersedes the latest hard stop.
|
|
||||||
if self.rate_limit_refresh_state.has_pending_recovery() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let Some(thread_id) = self.active_thread_id else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
if Some(thread_id) != self.chat_widget.thread_id() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let Some(switch) = self.chat_widget.backend_banner_fallback() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let target = switch.model;
|
|
||||||
let entering_reserve = target.model == crate::model_catalog::LUNA_RESERVE_MODEL;
|
|
||||||
if entering_reserve && !self.chat_widget.prepare_luna_reserve_return() {
|
|
||||||
self.chat_widget.show_unavailable_reserve_recovery();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let effort = switch
|
|
||||||
.effort
|
|
||||||
.filter(|effort| {
|
|
||||||
target
|
|
||||||
.supported_reasoning_efforts
|
|
||||||
.iter()
|
|
||||||
.any(|option| option.effort == *effort)
|
|
||||||
})
|
|
||||||
.unwrap_or(target.default_reasoning_effort);
|
|
||||||
let mut mode = self.chat_widget.effective_collaboration_mode();
|
|
||||||
mode.settings.model = target.model.clone();
|
|
||||||
mode.settings.reasoning_effort = Some(effort.clone());
|
|
||||||
// Automatic recovery must not apply the permission defaults used by manual model selection.
|
|
||||||
let params = ThreadSettingsUpdateParams {
|
|
||||||
thread_id: thread_id.to_string(),
|
|
||||||
model: Some(target.model.clone()),
|
|
||||||
effort: Some(effort.clone()),
|
|
||||||
collaboration_mode: Some(mode.clone()),
|
|
||||||
service_tier: service_tier_resolution::service_tier_update_for_core(
|
|
||||||
self.chat_widget.config_ref(),
|
|
||||||
&self.local_settings.notices,
|
|
||||||
&target.model,
|
|
||||||
&self.model_catalog.try_list_models().unwrap_or_default(),
|
|
||||||
),
|
|
||||||
..ThreadSettingsUpdateParams::default()
|
|
||||||
};
|
|
||||||
// Older remote servers can decline this method. Keep the existing recovery UI in that
|
|
||||||
// case or on failure, rather than changing local selection before the task accepts it.
|
|
||||||
// Event dispatch awaits this operation; a queued manual model selection runs afterward.
|
|
||||||
if self.send_thread_settings_update(app_server, params).await {
|
|
||||||
self.chat_widget.finish_backend_banner_fallback(mode);
|
|
||||||
self.sync_active_thread_service_tier_to_cached_session()
|
|
||||||
.await;
|
|
||||||
let (prefix, suffix) = match switch.reason {
|
|
||||||
AutomaticModelSwitchReason::UsageLimit => {
|
|
||||||
("Automatically switched to", " due to usage limits.")
|
|
||||||
}
|
|
||||||
AutomaticModelSwitchReason::UsageRecovered => (
|
|
||||||
"Automatically switched back to",
|
|
||||||
" because ordinary usage is available again.",
|
|
||||||
),
|
|
||||||
};
|
|
||||||
let mut message = format!("{prefix} {}", model_display_name(&target.model));
|
|
||||||
if let Some(label) = Self::reasoning_label_for(&target.model, Some(&effort)) {
|
|
||||||
message.push(' ');
|
|
||||||
message.push_str(&label);
|
|
||||||
}
|
|
||||||
message.push_str(suffix);
|
|
||||||
self.chat_widget.add_info_message(message, /*hint*/ None);
|
|
||||||
} else if entering_reserve {
|
|
||||||
self.chat_widget.show_unavailable_reserve_recovery();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
//! Orders full usage reads and coalesces recovery refreshes within an account/limit generation.
|
|
||||||
//! Periodic reads share that ordering and wait while another periodic read or recovery is pending.
|
|
||||||
|
|
||||||
use crate::app_event::RateLimitRefreshOrigin;
|
|
||||||
use std::time::Duration;
|
|
||||||
use std::time::Instant;
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(super) struct RateLimitRefreshState {
|
|
||||||
next_id: u64,
|
|
||||||
applied_id: u64,
|
|
||||||
recovery: Option<PendingRecovery>,
|
|
||||||
periodic: Option<(u64, u64)>,
|
|
||||||
last_requested_at: Option<Instant>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct PendingRecovery {
|
|
||||||
request: (u64, u64),
|
|
||||||
origin: RateLimitRefreshOrigin,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
pub(super) enum RateLimitRefreshOutcome {
|
|
||||||
Apply,
|
|
||||||
Ignore,
|
|
||||||
RefreshRecovery,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(PartialEq, Eq)]
|
|
||||||
pub(super) enum RateLimitReadStatus {
|
|
||||||
Succeeded,
|
|
||||||
Failed,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RateLimitRefreshState {
|
|
||||||
pub(super) fn poll_deadline(&self, interval: Duration) -> Option<Instant> {
|
|
||||||
if self.periodic.is_some() || self.recovery.is_some() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
Some(
|
|
||||||
self.last_requested_at
|
|
||||||
.map(|last| last + interval)
|
|
||||||
.unwrap_or_else(Instant::now),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn has_pending_recovery(&self) -> bool {
|
|
||||||
self.recovery.is_some()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn start(
|
|
||||||
&mut self,
|
|
||||||
origin: RateLimitRefreshOrigin,
|
|
||||||
generation: &mut u64,
|
|
||||||
) -> Option<(u64, u64)> {
|
|
||||||
if origin == RateLimitRefreshOrigin::Periodic
|
|
||||||
&& (self.periodic.is_some() || self.recovery.is_some())
|
|
||||||
{
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
if matches!(origin, RateLimitRefreshOrigin::Recovery) {
|
|
||||||
// A new hard error supersedes a post-reset read that started before the error.
|
|
||||||
if self
|
|
||||||
.recovery
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|pending| pending.origin == RateLimitRefreshOrigin::Recovery)
|
|
||||||
{
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
// A hard error invalidates even an older read without a preceding rolling notification.
|
|
||||||
*generation = generation.wrapping_add(1);
|
|
||||||
}
|
|
||||||
self.next_id = self.next_id.wrapping_add(1);
|
|
||||||
let request = (self.next_id, *generation);
|
|
||||||
self.last_requested_at = Some(Instant::now());
|
|
||||||
if origin == RateLimitRefreshOrigin::Periodic {
|
|
||||||
self.periodic = Some(request);
|
|
||||||
}
|
|
||||||
// The post-reset read takes over the hold from the invalidated recovery request.
|
|
||||||
if matches!(
|
|
||||||
origin,
|
|
||||||
RateLimitRefreshOrigin::Recovery | RateLimitRefreshOrigin::ResetConsume { .. }
|
|
||||||
) {
|
|
||||||
self.recovery = Some(PendingRecovery { request, origin });
|
|
||||||
}
|
|
||||||
Some(request)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Account changes and successful resets invalidate the need as well as the old response.
|
|
||||||
pub(super) fn invalidate_recovery(&mut self) {
|
|
||||||
self.recovery = None;
|
|
||||||
self.periodic = None;
|
|
||||||
self.last_requested_at = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn finish(
|
|
||||||
&mut self,
|
|
||||||
request_id: u64,
|
|
||||||
generation: u64,
|
|
||||||
current_generation: u64,
|
|
||||||
status: RateLimitReadStatus,
|
|
||||||
) -> RateLimitRefreshOutcome {
|
|
||||||
if self.periodic == Some((request_id, generation)) {
|
|
||||||
self.periodic = None;
|
|
||||||
}
|
|
||||||
if generation == current_generation && request_id == self.next_id {
|
|
||||||
// Completion starts the next wait, including after failures/timeouts, so errors
|
|
||||||
// cannot create a tight retry loop while the account is nearly exhausted.
|
|
||||||
self.last_requested_at = Some(Instant::now());
|
|
||||||
}
|
|
||||||
if self
|
|
||||||
.recovery
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|pending| pending.request == (request_id, generation))
|
|
||||||
{
|
|
||||||
self.recovery = None;
|
|
||||||
// A rolling hard stop can arrive after the error, without another error notification.
|
|
||||||
if generation != current_generation {
|
|
||||||
return RateLimitRefreshOutcome::RefreshRecovery;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if generation != current_generation
|
|
||||||
|| request_id < self.applied_id
|
|
||||||
|| status == RateLimitReadStatus::Failed
|
|
||||||
{
|
|
||||||
return RateLimitRefreshOutcome::Ignore;
|
|
||||||
}
|
|
||||||
self.applied_id = request_id;
|
|
||||||
RateLimitRefreshOutcome::Apply
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,505 +0,0 @@
|
|||||||
use super::*;
|
|
||||||
use crate::chatwidget::UserMessage;
|
|
||||||
use crate::chatwidget::tests::helpers::normalize_snapshot_paths;
|
|
||||||
use crate::chatwidget::tests::helpers::set_fast_mode_test_catalog_for_models;
|
|
||||||
use codex_app_server_protocol::GetAccountRateLimitsResponse;
|
|
||||||
use codex_app_server_protocol::ThreadSettingsUpdateParams;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
pub(super) fn fallback_response() -> GetAccountRateLimitsResponse {
|
|
||||||
serde_json::from_value(json!({
|
|
||||||
"accountId": "workspace-a", "rateLimits": {},
|
|
||||||
"rateLimitUpsell": {
|
|
||||||
"banner_type": "model_recovery", "model_slug": "gpt-5.5",
|
|
||||||
"blocked_model_slug": "gpt-5.5",
|
|
||||||
"fallback_model_slugs": ["unavailable-model", "gpt-5.5", "gpt-5.6-terra"],
|
|
||||||
"title": "Selected model usage exhausted",
|
|
||||||
"description": "Add credits to use this model again.",
|
|
||||||
"presentation": "dismissible",
|
|
||||||
"ctas": [{"action": "view_usage", "label": "View usage"}]
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_fallback_model(app: &mut App) {
|
|
||||||
set_chatgpt_auth(&mut app.chat_widget);
|
|
||||||
set_fast_mode_test_catalog_for_models(&mut app.chat_widget, "gpt-5.5", "gpt-5.6-terra");
|
|
||||||
app.model_catalog = app.chat_widget.model_catalog();
|
|
||||||
app.chat_widget.set_model("gpt-5.5");
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) async fn start_fallback_thread(
|
|
||||||
app: &mut App,
|
|
||||||
) -> Result<session_lifecycle_requests::RecordingAppServer> {
|
|
||||||
let (mut server, requests, proxy) = session_lifecycle_requests::start_recording_app_server(
|
|
||||||
&app.config,
|
|
||||||
/*blocked_thread_list*/ None,
|
|
||||||
/*failed_thread_name*/ None,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let started = server.start_thread(&app.config).await?;
|
|
||||||
app.enqueue_primary_thread_session(started.session, started.turns)
|
|
||||||
.await?;
|
|
||||||
configure_fallback_model(app);
|
|
||||||
Ok((server, requests, proxy))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_fallback_updates_task_settings_and_keeps_notice() -> Result<()> {
|
|
||||||
for mode_kind in [ModeKind::Default, ModeKind::Plan] {
|
|
||||||
let (mut app, mut events, mut ops) = make_test_app_with_channels().await;
|
|
||||||
let (mut server, requests, proxy) = start_fallback_thread(&mut app).await?;
|
|
||||||
let thread_id = app.active_thread_id.expect("active fallback thread");
|
|
||||||
app.chat_widget
|
|
||||||
.set_reasoning_effort(Some(ReasoningEffortConfig::Medium));
|
|
||||||
if mode_kind == ModeKind::Plan {
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::from(KeyCode::BackTab));
|
|
||||||
app.chat_widget
|
|
||||||
.set_plan_mode_reasoning_effort(Some(ReasoningEffortConfig::High));
|
|
||||||
}
|
|
||||||
app.chat_widget
|
|
||||||
.set_feature_enabled(Feature::FastMode, /*enabled*/ true);
|
|
||||||
app.chat_widget
|
|
||||||
.set_service_tier(Some(ServiceTier::Fast.request_value().to_string()));
|
|
||||||
let mut expected_mode = app.chat_widget.effective_collaboration_mode();
|
|
||||||
assert_eq!(expected_mode.mode, mode_kind);
|
|
||||||
expected_mode.settings.model = "gpt-5.6-terra".into();
|
|
||||||
expected_mode.settings.reasoning_effort = Some(ReasoningEffortConfig::Medium);
|
|
||||||
let default_model = app.config.model.clone();
|
|
||||||
let default_plan_effort = app.config.plan_mode_reasoning_effort.clone();
|
|
||||||
let config_path = app.config.codex_home.join("config.toml");
|
|
||||||
let saved_config = std::fs::read(&config_path).ok();
|
|
||||||
while events.try_recv().is_ok() {}
|
|
||||||
while ops.try_recv().is_ok() {}
|
|
||||||
requests.lock().unwrap().clear();
|
|
||||||
let response = fallback_response();
|
|
||||||
let generation = app.rate_limit_hard_stop_generation;
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
app.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
&mut server,
|
|
||||||
AppEvent::RateLimitsLoaded {
|
|
||||||
request_id: 1,
|
|
||||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id: 0 },
|
|
||||||
hard_stop_generation: generation,
|
|
||||||
result: Ok(response.clone()),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let actual_mode = app.chat_widget.effective_collaboration_mode();
|
|
||||||
assert_eq!(actual_mode, expected_mode);
|
|
||||||
assert_eq!(app.chat_widget.current_service_tier(), None);
|
|
||||||
let sent = requests.lock().unwrap().clone();
|
|
||||||
let methods: Vec<_> = sent.iter().map(|request| request.method.as_str()).collect();
|
|
||||||
assert_eq!(methods, ["thread/settings/update"]);
|
|
||||||
assert_eq!(
|
|
||||||
serde_json::from_value::<ThreadSettingsUpdateParams>(sent[0].params.clone().unwrap())?,
|
|
||||||
ThreadSettingsUpdateParams {
|
|
||||||
thread_id: thread_id.to_string(),
|
|
||||||
model: Some("gpt-5.6-terra".into()),
|
|
||||||
effort: Some(ReasoningEffortConfig::Medium),
|
|
||||||
collaboration_mode: Some(expected_mode.clone()),
|
|
||||||
service_tier: Some(Some("default".into())),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
);
|
|
||||||
let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 72);
|
|
||||||
assert!(rendered.contains("Selected model usage exhausted"));
|
|
||||||
if mode_kind == ModeKind::Default {
|
|
||||||
insta::assert_snapshot!(
|
|
||||||
"backend_banner_after_fallback",
|
|
||||||
normalize_snapshot_paths(rendered)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE));
|
|
||||||
let queued = std::iter::from_fn(|| events.try_recv().ok()).collect::<Vec<_>>();
|
|
||||||
assert!(queued.iter().any(|event| matches!(event, AppEvent::OpenUrlInBrowser { url } if url == "https://chatgpt.com/settings/usage")));
|
|
||||||
let notices = queued
|
|
||||||
.iter()
|
|
||||||
.filter_map(|event| match event {
|
|
||||||
AppEvent::InsertHistoryCell(cell) => {
|
|
||||||
Some(lines_to_single_string(&cell.display_lines(/*width*/ 80)))
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
assert_eq!(notices.len(), 1);
|
|
||||||
insta::assert_snapshot!("backend_banner_fallback_notice", notices[0]);
|
|
||||||
assert!(!queued.iter().any(|event| matches!(
|
|
||||||
event,
|
|
||||||
AppEvent::PersistModelSelection { .. } | AppEvent::CodexOp(_)
|
|
||||||
)));
|
|
||||||
assert!(ops.try_recv().is_err(), "switch must not replay a turn");
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
|
||||||
app.chat_widget.update_backend_banner(&response);
|
|
||||||
app.apply_backend_banner_fallback(&mut server).await;
|
|
||||||
assert!(
|
|
||||||
!render_bottom_popup(&app.chat_widget, /*width*/ 72)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
let mut healthy = response;
|
|
||||||
healthy.rate_limit_upsell = None;
|
|
||||||
app.chat_widget.update_backend_banner(&healthy);
|
|
||||||
app.apply_backend_banner_fallback(&mut server).await;
|
|
||||||
assert_eq!(app.chat_widget.current_model(), "gpt-5.6-terra");
|
|
||||||
assert_eq!(requests.lock().unwrap().len(), 1);
|
|
||||||
assert!(
|
|
||||||
!std::iter::from_fn(|| events.try_recv().ok())
|
|
||||||
.any(|event| matches!(event, AppEvent::InsertHistoryCell(_)))
|
|
||||||
);
|
|
||||||
assert_eq!(app.config.model, default_model);
|
|
||||||
assert_eq!(app.config.plan_mode_reasoning_effort, default_plan_effort);
|
|
||||||
assert_eq!(std::fs::read(&config_path).ok(), saved_config);
|
|
||||||
if mode_kind == ModeKind::Plan {
|
|
||||||
let chat = &mut app.chat_widget;
|
|
||||||
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
|
|
||||||
assert_eq!(chat.active_collaboration_mode_kind(), ModeKind::Default);
|
|
||||||
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
|
|
||||||
}
|
|
||||||
app.chat_widget
|
|
||||||
.restore_user_message_to_composer(UserMessage::from("continue"));
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
||||||
assert_matches!(next_user_turn_op(&mut ops), AppCommand::UserTurn { model, collaboration_mode: Some(mode), .. }
|
|
||||||
if model == "gpt-5.6-terra" && mode == expected_mode);
|
|
||||||
server.shutdown().await?;
|
|
||||||
proxy.await??;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_fallback_uses_current_task_and_accepted_generation() -> Result<()> {
|
|
||||||
let (mut app, _events, _ops) = make_test_app_with_channels().await;
|
|
||||||
let (mut server, requests, proxy) = start_fallback_thread(&mut app).await?;
|
|
||||||
let read_generation = app.rate_limit_hard_stop_generation;
|
|
||||||
let second = server.start_thread(&app.config).await?;
|
|
||||||
let active_id = second.session.thread_id;
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
let init = app.chatwidget_init_for_forked_or_resumed_thread(
|
|
||||||
&mut tui,
|
|
||||||
app.config.clone(),
|
|
||||||
/*initial_user_message*/ None,
|
|
||||||
);
|
|
||||||
app.replace_chat_widget(ChatWidget::new_with_app_event(init));
|
|
||||||
app.store_active_thread_receiver().await;
|
|
||||||
app.active_thread_id = None;
|
|
||||||
app.enqueue_primary_thread_session(second.session, second.turns)
|
|
||||||
.await?;
|
|
||||||
configure_fallback_model(&mut app);
|
|
||||||
requests.lock().unwrap().clear();
|
|
||||||
app.rate_limit_hard_stop_generation = read_generation.wrapping_add(1);
|
|
||||||
for generation in [read_generation, app.rate_limit_hard_stop_generation] {
|
|
||||||
app.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
&mut server,
|
|
||||||
AppEvent::RateLimitsLoaded {
|
|
||||||
request_id: 1,
|
|
||||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id: 0 },
|
|
||||||
hard_stop_generation: generation,
|
|
||||||
result: Ok(fallback_response()),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
if generation == read_generation {
|
|
||||||
assert_eq!(app.chat_widget.current_model(), "gpt-5.5");
|
|
||||||
assert!(requests.lock().unwrap().is_empty());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let sent = requests.lock().unwrap().clone();
|
|
||||||
assert_eq!(sent.len(), 1);
|
|
||||||
assert_eq!(
|
|
||||||
sent[0].params.as_ref().unwrap()["threadId"],
|
|
||||||
active_id.to_string()
|
|
||||||
);
|
|
||||||
assert_eq!(app.chat_widget.current_model(), "gpt-5.6-terra");
|
|
||||||
server.shutdown().await?;
|
|
||||||
proxy.await??;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_fallback_keeps_existing_recovery_without_candidate() -> Result<()> {
|
|
||||||
let (mut app, _events, _ops) = make_test_app_with_channels().await;
|
|
||||||
let (mut server, requests, proxy) = start_fallback_thread(&mut app).await?;
|
|
||||||
requests.lock().unwrap().clear();
|
|
||||||
for (replacement, expect_legacy_banner) in [
|
|
||||||
(json!([]), true),
|
|
||||||
(json!(["unavailable-model"]), false),
|
|
||||||
(json!(["gpt-5.5"]), false),
|
|
||||||
] {
|
|
||||||
let mut response = fallback_response();
|
|
||||||
response.rate_limit_upsell.as_mut().unwrap()["fallback_model_slugs"] = replacement;
|
|
||||||
app.chat_widget.update_backend_banner(&response);
|
|
||||||
app.apply_backend_banner_fallback(&mut server).await;
|
|
||||||
assert_eq!(app.chat_widget.current_model(), "gpt-5.5");
|
|
||||||
let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 72);
|
|
||||||
assert_eq!(rendered.contains("View usage"), expect_legacy_banner);
|
|
||||||
if !expect_legacy_banner {
|
|
||||||
insta::assert_snapshot!(
|
|
||||||
"backend_banner_fallback_unavailable",
|
|
||||||
normalize_snapshot_paths(rendered)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
app.chat_widget.set_model("gpt-5.6-terra");
|
|
||||||
app.chat_widget.update_backend_banner(&fallback_response());
|
|
||||||
app.apply_backend_banner_fallback(&mut server).await;
|
|
||||||
assert_eq!(app.chat_widget.current_model(), "gpt-5.6-terra");
|
|
||||||
assert!(
|
|
||||||
render_bottom_popup(&app.chat_widget, /*width*/ 72)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
assert!(requests.lock().unwrap().is_empty());
|
|
||||||
server.shutdown().await?;
|
|
||||||
proxy.await??;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_fallback_handles_settings_failure_and_queued_manual_selection() -> Result<()>
|
|
||||||
{
|
|
||||||
use futures::SinkExt;
|
|
||||||
use futures::StreamExt;
|
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
|
||||||
|
|
||||||
for (use_reserve, error_code) in [false, true]
|
|
||||||
.into_iter()
|
|
||||||
.flat_map(|reserve| [Some(-32601), Some(-32603), None].map(|error| (reserve, error)))
|
|
||||||
{
|
|
||||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
|
||||||
let id = ThreadId::new();
|
|
||||||
app.active_thread_id = Some(id);
|
|
||||||
app.chat_widget
|
|
||||||
.handle_thread_session(test_thread_session(id, app.config.cwd.to_path_buf()));
|
|
||||||
if use_reserve {
|
|
||||||
app.primary_session_configured =
|
|
||||||
Some(test_thread_session(id, app.config.cwd.to_path_buf()));
|
|
||||||
super::luna_reserve_recovery_tests::configure_reserve_catalog(&mut app);
|
|
||||||
} else {
|
|
||||||
configure_fallback_model(&mut app);
|
|
||||||
}
|
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
|
||||||
let websocket_url = format!("ws://{}", listener.local_addr()?);
|
|
||||||
let codex_home = app.config.codex_home.display().to_string();
|
|
||||||
let manual_selection_tx = app.app_event_tx.clone();
|
|
||||||
let fake = tokio::spawn(async move {
|
|
||||||
let (stream, _) = listener.accept().await?;
|
|
||||||
let mut socket = tokio_tungstenite::accept_async(stream).await?;
|
|
||||||
let mut settings_requests = 0;
|
|
||||||
while let Some(frame) = socket.next().await {
|
|
||||||
let Message::Text(text) = frame? else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let request: serde_json::Value = serde_json::from_str(&text)?;
|
|
||||||
if request["id"].is_null() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let response = if request["method"] == "initialize" {
|
|
||||||
json!({"id": request["id"], "result": {"userAgent": "test", "codexHome": codex_home}})
|
|
||||||
} else {
|
|
||||||
assert_eq!(request["method"], "thread/settings/update");
|
|
||||||
settings_requests += 1;
|
|
||||||
if let Some(error_code) = error_code {
|
|
||||||
json!({"id": request["id"], "error": {"code": error_code, "message": "settings unavailable"}})
|
|
||||||
} else {
|
|
||||||
if settings_requests == 1 {
|
|
||||||
// A manual selection arriving while the RPC is pending must win afterward.
|
|
||||||
manual_selection_tx.send(AppEvent::UpdateModel("gpt-5.5".into()));
|
|
||||||
}
|
|
||||||
json!({"id": request["id"], "result": {}})
|
|
||||||
}
|
|
||||||
};
|
|
||||||
socket
|
|
||||||
.send(Message::Text(response.to_string().into()))
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
Result::<()>::Ok(())
|
|
||||||
});
|
|
||||||
let client = crate::connect_remote_app_server(crate::RemoteAppServerEndpoint::WebSocket {
|
|
||||||
websocket_url,
|
|
||||||
auth_token: None,
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
let mut server = AppServerSession::new(
|
|
||||||
crate::backend_id::BackendId::new(),
|
|
||||||
client,
|
|
||||||
crate::app_server_session::ThreadParamsMode::Embedded,
|
|
||||||
);
|
|
||||||
assert!(!crate::app::safety_recourse::supports_server(&server));
|
|
||||||
while events.try_recv().is_ok() {}
|
|
||||||
let pending_turn = if use_reserve && error_code.is_some() {
|
|
||||||
app.chat_widget
|
|
||||||
.restore_user_message_to_composer(UserMessage::from("queued before usage reply"));
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::from(KeyCode::Enter));
|
|
||||||
Some(
|
|
||||||
std::iter::from_fn(|| events.try_recv().ok())
|
|
||||||
.find(|event| matches!(event, AppEvent::CodexOp(AppCommand::UserTurn { .. })))
|
|
||||||
.expect("turn already queued before the failed switch"),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
let response = if use_reserve {
|
|
||||||
super::luna_reserve_recovery_tests::reserve_response()
|
|
||||||
} else {
|
|
||||||
fallback_response()
|
|
||||||
};
|
|
||||||
app.chat_widget.update_backend_banner(&response);
|
|
||||||
app.apply_backend_banner_fallback(&mut server).await;
|
|
||||||
let queued = std::iter::from_fn(|| events.try_recv().ok()).collect::<Vec<_>>();
|
|
||||||
let switch_notices = queued
|
|
||||||
.iter()
|
|
||||||
.filter(|event| match event {
|
|
||||||
AppEvent::InsertHistoryCell(cell) => {
|
|
||||||
lines_to_single_string(&cell.display_lines(/*width*/ 80))
|
|
||||||
.contains("Automatically switched")
|
|
||||||
}
|
|
||||||
_ => false,
|
|
||||||
})
|
|
||||||
.count();
|
|
||||||
assert_eq!(switch_notices, usize::from(error_code.is_none()));
|
|
||||||
if error_code.is_none() {
|
|
||||||
assert_eq!(
|
|
||||||
app.chat_widget.current_model(),
|
|
||||||
if use_reserve {
|
|
||||||
"gpt-reserve"
|
|
||||||
} else {
|
|
||||||
"gpt-5.6-terra"
|
|
||||||
}
|
|
||||||
);
|
|
||||||
let manual_selection = queued
|
|
||||||
.into_iter()
|
|
||||||
.find(|event| matches!(event, AppEvent::UpdateModel(_)))
|
|
||||||
.unwrap();
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
app.handle_event(&mut tui, &mut server, manual_selection)
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
assert_eq!(app.chat_widget.current_model(), "gpt-5.5");
|
|
||||||
assert!(!render_bottom_popup(&app.chat_widget, /*width*/ 72).contains("View usage"));
|
|
||||||
if use_reserve && error_code.is_some() {
|
|
||||||
let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 90);
|
|
||||||
assert!(rendered.contains("Add credits"));
|
|
||||||
assert!(!rendered.contains("You’re now using Luna"));
|
|
||||||
if error_code == Some(-32601) {
|
|
||||||
insta::assert_snapshot!(
|
|
||||||
"luna_reserve_settings_unavailable",
|
|
||||||
normalize_snapshot_paths(rendered)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE));
|
|
||||||
assert!(
|
|
||||||
std::iter::from_fn(|| events.try_recv().ok())
|
|
||||||
.any(|event| matches!(event, AppEvent::OpenUrlInBrowser { .. }))
|
|
||||||
);
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
app.handle_event(&mut tui, &mut server, pending_turn.unwrap())
|
|
||||||
.await?;
|
|
||||||
assert_eq!(
|
|
||||||
app.chat_widget.queued_user_message_texts(),
|
|
||||||
vec!["queued before usage reply"]
|
|
||||||
);
|
|
||||||
app.chat_widget.finish_rate_limit_recovery();
|
|
||||||
app.chat_widget
|
|
||||||
.restore_user_message_to_composer(UserMessage::from("after recovery"));
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::from(KeyCode::Enter));
|
|
||||||
assert_eq!(
|
|
||||||
app.chat_widget.queued_user_message_texts(),
|
|
||||||
vec!["queued before usage reply", "after recovery"]
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
!std::iter::from_fn(|| events.try_recv().ok())
|
|
||||||
.any(|event| matches!(event, AppEvent::CodexOp(AppCommand::UserTurn { .. })))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
server.shutdown().await?;
|
|
||||||
fake.await??;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_fallback_preserves_permissions_for_first_eligible_cyber_model() -> Result<()>
|
|
||||||
{
|
|
||||||
let mut app = make_test_app().await;
|
|
||||||
assert!(
|
|
||||||
app.apply_permission_profile_selection(PermissionProfileSelection {
|
|
||||||
profile_id: codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY.into(),
|
|
||||||
approval_policy: Some(AskForApproval::UnlessTrusted),
|
|
||||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
|
||||||
display_label: "Read Only".into(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
);
|
|
||||||
let mut server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
|
||||||
let started = server.start_thread(&app.config).await?;
|
|
||||||
let thread_id = started.session.thread_id;
|
|
||||||
app.enqueue_primary_thread_session(started.session, started.turns)
|
|
||||||
.await?;
|
|
||||||
configure_fallback_model(&mut app);
|
|
||||||
let mut models = app.model_catalog.try_list_models()?;
|
|
||||||
let mut cyber_model = models
|
|
||||||
.iter()
|
|
||||||
.find(|model| model.model == "gpt-5.6-terra")
|
|
||||||
.unwrap()
|
|
||||||
.clone();
|
|
||||||
// Like the manual-selection tests, classify a fixture model through catalog metadata.
|
|
||||||
cyber_model.model = "cyber-test-model".into();
|
|
||||||
cyber_model.model_specialty = Some(MODEL_SPECIALTY_CYBER.into());
|
|
||||||
models.push(cyber_model.clone());
|
|
||||||
app.model_catalog = Arc::new(ModelCatalog::new(models));
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
let mut init = app.chatwidget_init_for_forked_or_resumed_thread(
|
|
||||||
&mut tui,
|
|
||||||
app.config.clone(),
|
|
||||||
/*initial_user_message*/ None,
|
|
||||||
);
|
|
||||||
init.model_catalog = app.model_catalog.clone();
|
|
||||||
app.replace_chat_widget(ChatWidget::new_with_app_event(init));
|
|
||||||
app.chat_widget
|
|
||||||
.handle_thread_session(app.primary_session_configured.clone().unwrap());
|
|
||||||
app.chat_widget.set_model("gpt-5.5");
|
|
||||||
app.chat_widget
|
|
||||||
.set_reasoning_effort(Some(ReasoningEffortConfig::Medium));
|
|
||||||
let mut response = fallback_response();
|
|
||||||
response.rate_limit_upsell.as_mut().unwrap()["fallback_model_slugs"] = json!([
|
|
||||||
"unavailable-model",
|
|
||||||
"gpt-5.5",
|
|
||||||
cyber_model.model,
|
|
||||||
"gpt-5.6-terra"
|
|
||||||
]);
|
|
||||||
app.chat_widget.update_backend_banner(&response);
|
|
||||||
app.apply_backend_banner_fallback(&mut server).await;
|
|
||||||
assert_eq!(app.chat_widget.current_model(), cyber_model.model);
|
|
||||||
let settings = next_thread_settings_updated(&mut server, thread_id)
|
|
||||||
.await
|
|
||||||
.thread_settings;
|
|
||||||
assert_eq!(
|
|
||||||
(
|
|
||||||
settings.model,
|
|
||||||
settings.effort,
|
|
||||||
settings.approval_policy,
|
|
||||||
settings.approvals_reviewer.to_core(),
|
|
||||||
settings.active_permission_profile.unwrap().id
|
|
||||||
),
|
|
||||||
(
|
|
||||||
cyber_model.model,
|
|
||||||
Some(ReasoningEffortConfig::Medium),
|
|
||||||
AskForApproval::UnlessTrusted,
|
|
||||||
ApprovalsReviewer::User,
|
|
||||||
codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY.to_string()
|
|
||||||
),
|
|
||||||
);
|
|
||||||
server.shutdown().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -1,567 +0,0 @@
|
|||||||
use super::*;
|
|
||||||
use crate::app::rate_limit_refresh::RateLimitReadStatus;
|
|
||||||
use crate::app::rate_limit_refresh::RateLimitRefreshOutcome;
|
|
||||||
use app_test_support::ChatGptAuthFixture;
|
|
||||||
use app_test_support::write_chatgpt_auth;
|
|
||||||
use codex_app_server_protocol::CodexErrorInfo;
|
|
||||||
use codex_app_server_protocol::ErrorNotification;
|
|
||||||
use codex_app_server_protocol::GetAccountRateLimitsResponse;
|
|
||||||
use codex_config::types::AuthCredentialsStoreMode;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
use serde_json::json;
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::MockServer;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
|
|
||||||
fn response_with_banner() -> GetAccountRateLimitsResponse {
|
|
||||||
serde_json::from_value(json!({
|
|
||||||
"accountId":"workspace-a", "rateLimitUpsell":{
|
|
||||||
"banner_type":"selected_model_limit", "model_slug":"test-model-a", "presentation":"inline",
|
|
||||||
"title":"Selected model usage exhausted", "description":"Switch to another model or contact your owner.",
|
|
||||||
"ctas":[{"action":"notify_owner","label":"Notify owner"}]
|
|
||||||
},
|
|
||||||
"rateLimits":{}, "rateLimitsByLimitId":null,"rateLimitResetCredits":null
|
|
||||||
})).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn next_rate_limits_loaded(
|
|
||||||
events: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
|
|
||||||
) -> Result<AppEvent> {
|
|
||||||
Ok(
|
|
||||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 10), async {
|
|
||||||
loop {
|
|
||||||
let event = events.recv().await.expect("app event channel");
|
|
||||||
if matches!(event, AppEvent::RateLimitsLoaded { .. }) {
|
|
||||||
break event;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.await?,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn luna_reserve_periodic_refresh_adapts_without_an_experiment_banner() -> Result<()> {
|
|
||||||
let backend = MockServer::start().await;
|
|
||||||
let home = tempdir()?;
|
|
||||||
write_chatgpt_auth(
|
|
||||||
home.path(),
|
|
||||||
ChatGptAuthFixture::new("local-test-token")
|
|
||||||
.account_id("workspace-a")
|
|
||||||
.chatgpt_user_id("user-a")
|
|
||||||
.plan_type("plus"),
|
|
||||||
AuthCredentialsStoreMode::File,
|
|
||||||
)
|
|
||||||
.expect("write synthetic auth");
|
|
||||||
std::fs::write(
|
|
||||||
home.path().join("config.toml"),
|
|
||||||
format!(
|
|
||||||
"chatgpt_base_url = {:?}\ncli_auth_credentials_store = \"file\"\n",
|
|
||||||
backend.uri()
|
|
||||||
),
|
|
||||||
)?;
|
|
||||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
|
||||||
app.config.codex_home = home.path().to_path_buf().abs();
|
|
||||||
app.config.chatgpt_base_url = backend.uri();
|
|
||||||
app.config.sqlite = codex_state::SqliteConfig::new_for_testing(home.path().abs());
|
|
||||||
set_chatgpt_auth(&mut app.chat_widget);
|
|
||||||
let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
for (used, seconds) in [(10, 60), (75, 30), (90, 15), (99, 5), (20, 60)] {
|
|
||||||
backend.reset().await;
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/api/codex/usage"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
|
||||||
"account_id": "workspace-a", "user_id": "user-a", "plan_type": "plus",
|
|
||||||
"rate_limit": {"allowed": true, "limit_reached": false,
|
|
||||||
"primary_window": {"used_percent": used, "limit_window_seconds": 18000,
|
|
||||||
"reset_after_seconds": 1800, "reset_at": 2000000000}},
|
|
||||||
"rate_limit_reset_credits": {"available_count": 1}
|
|
||||||
})))
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&backend)
|
|
||||||
.await;
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/api/codex/rate-limit-reset-credits"))
|
|
||||||
.respond_with(ResponseTemplate::new(/*s*/ 200))
|
|
||||||
.expect(/*r*/ 0)
|
|
||||||
.mount(&backend)
|
|
||||||
.await;
|
|
||||||
app.refresh_rate_limits(&session, RateLimitRefreshOrigin::Periodic);
|
|
||||||
// A second timer tick while this RPC is pending must not add another request.
|
|
||||||
app.refresh_rate_limits(&session, RateLimitRefreshOrigin::Periodic);
|
|
||||||
assert!(
|
|
||||||
app.rate_limit_refresh_state
|
|
||||||
.poll_deadline(Duration::from_secs(/*secs*/ 60))
|
|
||||||
.is_none()
|
|
||||||
);
|
|
||||||
let loaded = next_rate_limits_loaded(&mut events).await?;
|
|
||||||
assert_matches!(&loaded, AppEvent::RateLimitsLoaded { result: Ok(_), .. });
|
|
||||||
let before = std::time::Instant::now();
|
|
||||||
app.handle_event(&mut tui, &mut session, loaded).await?;
|
|
||||||
let after = std::time::Instant::now();
|
|
||||||
let interval = app.chat_widget.rate_limit_refresh_interval().unwrap();
|
|
||||||
assert_eq!(interval, Duration::from_secs(seconds));
|
|
||||||
let deadline = app
|
|
||||||
.rate_limit_refresh_state
|
|
||||||
.poll_deadline(interval)
|
|
||||||
.unwrap();
|
|
||||||
assert!(deadline >= before + interval && deadline <= after + interval);
|
|
||||||
let requests = backend.received_requests().await.unwrap();
|
|
||||||
let usage = requests
|
|
||||||
.iter()
|
|
||||||
.find(|request| request.url.path() == "/api/codex/usage")
|
|
||||||
.unwrap();
|
|
||||||
assert!(usage.headers.contains_key("x-openai-codex-luna-reserve"));
|
|
||||||
backend.verify().await;
|
|
||||||
}
|
|
||||||
session.shutdown().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_limit_error_refreshes_again_after_intervening_rolling_hard_stop()
|
|
||||||
-> Result<()> {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let home = tempdir()?;
|
|
||||||
write_chatgpt_auth(
|
|
||||||
home.path(),
|
|
||||||
ChatGptAuthFixture::new("local-test-token")
|
|
||||||
.account_id("workspace-a")
|
|
||||||
.chatgpt_user_id("user-a")
|
|
||||||
.plan_type("team"),
|
|
||||||
AuthCredentialsStoreMode::File,
|
|
||||||
)
|
|
||||||
.expect("write synthetic auth");
|
|
||||||
std::fs::write(
|
|
||||||
home.path().join("config.toml"),
|
|
||||||
format!(
|
|
||||||
"chatgpt_base_url = {:?}\ncli_auth_credentials_store = \"file\"\n",
|
|
||||||
server.uri()
|
|
||||||
),
|
|
||||||
)?;
|
|
||||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
|
||||||
app.config.codex_home = home.path().to_path_buf().abs();
|
|
||||||
app.config.chatgpt_base_url = server.uri();
|
|
||||||
app.config.sqlite = codex_state::SqliteConfig::new_for_testing(home.path().abs());
|
|
||||||
set_chatgpt_auth(&mut app.chat_widget);
|
|
||||||
app.chat_widget.set_model("test-model-a");
|
|
||||||
let mut healthy = response_with_banner();
|
|
||||||
healthy.rate_limit_upsell = None;
|
|
||||||
app.chat_widget.update_backend_banner(&healthy);
|
|
||||||
assert!(
|
|
||||||
!render_bottom_popup(&app.chat_widget, /*width*/ 90)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/api/codex/usage"))
|
|
||||||
.respond_with(
|
|
||||||
ResponseTemplate::new(200)
|
|
||||||
.set_delay(std::time::Duration::from_millis(/*millis*/ 100))
|
|
||||||
.set_body_json(json!({
|
|
||||||
"account_id":"workspace-a","user_id":"user-a","plan_type":"team",
|
|
||||||
"rate_limit":{"allowed":true,"limit_reached":false},
|
|
||||||
"rate_limit_upsell":response_with_banner().rate_limit_upsell,
|
|
||||||
"rate_limit_reset_credits":{"available_count":0}
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.expect(3)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
Mock::given(method("GET"))
|
|
||||||
.and(path("/api/codex/rate-limit-reset-credits"))
|
|
||||||
.respond_with(
|
|
||||||
ResponseTemplate::new(200).set_body_json(json!({"available_count":0,"credits":[]})),
|
|
||||||
)
|
|
||||||
.expect(3)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
while events.try_recv().is_ok() {}
|
|
||||||
app.chat_widget.handle_server_notification(
|
|
||||||
ServerNotification::Error(ErrorNotification {
|
|
||||||
error: AppServerTurnError {
|
|
||||||
misalignment: None,
|
|
||||||
message: "credits exhausted".into(),
|
|
||||||
codex_error_info: Some(CodexErrorInfo::UsageLimitExceeded),
|
|
||||||
additional_details: None,
|
|
||||||
},
|
|
||||||
will_retry: false,
|
|
||||||
thread_id: "thread-a".into(),
|
|
||||||
turn_id: "turn-a".into(),
|
|
||||||
}),
|
|
||||||
/*replay_kind*/ None,
|
|
||||||
);
|
|
||||||
let recovery = loop {
|
|
||||||
let event = events
|
|
||||||
.try_recv()
|
|
||||||
.expect("limit error should request recovery without a command");
|
|
||||||
if matches!(
|
|
||||||
event,
|
|
||||||
AppEvent::RefreshRateLimits {
|
|
||||||
origin: RateLimitRefreshOrigin::Recovery
|
|
||||||
}
|
|
||||||
) {
|
|
||||||
break event;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
app.handle_event(&mut tui, &mut session, recovery).await?;
|
|
||||||
app.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
&mut session,
|
|
||||||
AppEvent::RefreshRateLimits {
|
|
||||||
origin: RateLimitRefreshOrigin::Recovery,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let mut rolling = response_with_banner().rate_limits;
|
|
||||||
rolling.rate_limit_reached_type =
|
|
||||||
Some(codex_app_server_protocol::RateLimitReachedType::WorkspaceMemberCreditsDepleted);
|
|
||||||
app.handle_app_server_event(
|
|
||||||
&session,
|
|
||||||
codex_app_server_client::AppServerEvent::ServerNotification(Box::new(
|
|
||||||
ServerNotification::AccountRateLimitsUpdated(
|
|
||||||
codex_app_server_protocol::AccountRateLimitsUpdatedNotification {
|
|
||||||
rate_limits: rolling.clone(),
|
|
||||||
},
|
|
||||||
),
|
|
||||||
)),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
let loaded = next_rate_limits_loaded(&mut events).await?;
|
|
||||||
assert!(
|
|
||||||
matches!(&loaded, AppEvent::RateLimitsLoaded { result: Ok(_), .. }),
|
|
||||||
"{loaded:?}"
|
|
||||||
);
|
|
||||||
app.handle_event(&mut tui, &mut session, loaded).await?;
|
|
||||||
assert!(
|
|
||||||
!render_bottom_popup(&app.chat_widget, /*width*/ 90)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
// No second inference Error or explicit refresh: the obsolete read starts its own replacement.
|
|
||||||
let loaded = next_rate_limits_loaded(&mut events).await?;
|
|
||||||
app.handle_event(&mut tui, &mut session, loaded).await?;
|
|
||||||
let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 90);
|
|
||||||
assert!(rendered.contains("Selected model usage exhausted"));
|
|
||||||
assert!(rendered.contains("Notify owner"));
|
|
||||||
// A background operation can report the same hard stop after the full response omitted
|
|
||||||
// aggregate reached_type: included usage for other models is still available.
|
|
||||||
app.handle_app_server_event(
|
|
||||||
&session,
|
|
||||||
codex_app_server_client::AppServerEvent::ServerNotification(Box::new(
|
|
||||||
ServerNotification::AccountRateLimitsUpdated(
|
|
||||||
codex_app_server_protocol::AccountRateLimitsUpdatedNotification {
|
|
||||||
rate_limits: rolling,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
)),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert!(
|
|
||||||
render_bottom_popup(&app.chat_widget, /*width*/ 90)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
let loaded = next_rate_limits_loaded(&mut events).await?;
|
|
||||||
app.handle_event(&mut tui, &mut session, loaded).await?;
|
|
||||||
assert!(
|
|
||||||
render_bottom_popup(&app.chat_widget, /*width*/ 90)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
app.chat_widget.set_model("test-model-b");
|
|
||||||
assert!(
|
|
||||||
!render_bottom_popup(&app.chat_widget, /*width*/ 90)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
session.shutdown().await?;
|
|
||||||
server.verify().await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn backend_banner_recovery_follows_rolling_invalidation_without_another_error() {
|
|
||||||
let mut refresh = crate::app::rate_limit_refresh::RateLimitRefreshState::default();
|
|
||||||
let mut epoch = 0;
|
|
||||||
let first = refresh
|
|
||||||
.start(RateLimitRefreshOrigin::Recovery, &mut epoch)
|
|
||||||
.unwrap();
|
|
||||||
epoch += 1;
|
|
||||||
assert_eq!(
|
|
||||||
refresh.finish(first.0, first.1, epoch, RateLimitReadStatus::Succeeded),
|
|
||||||
RateLimitRefreshOutcome::RefreshRecovery
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_rolling_only_recovery_holds_new_input() -> Result<()> {
|
|
||||||
let (mut app, _events, mut ops) = make_test_app_with_channels().await;
|
|
||||||
let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
app.chat_widget.handle_thread_session(test_thread_session(
|
|
||||||
ThreadId::new(),
|
|
||||||
app.config.cwd.to_path_buf(),
|
|
||||||
));
|
|
||||||
set_chatgpt_auth(&mut app.chat_widget);
|
|
||||||
app.chat_widget.set_model("test-model-a");
|
|
||||||
let mut rolling = response_with_banner().rate_limits;
|
|
||||||
rolling.spend_control_reached = Some(true);
|
|
||||||
app.handle_app_server_event(
|
|
||||||
&session,
|
|
||||||
codex_app_server_client::AppServerEvent::ServerNotification(Box::new(
|
|
||||||
ServerNotification::AccountRateLimitsUpdated(
|
|
||||||
codex_app_server_protocol::AccountRateLimitsUpdatedNotification {
|
|
||||||
rate_limits: rolling,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
)),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
app.chat_widget.apply_external_edit("follow-up".into());
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
||||||
assert_eq!(
|
|
||||||
app.chat_widget.queued_user_message_texts(),
|
|
||||||
vec!["follow-up"]
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
!std::iter::from_fn(|| ops.try_recv().ok()).any(|op| matches!(op, Op::UserTurn { .. }))
|
|
||||||
);
|
|
||||||
app.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
&mut session,
|
|
||||||
AppEvent::RateLimitsLoaded {
|
|
||||||
request_id: 1,
|
|
||||||
origin: RateLimitRefreshOrigin::Recovery,
|
|
||||||
hard_stop_generation: app.rate_limit_hard_stop_generation,
|
|
||||||
result: Ok(response_with_banner()),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
assert!(
|
|
||||||
matches!(next_user_turn_op(&mut ops), Op::UserTurn { items, .. }
|
|
||||||
if items == vec![UserInput::Text { text: "follow-up".into(), text_elements: Vec::new() }])
|
|
||||||
);
|
|
||||||
session.shutdown().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_account_changes_invalidate_pending_recovery() -> Result<()> {
|
|
||||||
let (mut app, _events, _ops) = make_test_app_with_channels().await;
|
|
||||||
let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
app.chat_widget.set_model("test-model-a");
|
|
||||||
let current = response_with_banner();
|
|
||||||
app.chat_widget.update_backend_banner(¤t);
|
|
||||||
assert!(
|
|
||||||
render_bottom_popup(&app.chat_widget, /*width*/ 90)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
let pending = app
|
|
||||||
.rate_limit_refresh_state
|
|
||||||
.start(
|
|
||||||
RateLimitRefreshOrigin::Recovery,
|
|
||||||
&mut app.rate_limit_hard_stop_generation,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
app.handle_app_server_event(
|
|
||||||
&session,
|
|
||||||
codex_app_server_client::AppServerEvent::ServerNotification(Box::new(
|
|
||||||
ServerNotification::AccountUpdated(
|
|
||||||
codex_app_server_protocol::AccountUpdatedNotification {
|
|
||||||
auth_mode: None,
|
|
||||||
plan_type: None,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
)),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
app.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
&mut session,
|
|
||||||
AppEvent::RateLimitsLoaded {
|
|
||||||
request_id: pending.0,
|
|
||||||
origin: RateLimitRefreshOrigin::Recovery,
|
|
||||||
hard_stop_generation: pending.1,
|
|
||||||
result: Ok(current),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
assert!(
|
|
||||||
!render_bottom_popup(&app.chat_widget, /*width*/ 90)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
app.rate_limit_refresh_state
|
|
||||||
.start(
|
|
||||||
RateLimitRefreshOrigin::Recovery,
|
|
||||||
&mut app.rate_limit_hard_stop_generation
|
|
||||||
)
|
|
||||||
.is_some()
|
|
||||||
);
|
|
||||||
session.shutdown().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_reset_redemption_rejects_pre_reset_content() -> Result<()> {
|
|
||||||
let (mut app, _events, mut ops) = make_test_app_with_channels().await;
|
|
||||||
let mut session = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
app.chat_widget.handle_thread_session(test_thread_session(
|
|
||||||
ThreadId::new(),
|
|
||||||
app.config.cwd.to_path_buf(),
|
|
||||||
));
|
|
||||||
app.chat_widget.set_model("test-model-a");
|
|
||||||
let banner = response_with_banner();
|
|
||||||
app.chat_widget.update_backend_banner(&banner);
|
|
||||||
assert!(
|
|
||||||
render_bottom_popup(&app.chat_widget, /*width*/ 90)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
let pending = app
|
|
||||||
.rate_limit_refresh_state
|
|
||||||
.start(
|
|
||||||
RateLimitRefreshOrigin::Recovery,
|
|
||||||
&mut app.rate_limit_hard_stop_generation,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
app.chat_widget.hold_rate_limit_recovery();
|
|
||||||
app.chat_widget.apply_external_edit("after reset".into());
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
||||||
assert_eq!(
|
|
||||||
app.chat_widget.queued_user_message_texts(),
|
|
||||||
vec!["after reset"]
|
|
||||||
);
|
|
||||||
let request_id = app.chat_widget.show_rate_limit_reset_consuming_popup();
|
|
||||||
app.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
&mut session,
|
|
||||||
AppEvent::RateLimitResetCreditConsumed {
|
|
||||||
request_id,
|
|
||||||
idempotency_key: "mock-reset".into(),
|
|
||||||
credit_id: None,
|
|
||||||
result: Ok(
|
|
||||||
codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse {
|
|
||||||
outcome:
|
|
||||||
codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome::Reset,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let mut recovered = banner.clone();
|
|
||||||
recovered.rate_limit_upsell = None;
|
|
||||||
recovered.rate_limit_reset_credits =
|
|
||||||
Some(codex_app_server_protocol::RateLimitResetCreditsSummary {
|
|
||||||
available_count: 0,
|
|
||||||
credits: None,
|
|
||||||
});
|
|
||||||
app.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
&mut session,
|
|
||||||
AppEvent::RateLimitsLoaded {
|
|
||||||
request_id: 2,
|
|
||||||
origin: RateLimitRefreshOrigin::ResetConsume { request_id },
|
|
||||||
hard_stop_generation: app.rate_limit_hard_stop_generation,
|
|
||||||
result: Ok(recovered),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
assert!(
|
|
||||||
matches!(next_user_turn_op(&mut ops), Op::UserTurn { items, .. }
|
|
||||||
if items == vec![UserInput::Text { text: "after reset".into(), text_elements: Vec::new() }])
|
|
||||||
);
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
|
||||||
app.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
&mut session,
|
|
||||||
AppEvent::RateLimitsLoaded {
|
|
||||||
request_id: pending.0,
|
|
||||||
origin: RateLimitRefreshOrigin::Recovery,
|
|
||||||
hard_stop_generation: pending.1,
|
|
||||||
result: Ok(banner),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
assert!(
|
|
||||||
!render_bottom_popup(&app.chat_widget, /*width*/ 90)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
app.rate_limit_refresh_state
|
|
||||||
.start(
|
|
||||||
RateLimitRefreshOrigin::Recovery,
|
|
||||||
&mut app.rate_limit_hard_stop_generation
|
|
||||||
)
|
|
||||||
.is_some()
|
|
||||||
);
|
|
||||||
session.shutdown().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn backend_banner_post_reset_read_preserves_newer_recovery_hold() {
|
|
||||||
let mut refresh = crate::app::rate_limit_refresh::RateLimitRefreshState::default();
|
|
||||||
let mut epoch = 0;
|
|
||||||
let old = refresh
|
|
||||||
.start(RateLimitRefreshOrigin::Recovery, &mut epoch)
|
|
||||||
.unwrap();
|
|
||||||
epoch += 1;
|
|
||||||
refresh.invalidate_recovery();
|
|
||||||
let reset = refresh
|
|
||||||
.start(
|
|
||||||
RateLimitRefreshOrigin::ResetConsume { request_id: 1 },
|
|
||||||
&mut epoch,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
refresh.finish(old.0, old.1, epoch, RateLimitReadStatus::Succeeded),
|
|
||||||
RateLimitRefreshOutcome::Ignore
|
|
||||||
);
|
|
||||||
assert!(refresh.has_pending_recovery());
|
|
||||||
let newer = refresh
|
|
||||||
.start(RateLimitRefreshOrigin::Recovery, &mut epoch)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
refresh.finish(reset.0, reset.1, epoch, RateLimitReadStatus::Succeeded),
|
|
||||||
RateLimitRefreshOutcome::Ignore
|
|
||||||
);
|
|
||||||
assert!(refresh.has_pending_recovery());
|
|
||||||
assert_eq!(
|
|
||||||
refresh.finish(newer.0, newer.1, epoch, RateLimitReadStatus::Failed),
|
|
||||||
RateLimitRefreshOutcome::Ignore
|
|
||||||
);
|
|
||||||
assert!(!refresh.has_pending_recovery());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn backend_banner_recovery_coalesces_until_newer_epoch_can_be_read() {
|
|
||||||
let mut refresh = crate::app::rate_limit_refresh::RateLimitRefreshState::default();
|
|
||||||
let mut epoch = 0;
|
|
||||||
let first = refresh
|
|
||||||
.start(RateLimitRefreshOrigin::Recovery, &mut epoch)
|
|
||||||
.unwrap();
|
|
||||||
epoch += 1; // A newer rolling hard stop makes the in-flight response obsolete.
|
|
||||||
for _ in 0..10 {
|
|
||||||
assert_eq!(
|
|
||||||
refresh.start(RateLimitRefreshOrigin::Recovery, &mut epoch),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert_eq!(
|
|
||||||
refresh.finish(first.0, first.1, epoch, RateLimitReadStatus::Succeeded),
|
|
||||||
RateLimitRefreshOutcome::RefreshRecovery
|
|
||||||
);
|
|
||||||
let next = refresh
|
|
||||||
.start(RateLimitRefreshOrigin::Recovery, &mut epoch)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
refresh.finish(next.0, next.1, epoch, RateLimitReadStatus::Succeeded),
|
|
||||||
RateLimitRefreshOutcome::Apply
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
use super::backend_banner_fallback_tests::fallback_response;
|
|
||||||
use super::*;
|
|
||||||
use crate::chatwidget::UserMessage;
|
|
||||||
use crate::chatwidget::tests::helpers::set_fast_mode_test_catalog_for_models;
|
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn backend_banner_fallback_applies_before_initial_and_queued_startup_prompts() -> Result<()> {
|
|
||||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
|
||||||
let mut config = app.config.clone();
|
|
||||||
config.model = Some("gpt-5.5".into());
|
|
||||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
||||||
let init = app.chatwidget_init_for_forked_or_resumed_thread(
|
|
||||||
&mut tui,
|
|
||||||
config.clone(),
|
|
||||||
Some(UserMessage::from("initial prompt")),
|
|
||||||
);
|
|
||||||
app.replace_chat_widget(ChatWidget::new_with_app_event(init));
|
|
||||||
set_chatgpt_auth(&mut app.chat_widget);
|
|
||||||
set_fast_mode_test_catalog_for_models(&mut app.chat_widget, "gpt-5.5", "gpt-5.6-terra");
|
|
||||||
app.model_catalog = app.chat_widget.model_catalog();
|
|
||||||
app.pending_startup_thread_start = true;
|
|
||||||
app.chat_widget.set_model("gpt-5.5");
|
|
||||||
app.chat_widget
|
|
||||||
.set_queue_submissions_until_session_configured(/*queue*/ true);
|
|
||||||
app.chat_widget
|
|
||||||
.apply_external_edit("queued follow-up".into());
|
|
||||||
app.chat_widget
|
|
||||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
||||||
let (mut server, requests, proxy) = session_lifecycle_requests::start_recording_app_server(
|
|
||||||
&config, /*blocked_thread_list*/ None, /*failed_thread_name*/ None,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let generation = app.rate_limit_hard_stop_generation;
|
|
||||||
app.handle_event(
|
|
||||||
&mut tui,
|
|
||||||
&mut server,
|
|
||||||
AppEvent::RateLimitsLoaded {
|
|
||||||
request_id: 1,
|
|
||||||
origin: RateLimitRefreshOrigin::StartupPrefetch {
|
|
||||||
reset_hint_request_id: 0,
|
|
||||||
},
|
|
||||||
hard_stop_generation: generation,
|
|
||||||
result: Ok(fallback_response()),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
assert!(requests.lock().unwrap().is_empty());
|
|
||||||
assert!(
|
|
||||||
!render_bottom_popup(&app.chat_widget, /*width*/ 72)
|
|
||||||
.contains("Selected model usage exhausted")
|
|
||||||
);
|
|
||||||
let started = server.start_thread(&config).await?;
|
|
||||||
let thread_id = started.session.thread_id;
|
|
||||||
requests.lock().unwrap().clear();
|
|
||||||
while events.try_recv().is_ok() {}
|
|
||||||
app.handle_startup_thread_started(&mut server, Ok(started))
|
|
||||||
.await?;
|
|
||||||
assert_eq!(app.active_thread_id, Some(thread_id));
|
|
||||||
let submissions = std::iter::from_fn(|| events.try_recv().ok())
|
|
||||||
.filter_map(|event| {
|
|
||||||
if let AppEvent::CodexOp(AppCommand::UserTurn { model, items, .. }) = event {
|
|
||||||
Some((model, items))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
assert_eq!(
|
|
||||||
submissions,
|
|
||||||
vec![(
|
|
||||||
"gpt-5.6-terra".into(),
|
|
||||||
vec![UserInput::Text {
|
|
||||||
text: "initial prompt".into(),
|
|
||||||
text_elements: Vec::new(),
|
|
||||||
}]
|
|
||||||
)]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
app.chat_widget.queued_user_message_texts(),
|
|
||||||
vec!["queued follow-up"]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
requests
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.map(|request| request.method.as_str())
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
vec!["thread/settings/update"]
|
|
||||||
);
|
|
||||||
server.shutdown().await?;
|
|
||||||
proxy.await??;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user