Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cli): read authoritative usage and spend from the Tokamak usage API (#9034)

Akarshan Biswas9925f8b6d9fa
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index 2f4c0cf60..c9826fbdc 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -80,7 +80,8 @@ bounded by `--max-turns` or by cancelling it.
<Callout type="warning">
`--max-session-tokens` and `[budget].max_tokens` do **not** stop a run. Crossing the ceiling is
advisory: the run compacts its history, records a note, and carries on, tool calls included. Use
-`--max-turns` for a hard bound on an unattended run.
+`--max-budget-usd` to bound what an unattended run may spend, or `--max-turns` to bound how many
+turns it may take.
</Callout>
```bash
@@ -105,6 +106,7 @@ jan cli agent run --max-turns 5 --max-session-tokens 20000 "triage the build fai
| `--no-worktree` | Work in the project directory, overriding a persistent `worktree` setting |
| `--max-turns <N>` | Hard cap on agentic turns. If the model is still calling tools at N the run fails with `reached the N-turn limit...` and a non-zero exit; with `--output-format json` the partial answer is still in `result`. Bounds the parent run only - subagent turns are not counted. `0` means unbounded, which is the default |
| `--max-session-tokens <N>` | Advisory token ceiling for this run, overriding `[budget].max_tokens`. Triggers compaction and a recorded note when passed; it does not terminate the run. `0` means no ceiling |
+| `--max-budget-usd <USD>` | Stop the run once it has spent this much, overriding `[budget].max_usd`. Priced from the provider's published rates, so a model with no published price is **refused** rather than run uncapped - including a subagent whose definition names its own model. Subagents inherit the ceiling. Compaction is billed against it like any other request. Stopping this way exits `0` with `stop_reason: budget_exceeded`; `0` as a limit stops at the first billed request |
| `--provider`, `--api-key` | Credential overrides for this run |
| `--output-format <FORMAT>` | `text` (default) streams the answer; `json` prints one result object; `stream-json` prints one JSON event per line |
| `--input-format <FORMAT>` | `text` (default) ignores stdin; `stream-json` reads client messages while the run is in flight. Requires `--output-format stream-json` |
@@ -167,7 +169,7 @@ had said before it broke as `result`:
| --- | --- |
| `protocol_version` | The wire contract this object belongs to. See [the protocol version](#the-protocol-version) |
| `result` | The final answer, or the partial answer of the turn that failed. Reasoning is stripped |
-| `stop_reason` | The upstream finish reason, or `error` |
+| `stop_reason` | The upstream finish reason, `budget_exceeded` when `--max-budget-usd` stopped the run, or `error` |
| `error.code` | `context_overflow`, `upstream_error`, `setup_error`, or the raw code |
| `session_id` | Short session id for `--resume`. `null` when the run failed before producing one |
| `num_turns` | Agent turns taken. Subagent turns are not counted |
@@ -181,6 +183,14 @@ consumers should branch on the difference rather than coalescing with `0`.
The process exit code is unchanged: `0` on success, `1` on failure.
+A run stopped by `--max-budget-usd` exits **`0`**: the turns it took are real work with a real
+answer, and the ceiling did what it was asked to do. Hitting `--max-turns` while the model is still
+calling tools exits **`1`**, because that one ends the run with no answer at all. So a plain-text
+consumer cannot tell a budget stop from a finished task by the exit code alone - the answer may be
+knowingly unfinished. A CI job that must distinguish them should read `stop_reason` from
+`--output-format json` and branch on `budget_exceeded`; in text mode the run records a
+`[cost ceiling reached]` note instead.
+
#### Streaming JSON, in both directions
`--output-format stream-json` prints one JSON object per line as the run proceeds -- assistant
diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdx
index 5436bfda5..261959388 100644
--- a/docs/src/pages/docs/agent/project-config.mdx
+++ b/docs/src/pages/docs/agent/project-config.mdx
@@ -80,6 +80,7 @@ instructions_file = "AGENT.md"
# 0 disables the cap.
[budget]
# max_tokens = 128000
+# max_usd = 5.00
[tools]
default = "read-only"
@@ -125,6 +126,7 @@ Desktop. Most projects don't need it. See [Providers](/docs/agent/providers#per-
| Key | Default | Description |
| --- | --- | --- |
| `max_tokens` | `128000` | Advisory token ceiling for one run (new spend across all turns). Set `0` to disable it. Overridden per invocation by `--max-session-tokens`. Defaults to `128000` when unset |
+| `max_usd` | unset | USD one run may spend before it stops -- a hard bound, unlike `max_tokens`. Priced from the provider's published rates, so a model with no published price is refused rather than run uncapped. Subagents inherit it. Overridden per invocation by `--max-budget-usd` |
A marker for how far one run has gone, distinct from the per-request context window. It tracks the
run's marginal token spend (replayed context is not recharged each turn).
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index 7e1a54941..780c269c7 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -49,8 +49,8 @@ See [Sessions](/docs/agent/sessions).
| `/plan [exit\|text]` | Enter read-only plan mode, optionally with a first message |
| `/todo [add [phase\|] text \| clear]` | Open the todo editor, append an item, or drop all |
| `/compact` | Summarize older turns to free up context |
-| `/context` | Show what is filling the context window, by category - opens a live overlay while the turn keeps running |
-| `/usage` | Show this session's tokens and estimated cost, per model. Priced from what the provider publishes; a model it publishes no price for is listed as such rather than counted as free |
+| `/context` | Show what is filling the context window, by category. Opens a readout docked above the input, live while the turn keeps running; Esc or `q` closes it |
+| `/usage [session\|run\|account\|daily\|requests\|limits\|<execution-id>]` | Bare: an overview of both answers -- this session's estimate over your account's recorded spend, each labelled with its source and never added together. The session half draws immediately; the account half fills in when the read lands, or says why it could not. `session` shows the local estimate alone: total tokens and estimated cost, then the costliest models behind it, priced from what the provider publishes (a model it publishes no price for is listed as such rather than counted as free); `m` expands the model list past the top few. The other views read what the provider actually recorded, each leading with the figure it was opened for -- account spend, the newest day, whether spending is allowed -- with breakdowns folded behind the same `m`. Reported amounts print exactly as the provider sent them, so they never read as a local estimate. Same docked readout as `/context`, and only one is open at a time; the input field is inactive while it is up |
| `/cancel [N]` | Cancel queued messages. Bare: all, or an index |
| `/agents` | Inspect running subagents: each one's stats and current activity |
| `/shells` (alias `/jobs`) | Inspect and stop background shell commands the agent left running |
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index ff9c50175..8fd87fc54 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -145,7 +145,10 @@ rmcp = { version = "3.2.0", features = [
"reqwest",
] }
serde = { version = "1.0", features = ["derive"] }
-serde_json = "1.0"
+# `raw_value` keeps a JSON number as the text the server sent. Money fields in
+# the Tokamak usage API must round-trip exactly, and a plain parse routes every
+# number through f64 (see core/cli/tokamak/usage.rs).
+serde_json = { version = "1.0", features = ["raw_value"] }
serde_yaml = "0.9.34"
toml = "0.8"
toml_edit = "0.23"
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rs
index d74c77b0b..d0543d7d9 100644
--- a/src-tauri/jan-cli/src/main.rs
+++ b/src-tauri/jan-cli/src/main.rs
@@ -163,12 +163,16 @@ impl ResumeArgs {
}
}
-/// Per-invocation cost limits for `jan cli agent run`. Both mirror the engine's
-/// own semantics: `0` means unbounded, and an unpassed flag leaves the config
-/// files (or, for turns, nothing at all) in charge.
+/// Per-invocation cost limits for `jan cli agent run`. All three mirror the
+/// engine's own semantics: an unpassed flag leaves the config files (or, for
+/// turns, nothing at all) in charge.
///
-/// Only `--max-turns` ends a run. The token ceiling is advisory: passing it
-/// compacts the conversation and records a note, then the run continues.
+/// Two of them stop a run and one does not. `--max-turns` bounds how many turns
+/// it may take, `--max-budget-usd` bounds what it may spend; the token ceiling
+/// is advisory, compacting the conversation and recording a note before the run
+/// continues. A money ceiling is the one a user reaching for a limit usually
+/// means: turns and tokens are both proxies for the number they actually care
+/// about.
#[derive(Args, Clone, Copy)]
struct BudgetArgs {
/// Fail the run after at most N agentic turns; bounds this run only, not
@@ -179,6 +183,11 @@ struct BudgetArgs {
/// compaction and a note, but does not stop the run (0 = no ceiling)
#[arg(long, value_name = "N")]
max_session_tokens: Option<u64>,
+ /// Stop the run once it has spent this much in USD, overriding
+ /// [budget].max_usd. Priced from the provider's published rates, so a
+ /// model with no published price is refused rather than run uncapped
+ #[arg(long, value_name = "USD")]
+ max_budget_usd: Option<f64>,
}
/// Same flags for `jan cli agent run`, which has a required positional TASK: a
@@ -226,26 +235,42 @@ enum Commands {
#[command(subcommand)]
cmd: AuthCommands,
},
- /// Manage provider credentials in ~/.jan/config.toml (used by the TUI and CLI)
+ /// Read recorded usage and spend from the provider's usage API
#[command(display_order = 4)]
+ Usage {
+ // Optional so bare `jan usage` answers "what have I spent" with the
+ // account summary. Unlike the TUI's bare `/usage` there is no session
+ // to estimate here -- a one-shot command has run no requests -- so the
+ // overview's local half does not exist and the account total is the
+ // whole answer.
+ #[command(subcommand)]
+ cmd: Option<UsageCommands>,
+ /// Print the provider's response body verbatim instead of a table.
+ /// Reshaping it would mean re-serializing money fields, which is how a
+ /// figure loses digits, so this forwards the bytes as received.
+ #[arg(long, global = true)]
+ json: bool,
+ },
+ /// Manage provider credentials in ~/.jan/config.toml (used by the TUI and CLI)
+ #[command(display_order = 5)]
Config {
#[command(subcommand)]
cmd: AgentConfigCommands,
},
/// Manage project-local plugins and their skills
- #[command(display_order = 5)]
+ #[command(display_order = 6)]
Plugin {
#[command(subcommand)]
cmd: PluginCommands,
},
/// Serve Jan's built-in tools to another agent over MCP
- #[command(display_order = 6)]
+ #[command(display_order = 7)]
Mcp {
#[command(subcommand)]
cmd: McpServeCommands,
},
/// Update this binary to the latest build of the channel it was built for
- #[command(display_order = 7)]
+ #[command(display_order = 8)]
Update {
/// Report whether an update exists without installing it
#[arg(long)]
@@ -287,6 +312,35 @@ enum McpServeCommands {
},
}
+/// Reads against the provider's usage API.
+///
+/// Deliberately a sibling of `jan auth` rather than a mode of the agent: these
+/// are account-level questions about money, answered by the server, and none of
+/// them runs a model or touches a project. Every one of them reports figures
+/// the provider recorded -- not the local per-session estimate the TUI's bare
+/// `/usage` prints, which is an estimate and says so.
+#[derive(Subcommand)]
+enum UsageCommands {
+ /// Usage across this account's credentials, not only the key in use
+ Account,
+ /// Daily usage totals
+ Daily,
+ /// Recently recorded requests
+ Requests,
+ /// Current usage-limit status (separate from wallet credit)
+ Limits,
+ /// Inspect one execution by its X-Tokamak-Execution-Id
+ Generation {
+ /// The execution id, from the response header of an inference request
+ id: String,
+ },
+ /// Find every execution tagged with an X-Client-Request-Id
+ Correlate {
+ /// The correlation id sent on the original request
+ client_request_id: String,
+ },
+}
+
/// Tokamak sign-in inspection and control.
#[derive(Subcommand)]
enum AuthCommands {
@@ -686,6 +740,12 @@ async fn main() {
std::process::exit(1);
}
}
+ Commands::Usage { cmd, json } => {
+ if let Err(e) = handle_usage(cmd, json).await {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ }
Commands::Config { cmd } => {
if let Err(e) = handle_agent_config(cmd) {
eprintln!("Error: {e}");
@@ -908,6 +968,7 @@ async fn handle_agent(cmd: AgentCommands) {
worktree: worktree.into_flag(),
max_turns: budget.max_turns,
max_session_tokens: budget.max_session_tokens,
+ max_budget_usd: budget.max_budget_usd,
..Default::default()
},
resume.into_request(),
@@ -953,6 +1014,58 @@ async fn handle_agent(cmd: AgentCommands) {
}
}
+/// `jan usage` handler: read recorded spend from the provider's usage API.
+///
+/// Every view goes through one fetch so failures, timeouts and the not-signed-in
+/// case are reported identically regardless of which endpoint was asked for. A
+/// generation lookup is then rendered field by field, because its schema is
+/// documented; the rest are printed as flattened `path value` pairs, so a
+/// field the server added since this build still shows up instead of being
+/// silently dropped by a struct that does not know about it.
+async fn handle_usage(cmd: Option<UsageCommands>, json: bool) -> Result<(), String> {
+ use app_lib::core::cli::tokamak::usage::{self, Query, UsageError};
+
+ let query = match &cmd {
+ None | Some(UsageCommands::Account) => Query::Summary,
+ Some(UsageCommands::Daily) => Query::Daily,
+ Some(UsageCommands::Requests) => Query::Requests,
+ Some(UsageCommands::Limits) => Query::Limits,
+ Some(UsageCommands::Generation { id }) => Query::Generation(id.clone()),
+ Some(UsageCommands::Correlate { client_request_id }) => {
+ Query::Correlated(client_request_id.clone())
+ }
+ };
+
+ let payload = match usage::fetch(&query).await {
+ Ok(payload) => payload,
+ // A not-found is a real answer to "what did this execution cost", not a
+ // crash, but it is still a failed lookup: exit non-zero so a script
+ // cannot read it as a zero charge.
+ Err(e @ UsageError::NotFound) => return Err(e.to_string()),
+ Err(e) => return Err(e.to_string()),
+ };
+
+ if json {
+ println!("{}", payload.as_str());
+ return Ok(());
+ }
+
+ // The same renderer the TUI readout draws, so the two surfaces cannot
+ // drift: one place decides how a reported charge is displayed. `Fixed`
+ // because nothing is folded here -- a fold is an interactive affordance,
+ // and a piped view that silently dropped rows would be wrong for the
+ // scripts reading it -- and because there is no `m` to press in a pipe, so
+ // the keybinding hint must not print either.
+ for line in app_lib::core::cli::usage_view::reported_usage_lines(
+ &query,
+ &payload,
+ app_lib::core::cli::usage_view::Fold::Fixed,
+ ) {
+ println!("{line}");
+ }
+ Ok(())
+}
+
/// `jan auth` handler: report sign-in state or sign out.
async fn handle_auth(cmd: AuthCommands) -> Result<(), String> {
use app_lib::core::cli::tokamak;
@@ -1341,6 +1454,21 @@ mod tests {
let zero = parsed_budget(&["--max-turns", "0", "--max-session-tokens", "0"]);
assert_eq!(zero.max_turns, Some(0));
assert_eq!(zero.max_session_tokens, Some(0));
+
+ // The money ceiling parses as a decimal amount, not a token count: a
+ // budget users write as "$2.50" must not be truncated to 2 on the way
+ // in, which is the failure an integer type here would produce.
+ assert_eq!(parsed_budget(&[]).max_budget_usd, None);
+ assert_eq!(
+ parsed_budget(&["--max-budget-usd", "2.50"]).max_budget_usd,
+ Some(2.50)
+ );
+ // `0` is a real ceiling (stop at the first billed request), so it must
+ // survive as `Some(0.0)` rather than collapsing into "unset".
+ assert_eq!(
+ parsed_budget(&["--max-budget-usd", "0"]).max_budget_usd,
+ Some(0.0)
+ );
}
/// Parse `jan cli agent run <task> <extra...>` and pull out its input format.
@@ -1557,6 +1685,63 @@ mod tests {
));
}
+ #[test]
+ fn usage_subcommands_parse() {
+ let view = |argv: &[&str]| {
+ let mut full = vec!["jan", "usage"];
+ full.extend_from_slice(argv);
+ match Cli::parse_from(full).command {
+ Some(Commands::Usage { cmd, .. }) => cmd,
+ other => panic!("expected a usage command, got {:?}", other.is_some()),
+ }
+ };
+ assert!(matches!(view(&["account"]), Some(UsageCommands::Account)));
+ assert!(matches!(view(&["daily"]), Some(UsageCommands::Daily)));
+ assert!(matches!(view(&["requests"]), Some(UsageCommands::Requests)));
+ assert!(matches!(view(&["limits"]), Some(UsageCommands::Limits)));
+ match view(&["generation", "exec-1"]) {
+ Some(UsageCommands::Generation { id }) => assert_eq!(id, "exec-1"),
+ _ => panic!("expected a generation lookup"),
+ }
+ match view(&["correlate", "my-app-request-001"]) {
+ Some(UsageCommands::Correlate { client_request_id }) => {
+ assert_eq!(client_request_id, "my-app-request-001");
+ }
+ _ => panic!("expected a correlation lookup"),
+ }
+ // Bare `jan usage` is the account summary: with no session to
+ // estimate, the recorded total is the only answer there is.
+ assert!(view(&[]).is_none(), "the subcommand is optional");
+ }
+
+ /// An id is required, not optional: a bare `jan usage generation` would
+ /// otherwise have to invent one.
+ #[test]
+ fn a_generation_lookup_requires_an_id() {
+ assert!(Cli::try_parse_from(["jan", "usage", "generation"]).is_err());
+ assert!(Cli::try_parse_from(["jan", "usage", "correlate"]).is_err());
+ }
+
+ #[test]
+ fn usage_json_flag_parses_after_the_subcommand() {
+ let cli = Cli::parse_from(["jan", "usage", "account", "--json"]);
+ assert!(matches!(
+ cli.command,
+ Some(Commands::Usage {
+ cmd: Some(UsageCommands::Account),
+ json: true
+ })
+ ));
+ let cli = Cli::parse_from(["jan", "usage", "account"]);
+ assert!(matches!(
+ cli.command,
+ Some(Commands::Usage {
+ cmd: Some(UsageCommands::Account),
+ json: false
+ })
+ ));
+ }
+
/// Parse a `jan cli mcp <cmd> <extra...>` argv and pull out the subcommand.
fn parsed_mcp(extra: &[&str]) -> McpCommands {
let mut argv = vec!["jan", "cli", "mcp"];
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rs
index 9f90c94c1..698eedecf 100644
--- a/src-tauri/src/core/agent/compaction.rs
+++ b/src-tauri/src/core/agent/compaction.rs
@@ -317,7 +317,9 @@ pub(crate) async fn compact_conversation(
};
let kept = &rest[cut..];
- let summary = summarize(&rest[..cut], model_id, model).await?;
+ // The interactive `/compact` meters nothing: it is not inside a run's
+ // budget, so there is no ceiling for this request to be charged against.
+ let (summary, _usage) = summarize(&rest[..cut], model_id, model).await?;
let mut out = Vec::with_capacity(system_msgs.len() + 1 + kept.len());
out.extend_from_slice(system_msgs);
@@ -330,14 +332,20 @@ pub(crate) async fn compact_conversation(
/// transcript's compaction path, where the summary becomes an event rather than
/// a rewritten list. The node carries [`SUMMARY_MARKER`], so a later turn reads
/// it as condensed history instead of mistaking it for a prompt.
+///
+/// Returns the summarizer's own reported usage alongside the node. A compaction
+/// is a paid request like any other -- a turn can make several of them (the
+/// preflight plus up to `MAX_COMPACTION_ATTEMPTS` overflow retries) -- so the
+/// caller folds it into the run's budget instead of letting the spend go
+/// unrecorded. `None` when the summarizer reported none or never ran.
pub(crate) async fn summarize_span(
span: &[Value],
model_id: &str,
model: &dyn ModelInvoker,
-) -> Result<Value, String> {
+) -> Result<(Value, Option<crate::core::agent::events::Usage>), String> {
summarize(span, model_id, model)
.await
- .map(|text| summary_message(&text))
+ .map(|(text, usage)| (summary_message(&text), usage))
}
/// Flatten a span of wire messages into a plain-text transcript. Rendering
@@ -407,10 +415,18 @@ fn clamp_middle(text: &str, max: usize) -> String {
/// the caller must block rather than fabricate a fallback note for a
/// smaller-window model. Every other failure and empty/unreadable completion
/// stays recoverable and returns [`FALLBACK_NOTE`].
-async fn summarize(dropped: &[Value], model_id: &str, model: &dyn ModelInvoker) -> Result<String, String> {
+/// The reported usage rides back with the text so the caller can charge it: see
+/// [`summarize_span`]. A path that produced no request (an empty span) or a
+/// failure that degraded to [`FALLBACK_NOTE`] reports `None` rather than zeros,
+/// which is the same "nothing to charge" answer without inventing a figure.
+async fn summarize(
+ dropped: &[Value],
+ model_id: &str,
+ model: &dyn ModelInvoker,
+) -> Result<(String, Option<crate::core::agent::events::Usage>), String> {
let transcript = clamp_middle(&render_transcript(dropped), SUMMARY_INPUT_CHARS);
if transcript.trim().is_empty() {
- return Ok(FALLBACK_NOTE.to_string());
+ return Ok((FALLBACK_NOTE.to_string(), None));
}
let request = json!({
"model": model_id,
@@ -430,7 +446,10 @@ async fn summarize(dropped: &[Value], model_id: &str, model: &dyn ModelInvoker)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string);
- Ok(summary.unwrap_or_else(|| FALLBACK_NOTE.to_string()))
+ // Charged whatever the body said: a completion whose text was empty
+ // still cost what the provider reported for it.
+ let usage = crate::core::agent::events::Usage::from_completion(&completion);
+ Ok((summary.unwrap_or_else(|| FALLBACK_NOTE.to_string()), usage))
}
Err(e) => {
// A model-switch compaction targets the (smaller) new model: if the
@@ -439,7 +458,7 @@ async fn summarize(dropped: &[Value], model_id: &str, model: &dyn ModelInvoker)
if crate::core::agent::upstream::is_context_overflow_error(&e) {
Err(e)
} else {
- Ok(FALLBACK_NOTE.to_string())
+ Ok((FALLBACK_NOTE.to_string(), None))
}
}
}
diff --git a/src-tauri/src/core/agent/correlation.rs b/src-tauri/src/core/agent/correlation.rs
new file mode 100644
index 000000000..f847a1621
--- /dev/null
+++ b/src-tauri/src/core/agent/correlation.rs
@@ -0,0 +1,196 @@
+//! Correlating an agent request with the provider's billing record.
+//!
+//! A charge is recorded by the provider, keyed by an execution id. To ask what
+//! a request cost you need a handle on that record, and there are exactly two
+//! ways to get one:
+//!
+//! 1. **The execution id the provider returns** on the inference response, in
+//! the `X-Tokamak-Execution-Id` header. This is the direct handle, but it is
+//! only readable where the agent owns the HTTP response -- the native-wire
+//! converter path. The default path runs through `genai`, which drops the
+//! response headers on a successful stream (they survive only inside an
+//! error), so there is nothing to read there.
+//! 2. **A correlation id the caller sends**, in `X-Client-Request-Id`. The
+//! provider records it against every execution the request produced, and it
+//! is searchable afterwards. This works on every path, including the one
+//! where the execution id is unreachable, which is why it is the mechanism
+//! the agent relies on rather than a convenience.
+//!
+//! The two are not equivalent and this module does not pretend otherwise. An
+//! execution id names exactly one execution; a correlation id may match several
+//! and is explicitly not an idempotency key, so a retried request shares it.
+//! That is a property to report, not to engineer around: a turn that was
+//! retried really did produce more than one execution, and more than one
+//! charge.
+//!
+//! Feature-neutral on purpose. The header names and the id format have to be
+//! identical in the desktop and `cli` builds -- a correlation id that differs
+//! between them would silently fail to correlate, which is the one failure mode
+//! that looks like success.
+
+/// Header the provider returns on an inference response, naming that execution.
+///
+/// Readable only where the agent holds the `reqwest::Response` itself. See the
+/// module docs for why the default path cannot see it.
+pub const EXECUTION_ID_HEADER: &str = "X-Tokamak-Execution-Id";
+
+/// Header the agent sends so its requests can be found later.
+///
+/// A correlation value can match several executions; it is not an idempotency
+/// key, and nothing here treats it as one.
+pub const CLIENT_REQUEST_ID_HEADER: &str = "X-Client-Request-Id";
+
+/// Longest correlation id the agent will send.
+///
+/// A header a provider truncates or rejects correlates nothing, and the failure
+/// is invisible at send time -- the request succeeds and only the later lookup
+/// comes back empty. Bounded well under any plausible header limit so that
+/// cannot happen.
+const MAX_ID_LEN: usize = 96;
+
+/// The correlation id for a session, or `None` when there is no session to
+/// correlate.
+///
+/// Scoped to the session rather than the turn deliberately. The question this
+/// answers in practice is "what did this run cost", which is a sum over every
+/// execution the session produced, and a session-wide id is what makes that a
+/// single lookup. Per-turn ids would answer a narrower question at the cost of
+/// making the common one N queries.
+pub fn session_request_id(session_id: Option<&str>) -> Option<String> {
+ let session = session_id?.trim();
+ if session.is_empty() {
+ return None;
+ }
+ // Prefixed so a correlation id is recognizable as ours in a provider's
+ // dashboard, where it sits beside ids from every other client.
+ let id = format!("jan-{session}");
+ Some(sanitize(&id))
+}
+
+/// Reduce an id to characters that are safe in an HTTP header value and stable
+/// across the two builds.
+///
+/// Anything outside a conservative ASCII set becomes `-`: a header value with a
+/// control character is rejected by `reqwest` at send time, which would turn a
+/// correlation id into a failed request rather than a failed lookup.
+fn sanitize(raw: &str) -> String {
+ raw.chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
+ c
+ } else {
+ '-'
+ }
+ })
+ .take(MAX_ID_LEN)
+ .collect()
+}
+
+/// Where a captured execution id rides back from the send path to the agent
+/// loop.
+///
+/// The completion JSON is the only value the invoker returns, so an id read
+/// from the response headers is attached to it under this key. Namespaced with
+/// a leading underscore so it cannot collide with a field a provider actually
+/// sends.
+///
+/// Nothing strips it back out, and nothing needs to: every consumer projects
+/// the fields it wants (`choices[].message`, `usage`, `finish_reason`) rather
+/// than forwarding the body, so this key never reaches a transcript or a
+/// resent request. A consumer that did forward a whole completion would have
+/// to drop it here first.
+pub const EXECUTION_ID_FIELD: &str = "_jan_execution_id";
+
+/// Attach a captured execution id to a completion body.
+pub fn attach_execution_id(completion: &mut serde_json::Value, execution_id: &str) {
+ if let Some(obj) = completion.as_object_mut() {
+ obj.insert(
+ EXECUTION_ID_FIELD.to_string(),
+ serde_json::Value::String(execution_id.to_string()),
+ );
+ }
+}
+
+/// Read back an execution id attached by [`attach_execution_id`].
+pub fn execution_id_of(completion: &serde_json::Value) -> Option<String> {
+ completion
+ .get(EXECUTION_ID_FIELD)?
+ .as_str()
+ .filter(|id| !id.is_empty())
+ .map(str::to_string)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_session_yields_a_recognizable_id() {
+ let id = session_request_id(Some("0b7c1d2e-3f45")).expect("a session has an id");
+ assert_eq!(id, "jan-0b7c1d2e-3f45");
+ }
+
+ /// No session means nothing to correlate, and sending a placeholder would
+ /// pollute the provider's records with an id that matches every run.
+ #[test]
+ fn no_session_means_no_correlation_id() {
+ assert_eq!(session_request_id(None), None);
+ assert_eq!(session_request_id(Some("")), None);
+ assert_eq!(session_request_id(Some(" ")), None);
+ }
+
+ /// A header value with a control character is rejected at send time, which
+ /// would turn a missing lookup into a failed request.
+ #[test]
+ fn an_id_is_reduced_to_header_safe_characters() {
+ let id = session_request_id(Some("we ird\n\tvalue")).expect("still an id");
+ assert!(
+ id.chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.'),
+ "{id}"
+ );
+ assert!(!id.contains('\n') && !id.contains(' '), "{id}");
+ }
+
+ #[test]
+ fn an_id_is_bounded() {
+ let id = session_request_id(Some(&"x".repeat(500))).expect("still an id");
+ assert!(id.len() <= MAX_ID_LEN, "{} chars", id.len());
+ }
+
+ /// The same session must produce the same id in both builds and on every
+ /// turn, or the correlation finds only part of the run.
+ #[test]
+ fn the_id_is_stable_for_a_session() {
+ let a = session_request_id(Some("session-1"));
+ let b = session_request_id(Some("session-1"));
+ assert_eq!(a, b);
+ assert_ne!(a, session_request_id(Some("session-2")));
+ }
+
+ #[test]
+ fn an_execution_id_round_trips_through_the_completion() {
+ let mut completion = serde_json::json!({"choices": [], "usage": {}});
+ assert_eq!(execution_id_of(&completion), None);
+ attach_execution_id(&mut completion, "exec-9");
+ assert_eq!(execution_id_of(&completion), Some("exec-9".to_string()));
+ }
+
+ /// An empty header value is not an execution id; treating it as one would
+ /// produce a lookup that can only come back not-found.
+ #[test]
+ fn an_empty_execution_id_is_not_attached_as_one() {
+ let mut completion = serde_json::json!({});
+ attach_execution_id(&mut completion, "");
+ assert_eq!(execution_id_of(&completion), None);
+ }
+
+ /// A completion that is not an object (an error shape) must not panic the
+ /// attach path.
+ #[test]
+ fn attaching_to_a_non_object_is_a_no_op() {
+ let mut completion = serde_json::json!("not an object");
+ attach_execution_id(&mut completion, "exec-1");
+ assert_eq!(execution_id_of(&completion), None);
+ }
+}
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index 4c8e91de3..f4077e124 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -191,7 +191,21 @@ pub enum StreamEvent {
/// all. Consumers accumulate these to show context pressure, output
/// volume, and throughput while the work is still happening -- for the
/// parent run and, via the [`Subagent`] bracket, for each child.
- TurnUsage { usage: Usage },
+ TurnUsage {
+ usage: Usage,
+ /// The provider's id for the execution that produced this usage, when
+ /// it reported one. This is the handle a per-request billing lookup is
+ /// keyed by, so a consumer can ask what this one request actually
+ /// cost rather than only what it estimates.
+ ///
+ /// A sibling of `usage` rather than a field inside it, because it is a
+ /// billing handle and not a token count. Absent on the default upstream
+ /// path, which cannot see the response headers (see
+ /// [`crate::core::agent::correlation`]); that is a limitation to report,
+ /// not a reason to synthesize one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ execution_id: Option<String>,
+ },
/// Terminal success: the model returned a final (tool-free) completion.
Done {
stop_reason: String,
@@ -518,6 +532,7 @@ pub(crate) mod tests {
cached_tokens: Some(64),
cache_write_tokens: None,
},
+ execution_id: None,
},
),
(
diff --git a/src-tauri/src/core/agent/genai_bridge.rs b/src-tauri/src/core/agent/genai_bridge.rs
index 34425c5a2..e48a44b9c 100644
--- a/src-tauri/src/core/agent/genai_bridge.rs
+++ b/src-tauri/src/core/agent/genai_bridge.rs
@@ -99,6 +99,7 @@ fn client_for(
request_url: &str,
api_key: Option<&str>,
adapter: AdapterKind,
+ client_request_id: Option<&str>,
) -> Client {
let endpoint = Endpoint::from_owned(endpoint_base.to_string());
@@ -121,6 +122,16 @@ fn client_for(
if let Some(key) = api_key.filter(|k| !k.is_empty()) {
headers.push(("Authorization".to_string(), format!("Bearer {key}")));
}
+ // The correlation id has to go in here rather than through
+ // `ChatOptions::with_extra_headers`: genai overwrites the whole header map
+ // with this override's when `RequestOverride` is set, which it always is on
+ // this path, so extra headers set anywhere else are silently dropped.
+ if let Some(id) = client_request_id.filter(|id| !id.is_empty()) {
+ headers.push((
+ super::correlation::CLIENT_REQUEST_ID_HEADER.to_string(),
+ id.to_string(),
+ ));
+ }
let auth = AuthData::RequestOverride {
url: request_url.to_string(),
headers: genai::Headers::from(headers),
@@ -622,6 +633,7 @@ pub(crate) async fn stream_chat_completions(
api_type: Option<&str>,
body: &serde_json::Value,
events: &mpsc::UnboundedSender<StreamEvent>,
+ client_request_id: Option<&str>,
) -> Result<serde_json::Value, String> {
let (model, chat_req) = chat_request_from_body(body)?;
let options = options_from_body(body);
@@ -638,7 +650,14 @@ pub(crate) async fn stream_chat_completions(
let mut last_err = String::from("Upstream request failed");
for (key_index, key) in keys.iter().enumerate() {
- let client = client_for(http, &endpoint_base, upstream_url, *key, adapter);
+ let client = client_for(
+ http,
+ &endpoint_base,
+ upstream_url,
+ *key,
+ adapter,
+ client_request_id,
+ );
for attempt in 0..MAX_ATTEMPTS {
let mut progressed = false;
@@ -1213,7 +1232,7 @@ mod tests {
async fn run(url: &str, keys: &[String], events: &mpsc::UnboundedSender<StreamEvent>)
-> Result<serde_json::Value, String> {
- stream_chat_completions(&build_http_client(), url, keys, None, &body(), events).await
+ stream_chat_completions(&build_http_client(), url, keys, None, &body(), events, None).await
}
#[tokio::test]
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 3ea81836b..cece0fe19 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -595,6 +595,58 @@ pub(crate) fn set_default_model_if_unset(model: &str) -> Result<bool, String> {
Ok(true)
}
+/// Why `default_model` was (re)pointed, so a caller can tell the user which of
+/// the two happened -- adopting a default is routine, replacing one the user
+/// chose needs saying out loud.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum DefaultModelChange {
+ /// There was no default; `model` was adopted.
+ Adopted,
+ /// The previous default is no longer offered by any provider, so it was
+ /// replaced by `model`.
+ Repointed,
+}
+
+/// Point `default_model` at `model` when there is no default, **or** when the
+/// current default is not offered by any configured provider. Returns what
+/// changed, or `None` when the existing default was left alone.
+///
+/// The second case is the one [`set_default_model_if_unset`] cannot handle. A
+/// sign-in replaces a provider's roster wholesale, so a re-login after the
+/// upstream retires a model leaves `default_model` pointing at something no
+/// provider serves. That is not an "explicit choice" worth protecting any more:
+/// it is a fossil, and every run fails on it with a 404 (or, for a cost
+/// ceiling, is refused as unpriceable) with nothing connecting the failure to
+/// the sign-in that caused it.
+///
+/// A default some *other* provider still offers is left alone -- this provider's
+/// roster says nothing about models it never served.
+pub(crate) fn adopt_default_model(model: &str) -> Result<Option<DefaultModelChange>, String> {
+ let model = model.trim();
+ if model.is_empty() {
+ return Ok(None);
+ }
+ let mut config = load_raw()?;
+ let current = config
+ .default_model
+ .as_deref()
+ .map(str::trim)
+ .filter(|m| !m.is_empty())
+ .map(str::to_string);
+ let change = match current {
+ None => DefaultModelChange::Adopted,
+ // Already fine, and re-pointing an offered default would overwrite a
+ // deliberate choice on every sign-in.
+ Some(current) if config.providers.values().any(|p| p.models.contains(&current)) => {
+ return Ok(None)
+ }
+ Some(_) => DefaultModelChange::Repointed,
+ };
+ config.default_model = Some(model.to_string());
+ write_raw(&config)?;
+ Ok(Some(change))
+}
+
/// Server-assigned metadata for a provider's stored key, when a v5 device-flow
/// login recorded any. Used by `jan auth status` / the expiry warning and by
/// `jan auth logout` to revoke the exact key.
@@ -1299,6 +1351,48 @@ models = ["gpt-4o"]
});
}
+ /// `adopt_default_model` is the sign-in half that `set_default_model_if_unset`
+ /// cannot do: it distinguishes "the user chose this" from "this is a fossil
+ /// no configured provider serves any more".
+ #[test]
+ fn adopting_a_default_replaces_only_one_no_provider_offers() {
+ with_temp_home(|_| {
+ let offer = |models: &[&str]| {
+ set_provider(
+ "tokamak",
+ ProviderUpdate {
+ models: Some(models.iter().map(|m| (*m).to_string()).collect()),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ };
+
+ // Nothing chosen yet: adopted.
+ offer(&["m1", "m2"]);
+ assert_eq!(
+ adopt_default_model("m1").expect("adopt"),
+ Some(DefaultModelChange::Adopted)
+ );
+
+ // Still offered, so it is a live choice and must survive.
+ assert_eq!(adopt_default_model("m2").expect("leave"), None);
+ assert_eq!(default_model().expect("read").as_deref(), Some("m1"));
+
+ // Retired upstream: now it is a fossil, and re-pointing is reported.
+ offer(&["m2", "m3"]);
+ assert_eq!(
+ adopt_default_model("m2").expect("repoint"),
+ Some(DefaultModelChange::Repointed)
+ );
+ assert_eq!(default_model().expect("read").as_deref(), Some("m2"));
+
+ // A blank candidate is never written: it would read as configured.
+ assert_eq!(adopt_default_model(" ").expect("blank"), None);
+ assert_eq!(default_model().expect("read").as_deref(), Some("m2"));
+ });
+ }
+
#[test]
fn default_model_set_keeps_existing_providers_and_rejects_blank() {
with_temp_home(|_| {
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index c050383e2..481b224d8 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -255,6 +255,11 @@ struct HttpModelInvoker {
/// Native provider converters still use reqwest 0.12 while the default
/// agent path uses genai's reqwest 0.13 client.
converter_client: reqwest::Client,
+ /// Correlation id sent with every request this invoker makes, so the run's
+ /// executions are findable in the provider's usage records afterwards. See
+ /// [`crate::core::agent::correlation`]. `None` when the run has no session
+ /// to correlate.
+ client_request_id: Option<String>,
}
fn converter_http_client() -> reqwest::Client {
@@ -289,6 +294,7 @@ impl ModelInvoker for HttpModelInvoker {
converter.as_ref(),
&normalized,
events,
+ self.client_request_id.as_deref(),
)
.await
} else {
@@ -300,6 +306,7 @@ impl ModelInvoker for HttpModelInvoker {
None,
&normalized,
events,
+ self.client_request_id.as_deref(),
)
.await
}
@@ -336,6 +343,9 @@ struct SubagentContext {
parent_args: OrchestrationArgs,
model_id: String,
max_session_tokens: Option<u64>,
+ /// The run's money ceiling, forwarded to every child (see
+ /// [`crate::core::agent::subagent::ParentRun::cost_remaining`]).
+ cost_ceiling: Option<crate::core::agent::session::CostCeiling>,
/// The parent's `send_reasoning`, forwarded to every child body: a child
/// resends the reasoning of its own tool-call turns, so an opt-out that
/// stopped at the parent would still break a strict provider.
@@ -923,6 +933,7 @@ impl CompositeToolInvoker {
model: ctx.model_id.clone(),
budget_remaining: ctx.max_session_tokens,
send_reasoning: ctx.send_reasoning,
+ cost_remaining: ctx.cost_ceiling,
},
&self.events,
// Unconfined means no scratch: the tools see the real
@@ -2130,6 +2141,30 @@ fn advertise_local_tools(
}
}
+/// The last completion of a run stopped by its money ceiling, rewritten into a
+/// terminal answer.
+///
+/// Two things have to change. The `finish_reason` becomes `budget_exceeded`, so
+/// a caller can tell a run that ran out of money from one the model chose to
+/// end -- the difference between "here is your answer" and "here is as far as
+/// your budget got". And any `tool_calls` are dropped: this completion is
+/// returned *instead of* executing them, so leaving them on the message would
+/// hand the caller an assistant turn whose calls are never answered, which is
+/// an invalid conversation to resume from.
+fn halted_over_budget(mut completion: serde_json::Value) -> serde_json::Value {
+ if let Some(choice) = completion
+ .get_mut("choices")
+ .and_then(|c| c.as_array_mut())
+ .and_then(|choices| choices.first_mut())
+ {
+ if let Some(message) = choice.get_mut("message").and_then(|m| m.as_object_mut()) {
+ message.remove("tool_calls");
+ }
+ choice["finish_reason"] = serde_json::json!("budget_exceeded");
+ }
+ completion
+}
+
fn stop_reason_of(completion: &serde_json::Value) -> String {
completion
.get("choices")
@@ -2659,6 +2694,9 @@ async fn orchestrate_inner(
.await
.and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),
converter_client: converter_http_client(),
+ client_request_id: crate::core::agent::correlation::session_request_id(
+ args.session_id.as_deref(),
+ ),
};
let mcp_tools = McpToolInvoker {
tool_to_server,
@@ -2667,7 +2705,8 @@ async fn orchestrate_inner(
};
let max_session_tokens = body_session_budget(json_body);
- let mut budget = SessionBudget::new(max_session_tokens);
+ let cost_ceiling = body_cost_ceiling(json_body);
+ let mut budget = SessionBudget::new(max_session_tokens).with_cost_ceiling(cost_ceiling);
// Top-level runs index their final assistant answer into project memory;
// isolated child (subagent) runs skip it to keep history independent.
@@ -2695,6 +2734,7 @@ async fn orchestrate_inner(
parent_args: args.clone(),
model_id: model_id.clone(),
max_session_tokens,
+ cost_ceiling,
send_reasoning: body_send_reasoning(json_body),
bg: bg.clone(),
});
@@ -3067,6 +3107,12 @@ pub(crate) async fn compact_history(
.await
.and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),
converter_client: converter_http_client(),
+ // A compaction call is billed to the same session as the turn that
+ // triggered it, so it carries the same correlation id: leaving it out
+ // would make the session's recorded spend smaller than the bill.
+ client_request_id: crate::core::agent::correlation::session_request_id(
+ args.session_id.as_deref(),
+ ),
};
crate::core::agent::compaction::compact_conversation(messages, model_id, &model, keep_recent)
.await
@@ -3101,6 +3147,10 @@ pub(crate) async fn evaluate_goal(
.await
.and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),
converter_client: converter_http_client(),
+ // Same session, same bill (see `compact_history`).
+ client_request_id: crate::core::agent::correlation::session_request_id(
+ args.session_id.as_deref(),
+ ),
};
crate::core::agent::goal::evaluate(smol_model_id, condition, messages, &model).await
}
@@ -3154,6 +3204,35 @@ fn body_session_budget(json_body: &serde_json::Value) -> Option<u64> {
.filter(|v| *v > 0)
}
+/// Money ceiling for a request body: `max_budget_usd` plus the `token_rates` to
+/// charge against. Both are required, because a limit with no prices cannot be
+/// enforced and prices with no limit meter nothing -- either alone is a
+/// configuration the caller got wrong, and silently running uncapped is the
+/// one outcome a cost ceiling must never produce. The CLI refuses that case up
+/// front (`resolve_cost_ceiling`); here it simply does not meter.
+///
+/// `0` is not special-cased: a `0` ceiling stops the run at the first billed
+/// request, which is what asking to spend nothing means.
+fn body_cost_ceiling(
+ json_body: &serde_json::Value,
+) -> Option<crate::core::agent::session::CostCeiling> {
+ let max_usd = json_body
+ .get("max_budget_usd")
+ .and_then(|v| v.as_f64())
+ .filter(|v| v.is_finite() && *v >= 0.0)?;
+ let rates = json_body.get("token_rates")?;
+ let rate = |key: &str| rates.get(key).and_then(|v| v.as_f64()).filter(|v| *v >= 0.0);
+ Some(crate::core::agent::session::CostCeiling {
+ rates: crate::core::agent::session::TokenRates {
+ prompt_usd: rate("prompt_usd")?,
+ completion_usd: rate("completion_usd")?,
+ cache_read_usd: rate("cache_read_usd"),
+ cache_write_usd: rate("cache_write_usd"),
+ },
+ max_usd,
+ })
+}
+
async fn receive_steering(
steering: Option<&mpsc::UnboundedSender<SteeringRequest>>,
messages: Vec<serde_json::Value>,
@@ -3244,18 +3323,25 @@ fn record_assistant_turn(transcript: &mut Transcript, message: &serde_json::Valu
/// The original span stays in the record - only the projection omits it - so a
/// later turn, a different provider, or a changed `keep_recent` can still
/// rebuild from it.
+///
+/// The summarizer's request is billed like any other, so its usage is folded
+/// into `budget` here. A turn can compact several times (the preflight plus the
+/// overflow retries), and spend the budget never saw would make `/usage` and
+/// the money ceiling agree with each other while both undercounted.
async fn compact(
transcript: &mut Transcript,
keep_recent: usize,
model_id: &str,
model: &dyn ModelInvoker,
+ budget: &mut SessionBudget,
) -> Result<Option<usize>, String> {
let Some(plan) = transcript.compaction_plan(keep_recent) else {
return Ok(None);
};
let summarized = plan.summarize.len();
- let summary =
+ let (summary, usage) =
crate::core::agent::compaction::summarize_span(&plan.summarize, model_id, model).await?;
+ budget.record_side_request(&usage);
transcript.record_compaction(summary, plan.covers);
Ok(Some(summarized))
}
@@ -3308,8 +3394,44 @@ async fn run_turn_cycle(
let mut closeout_nudged = false;
// The monitor set last published as `StreamEvent::Monitors`.
let mut shown_monitors = Vec::new();
+ // The last completion this cycle received, so a run stopped by its money
+ // ceiling returns the work it actually did rather than an error with no
+ // answer in it. `None` only before the first request.
+ let mut last_completion: Option<serde_json::Value> = None;
while unlimited || turn < max_turns {
+ // The money ceiling is enforced here, at the one point every path that
+ // would start another request passes through -- the `continue`s below
+ // (truncated response, closeout nudge, steering, tool results) each
+ // lead back to a paid request, so checking at any one of them would
+ // leave the others uncapped.
+ //
+ // A ceiling stops the run; it does not fail it. The turns already taken
+ // are real work the user is being billed for, so the answer is returned
+ // with `finish_reason: "budget_exceeded"` rather than discarded into an
+ // error with no result.
+ if budget.over_cost_ceiling() {
+ if let Some(completion) = last_completion.take() {
+ let spent = budget.spent_usd().unwrap_or(0.0);
+ let max = budget.max_usd().unwrap_or(0.0);
+ log::info!("agent: stopping the run, spent ${spent:.4} of a ${max:.4} ceiling");
+ // Recorded so a resumed thread shows why it stopped mid-task,
+ // rather than looking like the model chose to stop. A system
+ // note, not an assistant turn: the model never wrote it.
+ transcript.record_message(serde_json::json!({
+ "role": "system",
+ "content": format!(
+ "[cost ceiling reached] This run stopped after spending about \
+ ${spent:.4} against its ${max:.4} ceiling. The task may be \
+ unfinished; raising --max-budget-usd and resuming continues it."
+ ),
+ }));
+ let _ = events.send(StreamEvent::MessagesUpdated {
+ messages: client_history(&transcript, send_reasoning),
+ });
+ return Ok(halted_over_budget(completion));
+ }
+ }
for message in receive_steering(
steering,
project(&transcript, volatile_system.as_deref(), send_reasoning),
@@ -3380,15 +3502,18 @@ async fn run_turn_cycle(
// nothing safe left to drop, and retrying here would spin.
if !preflighted {
preflighted = true;
- if let Some(budget) = compaction {
+ // Named apart from the run's `budget` (money and tokens
+ // spent), which the compaction below is itself charged to.
+ if let Some(window) = compaction {
let estimate =
crate::core::agent::compaction::estimate_request_tokens(&request_value);
- if estimate > budget.trigger_tokens() {
+ if estimate > window.trigger_tokens() {
if let Some(dropped) = compact(
&mut transcript,
crate::core::agent::compaction::DEFAULT_KEEP_RECENT,
model_id,
model,
+ budget,
)
.await?
{
@@ -3396,8 +3521,8 @@ async fn run_turn_cycle(
"agent: prompt estimated at {estimate} tokens against a {} \
token trigger on a {} token window, compacted {dropped} \
messages into a summary before dispatch",
- budget.trigger_tokens(),
- budget.context_window
+ window.trigger_tokens(),
+ window.context_window
);
// Published for the same reason the overflow
// path below publishes: a client holding the
@@ -3412,7 +3537,7 @@ async fn run_turn_cycle(
text: format!(
"compacted {dropped} messages into a summary before sending \
({estimate} tokens against a {} token budget)",
- budget.trigger_tokens()
+ window.trigger_tokens()
),
});
continue;
@@ -3435,9 +3560,10 @@ async fn run_turn_cycle(
.await;
// Nothing safe left to drop: the request is smaller than the
// window only in the provider's own maths.
- let dropped = compact(&mut transcript, keep_recent, model_id, model)
- .await?
- .ok_or(e)?;
+ let dropped =
+ compact(&mut transcript, keep_recent, model_id, model, budget)
+ .await?
+ .ok_or(e)?;
log::info!(
"agent: context overflow, compacted {dropped} messages into a \
summary (attempt {})",
@@ -3491,11 +3617,15 @@ async fn run_turn_cycle(
transcript.record_prompt_tail(text);
}
+ last_completion = Some(completion.clone());
let turn_usage = Usage::from_completion(&completion);
// Publish before the tool calls run: the numbers describe the request
// that just landed, and a long tool phase shouldn't sit on them.
if let Some(usage) = turn_usage.clone() {
- let _ = events.send(StreamEvent::TurnUsage { usage });
+ let _ = events.send(StreamEvent::TurnUsage {
+ usage,
+ execution_id: crate::core::agent::correlation::execution_id_of(&completion),
+ });
}
budget.record(&turn_usage);
@@ -3610,6 +3740,7 @@ async fn run_turn_cycle(
crate::core::agent::compaction::DEFAULT_KEEP_RECENT,
model_id,
model,
+ budget,
)
.await
{
@@ -5893,6 +6024,133 @@ mod tests {
})
}
+ /// A run stopped by its money ceiling returns the work it already did,
+ /// rather than failing. The turns taken are real work the user is billed
+ /// for, so discarding them into an error would charge for an answer it then
+ /// threw away -- and the caller could not tell "out of budget" from "the
+ /// provider broke".
+ #[tokio::test]
+ async fn the_cost_ceiling_stops_the_run_and_keeps_the_answer() {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ // One request whose usage alone blows a $0.01 ceiling, then a second
+ // the loop must never make.
+ let mut expensive = bash_call_completion();
+ expensive["usage"] = json!({
+ "prompt_tokens": 1_000_000,
+ "completion_tokens": 0,
+ "total_tokens": 1_000_000,
+ });
+ let model = MockModel::new(vec![expensive, final_answer("never reached")]);
+ let tool = FixedTool {
+ content: "ok".to_string(),
+ };
+ let mut budget = SessionBudget::new(None).with_cost_ceiling(Some(
+ crate::core::agent::session::CostCeiling {
+ rates: crate::core::agent::session::TokenRates {
+ // $1 per million prompt tokens, so one request costs $1.
+ prompt_usd: 1e-6,
+ completion_usd: 1e-6,
+ cache_read_usd: None,
+ cache_write_usd: None,
+ },
+ max_usd: 0.01,
+ },
+ ));
+
+ let result = run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ Transcript::from_history(vec![json!({ "role": "user", "content": "go" })]),
+ None,
+ true,
+ 0,
+ &mut budget,
+ &model,
+ &tool,
+ crate::core::agent::plan::RunMode::Normal,
+ None,
+ None,
+ None,
+ None,
+ )
+ .await
+ .expect("a ceiling stops the run, it does not fail it");
+
+ assert_eq!(
+ model.requests.lock().unwrap().len(),
+ 1,
+ "the second request is the one the ceiling exists to prevent"
+ );
+ assert_eq!(
+ result["choices"][0]["finish_reason"],
+ json!("budget_exceeded"),
+ "a caller must be able to tell this from a model that chose to stop: {result}"
+ );
+ // The returned completion asked for a tool call that will never be
+ // answered, so leaving it on the message would hand the caller an
+ // invalid conversation to resume from.
+ assert!(
+ result["choices"][0]["message"].get("tool_calls").is_none(),
+ "unanswered tool calls must not survive on the final message: {result}"
+ );
+ }
+
+ /// A compaction is a paid request and has to reach the run's budget. It is
+ /// not the metered dispatch, so nothing else charges it: a turn can make up
+ /// to five of them (the preflight plus `MAX_COMPACTION_ATTEMPTS` overflow
+ /// retries), and spend the budget never saw would leave `/usage` and the
+ /// money ceiling agreeing with each other while both undercounted.
+ #[tokio::test]
+ async fn compacting_charges_the_summarizer_to_the_run() {
+ // A history long enough to have a span worth summarizing.
+ let mut transcript = Transcript::default();
+ for i in 0..12 {
+ transcript.record_message(json!({ "role": "user", "content": format!("turn {i}") }));
+ transcript
+ .record_message(json!({ "role": "assistant", "content": format!("ack {i}") }));
+ }
+
+ let mut summary = final_answer("the story so far");
+ summary["usage"] = json!({
+ "prompt_tokens": 500_000,
+ "completion_tokens": 1_000,
+ "total_tokens": 501_000,
+ });
+ let model = MockModel::new(vec![summary]);
+
+ let mut budget = SessionBudget::new(None).with_cost_ceiling(Some(
+ crate::core::agent::session::CostCeiling {
+ // $1 per million either way: this summarizer call costs $0.501.
+ rates: crate::core::agent::session::TokenRates {
+ prompt_usd: 1e-6,
+ completion_usd: 1e-6,
+ cache_read_usd: None,
+ cache_write_usd: None,
+ },
+ max_usd: 0.25,
+ },
+ ));
+ assert!(!budget.over_cost_ceiling(), "nothing spent yet");
+
+ let dropped = compact(&mut transcript, 4, "m", &model, &mut budget)
+ .await
+ .expect("the summarizer answered")
+ .expect("a long history has a span to compact");
+ assert!(dropped > 0);
+
+ let spent = budget.spent_usd().expect("metered");
+ assert!(
+ (spent - 0.501).abs() < 1e-9,
+ "the summarizer's own request is billed: {spent}"
+ );
+ assert!(
+ budget.over_cost_ceiling(),
+ "a compaction can exhaust the ceiling on its own"
+ );
+ }
+
async fn bash_result_is_error_flag(content: &str) -> bool {
let (tx, mut rx) = mpsc::unbounded_channel();
let model = MockModel::new(vec![
@@ -6596,6 +6854,86 @@ mod tests {
);
}
+ /// The wire boundary where a run becomes metered, or silently does not.
+ /// The CLI refuses an unpriceable ceiling up front, but this function is
+ /// what the loop actually believes, and it is reached by three callers
+ /// (the plain CLI, the TUI, and a subagent dispatch). A body that carries
+ /// a limit but no rates, or rates but no limit, is a caller bug -- and
+ /// running uncapped is the one outcome a cost ceiling must never produce
+ /// silently, so the pairing is asserted here rather than assumed.
+ #[test]
+ fn a_cost_ceiling_needs_both_a_limit_and_the_rates_to_meter_it() {
+ let rates = json!({ "prompt_usd": 1e-6, "completion_usd": 10e-6 });
+
+ assert!(body_cost_ceiling(&json!({})).is_none(), "nothing asked for");
+ assert!(
+ body_cost_ceiling(&json!({ "max_budget_usd": 2.0 })).is_none(),
+ "a limit with no prices cannot be enforced"
+ );
+ assert!(
+ body_cost_ceiling(&json!({ "token_rates": rates })).is_none(),
+ "prices with no limit meter nothing"
+ );
+ // Rates that are present but incomplete are not a ceiling either: the
+ // two required legs of the formula have no sane default, and guessing
+ // one would meter against a price the user was never shown.
+ assert!(
+ body_cost_ceiling(&json!({
+ "max_budget_usd": 2.0,
+ "token_rates": { "prompt_usd": 1e-6 },
+ }))
+ .is_none(),
+ "a half-specified rate sheet is not a rate sheet"
+ );
+
+ let ceiling = body_cost_ceiling(&json!({
+ "max_budget_usd": 2.5,
+ "token_rates": {
+ "prompt_usd": 1e-6,
+ "completion_usd": 10e-6,
+ "cache_read_usd": 0.1e-6,
+ "cache_write_usd": 1.25e-6,
+ },
+ }))
+ .expect("a limit and its rates together are a ceiling");
+ assert_eq!(ceiling.max_usd, 2.5);
+ assert_eq!(ceiling.rates.prompt_usd, 1e-6);
+ assert_eq!(ceiling.rates.cache_read_usd, Some(0.1e-6));
+
+ // Cache rates are genuinely optional -- a provider may publish none --
+ // and their absence bills the cached share at the prompt rate rather
+ // than voiding the ceiling.
+ let no_cache = body_cost_ceiling(&json!({
+ "max_budget_usd": 1.0,
+ "token_rates": { "prompt_usd": 1e-6, "completion_usd": 10e-6 },
+ }))
+ .expect("cache rates are optional");
+ assert_eq!(no_cache.rates.cache_read_usd, None);
+
+ // `0` is a real ceiling (stop at the first billed request), not a
+ // synonym for unbounded the way `max_session_tokens: 0` is. The two
+ // limits sit side by side in the same body, so this must not drift.
+ let zero = body_cost_ceiling(&json!({
+ "max_budget_usd": 0,
+ "token_rates": { "prompt_usd": 1e-6, "completion_usd": 10e-6 },
+ }))
+ .expect("zero is a ceiling, not an absence");
+ assert_eq!(zero.max_usd, 0.0);
+
+ // Nonsense amounts do not meter. A negative or non-finite ceiling is
+ // never satisfiable, and treating it as `0` would stop every run.
+ for bad in [json!(-1.0), json!("2.00"), json!(null)] {
+ assert!(
+ body_cost_ceiling(&json!({
+ "max_budget_usd": bad,
+ "token_rates": { "prompt_usd": 1e-6, "completion_usd": 10e-6 },
+ }))
+ .is_none(),
+ "{bad} is not an amount"
+ );
+ }
+ }
+
#[test]
fn stop_reason_reads_first_choice() {
let completion = json!({ "choices": [{ "finish_reason": "tool_calls" }] });
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index fb02ec51c..635bae085 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -13,6 +13,7 @@ pub mod bg_shell;
pub mod commands;
pub mod compaction;
pub mod context;
+pub mod correlation;
pub mod events;
pub mod genai_bridge;
pub mod git;
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index c12b6977c..4129c7852 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -119,6 +119,13 @@ pub(crate) struct SkillsSection {
pub(crate) struct BudgetSection {
#[serde(default)]
pub max_tokens: Option<u64>,
+ /// USD a run may spend before it stops. Unlike `max_tokens` this is a hard
+ /// bound. It is priced from the provider's published rates, so a model with
+ /// no published price cannot be capped at all and a run that asks for one is
+ /// refused rather than run uncapped -- including a subagent whose definition
+ /// names a model of its own (see `child_cost_ceiling`).
+ #[serde(default)]
+ pub max_usd: Option<f64>,
}
/// `[agent]` — resolves the model and per-run knobs for CLI agent runs.
@@ -247,11 +254,15 @@ const AGENT_TOML_TEMPLATE: &str = r#"[agent]
# base_url = "https://api.openai.com/v1"
# models = ["gpt-4o"]
-# The run's only cap: new token spend across all turns (replayed context is not
-# recharged each turn). There is no turn limit. Defaults to 128000 when unset;
-# 0 disables the cap so the agent runs until the task is done or cancelled.
+# New token spend across all turns (replayed context is not recharged each
+# turn). Advisory: crossing it compacts and files a note, it does not stop the
+# run. Defaults to 128000 when unset; 0 disables the cap.
[budget]
# max_tokens = 128000
+# USD this run may spend before it stops -- unlike max_tokens, a hard bound.
+# Priced from the provider's published rates, so a model with no published
+# price is refused rather than run uncapped. Overridden by --max-budget-usd.
+# max_usd = 5.00
[tools]
# read-only | deny | allow. read-only (default) exposes MCP tools and built-in
diff --git a/src-tauri/src/core/agent/session.rs b/src-tauri/src/core/agent/session.rs
index cd9b274b5..0bf26c202 100644
--- a/src-tauri/src/core/agent/session.rs
+++ b/src-tauri/src/core/agent/session.rs
@@ -1,14 +1,86 @@
//! Session-level budget caps for the agent loop. Tracks cumulative token usage
//! across turns and signals when a configured ceiling is reached.
+//!
+//! Two ceilings live here and they are not the same kind of thing. The token
+//! ceiling is *marginal*: replayed context is not recharged each turn, because
+//! it measures how much new work a run is doing. The money ceiling is
+//! *cumulative*, because a provider bills the whole prompt it is resent on
+//! every request -- so the run's actual charge is the sum over requests, and
+//! costing it marginally would understate a long tool-calling run by exactly
+//! the factor that makes such runs expensive.
use crate::core::agent::events::Usage;
+/// What a provider charges per token, in USD. The rates a run started with,
+/// snapshotted: a money ceiling is enforced against the prices the user was
+/// shown when they set it, not against a listing refetched mid-run.
+///
+/// Lives here rather than beside the model catalog it is read from because the
+/// agent loop -- which is not `cli`-gated -- is what enforces the ceiling, and
+/// the catalog is gated. `cli::model_catalog::ModelInfo` delegates to this, so
+/// there is one formula rather than a second one that drifts.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct TokenRates {
+ pub prompt_usd: f64,
+ pub completion_usd: f64,
+ /// A rate the provider did not publish falls back to the prompt rate, which
+ /// is what a prompt/completion-only price list already charges.
+ pub cache_read_usd: Option<f64>,
+ pub cache_write_usd: Option<f64>,
+}
+
+impl TokenRates {
+ /// USD for one request's token counts.
+ ///
+ /// `cached` and `cache_write` are **shares of `prompt`**, not additions to
+ /// it: every pipeline that reaches here normalizes Anthropic's usage the
+ /// OpenAI way, so `prompt_tokens = input + cache_read + cache_write` (genai
+ /// `anthropic/adapter_shared.rs`, and `core::server::converters` for Jan's
+ /// own responses). Each share is billed at its own rate and the remainder
+ /// at the prompt rate.
+ pub fn cost_usd(&self, prompt: u64, completion: u64, cached: u64, cache_write: u64) -> f64 {
+ // Clamped so a provider reporting a share larger than the prompt (or
+ // two shares that together exceed it) cannot underflow the remainder.
+ let cached = cached.min(prompt);
+ let written = cache_write.min(prompt - cached);
+ let fresh = prompt - cached - written;
+ fresh as f64 * self.prompt_usd
+ + cached as f64 * self.cache_read_usd.unwrap_or(self.prompt_usd)
+ + written as f64 * self.cache_write_usd.unwrap_or(self.prompt_usd)
+ + completion as f64 * self.completion_usd
+ }
+
+ /// USD for one reported usage record. An omitted count contributes nothing
+ /// rather than being guessed at.
+ fn cost_of(&self, usage: &Usage) -> f64 {
+ self.cost_usd(
+ usage.prompt_tokens.unwrap_or(0),
+ usage.completion_tokens.unwrap_or(0),
+ usage.cached_tokens.unwrap_or(0),
+ usage.cache_write_tokens.unwrap_or(0),
+ )
+ }
+}
+
+/// A run's money ceiling: the rates to charge at, and the limit to stop at.
+/// Both or neither -- a ceiling with no rates cannot be enforced, and the CLI
+/// refuses such a run up front rather than letting it proceed uncapped.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct CostCeiling {
+ pub rates: TokenRates,
+ pub max_usd: f64,
+}
+
#[derive(Debug, Default)]
pub(crate) struct SessionBudget {
max_tokens: Option<u64>,
spent_tokens: u64,
last_total: u64,
last_prompt: Option<u64>,
+ /// `None` leaves money unmetered, which is the default: without published
+ /// prices there is no honest number to meter against.
+ ceiling: Option<CostCeiling>,
+ spent_usd: f64,
}
impl SessionBudget {
@@ -18,9 +90,17 @@ impl SessionBudget {
spent_tokens: 0,
last_total: 0,
last_prompt: None,
+ ceiling: None,
+ spent_usd: 0.0,
}
}
+ /// Meter this run's spend against a money ceiling.
+ pub(crate) fn with_cost_ceiling(mut self, ceiling: Option<CostCeiling>) -> Self {
+ self.ceiling = ceiling;
+ self
+ }
+
/// Fold a completion's usage into the running total, returning the new total.
///
/// Counts new completion tokens and positive prompt-token growth rather than
@@ -56,17 +136,75 @@ impl SessionBudget {
self.last_prompt = usage.prompt_tokens.or(self.last_prompt);
self.spent_tokens = self.spent_tokens.saturating_add(delta);
+ // Money is charged on the request as billed -- the whole prompt, every
+ // time -- rather than on the marginal `delta` above.
+ if let Some(ceiling) = &self.ceiling {
+ self.spent_usd += ceiling.rates.cost_of(usage);
+ }
self.spent_tokens
}
+ /// Charge a request that is not part of the conversation being replayed --
+ /// today, the compaction summarizer.
+ ///
+ /// Money is charged in full, exactly as the provider bills it: this is a
+ /// paid request, and a turn can make several of them (the preflight
+ /// compaction plus each overflow retry), so leaving them out would let a
+ /// run spend past its ceiling while the ceiling read as unreached.
+ ///
+ /// Tokens count the completion only, and the prompt baseline is left alone.
+ /// [`Self::record`] meters the conversation's *marginal* growth by
+ /// comparing each request's prompt against the last one's; a side request
+ /// carries a different prompt entirely (a rendered transcript), so letting
+ /// it set that baseline would make the next real turn's growth arbitrary.
+ pub(crate) fn record_side_request(&mut self, usage: &Option<Usage>) {
+ let Some(usage) = usage.as_ref() else {
+ return;
+ };
+ self.spent_tokens = self
+ .spent_tokens
+ .saturating_add(usage.completion_tokens.unwrap_or(0));
+ if let Some(ceiling) = &self.ceiling {
+ self.spent_usd += ceiling.rates.cost_of(usage);
+ }
+ }
+
pub(crate) fn spent(&self) -> u64 {
self.spent_tokens
}
- /// True only when a ceiling is configured and has been reached or exceeded.
+ /// USD charged so far, or `None` when this run meters no money at all --
+ /// which is not the same as having spent nothing.
+ pub(crate) fn spent_usd(&self) -> Option<f64> {
+ self.ceiling.is_some().then_some(self.spent_usd)
+ }
+
+ pub(crate) fn max_usd(&self) -> Option<f64> {
+ self.ceiling.as_ref().map(|c| c.max_usd)
+ }
+
+ /// True only when a token ceiling is configured and has been reached or
+ /// exceeded. Advisory: the run carries on past it.
pub(crate) fn exhausted(&self) -> bool {
matches!(self.max_tokens, Some(max) if self.spent_tokens >= max)
}
+
+ /// True once the money ceiling is reached. Unlike [`Self::exhausted`] this
+ /// **stops the run**: the user named a sum they were willing to spend, and
+ /// a ceiling that only filed a note would let a loop spend past it without
+ /// limit.
+ ///
+ /// Checked after a request rather than before, because the cost of a
+ /// request is not known until the provider reports its usage. The overshoot
+ /// is therefore bounded by the requests made between two checks, which is
+ /// the tightest bound available to a caller that cannot price a completion
+ /// it has not yet received. That is the metered dispatch plus any
+ /// compactions the same turn made -- all of them charged (see
+ /// [`Self::record_side_request`]), so the ceiling is never read as unreached
+ /// because of spend nobody counted.
+ pub(crate) fn over_cost_ceiling(&self) -> bool {
+ matches!(self.ceiling, Some(c) if self.spent_usd >= c.max_usd)
+ }
}
#[cfg(test)]
@@ -148,6 +286,155 @@ mod tests {
assert!(b.exhausted());
}
+ fn rates() -> TokenRates {
+ TokenRates {
+ prompt_usd: 1e-6,
+ completion_usd: 10e-6,
+ cache_read_usd: None,
+ cache_write_usd: None,
+ }
+ }
+
+ fn capped(max_usd: f64) -> SessionBudget {
+ SessionBudget::new(None).with_cost_ceiling(Some(CostCeiling {
+ rates: rates(),
+ max_usd,
+ }))
+ }
+
+ /// Money is cumulative where tokens are marginal. A provider bills the whole
+ /// prompt it is resent on every request, so a run that replays a large
+ /// context over many turns is charged for it every time -- costing it the
+ /// way `spent_tokens` is counted would understate exactly the runs that get
+ /// expensive.
+ #[test]
+ fn cost_charges_every_request_for_the_whole_prompt() {
+ let mut b = capped(1.0);
+ // Three turns replaying a 10K prompt: marginally almost nothing new,
+ // but billed three times over.
+ b.record(&usage_with_parts(10_000, 100, 10_100));
+ b.record(&usage_with_parts(10_100, 100, 10_200));
+ b.record(&usage_with_parts(10_200, 100, 10_300));
+ let spent = b.spent_usd().expect("metered");
+ assert!(
+ (spent - (30_300.0 * 1e-6 + 300.0 * 10e-6)).abs() < 1e-9,
+ "every request pays for its whole prompt: {spent}"
+ );
+ // Marginal token spend over the same three turns is a third of the 30K
+ // tokens actually billed: the baseline plus 100 new completion and 100
+ // prompt-growth tokens a turn. The two ceilings measure different
+ // things, which is why money could not simply be priced off `spent()`.
+ assert_eq!(b.spent(), 10_500);
+ }
+
+ /// An unmetered run reports `None`, not `0.0`. "This run tracks no money"
+ /// and "this run has spent nothing" are different answers, and a surface
+ /// that renders the second for the first would show a $0.00 spend for a run
+ /// that is in fact spending.
+ #[test]
+ fn an_unmetered_run_reports_no_cost_rather_than_zero() {
+ let mut b = SessionBudget::new(Some(100));
+ b.record(&usage_with_parts(10_000, 500, 10_500));
+ assert_eq!(b.spent_usd(), None);
+ assert_eq!(b.max_usd(), None);
+ assert!(!b.over_cost_ceiling(), "nothing to be over");
+ }
+
+ /// The ceiling trips at or past the limit, and only then.
+ #[test]
+ fn the_cost_ceiling_trips_once_spend_reaches_it() {
+ // 100K prompt at $1/M plus 10K completion at $10/M = $0.20 a request.
+ let mut b = capped(0.5);
+ b.record(&usage_with_parts(100_000, 10_000, 110_000));
+ assert!(!b.over_cost_ceiling(), "$0.20 of $0.50");
+ b.record(&usage_with_parts(100_000, 10_000, 110_000));
+ assert!(!b.over_cost_ceiling(), "$0.40 of $0.50");
+ b.record(&usage_with_parts(100_000, 10_000, 110_000));
+ assert!(b.over_cost_ceiling(), "$0.60 is past $0.50");
+ }
+
+ /// A compaction is a paid request, and a turn can make several of them (the
+ /// preflight plus each overflow retry). Spend the budget never saw would let
+ /// a run go past its ceiling while `/usage` and the ceiling agreed with each
+ /// other about a figure that was simply too low.
+ #[test]
+ fn a_side_request_is_charged_without_moving_the_prompt_baseline() {
+ let mut b = capped(1.0);
+ b.record(&usage_with_parts(100_000, 10_000, 110_000));
+ let after_turn = b.spent_usd().expect("metered");
+
+ // A summarizer call: its own prompt, its own completion, all billed.
+ b.record_side_request(&usage_with_parts(20_000, 500, 20_500));
+ let charged = b.spent_usd().expect("metered") - after_turn;
+ let expected = 20_000.0 * 1e-6 + 500.0 * 10e-6;
+ assert!((charged - expected).abs() < 1e-12, "{charged} != {expected}");
+
+ // The next real turn's marginal token spend is still measured against
+ // the conversation's own last prompt (100K), not the summarizer's 20K:
+ // a side request replays a different prompt entirely, so letting it set
+ // that baseline would make the next turn's growth arbitrary.
+ b.record(&usage_with_parts(100_100, 200, 100_300));
+ assert_eq!(
+ b.spent(),
+ 110_000 + 500 + 300,
+ "the turn after a side request grows by 100 prompt + 200 completion"
+ );
+ }
+
+ /// An unmetered run charges a side request nothing and reports nothing,
+ /// exactly as it does for an ordinary one.
+ #[test]
+ fn a_side_request_on_an_unmetered_run_stays_unmetered() {
+ let mut b = SessionBudget::new(None);
+ b.record_side_request(&usage_with_parts(1_000, 100, 1_100));
+ assert_eq!(b.spent_usd(), None);
+ assert_eq!(b.spent(), 100);
+ }
+
+ /// A `0` ceiling is honest rather than a synonym for unbounded -- which is
+ /// what `max_tokens` means by `0`, so the two must not be confused. Asking
+ /// to spend nothing stops at the first billed request.
+ #[test]
+ fn a_zero_ceiling_stops_at_the_first_billed_request() {
+ let mut b = capped(0.0);
+ assert!(b.over_cost_ceiling(), "zero is reached before anything runs");
+ b.record(&usage_with_parts(10, 1, 11));
+ assert!(b.over_cost_ceiling());
+ }
+
+ /// Cache shares are billed at their own rates and come *out of* the prompt,
+ /// never on top of it: the pipelines normalize Anthropic's usage the OpenAI
+ /// way, so `prompt = fresh + cache_read + cache_write`. Adding them would
+ /// double-charge a cached prompt, which is the case caching exists to make
+ /// cheaper.
+ #[test]
+ fn cache_shares_come_out_of_the_prompt_at_their_own_rates() {
+ let r = TokenRates {
+ prompt_usd: 10e-6,
+ completion_usd: 0.0,
+ cache_read_usd: Some(1e-6),
+ cache_write_usd: Some(20e-6),
+ };
+ // 1000 prompt = 700 fresh + 200 read + 100 written.
+ let cost = r.cost_usd(1_000, 0, 200, 100);
+ let expected = 700.0 * 10e-6 + 200.0 * 1e-6 + 100.0 * 20e-6;
+ assert!((cost - expected).abs() < 1e-12, "{cost} != {expected}");
+
+ // A provider reporting shares larger than the prompt cannot underflow
+ // the remainder into a negative charge.
+ let clamped = r.cost_usd(100, 0, 900, 900);
+ assert!(clamped >= 0.0, "{clamped}");
+ }
+
+ /// An unpublished cache rate falls back to the prompt rate, which is what a
+ /// prompt/completion-only price list already charges -- not to zero, which
+ /// would bill a cached prompt as free.
+ #[test]
+ fn an_unpublished_cache_rate_bills_at_the_prompt_rate() {
+ let r = rates();
+ assert_eq!(r.cost_usd(1_000, 0, 400, 0), r.cost_usd(1_000, 0, 0, 0));
+ }
+
#[test]
fn absent_usage_does_not_advance_spend() {
let mut b = SessionBudget::new(Some(10));
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index f724862ee..13ee03605 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -934,19 +934,94 @@ pub(crate) struct ParentRun {
pub(crate) model: String,
pub(crate) budget_remaining: Option<u64>,
pub(crate) send_reasoning: bool,
+ /// The parent's remaining money ceiling, or `None` when it meters none.
+ ///
+ /// Every child gets the *whole* remainder rather than a share of it, which
+ /// means N children may each spend it: the ceiling bounds any one lineage,
+ /// not the fan-out. Splitting it N ways is worse -- the split would have to
+ /// be chosen before anyone knows which child does the work, and starving a
+ /// child of budget mid-task fails the run the user asked for. The parent's
+ /// own ceiling still stops the run once those charges land on it.
+ pub(crate) cost_remaining: Option<crate::core::agent::session::CostCeiling>,
+}
+
+/// The model a dispatch will actually be billed for: the definition's own when
+/// it names one, else the dispatching run's. Resolved in one place because the
+/// request body and the ceiling priced against it must not disagree.
+fn child_model(resolved: &ResolvedDispatch, parent: &ParentRun) -> String {
+ resolved
+ .definition
+ .model
+ .clone()
+ .unwrap_or_else(|| parent.model.clone())
+}
+
+/// The per-token rates a model is published at, or `None` when it cannot be
+/// priced at all.
+///
+/// The lookup names no provider: a child's serving provider is not resolved on
+/// this path, and the catalog's provider-less `get` answers only on an
+/// unambiguous hit -- two providers quoting one id at different prices is a
+/// `None`, which is the correct direction here (a refusal, not a guess).
+#[cfg(feature = "cli")]
+fn published_rates(model: &str) -> Option<crate::core::agent::session::TokenRates> {
+ crate::core::cli::model_catalog::load()
+ .get(None, model)
+ .and_then(|info| info.rates())
}
-/// Build the child request body shared by every subagent run.
+/// No model catalog outside the `cli` build, so nothing here can be priced.
+/// Metered runs only ever start on the CLI path, so this is the unreachable
+/// case -- and answering `None` refuses rather than invents a rate.
+#[cfg(not(feature = "cli"))]
+fn published_rates(_model: &str) -> Option<crate::core::agent::session::TokenRates> {
+ None
+}
+
+/// The money ceiling a child actually runs under: the parent's limit, priced
+/// against the model the child will be billed for.
+///
+/// A definition may name its own model, and the parent's rates are the *parent*
+/// model's. Forwarding them unchanged bills the child at a price nobody quoted:
+/// a pricier child is undercounted -- against the user, not in their favour --
+/// and a child with no published price would run on invented rates, the exact
+/// thing `resolve_cost_ceiling` refuses for the parent. So when the models
+/// differ the child's own rates are looked up, and a dispatch that cannot be
+/// priced is refused rather than metered wrongly.
+///
+/// The limit itself is inherited whole (see [`ParentRun::cost_remaining`]);
+/// only the rates are re-resolved.
+fn child_cost_ceiling(
+ model: &str,
+ parent: &ParentRun,
+) -> Result<Option<crate::core::agent::session::CostCeiling>, SubagentError> {
+ let Some(ceiling) = parent.cost_remaining else {
+ return Ok(None);
+ };
+ if model == parent.model {
+ return Ok(Some(ceiling));
+ }
+ let rates = published_rates(model).ok_or_else(|| {
+ SubagentError::Upstream(format!(
+ "cannot dispatch a subagent on {model} under a ${:.4} ceiling: this model has no \
+ published price, and metering it at {}'s rates would charge the run against a \
+ price nobody quoted. Drop the definition's own model so the child runs on the \
+ run's, or remove the limit.",
+ ceiling.max_usd, parent.model
+ ))
+ })?;
+ Ok(Some(crate::core::agent::session::CostCeiling { rates, ..ceiling }))
+}
+
+/// Build the child request body shared by every subagent run. `parent` is the
+/// inheritance the child runs under, which the dispatch path has already
+/// re-priced for the child's own model (see [`child_cost_ceiling`]).
fn child_body(
resolved: &ResolvedDispatch,
description: &str,
parent: &ParentRun,
) -> serde_json::Value {
- let model = resolved
- .definition
- .model
- .clone()
- .unwrap_or_else(|| parent.model.clone());
+ let model = child_model(resolved, parent);
let mut body = serde_json::Map::new();
body.insert("model".to_string(), serde_json::json!(model));
body.insert(
@@ -962,6 +1037,26 @@ fn child_body(
if let Some(remaining) = parent.budget_remaining {
body.insert("max_session_tokens".to_string(), serde_json::json!(remaining));
}
+ // A child dispatched by a capped run is capped too: subagents are where a
+ // run's spend multiplies, so a ceiling the children did not inherit would
+ // be one the parent could spend around by fanning out. The rates here are
+ // the ones `child_cost_ceiling` resolved for `model` above, so the limit
+ // and the price it is metered at describe the same model.
+ if let Some(ceiling) = parent.cost_remaining {
+ body.insert(
+ "max_budget_usd".to_string(),
+ serde_json::json!(ceiling.max_usd),
+ );
+ body.insert(
+ "token_rates".to_string(),
+ serde_json::json!({
+ "prompt_usd": ceiling.rates.prompt_usd,
+ "completion_usd": ceiling.rates.completion_usd,
+ "cache_read_usd": ceiling.rates.cache_read_usd,
+ "cache_write_usd": ceiling.rates.cache_write_usd,
+ }),
+ );
+ }
// A child's own tool-call turns carry `reasoning_content`, so the parent's
// opt-out has to travel with the dispatch or a strict provider still sees
// the field on the second child turn.
@@ -1097,6 +1192,13 @@ pub(crate) fn spawn_subagent(
.ok_or_else(|| SubagentError::Upstream("subagents require an active project".to_string()))?;
let registry = SubagentRegistry::load(project_root);
let resolved = resolve_dispatch(&registry, &req, &parent_args.permissions)?;
+ // Re-priced before anything is spawned: a child whose own model cannot be
+ // metered under this ceiling fails the dispatch here rather than running on
+ // the parent's prices.
+ let parent = &ParentRun {
+ cost_remaining: child_cost_ceiling(&child_model(&resolved, parent), parent)?,
+ ..parent.clone()
+ };
let name = resolved.definition.name.clone();
let run_id = next_subagent_run_id(&name);
@@ -1302,7 +1404,11 @@ pub(crate) fn spawn_dispatch_plan(
let registry = SubagentRegistry::load(project_root);
for phase in &plan.phases {
for req in &phase.subagents {
- resolve_dispatch(&registry, req, &parent_args.permissions)?;
+ let resolved = resolve_dispatch(&registry, req, &parent_args.permissions)?;
+ // Priced up front for the same reason the permission check is: a
+ // later phase naming an unpriceable model must fail the whole plan
+ // now, not after the earlier phases have already been billed.
+ child_cost_ceiling(&child_model(&resolved, parent), parent)?;
}
}
@@ -2248,9 +2354,95 @@ mod tests {
model: "m".to_string(),
budget_remaining: None,
send_reasoning: true,
+ cost_remaining: None,
}
}
+ /// A capped parent's children are capped too. Subagents are where a run's
+ /// spend multiplies, so a ceiling that stopped at the parent would be one
+ /// any run could spend around by dispatching.
+ #[test]
+ fn child_body_inherits_the_parents_cost_ceiling() {
+ let reg = registry_with("reviewer", None);
+ let p = ToolPermissions::allow_all();
+ let resolved = resolve_dispatch(&reg, &req("reviewer", None), &p).expect("resolves");
+
+ let uncapped = child_body(&resolved, "task", &parent_run());
+ assert!(
+ uncapped.get("max_budget_usd").is_none(),
+ "an unmetered parent must not invent a ceiling: {uncapped}"
+ );
+ assert!(uncapped.get("token_rates").is_none());
+
+ let capped = child_body(
+ &resolved,
+ "task",
+ &ParentRun {
+ cost_remaining: Some(crate::core::agent::session::CostCeiling {
+ rates: crate::core::agent::session::TokenRates {
+ prompt_usd: 1e-6,
+ completion_usd: 2e-6,
+ cache_read_usd: None,
+ cache_write_usd: None,
+ },
+ max_usd: 0.25,
+ }),
+ ..parent_run()
+ },
+ );
+ assert_eq!(capped["max_budget_usd"], serde_json::json!(0.25));
+ // The rates travel with the limit: a child that inherited the ceiling
+ // but not the prices could not meter itself against it.
+ assert_eq!(capped["token_rates"]["prompt_usd"], serde_json::json!(1e-6));
+ assert_eq!(
+ capped["token_rates"]["completion_usd"],
+ serde_json::json!(2e-6)
+ );
+ }
+
+ /// A definition naming its own model must not be metered at the parent's
+ /// prices. The parent's ceiling is the parent *model's* rates, so carrying
+ /// them onto a differently-priced child bills the run against a price
+ /// nobody quoted -- and undercounts a pricier child, i.e. against the user.
+ /// A child that cannot be priced is refused, the same answer
+ /// `resolve_cost_ceiling` gives for an unpriced parent.
+ #[test]
+ fn a_child_on_its_own_model_is_not_billed_at_the_parents_rates() {
+ let ceiling = crate::core::agent::session::CostCeiling {
+ rates: crate::core::agent::session::TokenRates {
+ prompt_usd: 1e-6,
+ completion_usd: 2e-6,
+ cache_read_usd: None,
+ cache_write_usd: None,
+ },
+ max_usd: 0.25,
+ };
+ let parent = ParentRun {
+ cost_remaining: Some(ceiling),
+ ..parent_run()
+ };
+
+ // Same model: the parent's own rates are the right ones, inherited whole.
+ assert_eq!(
+ child_cost_ceiling(&parent.model, &parent).expect("same model prices"),
+ Some(ceiling)
+ );
+
+ // A different model with no published price is refused rather than run
+ // on the parent's rates. The name cannot appear in any real catalog.
+ let refused = child_cost_ceiling("no-such-model-jan-test", &parent)
+ .expect_err("an unpriceable child under a ceiling must be refused");
+ let message = refused.to_string();
+ assert!(message.contains("no-such-model-jan-test"), "{message}");
+ assert!(message.contains("no published price"), "{message}");
+
+ // An unmetered parent is unchanged: nothing to price, nothing to refuse.
+ assert_eq!(
+ child_cost_ceiling("no-such-model-jan-test", &parent_run()).expect("unmetered"),
+ None
+ );
+ }
+
/// `[agent].send_reasoning = false` has to reach the child body: a child
/// resends the `reasoning_content` of its own tool-call turns, so an opt-out
/// that stopped at the parent would still break a strict provider on the
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index cef38978b..b1b6a27c3 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -1342,6 +1342,7 @@ pub(crate) async fn stream_openai_chat_completions(
api_type: Option<&str>,
body: &serde_json::Value,
events: &mpsc::UnboundedSender<StreamEvent>,
+ client_request_id: Option<&str>,
) -> Result<serde_json::Value, String> {
super::genai_bridge::stream_chat_completions(
client,
@@ -1350,6 +1351,7 @@ pub(crate) async fn stream_openai_chat_completions(
api_type,
body,
events,
+ client_request_id,
)
.await
}
@@ -1365,6 +1367,11 @@ pub(crate) async fn stream_openai_chat_completions(
/// `upstream_url` is the resolved base + "/chat/completions" (see
/// [`resolve_upstream_for_model`]); the base is recovered by stripping that
/// suffix and the native path appended in its place.
+///
+/// `client_request_id` is sent as the correlation header so this request can be
+/// found in the provider's usage records later (see
+/// [`crate::core::agent::correlation`]). This path also owns the HTTP response,
+/// so unlike the genai path it can read the execution id straight back off it.
pub(crate) async fn stream_converted_chat_completions(
client: &Client,
upstream_url: &str,
@@ -1372,6 +1379,7 @@ pub(crate) async fn stream_converted_chat_completions(
converter: &dyn UpstreamConverter,
body: &serde_json::Value,
events: &mpsc::UnboundedSender<StreamEvent>,
+ client_request_id: Option<&str>,
) -> Result<serde_json::Value, String> {
// Base is upstream_url minus the trailing "/chat/completions". Recover it
// the same way the proxy does when it swaps the destination path.
@@ -1417,6 +1425,15 @@ pub(crate) async fn stream_converted_chat_completions(
for (name, value) in converter.extra_headers() {
req = req.header(name, value);
}
+ // Correlation id, so this request is findable in the provider's usage
+ // records. Harmless to a provider that does not use it: an unknown
+ // request header is ignored.
+ if let Some(id) = client_request_id {
+ req = req.header(
+ crate::core::agent::correlation::CLIENT_REQUEST_ID_HEADER,
+ id,
+ );
+ }
let resp = req
.body(native_body.to_string())
@@ -1450,15 +1467,30 @@ pub(crate) async fn stream_converted_chat_completions(
.map(|ct| ct.contains("event-stream"))
.unwrap_or(true);
- if is_sse {
- return consume_converted_sse(resp, converter, events).await;
- }
+ // The execution id, read here because this is the last point at which
+ // the response headers exist: both branches below consume the body.
+ // This is the direct billing handle, and the only path that can get one
+ // -- the genai path discards headers on a successful stream.
+ let execution_id = resp
+ .headers()
+ .get(crate::core::agent::correlation::EXECUTION_ID_HEADER)
+ .and_then(|v| v.to_str().ok())
+ .filter(|id| !id.is_empty())
+ .map(str::to_string);
- let bytes = resp
- .bytes()
- .await
- .map_err(|e| format!("Upstream body read failed: {e}"))?;
- return decode_converted_response(&bytes, converter);
+ let mut completion = if is_sse {
+ consume_converted_sse(resp, converter, events).await?
+ } else {
+ let bytes = resp
+ .bytes()
+ .await
+ .map_err(|e| format!("Upstream body read failed: {e}"))?;
+ decode_converted_response(&bytes, converter)?
+ };
+ if let Some(id) = execution_id {
+ crate::core::agent::correlation::attach_execution_id(&mut completion, &id);
+ }
+ return Ok(completion);
}
Err(last_err)
@@ -2344,6 +2376,7 @@ mod tests {
None,
&json!({ "model": "m", "messages": [] }),
&tx,
+ None,
)
.await
.expect("the retry carries the turn");
@@ -2403,6 +2436,7 @@ mod tests {
"max_tokens": 128,
}),
&tx,
+ None,
)
.await
.expect("request");
@@ -2420,6 +2454,128 @@ mod tests {
assert!(body.get("max_output_tokens").is_none());
}
+ /// The correlation id has to actually reach the wire, and the execution id
+ /// has to come back off the response headers before the body is consumed.
+ /// Both are invisible when broken -- the request still succeeds and only a
+ /// later billing lookup comes back empty -- so this asserts the bytes.
+ #[tokio::test]
+ async fn the_converted_path_sends_the_correlation_id_and_captures_the_execution_id() {
+ use base64::Engine as _;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind");
+ let addr = listener.local_addr().expect("addr");
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accept");
+ let mut bytes = vec![0u8; 16 * 1024];
+ let read = socket.read(&mut bytes).await.expect("read");
+ bytes.truncate(read);
+ let response = "event: response.completed\n\
+ data: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n";
+ let wire = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nX-Tokamak-Execution-Id: exec-abc\r\n\r\n{response}",
+ response.len()
+ );
+ socket.write_all(wire.as_bytes()).await.expect("response");
+ String::from_utf8(bytes).expect("request is utf-8")
+ });
+
+ let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .encode(br#"{"https://api.openai.com/auth":{"chatgpt_account_id":"account-123"}}"#);
+ let token = format!("header.{payload}.signature");
+ let converter =
+ crate::core::server::converters::converter_for(Some("openai-responses"), true)
+ .expect("converter");
+ let (tx, _rx) = sink();
+ let completion = stream_converted_chat_completions(
+ &Client::new(),
+ &format!("http://{addr}/chat/completions"),
+ &[token],
+ converter.as_ref(),
+ &json!({
+ "model": "gpt-5.6-terra",
+ "messages": [{"role": "user", "content": "hi"}],
+ }),
+ &tx,
+ Some("jan-session-7"),
+ )
+ .await
+ .expect("request");
+
+ let request = server.await.expect("server task");
+ assert!(
+ request
+ .to_ascii_lowercase()
+ .contains("\r\nx-client-request-id: jan-session-7\r\n"),
+ "the correlation id must reach the wire: {request}"
+ );
+ assert_eq!(
+ crate::core::agent::correlation::execution_id_of(&completion),
+ Some("exec-abc".to_string()),
+ "the execution id must be read off the response headers"
+ );
+ }
+
+ /// No session means no correlation id, and the header must then be absent
+ /// rather than sent empty -- an empty value would correlate every run that
+ /// had no session.
+ #[tokio::test]
+ async fn no_correlation_id_means_no_header() {
+ use base64::Engine as _;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind");
+ let addr = listener.local_addr().expect("addr");
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accept");
+ let mut bytes = vec![0u8; 16 * 1024];
+ let read = socket.read(&mut bytes).await.expect("read");
+ bytes.truncate(read);
+ let response = "event: response.completed\n\
+ data: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n";
+ let wire = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{response}",
+ response.len()
+ );
+ socket.write_all(wire.as_bytes()).await.expect("response");
+ String::from_utf8(bytes).expect("request is utf-8")
+ });
+
+ let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .encode(br#"{"https://api.openai.com/auth":{"chatgpt_account_id":"a"}}"#);
+ let converter =
+ crate::core::server::converters::converter_for(Some("openai-responses"), true)
+ .expect("converter");
+ let (tx, _rx) = sink();
+ let completion = stream_converted_chat_completions(
+ &Client::new(),
+ &format!("http://{addr}/chat/completions"),
+ &[format!("header.{payload}.signature")],
+ converter.as_ref(),
+ &json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]}),
+ &tx,
+ None,
+ )
+ .await
+ .expect("request");
+
+ let request = server.await.expect("server task");
+ assert!(
+ !request.to_ascii_lowercase().contains("x-client-request-id"),
+ "{request}"
+ );
+ // A response with no execution-id header attaches none, rather than an
+ // empty string that would produce a guaranteed not-found lookup.
+ assert_eq!(
+ crate::core::agent::correlation::execution_id_of(&completion),
+ None
+ );
+ }
+
/// A proxy in the environment breaks Jan and nothing else, and never shows up
/// in the error. Names only: the values carry credentials.
#[test]
diff --git a/src-tauri/src/core/cli/auth/providers.rs b/src-tauri/src/core/cli/auth/providers.rs
index 6a7e36537..fcd54f40d 100644
--- a/src-tauri/src/core/cli/auth/providers.rs
+++ b/src-tauri/src/core/cli/auth/providers.rs
@@ -258,11 +258,16 @@ fn failure_for(definition: &ProviderDefinition, status: u16, _body: &str) -> Log
}
}
-/// Model ids from a `/models` payload, sorted and deduped so a config write
-/// and the "N models" report are stable across calls. Accepts the OpenAI shape
+/// Model ids in the order the endpoint listed them, trimmed and deduped but
+/// deliberately **not** sorted. Accepts the OpenAI shape
/// (`{"data":[{"id":...}]}`) plus the bare-array and array-of-strings variants
/// smaller gateways serve. Anthropic's `/models` uses the same `data` shape.
-pub(crate) fn parse_models(value: &serde_json::Value) -> Vec<String> {
+///
+/// Wire order is kept because it is the only signal a provider has about which
+/// model it would lead with; a router-style gateway can rank its listing.
+/// Sorting is applied separately by [`parse_models`], for the stored roster
+/// where a stable order is what matters.
+pub(crate) fn listed_model_ids(value: &serde_json::Value) -> Vec<String> {
let entries = value
.get("data")
.and_then(|d| d.as_array())
@@ -270,17 +275,29 @@ pub(crate) fn parse_models(value: &serde_json::Value) -> Vec<String> {
let Some(entries) = entries else {
return Vec::new();
};
- let mut ids: Vec<String> = entries
- .iter()
- .filter_map(|entry| {
- entry
- .as_str()
- .or_else(|| entry.get("id").and_then(|id| id.as_str()))
- })
- .map(str::trim)
- .filter(|id| !id.is_empty())
- .map(String::from)
- .collect();
+ let mut ids: Vec<String> = Vec::new();
+ for entry in entries {
+ let Some(id) = entry
+ .as_str()
+ .or_else(|| entry.get("id").and_then(|id| id.as_str()))
+ .map(str::trim)
+ .filter(|id| !id.is_empty())
+ else {
+ continue;
+ };
+ // Deduped in place rather than by sort+dedup, which would lose the
+ // order this function exists to preserve.
+ if !ids.iter().any(|seen| seen == id) {
+ ids.push(id.to_string());
+ }
+ }
+ ids
+}
+
+/// Model ids from a `/models` payload, sorted and deduped so a config write
+/// and the "N models" report are stable across calls.
+pub(crate) fn parse_models(value: &serde_json::Value) -> Vec<String> {
+ let mut ids = listed_model_ids(value);
ids.sort();
ids.dedup();
ids
diff --git a/src-tauri/src/core/cli/login.rs b/src-tauri/src/core/cli/login.rs
index 1f554e3ec..307cb5dd7 100644
--- a/src-tauri/src/core/cli/login.rs
+++ b/src-tauri/src/core/cli/login.rs
@@ -206,7 +206,13 @@ fn report(login: &tokamak::Login) {
}
println!(" key saved to {}", login.config_path.display());
if let Some(model) = &login.default_model {
- println!(" default model: {model}");
+ if login.replaced_default {
+ // The previous default survives in no roster, so leaving it in
+ // place would 404 every run. Reported rather than applied quietly.
+ println!(" default model: {model} (replaced one no longer offered)");
+ } else {
+ println!(" default model: {model}");
+ }
}
println!();
}
@@ -238,12 +244,15 @@ mod tests {
vec!["a".into(), "b".into()],
] {
for account in [None, Some("[email protected]".to_string())] {
- report(&tokamak::Login {
- models: models.clone(),
- config_path: std::path::PathBuf::from("/tmp/config.toml"),
- default_model: Some("a".to_string()),
- account,
- });
+ for replaced_default in [false, true] {
+ report(&tokamak::Login {
+ models: models.clone(),
+ config_path: std::path::PathBuf::from("/tmp/config.toml"),
+ default_model: Some("a".to_string()),
+ replaced_default,
+ account: account.clone(),
+ });
+ }
}
}
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index c8099fbfd..7b2f19597 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -23,6 +23,7 @@ pub mod telemetry;
pub mod terminal_setup;
pub mod tokamak;
mod tui;
+pub mod usage_view;
pub mod updater;
pub mod worktree;
@@ -782,6 +783,57 @@ fn resolve_session_budget(flag: Option<u64>, configured: Option<u64>) -> u64 {
flag.or(configured).unwrap_or(DEFAULT_MAX_SESSION_TOKENS)
}
+/// The money ceiling for a run, priced against the model actually being billed.
+///
+/// Precedence matches the token budget: `--max-budget-usd`, then
+/// `[budget].max_usd`, then none. Unlike that one, this can fail. A ceiling is
+/// only meaningful if the run can be priced, and the price comes from the
+/// provider's last `/models` listing, so three things go wrong in ways the user
+/// has to be told about rather than have guessed at:
+///
+/// - **the model publishes no prices.** Refused. The alternative is to run
+/// uncapped, and a user who asked to spend at most $2 has to end up either
+/// capped or stopped -- never billed without a limit because a listing was
+/// thin. This is also why an unpriced model cannot be worked around by
+/// assuming a rate: an invented price produces an invented ceiling.
+/// - **a negative limit.** Refused as a typo. `0` is allowed and honest: it
+/// stops at the first billed request.
+/// - **no ceiling asked for.** The common case, and not an error: the run is
+/// unmetered, exactly as before this flag existed.
+///
+/// Refusing at startup rather than at the first request is the point: a run
+/// that cannot be capped must not do paid work before saying so.
+fn resolve_cost_ceiling(
+ flag: Option<f64>,
+ configured: Option<f64>,
+ provider: Option<&str>,
+ model: &str,
+) -> Result<Option<crate::core::agent::session::CostCeiling>, String> {
+ let Some(max_usd) = flag.or(configured) else {
+ return Ok(None);
+ };
+ if !max_usd.is_finite() || max_usd < 0.0 {
+ return Err(format!(
+ "a cost ceiling must be a non-negative amount in USD, not {max_usd}"
+ ));
+ }
+ let rates = model_catalog::load()
+ .get(provider, model)
+ .and_then(|info| info.rates())
+ .ok_or_else(|| {
+ format!(
+ "cannot cap spend for {model}: this provider publishes no prices for it, so \
+ there is nothing to meter a ${max_usd} ceiling against. Remove the limit to \
+ run uncapped, or switch to a model the provider prices (`/model` in the TUI \
+ refreshes the listing)."
+ )
+ })?;
+ Ok(Some(crate::core::agent::session::CostCeiling {
+ rates,
+ max_usd,
+ }))
+}
+
/// Resolve the `--project` flag (default `"."`) to an absolute path. The raw
/// value is what the model would otherwise see verbatim in the system prompt's
/// working-directory block, so a bare "." must become the real cwd rather than
@@ -877,6 +929,10 @@ pub fn cli_agent_status(
// `--sandbox` below, cannot be reflected in a config dump.
"max_session_tokens": resolve_session_budget(None, cfg.budget.max_tokens),
"max_session_tokens_source": session_budget_source(None, cfg.budget.max_tokens),
+ // The configured money ceiling, or null when the project sets none.
+ // Reported unpriced: whether it can actually be enforced depends on the
+ // model a run resolves, which a config dump has not resolved.
+ "max_budget_usd": cfg.budget.max_usd,
"tools": {
"default": cfg.tools.default,
"allow": cfg.tools.allow,
@@ -1169,6 +1225,11 @@ pub(crate) struct SessionLimits {
/// body, which the engine reads as unbounded; `0` means unbounded too (see
/// `body_turn_cap`).
pub max_turns: Option<u64>,
+ /// `--max-budget-usd`, else `[budget].max_usd`: the run's money ceiling and
+ /// the rates to meter it against, resolved once at startup by
+ /// `resolve_cost_ceiling` (which refuses a model with no published price).
+ /// `None` leaves the run unmetered, which is the default.
+ pub cost_ceiling: Option<crate::core::agent::session::CostCeiling>,
}
/// Resolved engine handle for a chat session: the args are built once and the
@@ -1237,6 +1298,18 @@ fn request_body(
if let Some(turns) = limits.max_turns {
body["max_turns"] = serde_json::json!(turns);
}
+ // The ceiling travels with the rates it is metered against: the loop is not
+ // `cli`-gated and cannot read the model catalog, so prices resolved here
+ // are the only ones it will ever see (`body_cost_ceiling`).
+ if let Some(ceiling) = limits.cost_ceiling {
+ body["max_budget_usd"] = serde_json::json!(ceiling.max_usd);
+ body["token_rates"] = serde_json::json!({
+ "prompt_usd": ceiling.rates.prompt_usd,
+ "completion_usd": ceiling.rates.completion_usd,
+ "cache_read_usd": ceiling.rates.cache_read_usd,
+ "cache_write_usd": ceiling.rates.cache_write_usd,
+ });
+ }
// Reasoning resend policy: the request-level flag the loop reads to
// decide whether prior assistant `reasoning_content` goes back out.
body["send_reasoning"] = serde_json::json!(send_reasoning);
@@ -1280,6 +1353,11 @@ pub struct SessionFlags {
/// `[budget].max_tokens`. `None` (not passed) defers to that, then to
/// `DEFAULT_MAX_SESSION_TOKENS`.
pub max_session_tokens: Option<u64>,
+ /// `--max-budget-usd`: hard USD ceiling for the run, outranking
+ /// `[budget].max_usd`. `None` (not passed) defers to that, then leaves the
+ /// run unmetered. A run that asks for one but cannot be priced is refused
+ /// (see `resolve_cost_ceiling`).
+ pub max_budget_usd: Option<f64>,
}
/// The desktop app's currently-selected model, adopted only when signed in to
@@ -1578,6 +1656,18 @@ fn prepare_agent_session(
reserve_tokens: cfg.agent.compaction_reserve_tokens,
});
+ // Resolved before the session is built: a run that asked for a ceiling it
+ // cannot be priced against is refused here, before any paid request.
+ // Priced against `serving_provider`, the provider that will actually be
+ // billed, rather than whichever one the catalog finds first -- the same
+ // model can carry different rates on two of them.
+ let cost_ceiling = resolve_cost_ceiling(
+ flags.max_budget_usd,
+ cfg.budget.max_usd,
+ serving_provider.as_deref(),
+ &model,
+ )?;
+
Ok(AgentSession {
args,
permission_requests,
@@ -1595,6 +1685,7 @@ fn prepare_agent_session(
cfg.budget.max_tokens,
),
max_turns: flags.max_turns,
+ cost_ceiling,
},
show_reasoning: cfg.agent.show_reasoning.unwrap_or(false),
stream_reasoning: crate::core::agent::global_config::stream_reasoning_enabled(),
@@ -3656,6 +3747,57 @@ mod tests {
assert_eq!(session_budget_source(Some(0), Some(50_000)), "flag");
}
+ /// The money ceiling resolves flag > config > none, and a run that asks
+ /// for one it cannot price is **refused** rather than run uncapped -- the
+ /// one outcome a cost ceiling must never produce. Asking for none is not
+ /// an error: that is the default, and it leaves the run unmetered.
+ ///
+ /// The refusal cases are asserted against an unpriced model because that is
+ /// the failure that matters: these tests do not write a model catalog, so
+ /// every lookup here misses, which is exactly the state a user on a plain
+ /// OpenAI-compatible endpoint is in.
+ #[test]
+ fn a_cost_ceiling_is_refused_rather_than_run_uncapped() {
+ // A model id no listing can plausibly carry, so the lookup misses no
+ // matter what the developer running these tests has cached in
+ // `~/.jan/model_catalog.json` -- which is the state every user of a
+ // plain OpenAI-compatible endpoint is in anyway.
+ let unpriced = "no-such-model/never-published-a-price";
+
+ // No ceiling asked for: unmetered, and never a price lookup.
+ assert_eq!(resolve_cost_ceiling(None, None, None, unpriced), Ok(None));
+
+ // Asked for, but the model publishes no prices.
+ let refused = resolve_cost_ceiling(Some(2.0), None, None, unpriced)
+ .expect_err("an unpriceable ceiling must not silently run uncapped");
+ assert!(
+ refused.contains("publishes no prices"),
+ "the message has to say why: {refused}"
+ );
+ // The config source is refused on the same terms as the flag: a
+ // ceiling that came from agent.toml is no more enforceable.
+ assert!(resolve_cost_ceiling(None, Some(2.0), None, unpriced).is_err());
+ // Precedence, read off the amount the refusal quotes: the flag's $2
+ // is the ceiling in force, not the config's $9.
+ let precedence = resolve_cost_ceiling(Some(2.0), Some(9.0), None, unpriced)
+ .expect_err("still unpriceable");
+ assert!(
+ precedence.contains("$2") && !precedence.contains("$9"),
+ "the flag outranks the config: {precedence}"
+ );
+
+ // A negative limit is a typo, not a request to spend nothing.
+ let negative = resolve_cost_ceiling(Some(-1.0), None, None, unpriced)
+ .expect_err("a negative ceiling is rejected");
+ assert!(negative.contains("non-negative"), "{negative}");
+ assert!(resolve_cost_ceiling(Some(f64::NAN), None, None, unpriced).is_err());
+
+ // `0` is honest and must not be confused with "unset": it means stop
+ // at the first billed request. It still needs prices, so an unpriced
+ // model refuses rather than quietly passing the zero through.
+ assert!(resolve_cost_ceiling(Some(0.0), None, None, unpriced).is_err());
+ }
+
fn limits_with(max_turns: Option<u64>, max_session_tokens: u64) -> SessionLimits {
SessionLimits {
context_window: 128_000,
@@ -3666,6 +3808,7 @@ mod tests {
max_tokens: None,
max_session_tokens,
max_turns,
+ cost_ceiling: None,
}
}
diff --git a/src-tauri/src/core/cli/model_catalog.rs b/src-tauri/src/core/cli/model_catalog.rs
index d43382791..7008889cc 100644
--- a/src-tauri/src/core/cli/model_catalog.rs
+++ b/src-tauri/src/core/cli/model_catalog.rs
@@ -55,27 +55,31 @@ impl ModelInfo {
self.prompt_usd.is_some() && self.completion_usd.is_some()
}
- /// Estimated USD for one request's token counts.
- ///
- /// `cached` and `cache_write` are **shares of `prompt`**, not additions to
- /// it: every pipeline that reaches here normalizes Anthropic's usage the
- /// OpenAI way, so `prompt_tokens = input + cache_read + cache_write` (genai
- /// `anthropic/adapter_shared.rs`, and `core::server::converters` for Jan's
- /// own responses). Each share is billed at its own rate and the remainder
- /// at the prompt rate; a rate the provider did not publish falls back to
- /// the prompt rate, which is exactly what a prompt/completion-only price
- /// list already charges.
+ /// The per-token rates for this model, or `None` when it cannot be priced.
+ /// This is what a run's money ceiling is metered against, so it is the same
+ /// `has_pricing` answer rather than a second, looser notion of "priced".
+ pub fn rates(&self) -> Option<crate::core::agent::session::TokenRates> {
+ Some(crate::core::agent::session::TokenRates {
+ prompt_usd: self.prompt_usd?,
+ completion_usd: self.completion_usd?,
+ cache_read_usd: self.cache_read_usd,
+ cache_write_usd: self.cache_write_usd,
+ })
+ }
+
+ /// Estimated USD for one request's token counts. An unpriced model costs
+ /// nothing here; callers that must not bill a missing price as free go
+ /// through [`TokenUsage::cost_usd`], which checks [`Self::has_pricing`]
+ /// first.
pub fn cost_usd(&self, prompt: u64, completion: u64, cached: u64, cache_write: u64) -> f64 {
- let prompt_rate = self.prompt_usd.unwrap_or(0.0);
- // Clamped so a provider reporting a share larger than the prompt (or
- // two shares that together exceed it) cannot underflow the remainder.
- let cached = cached.min(prompt);
- let written = cache_write.min(prompt - cached);
- let fresh = prompt - cached - written;
- fresh as f64 * prompt_rate
- + cached as f64 * self.cache_read_usd.unwrap_or(prompt_rate)
- + written as f64 * self.cache_write_usd.unwrap_or(prompt_rate)
- + completion as f64 * self.completion_usd.unwrap_or(0.0)
+ self.rates()
+ .unwrap_or(crate::core::agent::session::TokenRates {
+ prompt_usd: self.prompt_usd.unwrap_or(0.0),
+ completion_usd: self.completion_usd.unwrap_or(0.0),
+ cache_read_usd: self.cache_read_usd,
+ cache_write_usd: self.cache_write_usd,
+ })
+ .cost_usd(prompt, completion, cached, cache_write)
}
}
diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rs
index 52f93358b..18dfd1a55 100644
--- a/src-tauri/src/core/cli/run_report.rs
+++ b/src-tauri/src/core/cli/run_report.rs
@@ -112,6 +112,10 @@ pub(crate) struct RunReport {
/// never read -- is the alarm this counter exists to raise.
cached_tokens: Option<u64>,
cache_write_tokens: Option<u64>,
+ /// Provider execution ids seen this run, in request order. Each is a handle
+ /// to one billing record; the `usage` above is only an estimate of the same
+ /// requests.
+ execution_ids: Vec<String>,
}
impl RunReport {
@@ -138,8 +142,17 @@ impl RunReport {
// Reasoning is display-only: it must not enter the piped/plain-text
// report answer, which is reserved for the final completion.
StreamEvent::Reasoning { .. } => {}
-StreamEvent::TurnUsage { usage } => {
+StreamEvent::TurnUsage {
+ usage,
+ execution_id,
+ } => {
self.usage.add(usage);
+ // Recorded so a scripted run can look up what the provider
+ // actually charged for each request it made, rather than only
+ // the local estimate this report already carries.
+ if let Some(id) = execution_id {
+ self.execution_ids.push(id.clone());
+ }
accumulate(&mut self.cached_tokens, usage.cached_tokens);
accumulate(&mut self.cache_write_tokens, usage.cache_write_tokens);
}
@@ -202,6 +215,8 @@ StreamEvent::TurnUsage { usage } => {
estimated_cost_usd: self
.usage
.cost_usd(super::model_catalog::load().get(provider, model)),
+ execution_ids: (!self.execution_ids.is_empty())
+ .then(|| self.execution_ids.clone()),
},
}
}
@@ -326,6 +341,13 @@ struct ReportUsage {
cache_write_tokens: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
estimated_cost_usd: Option<f64>,
+ /// Provider execution ids for the requests this run made, when the upstream
+ /// returned them. `jan usage generation <id>` turns one into the recorded
+ /// charge -- the authoritative counterpart to `estimated_cost_usd`. Omitted
+ /// rather than empty when none were reported, so its absence is never read
+ /// as "no requests were made".
+ #[serde(skip_serializing_if = "Option::is_none")]
+ execution_ids: Option<Vec<String>>,
}
/// Fold one request's optional cache total into the run's. An absent field adds
@@ -618,6 +640,7 @@ mod tests {
StreamEvent::Step { index: 1, max: 0 },
StreamEvent::TurnUsage {
usage: usage(9011, 655),
+ execution_id: None,
},
token("done"),
StreamEvent::Done {
@@ -656,6 +679,7 @@ mod tests {
StreamEvent::Step { index: 1, max: 0 },
StreamEvent::TurnUsage {
usage: usage(8123, 0),
+ execution_id: None,
},
token("I started reviewing auth.rs and"),
StreamEvent::Error {
@@ -713,7 +737,7 @@ mod tests {
}
value(report.finish(None, None, "m", 1, Some("done")))
};
- let turn = |usage| StreamEvent::TurnUsage { usage };
+ let turn = |usage| StreamEvent::TurnUsage { usage, execution_id: None };
let silent = envelope(vec![turn(usage(1_000, 10))]);
assert!(silent["usage"]["cached_tokens"].is_null(), "{silent}");
@@ -752,9 +776,11 @@ mod tests {
StreamEvent::Step { index: 1, max: 0 },
StreamEvent::TurnUsage {
usage: usage(100, 10),
+ execution_id: None,
},
child(StreamEvent::TurnUsage {
usage: usage(50, 5),
+ execution_id: None,
}),
// A child's own turns and prose belong to the child, not this run.
child(StreamEvent::Step { index: 9, max: 0 }),
@@ -762,6 +788,7 @@ mod tests {
StreamEvent::Step { index: 2, max: 0 },
StreamEvent::TurnUsage {
usage: usage(200, 20),
+ execution_id: None,
},
] {
report.observe(&ev);
@@ -797,6 +824,7 @@ mod tests {
let mut report = RunReport::default();
report.observe(&StreamEvent::TurnUsage {
usage: usage(1_000_000, 100_000),
+ execution_id: None,
});
let out = value(report.finish(None, None, "priced-model", 1, Some("done")));
assert_eq!(out["usage"]["estimated_cost_usd"], 2.0);
@@ -804,6 +832,7 @@ mod tests {
let mut report = RunReport::default();
report.observe(&StreamEvent::TurnUsage {
usage: usage(1_000, 100),
+ execution_id: None,
});
let out = value(report.finish(None, None, "unknown-model", 1, Some("done")));
assert!(
diff --git a/src-tauri/src/core/cli/tokamak.rs b/src-tauri/src/core/cli/tokamak.rs
index 5cb80fb37..d64027f01 100644
--- a/src-tauri/src/core/cli/tokamak.rs
+++ b/src-tauri/src/core/cli/tokamak.rs
@@ -19,10 +19,14 @@
//! [`super::tui`] for `/login`); this module is UI-free so both share one
//! implementation.
+pub mod usage;
+
use std::path::PathBuf;
use std::time::Duration;
-use crate::core::agent::global_config::{set_default_model_if_unset, set_provider, ProviderUpdate};
+use crate::core::agent::global_config::{
+ adopt_default_model, set_provider, DefaultModelChange, ProviderUpdate,
+};
/// Provider id this login writes to in `~/.jan/config.toml`.
pub const PROVIDER: &str = "tokamak";
@@ -61,8 +65,13 @@ const VERIFY_TIMEOUT: Duration = Duration::from_secs(20);
pub struct Login {
pub models: Vec<String>,
pub config_path: PathBuf,
- /// The model written to `default_model`, or `None` when the user already had one.
+ /// The model written to `default_model`, or `None` when the user already had
+ /// a usable one.
pub default_model: Option<String>,
+ /// Set when [`Login::default_model`] *replaced* a stale default rather than
+ /// filling an empty one, so the caller can say so: silently changing the
+ /// model a user thinks they are on would be worse than the 404 it avoids.
+ pub replaced_default: bool,
/// Who the server says signed in. Only the browser flow reports one; the
/// paste flow never learns it.
pub account: Option<String>,
@@ -76,10 +85,21 @@ pub fn sanitize_key(raw: &str) -> Result<String, String> {
super::auth::providers::sanitize_key(raw)
}
+/// What a `/models` listing said, for the two things that read it differently.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct Roster {
+ /// Every id, sorted, as stored in the provider's `models` list.
+ pub stored: Vec<String>,
+ /// The id the endpoint listed **first**. Kept separately because `stored`
+ /// is sorted, which would make "the provider's first model" mean nothing
+ /// more than "alphabetically first".
+ pub first_listed: Option<String>,
+}
+
/// Verify `api_key` against Tokamak and return the model ids it grants access
/// to. An empty list is a valid answer (the account has no models yet), so the
/// caller decides whether that is usable.
-async fn verify_key(api_key: &str) -> Result<Vec<String>, String> {
+async fn verify_key(api_key: &str) -> Result<Roster, String> {
let client = reqwest::Client::builder()
.timeout(VERIFY_TIMEOUT)
.build()
@@ -103,28 +123,39 @@ async fn verify_key(api_key: &str) -> Result<Vec<String>, String> {
// here is what lets `/context` and `/usage` report the real window and an
// actual cost rather than a catalog guess.
super::model_catalog::cache_listing(PROVIDER, &parsed);
- Ok(parse_models(&parsed))
+ Ok(roster_of(&parsed))
+}
+
+/// Split out so the sorted/wire-order pairing is testable without a server.
+fn roster_of(parsed: &serde_json::Value) -> Roster {
+ Roster {
+ stored: parse_models(parsed),
+ first_listed: super::auth::providers::listed_model_ids(parsed)
+ .into_iter()
+ .next(),
+ }
}
/// Verify the key, then persist it as the `tokamak` provider. Nothing is written
/// when verification fails, so a typo never leaves a broken entry behind.
pub async fn login(api_key: &str) -> Result<Login, String> {
let api_key = sanitize_key(api_key)?;
- let models = verify_key(&api_key).await?;
- persist(&api_key, models)
+ let roster = verify_key(&api_key).await?;
+ persist(&api_key, roster)
}
/// Write the verified key + model list to `~/.jan/config.toml`, adopting the
-/// first model as `default_model` when the user has none (otherwise the agent
-/// would still start with "no model specified" right after signing in).
-fn persist(api_key: &str, models: Vec<String>) -> Result<Login, String> {
+/// provider's first-listed model as `default_model` when the user has none
+/// (otherwise the agent would still start with "no model specified" right after
+/// signing in) or when their default is no longer offered anywhere.
+fn persist(api_key: &str, roster: Roster) -> Result<Login, String> {
let config_path = set_provider(
PROVIDER,
ProviderUpdate {
api_key: Some(api_key.to_string()),
clear_api_key: false,
base_url: Some(base_url()),
- models: Some(models.clone()),
+ models: Some(roster.stored.clone()),
api_type: None,
// A pasted key carries no metadata, and any left over from a
// previous browser login belongs to a key this one replaces.
@@ -133,20 +164,36 @@ fn persist(api_key: &str, models: Vec<String>) -> Result<Login, String> {
account: Some(None),
},
)?;
- let default_model = match models.first() {
- Some(first) if set_default_model_if_unset(first)? => Some(first.clone()),
- _ => None,
- };
+ let (default_model, replaced_default) = resolve_default(&roster)?;
Ok(Login {
- models,
+ models: roster.stored,
config_path,
default_model,
+ replaced_default,
// The paste flow verifies a key against `/v1/models`; it never learns
// who the key belongs to.
account: None,
})
}
+/// Point `default_model` at the provider's first-listed model when the stored
+/// default is missing or stale, reporting what happened.
+///
+/// Called *after* the roster is written, so the staleness check sees the list
+/// this sign-in just installed rather than the one it replaced -- that ordering
+/// is the whole point: a model retired upstream is only detectable once the new
+/// roster is on disk.
+fn resolve_default(roster: &Roster) -> Result<(Option<String>, bool), String> {
+ let Some(first) = roster.first_listed.as_ref() else {
+ return Ok((None, false));
+ };
+ Ok(match adopt_default_model(first)? {
+ Some(DefaultModelChange::Adopted) => (Some(first.clone()), false),
+ Some(DefaultModelChange::Repointed) => (Some(first.clone()), true),
+ None => (None, false),
+ })
+}
+
/// Run the device (browser-approval) login to completion and persist the
/// minted key. `pending` comes from [`super::device_auth::begin`].
///
@@ -158,25 +205,22 @@ pub(crate) async fn device_login(
pending: super::device_auth::PendingAuth,
) -> Result<Login, String> {
let minted = pending.claim().await?;
- let models = verify_key(&minted.api_key).await?;
- persist_minted(&minted, models)
+ let roster = verify_key(&minted.api_key).await?;
+ persist_minted(&minted, roster)
}
/// Persist a verified key plus the server-assigned key metadata (`key_id`/
/// `key_expires_at`, so `auth status` can show the expiry and logout can revoke
-/// this exact key), adopting the first model as `default_model` when the user
-/// has none.
-fn persist_minted(
- minted: &super::device_auth::Minted,
- models: Vec<String>,
-) -> Result<Login, String> {
+/// this exact key), adopting the provider's first-listed model as
+/// `default_model` when the user has none or theirs is no longer offered.
+fn persist_minted(minted: &super::device_auth::Minted, roster: Roster) -> Result<Login, String> {
let config_path = set_provider(
PROVIDER,
ProviderUpdate {
api_key: Some(minted.api_key.clone()),
clear_api_key: false,
base_url: Some(base_url()),
- models: Some(models.clone()),
+ models: Some(roster.stored.clone()),
api_type: None,
// Written even when the server sent nothing, so a re-login cannot
// leave the previous key's id behind to be revoked by mistake.
@@ -185,14 +229,12 @@ fn persist_minted(
account: Some(minted.account.clone()),
},
)?;
- let default_model = match models.first() {
- Some(first) if set_default_model_if_unset(first)? => Some(first.clone()),
- _ => None,
- };
+ let (default_model, replaced_default) = resolve_default(&roster)?;
Ok(Login {
- models,
+ models: roster.stored,
config_path,
default_model,
+ replaced_default,
account: minted.account.clone(),
})
}
@@ -442,6 +484,12 @@ mod tests {
parse_models(&body),
vec!["alpha".to_string(), "tokamak-1-preview".to_string()]
);
+ // Same payload, order preserved: the junk entries are still dropped and
+ // the duplicate still collapses, but to its *first* appearance.
+ assert_eq!(
+ super::super::auth::providers::listed_model_ids(&body),
+ vec!["tokamak-1-preview".to_string(), "alpha".to_string()]
+ );
}
#[test]
@@ -465,10 +513,21 @@ mod tests {
assert!(describe_failure(418, "").contains("418"));
}
+ /// A roster as a server would hand it over: `stored` sorted, `first_listed`
+ /// the id the endpoint led with.
+ fn roster(ids: &[&str]) -> Roster {
+ let mut stored: Vec<String> = ids.iter().map(|s| (*s).to_string()).collect();
+ stored.sort();
+ Roster {
+ stored,
+ first_listed: ids.first().map(|s| (*s).to_string()),
+ }
+ }
+
#[test]
fn persist_writes_provider_entry_and_default_model() {
with_temp_home(|_| {
- let login = persist("tk-1", vec!["m-a".into(), "m-b".into()]).expect("persist");
+ let login = persist("tk-1", roster(&["m-a", "m-b"])).expect("persist");
assert_eq!(login.default_model.as_deref(), Some("m-a"));
let configs = load_global_config().expect("load");
@@ -483,16 +542,18 @@ mod tests {
#[test]
fn persist_respects_an_existing_default_model() {
with_temp_home(|_| {
+ // Offered by this very roster, so it is a live choice, not a fossil.
crate::core::agent::global_config::set_default_model_if_unset("chosen").unwrap();
- let login = persist("tk-1", vec!["m-a".into()]).expect("persist");
+ let login = persist("tk-1", roster(&["m-a", "chosen"])).expect("persist");
assert_eq!(login.default_model, None);
+ assert!(!login.replaced_default);
});
}
#[test]
fn persist_with_no_models_still_saves_the_key() {
with_temp_home(|_| {
- let login = persist("tk-1", Vec::new()).expect("persist");
+ let login = persist("tk-1", roster(&[])).expect("persist");
assert!(login.models.is_empty());
assert_eq!(login.default_model, None);
let configs = load_global_config().expect("load");
@@ -506,8 +567,8 @@ mod tests {
#[test]
fn relogin_replaces_the_key_and_model_list() {
with_temp_home(|_| {
- persist("tk-old", vec!["m-a".into(), "m-b".into()]).expect("first");
- persist("tk-new", vec!["m-c".into()]).expect("second");
+ persist("tk-old", roster(&["m-a", "m-b"])).expect("first");
+ persist("tk-new", roster(&["m-c"])).expect("second");
let configs = load_global_config().expect("load");
let cfg = configs.get(PROVIDER).unwrap();
assert_eq!(cfg.api_key.as_deref(), Some("tk-new"));
@@ -515,6 +576,113 @@ mod tests {
});
}
+ /// The bug this guards: a re-login replaces the provider's roster wholesale,
+ /// so a default the upstream has since retired is left pointing at a model
+ /// nothing serves. Every later run 404s, and a `--max-budget-usd` ceiling is
+ /// refused as unpriceable, with nothing connecting either to the sign-in.
+ #[test]
+ fn a_relogin_repoints_a_default_the_provider_no_longer_offers() {
+ with_temp_home(|_| {
+ let first = persist("tk-old", roster(&["legacy-preview", "m-b"])).expect("first");
+ assert_eq!(first.default_model.as_deref(), Some("legacy-preview"));
+ assert!(!first.replaced_default, "nothing to replace on a fresh sign-in");
+
+ // The upstream retires it; the next sign-in lists a new roster.
+ let again = persist("tk-new", roster(&["m-c", "m-d"])).expect("second");
+ assert_eq!(again.default_model.as_deref(), Some("m-c"));
+ assert!(
+ again.replaced_default,
+ "a stale default must be reported as replaced, not swapped in silence"
+ );
+ assert_eq!(
+ crate::core::agent::global_config::default_model().unwrap().as_deref(),
+ Some("m-c"),
+ "the repoint must reach disk"
+ );
+ });
+ }
+
+ /// The other half: a default this sign-in still offers is a live choice, and
+ /// re-pointing it would overwrite a deliberate `/model` pick on every login.
+ #[test]
+ fn a_relogin_leaves_a_still_offered_default_alone() {
+ with_temp_home(|_| {
+ // Listed first, so this is what the user ended up on.
+ persist("tk-old", roster(&["chosen", "m-a"])).expect("first");
+
+ // A later sign-in leads with a different model, but still offers it.
+ let again = persist("tk-new", roster(&["m-a", "chosen"])).expect("second");
+ assert_eq!(again.default_model, None);
+ assert!(!again.replaced_default);
+ assert_eq!(
+ crate::core::agent::global_config::default_model().unwrap().as_deref(),
+ Some("chosen")
+ );
+ });
+ }
+
+ /// A model another provider still serves was not retired by this one, so the
+ /// tokamak roster says nothing about it either way.
+ #[test]
+ fn a_default_another_provider_serves_survives_a_tokamak_relogin() {
+ with_temp_home(|_| {
+ crate::core::agent::global_config::set_provider(
+ "local",
+ ProviderUpdate {
+ base_url: Some("http://localhost:1337/v1".into()),
+ models: Some(vec!["local-model".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ crate::core::agent::global_config::set_default_model_if_unset("local-model").unwrap();
+
+ let login = persist("tk-1", roster(&["m-a"])).expect("persist");
+ assert_eq!(login.default_model, None);
+ assert!(!login.replaced_default);
+ assert_eq!(
+ crate::core::agent::global_config::default_model().unwrap().as_deref(),
+ Some("local-model")
+ );
+ });
+ }
+
+ /// `default_model` follows the provider's wire order, not the sorted roster:
+ /// a gateway that ranks its listing is stating a preference, and sorting
+ /// would silently reduce "first" to "alphabetically first".
+ #[test]
+ fn the_adopted_default_is_the_first_listed_not_the_first_sorted() {
+ with_temp_home(|_| {
+ let listing = json!({"data": [{"id": "zeta-flagship"}, {"id": "alpha-legacy"}]});
+ let roster = roster_of(&listing);
+ assert_eq!(roster.first_listed.as_deref(), Some("zeta-flagship"));
+ assert_eq!(
+ roster.stored,
+ vec!["alpha-legacy".to_string(), "zeta-flagship".to_string()],
+ "the stored roster stays sorted for a stable config write"
+ );
+
+ let login = persist("tk-1", roster).expect("persist");
+ assert_eq!(login.default_model.as_deref(), Some("zeta-flagship"));
+ });
+ }
+
+ /// An account with no models must not be recorded as having chosen one:
+ /// there is nothing to point at, and writing an empty default would make
+ /// the config look configured.
+ #[test]
+ fn an_empty_roster_adopts_no_default() {
+ with_temp_home(|_| {
+ let login = persist("tk-1", roster(&[])).expect("persist");
+ assert_eq!(login.default_model, None);
+ assert!(!login.replaced_default);
+ assert_eq!(
+ crate::core::agent::global_config::default_model().unwrap(),
+ None
+ );
+ });
+ }
+
/// Build a claim result the way `device_auth` hands one over.
fn minted(key_id: Option<&str>, expires_at: Option<u64>) -> super::super::device_auth::Minted {
super::super::device_auth::Minted {
@@ -531,7 +699,7 @@ mod tests {
fn persist_minted_records_the_server_key_metadata() {
with_temp_home(|_| {
use crate::core::agent::global_config::provider_key_meta;
- let login = persist_minted(&minted(Some("k-1"), Some(1700000000)), vec!["m-a".into()])
+ let login = persist_minted(&minted(Some("k-1"), Some(1700000000)), roster(&["m-a"]))
.expect("persist");
assert_eq!(login.default_model.as_deref(), Some("m-a"));
assert_eq!(login.account.as_deref(), Some("[email protected]"));
@@ -551,7 +719,7 @@ mod tests {
#[test]
fn legacy_persist_writes_no_key_metadata() {
with_temp_home(|_| {
- persist("tk-1", vec![]).expect("persist");
+ persist("tk-1", roster(&[])).expect("persist");
use crate::core::agent::global_config::provider_key_meta;
let meta = provider_key_meta(PROVIDER).expect("meta");
assert!(meta.key_id.is_none());
@@ -565,11 +733,11 @@ mod tests {
#[test]
fn the_account_is_recorded_by_the_mint_and_cleared_by_a_paste() {
with_temp_home(|_| {
- persist_minted(&minted(Some("k-1"), None), vec![]).expect("persist");
+ persist_minted(&minted(Some("k-1"), None), roster(&[])).expect("persist");
assert_eq!(account().as_deref(), Some("[email protected]"));
assert_eq!(auth_status().account.as_deref(), Some("[email protected]"));
- persist("tk-pasted", vec![]).expect("persist paste");
+ persist("tk-pasted", roster(&[])).expect("persist paste");
assert_eq!(
account(),
None,
@@ -583,7 +751,7 @@ mod tests {
fn auth_status_reflects_signed_in_state_and_metadata() {
with_temp_home(|_| {
assert!(!auth_status().signed_in);
- persist_minted(&minted(Some("k-1"), Some(1700000000)), vec![]).expect("persist");
+ persist_minted(&minted(Some("k-1"), Some(1700000000)), roster(&[])).expect("persist");
let status = auth_status();
assert!(status.signed_in);
assert_eq!(status.endpoint, BASE_URL);
@@ -642,7 +810,7 @@ mod tests {
#[test]
fn expiry_warning_is_quiet_without_a_recorded_expiry() {
with_temp_home(|_| {
- persist("tk-1", vec![]).expect("persist");
+ persist("tk-1", roster(&[])).expect("persist");
assert_eq!(expiry_warning(), None);
});
}
@@ -651,7 +819,7 @@ mod tests {
fn expiry_warning_fires_for_a_key_that_is_about_to_lapse() {
with_temp_home(|_| {
let soon = unix_now() + 2 * 24 * 60 * 60;
- persist_minted(&minted(Some("k-1"), Some(soon)), vec![]).expect("persist");
+ persist_minted(&minted(Some("k-1"), Some(soon)), roster(&[])).expect("persist");
let warning = expiry_warning().expect("a key expiring in 2 days must warn");
assert!(warning.contains("2 days"), "{warning}");
});
@@ -676,7 +844,7 @@ mod tests {
#[test]
fn logout_without_a_key_id_clears_locally_only() {
with_temp_home(|_| {
- persist_minted(&minted(None, None), vec!["m-a".into()]).expect("persist");
+ persist_minted(&minted(None, None), roster(&["m-a"])).expect("persist");
assert!(auth_status().signed_in);
assert_eq!(run_logout(), Logout::ClearedOnly);
@@ -693,7 +861,7 @@ mod tests {
#[test]
fn logout_clears_locally_even_when_revocation_fails() {
with_temp_home(|_| {
- persist_minted(&minted(Some("k-1"), None), vec!["m-a".into()]).expect("persist");
+ persist_minted(&minted(Some("k-1"), None), roster(&["m-a"])).expect("persist");
assert_eq!(run_logout(), Logout::ClearedOnly);
assert!(!auth_status().signed_in);
});
diff --git a/src-tauri/src/core/cli/tokamak/usage.rs b/src-tauri/src/core/cli/tokamak/usage.rs
new file mode 100644
index 000000000..85fe813b9
--- /dev/null
+++ b/src-tauri/src/core/cli/tokamak/usage.rs
@@ -0,0 +1,967 @@
+//! Authoritative usage and spend, read from Tokamak's usage API.
+//!
+//! This is the counterpart to [`super::super::model_catalog`]'s estimate, not a
+//! replacement for it. The estimate is what the client can compute from token
+//! counts and a cached price list: it works offline, mid-turn, and for any
+//! provider, and it is the only thing available while a request is still in
+//! flight. What it can never be is a *charge* -- the price list may be stale or
+//! incomplete, the token counts may be reconstructed client-side, and billing
+//! can still be pending after a response completes.
+//!
+//! So the two are kept apart by construction. Everything in this module is a
+//! figure the server reported; nothing here is ever summed with, compared
+//! against, or substituted for a local estimate. [`Money`] exists to make that
+//! separation enforceable at the type level: an estimate is an `f64`, a charge
+//! is a `Money`, and there is deliberately no arithmetic between them.
+//!
+//! ## Why money is a string
+//!
+//! Tokamak's generation money fields are exact JSON numbers and its analytics
+//! money fields are decimal strings, both of which must survive a round trip
+//! intact if anyone is going to reconcile a charge against an invoice.
+//! `serde_json` without `arbitrary_precision` parses every JSON number through
+//! `f64`, so `0.000000123456789012345` comes back subtly different from what
+//! the server sent, and the difference lands in exactly the low-order digits a
+//! reconciliation cares about. [`Money`] therefore keeps the literal text the
+//! server sent, captured through `RawValue` before any numeric conversion can
+//! happen, and never converts it back.
+//!
+//! The same reasoning applies to every payload whose schema this module does
+//! not pin down: [`Payload`] walks the raw JSON text rather than a parsed
+//! `Value`, so an undocumented money field is rendered exactly as received
+//! instead of being quietly rounded on the way through.
+
+use std::time::Duration;
+
+use serde::Deserialize;
+use serde_json::value::RawValue;
+
+/// Bound on every call here. Usage endpoints are reads with no side effects, so
+/// a slow one is abandoned rather than retried: a retry against a paginated
+/// endpoint risks double-reading, and a stale spend figure is worse than a slow
+/// one.
+const USAGE_TIMEOUT: Duration = Duration::from_secs(20);
+
+/// Header Tokamak returns on an inference response, naming that execution.
+/// Every per-request lookup in this module is keyed by it.
+///
+/// Re-exported rather than redeclared: the send path that reads this header off
+/// a response lives in `agent::correlation`, and two spellings of one header
+/// name is one rename away from a lookup that silently finds nothing.
+pub use crate::core::agent::correlation::EXECUTION_ID_HEADER;
+
+/// Header a caller may send on an inference request to correlate it later.
+/// A correlation value can match several executions; it is not an idempotency
+/// key, and nothing here treats it as one. Re-exported for the reason above.
+pub use crate::core::agent::correlation::CLIENT_REQUEST_ID_HEADER;
+
+/// Why a usage read did not produce an answer.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum UsageError {
+ /// No Tokamak key is configured, so there is no account to read.
+ NotSignedIn,
+ /// The execution or correlation id named nothing this credential can see.
+ /// Per the API contract a foreign execution is reported as not found, so
+ /// this does not distinguish "never existed" from "belongs to someone
+ /// else" -- and neither should the message shown for it.
+ NotFound,
+ /// Anything else: transport failure, an upstream error status, or a body
+ /// that could not be read. Already phrased for a user.
+ Failed(String),
+}
+
+impl std::fmt::Display for UsageError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::NotSignedIn => write!(f, "not signed in to Tokamak - run `jan login`"),
+ Self::NotFound => write!(
+ f,
+ "no such record for this credential (a foreign execution reads as not found)"
+ ),
+ Self::Failed(message) => write!(f, "{message}"),
+ }
+ }
+}
+
+/// An exact monetary amount, kept as the literal text the server sent.
+///
+/// Deliberately not a number: see the module docs. There is no `f64`
+/// conversion and no arithmetic, because the only correct thing to do with a
+/// charge the server computed is show it or hand it to something that does
+/// decimal arithmetic properly. Summing charges client-side would reintroduce
+/// precisely the rounding this type exists to prevent.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Money(String);
+
+impl Money {
+ /// The amount exactly as the server wrote it.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+
+ /// Accept a JSON number literal or a decimal string, rejecting anything
+ /// that is not a plain decimal. A value shaped like `1e-7` is valid JSON
+ /// but is not a decimal literal, so it is kept verbatim rather than
+ /// normalized -- rewriting it would be the same class of mistake as
+ /// rounding it.
+ fn parse(raw: &RawValue) -> Option<Self> {
+ let text = raw.get().trim();
+ if text == "null" {
+ return None;
+ }
+ let unquoted = match text.strip_prefix('"').and_then(|t| t.strip_suffix('"')) {
+ // A decimal string carries no escapes worth handling; one that does
+ // is not a money field.
+ Some(inner) if !inner.contains('\\') => inner,
+ Some(_) => return None,
+ None => text,
+ };
+ let body = unquoted.strip_prefix('-').unwrap_or(unquoted);
+ let plausible = !body.is_empty()
+ && body.chars().all(|c| c.is_ascii_digit() || c == '.' || c == 'e' || c == 'E'
+ || c == '+' || c == '-')
+ && body.chars().any(|c| c.is_ascii_digit());
+ plausible.then(|| Self(unquoted.to_string()))
+ }
+}
+
+impl std::fmt::Display for Money {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+/// How far a billing figure has settled. Rendered verbatim rather than mapped
+/// onto a local vocabulary: a `pending` charge is not a final one, and calling
+/// it anything else would invite treating it as final.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum BillingStatus {
+ Final,
+ Pending,
+ NotBilled,
+ Cancelled,
+ /// A status this build does not know. Forwarded as-is instead of being
+ /// folded into one of the above, since guessing which would be a guess
+ /// about money.
+ Other(String),
+}
+
+impl BillingStatus {
+ fn from_str(raw: &str) -> Self {
+ match raw {
+ "final" => Self::Final,
+ "pending" => Self::Pending,
+ "not_billed" => Self::NotBilled,
+ "cancelled" => Self::Cancelled,
+ other => Self::Other(other.to_string()),
+ }
+ }
+
+ /// Whether the charge alongside this status is settled. A `false` here must
+ /// suppress any claim that the amount is what was billed.
+ pub fn is_final(&self) -> bool {
+ matches!(self, Self::Final)
+ }
+}
+
+impl std::fmt::Display for BillingStatus {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Final => f.write_str("final"),
+ Self::Pending => f.write_str("pending"),
+ Self::NotBilled => f.write_str("not_billed"),
+ Self::Cancelled => f.write_str("cancelled"),
+ Self::Other(other) => f.write_str(other),
+ }
+ }
+}
+
+/// One execution's record, as returned by `GET /v1/generation`.
+///
+/// Every field but `id` is optional, and that is the contract rather than
+/// defensive coding: a missing cost or token count means **unavailable**, not
+/// zero. Defaulting any of these to `0` would be indistinguishable from an
+/// honest zero and would turn "we do not know" into "it was free".
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Generation {
+ /// Tokamak execution UUID. Not the provider's response id.
+ pub id: String,
+ pub model: Option<String>,
+ pub streamed: Option<bool>,
+ pub native_tokens_prompt: Option<u64>,
+ pub native_tokens_completion: Option<u64>,
+ pub billing_status: Option<BillingStatus>,
+ /// The customer charge, when known.
+ pub total_cost: Option<Money>,
+ pub currency: Option<String>,
+ /// Measured usage cost, when returned. Explicitly **not** the customer
+ /// charge; reported beside `total_cost`, never in place of it.
+ pub rated_cost: Option<Money>,
+ /// The admission ceiling, when returned. Also not the customer charge --
+ /// it is what the request was authorized to spend, not what it did.
+ pub authorized_amount: Option<Money>,
+}
+
+/// Raw field layout of a generation record, with every money field captured as
+/// unparsed text so it never passes through `f64`.
+#[derive(Deserialize)]
+struct GenerationWire {
+ id: String,
+ #[serde(default)]
+ model: Option<String>,
+ #[serde(default)]
+ streamed: Option<bool>,
+ #[serde(default)]
+ native_tokens_prompt: Option<u64>,
+ #[serde(default)]
+ native_tokens_completion: Option<u64>,
+ #[serde(default)]
+ billing_status: Option<String>,
+ #[serde(default)]
+ total_cost: Option<Box<RawValue>>,
+ #[serde(default)]
+ currency: Option<String>,
+ #[serde(default)]
+ rated_cost: Option<Box<RawValue>>,
+ #[serde(default)]
+ authorized_amount: Option<Box<RawValue>>,
+}
+
+impl From<GenerationWire> for Generation {
+ fn from(wire: GenerationWire) -> Self {
+ let money = |raw: Option<Box<RawValue>>| raw.as_deref().and_then(Money::parse);
+ Self {
+ id: wire.id,
+ model: wire.model,
+ streamed: wire.streamed,
+ native_tokens_prompt: wire.native_tokens_prompt,
+ native_tokens_completion: wire.native_tokens_completion,
+ billing_status: wire.billing_status.as_deref().map(BillingStatus::from_str),
+ total_cost: money(wire.total_cost),
+ currency: wire.currency,
+ rated_cost: money(wire.rated_cost),
+ authorized_amount: money(wire.authorized_amount),
+ }
+ }
+}
+
+/// A response body whose schema this module does not pin down, kept as raw JSON
+/// text.
+///
+/// The account, daily and limit endpoints report figures whose exact field
+/// layout is a server concern and changes independently of this client.
+/// Deserializing them into a typed struct would mean either dropping fields the
+/// server added or rounding money fields the schema did not anticipate, so they
+/// are walked as text instead: unknown fields still appear, and an undocumented
+/// money field is shown exactly as sent.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Payload(String);
+
+impl Payload {
+ /// Flatten to `(dotted.path, value)` pairs with scalars rendered as their
+ /// source text. Objects recurse by key, arrays by index.
+ ///
+ /// The order is [`flatten`]'s: object keys sorted (JSON object order is not
+ /// meaningful, and a stable order is what makes the output diffable between
+ /// two runs), array elements in index order. Deliberately *not* re-sorted by
+ /// path afterwards -- a string sort puts `days[10]` before `days[2]`, which
+ /// reorders a list the server sent in a meaningful order.
+ pub fn fields(&self) -> Vec<(String, String)> {
+ let mut out = Vec::new();
+ match serde_json::from_str::<&RawValue>(&self.0) {
+ Ok(root) => flatten(String::new(), root, &mut out),
+ // Unreachable for a body that already parsed once, but a panic here
+ // would be a panic over a usage readout.
+ Err(_) => out.push((String::new(), self.0.clone())),
+ }
+ out
+ }
+
+ /// The body as received, for `--json` style output that must not reshape it.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+/// Walk raw JSON text, emitting one entry per scalar leaf. Numbers keep their
+/// literal text; strings are unquoted for display but not otherwise decoded,
+/// since a usage payload's strings are ids, currencies and decimal amounts.
+fn flatten(path: String, raw: &RawValue, out: &mut Vec<(String, String)>) {
+ let text = raw.get().trim();
+ if text.starts_with('{') {
+ // BTreeMap and not a Vec of pairs: object key order is not meaningful,
+ // and sorting here keeps nested output stable for free.
+ if let Ok(map) = serde_json::from_str::<std::collections::BTreeMap<String, &RawValue>>(text)
+ {
+ if map.is_empty() {
+ out.push((path, "{}".to_string()));
+ return;
+ }
+ for (key, value) in map {
+ let child = if path.is_empty() {
+ key
+ } else {
+ format!("{path}.{key}")
+ };
+ flatten(child, value, out);
+ }
+ return;
+ }
+ } else if text.starts_with('[') {
+ if let Ok(items) = serde_json::from_str::<Vec<&RawValue>>(text) {
+ if items.is_empty() {
+ out.push((path, "[]".to_string()));
+ return;
+ }
+ for (i, item) in items.into_iter().enumerate() {
+ flatten(format!("{path}[{i}]"), item, out);
+ }
+ return;
+ }
+ }
+ let scalar = match text.strip_prefix('"').and_then(|t| t.strip_suffix('"')) {
+ Some(inner) if !inner.contains('\\') => inner.to_string(),
+ _ => text.to_string(),
+ };
+ out.push((path, scalar));
+}
+
+/// Which read to perform. One enum rather than six functions so the shared
+/// request path -- auth, timeout, status mapping -- exists once, and so a
+/// caller can name a view without knowing its route.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Query {
+ /// `GET /v1/usage/me`: usage across this account's credentials, not only
+ /// the key making the request.
+ Summary,
+ /// `GET /v1/usage/me/requests`: recently recorded requests.
+ Requests,
+ /// `GET /v1/usage/me/daily`: daily totals.
+ Daily,
+ /// `GET /v1/usage/limits/current`: usage-limit status. Separate from wallet
+ /// credit, which is its own check and is not read here.
+ Limits,
+ /// `GET /v1/generation?id=`: one execution.
+ Generation(String),
+ /// `GET /v1/generations?client_request_id=`: every execution a caller
+ /// tagged with the same correlation id.
+ Correlated(String),
+}
+
+impl Query {
+ /// Path and query pairs, relative to the API root.
+ fn route(&self) -> (&'static str, Vec<(&'static str, &str)>) {
+ match self {
+ Self::Summary => ("usage/me", Vec::new()),
+ Self::Requests => ("usage/me/requests", Vec::new()),
+ Self::Daily => ("usage/me/daily", Vec::new()),
+ Self::Limits => ("usage/limits/current", Vec::new()),
+ Self::Generation(id) => ("generation", vec![("id", id.as_str())]),
+ Self::Correlated(id) => ("generations", vec![("client_request_id", id.as_str())]),
+ }
+ }
+
+ /// How this view is named in output.
+ pub fn label(&self) -> &'static str {
+ match self {
+ Self::Summary => "account usage",
+ Self::Requests => "recent requests",
+ Self::Daily => "daily totals",
+ Self::Limits => "usage limits",
+ Self::Generation(_) => "generation",
+ Self::Correlated(_) => "correlated generations",
+ }
+ }
+}
+
+/// Perform `query` against the configured Tokamak deployment and return the raw
+/// body.
+///
+/// Honours `TOKAMAK_BASE_URL` through [`super::base_url`], so a dev stack is
+/// reachable without a rebuild, and shapes failures through the same
+/// [`super::describe_failure`] the sign-in path uses -- one voice for upstream
+/// problems regardless of which endpoint hit them.
+pub async fn fetch(query: &Query) -> Result<Payload, UsageError> {
+ let api_key = super::stored_api_key().ok_or(UsageError::NotSignedIn)?;
+ let client = reqwest::Client::builder()
+ .timeout(USAGE_TIMEOUT)
+ .build()
+ .map_err(|e| UsageError::Failed(e.to_string()))?;
+
+ let root = super::base_url();
+ let (path, params) = query.route();
+ let mut request = client
+ .get(format!("{root}/{path}"))
+ .header("Authorization", format!("Bearer {api_key}"));
+ if !params.is_empty() {
+ request = request.query(&params);
+ }
+
+ let response = request
+ .send()
+ .await
+ .map_err(|e| UsageError::Failed(format!("could not reach {root}: {e}")))?;
+
+ let status = response.status();
+ let body = response.text().await.unwrap_or_default();
+ if status.as_u16() == 404 {
+ return Err(UsageError::NotFound);
+ }
+ if !status.is_success() {
+ return Err(UsageError::Failed(super::describe_failure(
+ status.as_u16(),
+ &body,
+ )));
+ }
+ // Parsed once here so every later walk of the text is infallible, and so a
+ // truncated body fails as a read error rather than as an empty readout.
+ serde_json::from_str::<&RawValue>(&body)
+ .map_err(|e| UsageError::Failed(format!("Tokamak returned a response we could not read: {e}")))?;
+ Ok(Payload(body))
+}
+
+/// Read one execution. The record arrives inside `data`, which holds exactly
+/// one entry for this endpoint; an empty `data` is the documented shape of a
+/// lookup that matched nothing and so reads as [`UsageError::NotFound`] rather
+/// than as an empty success.
+pub async fn generation(execution_id: &str) -> Result<Generation, UsageError> {
+ let payload = fetch(&Query::Generation(execution_id.to_string())).await?;
+ let mut records = parse_generations(payload.as_str())?;
+ if records.is_empty() {
+ return Err(UsageError::NotFound);
+ }
+ Ok(records.remove(0))
+}
+
+/// Read every execution tagged with `client_request_id`. Unlike a single
+/// lookup, an empty result here is a legitimate answer -- the caller may simply
+/// never have sent that id -- so it is `Ok(vec![])`, not a not-found.
+pub async fn correlated(client_request_id: &str) -> Result<Vec<Generation>, UsageError> {
+ let payload = fetch(&Query::Correlated(client_request_id.to_string())).await?;
+ parse_generations(payload.as_str())
+}
+
+/// Parse an already-fetched payload as generation records, for a caller that
+/// fetched through [`fetch`] rather than [`generation`] (the TUI, which runs
+/// every view through one off-loop job and renders the result afterwards).
+pub fn parse_generations_payload(payload: &Payload) -> Result<Vec<Generation>, UsageError> {
+ parse_generations(payload.as_str())
+}
+
+/// Pull the `data` array out of a generations body. Both endpoints answer with
+/// `data` as an array (the single lookup simply puts one record in it), so one
+/// parser serves both.
+fn parse_generations(body: &str) -> Result<Vec<Generation>, UsageError> {
+ #[derive(Deserialize)]
+ struct Envelope {
+ #[serde(default)]
+ data: Vec<GenerationWire>,
+ }
+ let envelope: Envelope = serde_json::from_str(body)
+ .map_err(|e| UsageError::Failed(format!("could not read the generation record: {e}")))?;
+ Ok(envelope.data.into_iter().map(Generation::from).collect())
+}
+
+/// Build a [`Payload`] from a literal body, for tests in other modules that
+/// need to render a readout without a server to fetch it from.
+#[cfg(test)]
+pub fn parse_payload_for_test(body: &str) -> Payload {
+ Payload(body.to_string())
+}
+
+/// One row of aggregated analytics: a model's slice of the account summary, a
+/// day's totals, or the account-wide total.
+///
+/// Token counts default to zero because these endpoints report a count for
+/// every bucket they return a row for -- a row exists *because* there was
+/// traffic. Cost does not default: it is [`Money`] or nothing, for the same
+/// reason a generation's charge is.
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub struct Aggregate {
+ /// Model id for a by-model row, the date for a daily row, empty for the
+ /// account total.
+ pub label: String,
+ pub prompt_tokens: u64,
+ pub completion_tokens: u64,
+ pub cache_read_tokens: u64,
+ pub cache_creation_tokens: u64,
+ pub request_count: u64,
+ /// What the server computed this slice cost. Exact text, never summed
+ /// client-side -- the server already totalled it in the row that says so.
+ pub cost: Option<Money>,
+ /// What caching saved, when reported.
+ pub savings: Option<Money>,
+}
+
+#[derive(Deserialize)]
+struct AggregateWire {
+ #[serde(default)]
+ model: Option<String>,
+ #[serde(default)]
+ date: Option<String>,
+ #[serde(default)]
+ total_prompt_tokens: u64,
+ #[serde(default)]
+ total_completion_tokens: u64,
+ #[serde(default)]
+ cache_read_tokens: u64,
+ #[serde(default)]
+ cache_creation_tokens: u64,
+ #[serde(default)]
+ request_count: u64,
+ #[serde(default)]
+ estimated_cost_usd: Option<Box<RawValue>>,
+ #[serde(default)]
+ cache_savings_usd: Option<Box<RawValue>>,
+}
+
+impl From<AggregateWire> for Aggregate {
+ fn from(wire: AggregateWire) -> Self {
+ Self {
+ // A daily row is named by its date and a model row by its model;
+ // the account total carries neither and is labelled by context.
+ label: wire
+ .model
+ .filter(|m| !m.is_empty())
+ .or(wire.date)
+ .unwrap_or_default(),
+ prompt_tokens: wire.total_prompt_tokens,
+ completion_tokens: wire.total_completion_tokens,
+ cache_read_tokens: wire.cache_read_tokens,
+ cache_creation_tokens: wire.cache_creation_tokens,
+ request_count: wire.request_count,
+ cost: wire.estimated_cost_usd.as_deref().and_then(Money::parse),
+ savings: wire.cache_savings_usd.as_deref().and_then(Money::parse),
+ }
+ }
+}
+
+/// `GET /v1/usage/me`: the account total plus its per-model breakdown.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct AccountSummary {
+ /// Window the figures cover, as the server dated it.
+ pub period: Option<(String, String)>,
+ pub total: Aggregate,
+ pub by_model: Vec<Aggregate>,
+}
+
+/// Parse the account summary. Returns `None` when the body is not that shape,
+/// so the caller can fall back to the generic field walk rather than claim the
+/// server sent nothing.
+pub fn parse_account_summary(payload: &Payload) -> Option<AccountSummary> {
+ #[derive(Deserialize)]
+ struct Period {
+ start_date: String,
+ end_date: String,
+ }
+ #[derive(Deserialize)]
+ struct Wire {
+ #[serde(default)]
+ period: Option<Period>,
+ total_usage: AggregateWire,
+ #[serde(default)]
+ by_model: Vec<AggregateWire>,
+ }
+ let wire: Wire = serde_json::from_str(payload.as_str()).ok()?;
+ Some(AccountSummary {
+ period: wire.period.map(|p| (p.start_date, p.end_date)),
+ total: wire.total_usage.into(),
+ by_model: wire.by_model.into_iter().map(Aggregate::from).collect(),
+ })
+}
+
+/// Parse `GET /v1/usage/me/daily`, a bare array of per-day totals.
+pub fn parse_daily(payload: &Payload) -> Option<Vec<Aggregate>> {
+ let wire: Vec<AggregateWire> = serde_json::from_str(payload.as_str()).ok()?;
+ Some(wire.into_iter().map(Aggregate::from).collect())
+}
+
+/// One recorded request from `GET /v1/usage/me/requests`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RequestRecord {
+ pub execution_id: Option<String>,
+ pub model: Option<String>,
+ pub billing_status: Option<BillingStatus>,
+ pub prompt_tokens: u64,
+ pub completion_tokens: u64,
+ pub cache_read_tokens: u64,
+ pub cost: Option<Money>,
+ pub created_at: Option<String>,
+ /// HTTP status the caller saw. A non-200 is why a row may have no cost.
+ pub status: Option<u16>,
+}
+
+#[derive(Deserialize)]
+struct RequestWire {
+ #[serde(default)]
+ execution_id: Option<String>,
+ #[serde(default)]
+ model: Option<String>,
+ #[serde(default)]
+ billing_status: Option<String>,
+ #[serde(default)]
+ prompt_tokens: u64,
+ #[serde(default)]
+ completion_tokens: u64,
+ #[serde(default)]
+ cache_read_tokens: u64,
+ #[serde(default)]
+ estimated_cost_usd: Option<Box<RawValue>>,
+ #[serde(default)]
+ created_at: Option<String>,
+ #[serde(default)]
+ status: Option<u16>,
+}
+
+/// Parse the recorded-requests list out of its `data` envelope.
+pub fn parse_requests(payload: &Payload) -> Option<Vec<RequestRecord>> {
+ #[derive(Deserialize)]
+ struct Envelope {
+ #[serde(default)]
+ data: Vec<RequestWire>,
+ }
+ let envelope: Envelope = serde_json::from_str(payload.as_str()).ok()?;
+ Some(
+ envelope
+ .data
+ .into_iter()
+ .map(|wire| RequestRecord {
+ execution_id: wire.execution_id,
+ model: wire.model,
+ billing_status: wire.billing_status.as_deref().map(BillingStatus::from_str),
+ prompt_tokens: wire.prompt_tokens,
+ completion_tokens: wire.completion_tokens,
+ cache_read_tokens: wire.cache_read_tokens,
+ cost: wire.estimated_cost_usd.as_deref().and_then(Money::parse),
+ created_at: wire.created_at,
+ status: wire.status,
+ })
+ .collect(),
+ )
+}
+
+/// `GET /v1/usage/limits/current`: whether the account is currently allowed to
+/// spend, and the decisions behind that.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LimitStatus {
+ pub allowed: bool,
+ /// Each limit the server evaluated, rendered from whatever fields it
+ /// carried -- the decision schema is not pinned here.
+ pub decisions: Vec<String>,
+}
+
+/// Parse the current-limits view. A `null` `decisions` is the documented shape
+/// of "nothing to report", not an error.
+pub fn parse_limits(payload: &Payload) -> Option<LimitStatus> {
+ #[derive(Deserialize)]
+ struct Wire {
+ allowed: bool,
+ #[serde(default)]
+ decisions: Option<Vec<Box<RawValue>>>,
+ }
+ let wire: Wire = serde_json::from_str(payload.as_str()).ok()?;
+ Some(LimitStatus {
+ allowed: wire.allowed,
+ decisions: wire
+ .decisions
+ .unwrap_or_default()
+ .iter()
+ .map(|raw| {
+ // Unpinned schema: flatten each decision to `key=value` pairs
+ // so an added field shows up instead of being dropped.
+ let mut fields = Vec::new();
+ flatten(String::new(), raw, &mut fields);
+ fields
+ .iter()
+ .map(|(path, value)| format!("{path}={value}"))
+ .collect::<Vec<_>>()
+ .join(" ")
+ })
+ .collect(),
+ })
+}
+
+/// How a field with no value is shown. Never `0` and never blank: the whole
+/// point is that unavailable and zero are different answers, and a blank cell
+/// reads as zero to most people.
+pub const UNAVAILABLE: &str = "unavailable";
+
+/// Render one generation as aligned `label: value` lines.
+///
+/// `rated_cost` and `authorized_amount` are labelled for what they are rather
+/// than presented alongside the charge as if interchangeable, and a
+/// non-`final` billing status is called out on the cost line itself so the
+/// number is never read as settled.
+pub fn generation_lines(record: &Generation) -> Vec<String> {
+ let optional = |value: Option<String>| value.unwrap_or_else(|| UNAVAILABLE.to_string());
+ let currency = record
+ .currency
+ .as_deref()
+ .map(|c| format!(" {c}"))
+ .unwrap_or_default();
+
+ let mut lines = vec![
+ format!("execution: {}", record.id),
+ format!("model: {}", optional(record.model.clone())),
+ format!(
+ "streamed: {}",
+ optional(record.streamed.map(|s| s.to_string()))
+ ),
+ format!(
+ "tokens in: {}",
+ optional(record.native_tokens_prompt.map(|t| t.to_string()))
+ ),
+ format!(
+ "tokens out: {}",
+ optional(record.native_tokens_completion.map(|t| t.to_string()))
+ ),
+ format!(
+ "billing: {}",
+ optional(record.billing_status.as_ref().map(|s| s.to_string()))
+ ),
+ ];
+
+ let settled = record.billing_status.as_ref().is_some_and(BillingStatus::is_final);
+ lines.push(match &record.total_cost {
+ Some(cost) if settled => format!("charge: {cost}{currency}"),
+ // A figure that is not final is still worth showing -- it is the best
+ // information there is -- but it must not be called a charge.
+ Some(cost) => format!("charge: {cost}{currency} (not final)"),
+ None => format!("charge: {UNAVAILABLE}"),
+ });
+ if let Some(rated) = &record.rated_cost {
+ lines.push(format!("rated cost: {rated}{currency} (measured usage, not the charge)"));
+ }
+ if let Some(authorized) = &record.authorized_amount {
+ lines.push(format!(
+ "authorized: {authorized}{currency} (admission ceiling, not the charge)"
+ ));
+ }
+ lines
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn raw(text: &str) -> Box<RawValue> {
+ RawValue::from_string(text.to_string()).expect("valid json")
+ }
+
+ /// The whole reason [`Money`] is not an `f64`. This literal has more
+ /// significant digits than a double can hold, so a parse-and-reformat round
+ /// trip changes it -- and the digits it changes are the ones a
+ /// reconciliation against an invoice would be looking at.
+ #[test]
+ fn money_survives_a_value_f64_would_round() {
+ let exact = "0.1234567890123456789012345";
+ let money = Money::parse(&raw(exact)).expect("a decimal literal is money");
+ assert_eq!(money.as_str(), exact);
+
+ let through_f64 = exact.parse::<f64>().expect("parses as a double");
+ assert_ne!(
+ through_f64.to_string(),
+ exact,
+ "the test value must actually be one f64 mangles, or it proves nothing"
+ );
+ }
+
+ /// Analytics money arrives as a decimal string while generation money
+ /// arrives as a bare number. Both are the same kind of thing and both must
+ /// come back byte-identical.
+ #[test]
+ fn money_accepts_both_the_string_and_number_forms() {
+ assert_eq!(
+ Money::parse(&raw("\"12.3456789\"")).map(|m| m.as_str().to_string()),
+ Some("12.3456789".to_string())
+ );
+ assert_eq!(
+ Money::parse(&raw("12.3456789")).map(|m| m.as_str().to_string()),
+ Some("12.3456789".to_string())
+ );
+ assert_eq!(
+ Money::parse(&raw("-0.5")).map(|m| m.as_str().to_string()),
+ Some("-0.5".to_string())
+ );
+ }
+
+ /// A null cost is unavailable, not zero -- the distinction this whole
+ /// module is built around.
+ #[test]
+ fn a_null_amount_is_not_money() {
+ assert_eq!(Money::parse(&raw("null")), None);
+ assert_eq!(Money::parse(&raw("\"\"")), None);
+ assert_eq!(Money::parse(&raw("{}")), None);
+ }
+
+ #[test]
+ fn a_generation_record_keeps_its_exact_charge() {
+ let body = r#"{"data":[{
+ "id":"exec-1",
+ "model":"gpt-5",
+ "streamed":true,
+ "native_tokens_prompt":1200,
+ "native_tokens_completion":34,
+ "billing_status":"final",
+ "total_cost":0.000000123456789012345678,
+ "currency":"USD"
+ }]}"#;
+ let mut records = parse_generations(body).expect("parses");
+ let record = records.remove(0);
+ assert_eq!(record.id, "exec-1");
+ assert_eq!(record.model.as_deref(), Some("gpt-5"));
+ assert_eq!(record.streamed, Some(true));
+ assert_eq!(record.native_tokens_prompt, Some(1200));
+ assert_eq!(record.billing_status, Some(BillingStatus::Final));
+ assert_eq!(
+ record.total_cost.as_ref().map(Money::as_str),
+ Some("0.000000123456789012345678"),
+ "the charge must be exactly what the server sent"
+ );
+ }
+
+ /// Missing fields must stay missing all the way to the rendered line, and
+ /// must never be defaulted into a zero that reads as "it was free".
+ #[test]
+ fn missing_fields_render_as_unavailable_not_zero() {
+ let body = r#"{"data":[{"id":"exec-2"}]}"#;
+ let mut records = parse_generations(body).expect("parses");
+ let record = records.remove(0);
+ assert_eq!(record.total_cost, None);
+ assert_eq!(record.native_tokens_prompt, None);
+
+ let lines = generation_lines(&record).join("\n");
+ assert!(lines.contains("charge: unavailable"), "{lines}");
+ assert!(lines.contains("tokens in: unavailable"), "{lines}");
+ assert!(!lines.contains(" 0"), "nothing may be defaulted to zero: {lines}");
+ }
+
+ /// An honest zero is a different answer from an absent one, and has to
+ /// render as a zero.
+ #[test]
+ fn a_reported_zero_is_reported_as_zero() {
+ let body = r#"{"data":[{"id":"e","native_tokens_completion":0,"total_cost":0,"billing_status":"not_billed"}]}"#;
+ let mut records = parse_generations(body).expect("parses");
+ let record = records.remove(0);
+ assert_eq!(record.native_tokens_completion, Some(0));
+ assert_eq!(record.total_cost.as_ref().map(Money::as_str), Some("0"));
+ let lines = generation_lines(&record).join("\n");
+ assert!(lines.contains("tokens out: 0"), "{lines}");
+ }
+
+ /// A pending charge is shown, because it is the best figure available, but
+ /// never as a settled one.
+ #[test]
+ fn a_pending_charge_is_never_presented_as_final() {
+ let body = r#"{"data":[{"id":"e","total_cost":1.25,"currency":"USD","billing_status":"pending"}]}"#;
+ let mut records = parse_generations(body).expect("parses");
+ let lines = generation_lines(&records.remove(0)).join("\n");
+ assert!(lines.contains("billing: pending"), "{lines}");
+ assert!(lines.contains("1.25 USD (not final)"), "{lines}");
+ }
+
+ /// Neither of these is the customer charge, and the output has to say so
+ /// rather than let them be mistaken for it.
+ #[test]
+ fn rated_and_authorized_are_labelled_as_not_the_charge() {
+ let body = r#"{"data":[{"id":"e","rated_cost":"0.30","authorized_amount":"5.00","billing_status":"pending"}]}"#;
+ let mut records = parse_generations(body).expect("parses");
+ let lines = generation_lines(&records.remove(0)).join("\n");
+ assert!(lines.contains("rated cost: 0.30 (measured usage, not the charge)"), "{lines}");
+ assert!(
+ lines.contains("authorized: 5.00 (admission ceiling, not the charge)"),
+ "{lines}"
+ );
+ }
+
+ /// An unknown billing status is forwarded rather than guessed at, and is
+ /// not treated as final.
+ #[test]
+ fn an_unknown_billing_status_is_forwarded_and_not_final() {
+ let status = BillingStatus::from_str("reconciling");
+ assert_eq!(status, BillingStatus::Other("reconciling".to_string()));
+ assert!(!status.is_final());
+ assert_eq!(status.to_string(), "reconciling");
+ }
+
+ /// The documented shape of a lookup that matched nothing.
+ #[test]
+ fn an_empty_data_array_is_no_records() {
+ assert!(parse_generations(r#"{"data":[]}"#).expect("parses").is_empty());
+ assert!(parse_generations("{}").expect("parses").is_empty());
+ }
+
+ #[test]
+ fn a_body_that_is_not_a_generation_envelope_is_an_error() {
+ assert!(matches!(
+ parse_generations("not json"),
+ Err(UsageError::Failed(_))
+ ));
+ }
+
+ /// The undocumented-schema path: unknown fields survive, and money keeps
+ /// its digits because the walk never parses a number.
+ #[test]
+ fn payload_flattens_unknown_shapes_without_rounding_money() {
+ let payload = Payload(
+ r#"{"spend":"0.1234567890123456789","buckets":[{"day":"2026-09-01","cost":0.000000000000000001}],"future_field":true}"#
+ .to_string(),
+ );
+ let fields = payload.fields();
+ let lookup = |name: &str| {
+ fields
+ .iter()
+ .find(|(path, _)| path == name)
+ .map(|(_, value)| value.as_str())
+ };
+ assert_eq!(lookup("spend"), Some("0.1234567890123456789"));
+ assert_eq!(lookup("buckets[0].day"), Some("2026-09-01"));
+ assert_eq!(lookup("buckets[0].cost"), Some("0.000000000000000001"));
+ assert_eq!(
+ lookup("future_field"),
+ Some("true"),
+ "a field this build has never heard of must still be reported"
+ );
+ }
+
+ #[test]
+ fn payload_fields_are_sorted_so_output_is_stable() {
+ let payload = Payload(r#"{"z":1,"a":2,"m":{"b":3}}"#.to_string());
+ let paths: Vec<String> = payload.fields().into_iter().map(|(p, _)| p).collect();
+ assert_eq!(paths, vec!["a".to_string(), "m.b".to_string(), "z".to_string()]);
+ }
+
+ #[test]
+ fn empty_containers_are_reported_rather_than_dropped() {
+ let payload = Payload(r#"{"rows":[],"meta":{}}"#.to_string());
+ let fields = payload.fields();
+ assert!(fields.iter().any(|(p, v)| p == "rows" && v == "[]"), "{fields:?}");
+ assert!(fields.iter().any(|(p, v)| p == "meta" && v == "{}"), "{fields:?}");
+ }
+
+ #[test]
+ fn routes_match_the_documented_endpoints() {
+ assert_eq!(Query::Summary.route().0, "usage/me");
+ assert_eq!(Query::Requests.route().0, "usage/me/requests");
+ assert_eq!(Query::Daily.route().0, "usage/me/daily");
+ assert_eq!(Query::Limits.route().0, "usage/limits/current");
+ let generation = Query::Generation("x".to_string());
+ let (path, params) = generation.route();
+ assert_eq!((path, params), ("generation", vec![("id", "x")]));
+ let correlated = Query::Correlated("c".to_string());
+ let (path, params) = correlated.route();
+ assert_eq!(
+ (path, params),
+ ("generations", vec![("client_request_id", "c")])
+ );
+ }
+
+ /// A not-found is phrased so it cannot be read as "you were charged
+ /// nothing", and does not speculate about whose execution it was.
+ #[test]
+ fn the_not_found_message_does_not_imply_a_zero_charge() {
+ let message = UsageError::NotFound.to_string();
+ assert!(message.contains("not found"), "{message}");
+ assert!(!message.contains('0'), "{message}");
+ }
+}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index b559fcf72..2b4cd4513 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -704,16 +704,96 @@ enum ToolsState {
Failed(String),
}
-/// Overlay state for the `/context` readout. Replaces the old idle-only
-/// transcript row: the report now lands here off the render loop, so `/context`
-/// stays responsive while a turn is running and the readout reads as a popup
-/// the user closes with Esc rather than a line committed to the conversation.
-enum ContextView {
- /// Requested, not yet computed. The off-loop job for it is in flight (or
- /// queued behind the loop picking up `context_request`).
+/// A docked readout: `/context` and every `/usage` view, which are one kind of
+/// surface -- a question the user asks about the run, answered in place and
+/// dismissed with Esc, never committed to the conversation.
+///
+/// One field on `App` holds one of these, so a second readout *replaces* the
+/// first rather than stacking on it. That exclusivity used to be a comment
+/// ("only one can be open at a time") maintained by two independent `Option`s
+/// that could both be `Some`; here it is the type.
+///
+/// The variants stay distinct because the questions are distinct, and the
+/// difference is the whole point of the feature: `Context` and `Session` are
+/// **local estimates**, `Reported` is **what the provider actually recorded**.
+/// Collapsing them into a bag of lines would make it possible to render a
+/// charge and an estimate identically, which is the one thing these surfaces
+/// must never do.
+enum Readout {
+ /// `/context`: the current window. Requested, not yet computed -- the
+ /// off-loop job is in flight (or queued behind `readout_request`).
+ ContextLoading,
+ /// `/context`: the computed report.
+ Context(Box<ContextReport>),
+ /// Bare `/usage`: this session's local estimate, priced from the
+ /// provider's published rates. Rendered from live `App` state at draw
+ /// time rather than snapshotted here, so a readout left open during a turn
+ /// keeps counting instead of freezing on the totals it opened with.
+ ///
+ /// The flag is whether the model list is expanded past the top few. It
+ /// lives on the readout rather than on `App` so it resets with the dock:
+ /// an expansion is a thing you did to this readout, not a preference.
+ Session { all_models: bool },
+ /// Bare `/usage`: the session estimate and the account's recorded spend
+ /// in one pane, each labelled with its source.
+ ///
+ /// The two halves are never added together and never share a figure --
+ /// that is the whole reason this is one readout with two sections rather
+ /// than one combined number. The session half renders instantly from
+ /// local state; the account half arrives over the network, so it carries
+ /// its own state instead of holding the whole readout on a spinner.
+ Overview {
+ all_models: bool,
+ account: AccountSlot,
+ },
+ /// `/usage <account view>`: requested, not yet fetched.
+ ReportedLoading(super::tokamak::usage::Query),
+ /// `/usage <account view>`: the fetched body, rendered at draw time.
+ ///
+ /// The payload is kept rather than the rendered lines so `m` can fold the
+ /// breakdown without refetching -- re-asking the server for a list the
+ /// user already has would bill a request to expand a table. `error` holds
+ /// a failed read, which has no payload to re-render.
+ Reported {
+ title: String,
+ query: super::tokamak::usage::Query,
+ payload: Box<super::tokamak::usage::Payload>,
+ all_rows: bool,
+ },
+ /// `/usage <account view>`: the read failed, and why.
+ ReportedError { title: String, message: String },
+}
+
+/// The account half of the overview, which is a network read and so has to
+/// be able to say "not yet", "not available" and "not configured" without
+/// taking the session half down with it.
+#[derive(Debug, Clone)]
+enum AccountSlot {
+ /// No Tokamak credential, so there is no account to read. Not an error:
+ /// most providers have no usage API and the session estimate is the whole
+ /// answer for them.
+ NotConfigured,
Loading,
- /// The computed report, ready to render.
- Ready(Box<ContextReport>),
+ Ready(Box<super::tokamak::usage::Payload>),
+ /// The read failed, and why. Shown rather than swallowed: a blank account
+ /// section would read as "you have spent nothing".
+ Failed(String),
+}
+
+impl Readout {
+ /// The dock's title. Names the *source*, not just the command: "session
+ /// estimate" and what the provider recorded are different claims about
+ /// money, and the title is where a user reads which one they are looking
+ /// at.
+ fn title(&self) -> String {
+ match self {
+ Readout::ContextLoading | Readout::Context(_) => "context".to_string(),
+ Readout::Session { .. } => "session estimate".to_string(),
+ Readout::Overview { .. } => "usage".to_string(),
+ Readout::ReportedLoading(query) => query.label().to_string(),
+ Readout::Reported { title, .. } | Readout::ReportedError { title, .. } => title.clone(),
+ }
+ }
}
/// Off-loop MCP work the detail screen hands to the loop. Everything here
@@ -1778,9 +1858,15 @@ struct App {
/// Per-request output cap forwarded to the model as OpenAI `max_tokens`.
/// `None` omits the field (model default).
max_tokens: Option<u64>,
- /// Token-spend ceiling for one message's run; `0` is unbounded. The only
- /// cap on run length -- there is no turn limit.
+ /// Token-spend ceiling for one message's run; `0` is unbounded. Advisory:
+ /// crossing it compacts and files a note rather than stopping the run.
max_session_tokens: u64,
+ /// `[budget].max_usd`: what one message's run may spend before it stops,
+ /// with the rates to meter it against. `None` -- the default -- leaves the
+ /// session unmetered. Per run, not per session: each message gets the same
+ /// ceiling, because the user set a bound on what a task may cost and an
+ /// interactive session is a sequence of tasks, not one.
+ cost_ceiling: Option<crate::core::agent::session::CostCeiling>,
/// Repo top-level when the project is a git repo; enables workspace snapshots.
/// Cleared if git setup fails, permanently disabling snapshots this session.
repo_root: Option<PathBuf>,
@@ -1981,12 +2067,24 @@ struct App {
/// keyboard while open. Holds the setting being edited and any validation
/// error; writes go straight to agent.toml on Enter.
settings_prompt: Option<SettingsPrompt>,
- /// Current `/context` overlay, if one is open. `None` when closed.
- context_view: Option<ContextView>,
+ /// The open readout (`/context` or any `/usage` view), or `None`. One
+ /// field, so opening either replaces the other instead of stacking two
+ /// popups over each other.
+ readout: Option<Readout>,
/// Set by `/context` to ask the loop to compute the report off the render
/// loop (it sizes the tool segment, which takes the MCP server lock a turn
/// may be holding). Taken once, like `mcp_job_request`.
context_request: bool,
+ /// The provider's execution id for the most recent request that reported
+ /// one, so `/usage` can name something concrete to look up. `None` when no
+ /// request has reported one -- which is the normal case on the default
+ /// upstream path, where the response headers are unreachable.
+ last_execution_id: Option<String>,
+ /// Set by `/usage <mode>` to ask the loop to perform the read off the
+ /// render loop. These are network calls against the provider's usage API,
+ /// so running one inline would freeze the frame for as long as the request
+ /// takes. Taken once, like `context_request`.
+ reported_usage_request: Option<super::tokamak::usage::Query>,
/// Active MCP add/edit wizard (docked); owns the keyboard while open.
mcp_prompt: Option<McpPrompt>,
/// The `/mcp` detail screen's data, alongside the `McpServer` picker whose
@@ -2528,6 +2626,7 @@ impl App {
compaction_reserve_tokens: limits.compaction_reserve_tokens,
max_tokens: limits.max_tokens,
max_session_tokens: limits.max_session_tokens,
+ cost_ceiling: limits.cost_ceiling,
repo_root,
git_branch: git::current_branch(&project_root),
project_root,
@@ -2594,8 +2693,10 @@ impl App {
model_picker: None,
login: None,
settings_prompt: None,
- context_view: None,
+ readout: None,
context_request: false,
+ last_execution_id: None,
+ reported_usage_request: None,
mcp_prompt: None,
mcp_detail: None,
agent_detail: None,
@@ -3528,7 +3629,12 @@ impl App {
/// every keystroke but leaves a cursor blinking in the composer promises a
/// field that is not there.
fn blocking_dock(&self) -> Option<&'static str> {
- if self.login.is_some() {
+ if self.account_login.is_some() {
+ // First in `handle_key` too, and it outranks `login`: this dock owns
+ // the OAuth code being typed or pasted, so a queued ask that
+ // consumed a keystroke here would swallow the secret.
+ Some("finish signing in above")
+ } else if self.login.is_some() {
Some("sign in in the dock above")
} else if self.browser_confirm.is_some() {
Some("answer the question above")
@@ -3536,6 +3642,11 @@ impl App {
Some("edit the setting above")
} else if self.mcp_prompt.is_some() || self.provider_prompt.is_some() {
Some("finish the wizard above")
+ } else if self.readout.is_some() {
+ // A readout takes the keyboard while it is docked -- `q`, `m` and
+ // Esc are its keys, so a keystroke meant for it must never land in
+ // the field as text the user then has to delete.
+ Some("Esc or q to close the readout above")
} else {
None
}
@@ -4619,6 +4730,18 @@ impl App {
if let Some(max) = self.max_tokens {
body["max_tokens"] = serde_json::json!(max);
}
+ // The money ceiling and the rates it is metered against. The loop is
+ // not `cli`-gated and cannot read the model catalog, so the prices
+ // resolved at startup are the only ones it sees.
+ if let Some(ceiling) = self.cost_ceiling {
+ body["max_budget_usd"] = serde_json::json!(ceiling.max_usd);
+ body["token_rates"] = serde_json::json!({
+ "prompt_usd": ceiling.rates.prompt_usd,
+ "completion_usd": ceiling.rates.completion_usd,
+ "cache_read_usd": ceiling.rates.cache_read_usd,
+ "cache_write_usd": ceiling.rates.cache_write_usd,
+ });
+ }
// Live plan-mode toggle: the backend reads this per turn and falls back
// to the session default when absent. Only forwarded in Plan so normal
// turns keep an unchanged body.
@@ -5573,7 +5696,18 @@ impl App {
name,
event,
} => self.apply_subagent_event(&run_id, &name, *event),
- StreamEvent::TurnUsage { usage } => {
+ StreamEvent::TurnUsage {
+ usage,
+ execution_id,
+ } => {
+ // The provider's handle for the request that just landed, kept
+ // so `/usage` can offer a lookup of what it actually cost
+ // instead of only the estimate. Only overwritten when one was
+ // reported: a path that cannot see the header (the default one)
+ // must not erase an id an earlier request did report.
+ if let Some(id) = execution_id {
+ self.last_execution_id = Some(id);
+ }
// Session totals are per model: `/usage` prices each at its own
// published rates, and the current model is the one billed.
let key = self.usage_key();
@@ -5699,10 +5833,18 @@ impl App {
// prefix (a child has its own). `--output-format json` is the
// surface that folds child usage in, because that figure is a bill
// rather than a rate.
- StreamEvent::TurnUsage { usage } => {
+ StreamEvent::TurnUsage {
+ usage,
+ execution_id,
+ } => {
if let Some(panel) = self.subagents.iter_mut().find(|p| p.run_id == run_id) {
panel.prompt_tokens = usage.prompt_tokens.unwrap_or(panel.prompt_tokens);
}
+ // A child's requests are billed to the same account, so its
+ // execution ids are as lookup-worthy as the parent's.
+ if let Some(id) = execution_id {
+ self.last_execution_id = Some(id);
+ }
// A child's tokens are spend on the same account, against the
// model the dispatch inherited, so they belong in the session
// total. `RunReport` already counts them; without this `/usage`
@@ -6350,13 +6492,36 @@ fn session_cost(
priced.then_some((total, unpriced))
}
-/// The `/usage` readout: one row per model this session billed against, then a
-/// total. Kept free of `App` so the arithmetic is testable on its own.
+/// How many models the session readout lists before folding the rest away.
+/// Enough to show where the money went, short enough that the dock stays a
+/// glance rather than a table; the rest are one keystroke away and are still
+/// counted in the total, so folding hides detail and never spend.
+const TOP_MODELS: usize = 3;
+
+/// One model's line in the session readout, kept as data until the whole set
+/// is known: the rows are ranked by cost and the label column is padded to the
+/// widest label actually shown, neither of which can be decided while walking
+/// the map.
+struct UsageRow {
+ label: String,
+ /// `None` is "the provider publishes no price", never zero.
+ cost: Option<f64>,
+ usage: super::model_catalog::TokenUsage,
+}
+
+/// The `/usage` readout: the session's own spend first, then the models that
+/// account for it, ranked by cost with the tail folded behind `m`.
+///
+/// Summary-before-detail rather than a flat list with the total at the bottom:
+/// the question this readout answers is "what has this session cost", and a
+/// list makes the reader add rows up to find out. Kept free of `App` so the
+/// arithmetic is testable on its own.
fn usage_lines(
usage: &std::collections::BTreeMap<UsageKey, super::model_catalog::TokenUsage>,
+ all_models: bool,
) -> Vec<Vec<Span<'static>>> {
let catalog = super::model_catalog::load();
- let mut rows = Vec::new();
+ let mut rows: Vec<UsageRow> = Vec::new();
let mut totals = super::model_catalog::TokenUsage::default();
let mut total_cost = 0.0;
let mut any_priced = false;
@@ -6371,41 +6536,98 @@ fn usage_lines(
None => any_unpriced = true,
}
totals.merge(model_usage);
- rows.push(vec![
- Span::styled(format!("{} ", key.label()), Style::new().cyan()),
- Span::raw(usage_counts(model_usage)),
+ rows.push(UsageRow {
+ label: key.label(),
+ cost,
+ usage: model_usage.clone(),
+ });
+ }
+ // Ranked by what each model cost, so a truncated list keeps the models
+ // that matter. Unpriced models sort last by token volume rather than being
+ // treated as free: they have no cost to rank by, but hiding the busiest of
+ // them would hide the one most likely to be expensive.
+ rows.sort_by(|a, b| {
+ let tokens = |r: &UsageRow| r.usage.prompt_tokens + r.usage.completion_tokens;
+ match (a.cost, b.cost) {
+ (Some(x), Some(y)) => y.partial_cmp(&x).unwrap_or(std::cmp::Ordering::Equal),
+ (Some(_), None) => std::cmp::Ordering::Less,
+ (None, Some(_)) => std::cmp::Ordering::Greater,
+ (None, None) => tokens(b).cmp(&tokens(a)),
+ }
+ .then_with(|| a.label.cmp(&b.label))
+ });
+
+ let indent = || Span::raw(" ");
+ let dim = Style::new().dark_gray();
+ let mut out: Vec<Vec<Span<'static>>> = Vec::new();
+
+ out.push(vec![Span::styled("this session", Style::new().bold())]);
+ let mut summary = vec![indent()];
+ if any_priced {
+ summary.push(Span::styled(
+ format!("~{} ", format_usd(total_cost)),
+ Style::new().yellow().bold(),
+ ));
+ }
+ summary.push(Span::raw(usage_counts(&totals)));
+ out.push(summary);
+ if any_unpriced && any_priced {
+ out.push(vec![
+ indent(),
+ Span::styled("excludes models with no published price", dim),
+ ]);
+ }
+
+ let shown = if all_models {
+ rows.len()
+ } else {
+ rows.len().min(TOP_MODELS)
+ };
+ let hidden = rows.len() - shown;
+ out.push(Vec::new());
+ out.push(vec![Span::styled(
+ if hidden > 0 { "top models" } else { "models" },
+ Style::new().bold(),
+ )]);
+ let width = rows[..shown]
+ .iter()
+ .map(|r| r.label.chars().count())
+ .max()
+ .unwrap_or(0);
+ for row in &rows[..shown] {
+ out.push(vec![
+ indent(),
+ Span::styled(
+ format!("{:<width$} ", row.label),
+ Style::new().cyan(),
+ ),
Span::styled(
- match cost {
- Some(c) => format!(" ~{}", format_usd(c)),
+ match row.cost {
+ Some(c) => format!("~{}", format_usd(c)),
// A model the provider publishes no prices for: say so,
// rather than let a total imply it cost nothing.
- None => " (no published price)".to_string(),
+ None => "(no published price)".to_string(),
},
Style::new().yellow(),
),
+ Span::raw(format!(" {}", usage_counts(&row.usage))),
]);
}
- if rows.len() > 1 || any_priced {
- rows.push(vec![
- Span::styled("total ", Style::new().bold()),
- Span::raw(usage_counts(&totals)),
+ if hidden > 0 {
+ out.push(vec![
+ indent(),
Span::styled(
- if any_priced {
- format!(" ~{}", format_usd(total_cost))
- } else {
- String::new()
- },
- Style::new().yellow().bold(),
+ format!(
+ "+{hidden} more model{} · m to show all",
+ if hidden == 1 { "" } else { "s" }
+ ),
+ dim,
),
]);
+ } else if rows.len() > TOP_MODELS {
+ out.push(vec![indent(), Span::styled("m to fold the tail", dim)]);
}
- if any_unpriced && any_priced {
- rows.push(vec![Span::styled(
- "the total excludes models with no published price",
- Style::new().dim(),
- )]);
- }
- rows
+ out
}
/// `N req · 12.3K in (8.1K cached) · 3.4K out`, the shape both the per-model
@@ -6503,7 +6725,7 @@ impl ContextReport {
/// is slightly below 2.05 but `k * 10.0` lands on exactly 20.5, so the branch
/// selected decimal output while the renderer produced the self-defeating
/// `2.0K`. Integer math removes that representation mismatch.
-fn format_tokens(tokens: u64) -> String {
+pub(super) fn format_tokens(tokens: u64) -> String {
if tokens < 1_000 {
return tokens.to_string();
}
@@ -6702,6 +6924,170 @@ fn cost_summary_line(report: &ContextReport) -> Option<String> {
/// Plain `/context` summary: current usage and autocompaction threshold first,
/// followed by seven equal-scale category bars.
+/// The session half of a usage readout: the estimate, its model breakdown,
+/// and the provenance line that says it is an estimate.
+///
+/// Shared by `Readout::Session` and the overview's first section so the two
+/// cannot describe the same numbers differently.
+fn session_estimate_lines(app: &App, all_models: bool) -> Vec<Line<'static>> {
+ let dim = Style::new().dark_gray();
+ if app.session_usage.is_empty() {
+ return vec![Line::styled("no usage yet this session".to_string(), dim)];
+ }
+ let mut lines: Vec<Line<'static>> = usage_lines(&app.session_usage, all_models)
+ .into_iter()
+ .map(Line::from)
+ .collect();
+ // The provenance line is not decoration: every figure above it is
+ // priced from a published rate sheet, and a user comparing it with
+ // an invoice has to know which one they are holding.
+ lines.push(Line::styled(
+ "estimated from the provider's published prices - not a bill".to_string(),
+ dim,
+ ));
+ // A capped session names its ceiling. The estimate above is the
+ // whole session's spend while the ceiling applies per run, so this
+ // states the limit rather than implying progress toward it -- the
+ // two numbers do not measure the same thing.
+ if let Some(ceiling) = app.cost_ceiling {
+ lines.push(Line::styled(
+ format!(
+ "each run stops at {} (--max-budget-usd)",
+ format_usd(ceiling.max_usd)
+ ),
+ dim,
+ ));
+ }
+ lines
+}
+
+/// Bare `/usage`: this session's estimate over the account's recorded spend.
+///
+/// Two sections, never one total. They measure different things -- a local
+/// guess at what this process has run up, and what the provider has actually
+/// recorded across every client on the account -- and adding them would
+/// double-count this very session while implying a precision neither has. The
+/// heading of each names its source, and the account half degrades to a
+/// reason rather than a blank when it cannot be read.
+fn overview_lines(
+ app: &App,
+ all_models: bool,
+ account: &AccountSlot,
+ width: usize,
+) -> Vec<Line<'static>> {
+ let dim = Style::new().dark_gray();
+ let mut lines = vec![Line::styled(
+ "THIS SESSION (estimated)".to_string(),
+ Style::new().bold(),
+ )];
+ lines.extend(session_estimate_lines(app, all_models));
+
+ lines.push(Line::raw(""));
+ lines.push(Line::styled(
+ "ON YOUR ACCOUNT (recorded by the provider)".to_string(),
+ Style::new().bold(),
+ ));
+ match account {
+ AccountSlot::NotConfigured => lines.push(Line::styled(
+ "no account usage API is configured for this provider".to_string(),
+ dim,
+ )),
+ AccountSlot::Loading => lines.push(Line::raw("reading account usage...")),
+ AccountSlot::Failed(message) => {
+ lines.extend(wrap_text(message, dim, width).into_iter().map(Line::from));
+ }
+ AccountSlot::Ready(payload) => {
+ // The account total only -- the per-model breakdown belongs to
+ // `/usage account`, which is one keystroke away and is where
+ // someone who wants it is already going. An overview that printed
+ // both breakdowns would be two screens of table under a heading
+ // promising a summary.
+ let query = super::tokamak::usage::Query::Summary;
+ let reported = super::usage_view::account_total_lines(payload);
+ match reported {
+ Some(rows) => lines.extend(
+ rows.iter()
+ .flat_map(|line| wrap_text(line, Style::new(), width))
+ .map(Line::from),
+ ),
+ // Unparseable: fall back to the same field walk every other
+ // reported view degrades to, rather than showing nothing.
+ None => lines.extend(
+ super::usage_view::reported_usage_lines(
+ &query,
+ payload,
+ super::usage_view::Fold::Folded,
+ )
+ .iter()
+ .flat_map(|line| wrap_text(line, Style::new(), width))
+ .map(Line::from),
+ ),
+ }
+ }
+ }
+
+ lines.push(Line::raw(""));
+ lines.push(Line::styled(
+ "/usage account · daily · requests · limits for the detail".to_string(),
+ dim,
+ ));
+ lines
+}
+
+/// The docked readout's body at `width`.
+///
+/// Takes `App` because the session estimate is rendered from live state rather
+/// than from a snapshot taken when the readout opened: a user who leaves it up
+/// during a turn is watching the run's spend, and a frozen total would be
+/// quietly wrong from the first token that arrived after it.
+fn readout_lines(app: &App, readout: &Readout, width: usize) -> Vec<Line<'static>> {
+ let dim = Style::new().dark_gray();
+ match readout {
+ Readout::ContextLoading => vec![Line::raw("computing context...")],
+ Readout::Context(report) => context_lines(report, width),
+ Readout::Session { all_models } => {
+ let mut lines = session_estimate_lines(app, *all_models);
+ lines.push(Line::styled(
+ match &app.last_execution_id {
+ // A concrete id beats naming the command: this is the one
+ // request whose real charge can be looked up right now.
+ Some(id) => format!("/usage {id} for what the provider recorded"),
+ None => "/usage account for what the provider actually recorded".to_string(),
+ },
+ dim,
+ ));
+ lines
+ }
+ Readout::Overview {
+ all_models,
+ account,
+ } => overview_lines(app, *all_models, account, width),
+ Readout::ReportedLoading(query) => {
+ vec![Line::raw(format!("reading {}...", query.label()))]
+ }
+ Readout::Reported {
+ query,
+ payload,
+ all_rows,
+ ..
+ } => super::usage_view::reported_usage_lines(
+ query,
+ payload,
+ super::usage_view::Fold::docked(*all_rows),
+ )
+ .iter()
+ // Hard-wrapped rather than clipped: a truncated money figure is a
+ // wrong money figure.
+ .flat_map(|line| wrap_text(line, Style::new(), width))
+ .map(Line::from)
+ .collect(),
+ Readout::ReportedError { message, .. } => wrap_text(message, Style::new(), width)
+ .into_iter()
+ .map(Line::from)
+ .collect(),
+ }
+}
+
fn context_lines(report: &ContextReport, width: usize) -> Vec<Line<'static>> {
let max = width.max(1);
let percents = report.percents();
@@ -8639,6 +9025,30 @@ async fn await_context(
joined.ok()
}
+/// Await an in-flight account-usage read, parking forever when none is running
+/// so this can sit in the loop's `select!` unconditionally.
+#[allow(clippy::type_complexity)]
+async fn await_reported_usage(
+ task: &mut Option<
+ tokio::task::JoinHandle<(
+ super::tokamak::usage::Query,
+ Result<super::tokamak::usage::Payload, super::tokamak::usage::UsageError>,
+ )>,
+ >,
+) -> Option<(
+ super::tokamak::usage::Query,
+ Result<super::tokamak::usage::Payload, super::tokamak::usage::UsageError>,
+)> {
+ let joined = match task.as_mut() {
+ Some(h) => h.await,
+ None => return pending().await,
+ };
+ *task = None;
+ // A panicked job leaves the overlay on its loading state for the user to
+ // close, same as `await_context`.
+ joined.ok()
+}
+
/// Await an in-flight `/login` verification, parking forever when none is
/// running so this can sit in the loop's `select!` unconditionally.
async fn await_login(
@@ -9302,6 +9712,11 @@ async fn chat_loop<B: Backend>(
// executing an MCP tool call holds it for up to the tool-call timeout), so
// it must never run on the render loop. One at a time.
let mut context_task: Option<tokio::task::JoinHandle<ContextReport>> = None;
+ type ReportedUsageResult = (
+ super::tokamak::usage::Query,
+ Result<super::tokamak::usage::Payload, super::tokamak::usage::UsageError>,
+ );
+ let mut reported_usage_task: Option<tokio::task::JoinHandle<ReportedUsageResult>> = None;
// The update check is a network round trip, so it runs off the render loop
// and notes itself whenever it lands rather than delaying the first frame.
let mut update_task = Some(tokio::spawn(super::updater::available_update()));
@@ -9449,6 +9864,17 @@ async fn chat_loop<B: Backend>(
let snapshot = app.context_snapshot();
context_task = Some(tokio::spawn(compute_context_report(snapshot)));
}
+ // `/usage <view>` asked for an account read. It is a network call, so
+ // it runs off the render loop exactly like `/context`'s report: one at
+ // a time, with the overlay sitting on its loading state until it lands.
+ if reported_usage_task.is_none() {
+ if let Some(query) = app.reported_usage_request.take() {
+ reported_usage_task = Some(tokio::spawn(async move {
+ let result = super::tokamak::usage::fetch(&query).await;
+ (query, result)
+ }));
+ }
+ }
// A key was submitted at the `/login` prompt: verify it off-loop. One at
// a time - the prompt is read-only while `verifying`.
if login_task.is_none() {
@@ -9682,6 +10108,9 @@ async fn chat_loop<B: Backend>(
// landing after the overlay was closed must not reopen it.
finish_context_report(app, report);
}
+ Some((query, result)) = await_reported_usage(&mut reported_usage_task) => {
+ finish_reported_usage(app, &query, result);
+ }
login_res = await_login(&mut login_task) => {
let login_ok = login_res.is_ok();
finish_login(app, login_res);
@@ -10586,13 +11015,23 @@ async fn handle_key(
// without cancelling the running turn. Nothing else reaches the input box
// or the transcript shortcuts (e.g. a bare `q` must not quit) while it is
// up.
- if app.context_view.is_some() {
+ if app.readout.is_some() {
match key.code {
+ // `m` folds a readout's list open and shut -- the session's
+ // models, or an account view's breakdown. Readouts with no tail
+ // fall through to the catch-all and do nothing rather than
+ // closing the dock.
+ KeyCode::Char('m') if !ctrl => match &mut app.readout {
+ Some(Readout::Session { all_models })
+ | Some(Readout::Overview { all_models, .. }) => *all_models = !*all_models,
+ Some(Readout::Reported { all_rows, .. }) => *all_rows = !*all_rows,
+ _ => {}
+ },
KeyCode::Esc | KeyCode::Char('q') if !ctrl => {
- app.context_view = None;
+ app.readout = None;
}
_ if ctrl_c => {
- app.context_view = None;
+ app.readout = None;
}
_ => {}
}
@@ -11584,8 +12023,8 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
},
SlashCommand {
name: "/usage",
- hint: "",
- description: "Show this session's tokens and estimated cost, per model",
+ hint: "[session|run|account|daily|requests|limits|<execution-id>]",
+ description: "This session's estimated cost and your account's recorded spend",
alias_of: None,
},
SlashCommand {
@@ -11894,7 +12333,7 @@ async fn run_command(
}
"compact" => compact_command(app),
"context" => context_command(app),
- "usage" => usage_command(app),
+ "usage" => usage_command(app, arg),
"threads" | "list" => match super::list_threads_in(&app.agent_dir) {
Ok(threads) if threads.is_empty() => {
app.note("no saved threads found");
@@ -11987,35 +12426,167 @@ async fn run_command(
/// The report is *not* computed here. Sizing the tool segment takes the MCP
/// server lock, which a turn executing an MCP tool call holds for up to the
/// tool-call timeout; computing it inline on the key-handling path would
-/// freeze the whole UI. So this only sets the overlay to its loading state and
-/// raises a flag the loop picks up, which computes the report on its own task
-/// and fills the overlay in when it lands. Unlike the old idle-only transcript
-/// row, the readout is a popup the user closes with Esc, so it stays available
+/// freeze the whole UI. So this only opens the readout on its loading state
+/// and raises a flag the loop picks up, which computes the report on its own
+/// task and fills it in when it lands. Unlike the old idle-only transcript
+/// row, the readout is a dock the user closes with Esc, so it stays available
/// mid-turn without ever blocking the render loop.
fn context_command(app: &mut App) {
- app.context_view = Some(ContextView::Loading);
+ app.readout = Some(Readout::ContextLoading);
app.context_request = true;
}
-/// `/usage`: what this session has actually spent, per model. Unlike
+/// `/usage`: what this session has spent, per model, in the same dock
+/// `/context` uses -- these are one kind of surface (a question about the run,
+/// answered in place and dismissed), so they must not look like two.
+///
+/// Unlike
/// `/context` -- which describes the *current* window, a single request's worth
/// -- these are sums across every request, because that is what a provider
/// bills. Prices come from the provider's own `/models` listing (cached by
/// [`super::model_catalog`]), so a model it publishes no price for is reported
/// as such rather than counted as free. Local to the transcript: nothing is
/// sent upstream, and no account-level spend is available to ask for.
-fn usage_command(app: &mut App) {
- if app.session_usage.is_empty() {
- app.note("no usage yet this session");
- return;
+fn usage_command(app: &mut App, arg: &str) {
+ match parse_usage_mode(arg) {
+ // A glance-and-dismiss answer, not part of the conversation: it opens
+ // the same dock every other readout uses and writes nothing to the
+ // transcript. An empty session still opens it -- "nothing yet" is the
+ // answer to the question that was asked, and answering it somewhere
+ // else would make the command's surface depend on its result.
+ UsageMode::Session => app.readout = Some(Readout::Session { all_models: false }),
+ // Bare `/usage` is "how much am I spending", which has two honest
+ // answers: this session's estimate and the account's recorded total.
+ // The session half draws immediately from local state, so the pane is
+ // never empty while the network read is in flight -- and when there is
+ // no account API to read, the overview is still the estimate plus a
+ // line saying so, rather than an error.
+ UsageMode::Overview => {
+ let configured = super::tokamak::auth_status().signed_in;
+ app.readout = Some(Readout::Overview {
+ all_models: false,
+ account: if configured {
+ AccountSlot::Loading
+ } else {
+ AccountSlot::NotConfigured
+ },
+ });
+ if configured {
+ app.reported_usage_request = Some(super::tokamak::usage::Query::Summary);
+ }
+ }
+ UsageMode::Run => {
+ // Every request this session made carries the session's correlation
+ // id, so one lookup returns the whole run's executions -- which is
+ // the authoritative answer to the question bare `/usage` estimates.
+ let correlation = app
+ .args
+ .as_ref()
+ .and_then(|args| args.session_id.as_deref())
+ .and_then(|id| {
+ crate::core::agent::correlation::session_request_id(Some(id))
+ });
+ match correlation {
+ Some(id) => usage_command(app, &format!("correlate {id}")),
+ None => {
+ app.note("this run has no session id to correlate");
+ app.system_detail_text(
+ "executions are found by the id sent with each request; without a session there is none",
+ );
+ }
+ }
+ }
+ UsageMode::Account(query) => {
+ // An account read needs a Tokamak key. Saying so here, before any
+ // request, keeps a user on another provider from watching a
+ // spinner resolve into an auth error.
+ if !super::tokamak::auth_status().signed_in {
+ app.note("no account usage API is configured for this provider");
+ app.system_detail_text(
+ "account spend is read from Tokamak; `/usage` alone still estimates this session",
+ );
+ return;
+ }
+ app.readout = Some(Readout::ReportedLoading(query.clone()));
+ app.reported_usage_request = Some(query);
+ }
+ UsageMode::Unknown(arg) => {
+ app.note(&format!("unknown usage view: {arg}"));
+ app.system_detail_text(USAGE_MODE_HELP);
+ }
}
- app.note("session usage");
- for row in usage_lines(&app.session_usage) {
- app.system_detail(row);
+}
+
+/// What `/usage` was asked for.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum UsageMode {
+ /// The default: this session's estimate and the account's recorded spend,
+ /// side by side.
+ Overview,
+ /// This session's local estimate alone -- the only view that works
+ /// offline, mid-turn, and for a non-Tokamak provider.
+ Session,
+ /// An authoritative read from the provider's usage API.
+ Account(super::tokamak::usage::Query),
+ /// Every execution this run produced, found by its correlation id.
+ /// Resolved into an [`UsageMode::Account`] lookup once the session id is
+ /// known, which only the caller has.
+ Run,
+ Unknown(String),
+}
+
+const USAGE_MODE_HELP: &str =
+ "/usage (overview) · session · run · account · daily · requests · limits · <execution-id>";
+
+/// Parse the argument to `/usage`.
+///
+/// A bare `/usage` stays the session estimate it has always been -- the one
+/// answer available instantly and without a network -- so this only ever adds
+/// views. An argument that is not a known mode is treated as an execution id
+/// rather than rejected: that is the shape of the thing a user pastes, and an
+/// id that turns out not to exist reports a clean not-found.
+fn parse_usage_mode(arg: &str) -> UsageMode {
+ use super::tokamak::usage::Query;
+ let arg = arg.trim();
+ match arg {
+ "" => UsageMode::Overview,
+ "session" => UsageMode::Session,
+ "run" => UsageMode::Run,
+ "account" | "me" => UsageMode::Account(Query::Summary),
+ "daily" => UsageMode::Account(Query::Daily),
+ "requests" => UsageMode::Account(Query::Requests),
+ "limits" => UsageMode::Account(Query::Limits),
+ other => {
+ // `correlate <id>` is how `/usage run` re-enters this parser once it
+ // has resolved the session's correlation id, and is usable directly
+ // for an id from another run. Matched before the lone-word case
+ // below, or a bare `correlate` would be looked up as an execution
+ // id of that name.
+ if let Some(id) = other
+ .strip_prefix("correlate")
+ .map(str::trim)
+ .filter(|_| other == "correlate" || other.starts_with("correlate "))
+ {
+ return if id.is_empty() {
+ UsageMode::Unknown(other.to_string())
+ } else {
+ UsageMode::Account(Query::Correlated(id.to_string()))
+ };
+ }
+ // Anything else is taken as an execution id, but only when it is
+ // plausibly one: a word with no whitespace. A phrase is a typo, and
+ // sending it upstream to be told it does not exist would be a worse
+ // answer than naming the available views.
+ if other.split_whitespace().count() == 1 {
+ UsageMode::Account(Query::Generation(other.to_string()))
+ } else {
+ UsageMode::Unknown(other.to_string())
+ }
+ }
}
- app.system_detail_text("estimated from the provider's published prices - not a bill");
}
+
/// The `/init` prompt. Onboarding a project means producing the three things a
/// later session reads back: the root `JAN.md` (ingested as project context),
/// skills for repeatable workflows, and memory for durable facts. Phrased as a
@@ -14870,8 +15441,10 @@ fn finish_tokamak_login(app: &mut App, result: Result<super::tokamak::Login, Str
models,
config_path,
default_model,
+ replaced_default,
account,
} = login;
+ let repointed = replaced_default.then(|| default_model.clone()).flatten();
finish_login(
app,
Ok(crate::core::cli::auth::LoginResult {
@@ -14884,6 +15457,14 @@ fn finish_tokamak_login(app: &mut App, result: Result<super::tokamak::Login, Str
if let Some(account) = account {
app.note(&format!("signed in to Tokamak as {account}"));
}
+ // Said out loud rather than applied quietly: the user picked the
+ // old default at some point, and a model silently swapped under
+ // them is worse than the 404 the swap avoids.
+ if let Some(model) = repointed {
+ app.note(&format!(
+ "your default model is no longer offered - switched to {model}"
+ ));
+ }
if let Some(warning) = super::tokamak::expiry_warning() {
app.note(&warning);
}
@@ -14990,7 +15571,9 @@ fn adopt_login_model(app: &mut App, login: &crate::core::cli::auth::LoginResult)
if runnable.iter().any(|(_, model)| *model == app.model) {
return;
}
- if let Some(model) = login.models.first() {
+ // The default the sign-in just settled on, when it wrote one: it is the
+ // provider's own first-listed model, where `models` is merely sorted.
+ if let Some(model) = login.default_model.as_ref().or_else(|| login.models.first()) {
app.model = model.clone();
let _ = super::cli_set_project_model(&app.agent_dir, &app.model);
}
@@ -15223,9 +15806,57 @@ async fn finish_mcp_job(
/// not reopen a popup they walked away from (mirrors how `finish_mcp_job`
/// drops a listing whose screen has been left).
fn finish_context_report(app: &mut App, report: ContextReport) {
- if app.context_view.is_some() {
- app.context_view = Some(ContextView::Ready(Box::new(report)));
+ // Only while `/context` is still the readout on screen. Checking the
+ // variant rather than merely "something is open" matters now that one
+ // field holds them all: a user who ran `/context` and then `/usage` before
+ // the report landed must not have the usage view yanked out from under
+ // them by the earlier request finishing.
+ if matches!(app.readout, Some(Readout::ContextLoading)) {
+ app.readout = Some(Readout::Context(Box::new(report)));
+ }
+}
+
+/// Fold a finished account-usage read into its overlay. Like
+/// [`finish_context_report`], a result landing after the user closed the
+/// overlay is dropped rather than reopening it.
+///
+/// A failure fills the overlay rather than being swallowed: the user asked a
+/// question about money and "the request did not land" is a real answer, where
+/// an empty popup would read as "nothing was spent".
+fn finish_reported_usage(
+ app: &mut App,
+ query: &super::tokamak::usage::Query,
+ result: Result<super::tokamak::usage::Payload, super::tokamak::usage::UsageError>,
+) {
+ // The overview holds the account read in a slot beside the session
+ // estimate, so a landing result fills that slot rather than replacing the
+ // readout -- replacing it would throw away the half already on screen.
+ if let Some(Readout::Overview { account, .. }) = &mut app.readout {
+ if matches!(account, AccountSlot::Loading) {
+ *account = match result {
+ Ok(payload) => AccountSlot::Ready(Box::new(payload)),
+ Err(e) => AccountSlot::Failed(e.to_string()),
+ };
+ }
+ return;
+ }
+ // Same rule as `finish_context_report`, and for the same reason: a result
+ // only fills the readout that is still waiting for it.
+ if !matches!(app.readout, Some(Readout::ReportedLoading(_))) {
+ return;
}
+ app.readout = Some(match result {
+ Ok(payload) => Readout::Reported {
+ title: query.label().to_string(),
+ query: query.clone(),
+ payload: Box::new(payload),
+ all_rows: false,
+ },
+ Err(e) => Readout::ReportedError {
+ title: query.label().to_string(),
+ message: e.to_string(),
+ },
+ });
}
/// Open the add/edit wizard prefilled from a configured server.
@@ -16774,46 +17405,41 @@ fn draw(f: &mut Frame, app: &mut App) {
}
f.render_widget(input_box(app).scroll((input_scroll, 0)), chunks[2]);
f.render_widget(dock_line(app, chunks[3].width), chunks[3]);
- // The `/context` overlay renders on top of (never instead of) the finished
+ // A readout (`/context`, `/usage`) docks above the input box, where every
+ // other prompt in this TUI lives -- `/login`, `/settings`, `/mcp`, the
+ // provider wizard. It renders on top of (never instead of) the finished
// frame, so the spinner and streamed output keep animating behind it
- // mid-turn. A centered bordered popup over the body, titled like the
- // pickers, with the readout re-laid out by the same `context_lines` the
- // old transcript row used - the numbers and layout are unchanged, only the
- // surface (a popup the user closes with Esc) differs. The rect is clamped
- // to the frame and never indexes a zero-width/zero-height area, so it
- // stays correct at tiny terminal sizes.
- if let Some(view) = &app.context_view {
- let body = chunks[1];
- // The rect is sized before the content, because the readout's height
- // depends on the width it is laid out at. Borders cost two columns and
- // two rows, so the content width is the popup's inner width -- laying
- // out at the popup's *outer* width would push the rail's right edge
- // under the border and silently clip it.
- let outer_w = body.width.saturating_sub(2).max(1);
- let content_w = outer_w.saturating_sub(2).max(1);
- let lines: Vec<Line<'static>> = match view {
- ContextView::Loading => vec![Line::raw("computing context...")],
- ContextView::Ready(report) => context_lines(report, content_w as usize),
- };
- // Two rows for the borders. A frame too short to hold the whole readout
- // gets as much of it as fits rather than nothing.
- let height = (lines.len() as u16 + 2).min(body.height);
+ // mid-turn.
+ //
+ // Docked rather than centered because a readout is something you consult
+ // while looking at the conversation, and the bottom is where the eye
+ // already is; a mid-screen box also covers the transcript the numbers are
+ // about. The rect is clamped to the frame and never indexes a
+ // zero-width/zero-height area, so it stays correct at tiny terminal sizes.
+ if let Some(readout) = &app.readout {
+ // Sized before the content, because the readout's height depends on
+ // the width it is laid out at. Borders cost two columns and two rows,
+ // so content is laid out at the *inner* width -- using the outer width
+ // would push the context rail's right edge under the border and
+ // silently clip it.
+ let content_w = chunks[2].width.saturating_sub(2).max(1);
+ let lines = readout_lines(app, readout, content_w as usize);
+ let height = (lines.len() as u16 + 2).min(chunks[1].height);
+ let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);
let rect = ratatui::layout::Rect {
- x: body.x + body.width.saturating_sub(outer_w) / 2,
- y: body.y + body.height.saturating_sub(height) / 2,
- width: outer_w,
+ x: chunks[2].x,
+ y,
+ width: chunks[2].width,
height,
};
let block = Block::default()
.borders(Borders::ALL)
.border_style(Style::new().cyan())
.title(Span::styled(
- " context ",
+ format!(" {} ", readout.title()),
Style::new().on_cyan().black().bold(),
));
let inner = block.inner(rect);
- // A frame with no room for the popup draws nothing -- and must still
- // fall through to the prompts below, so this never returns from `draw`.
if rect.width > 0 && rect.height > 0 {
f.render_widget(ratatui::widgets::Clear, rect);
f.render_widget(block, rect);
@@ -19223,7 +19849,7 @@ mod tests {
thinking_open, tilde_path, tokens_per_second, tool_activity, tool_finished,
transcript_top_padding, unescape_partial_json_string, user_content_parts, wave_sweep_line,
with_wave_glyph, without_think_tags, worktree_command, App, CompactKind, ContextReport,
- ContextSegment, ContextView, CurrentRun, McpField, McpPrompt, MonitorSet, Pending,
+ ContextSegment, CurrentRun, Readout, McpField, McpPrompt, MonitorSet, Pending,
PendingImage, PickerKind, ProviderField, ReasoningSeg, ResumeRequest, ResumeTarget, Row,
RowKind, Selection, SelectionMode, SnapshotJob, Status, Worktree, AGENT_SETTINGS,
ALT_SCROLL_RESTORE, ALT_SCROLL_SAVE_OFF, COPY_NOTICE, DIFF_ADD_BG, DIFF_DEL_BG,
@@ -19320,6 +19946,7 @@ mod tests {
max_tokens: None,
max_session_tokens: 128_000,
max_turns: None,
+ cost_ceiling: None,
};
let app = App::new(
"m".into(),
@@ -19824,6 +20451,7 @@ mod tests {
max_tokens: None,
max_session_tokens: 128_000,
max_turns: None,
+ cost_ceiling: None,
},
false,
agent_dir,
@@ -24216,7 +24844,22 @@ mod tests {
/// the next dock added cannot quietly regress only the rendering half.
#[test]
fn every_blocking_dock_marks_the_input_row_inactive() {
- let setups: [DockSetup; 6] = [
+ let setups: [DockSetup; 8] = [
+ // The account OAuth dock takes every keystroke and outranks the
+ // API-key one, so it has to block the field as hard as the rest.
+ ("account_login", |app| {
+ app.account_login = Some(super::AccountLoginPrompt::new(
+ crate::core::cli::auth::account::begin(
+ crate::core::cli::auth::account::AccountProvider::Claude,
+ )
+ .expect("an account login session builds offline"),
+ ))
+ }),
+ // A readout is docked like any other prompt and owns the same
+ // keys, so the field must go inactive for it too.
+ ("readout", |app| {
+ app.readout = Some(super::Readout::Session { all_models: false })
+ }),
("login/connecting", |app| {
app.login = Some(super::LoginPrompt::connecting())
}),
@@ -24351,6 +24994,7 @@ mod tests {
models: vec!["tokamak-1-preview".into()],
config_path: std::path::PathBuf::from("/tmp/config.toml"),
default_model: None,
+ replaced_default: false,
account: Some("[email protected]".into()),
}),
));
@@ -28442,6 +29086,7 @@ mod tests {
None,
&json!({"model": "m", "messages": [{"role": "user", "content": "go"}]}),
&tx,
+ None,
),
)
.await
@@ -29220,6 +29865,7 @@ mod tests {
cached_tokens: Some(900),
..Default::default()
},
+ execution_id: None,
});
assert_eq!(app.session_cached_tokens, 900);
@@ -30701,6 +31347,7 @@ mod tests {
total_tokens: Some(12_900),
..Default::default()
},
+ execution_id: None,
},
);
subagent_event(
@@ -31429,6 +32076,7 @@ mod tests {
total_tokens: Some(40_500),
..Default::default()
},
+ execution_id: None,
});
}
assert_eq!(app.turn_output_tokens, 1_500);
@@ -31684,7 +32332,7 @@ mod tests {
),
]);
- let text: Vec<String> = super::usage_lines(&usage)
+ let text: Vec<String> = super::usage_lines(&usage, false)
.iter()
.map(|row| row.iter().map(|s| s.content.to_string()).collect())
.collect();
@@ -31696,9 +32344,14 @@ mod tests {
"an unpriced model must say so: {joined}"
);
assert!(
- joined.contains("the total excludes models with no published price"),
+ joined.contains("excludes models with no published price"),
"{joined}"
);
+ // Summary before detail: the session's own total is readable
+ // without adding the model rows up.
+ let session = joined.find("this session").expect("a summary section");
+ let models = joined.find("models\n").expect("a models section");
+ assert!(session < models, "the summary leads: {joined}");
// 60K fresh prompt + 40K cached + 10K completion, at the seeded rates.
let expected = 60_000.0 * 0.000005 + 40_000.0 * 0.0000005 + 10_000.0 * 0.000025;
@@ -31709,6 +32362,82 @@ mod tests {
});
}
+ /// A long model list folds to the costliest few, and the fold states how
+ /// many it hid. Folding may hide *detail* only: the summary above it is
+ /// the whole session either way, so no spend disappears with the rows.
+ #[test]
+ fn the_model_list_folds_to_the_costliest_and_says_what_it_hid() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let mut usage = std::collections::BTreeMap::new();
+ for (i, name) in ["alpha", "bravo", "charlie", "delta", "echo"]
+ .iter()
+ .enumerate()
+ {
+ seed_priced_model("tokamak", name);
+ // Ascending spend, so the map's alphabetical order is not the
+ // ranked order and a naive truncation would keep the wrong
+ // three.
+ usage.insert(
+ usage_key("tokamak", name),
+ usage_of(1, 1_000 * (i as u64 + 1), 100, 0),
+ );
+ }
+ let render = |all| {
+ super::usage_lines(&usage, all)
+ .iter()
+ .map(|row| row.iter().map(|s| s.content.to_string()).collect())
+ .collect::<Vec<String>>()
+ .join("\n")
+ };
+
+ let folded = render(false);
+ assert!(folded.contains("top models"), "{folded}");
+ assert!(folded.contains("+2 more models"), "{folded}");
+ for kept in ["echo", "delta", "charlie"] {
+ assert!(folded.contains(kept), "the costliest stay: {folded}");
+ }
+ for hidden in ["alpha", "bravo"] {
+ assert!(!folded.contains(hidden), "the cheapest fold: {folded}");
+ }
+
+ let expanded = render(true);
+ for name in ["alpha", "bravo", "charlie", "delta", "echo"] {
+ assert!(expanded.contains(name), "{expanded}");
+ }
+ assert!(!expanded.contains("more model"), "{expanded}");
+
+ // The figure that matters is identical either way.
+ let total = super::format_usd(super::session_cost(&usage).expect("priced").0);
+ assert!(folded.contains(&total), "{folded}");
+ assert!(expanded.contains(&total), "{expanded}");
+ });
+ }
+
+ /// `m` toggles the fold, and only on the session readout -- on any other
+ /// readout it must not be mistaken for a close.
+ #[tokio::test]
+ async fn m_toggles_the_model_fold_without_closing_the_readout() {
+ let mut app = test_app();
+ app.readout = Some(Readout::Session { all_models: false });
+ press(&mut app, KeyCode::Char('m'), KeyModifiers::NONE).await;
+ assert!(
+ matches!(app.readout, Some(Readout::Session { all_models: true })),
+ "m expands"
+ );
+ press(&mut app, KeyCode::Char('m'), KeyModifiers::NONE).await;
+ assert!(
+ matches!(app.readout, Some(Readout::Session { all_models: false })),
+ "m folds back"
+ );
+
+ app.readout = Some(Readout::ContextLoading);
+ press(&mut app, KeyCode::Char('m'), KeyModifiers::NONE).await;
+ assert!(
+ matches!(app.readout, Some(Readout::ContextLoading)),
+ "m is inert where there is no tail to fold"
+ );
+ }
+
/// With nothing priced there is no cost line at all, rather than a `$0.00`
/// that would read as a free session.
#[test]
@@ -31797,9 +32526,11 @@ mod tests {
};
app.apply(StreamEvent::TurnUsage {
usage: usage(100, 20),
+ execution_id: None,
});
app.apply(StreamEvent::TurnUsage {
usage: usage(300, 40),
+ execution_id: None,
});
let recorded = app
@@ -31836,13 +32567,19 @@ mod tests {
cached_tokens: None,
cache_write_tokens: None,
};
- app.apply(StreamEvent::TurnUsage { usage: usage(100) });
+ app.apply(StreamEvent::TurnUsage {
+ usage: usage(100),
+ execution_id: None,
+ });
start_subagent(&mut app, "r0", "alpha");
subagent_event(
&mut app,
"r0",
"alpha",
- StreamEvent::TurnUsage { usage: usage(400) },
+ StreamEvent::TurnUsage {
+ usage: usage(400),
+ execution_id: None,
+ },
);
let recorded = app.session_usage.values().next().expect("usage recorded");
@@ -31854,12 +32591,444 @@ mod tests {
}
/// `/usage` with nothing to report says so rather than printing an empty
- /// table.
+ /// table -- and says it in the readout, not the transcript. Answering an
+ /// empty session somewhere else would make the command's surface depend on
+ /// its result, so a user could not learn where to look.
#[test]
fn usage_command_with_no_requests_notes_it() {
let mut app = test_app();
- super::usage_command(&mut app);
- assert!(transcript_text(&app).contains("no usage yet this session"));
+ super::usage_command(&mut app, "session");
+ assert!(
+ matches!(app.readout, Some(Readout::Session { .. })),
+ "an empty session still opens the readout"
+ );
+ assert!(
+ readout_text(&app).contains("no usage yet this session"),
+ "{}",
+ readout_text(&app)
+ );
+ assert!(
+ transcript_text(&app).is_empty(),
+ "a readout is never committed to the conversation: {}",
+ transcript_text(&app)
+ );
+ }
+
+ /// The docked readout's rendered text, which is what the user actually
+ /// reads -- assertions go through the same `readout_lines` the frame draws
+ /// so a test cannot pass on state the renderer would never show.
+ fn readout_text(app: &App) -> String {
+ let Some(readout) = &app.readout else {
+ return String::new();
+ };
+ super::readout_lines(app, readout, 80)
+ .iter()
+ .map(|line| {
+ line.spans
+ .iter()
+ .map(|s| s.content.as_ref())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ }
+
+ /// Bare `/usage` is the overview -- "how much am I spending" has two
+ /// honest answers and the default shows both. `session` still names the
+ /// estimate alone, which is the only view that works offline, mid-turn
+ /// and for a provider with no usage API.
+ #[test]
+ fn bare_usage_is_the_overview_and_session_is_still_reachable() {
+ assert_eq!(super::parse_usage_mode(""), super::UsageMode::Overview);
+ assert_eq!(super::parse_usage_mode(" "), super::UsageMode::Overview);
+ assert_eq!(super::parse_usage_mode("session"), super::UsageMode::Session);
+ }
+
+ /// The overview renders the session estimate immediately, without waiting
+ /// on the network: the half that can be answered locally must never be
+ /// held hostage by the half that cannot.
+ #[test]
+ fn the_overview_shows_the_session_estimate_before_the_account_lands() {
+ let mut app = test_app();
+ app.set_model("anthropic/claude-opus-5".to_string());
+ app.apply(StreamEvent::TurnUsage {
+ usage: crate::core::agent::events::Usage {
+ prompt_tokens: Some(100_000),
+ completion_tokens: Some(10_000),
+ total_tokens: None,
+ cached_tokens: None,
+ cache_write_tokens: None,
+ },
+ execution_id: None,
+ });
+ app.readout = Some(Readout::Overview {
+ all_models: false,
+ account: super::AccountSlot::Loading,
+ });
+ let text = readout_text(&app);
+ assert!(text.contains("THIS SESSION (estimated)"), "{text}");
+ assert!(text.contains("this session"), "{text}");
+ assert!(text.contains("ON YOUR ACCOUNT"), "{text}");
+ assert!(text.contains("reading account usage..."), "{text}");
+ // The estimate is on screen while the account read is still in flight.
+ assert!(text.contains("not a bill"), "{text}");
+ }
+
+ /// The two figures are labelled by source and never combined. An overview
+ /// that added them would double-count this session inside the account
+ /// total it is sitting next to.
+ #[test]
+ fn the_overview_keeps_the_estimate_and_the_charge_apart() {
+ use crate::core::cli::tokamak::usage::parse_payload_for_test;
+ let mut app = test_app();
+ app.set_model("anthropic/claude-opus-5".to_string());
+ app.apply(StreamEvent::TurnUsage {
+ usage: crate::core::agent::events::Usage {
+ prompt_tokens: Some(100_000),
+ completion_tokens: Some(10_000),
+ total_tokens: None,
+ cached_tokens: None,
+ cache_write_tokens: None,
+ },
+ execution_id: None,
+ });
+ app.readout = Some(Readout::Overview {
+ all_models: false,
+ account: super::AccountSlot::Ready(Box::new(parse_payload_for_test(ACCOUNT_BODY))),
+ });
+ let text = readout_text(&app);
+
+ // Each half names its source in its own heading.
+ let session_at = text.find("THIS SESSION (estimated)").expect("session heading");
+ let account_at = text
+ .find("ON YOUR ACCOUNT (recorded by the provider)")
+ .expect("account heading");
+ assert!(session_at < account_at, "local first, recorded second: {text}");
+
+ // The account's exact recorded figure, unrounded.
+ assert!(text.contains("$1240.10224445"), "{text}");
+ // The session half is marked as an estimate in its heading and again
+ // in its own provenance line, so neither figure can be mistaken for
+ // the other kind.
+ assert!(text.contains("(estimated)"), "{text}");
+ assert!(text.contains("not a bill"), "{text}");
+ // No combined figure anywhere.
+ assert!(!text.contains("total spend"), "{text}");
+ assert!(text.contains("/usage account"), "points at the detail: {text}");
+ }
+
+ /// A provider with no usage API still gets an overview: the estimate, and
+ /// a line saying why there is no account half. Not an error -- most
+ /// providers have no such API and the estimate is the whole answer.
+ #[test]
+ fn the_overview_without_an_account_api_is_still_the_estimate() {
+ let mut app = test_app();
+ app.readout = Some(Readout::Overview {
+ all_models: false,
+ account: super::AccountSlot::NotConfigured,
+ });
+ let text = readout_text(&app);
+ assert!(text.contains("THIS SESSION"), "{text}");
+ assert!(
+ text.contains("no account usage API is configured"),
+ "{text}"
+ );
+ }
+
+ /// A failed account read says why, in place. A blank account section would
+ /// read as "you have spent nothing", which is the one thing it must not
+ /// say -- and it must not take the session half down with it.
+ #[test]
+ fn a_failed_account_read_does_not_blank_the_overview() {
+ use crate::core::cli::tokamak::usage::{Query, UsageError};
+ let mut app = test_app();
+ app.readout = Some(Readout::Overview {
+ all_models: false,
+ account: super::AccountSlot::Loading,
+ });
+ super::finish_reported_usage(
+ &mut app,
+ &Query::Summary,
+ Err(UsageError::Failed("could not reach the server".to_string())),
+ );
+ assert!(
+ matches!(
+ app.readout,
+ Some(Readout::Overview {
+ account: super::AccountSlot::Failed(_),
+ ..
+ })
+ ),
+ "the slot holds the failure, the readout survives"
+ );
+ let text = readout_text(&app);
+ assert!(text.contains("could not reach the server"), "{text}");
+ assert!(text.contains("THIS SESSION"), "the estimate survives: {text}");
+ }
+
+ /// An account result fills the overview's slot rather than replacing the
+ /// whole readout, which would discard the session half already drawn.
+ #[test]
+ fn an_account_result_fills_the_overview_slot() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ let mut app = test_app();
+ app.readout = Some(Readout::Overview {
+ all_models: false,
+ account: super::AccountSlot::Loading,
+ });
+ super::finish_reported_usage(
+ &mut app,
+ &Query::Summary,
+ Ok(parse_payload_for_test(ACCOUNT_BODY)),
+ );
+ match &app.readout {
+ Some(Readout::Overview { account, .. }) => {
+ assert!(matches!(account, super::AccountSlot::Ready(_)));
+ }
+ _ => panic!("the overview should have survived the result landing"),
+ }
+ let text = readout_text(&app);
+ assert!(text.contains("$1240.10224445"), "{text}");
+ assert!(text.contains("15049 req"), "{text}");
+ // The overview shows the total, not the whole per-model table --
+ // that belongs to `/usage account`.
+ assert!(!text.contains("top models"), "{text}");
+ }
+
+ #[test]
+ fn usage_modes_map_to_their_documented_endpoints() {
+ use crate::core::cli::tokamak::usage::Query;
+ let account = |arg: &str| match super::parse_usage_mode(arg) {
+ super::UsageMode::Account(q) => q,
+ other => panic!("{arg} should be an account view, got {other:?}"),
+ };
+ assert_eq!(account("account"), Query::Summary);
+ assert_eq!(account("daily"), Query::Daily);
+ assert_eq!(account("requests"), Query::Requests);
+ assert_eq!(account("limits"), Query::Limits);
+ }
+
+ /// `/usage run` asks the one question the session estimate approximates:
+ /// what this run actually cost. It resolves to a correlation lookup, which
+ /// is the only mechanism that works on the default upstream path.
+ #[test]
+ fn the_run_view_resolves_to_a_correlation_lookup() {
+ use crate::core::cli::tokamak::usage::Query;
+ assert_eq!(super::parse_usage_mode("run"), super::UsageMode::Run);
+ assert_eq!(
+ super::parse_usage_mode("correlate jan-session-7"),
+ super::UsageMode::Account(Query::Correlated("jan-session-7".to_string()))
+ );
+ // A correlation with no id would search for everything, and must not
+ // fall through to being looked up as an execution named "correlate".
+ assert!(matches!(
+ super::parse_usage_mode("correlate "),
+ super::UsageMode::Unknown(_)
+ ));
+ assert!(matches!(
+ super::parse_usage_mode("correlate"),
+ super::UsageMode::Unknown(_)
+ ));
+ }
+
+ /// Without a session there is no correlation id on any request, so there is
+ /// nothing to look up and saying so beats an empty result.
+ #[test]
+ fn the_run_view_without_a_session_says_so() {
+ let mut app = test_app();
+ super::usage_command(&mut app, "run");
+ let text = transcript_text(&app);
+ assert!(text.contains("no session id to correlate"), "{text}");
+ assert!(app.reported_usage_request.is_none());
+ }
+
+ /// A pasted execution id is what a user actually types here, so a lone
+ /// unrecognized word is a lookup rather than an error.
+ #[test]
+ fn a_lone_word_is_taken_as_an_execution_id() {
+ use crate::core::cli::tokamak::usage::Query;
+ assert_eq!(
+ super::parse_usage_mode("0b7c1d2e-3f45-6789-abcd-ef0123456789"),
+ super::UsageMode::Account(Query::Generation(
+ "0b7c1d2e-3f45-6789-abcd-ef0123456789".to_string()
+ ))
+ );
+ // A phrase is a typo, not an id; naming the views beats a round trip
+ // that can only come back not-found.
+ assert!(matches!(
+ super::parse_usage_mode("how much did i spend"),
+ super::UsageMode::Unknown(_)
+ ));
+ }
+
+ /// Without a Tokamak key there is no account to read, and the TUI must say
+ /// so locally instead of opening an overlay that can only resolve into an
+ /// auth failure. Critically it is not an error: the session estimate is
+ /// still a valid answer and the note points at it.
+ #[test]
+ fn an_account_view_without_a_key_is_declined_not_attempted() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let mut app = test_app();
+ super::usage_command(&mut app, "account");
+ let text = transcript_text(&app);
+ assert!(
+ text.contains("no account usage API is configured"),
+ "{text}"
+ );
+ assert!(
+ app.reported_usage_request.is_none(),
+ "nothing may be sent upstream without a key"
+ );
+ assert!(app.readout.is_none(), "no readout should open");
+ });
+ }
+
+ /// A view that landed must never be reopened after the user closed it,
+ /// matching `/context`'s overlay contract.
+ #[test]
+ fn a_usage_result_landing_after_close_is_dropped() {
+ use crate::core::cli::tokamak::usage::{Query, UsageError};
+ let mut app = test_app();
+ app.readout = None;
+ super::finish_reported_usage(&mut app, &Query::Summary, Err(UsageError::NotFound));
+ assert!(app.readout.is_none());
+ }
+
+ /// A failed read fills the overlay with the reason. An empty popup would
+ /// read as "you spent nothing", which is the one thing it must not say.
+ #[test]
+ fn a_failed_read_reports_the_reason_rather_than_an_empty_readout() {
+ use crate::core::cli::tokamak::usage::{Query, UsageError};
+ let mut app = test_app();
+ app.readout = Some(super::Readout::ReportedLoading(Query::Summary));
+ super::finish_reported_usage(&mut app, &Query::Summary, Err(UsageError::NotFound));
+ match &app.readout {
+ Some(super::Readout::ReportedError { message, .. }) => {
+ assert!(message.contains("not found"), "{message}");
+ }
+ _ => panic!("the readout should hold the failure"),
+ }
+ assert!(readout_text(&app).contains("not found"), "{}", readout_text(&app));
+ }
+
+ /// A live account summary, trimmed to six models. Shaped exactly as
+ /// `GET /v1/usage/me` answers, including the empty `provider` fields and
+ /// money as decimal strings.
+ const ACCOUNT_BODY: &str = r#"{
+ "period": {"start_date":"2026-08-23T08:57:21.160234939Z",
+ "end_date":"2026-09-22T08:57:21.160234939Z"},
+ "total_usage": {"model":"","provider":"","total_prompt_tokens":277414219,
+ "total_completion_tokens":10931093,"total_tokens":1892976850,
+ "request_count":15049,"estimated_cost_usd":"1240.10224445",
+ "cache_read_tokens":1577470525,"cache_creation_tokens":27161013,
+ "cache_savings_usd":"1200.5278263"},
+ "by_model": [
+ {"model":"cheap-model","total_prompt_tokens":56073,
+ "total_completion_tokens":2217,"request_count":29,
+ "estimated_cost_usd":"0.087158","cache_read_tokens":0,
+ "cache_creation_tokens":0,"cache_savings_usd":"0"},
+ {"model":"anthropic/claude-sonnet-5","total_prompt_tokens":4408975,
+ "total_completion_tokens":1295731,"request_count":1238,
+ "estimated_cost_usd":"46.7142352","cache_read_tokens":105369976,
+ "cache_creation_tokens":1545992,"cache_savings_usd":"189.6659568"},
+ {"model":"anthropic/claude-opus-5","total_prompt_tokens":8639502,
+ "total_completion_tokens":1546976,"request_count":2987,
+ "estimated_cost_usd":"195.67393925","cache_read_tokens":224635971,
+ "cache_creation_tokens":237447,"cache_savings_usd":"1010.8618695"},
+ {"model":"tokamak-1-preview","total_prompt_tokens":263419660,
+ "total_completion_tokens":2879420,"request_count":4884,
+ "estimated_cost_usd":"69.454827","cache_read_tokens":0,
+ "cache_creation_tokens":0,"cache_savings_usd":"0"},
+ {"model":"claude-opus-4-8","total_prompt_tokens":890009,
+ "total_completion_tokens":120000,"request_count":300,
+ "estimated_cost_usd":"12.5","cache_read_tokens":0,
+ "cache_creation_tokens":0,"cache_savings_usd":"0"},
+ {"model":"claude-haiku-4-5","total_prompt_tokens":100000,
+ "total_completion_tokens":20000,"request_count":120,
+ "estimated_cost_usd":"3.25","cache_read_tokens":0,
+ "cache_creation_tokens":0,"cache_savings_usd":"0"}
+ ]}"#;
+
+ /// `m` folds an account readout the same way it folds the session one, and
+ /// without refetching -- the payload is held, so expanding a table costs
+ /// no request.
+ #[tokio::test]
+ async fn m_folds_an_account_readout_without_refetching() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ let mut app = test_app();
+ app.readout = Some(super::Readout::ReportedLoading(Query::Summary));
+ super::finish_reported_usage(
+ &mut app,
+ &Query::Summary,
+ Ok(parse_payload_for_test(ACCOUNT_BODY)),
+ );
+ assert!(readout_text(&app).contains("m to show all"));
+ assert!(!readout_text(&app).contains("cheap-model"));
+
+ press(&mut app, KeyCode::Char('m'), KeyModifiers::NONE).await;
+ assert!(
+ matches!(app.readout, Some(super::Readout::Reported { all_rows: true, .. })),
+ "m expands"
+ );
+ assert!(readout_text(&app).contains("cheap-model"));
+
+ press(&mut app, KeyCode::Char('m'), KeyModifiers::NONE).await;
+ assert!(
+ matches!(app.readout, Some(super::Readout::Reported { all_rows: false, .. })),
+ "m folds back"
+ );
+ // Folding is a view change, not a close.
+ assert!(readout_text(&app).contains("account total"));
+ }
+
+ /// The session readout points at the authoritative view rather than
+ /// leaving the user to believe the estimate is the bill.
+ #[test]
+ fn the_session_readout_points_at_the_account_view() {
+ let mut app = test_app();
+ app.set_model("anthropic/claude-opus-5".to_string());
+ app.apply(StreamEvent::TurnUsage {
+ usage: crate::core::agent::events::Usage {
+ prompt_tokens: Some(100),
+ completion_tokens: Some(10),
+ total_tokens: None,
+ cached_tokens: None,
+ cache_write_tokens: None,
+ },
+ execution_id: None,
+ });
+ super::usage_command(&mut app, "");
+ let text = readout_text(&app);
+ assert!(text.contains("not a bill"), "{text}");
+ assert!(text.contains("/usage account"), "{text}");
+ }
+
+ /// The session estimate renders from live state, not from a snapshot taken
+ /// when the readout opened. A user who leaves it up during a turn is
+ /// watching the run's spend, so a total frozen at open time would be
+ /// quietly wrong from the first token that arrived after it.
+ #[test]
+ fn the_session_readout_keeps_counting_while_it_is_open() {
+ let mut app = test_app();
+ app.set_model("anthropic/claude-opus-5".to_string());
+ super::usage_command(&mut app, "");
+ assert!(readout_text(&app).contains("no usage yet this session"));
+
+ app.apply(StreamEvent::TurnUsage {
+ usage: crate::core::agent::events::Usage {
+ prompt_tokens: Some(1_000),
+ completion_tokens: Some(50),
+ total_tokens: None,
+ cached_tokens: None,
+ cache_write_tokens: None,
+ },
+ execution_id: None,
+ });
+ let text = readout_text(&app);
+ assert!(
+ text.contains("1 req"),
+ "the open readout must reflect the request that just landed: {text}"
+ );
}
/// A report with a measured fill and no cache fields, the starting point for
@@ -31994,6 +33163,7 @@ mod tests {
cached_tokens: Some(900),
..Default::default()
},
+ execution_id: None,
});
app.begin_turn();
assert_eq!(app.turn_cached_tokens, 0, "the per-turn sample resets");
@@ -32006,6 +33176,7 @@ mod tests {
cached_tokens: Some(0),
..Default::default()
},
+ execution_id: None,
});
assert_eq!(app.session_prompt_tokens, 5_000, "both requests billed");
assert_eq!(app.session_cached_tokens, 900);
@@ -32173,27 +33344,127 @@ mod tests {
}
}
- /// The `/context` overlay (not the old transcript row) goes through the
- /// same frame sizes the rest of the transcript survives. A mid-turn popup
- /// must never panic on rendering, however narrow or short the terminal.
+ /// Every readout variant goes through the frame sizes the rest of the
+ /// transcript survives. A readout is drawn mid-turn, over a live frame, so
+ /// it must never panic however narrow or short the terminal -- and the
+ /// docked rect is computed by subtraction, which is where an underflow
+ /// would hide.
#[test]
- fn tiny_frames_render_the_context_view_without_panicking() {
- let mut app = test_app();
+ fn tiny_frames_render_every_readout_without_panicking() {
let report = context_report(234_000, 35_000, [6_000, 9_000, 2_100, 8_000, 95_000]);
- app.context_view = Some(ContextView::Ready(Box::new(report)));
- for (w, h) in [
- (1u16, 1u16),
- (2, 3),
- (8, 4),
- (20, 6),
- (40, 2),
- (43, 12),
- (200, 80),
- ] {
- render_rows(&mut app, w, h);
+ let variants = || {
+ vec![
+ Readout::ContextLoading,
+ Readout::Context(Box::new(report.clone())),
+ Readout::Session { all_models: false },
+ Readout::Overview {
+ all_models: true,
+ account: super::AccountSlot::Ready(Box::new(
+ crate::core::cli::tokamak::usage::parse_payload_for_test(ACCOUNT_BODY),
+ )),
+ },
+ Readout::Overview {
+ all_models: false,
+ account: super::AccountSlot::Loading,
+ },
+ Readout::Overview {
+ all_models: false,
+ account: super::AccountSlot::Failed("could not reach the server".to_string()),
+ },
+ Readout::ReportedLoading(crate::core::cli::tokamak::usage::Query::Summary),
+ Readout::Reported {
+ title: "account".to_string(),
+ query: crate::core::cli::tokamak::usage::Query::Summary,
+ payload: Box::new(
+ crate::core::cli::tokamak::usage::parse_payload_for_test(ACCOUNT_BODY),
+ ),
+ all_rows: true,
+ },
+ Readout::ReportedError {
+ title: "account".to_string(),
+ message: "not found".to_string(),
+ },
+ ]
+ };
+ for readout in variants() {
+ let mut app = test_app();
+ app.readout = Some(readout);
+ for (w, h) in [
+ (1u16, 1u16),
+ (2, 3),
+ (8, 4),
+ (20, 6),
+ (40, 2),
+ (43, 12),
+ (200, 80),
+ ] {
+ render_rows(&mut app, w, h);
+ }
}
}
+ /// The readout docks above the input box rather than floating mid-screen,
+ /// so it sits where every other prompt in this TUI does and does not cover
+ /// the transcript its numbers are about.
+ #[test]
+ fn the_readout_docks_above_the_input_box() {
+ let mut app = test_app();
+ app.readout = Some(Readout::Reported {
+ title: "account".to_string(),
+ query: crate::core::cli::tokamak::usage::Query::Summary,
+ payload: Box::new(crate::core::cli::tokamak::usage::parse_payload_for_test(
+ r#"{"spend_usd":"1.25"}"#,
+ )),
+ all_rows: false,
+ });
+ let rows = render_rows(&mut app, 60, 24);
+ // Located by the title, not by border glyphs: other chrome draws
+ // horizontal rules too, so a glyph search finds the wrong box.
+ let top = rows
+ .iter()
+ .position(|row| row.contains("account"))
+ .expect("the readout draws its title");
+ // Docked: the box lives in the bottom half, against the input, rather
+ // than centered over the conversation.
+ assert!(
+ top > rows.len() / 2,
+ "the readout should dock at the bottom, found its top border at row {top} of {}",
+ rows.len()
+ );
+ }
+
+ /// One field holds the open readout, so asking for a second one replaces
+ /// the first. Two independent `Option`s could both be `Some` and render
+ /// one popup over another.
+ #[test]
+ fn opening_a_second_readout_replaces_the_first() {
+ let mut app = test_app();
+ super::context_command(&mut app);
+ assert!(matches!(app.readout, Some(Readout::ContextLoading)));
+ super::usage_command(&mut app, "session");
+ assert!(
+ matches!(app.readout, Some(Readout::Session { .. })),
+ "the newer readout wins outright"
+ );
+ }
+
+ /// A slow `/context` computation must not yank away a readout the user
+ /// opened after it. Landing results are matched to the view still waiting
+ /// for them, not merely to "something is open".
+ #[test]
+ fn a_late_context_report_does_not_replace_a_newer_readout() {
+ let mut app = test_app();
+ super::context_command(&mut app);
+ // The user gave up on it and asked for the session estimate instead.
+ super::usage_command(&mut app, "session");
+ let report = context_report(234_000, 35_000, [6_000, 9_000, 2_100, 8_000, 95_000]);
+ super::finish_context_report(&mut app, report);
+ assert!(
+ matches!(app.readout, Some(Readout::Session { .. })),
+ "the stale report must not displace what the user is now reading"
+ );
+ }
+
/// A compaction invalidates the provider's last measurement: the count is
/// an estimate until a fresh response reports one.
#[tokio::test]
@@ -32216,6 +33487,7 @@ mod tests {
total_tokens: Some(90_010),
..Default::default()
},
+ execution_id: None,
});
assert!(
app.context_report().await.fill_reported,
@@ -32241,6 +33513,7 @@ mod tests {
total_tokens: Some(120_010),
..Default::default()
},
+ execution_id: None,
});
assert!(app.context_report().await.fill_reported);
rewind_to(&mut app, 0, false);
@@ -32274,7 +33547,7 @@ mod tests {
app.status = Status::Running;
run_command(&mut app, "context", &no_mcp()).await;
assert!(
- matches!(app.context_view, Some(ContextView::Loading)),
+ matches!(app.readout, Some(Readout::ContextLoading)),
"mid-turn /context must open the loading overlay"
);
assert!(
@@ -32301,7 +33574,7 @@ mod tests {
async fn esc_closes_the_context_overlay_without_cancelling_the_turn() {
let mut app = test_app();
app.status = Status::Running;
- app.context_view = Some(ContextView::Loading);
+ app.readout = Some(Readout::ContextLoading);
app.context_request = true;
let registry: PermissionRegistry = Arc::new(tokio::sync::Mutex::new(HashMap::new()));
let mcp_servers = no_mcp();
@@ -32315,7 +33588,7 @@ mod tests {
)
.await;
assert!(
- app.context_view.is_none(),
+ app.readout.is_none(),
"Esc must close the context overlay"
);
assert_eq!(app.status, Status::Running, "the turn keeps running");
@@ -32324,7 +33597,7 @@ mod tests {
"closing the overlay must not spawn a run, let alone cancel one"
);
// A bare `q` also closes it, outranking the quit shortcut.
- app.context_view = Some(ContextView::Loading);
+ app.readout = Some(Readout::ContextLoading);
handle_key(
&mut app,
key(KeyCode::Char('q')),
@@ -32333,7 +33606,7 @@ mod tests {
&mcp_servers,
)
.await;
- assert!(app.context_view.is_none(), "q closes when not ctrl");
+ assert!(app.readout.is_none(), "q closes when not ctrl");
assert!(
!app.should_quit,
"q must not quit while the overlay is open"
@@ -32346,11 +33619,11 @@ mod tests {
#[tokio::test]
async fn a_context_result_landing_after_close_is_discarded() {
let mut app = test_app();
- app.context_view = None;
+ app.readout = None;
let report = context_report(128_000, 16_384, [1_000, 2_000, 3_000, 4_000, 5_000]);
finish_context_report(&mut app, report);
assert!(
- app.context_view.is_none(),
+ app.readout.is_none(),
"a result landing after the overlay closed must not reopen it"
);
}
diff --git a/src-tauri/src/core/cli/usage_view.rs b/src-tauri/src/core/cli/usage_view.rs
new file mode 100644
index 000000000..386d292a6
--- /dev/null
+++ b/src-tauri/src/core/cli/usage_view.rs
@@ -0,0 +1,645 @@
+//! One renderer for provider-reported usage, shared by the TUI readout and
+//! the `jan usage` subcommand.
+//!
+//! Both surfaces answer the same question from the same bytes, so they render
+//! through the same code: a fix to how a charge is displayed cannot land in
+//! one and miss the other. The output is plain `String` lines rather than
+//! styled spans because that is the intersection of what a dock and a pipe
+//! can both take; the TUI adds colour by wrapping, not by re-laying-out.
+//!
+//! Nothing here reformats a money figure. A reported amount is printed as the
+//! server wrote it (see [`crate::core::cli::tokamak::usage::Money`]), which is
+//! also what keeps it visually distinct from the session estimate's `~$0.57`.
+
+use super::tui::format_tokens;
+
+/// How many rows the account and daily views show before folding.
+const TOP_REPORTED_ROWS: usize = 5;
+
+/// How much of a ranked list to show, and whether the reader can change it.
+///
+/// Not a bool, because "show everything" has two different meanings here and
+/// only one of them may print a keybinding. The TUI's docked readout folds and
+/// unfolds with `m`; `jan usage` writes to a pipe, where nothing is folded (a
+/// view that silently dropped rows would be wrong for the scripts reading it)
+/// and there is no `m` to press.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Fold {
+ /// Docked: the tail is folded away, with the hint that shows it.
+ Folded,
+ /// Docked and unfolded: every row, with the hint that folds it back.
+ Unfolded,
+ /// Piped: every row and no hint at all.
+ Fixed,
+}
+
+impl Fold {
+ /// The docked spelling of an `all_rows` flag.
+ pub fn docked(all_rows: bool) -> Self {
+ if all_rows {
+ Self::Unfolded
+ } else {
+ Self::Folded
+ }
+ }
+
+ fn shows_all(self) -> bool {
+ !matches!(self, Self::Folded)
+ }
+
+ /// The trailing line offering the other half of the fold, or `None` when
+ /// there is no key to press.
+ fn hint(self, hidden: usize, noun: &str) -> Option<String> {
+ match self {
+ Self::Fixed => None,
+ _ if hidden > 0 => Some(format!(
+ " +{hidden} more {noun}{} · m to show all",
+ if hidden == 1 { "" } else { "s" }
+ )),
+ Self::Unfolded => Some(" m to fold the tail".to_string()),
+ Self::Folded => None,
+ }
+ }
+}
+
+/// A reported money amount, as the server wrote it, prefixed for display.
+///
+/// No reformatting and no rounding: the text is the figure. Deliberately not
+/// routed through the TUI's `format_usd`, which is the *estimate* formatter -- a
+/// provider-recorded charge that rendered identically to a local guess would
+/// be indistinguishable from one, which is the confusion this whole split
+/// exists to prevent. An estimate reads `~$0.57`; a reported figure reads
+/// `$0.570142` exactly as sent.
+fn reported_money(amount: Option<&crate::core::cli::tokamak::usage::Money>) -> String {
+ amount.map_or_else(
+ || crate::core::cli::tokamak::usage::UNAVAILABLE.to_string(),
+ |m| format!("${m}"),
+ )
+}
+
+/// Sort key for a reported amount. Ranking is the one place a charge may be
+/// approximated -- the ordering of a list is not a figure anyone reconciles --
+/// but the value shown beside it is still the server's exact text. An
+/// unparseable or absent amount ranks last rather than as zero.
+fn money_rank(amount: Option<&crate::core::cli::tokamak::usage::Money>) -> f64 {
+ amount
+ .and_then(|m| m.as_str().parse::<f64>().ok())
+ .unwrap_or(f64::NEG_INFINITY)
+}
+
+/// Just the date out of an RFC 3339 timestamp. For a reporting period, whose
+/// bounds are a month apart, the clock is noise.
+fn day_only(stamp: &str) -> String {
+ stamp.split_once('T').map_or(stamp, |(date, _)| date).to_string()
+}
+
+/// Trim an RFC 3339 timestamp to the date, or `YYYY-MM-DD HH:MM` when the time
+/// of day distinguishes rows. Long timestamps are most of a row's width and
+/// the seconds are never what is being compared.
+fn short_date(stamp: &str) -> String {
+ let Some((date, rest)) = stamp.split_once('T') else {
+ return stamp.to_string();
+ };
+ match rest.split_once(':') {
+ // Midnight is a daily bucket's marker, not a time: show the date alone.
+ Some((hour, tail)) if hour == "00" && tail.starts_with("00") => date.to_string(),
+ Some((hour, tail)) => format!("{date} {hour}:{}", &tail[..2.min(tail.len())]),
+ None => date.to_string(),
+ }
+}
+
+/// `N req · 12.3K in (8.1K cached) · 3.4K out`, for a server-reported row.
+/// Mirrors [`usage_counts`] so the session and account views read alike --
+/// token counts are the one thing the two sources measure the same way.
+fn reported_counts(row: &crate::core::cli::tokamak::usage::Aggregate) -> String {
+ let mut line = format!(
+ "{} req · {} in",
+ row.request_count,
+ format_tokens(row.prompt_tokens)
+ );
+ if row.cache_read_tokens > 0 {
+ line.push_str(&format!(" ({} cached)", format_tokens(row.cache_read_tokens)));
+ }
+ line.push_str(&format!(" · {} out", format_tokens(row.completion_tokens)));
+ if row.cache_creation_tokens > 0 {
+ line.push_str(&format!(
+ " · {} cache write",
+ format_tokens(row.cache_creation_tokens)
+ ));
+ }
+ line
+}
+
+/// Lay out ranked rows as a padded two-column table under a heading, folding
+/// past `TOP_REPORTED_ROWS`. Shared by the account and daily views, which
+/// differ only in what a row is named after.
+fn reported_rows(
+ heading: &str,
+ rows: &[crate::core::cli::tokamak::usage::Aggregate],
+ fold: Fold,
+ noun: &str,
+) -> Vec<String> {
+ if rows.is_empty() {
+ return Vec::new();
+ }
+ let shown = if fold.shows_all() {
+ rows.len()
+ } else {
+ rows.len().min(TOP_REPORTED_ROWS)
+ };
+ let hidden = rows.len() - shown;
+ let mut out = vec![String::new(), heading.to_string()];
+ let label_w = rows[..shown]
+ .iter()
+ .map(|r| r.label.chars().count())
+ .max()
+ .unwrap_or(0);
+ let costs: Vec<String> = rows[..shown]
+ .iter()
+ .map(|r| reported_money(r.cost.as_ref()))
+ .collect();
+ let cost_w = costs.iter().map(|c| c.chars().count()).max().unwrap_or(0);
+ for (row, cost) in rows[..shown].iter().zip(&costs) {
+ out.push(format!(
+ " {:<label_w$} {:<cost_w$} {}",
+ row.label,
+ cost,
+ reported_counts(row)
+ ));
+ }
+ out.extend(
+ fold.hint(hidden, noun)
+ .filter(|_| hidden > 0 || rows.len() > TOP_REPORTED_ROWS),
+ );
+ out
+}
+
+/// The account total, without the per-model table: the amount, what it bought
+/// and the window it covers. Three lines, because this is what someone asking
+/// "what have I spent" is owed before any breakdown.
+fn total_rows(summary: &crate::core::cli::tokamak::usage::AccountSummary) -> Vec<String> {
+ let mut out = vec![format!(
+ " {} {}",
+ reported_money(summary.total.cost.as_ref()),
+ reported_counts(&summary.total)
+ )];
+ if let Some(savings) = &summary.total.savings {
+ out.push(format!(" caching saved ${savings}"));
+ }
+ if let Some((start, end)) = &summary.period {
+ out.push(format!(" {} to {}", day_only(start), day_only(end)));
+ }
+ out
+}
+
+/// Just the account total, for the overview pane. `None` when the body is not
+/// a summary, so the caller can fall back to the generic field walk.
+pub fn account_total_lines(
+ payload: &crate::core::cli::tokamak::usage::Payload,
+) -> Option<Vec<String>> {
+ crate::core::cli::tokamak::usage::parse_account_summary(payload).map(|s| total_rows(&s))
+}
+
+/// Render a fetched account-usage payload.
+///
+/// Each view leads with the figure that answers the question asked -- the
+/// account's total spend, the day's total, whether spending is allowed -- and
+/// folds the breakdown beneath it, the same shape bare `/usage` uses for the
+/// session estimate. A payload this build cannot parse falls back to the raw
+/// field walk rather than reporting nothing, so a server-side schema change
+/// degrades to a flat dump instead of an empty readout.
+///
+/// `fold` says how much of each ranked list to show and whether a keybinding
+/// for the other half may be printed -- see [`Fold`], which is what keeps the
+/// docked readout's `m` hint out of a piped `jan usage`.
+pub fn reported_usage_lines(
+ query: &crate::core::cli::tokamak::usage::Query,
+ payload: &crate::core::cli::tokamak::usage::Payload,
+ fold: Fold,
+) -> Vec<String> {
+ use crate::core::cli::tokamak::usage;
+
+ // The generic walk: every field the server sent, values verbatim. Used for
+ // a view with no typed layout and as the fallback when one fails to parse.
+ let raw_fields = || -> Vec<String> {
+ let fields = payload.fields();
+ if fields.is_empty() {
+ vec!["the provider reported no figures for this view".to_string()]
+ } else {
+ // Padded to the widest path so the values line up as a column;
+ // a usage readout is scanned down the numbers, not read across.
+ let width = fields.iter().map(|(p, _)| p.len()).max().unwrap_or(0);
+ fields
+ .iter()
+ .map(|(path, value)| format!("{path:width$} {value}"))
+ .collect()
+ }
+ };
+
+ let mut lines = match query {
+ usage::Query::Generation(_) | usage::Query::Correlated(_) => {
+ match usage::parse_generations_payload(payload) {
+ Ok(records) if records.is_empty() => vec!["no matching execution".to_string()],
+ Ok(records) => records
+ .iter()
+ .flat_map(|record| {
+ usage::generation_lines(record)
+ .into_iter()
+ .chain(std::iter::once(String::new()))
+ })
+ .collect(),
+ Err(e) => vec![e.to_string()],
+ }
+ }
+ usage::Query::Summary => match usage::parse_account_summary(payload) {
+ Some(summary) => {
+ let mut out = vec!["account total".to_string()];
+ out.extend(total_rows(&summary));
+ // Costliest first: a folded list must keep the models that
+ // account for the spend, and the server already ranked nothing.
+ let mut models = summary.by_model.clone();
+ models.sort_by(|a, b| {
+ money_rank(b.cost.as_ref())
+ .partial_cmp(&money_rank(a.cost.as_ref()))
+ .unwrap_or(std::cmp::Ordering::Equal)
+ .then_with(|| a.label.cmp(&b.label))
+ });
+ out.extend(reported_rows("top models", &models, fold, "model"));
+ out
+ }
+ None => raw_fields(),
+ },
+ usage::Query::Daily => match usage::parse_daily(payload) {
+ Some(days) if days.is_empty() => {
+ vec!["no recorded days".to_string()]
+ }
+ // Sorted, not ranked: a daily view is read in date order rather
+ // than by size, so the order is the dates' own. The server already
+ // sends them newest-first, but "most recent day" below names a
+ // specific date and would state the wrong one if that ever
+ // changed -- and a descending sort on an ISO date string is a
+ // string sort, so it costs nothing to not depend on it.
+ Some(mut days) => {
+ days.sort_by(|a, b| b.label.cmp(&a.label));
+ let mut out = vec!["most recent day".to_string()];
+ out.push(format!(
+ " {} {}",
+ reported_money(days[0].cost.as_ref()),
+ reported_counts(&days[0])
+ ));
+ out.push(format!(" {}", short_date(&days[0].label)));
+ let dated: Vec<usage::Aggregate> = days
+ .iter()
+ .map(|day| usage::Aggregate {
+ label: short_date(&day.label),
+ ..day.clone()
+ })
+ .collect();
+ out.extend(reported_rows("by day", &dated, fold, "day"));
+ out
+ }
+ None => raw_fields(),
+ },
+ usage::Query::Requests => match usage::parse_requests(payload) {
+ Some(records) if records.is_empty() => {
+ vec!["no recorded requests".to_string()]
+ }
+ Some(records) => {
+ let shown = if fold.shows_all() {
+ records.len()
+ } else {
+ records.len().min(TOP_REPORTED_ROWS)
+ };
+ let hidden = records.len() - shown;
+ let mut out = vec![format!(
+ "{} recorded request{}",
+ records.len(),
+ if records.len() == 1 { "" } else { "s" }
+ )];
+ for record in &records[..shown] {
+ let model = record.model.clone().unwrap_or_else(|| {
+ usage::UNAVAILABLE.to_string()
+ });
+ let mut head = format!(
+ " {} {} {}",
+ short_date(record.created_at.as_deref().unwrap_or_default()),
+ reported_money(record.cost.as_ref()),
+ model
+ );
+ // Only worth the width when it changes how the row reads:
+ // an unsettled charge, or a request that failed.
+ if let Some(status) = &record.billing_status {
+ if !status.is_final() {
+ head.push_str(&format!(" ({status})"));
+ }
+ }
+ if record.status.is_some_and(|s| s >= 400) {
+ head.push_str(&format!(" [HTTP {}]", record.status.unwrap_or_default()));
+ }
+ out.push(head);
+ out.push(format!(
+ " {} in{} · {} out{}",
+ format_tokens(record.prompt_tokens),
+ if record.cache_read_tokens > 0 {
+ format!(" ({} cached)", format_tokens(record.cache_read_tokens))
+ } else {
+ String::new()
+ },
+ format_tokens(record.completion_tokens),
+ record
+ .execution_id
+ .as_deref()
+ .map(|id| format!(" · {id}"))
+ .unwrap_or_default()
+ ));
+ }
+ out.extend(
+ fold.hint(hidden, "request")
+ .filter(|_| hidden > 0 || records.len() > TOP_REPORTED_ROWS),
+ );
+ out
+ }
+ None => raw_fields(),
+ },
+ usage::Query::Limits => match usage::parse_limits(payload) {
+ Some(limits) => {
+ let mut out = vec![if limits.allowed {
+ "spending is allowed".to_string()
+ } else {
+ "spending is blocked by a usage limit".to_string()
+ }];
+ if limits.decisions.is_empty() {
+ out.push(" no limit decisions recorded".to_string());
+ } else {
+ for decision in &limits.decisions {
+ out.push(format!(" {decision}"));
+ }
+ }
+ // Named because the two are separate checks upstream: an
+ // allowed limit says nothing about whether the wallet is funded.
+ out.push(String::new());
+ out.push("usage limits and wallet credit are separate checks".to_string());
+ out
+ }
+ None => raw_fields(),
+ },
+ };
+ while lines.last().is_some_and(String::is_empty) {
+ lines.pop();
+ }
+ // The line that keeps the two kinds of number apart. Everything above came
+ // from the server; the session estimate lives behind a different command
+ // and the two are never added together.
+ lines.push(String::new());
+ lines.push("reported by the provider - not the local session estimate".to_string());
+ lines
+}
+
+#[cfg(test)]
+mod tests {
+ /// Every server-sourced readout has to declare itself as such, because the
+ /// same command one word apart prints a local estimate.
+ #[test]
+ fn a_reported_readout_says_it_is_not_the_local_estimate() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ // A body in no shape this build knows still renders: the generic
+ // field walk is the fallback, so a server-side schema change degrades
+ // to a flat dump rather than an empty readout.
+ let payload = parse_payload_for_test(r#"{"spend_usd":"1.25"}"#);
+ let lines = super::reported_usage_lines(&Query::Summary, &payload, super::Fold::Folded).join("\n");
+ assert!(lines.contains("spend_usd"), "{lines}");
+ assert!(lines.contains("1.25"), "{lines}");
+ assert!(
+ lines.contains("reported by the provider - not the local session estimate"),
+ "{lines}"
+ );
+ }
+
+ /// The account view answers "what have I spent" on its first line, with
+ /// the per-model breakdown folded beneath it -- the same shape bare
+ /// `/usage` uses. Before this it printed `by_model[7].cache_read_tokens`
+ /// style paths, which is the JSON object rather than an answer.
+ #[test]
+ fn the_account_view_leads_with_the_total_and_folds_the_models() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ let payload = parse_payload_for_test(ACCOUNT_BODY);
+ let folded = super::reported_usage_lines(&Query::Summary, &payload, super::Fold::Folded).join("\n");
+
+ assert!(folded.contains("account total"), "{folded}");
+ // Exact server text, never reformatted through the estimate's
+ // formatter -- a reconciliation reads these digits.
+ assert!(folded.contains("$1240.10224445"), "{folded}");
+ assert!(folded.contains("15049 req"), "{folded}");
+ assert!(folded.contains("caching saved $1200.5278263"), "{folded}");
+ assert!(folded.contains("2026-08-23 to 2026-09-22"), "{folded}");
+ assert!(!folded.contains("by_model["), "no raw JSON paths: {folded}");
+
+ // Six models, five shown, ranked by spend: the cheapest is the one hidden.
+ assert!(folded.contains("top models"), "{folded}");
+ assert!(folded.contains("anthropic/claude-opus-5"), "{folded}");
+ assert!(folded.contains("+1 more model · m to show all"), "{folded}");
+ assert!(!folded.contains("cheap-model"), "the cheapest folds: {folded}");
+
+ let all = super::reported_usage_lines(&Query::Summary, &payload, super::Fold::Unfolded).join("\n");
+ assert!(all.contains("cheap-model"), "{all}");
+ assert!(!all.contains("more model"), "{all}");
+ // The figure that matters does not move between the two.
+ assert!(all.contains("$1240.10224445"), "{all}");
+ }
+
+ /// `jan usage` writes to a pipe, where every row is printed (a view that
+ /// silently dropped rows would be wrong for the scripts reading it) and
+ /// there is no `m` to press. Offering the keystroke anyway names an
+ /// affordance that does not exist on this surface.
+ #[test]
+ fn a_piped_view_shows_every_row_and_offers_no_keystroke() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ let payload = parse_payload_for_test(ACCOUNT_BODY);
+ let piped = super::reported_usage_lines(&Query::Summary, &payload, super::Fold::Fixed)
+ .join("\n");
+
+ // Nothing folded: the row the docked view hides is here.
+ assert!(piped.contains("cheap-model"), "{piped}");
+ assert!(!piped.contains(" m to "), "no keybinding in a pipe: {piped}");
+ assert!(!piped.contains("more model"), "{piped}");
+ // The figures are the same ones the dock shows.
+ assert!(piped.contains("$1240.10224445"), "{piped}");
+ }
+
+ /// Ranking is by spend, so a folded list keeps the models the money went
+ /// to. Sorting by name would hide the expensive one behind an alphabet.
+ #[test]
+ fn account_models_rank_by_spend_not_by_name() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ let payload = parse_payload_for_test(ACCOUNT_BODY);
+ let lines = super::reported_usage_lines(&Query::Summary, &payload, super::Fold::Unfolded);
+ let position = |needle: &str| {
+ lines
+ .iter()
+ .position(|l| l.contains(needle))
+ .unwrap_or_else(|| panic!("{needle} missing from {lines:?}"))
+ };
+ assert!(
+ position("anthropic/claude-opus-5") < position("tokamak-1-preview"),
+ "195.67 outranks 69.45: {lines:?}"
+ );
+ assert!(
+ position("tokamak-1-preview") < position("anthropic/claude-sonnet-5"),
+ "69.45 outranks 46.71: {lines:?}"
+ );
+ assert!(
+ position("anthropic/claude-sonnet-5") < position("cheap-model"),
+ "46.71 outranks 0.08: {lines:?}"
+ );
+ }
+
+ /// A model the server reported no cost for is unavailable, not free, and
+ /// must rank last rather than as a zero that reads like "cost nothing".
+ #[test]
+ fn an_account_model_with_no_cost_reads_as_unavailable() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ let payload = parse_payload_for_test(
+ r#"{"total_usage":{"request_count":2,"estimated_cost_usd":"1.0"},
+ "by_model":[{"model":"priced","request_count":1,"estimated_cost_usd":"1.0"},
+ {"model":"unpriced","request_count":1,"estimated_cost_usd":null}]}"#,
+ );
+ let lines = super::reported_usage_lines(&Query::Summary, &payload, super::Fold::Unfolded);
+ let text = lines.join("\n");
+ assert!(text.contains("unavailable"), "{text}");
+ assert!(!text.contains("$0"), "an unknown cost is never a zero: {text}");
+ let position = |needle: &str| lines.iter().position(|l| l.contains(needle)).unwrap();
+ assert!(position("priced") < position("unpriced"), "{lines:?}");
+ }
+
+ /// The daily view keeps the server's date order rather than re-ranking by
+ /// spend: a run of days is read as a timeline, and the newest day is the
+ /// one the question is usually about.
+ #[test]
+ fn the_daily_view_leads_with_the_newest_day_in_date_order() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ let payload = parse_payload_for_test(
+ r#"[{"date":"2026-09-22T00:00:00Z","total_prompt_tokens":2643716,
+ "total_completion_tokens":624644,"request_count":1095,
+ "estimated_cost_usd":"66.8881106"},
+ {"date":"2026-09-21T00:00:00Z","total_prompt_tokens":3475890,
+ "total_completion_tokens":939555,"request_count":915,
+ "estimated_cost_usd":"57.56311"}]"#,
+ );
+ let lines = super::reported_usage_lines(&Query::Daily, &payload, super::Fold::Folded);
+ let text = lines.join("\n");
+ assert!(text.contains("most recent day"), "{text}");
+ assert!(text.contains("$66.8881106"), "{text}");
+ // A midnight bucket is a date, not a time of day.
+ assert!(text.contains("2026-09-22"), "{text}");
+ assert!(!text.contains("00:00"), "a daily bucket has no clock: {text}");
+ let position = |needle: &str| lines.iter().rposition(|l| l.contains(needle)).unwrap();
+ assert!(position("2026-09-22") < position("2026-09-21"), "{lines:?}");
+ }
+
+ /// "most recent day" names a specific date, so it must be the newest one in
+ /// the body rather than whichever the server happened to send first. The
+ /// server sends them newest-first today; this view does not depend on it.
+ #[test]
+ fn the_daily_view_finds_the_newest_day_whatever_order_it_arrives_in() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ // Oldest-first, the reverse of what the server sends.
+ let payload = parse_payload_for_test(
+ r#"[{"date":"2026-09-21T00:00:00Z","total_prompt_tokens":10,
+ "total_completion_tokens":1,"request_count":1,
+ "estimated_cost_usd":"1.00"},
+ {"date":"2026-09-22T00:00:00Z","total_prompt_tokens":20,
+ "total_completion_tokens":2,"request_count":2,
+ "estimated_cost_usd":"2.00"}]"#,
+ );
+ let lines = super::reported_usage_lines(&Query::Daily, &payload, super::Fold::Folded);
+ let head = lines[..3].join("\n");
+ assert!(head.contains("most recent day"), "{head}");
+ assert!(head.contains("2026-09-22"), "the newest date, not the first: {head}");
+ assert!(head.contains("$2.00"), "{head}");
+ // And the table under it reads newest-first too.
+ let position = |needle: &str| lines.iter().rposition(|l| l.contains(needle)).unwrap();
+ assert!(position("2026-09-22") < position("2026-09-21"), "{lines:?}");
+ }
+
+ /// The requests view is a list of executions, each with the id a user
+ /// needs to look the charge up with `/usage <execution-id>`.
+ #[test]
+ fn the_requests_view_lists_executions_with_their_ids() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ let payload = parse_payload_for_test(
+ r#"{"data":[{"execution_id":"4b1e70d6","billing_status":"not_billed",
+ "model":"anthropic/claude-opus-5","prompt_tokens":460,
+ "completion_tokens":371,"cache_read_tokens":41339,
+ "estimated_cost_usd":"0.0322445","status":200,
+ "created_at":"2026-09-22T08:57:20.751721Z"}]}"#,
+ );
+ let text = super::reported_usage_lines(&Query::Requests, &payload, super::Fold::Folded).join("\n");
+ assert!(text.contains("1 recorded request"), "{text}");
+ assert!(text.contains("4b1e70d6"), "the id to look up: {text}");
+ assert!(text.contains("$0.0322445"), "{text}");
+ assert!(text.contains("41K cached"), "{text}");
+ // Not yet billed, so the figure must not read as a settled charge.
+ assert!(text.contains("(not_billed)"), "{text}");
+ assert!(text.contains("2026-09-22 08:57"), "{text}");
+ }
+
+ /// The limits view answers a yes/no question, so it says yes or no instead
+ /// of printing `allowed true`.
+ #[test]
+ fn the_limits_view_answers_whether_spending_is_allowed() {
+ use crate::core::cli::tokamak::usage::{parse_payload_for_test, Query};
+ let allowed = parse_payload_for_test(r#"{"allowed":true,"decisions":null}"#);
+ let text = super::reported_usage_lines(&Query::Limits, &allowed, super::Fold::Folded).join("\n");
+ assert!(text.contains("spending is allowed"), "{text}");
+ assert!(text.contains("no limit decisions recorded"), "{text}");
+ // The two checks are separate upstream; an allowed limit is not credit.
+ assert!(text.contains("wallet credit are separate"), "{text}");
+
+ let blocked = parse_payload_for_test(
+ r#"{"allowed":false,"decisions":[{"limit":"monthly","used":"120.00"}]}"#,
+ );
+ let text = super::reported_usage_lines(&Query::Limits, &blocked, super::Fold::Folded).join("\n");
+ assert!(text.contains("blocked by a usage limit"), "{text}");
+ assert!(text.contains("monthly"), "{text}");
+ assert!(text.contains("120.00"), "{text}");
+ }
+
+
+ /// A live account summary, trimmed to six models. Shaped exactly as
+ /// `GET /v1/usage/me` answers, including the empty `provider` fields and
+ /// money as decimal strings.
+ const ACCOUNT_BODY: &str = r#"{
+ "period": {"start_date":"2026-08-23T08:57:21.160234939Z",
+ "end_date":"2026-09-22T08:57:21.160234939Z"},
+ "total_usage": {"model":"","provider":"","total_prompt_tokens":277414219,
+ "total_completion_tokens":10931093,"total_tokens":1892976850,
+ "request_count":15049,"estimated_cost_usd":"1240.10224445",
+ "cache_read_tokens":1577470525,"cache_creation_tokens":27161013,
+ "cache_savings_usd":"1200.5278263"},
+ "by_model": [
+ {"model":"cheap-model","total_prompt_tokens":56073,
+ "total_completion_tokens":2217,"request_count":29,
+ "estimated_cost_usd":"0.087158","cache_read_tokens":0,
+ "cache_creation_tokens":0,"cache_savings_usd":"0"},
+ {"model":"anthropic/claude-sonnet-5","total_prompt_tokens":4408975,
+ "total_completion_tokens":1295731,"request_count":1238,
+ "estimated_cost_usd":"46.7142352","cache_read_tokens":105369976,
+ "cache_creation_tokens":1545992,"cache_savings_usd":"189.6659568"},
+ {"model":"anthropic/claude-opus-5","total_prompt_tokens":8639502,
+ "total_completion_tokens":1546976,"request_count":2987,
+ "estimated_cost_usd":"195.67393925","cache_read_tokens":224635971,
+ "cache_creation_tokens":237447,"cache_savings_usd":"1010.8618695"},
+ {"model":"tokamak-1-preview","total_prompt_tokens":263419660,
+ "total_completion_tokens":2879420,"request_count":4884,
+ "estimated_cost_usd":"69.454827","cache_read_tokens":0,
+ "cache_creation_tokens":0,"cache_savings_usd":"0"},
+ {"model":"claude-opus-4-8","total_prompt_tokens":890009,
+ "total_completion_tokens":120000,"request_count":300,
+ "estimated_cost_usd":"12.5","cache_read_tokens":0,
+ "cache_creation_tokens":0,"cache_savings_usd":"0"},
+ {"model":"claude-haiku-4-5","total_prompt_tokens":100000,
+ "total_completion_tokens":20000,"request_count":120,
+ "estimated_cost_usd":"3.25","cache_read_tokens":0,
+ "cache_creation_tokens":0,"cache_savings_usd":"0"}
+ ]}"#;
+}