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): refresh provider model lists, and report window and cost from what they publish (#8977)

Akarshan Biswasf610ed9a8a9d
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index fa50acfa9..40a93273e 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -278,6 +278,19 @@ jan cli models list
"base_url": "https://api.anthropic.com/v1",
"has_api_key": true,
"id": "claude-fable-5"
+ },
+ {
+ "provider": "tokamak",
+ "api_type": "openai",
+ "base_url": "https://api.tokamak.sh/v1",
+ "has_api_key": true,
+ "id": "anthropic/claude-fable-5",
+ "info": {
+ "context_length": 1000000,
+ "max_output_tokens": 128000,
+ "prompt_usd": 0.00001,
+ "completion_usd": 0.00005
+ }
}
]
```
@@ -285,6 +298,39 @@ jan cli models list
This includes providers inherited from Jan Desktop, so it can list models even when
`jan config list` shows none of its own.
+`info` carries whatever the provider published about the model the last time its list was
+refreshed - context window, output cap, per-token prices. It is absent for an endpoint that lists
+ids and nothing else, which is the common case: a router-style gateway publishes this, while a
+vendor API such as Anthropic's `/v1/models` returns little more than the ids.
+
+### Refreshing the list
+
+A provider's model list is recorded when you sign in, and a gateway gains and retires models after
+that. Re-read it:
+
+```bash
+jan cli models refresh # every provider in ~/.jan/config.toml
+jan cli models refresh --provider tokamak # just one
+```
+
+Each provider's stored list is **replaced** with what its endpoint serves now, and the per-model
+metadata behind `info` is cached alongside. An endpoint that answers with no models at all is
+reported as a failure and its stored list is left alone - an empty answer is far more often an
+outage than a retirement. If the refresh drops the model `default_model` names, the summary says
+so, rather than leaving you to meet it as a 404 on the next run. The command exits non-zero if any
+provider could not be listed - including a `--provider` that names nothing refreshable - so a
+partial refresh is never reported as a complete one.
+
+Only providers with an entry in `~/.jan/config.toml` are refreshed. A provider inherited from Jan
+Desktop has nothing here to rewrite, so it is left alone; add it with `jan config set` first if you
+want its list kept current.
+
+The interactive console refreshes too, more cautiously: opening `/model` re-lists each provider once
+per session and **adds** what it finds, keeping ids the endpoint did not mention (a
+permission-scoped key or a paginated gateway can answer with a subset, and merely opening the picker
+should not delete a model you configured by hand). The picker's note names how many were kept that
+way. <kbd>Ctrl</kbd>+<kbd>R</kbd> inside the picker runs the full replacing refresh on demand.
+
## `jan cli mcp`
Manage Model Context Protocol servers in the shared `mcp_config.json` -- the same store Jan
diff --git a/docs/src/pages/docs/agent/context.mdx b/docs/src/pages/docs/agent/context.mdx
index 08c688919..32181857d 100644
--- a/docs/src/pages/docs/agent/context.mdx
+++ b/docs/src/pages/docs/agent/context.mdx
@@ -16,11 +16,12 @@ summarizing the older part of the conversation rather than failing.
The header carries live usage:
```
- jan agent tokamak-1-preview 10:40:49 turn 1/400 ctx 6K/128K 30.1/s [ready]
+ jan agent tokamak-1-preview 10:40:49 turn 1/400 ctx 6K/128K fallback 30.1/s [ready]
```
-`ctx 6K/128K` is context used against the window. It updates as each request lands, not only when a
-turn ends.
+`ctx 6K/128K` is context used against the window, and the word after it says where the window size
+came from (see [below](#where-the-window-size-comes-from)). It updates as each request lands, not
+only when a turn ends.
At the end of a turn you get a receipt:
@@ -52,6 +53,47 @@ rewind, or resume the provider count is reset, so the number falls back to an es
The report is a point-in-time snapshot taken when `/context` is typed, so numbers stay fixed
until you open it again.
+When a provider publishes prices for the model, the overlay also carries the session's estimated
+spend (`Session cost (estimated): ~$0.42`). That is every request so far, not the window: see
+[`/usage`](#usage-and-cost) for the per-model breakdown.
+
+## Where the window size comes from
+
+In order of precedence:
+
+1. `[agent].context_window` in the project's `agent.toml` - an explicit override always wins.
+2. What the provider reported for that model in its `GET /models` listing, cached when the model
+ list was last refreshed. A gateway serving a 1M-token variant of a model is believed over any
+ built-in guess.
+3. A built-in table of known model families.
+4. A conservative 128K fallback for a model nothing recognizes.
+
+The header names which one is in force (`ctx 6K/1000K provider`). Refreshing the model list with
+<kbd>Ctrl</kbd>+<kbd>R</kbd> in `/model` (or `jan cli models refresh`) is what populates step 2.
+
+## Usage and cost
+
+```
+/usage
+```
+
+Lists what this session has spent, one row per model plus a total: requests, prompt tokens in (and
+how many of those the provider served from its cache), tokens out, and an estimated cost.
+
+```
+session usage
+ tokamak/anthropic/claude-opus-5 12 req · 480K in (300K cached) · 21K out ~$1.42
+ total 12 req · 480K in (300K cached) · 21K out ~$1.42
+ estimated from the provider's published prices - not a bill
+```
+
+Unlike the context window - which describes a single request - these are sums over every request the
+session made, subagent requests included, because that is what a provider bills. Rows are per
+provider as well as per model: the same id served by two gateways is billed at two price lists.
+Prices come from the provider's own model listing, and a model it publishes only half a price list
+for is treated as unpriced - reported as `(no published price)` and left out of the total rather
+than counted as free. `/new` starts a new session, and a new count.
+
## Automatic compaction
As the conversation approaches the window, older turns are summarized to make room. The reserve is
diff --git a/docs/src/pages/docs/agent/providers.mdx b/docs/src/pages/docs/agent/providers.mdx
index ab10f3c45..757fbb7ff 100644
--- a/docs/src/pages/docs/agent/providers.mdx
+++ b/docs/src/pages/docs/agent/providers.mdx
@@ -69,8 +69,21 @@ move between fields and <kbd>k</kbd>/<kbd>j</kbd> type as ordinary characters (A
them). The base URL must be `https://`, or `http://` for a localhost endpoint, so a key is never
sent over a plaintext remote connection.
-A provider saved with no models is queried for its `GET /models` the next time you open `/model`,
-and the discovered ids are persisted - so a bare provider becomes selectable immediately.
+Providers with an entry in `~/.jan/config.toml` are queried for their `GET /models` the first time
+you open `/model` in a session, and newly discovered ids are persisted - so a provider saved with no
+models becomes selectable immediately, and one whose endpoint has gained models since you signed in
+picks them up. That automatic pass only ever *adds*: an id you configured by hand stays even if the
+endpoint stops listing it, since a permission-scoped key can answer with a subset. To take the
+endpoint's list as the truth and drop what it omits, ask for it - <kbd>Ctrl</kbd>+<kbd>R</kbd> in the
+picker, or `jan cli models refresh` headlessly. A refresh that retires the model `default_model`
+names says so in its summary.
+
+Providers inherited from Jan Desktop are never refreshed: there is no entry here to rewrite.
+
+Whatever the listing says about each model is cached in `~/.jan/model_catalog.json`. The context
+window drives the header gauge and compaction, and the per-token prices drive the cost lines in
+`/context` and `/usage`; the output cap is cached and echoed back by `jan cli models list`, but
+nothing reads it yet. That file is only a cache: delete it and the next refresh rebuilds it.
## Tokamak
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index de38ed8e9..12134aab9 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -50,6 +50,7 @@ See [Sessions](/docs/agent/sessions).
| `/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 |
| `/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 |
@@ -61,7 +62,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-
| Command | Description |
| --- | --- |
-| `/model [id]` | Switch model. Bare: pick interactively |
+| `/model [id]` | Switch model. Bare: pick interactively. Opening the picker re-lists each provider's models once per session; <kbd>Ctrl</kbd>+<kbd>R</kbd> inside it re-lists them again on demand |
| `/effort [low\|medium\|high]` | Set reasoning effort. Bare: show current; `low` is faster, `high` thinks deeper |
| `/mcp` | List, toggle, add, edit, and remove MCP servers; Enter opens a server's detail screen, where you can list its tools and sign in to it |
| `/plugin [list\|install <spec>\|remove <name>\|search [query]]` | Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace |
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rs
index 65b15b64b..15a959916 100644
--- a/src-tauri/jan-cli/src/main.rs
+++ b/src-tauri/jan-cli/src/main.rs
@@ -47,6 +47,7 @@ to opt out of both.",
jan --worktree # work in a dedicated git worktree, not your checkout\n \
jan cli agent run \"fix the failing test\" # run the agent non-interactively\n \
jan cli models list # show every configured provider model\n \
+ jan cli models refresh # re-read every provider's model list\n \
jan cli threads list # list saved conversation threads\n \
jan cli mcp list # list configured MCP servers\n \
jan cli mcp add my-server --command npx --arg -y --arg my-mcp \n \
@@ -462,6 +463,15 @@ enum ModelsCommands {
#[arg(long, default_value = ".")]
project: String,
},
+ /// Re-read every provider's /models endpoint, replacing the stored list
+ Refresh {
+ /// Only refresh this provider (e.g. tokamak)
+ #[arg(long)]
+ provider: Option<String>,
+ /// Project root whose agent.toml [provider] override is applied
+ #[arg(long, default_value = ".")]
+ project: String,
+ },
}
// ── MCP subcommands ────────────────────────────────────────────────────────
@@ -990,19 +1000,28 @@ async fn handle_models(cmd: ModelsCommands) {
std::process::exit(1);
}
};
+ let catalog = app_lib::core::cli::model_catalog::load();
let mut output: Vec<serde_json::Value> = configs
.values()
.filter(|c| app_lib::core::cli::providers::is_cli_reachable(c))
.filter(|c| provider.as_ref().is_none_or(|p| &c.provider == p))
.flat_map(|c| {
+ let catalog = &catalog;
c.models.iter().map(move |m| {
- serde_json::json!({
+ let mut entry = serde_json::json!({
"id": m,
"provider": c.provider,
"base_url": c.base_url,
"api_type": c.api_type,
"has_api_key": app_lib::core::cli::providers::has_credential(c),
- })
+ });
+ // Whatever the provider's own listing reported, when a
+ // refresh (or a sign-in) has cached it. Absent for a
+ // plain endpoint that lists ids and nothing else.
+ if let Some(info) = catalog.get(Some(&c.provider), m) {
+ entry["info"] = serde_json::to_value(info).unwrap_or_default();
+ }
+ entry
})
})
.collect();
@@ -1012,6 +1031,28 @@ async fn handle_models(cmd: ModelsCommands) {
});
println!("{}", serde_json::to_string_pretty(&output).unwrap());
}
+ ModelsCommands::Refresh { provider, project } => {
+ match app_lib::core::cli::providers::refresh_models(
+ Some(std::path::Path::new(&project)),
+ provider.as_deref(),
+ )
+ .await
+ {
+ Ok(refreshed) => {
+ println!("{}", refreshed.summary());
+ // A provider that could not be listed leaves its stored list
+ // in place, so the exit code has to say the refresh was
+ // partial or a script would read it as complete.
+ if !refreshed.failed.is_empty() {
+ std::process::exit(1);
+ }
+ }
+ Err(e) => {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ }
+ }
}
}
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index 9130e21f5..2752bb5d3 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -397,18 +397,22 @@ fn credentialed(config: &ProviderConfig) -> bool {
config.api_key.is_some() || !config.api_keys.is_empty()
}
-/// Resolve `model_id` to an upstream URL + key chain. The desktop build also
-/// resolves local engines (MLX session, llama-server router); the `cli` build is
-/// remote-only, so a model with no provider entry is unresolvable.
-pub(crate) async fn resolve_upstream_for_model(
+/// Which provider serves `model_id`, given the provider map. The single
+/// implementation of the routing order, so anything that *reports* on a
+/// request (its price, its context window, its header label) names the
+/// provider the request is actually sent to:
+///
+/// 1. a provider listing the id verbatim - reachable and credentialed first,
+/// then any, so a keyless twin does not shadow the signed-in entry;
+/// 2. a `<provider>/` prefix naming a configured provider;
+/// 3. a provider whose key *is* the model id (a local engine alias).
+///
+/// Sync and lock-free (the caller holds the map), so a render path or a price
+/// lookup can ask without awaiting the async resolver.
+pub(crate) fn pick_provider_for_model(
model_id: &str,
- provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
- #[cfg(not(feature = "cli"))] llama_state: Arc<LlamacppState>,
- #[cfg(not(feature = "cli"))] mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
-) -> Result<(String, Vec<String>), String> {
- let destination_path = "/chat/completions";
-
- let pc = provider_configs.lock().await;
+ pc: &HashMap<String, ProviderConfig>,
+) -> Option<String> {
let offers = |config: &ProviderConfig| config.models.iter().any(|m| m == model_id);
// The same model id can be listed by several providers, e.g. a cloud
@@ -432,7 +436,7 @@ pub(crate) async fn resolve_upstream_for_model(
#[cfg(not(feature = "cli"))]
let first_match = pc.iter().find(|(_, config)| offers(config));
- let provider_name = first_match
+ first_match
.map(|(_, config)| config.provider.clone())
.or_else(|| {
if let Some(sep_pos) = model_id.find('/') {
@@ -442,7 +446,22 @@ pub(crate) async fn resolve_upstream_for_model(
}
}
pc.get(model_id).map(|c| c.provider.clone())
- });
+ })
+}
+
+/// Resolve `model_id` to an upstream URL + key chain. The desktop build also
+/// resolves local engines (MLX session, llama-server router); the `cli` build is
+/// remote-only, so a model with no provider entry is unresolvable.
+pub(crate) async fn resolve_upstream_for_model(
+ model_id: &str,
+ provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
+ #[cfg(not(feature = "cli"))] llama_state: Arc<LlamacppState>,
+ #[cfg(not(feature = "cli"))] mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
+) -> Result<(String, Vec<String>), String> {
+ let destination_path = "/chat/completions";
+
+ let pc = provider_configs.lock().await;
+ let provider_name = pick_provider_for_model(model_id, &pc);
drop(pc);
if let Some(provider) = provider_name {
@@ -524,10 +543,22 @@ pub(crate) async fn resolve_upstream_for_model(
/// provider-qualified id (e.g. OpenCode GO) fail with "model not supported".
/// A slash inside a real model id (e.g. an org-scoped name) is left alone
/// unless the leading segment is literally a provider key.
+///
+/// A provider that lists the id verbatim wins over the prefix reading, exactly
+/// as resolution orders them: a gateway routing `anthropic/claude-opus-5` is
+/// serving a model whose id contains a slash, and stripping it because some
+/// *other* configured provider happens to be named `anthropic` sends an id the
+/// gateway has never heard of.
pub(crate) fn strip_provider_prefix(
model_id: &str,
provider_configs: &HashMap<String, ProviderConfig>,
) -> String {
+ if provider_configs
+ .values()
+ .any(|c| c.models.iter().any(|m| m == model_id))
+ {
+ return model_id.to_string();
+ }
if let Some(sep_pos) = model_id.find('/') {
let potential_provider: &str = &model_id[..sep_pos];
if provider_configs.contains_key(potential_provider) {
@@ -1916,6 +1947,23 @@ mod tests {
);
}
+ /// The gateway that serves `anthropic/claude-opus-5` lists it under that
+ /// full id; the desktop inherit also contributes a provider keyed
+ /// `anthropic`. Stripping there sends `claude-opus-5`, which the gateway
+ /// answers with 404 "model not found in accessible providers".
+ #[test]
+ fn a_verbatim_listed_id_keeps_its_slash_despite_a_same_named_provider() {
+ let mut pc = provider_configs(&[
+ ("tokamak", "https://api.tokamak.sh/v1"),
+ ("anthropic", "https://api.anthropic.com/v1"),
+ ]);
+ pc.get_mut("tokamak").unwrap().models = vec!["anthropic/claude-opus-5".to_string()];
+ assert_eq!(
+ strip_provider_prefix("anthropic/claude-opus-5", &pc),
+ "anthropic/claude-opus-5"
+ );
+ }
+
/// A bare model id (no slash) is returned unchanged.
#[test]
fn bare_model_id_is_unchanged() {
@@ -2247,6 +2295,70 @@ mod tests {
assert_eq!(keys, vec!["sk-opencode"]);
}
+ /// The reporting path (price, context window, header label) must name the
+ /// provider the request is routed to. A gateway listing a slashed id
+ /// verbatim wins over a provider whose key happens to match the prefix, on
+ /// both sides: reading the prefix first would price a Jan Router request
+ /// against an `anthropic` entry that publishes neither window nor price.
+ #[cfg(feature = "cli")]
+ #[tokio::test]
+ async fn a_verbatim_listed_slashed_id_is_reported_against_the_gateway_that_serves_it() {
+ let mut configs = provider_configs(&[
+ ("tokamak", "https://api.tokamak.sh/v1"),
+ ("anthropic", "https://api.anthropic.com/v1"),
+ ]);
+ configs.get_mut("tokamak").unwrap().models = vec!["anthropic/claude-opus-5".to_string()];
+
+ assert_eq!(
+ pick_provider_for_model("anthropic/claude-opus-5", &configs),
+ Some("tokamak".to_string())
+ );
+ let (url, _) =
+ resolve_upstream_for_model("anthropic/claude-opus-5", Arc::new(Mutex::new(configs)))
+ .await
+ .expect("the gateway listing the id serves it");
+ assert_eq!(url, "https://api.tokamak.sh/v1/chat/completions");
+ }
+
+ /// A provider credentialed through the `api_keys` chain rather than a bare
+ /// `api_key` is still the one routed to, so it must be the one reported:
+ /// naming its keyless twin prices the request at the wrong rates and, on
+ /// the window, against an entry that never published one.
+ #[cfg(feature = "cli")]
+ #[tokio::test]
+ async fn a_key_chain_credential_is_reported_like_it_is_routed() {
+ let mut configs = provider_configs(&[
+ ("aaa-keyless", "https://keyless.test/v1"),
+ ("zzz-keychain", "https://keychain.test/v1"),
+ ]);
+ configs.get_mut("aaa-keyless").unwrap().models = vec!["shared-model".to_string()];
+ let keychain = configs.get_mut("zzz-keychain").unwrap();
+ keychain.models = vec!["shared-model".to_string()];
+ keychain.api_keys = vec!["sk-chain".to_string()];
+
+ assert_eq!(
+ pick_provider_for_model("shared-model", &configs),
+ Some("zzz-keychain".to_string())
+ );
+ let (url, _) = resolve_upstream_for_model("shared-model", Arc::new(Mutex::new(configs)))
+ .await
+ .expect("the credentialed provider is selected");
+ assert_eq!(url, "https://keychain.test/v1/chat/completions");
+ }
+
+ /// A provider keyed by the model id (a local engine alias) is routable, so
+ /// the reporting path must name it too rather than leaving the row
+ /// unqualified and priced against whatever else lists the id.
+ #[cfg(feature = "cli")]
+ #[test]
+ fn a_provider_keyed_by_the_model_id_is_named() {
+ let configs = provider_configs(&[("my-local-model", "http://127.0.0.1:1337/v1")]);
+ assert_eq!(
+ pick_provider_for_model("my-local-model", &configs),
+ Some("my-local-model".to_string())
+ );
+ }
+
/// Holds the secret-store serialization guard, the temp data folder and the
/// `JAN_DATA_FOLDER` restore together, so an async test can keep all three
/// alive across `.await` without holding a bare lock guard over it.
diff --git a/src-tauri/src/core/cli/auth/providers.rs b/src-tauri/src/core/cli/auth/providers.rs
index 3a05b85d2..6a7e36537 100644
--- a/src-tauri/src/core/cli/auth/providers.rs
+++ b/src-tauri/src/core/cli/auth/providers.rs
@@ -51,6 +51,7 @@ pub fn logout(provider: &str) -> Result<(), LoginError> {
remove_provider(provider).map_err(|e| {
LoginError::Persist(format!("could not clear the provider configuration: {e}"))
})?;
+ crate::core::cli::model_catalog::forget(provider);
Ok(())
}
@@ -101,6 +102,7 @@ pub(crate) async fn discover_models(
definition.name
))
})?;
+ crate::core::cli::model_catalog::cache_listing(definition.id, &parsed);
Ok(parse_models(&parsed))
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 356f16c69..745c2df1d 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -11,6 +11,7 @@ pub mod journal;
pub mod login;
pub mod mcp;
mod model_capabilities;
+pub mod model_catalog;
mod path_refs;
pub mod run_report;
pub mod providers;
@@ -1005,6 +1006,9 @@ fn build_cli_orchestration_args(
pub(crate) struct PreparedRun {
pub args: OrchestrationArgs,
pub body: serde_json::Value,
+ /// The provider serving this run's model, for the per-provider price
+ /// lookup the JSON envelope's `estimated_cost_usd` goes through.
+ pub provider: Option<String>,
pub permission_requests: PermissionRegistry,
/// Background connect of `active` MCP servers, awaited before the first turn.
pub mcp_task: Option<tokio::task::JoinHandle<mcp::ConnectOutcome>>,
@@ -1053,6 +1057,10 @@ pub(crate) struct AgentSession {
pub args: OrchestrationArgs,
pub permission_requests: PermissionRegistry,
pub model: String,
+ /// The provider that will serve `model`, when one offers it. Carried so the
+ /// per-provider cached window and prices are read under the provider that
+ /// is actually billed, rather than whichever one the catalog finds first.
+ pub provider: Option<String>,
/// Fast model for the `smol` role (goal evaluation). Falls back to `model`.
pub smol_model: String,
pub limits: SessionLimits,
@@ -1342,6 +1350,11 @@ fn prepare_agent_session(
));
}
+ // Which provider will serve this model, resolved once here: the cached
+ // window and prices are per provider, and two gateways can list one id.
+ let serving_provider =
+ crate::core::cli::providers::provider_for_model(&model, &provider_configs);
+
// MCP servers marked `active` in mcp_config.json connect off-thread so setup/
// render isn't blocked on a cold stdio spawn. The caller awaits `mcp_task`
// before the first turn (tools are collected once per run), so a race with
@@ -1389,15 +1402,20 @@ fn prepare_agent_session(
flags.sandbox,
);
- // Resolution order: configured `[agent].context_window` override, then the
- // built-in model catalog, then the 128K fallback.
- let resolved_window =
- crate::core::cli::model_capabilities::resolve_context_window(&model, cfg.agent.context_window);
+ // Resolution order: configured `[agent].context_window` override, then what
+ // the provider's own `/models` listing reported, then the built-in model
+ // catalog, then the 128K fallback.
+ let resolved_window = crate::core::cli::model_capabilities::resolve_context_window(
+ &model,
+ cfg.agent.context_window,
+ crate::core::cli::model_capabilities::reported_window(serving_provider.as_deref(), &model),
+ );
Ok(AgentSession {
args,
permission_requests,
model,
+ provider: serving_provider,
smol_model,
limits: SessionLimits {
context_window: resolved_window.tokens,
@@ -1528,6 +1546,7 @@ fn prepare_agent_run(
Ok(PreparedRun {
args: session.args,
body,
+ provider: session.provider,
permission_requests: session.permission_requests,
mcp_task: session.mcp_task,
// Non-interactive runs persist into the same per-project store the TUI
@@ -1588,6 +1607,7 @@ async fn run_agent_loop(
let PreparedRun {
args,
body,
+ provider,
permission_requests,
mcp_task,
persist,
@@ -1598,6 +1618,7 @@ async fn run_agent_loop(
print_report(
format,
RunReport::setup_failure(&e).finish(
+ None,
None,
"",
started.elapsed().as_millis(),
@@ -1726,6 +1747,7 @@ async fn run_agent_loop(
format,
report.finish(
session_id.as_deref().map(short_id).as_deref(),
+ provider.as_deref(),
&model,
started.elapsed().as_millis(),
final_text.as_deref(),
diff --git a/src-tauri/src/core/cli/model_capabilities.rs b/src-tauri/src/core/cli/model_capabilities.rs
index 4574c96bd..bd9700b54 100644
--- a/src-tauri/src/core/cli/model_capabilities.rs
+++ b/src-tauri/src/core/cli/model_capabilities.rs
@@ -1,21 +1,25 @@
//! Pure per-model context-window resolution for the CLI.
//!
//! The effective context window comes from the selected model unless the
-//! project explicitly configures one. This module resolves that without any
-//! provider metadata request: a small fixed catalog of known model families
-//! covers the models Jan ships, and everything else falls back to a
-//! conservative default. The resolved value drives the header gauge and
+//! project explicitly configures one. Resolution is pure: the caller supplies
+//! the configured override and whatever the provider itself reported (cached in
+//! [`super::model_catalog`] from its `/models` listing, via [`reported_window`]),
+//! and a small fixed catalog of known model families covers the rest, with a
+//! conservative default under everything. The resolved value drives the header gauge and
//! proactive compaction, and is deliberately never sent up as a generation
//! parameter.
pub(crate) const FALLBACK_CONTEXT_WINDOW: u64 = 128_000;
/// Where a resolved context window came from. `Configured` is authoritative:
-/// `[agent].context_window` wins outright. `Catalog` is the built-in model
-/// family table. `Fallback` is the conservative default for an unknown model.
+/// `[agent].context_window` wins outright. `Provider` is the window the
+/// provider's own `/models` listing reported, which beats guessing. `Catalog`
+/// is the built-in model family table. `Fallback` is the conservative default
+/// for an unknown model.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ContextWindowSource {
Configured,
+ Provider,
Catalog,
Fallback,
}
@@ -31,6 +35,7 @@ impl ContextWindowSource {
pub(crate) fn label(self) -> &'static str {
match self {
ContextWindowSource::Configured => "configured",
+ ContextWindowSource::Provider => "provider",
ContextWindowSource::Catalog => "catalog",
ContextWindowSource::Fallback => "fallback",
}
@@ -92,12 +97,28 @@ fn catalog_window(model_id: &str) -> Option<u64> {
None
}
+/// The window the provider itself reported for `model_id`, from the cached
+/// `/models` listing. `None` when nothing was cached (a plain
+/// OpenAI-compatible endpoint reports only ids) or the model is unknown to it.
+///
+/// `provider` is the one that will actually serve the request: two gateways can
+/// list the same id with different deployments, so an unqualified lookup can
+/// report a window the request will not get.
+pub(crate) fn reported_window(provider: Option<&str>, model_id: &str) -> Option<u64> {
+ super::model_catalog::load()
+ .get(provider, model_id)
+ .and_then(|info| info.context_length)
+ .filter(|tokens| *tokens > 0)
+}
+
/// Resolve the effective context window for `model_id`. `configured` (from
-/// `[agent].context_window`) is authoritative when set; otherwise the built-in
-/// catalog is consulted; an unknown model gets the conservative fallback.
+/// `[agent].context_window`) is authoritative when set, then `reported` (what
+/// the provider's own listing said, via [`reported_window`]), then the built-in
+/// catalog; an unknown model gets the conservative fallback.
pub(crate) fn resolve_context_window(
model_id: &str,
configured: Option<u64>,
+ reported: Option<u64>,
) -> ResolvedContextWindow {
if let Some(tokens) = configured {
return ResolvedContextWindow {
@@ -105,6 +126,15 @@ pub(crate) fn resolve_context_window(
source: ContextWindowSource::Configured,
};
}
+ // The provider knows its own deployment: a gateway serving a 1M-window
+ // variant of a model the catalog knows at 200K is right and the table is
+ // wrong.
+ if let Some(tokens) = reported.filter(|t| *t > 0) {
+ return ResolvedContextWindow {
+ tokens,
+ source: ContextWindowSource::Provider,
+ };
+ }
let bare = strip_provider_qualifier(model_id);
match catalog_window(bare) {
Some(tokens) => ResolvedContextWindow {
@@ -124,7 +154,7 @@ mod tests {
#[test]
fn configured_window_overrides_every_catalog_entry() {
- let resolved = resolve_context_window("claude-sonnet-4-6", Some(333_000));
+ let resolved = resolve_context_window("claude-sonnet-4-6", Some(333_000), None);
assert_eq!(resolved.tokens, 333_000);
assert_eq!(resolved.source, ContextWindowSource::Configured);
}
@@ -132,20 +162,23 @@ mod tests {
#[test]
fn catalog_resolves_supported_model_families() {
assert_eq!(
- resolve_context_window("claude-sonnet-4-5", None).tokens,
+ resolve_context_window("claude-sonnet-4-5", None, None).tokens,
200_000
);
assert_eq!(
- resolve_context_window("claude-sonnet-4-6", None).tokens,
+ resolve_context_window("claude-sonnet-4-6", None, None).tokens,
1_000_000
);
- assert_eq!(resolve_context_window("gpt-5.2", None).tokens, 400_000);
assert_eq!(
- resolve_context_window("gpt-5.2-codex", None).tokens,
+ resolve_context_window("gpt-5.2", None, None).tokens,
+ 400_000
+ );
+ assert_eq!(
+ resolve_context_window("gpt-5.2-codex", None, None).tokens,
272_000
);
assert_eq!(
- resolve_context_window("gemini-3-pro", None).tokens,
+ resolve_context_window("gemini-3-pro", None, None).tokens,
1_000_000
);
}
@@ -153,15 +186,15 @@ mod tests {
#[test]
fn provider_qualifier_does_not_change_resolution() {
assert_eq!(
- resolve_context_window("anthropic/claude-sonnet-4-6", None),
- resolve_context_window("claude-sonnet-4-6", None),
+ resolve_context_window("anthropic/claude-sonnet-4-6", None, None),
+ resolve_context_window("claude-sonnet-4-6", None, None),
);
}
#[test]
fn unknown_model_uses_conservative_fallback() {
assert_eq!(
- resolve_context_window("private-gateway-model", None),
+ resolve_context_window("private-gateway-model", None, None),
ResolvedContextWindow {
tokens: 128_000,
source: ContextWindowSource::Fallback,
@@ -169,12 +202,43 @@ mod tests {
);
}
+ /// What the provider reports beats the built-in table, and loses only to an
+ /// explicit `[agent].context_window`.
+ #[test]
+ fn a_provider_reported_window_outranks_the_catalog() {
+ let resolved = resolve_context_window("claude-sonnet-4-5", None, Some(1_000_000));
+ assert_eq!(resolved.tokens, 1_000_000);
+ assert_eq!(resolved.source, ContextWindowSource::Provider);
+
+ assert_eq!(
+ resolve_context_window("claude-sonnet-4-5", Some(50_000), Some(1_000_000)),
+ ResolvedContextWindow {
+ tokens: 50_000,
+ source: ContextWindowSource::Configured,
+ }
+ );
+ // A model the table has never heard of stops falling back to 128K the
+ // moment its provider says otherwise.
+ assert_eq!(
+ resolve_context_window("openai/gpt-oss-120b-medium", None, Some(131_072)),
+ ResolvedContextWindow {
+ tokens: 131_072,
+ source: ContextWindowSource::Provider,
+ }
+ );
+ // A nonsense report is ignored rather than yielding a zero window.
+ assert_eq!(
+ resolve_context_window("claude-sonnet-4-5", None, Some(0)).source,
+ ContextWindowSource::Catalog
+ );
+ }
+
#[test]
fn non_catalog_provider_qualifier_is_not_stripped() {
// A provider Jan doesn't ship keeps its qualifier: the id must still
// fall through to the conservative default rather than mis-matching.
assert_eq!(
- resolve_context_window("azure/claude-sonnet-4-6", None).source,
+ resolve_context_window("azure/claude-sonnet-4-6", None, None).source,
ContextWindowSource::Fallback,
);
}
diff --git a/src-tauri/src/core/cli/model_catalog.rs b/src-tauri/src/core/cli/model_catalog.rs
new file mode 100644
index 000000000..d43382791
--- /dev/null
+++ b/src-tauri/src/core/cli/model_catalog.rs
@@ -0,0 +1,586 @@
+//! Per-model metadata cached from a provider's `/models` listing.
+//!
+//! `~/.jan/config.toml` records a provider's model **ids**, and that is all the
+//! agent needs to route a request. A router-style endpoint reports much more
+//! per model -- `context_length`, `max_completion_tokens` and per-token
+//! `pricing` -- which is exactly what the header gauge, `/context` and
+//! `/usage` would otherwise have to guess at (see
+//! [`super::model_capabilities`], whose catalog is a hand-maintained table of
+//! model families).
+//!
+//! That metadata lives here, in `~/.jan/model_catalog.json`, rather than in
+//! `config.toml`: the config is hand-edited and a pricing block per model would
+//! bury the three lines a user actually writes. This file is a **cache** --
+//! deleting it costs nothing but a refresh, and nothing here is a secret.
+
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+
+/// What a provider reports about one model. Every field is optional: a plain
+/// OpenAI-compatible endpoint reports nothing but the id, and a partial answer
+/// is still worth caching.
+#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct ModelInfo {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub display_name: Option<String>,
+ /// Total context window in tokens.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context_length: Option<u64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max_output_tokens: Option<u64>,
+ /// USD per token, as the provider prices them.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub prompt_usd: Option<f64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub completion_usd: Option<f64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cache_read_usd: Option<f64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cache_write_usd: Option<f64>,
+}
+
+impl ModelInfo {
+ /// Whether anything was actually learned. An entry that carries nothing is
+ /// not written: it would only make a later refresh look like a change.
+ fn is_empty(&self) -> bool {
+ *self == ModelInfo::default()
+ }
+
+ /// Whether this model can be priced at all. Both sides are required: a
+ /// listing publishing only `completion` would otherwise bill every input
+ /// token at $0 and print that as an ordinary estimate, which reads as a
+ /// cheap model rather than as the half-answer it is. Cache rates alone
+ /// cannot cost a request either, so they do not count.
+ pub fn has_pricing(&self) -> bool {
+ 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.
+ 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)
+ }
+}
+
+/// Billable tokens accounted for across a run or a session, summed per
+/// request. Unlike a context-window fill -- which is the latest request alone
+/// -- these are sums: a provider bills every request for the whole prompt it
+/// resends, so the spend is the sum.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct TokenUsage {
+ pub requests: u64,
+ pub prompt_tokens: u64,
+ pub completion_tokens: u64,
+ pub cached_tokens: u64,
+ pub cache_write_tokens: u64,
+}
+
+impl TokenUsage {
+ /// Fold in one request's reported usage. A provider that omits a field
+ /// contributes nothing for it rather than resetting the total.
+ pub fn add(&mut self, usage: &crate::core::agent::events::Usage) {
+ self.requests += 1;
+ self.prompt_tokens += usage.prompt_tokens.unwrap_or(0);
+ self.completion_tokens += usage.completion_tokens.unwrap_or(0);
+ self.cached_tokens += usage.cached_tokens.unwrap_or(0);
+ self.cache_write_tokens += usage.cache_write_tokens.unwrap_or(0);
+ }
+
+ pub fn merge(&mut self, other: &TokenUsage) {
+ self.requests += other.requests;
+ self.prompt_tokens += other.prompt_tokens;
+ self.completion_tokens += other.completion_tokens;
+ self.cached_tokens += other.cached_tokens;
+ self.cache_write_tokens += other.cache_write_tokens;
+ }
+
+ pub fn total_tokens(&self) -> u64 {
+ self.prompt_tokens + self.completion_tokens
+ }
+
+ /// Estimated USD, or `None` when the provider published no prices for this
+ /// model -- a missing price is never billed as free.
+ pub fn cost_usd(&self, info: Option<&ModelInfo>) -> Option<f64> {
+ let info = info.filter(|i| i.has_pricing())?;
+ Some(info.cost_usd(
+ self.prompt_tokens,
+ self.completion_tokens,
+ self.cached_tokens,
+ self.cache_write_tokens,
+ ))
+ }
+}
+
+/// The single entry across `maps` whose id matches `model_id` once the
+/// `<vendor>/` qualifier is stripped from either side. Two vendors serving the
+/// same bare name is an ambiguity, not a hit.
+fn unique_bare_match<'a>(
+ maps: impl Iterator<Item = &'a BTreeMap<String, ModelInfo>>,
+ model_id: &str,
+) -> Option<&'a ModelInfo> {
+ let bare = model_id.rsplit('/').next().unwrap_or(model_id);
+ let mut matches = maps
+ .flatten()
+ .filter(|(id, _)| id.rsplit('/').next() == Some(bare));
+ let first = matches.next()?;
+ matches.next().is_none().then_some(first.1)
+}
+
+/// The whole cache: provider id -> model id -> metadata.
+#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct Catalog {
+ #[serde(default)]
+ providers: BTreeMap<String, BTreeMap<String, ModelInfo>>,
+}
+
+fn catalog_path() -> Result<PathBuf, String> {
+ Ok(crate::core::agent::global_config::global_jan_dir()?.join("model_catalog.json"))
+}
+
+/// Read the cache. A missing or unreadable file is an empty catalog, never an
+/// error: this is metadata that improves a display, so a corrupt cache must
+/// never block a run.
+pub fn load() -> Catalog {
+ let Ok(path) = catalog_path() else {
+ return Catalog::default();
+ };
+ std::fs::read_to_string(path)
+ .ok()
+ .and_then(|raw| serde_json::from_str(&raw).ok())
+ .unwrap_or_default()
+}
+
+impl Catalog {
+ /// Replace one provider's entries, dropping the provider when it reported
+ /// nothing worth keeping.
+ pub fn set_provider(&mut self, provider: &str, models: BTreeMap<String, ModelInfo>) {
+ if models.is_empty() {
+ self.providers.remove(provider);
+ } else {
+ self.providers.insert(provider.to_string(), models);
+ }
+ }
+
+ pub fn remove_provider(&mut self, provider: &str) {
+ self.providers.remove(provider);
+ }
+
+ /// Metadata for `model_id` as `provider` reports it, matching the exact id
+ /// first and then a unique match on the bare id behind a `<vendor>/`
+ /// qualifier, since a user may name a model either way.
+ ///
+ /// When `provider` is cached, its answer is the whole answer: two providers
+ /// can serve one id at different prices, so falling through to another
+ /// one's entry would bill a request at rates nobody quoted. Only a provider
+ /// the catalog has never seen (or no provider at all) searches the rest,
+ /// and then only for an unambiguous hit.
+ pub fn get(&self, provider: Option<&str>, model_id: &str) -> Option<&ModelInfo> {
+ if let Some(models) = provider.and_then(|p| self.providers.get(p)) {
+ return models
+ .get(model_id)
+ .or_else(|| unique_bare_match(std::iter::once(models), model_id));
+ }
+ let mut exact = self.providers.values().filter_map(|m| m.get(model_id));
+ if let Some(found) = exact.next() {
+ // One provider knowing the id is an answer; several disagreeing
+ // about its price is not, and there is nothing here to choose by.
+ return exact.next().is_none().then_some(found);
+ }
+ unique_bare_match(self.providers.values(), model_id)
+ }
+
+ /// Persist the cache, creating `~/.jan` if needed.
+ pub fn save(&self) -> Result<(), String> {
+ let path = catalog_path()?;
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
+ }
+ let body = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
+ std::fs::write(&path, body).map_err(|e| format!("{}: {e}", path.display()))
+ }
+
+ #[cfg(test)]
+ fn provider_ids(&self, provider: &str) -> Vec<String> {
+ self.providers
+ .get(provider)
+ .map(|m| m.keys().cloned().collect())
+ .unwrap_or_default()
+ }
+}
+
+/// Cache whatever `listing` (a raw `/models` body) says about `provider`'s
+/// models. Best-effort by contract: this metadata only ever improves a readout,
+/// so a sign-in must never fail over it.
+pub fn cache_listing(provider: &str, listing: &serde_json::Value) {
+ let models = parse_listing(listing);
+ if models.is_empty() {
+ return;
+ }
+ let mut catalog = load();
+ catalog.set_provider(provider, models);
+ if let Err(e) = catalog.save() {
+ log::warn!("could not cache model metadata for '{provider}': {e}");
+ }
+}
+
+/// Drop a provider's cached metadata, for a sign-out that removed its entry.
+pub fn forget(provider: &str) {
+ let mut catalog = load();
+ catalog.remove_provider(provider);
+ let _ = catalog.save();
+}
+
+/// Per-model metadata from a `/models` payload, keyed by id. Ids with nothing
+/// to record are omitted, so a plain OpenAI-compatible endpoint yields an empty
+/// map rather than a row of empty entries.
+pub fn parse_listing(value: &serde_json::Value) -> BTreeMap<String, ModelInfo> {
+ let entries = value
+ .get("data")
+ .and_then(|d| d.as_array())
+ .or_else(|| value.as_array());
+ let Some(entries) = entries else {
+ return BTreeMap::new();
+ };
+ entries
+ .iter()
+ .filter_map(|entry| {
+ let id = entry
+ .get("id")
+ .and_then(|id| id.as_str())
+ .map(str::trim)
+ .filter(|id| !id.is_empty())?;
+ let info = model_info(entry);
+ (!info.is_empty()).then(|| (id.to_string(), info))
+ })
+ .collect()
+}
+
+fn model_info(entry: &serde_json::Value) -> ModelInfo {
+ let pricing = entry.get("pricing");
+ let rate = |key: &str| pricing.and_then(|p| p.get(key)).and_then(number);
+ ModelInfo {
+ display_name: entry
+ .get("model_display_name")
+ .or_else(|| entry.get("display_name"))
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|v| !v.is_empty())
+ .map(String::from),
+ context_length: entry
+ .get("context_length")
+ .or_else(|| entry.get("context_window"))
+ .and_then(number)
+ .map(|v| v as u64),
+ max_output_tokens: entry
+ .get("max_completion_tokens")
+ .or_else(|| entry.get("max_output_tokens"))
+ .and_then(number)
+ .map(|v| v as u64),
+ prompt_usd: rate("prompt"),
+ completion_usd: rate("completion"),
+ cache_read_usd: rate("input_cache_read"),
+ cache_write_usd: rate("input_cache_write"),
+ }
+}
+
+/// A JSON number, or a number written as a string. Every price in the Jan
+/// Router listing is a string (`"0.0000008"`), while `context_length` is a
+/// number, and other gateways swap which is which.
+fn number(value: &serde_json::Value) -> Option<f64> {
+ value
+ .as_f64()
+ .or_else(|| value.as_str()?.trim().parse::<f64>().ok())
+ .filter(|v| v.is_finite() && *v >= 0.0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::core::agent::global_config::with_temp_home;
+ use serde_json::json;
+
+ /// One entry in the shape the Jan Router serves: pricing as strings, window
+ /// and output cap as numbers.
+ fn router_entry(id: &str) -> serde_json::Value {
+ json!({
+ "id": id,
+ "object": "model",
+ "owned_by": "Jan Router",
+ "model_display_name": "claude-opus-5",
+ "pricing": {
+ "currency": "USD",
+ "prompt": "0.000005",
+ "completion": "0.000025",
+ "input_cache_read": "0.0000005",
+ "input_cache_write": "0.00000625",
+ "per_million_tokens": {"prompt": "5"}
+ },
+ "context_length": 1000000,
+ "max_completion_tokens": 128000
+ })
+ }
+
+ #[test]
+ fn parses_the_router_listing_shape() {
+ let listing = json!({"object": "list", "data": [router_entry("anthropic/claude-opus-5")]});
+ let parsed = parse_listing(&listing);
+ let info = parsed.get("anthropic/claude-opus-5").expect("entry");
+ assert_eq!(info.display_name.as_deref(), Some("claude-opus-5"));
+ assert_eq!(info.context_length, Some(1_000_000));
+ assert_eq!(info.max_output_tokens, Some(128_000));
+ assert_eq!(info.prompt_usd, Some(0.000005));
+ assert_eq!(info.completion_usd, Some(0.000025));
+ assert_eq!(info.cache_read_usd, Some(0.0000005));
+ assert_eq!(info.cache_write_usd, Some(0.00000625));
+ }
+
+ /// A plain OpenAI-compatible endpoint reports ids and nothing else; it must
+ /// produce no entries rather than a row of empty ones.
+ #[test]
+ fn a_bare_listing_yields_no_entries() {
+ assert!(parse_listing(&json!({"data": [{"id": "m-a"}, {"id": "m-b"}]})).is_empty());
+ assert!(parse_listing(&json!(["m-a"])).is_empty());
+ assert!(parse_listing(&json!({"unexpected": 1})).is_empty());
+ }
+
+ /// Numbers and numeric strings are both accepted, and a nonsense price is
+ /// dropped rather than poisoning a cost estimate.
+ #[test]
+ fn numeric_strings_are_accepted_and_junk_is_dropped() {
+ let parsed = parse_listing(&json!({"data": [
+ {"id": "a", "context_length": "200000", "pricing": {"prompt": 0.001, "completion": "n/a"}},
+ ]}));
+ let info = parsed.get("a").expect("entry");
+ assert_eq!(info.context_length, Some(200_000));
+ assert_eq!(info.prompt_usd, Some(0.001));
+ assert_eq!(info.completion_usd, None);
+ // Half a price list cannot cost a request; the entry is still cached
+ // for its window.
+ assert!(!info.has_pricing());
+ }
+
+ fn priced() -> ModelInfo {
+ ModelInfo {
+ prompt_usd: Some(0.000005),
+ completion_usd: Some(0.000025),
+ cache_read_usd: Some(0.0000005),
+ cache_write_usd: Some(0.00000625),
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn cost_bills_cached_prompt_tokens_at_the_cache_rate() {
+ let info = priced();
+ // 1000 prompt tokens, of which 800 were cache reads and 200 cache
+ // writes -- both shares of the prompt, per the normalized usage shape.
+ let expected = 800.0 * 0.0000005 + 200.0 * 0.00000625 + 100.0 * 0.000025;
+ assert!((info.cost_usd(1000, 100, 800, 200) - expected).abs() < 1e-12);
+ // With no cache rates both shares fall back to the prompt rate, so a
+ // provider pricing only prompt/completion bills the whole prompt once.
+ let flat = ModelInfo {
+ prompt_usd: Some(0.001),
+ completion_usd: Some(0.0),
+ ..Default::default()
+ };
+ assert!((flat.cost_usd(1000, 500, 400, 200) - 1.0).abs() < 1e-12);
+ }
+
+ /// The shape every pipeline produces: `prompt_tokens` already contains the
+ /// cache-creation tokens, so they must be billed once, at the write rate.
+ #[test]
+ fn cache_write_tokens_are_a_share_of_the_prompt_not_an_addition() {
+ let info = priced();
+ // 100 fresh input + 2000 cache creation reported as prompt_tokens 2100.
+ let expected = 100.0 * 0.000005 + 2000.0 * 0.00000625 + 100.0 * 0.000025;
+ let cost = info.cost_usd(2100, 100, 0, 2000);
+ assert!((cost - expected).abs() < 1e-12, "{cost} != {expected}");
+ // Billing the writes twice is what this pins against.
+ assert!(cost < expected + 2000.0 * 0.000005 - 1e-12);
+ }
+
+ /// Counts that exceed the prompt (a provider reporting the Anthropic shape
+ /// unnormalized) must clamp rather than underflow the fresh remainder.
+ #[test]
+ fn shares_larger_than_the_prompt_cannot_underflow() {
+ let info = priced();
+ assert!((info.cost_usd(100, 0, 500, 0) - 100.0 * 0.0000005).abs() < 1e-12);
+ assert!((info.cost_usd(100, 0, 0, 500) - 100.0 * 0.00000625).abs() < 1e-12);
+ let both = info.cost_usd(100, 0, 80, 500);
+ assert!((both - (80.0 * 0.0000005 + 20.0 * 0.00000625)).abs() < 1e-12);
+ }
+
+ /// Half a price list is not a price list: billing input at $0 would print
+ /// a confident, wrong estimate instead of "no published price".
+ #[test]
+ fn a_half_published_price_is_not_pricing() {
+ let completion_only = ModelInfo {
+ completion_usd: Some(0.000025),
+ ..Default::default()
+ };
+ assert!(!completion_only.has_pricing());
+ let prompt_only = ModelInfo {
+ prompt_usd: Some(0.000005),
+ ..Default::default()
+ };
+ assert!(!prompt_only.has_pricing());
+ let usage = TokenUsage {
+ prompt_tokens: 1000,
+ completion_tokens: 100,
+ ..Default::default()
+ };
+ assert_eq!(usage.cost_usd(Some(&completion_only)), None);
+ assert!(usage.cost_usd(Some(&priced())).is_some());
+ }
+
+ #[test]
+ fn a_model_with_no_pricing_cannot_be_costed() {
+ let info = ModelInfo {
+ context_length: Some(1000),
+ ..Default::default()
+ };
+ assert!(!info.has_pricing());
+ assert_eq!(info.cost_usd(1000, 1000, 0, 0), 0.0);
+ }
+
+ #[test]
+ fn lookup_prefers_the_named_provider_then_falls_back_to_the_bare_id() {
+ let mut catalog = Catalog::default();
+ catalog.set_provider(
+ "tokamak",
+ BTreeMap::from([(
+ "anthropic/claude-opus-5".to_string(),
+ ModelInfo {
+ context_length: Some(1_000_000),
+ ..Default::default()
+ },
+ )]),
+ );
+ assert_eq!(
+ catalog
+ .get(Some("tokamak"), "anthropic/claude-opus-5")
+ .and_then(|i| i.context_length),
+ Some(1_000_000)
+ );
+ // A provider that knows nothing still resolves through the global pass.
+ assert!(catalog
+ .get(Some("other"), "anthropic/claude-opus-5")
+ .is_some());
+ // The bare id resolves while it is unambiguous.
+ assert!(catalog.get(None, "claude-opus-5").is_some());
+ assert!(catalog.get(None, "nothing-like-this").is_none());
+ }
+
+ /// Two providers can serve one id at two prices, and a request is billed by
+ /// exactly one of them. A cached provider's own answer is therefore the
+ /// whole answer, and an unqualified lookup across disagreeing providers is
+ /// no answer at all rather than whichever sorts first.
+ #[test]
+ fn a_price_is_never_taken_from_another_provider() {
+ let entry = |usd| {
+ BTreeMap::from([(
+ "gpt-4o".to_string(),
+ ModelInfo {
+ prompt_usd: Some(usd),
+ completion_usd: Some(usd),
+ ..Default::default()
+ },
+ )])
+ };
+ let mut catalog = Catalog::default();
+ catalog.set_provider("a-cheap", entry(0.000001));
+ catalog.set_provider("z-dear", entry(0.00001));
+ assert_eq!(
+ catalog
+ .get(Some("z-dear"), "gpt-4o")
+ .and_then(|i| i.prompt_usd),
+ Some(0.00001)
+ );
+ assert!(
+ catalog.get(None, "gpt-4o").is_none(),
+ "with no provider named there is nothing to choose by"
+ );
+ // A provider that offers the model but has never been listed still
+ // falls through, since there is no answer of its own to prefer.
+ catalog.set_provider(
+ "only-vendor",
+ BTreeMap::from([("solo".to_string(), ModelInfo::default())]),
+ );
+ assert!(catalog.get(Some("only-vendor"), "gpt-4o").is_none());
+ assert!(catalog.get(Some("never-listed"), "solo").is_some());
+ }
+
+ /// Two vendors serving the same bare name is an ambiguity: guessing one
+ /// would silently price a request against the wrong model.
+ #[test]
+ fn an_ambiguous_bare_id_resolves_to_nothing() {
+ let entry = |usd| {
+ BTreeMap::from([(
+ format!("{usd}/shared-name"),
+ ModelInfo {
+ prompt_usd: Some(1.0),
+ ..Default::default()
+ },
+ )])
+ };
+ let mut catalog = Catalog::default();
+ catalog.set_provider("a", entry("vendor-a"));
+ catalog.set_provider("b", entry("vendor-b"));
+ assert!(catalog.get(None, "shared-name").is_none());
+ assert!(catalog.get(None, "vendor-a/shared-name").is_some());
+ }
+
+ #[test]
+ fn the_catalog_round_trips_through_disk() {
+ with_temp_home(|_| {
+ assert_eq!(load(), Catalog::default(), "a missing cache is empty");
+ let mut catalog = Catalog::default();
+ catalog.set_provider(
+ "tokamak",
+ parse_listing(&json!({"data": [router_entry("anthropic/claude-opus-5")]})),
+ );
+ catalog.save().expect("save");
+ let reloaded = load();
+ assert_eq!(reloaded, catalog);
+ assert_eq!(
+ reloaded.provider_ids("tokamak"),
+ vec!["anthropic/claude-opus-5".to_string()]
+ );
+
+ // A provider that reports nothing is dropped rather than left stale.
+ let mut catalog = reloaded;
+ catalog.set_provider("tokamak", BTreeMap::new());
+ catalog.save().expect("save");
+ assert!(load().provider_ids("tokamak").is_empty());
+ });
+ }
+
+ /// A corrupt cache must degrade to "no metadata", never to an error: it only
+ /// ever improves a readout.
+ #[test]
+ fn a_corrupt_cache_reads_as_empty() {
+ with_temp_home(|_| {
+ let path = catalog_path().unwrap();
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, "{not json").unwrap();
+ assert_eq!(load(), Catalog::default());
+ });
+ }
+}
diff --git a/src-tauri/src/core/cli/providers.rs b/src-tauri/src/core/cli/providers.rs
index 05e14aa99..2bd8931ea 100644
--- a/src-tauri/src/core/cli/providers.rs
+++ b/src-tauri/src/core/cli/providers.rs
@@ -114,6 +114,17 @@ pub fn is_cli_reachable(config: &ProviderConfig) -> bool {
config.base_url.as_deref().is_some_and(|u| !u.is_empty())
}
+/// Which provider serves `model`. Delegates to the routing order itself
+/// (`agent::upstream::pick_provider_for_model`) rather than restating it, so a
+/// price, a context window or a header label can never name a provider other
+/// than the one the request is sent to. `None` when nothing offers the model.
+///
+/// Sync and lock-free (the caller holds the map), so a render path or a price
+/// lookup can ask without awaiting the upstream resolver.
+pub fn provider_for_model(model: &str, pc: &HashMap<String, ProviderConfig>) -> Option<String> {
+ crate::core::agent::upstream::pick_provider_for_model(model, pc)
+}
+
/// Log a provider-config load failure at most once per process. Startup probes
/// this in two independent places (the headless sign-in guard and the model
/// fallback), and a malformed `~/.jan/config.toml` fails both, so without this
@@ -256,56 +267,211 @@ pub fn list_provider_models(project_root: Option<&std::path::Path>) -> Vec<(Stri
}
}
-/// Populate model lists for providers that have none configured
-/// (e.g. a provider just added via the `/settings` wizard with the models field
-/// left blank). For each reachable provider with an empty `models` list, query
-/// its OpenAI-compatible `GET {base_url}/models` endpoint and persist the
-/// discovered ids back to `~/.jan/config.toml`, mirroring how `/login` records
-/// Tokamak's model list. Returns `true` if at least one provider was populated.
-/// An unreachable endpoint is not fatal: it yields a warning and is skipped, so
-/// a dead credential never blocks the picker. The configured list is preserved
-/// when a provider already names models (the user's explicit choice wins), and
-/// only providers present in the global store are touched -- writing a
-/// models-only entry for a Desktop-inherited provider would shadow it.
-/// `already_probed` records which `(provider, base_url)` pairs were queried,
-/// so each is touched at most once per session: a dead upstream is not
-/// re-contacted on every picker open.
-pub async fn fetch_missing_models(
+/// One provider's model-list probe outcome, for the caller to report.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ProviderModels {
+ pub provider: String,
+ /// How many ids are configured for this provider after the probe.
+ pub models: usize,
+ /// Whether that differed from what was already configured. A refresh that
+ /// changes nothing is worth saying so rather than reading as a no-op.
+ pub changed: bool,
+ /// Configured ids the endpoint did not list, which an additive probe keeps.
+ /// Reported rather than dropped: see [`Roster::Additive`].
+ pub kept_unlisted: usize,
+}
+
+/// What a probe does with configured ids the endpoint did not list.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Roster {
+ /// The answer is the roster: an id it omits is dropped. Only the explicit
+ /// refresh, which the user asked for and whose summary reports the result.
+ Replace,
+ /// New ids are added and configured ones are kept. Merely opening `/model`
+ /// runs a probe, and a permission-scoped or paginated `/models` answering
+ /// with a subset must not delete a hand-added alias from
+ /// `~/.jan/config.toml` with no confirmation and no way to re-add it.
+ Additive,
+}
+
+/// What a model-list probe did across every provider it touched.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ModelRefresh {
+ /// Providers whose endpoint answered, in name order.
+ pub listed: Vec<ProviderModels>,
+ /// `(provider, reason)` for each endpoint that could not be listed. Never
+ /// fatal: one dead credential must not block the rest.
+ pub failed: Vec<(String, String)>,
+ /// `default_model`, when this refresh is what stopped a provider from
+ /// offering it. A retired model otherwise surfaces as a 404 on the next
+ /// run, with nothing to connect it to the refresh that dropped it.
+ pub retired_default: Option<String>,
+}
+
+impl ModelRefresh {
+ /// Whether anything was written to disk.
+ pub fn changed_any(&self) -> bool {
+ self.listed.iter().any(|p| p.changed)
+ }
+
+ /// One-line summary for a note or a terminal line.
+ pub fn summary(&self) -> String {
+ let mut parts: Vec<String> = self
+ .listed
+ .iter()
+ .map(|p| {
+ let suffix = if p.changed { "" } else { ", unchanged" };
+ let plural = if p.models == 1 { "" } else { "s" };
+ let kept = if p.kept_unlisted > 0 {
+ format!(
+ ", {} kept but no longer listed - `jan cli models refresh` drops them",
+ p.kept_unlisted
+ )
+ } else {
+ String::new()
+ };
+ format!("{}: {} model{plural}{suffix}{kept}", p.provider, p.models)
+ })
+ .collect();
+ parts.extend(
+ self.failed
+ .iter()
+ .map(|(provider, reason)| format!("{provider}: {reason}")),
+ );
+ if let Some(model) = &self.retired_default {
+ parts.push(format!(
+ "default model '{model}' is no longer offered - select a different model"
+ ));
+ }
+ if parts.is_empty() {
+ "no providers to refresh".to_string()
+ } else {
+ parts.join(" · ")
+ }
+ }
+}
+
+/// Re-list every reachable provider that has not been probed yet this session,
+/// **adding** what its endpoint serves now to the stored model list. This is
+/// what `/model` runs on its first open: a roster captured at sign-in goes stale
+/// as a router-style endpoint gains and retires models, and the picker is where
+/// that is noticed.
+///
+/// Additive because the user only asked to *see* the picker: a subset answer
+/// (a permission-scoped key, a paginated gateway) would otherwise delete
+/// configured ids unprompted. Dropping one is [`refresh_models`]'s job.
+///
+/// `already_probed` records which `(provider, base_url)` pairs were queried, so
+/// each is touched at most once per session -- a dead upstream must not cost the
+/// picker its full request timeout on every open. The explicit
+/// [`refresh_models`] has no such guard.
+pub async fn refresh_models_once(
project_root: Option<&std::path::Path>,
already_probed: &mut std::collections::HashSet<String>,
-) -> Result<bool, String> {
+) -> Result<ModelRefresh, String> {
+ probe_models(project_root, Roster::Additive, |config| {
+ mark_probed(already_probed, config)
+ })
+ .await
+}
+
+/// Re-list every reachable provider (or just `provider`) and rewrite its model
+/// list, **replacing** a configured one. This is the explicit "my provider added
+/// models since I signed in" action -- a router-style endpoint gains and retires
+/// models continuously, and nothing else in the CLI ever re-reads `/models`
+/// after the list is first populated.
+///
+/// Unlike [`refresh_models_once`] there is no once-per-session guard: the user
+/// asked. Per-model metadata (`context_length`, pricing) is cached alongside in
+/// `~/.jan/model_catalog.json` -- see [`super::model_catalog`].
+pub async fn refresh_models(
+ project_root: Option<&std::path::Path>,
+ provider: Option<&str>,
+) -> Result<ModelRefresh, String> {
+ let mut refresh = probe_models(project_root, Roster::Replace, |config| {
+ provider.is_none_or(|name| config.provider == name)
+ })
+ .await?;
+ // A `--provider` that matched nothing is a failed refresh, not an empty
+ // one: without this the caller prints "no providers to refresh" and exits
+ // 0, so a typo (or a Desktop-inherited name, which has no entry in
+ // `~/.jan/config.toml` to rewrite) reads to a script as a complete refresh.
+ if let Some(name) = provider {
+ if refresh.listed.is_empty() && refresh.failed.is_empty() {
+ refresh
+ .failed
+ .push((name.to_string(), unrefreshable_reason(project_root, name)));
+ }
+ }
+ Ok(refresh)
+}
+
+/// Why `provider` could not be refreshed, for the report above. Reads only
+/// local config: the endpoint was never reached.
+fn unrefreshable_reason(project_root: Option<&std::path::Path>, provider: &str) -> String {
+ let known = load_provider_configs(project_root, &ProviderOverrides::default().with_env())
+ .ok()
+ .and_then(|configs| configs.get(provider).cloned());
+ let Some(config) = known else {
+ return "not a configured provider".to_string();
+ };
+ if !is_cli_reachable(&config) {
+ return "no base_url, so the CLI cannot reach it".to_string();
+ }
+ match load_global_config() {
+ Ok(global) if !global.contains_key(provider) => {
+ "inherited from Jan Desktop, so there is no ~/.jan/config.toml entry to refresh"
+ .to_string()
+ }
+ _ => "could not be listed".to_string(),
+ }
+}
+
+/// Record `config` in the once-per-session probe set, answering whether it had
+/// not been probed yet.
+fn mark_probed(
+ already_probed: &mut std::collections::HashSet<String>,
+ config: &ProviderConfig,
+) -> bool {
+ let tag = format!(
+ "{}|{}",
+ config.provider,
+ config.base_url.clone().unwrap_or_default()
+ );
+ already_probed.insert(tag)
+}
+
+/// Query `GET {base_url}/models` for every reachable global provider `select`
+/// accepts, and persist what comes back: ids into `~/.jan/config.toml` and
+/// per-model metadata into the model catalog.
+///
+/// Only providers present in the global store are touched -- writing a
+/// models-only entry for a Desktop-inherited provider would shadow it. An
+/// endpoint that cannot be listed is reported in [`ModelRefresh::failed`] rather
+/// than failing the call, so one dead credential never blocks the others.
+async fn probe_models(
+ project_root: Option<&std::path::Path>,
+ roster: Roster,
+ mut select: impl FnMut(&ProviderConfig) -> bool,
+) -> Result<ModelRefresh, String> {
let global = load_global_config()?;
let configs = load_provider_configs(project_root, &ProviderOverrides::default().with_env())?;
- let to_fetch: Vec<(String, String, Vec<String>)> = configs
+ let mut to_fetch: Vec<(ProviderConfig, Vec<String>)> = configs
.values()
- .filter(|c| {
- global.contains_key(&c.provider) && is_cli_reachable(c) && c.models.is_empty()
- })
- // Probe each provider at most once per session. A provider that still
- // has an empty list after a probe was unreachable or offered nothing;
- // re-probing it on every bare `/model` would freeze the render loop
- // for the full request timeout each time. Filtered before the key is
- // fetched so a re-open cannot re-prompt for a provider already probed.
- .filter(|c| {
- let tag = format!("{}|{}", c.provider, c.base_url.clone().unwrap_or_default());
- if already_probed.contains(&tag) {
- return false;
- }
- already_probed.insert(tag);
- true
- })
+ .filter(|c| global.contains_key(&c.provider) && is_cli_reachable(c))
+ // Filtered before the key is fetched so a re-open cannot re-prompt for
+ // a provider already probed.
+ .filter(|c| select(c))
.cloned()
.map(|mut c| {
hydrate_provider_keys(&mut c);
- (
- c.provider.clone(),
- c.base_url.clone().unwrap_or_default(),
- c.bearer_key_chain(),
- )
+ let keys = c.bearer_key_chain();
+ (c, keys)
})
.collect();
+ to_fetch.sort_by(|a, b| a.0.provider.cmp(&b.0.provider));
if to_fetch.is_empty() {
- return Ok(false);
+ return Ok(ModelRefresh::default());
}
let client = reqwest::Client::builder()
@@ -315,53 +481,132 @@ pub async fn fetch_missing_models(
// Probe providers concurrently so a batch of dead upstreams cannot stall
// the `/model` picker for the sum of their timeouts; the slowest provider
// bounds the wait.
- let results = futures::future::join_all(to_fetch.into_iter().map(|(name, base_url, keys)| {
+ let results = futures::future::join_all(to_fetch.into_iter().map(|(config, keys)| {
let client = &client;
async move {
- let models = fetch_models(client, &base_url, &keys).await;
- (name, base_url, models)
+ let base_url = config.base_url.clone().unwrap_or_default();
+ let listing = fetch_models(client, &base_url, &keys).await;
+ (config, listing)
}
}))
.await;
- let mut populated = false;
- for (name, _, result) in results {
- let models = match result {
- Ok(m) => m,
+
+ let mut catalog = super::model_catalog::load();
+ let mut catalog_dirty = false;
+ let mut refresh = ModelRefresh::default();
+ let default_model = crate::core::agent::global_config::default_model()
+ .ok()
+ .flatten()
+ .filter(|m| !m.trim().is_empty());
+ let mut default_dropped = false;
+ for (config, result) in results {
+ let listing = match result {
+ Ok(listing) => listing,
Err(e) => {
- log::warn!("could not list models for provider '{name}': {e}");
+ refresh.failed.push((config.provider, e));
continue;
}
};
- if models.is_empty() {
+ // An endpoint that lists nothing is treated as having said nothing:
+ // wiping a working list over an empty answer is never the right guess.
+ if listing.ids.is_empty() {
+ refresh
+ .failed
+ .push((config.provider, "the endpoint listed no models".to_string()));
continue;
}
- crate::core::agent::global_config::set_provider(
- &name,
- crate::core::agent::global_config::ProviderUpdate {
- api_key: None,
- base_url: None,
- clear_api_key: false,
- models: Some(models),
- api_type: None,
- ..Default::default()
+ let unlisted: Vec<&String> = config
+ .models
+ .iter()
+ .filter(|m| !listing.ids.contains(m))
+ .collect();
+ let stored = match roster {
+ Roster::Replace => listing.ids.clone(),
+ Roster::Additive => {
+ let mut merged = listing.ids.clone();
+ merged.extend(unlisted.iter().map(|m| (*m).clone()));
+ merged.sort();
+ merged.dedup();
+ merged
+ }
+ };
+ // Only a provider that *used to* offer the default can retire it; one
+ // that never listed it says nothing about it either way, and an
+ // additive probe drops nothing at all.
+ if let Some(model) = &default_model {
+ if config.models.contains(model) && !stored.contains(model) {
+ default_dropped = true;
+ }
+ }
+ let changed = stored != config.models;
+ if changed {
+ crate::core::agent::global_config::set_provider(
+ &config.provider,
+ crate::core::agent::global_config::ProviderUpdate {
+ models: Some(stored.clone()),
+ ..Default::default()
+ },
+ )?;
+ }
+ // Metadata is refreshed even when the id list is unchanged: a price or
+ // a context window can move without the roster moving. An answer that
+ // carried no metadata at all leaves the cache alone rather than
+ // clearing it: a degraded id-only response is not a statement that the
+ // windows and prices cached earlier are wrong.
+ if !listing.info.is_empty() {
+ catalog.set_provider(&config.provider, listing.info);
+ catalog_dirty = true;
+ }
+ refresh.listed.push(ProviderModels {
+ provider: config.provider,
+ models: stored.len(),
+ changed,
+ kept_unlisted: match roster {
+ Roster::Additive => unlisted.len(),
+ Roster::Replace => 0,
},
- )?;
- populated = true;
+ });
+ }
+ // Another provider may still serve it, which is not a retirement.
+ if default_dropped {
+ if let Some(model) = default_model {
+ let still_offered = load_global_config()
+ .map(|configs| configs.values().any(|c| c.models.contains(&model)))
+ .unwrap_or(true);
+ if !still_offered {
+ refresh.retired_default = Some(model);
+ }
+ }
+ }
+ if catalog_dirty {
+ if let Err(e) = catalog.save() {
+ // The catalog only ever improves a readout, so a failed write is a
+ // warning: the ids it accompanies are already persisted.
+ log::warn!("could not save the model catalog: {e}");
+ }
}
- Ok(populated)
+ Ok(refresh)
+}
+
+/// What one `/models` response carried: the ids the config stores, plus the
+/// per-model metadata the catalog caches.
+struct ModelListing {
+ ids: Vec<String>,
+ info: std::collections::BTreeMap<String, super::model_catalog::ModelInfo>,
}
/// Query an OpenAI-compatible `GET {base_url}/models` with Bearer auth (trying
/// each key in the chain on 401/403, matching upstream resolution) and return
-/// the parsed, sorted, deduped ids from the response body. A provider with no
-/// key (a keyless local endpoint) is queried unauthenticated. A remote
-/// plaintext-`http` base URL is rejected up front so a bearer key is never
-/// sent over a cleartext connection (loopback `http` is allowed).
+/// the parsed, sorted, deduped ids from the response body plus whatever
+/// per-model metadata it reported. A provider with no key (a keyless local
+/// endpoint) is queried unauthenticated. A remote plaintext-`http` base URL is
+/// rejected up front so a bearer key is never sent over a cleartext connection
+/// (loopback `http` is allowed).
async fn fetch_models(
client: &reqwest::Client,
base_url: &str,
keys: &[String],
-) -> Result<Vec<String>, String> {
+) -> Result<ModelListing, String> {
if !(base_url.starts_with("https://")
|| (base_url.starts_with("http://") && is_loopback_url(base_url)))
{
@@ -390,7 +635,10 @@ async fn fetch_models(
let body = response.text().await.unwrap_or_default();
let parsed: serde_json::Value = serde_json::from_str(&body)
.map_err(|e| format!("{url} returned a response we could not read: {e}"))?;
- return Ok(super::tokamak::parse_models(&parsed));
+ return Ok(ModelListing {
+ ids: super::tokamak::parse_models(&parsed),
+ info: super::model_catalog::parse_listing(&parsed),
+ });
}
if status != reqwest::StatusCode::UNAUTHORIZED && status != reqwest::StatusCode::FORBIDDEN {
// A non-auth error (rate limit, upstream down) won't be fixed by
@@ -1108,7 +1356,7 @@ mod tests {
}
#[test]
- fn fetch_missing_models_populates_and_persists_empty_providers() {
+ fn refresh_models_once_populates_and_persists_empty_providers() {
crate::core::agent::global_config::with_temp_home(|_| {
let addr = models_stub(
serde_json::json!({"data": [{"id": "m-b"}, {"id": "m-a"}]}).to_string(),
@@ -1128,7 +1376,13 @@ mod tests {
.unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
- let populated = rt.block_on(fetch_missing_models(None, &mut std::collections::HashSet::new())).expect("fetch");
+ let populated = rt
+ .block_on(refresh_models_once(
+ None,
+ &mut std::collections::HashSet::new(),
+ ))
+ .expect("fetch")
+ .changed_any();
assert!(populated);
let configs = load_global_config().unwrap();
@@ -1140,34 +1394,170 @@ mod tests {
});
}
+ /// A stored list is no longer sacred: the first `/model` open of a session
+ /// re-lists a provider that already names models, which is the only way a
+ /// roster captured at sign-in ever picks up what the endpoint added since.
#[test]
- fn fetch_missing_models_leaves_configured_lists_alone() {
+ fn refresh_models_once_re_lists_a_configured_provider() {
crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(
+ serde_json::json!({"data": [{"id": "m-new"}, {"id": "my-model"}]}).to_string(),
+ 1,
+ );
crate::core::agent::global_config::set_provider(
"chosen",
crate::core::agent::global_config::ProviderUpdate {
api_key: Some("k".into()),
- base_url: Some("http://127.0.0.1:9/v1".into()), // would refuse
- clear_api_key: false,
+ base_url: Some(format!("http://{addr}/v1")),
models: Some(vec!["my-model".into()]),
- api_type: None,
- ..Default::default()
+ ..Default::default()
},
)
.unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
- // Nothing to fetch: the provider already names its models, so the
- // dead endpoint above must never be contacted.
- let populated = rt.block_on(fetch_missing_models(None, &mut std::collections::HashSet::new())).expect("fetch");
- assert!(!populated);
+ let refreshed = rt
+ .block_on(refresh_models_once(
+ None,
+ &mut std::collections::HashSet::new(),
+ ))
+ .expect("fetch");
+ assert!(refreshed.changed_any());
let configs = load_global_config().unwrap();
- assert_eq!(configs.get("chosen").unwrap().models, vec!["my-model".to_string()]);
+ assert_eq!(
+ configs.get("chosen").unwrap().models,
+ vec!["m-new".to_string(), "my-model".to_string()]
+ );
+ });
+ }
+
+ /// Merely opening `/model` runs the automatic probe, so a subset answer (a
+ /// permission-scoped key, a paginated gateway) must not delete a
+ /// hand-configured id from `~/.jan/config.toml`.
+ #[test]
+ fn an_automatic_probe_keeps_an_id_the_endpoint_stopped_listing() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(serde_json::json!({"data": [{"id": "gpt-4o"}]}).to_string(), 1);
+ crate::core::agent::global_config::set_provider(
+ "gateway",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec!["gpt-4o".into(), "my-alias".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt
+ .block_on(refresh_models_once(
+ None,
+ &mut std::collections::HashSet::new(),
+ ))
+ .expect("fetch");
+ assert!(!refreshed.changed_any(), "nothing was added or dropped");
+ assert_eq!(refreshed.listed[0].kept_unlisted, 1);
+ assert!(refreshed.summary().contains("no longer listed"));
+ assert_eq!(
+ load_global_config().unwrap().get("gateway").unwrap().models,
+ vec!["gpt-4o".to_string(), "my-alias".to_string()],
+ "a configured id survives a probe the user did not ask for"
+ );
+ });
+ }
+
+ /// The explicit refresh is the one that drops: the user asked for the
+ /// endpoint's roster, and the summary reports what it did.
+ #[test]
+ fn an_explicit_refresh_drops_an_id_the_endpoint_stopped_listing() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(serde_json::json!({"data": [{"id": "gpt-4o"}]}).to_string(), 1);
+ crate::core::agent::global_config::set_provider(
+ "gateway",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec!["gpt-4o".into(), "my-alias".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt
+ .block_on(refresh_models(None, Some("gateway")))
+ .expect("fetch");
+ assert!(refreshed.changed_any());
+ assert_eq!(refreshed.listed[0].kept_unlisted, 0);
+ assert_eq!(
+ load_global_config().unwrap().get("gateway").unwrap().models,
+ vec!["gpt-4o".to_string()]
+ );
+ });
+ }
+
+ /// `--provider` naming nothing refreshable is a failure, not an empty
+ /// refresh: the caller's exit code reads `failed`, and a typo that exits 0
+ /// tells a script the refresh completed.
+ #[test]
+ fn refreshing_an_unknown_provider_is_reported_as_failed() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt
+ .block_on(refresh_models(None, Some("typo")))
+ .expect("call");
+ assert!(refreshed.listed.is_empty());
+ assert_eq!(
+ refreshed.failed,
+ vec![("typo".to_string(), "not a configured provider".to_string())]
+ );
+ });
+ }
+
+ /// A degraded answer that lists ids and no metadata is not a statement that
+ /// the cached windows and prices are wrong, so it must not clear them.
+ #[test]
+ fn an_id_only_listing_keeps_the_cached_metadata() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(serde_json::json!({"data": [{"id": "m-a"}]}).to_string(), 1);
+ crate::core::agent::global_config::set_provider(
+ "gateway",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec!["m-a".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let mut catalog = super::super::model_catalog::Catalog::default();
+ catalog.set_provider(
+ "gateway",
+ std::collections::BTreeMap::from([(
+ "m-a".to_string(),
+ super::super::model_catalog::ModelInfo {
+ context_length: Some(200_000),
+ ..Default::default()
+ },
+ )]),
+ );
+ catalog.save().unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ rt.block_on(refresh_models(None, Some("gateway")))
+ .expect("fetch");
+ assert_eq!(
+ super::super::model_catalog::load()
+ .get(Some("gateway"), "m-a")
+ .and_then(|i| i.context_length),
+ Some(200_000)
+ );
});
}
#[test]
- fn fetch_missing_models_queries_keyless_loopback_providers() {
+ fn refresh_models_once_queries_keyless_loopback_providers() {
crate::core::agent::global_config::with_temp_home(|_| {
let addr = models_stub(
serde_json::json!({"data": [{"id": "local-model"}]}).to_string(),
@@ -1187,10 +1577,19 @@ mod tests {
.unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
- let populated = rt.block_on(fetch_missing_models(None, &mut std::collections::HashSet::new())).expect("fetch");
+ let populated = rt
+ .block_on(refresh_models_once(
+ None,
+ &mut std::collections::HashSet::new(),
+ ))
+ .expect("fetch")
+ .changed_any();
assert!(populated, "a keyless endpoint is queried unauthenticated");
let configs = load_global_config().unwrap();
- assert_eq!(configs.get("local").unwrap().models, vec!["local-model".to_string()]);
+ assert_eq!(
+ configs.get("local").unwrap().models,
+ vec!["local-model".to_string()]
+ );
});
}
@@ -1199,7 +1598,7 @@ mod tests {
/// implementation (probe one to completion before starting the next)
/// deadlocks into its 15s timeout and populates only one provider.
#[test]
- fn fetch_missing_models_probes_concurrently() {
+ fn refresh_models_once_probes_concurrently() {
crate::core::agent::global_config::with_temp_home(|_| {
let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));
let stub = |models: &str| {
@@ -1240,17 +1639,282 @@ mod tests {
let rt = tokio::runtime::Runtime::new().unwrap();
let populated = rt
- .block_on(fetch_missing_models(None, &mut std::collections::HashSet::new()))
- .expect("fetch");
+ .block_on(refresh_models_once(
+ None,
+ &mut std::collections::HashSet::new(),
+ ))
+ .expect("fetch")
+ .changed_any();
assert!(populated);
let configs = load_global_config().unwrap();
- assert_eq!(configs.get("prov-a").unwrap().models, vec!["model-a".to_string()]);
- assert_eq!(configs.get("prov-b").unwrap().models, vec!["model-b".to_string()]);
+ assert_eq!(
+ configs.get("prov-a").unwrap().models,
+ vec!["model-a".to_string()]
+ );
+ assert_eq!(
+ configs.get("prov-b").unwrap().models,
+ vec!["model-b".to_string()]
+ );
+ });
+ }
+
+ /// The point of the refresh: a provider whose list was captured at sign-in
+ /// picks up models the endpoint has gained since, and its per-model
+ /// metadata is cached alongside for `/context` and `/usage`.
+ #[test]
+ fn refresh_models_replaces_a_configured_list_and_caches_metadata() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(
+ serde_json::json!({"data": [
+ {"id": "anthropic/claude-opus-5", "context_length": 1000000,
+ "pricing": {"prompt": "0.000005", "completion": "0.000025"}},
+ {"id": "openai/gpt-oss-120b-medium", "context_length": 131072},
+ ]})
+ .to_string(),
+ 1,
+ );
+ crate::core::agent::global_config::set_provider(
+ "tokamak",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec!["stale-model".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt.block_on(refresh_models(None, None)).expect("refresh");
+ assert!(refreshed.changed_any());
+ assert_eq!(refreshed.failed, Vec::new());
+ assert_eq!(
+ refreshed.listed,
+ vec![ProviderModels {
+ provider: "tokamak".to_string(),
+ models: 2,
+ changed: true,
+ kept_unlisted: 0,
+ }]
+ );
+
+ let configs = load_global_config().unwrap();
+ assert_eq!(
+ configs.get("tokamak").unwrap().models,
+ vec![
+ "anthropic/claude-opus-5".to_string(),
+ "openai/gpt-oss-120b-medium".to_string()
+ ],
+ "a stale list is replaced, not merged"
+ );
+
+ let catalog = crate::core::cli::model_catalog::load();
+ let info = catalog
+ .get(Some("tokamak"), "anthropic/claude-opus-5")
+ .expect("metadata cached");
+ assert_eq!(info.context_length, Some(1_000_000));
+ assert_eq!(info.prompt_usd, Some(0.000005));
+ });
+ }
+
+ /// A refresh that retires the model `default_model` points at must say so:
+ /// otherwise the next run fails with a 404 nothing connects to the refresh.
+ #[test]
+ fn refresh_models_reports_a_retired_default_model() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(
+ serde_json::json!({"data": [{"id": "m-new"}]}).to_string(),
+ 1,
+ );
+ crate::core::agent::global_config::set_provider(
+ "prov",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec!["m-retired".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ crate::core::agent::global_config::set_default_model_if_unset("m-retired").unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt.block_on(refresh_models(None, None)).expect("refresh");
+ assert_eq!(refreshed.retired_default.as_deref(), Some("m-retired"));
+ assert!(refreshed.summary().contains("no longer offered"));
+ });
+ }
+
+ /// A default still served by some other provider was not retired, so the
+ /// warning must stay quiet.
+ #[test]
+ fn a_default_another_provider_still_serves_is_not_retired() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(
+ serde_json::json!({"data": [{"id": "m-new"}]}).to_string(),
+ 1,
+ );
+ crate::core::agent::global_config::set_provider(
+ "prov",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec!["shared".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ crate::core::agent::global_config::set_provider(
+ "backup",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some("https://other.example/v1".into()),
+ models: Some(vec!["shared".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ crate::core::agent::global_config::set_default_model_if_unset("shared").unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt
+ .block_on(refresh_models(None, Some("prov")))
+ .expect("refresh");
+ assert_eq!(refreshed.retired_default, None);
+ });
+ }
+
+ /// A refresh that finds the same roster must say so rather than reading as
+ /// a failure, and must not rewrite the config.
+ #[test]
+ fn refresh_models_reports_an_unchanged_roster() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(serde_json::json!({"data": [{"id": "m-a"}]}).to_string(), 1);
+ crate::core::agent::global_config::set_provider(
+ "prov",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec!["m-a".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt.block_on(refresh_models(None, None)).expect("refresh");
+ assert!(!refreshed.changed_any());
+ assert_eq!(refreshed.listed[0].models, 1);
+ assert!(
+ refreshed.summary().contains("unchanged"),
+ "{}",
+ refreshed.summary()
+ );
+ });
+ }
+
+ /// One dead upstream must not cost the others their refresh, and must be
+ /// reported rather than silently dropped.
+ #[test]
+ fn refresh_models_reports_failures_without_blocking_the_rest() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(serde_json::json!({"data": [{"id": "m-a"}]}).to_string(), 1);
+ for (name, base) in [
+ ("alive", format!("http://{addr}/v1")),
+ ("dead", "http://127.0.0.1:9/v1".to_string()),
+ ] {
+ crate::core::agent::global_config::set_provider(
+ name,
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(base),
+ models: Some(vec![]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ }
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt.block_on(refresh_models(None, None)).expect("refresh");
+ assert_eq!(refreshed.listed.len(), 1);
+ assert_eq!(refreshed.listed[0].provider, "alive");
+ assert_eq!(refreshed.failed.len(), 1);
+ assert_eq!(refreshed.failed[0].0, "dead");
+ });
+ }
+
+ /// `--provider` scopes the probe: nothing else is contacted, which is what
+ /// keeps a refresh of one provider from waiting on every other one.
+ #[test]
+ fn refresh_models_can_target_one_provider() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(serde_json::json!({"data": [{"id": "m-a"}]}).to_string(), 1);
+ crate::core::agent::global_config::set_provider(
+ "wanted",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec![]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ // A dead endpoint that must never be contacted.
+ crate::core::agent::global_config::set_provider(
+ "other",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some("http://127.0.0.1:9/v1".into()),
+ models: Some(vec![]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt
+ .block_on(refresh_models(None, Some("wanted")))
+ .expect("refresh");
+ assert_eq!(refreshed.listed.len(), 1);
+ assert!(
+ refreshed.failed.is_empty(),
+ "the other provider is untouched"
+ );
+ });
+ }
+
+ /// An endpoint that answers with an empty roster must not wipe a working
+ /// list: "nothing listed" is far more often an outage than a retirement.
+ #[test]
+ fn refresh_models_never_wipes_a_list_over_an_empty_answer() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let addr = models_stub(serde_json::json!({"data": []}).to_string(), 1);
+ crate::core::agent::global_config::set_provider(
+ "prov",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec!["keep-me".into()]),
+ ..Default::default()
+ },
+ )
+ .unwrap();
+
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let refreshed = rt.block_on(refresh_models(None, None)).expect("refresh");
+ assert!(refreshed.listed.is_empty());
+ assert_eq!(refreshed.failed.len(), 1);
+ let configs = load_global_config().unwrap();
+ assert_eq!(
+ configs.get("prov").unwrap().models,
+ vec!["keep-me".to_string()]
+ );
});
}
#[test]
- fn fetch_missing_models_short_circuits_already_probed() {
+ fn refresh_models_once_short_circuits_already_probed() {
crate::core::agent::global_config::with_temp_home(|_| {
// A dead endpoint: if it were contacted, the 15s timeout would hang.
crate::core::agent::global_config::set_provider(
@@ -1270,16 +1934,18 @@ mod tests {
let mut probed = std::collections::HashSet::new();
// First probe hits the dead endpoint (fast refusal) and warns.
let populated = rt
- .block_on(fetch_missing_models(None, &mut probed))
- .expect("fetch");
+ .block_on(refresh_models_once(None, &mut probed))
+ .expect("fetch")
+ .changed_any();
assert!(!populated);
assert_eq!(probed.len(), 1, "dead provider is recorded as probed");
// A second fetch must not re-contact the dead endpoint at all
// (the probed set short-circuits it), and must not error.
let again = rt
- .block_on(fetch_missing_models(None, &mut probed))
- .expect("second fetch");
+ .block_on(refresh_models_once(None, &mut probed))
+ .expect("second fetch")
+ .changed_any();
assert!(!again, "already-probed provider is not re-fetched");
});
}
diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rs
index 8f0504e43..97d2d0ecd 100644
--- a/src-tauri/src/core/cli/run_report.rs
+++ b/src-tauri/src/core/cli/run_report.rs
@@ -94,10 +94,9 @@ pub(crate) struct RunReport {
stop_reason: Option<String>,
error: Option<(String, String)>,
num_turns: u32,
- prompt_tokens: u64,
- completion_tokens: u64,
- cached_tokens: u64,
- cache_write_tokens: u64,
+ /// Billable tokens across every request of the run, including subagents'.
+ /// The same accumulator `/usage` sums a TUI session with.
+ usage: super::model_catalog::TokenUsage,
}
impl RunReport {
@@ -124,12 +123,7 @@ 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 } => {
- self.prompt_tokens += usage.prompt_tokens.unwrap_or(0);
- self.completion_tokens += usage.completion_tokens.unwrap_or(0);
- self.cached_tokens += usage.cached_tokens.unwrap_or(0);
- self.cache_write_tokens += usage.cache_write_tokens.unwrap_or(0);
- }
+ StreamEvent::TurnUsage { usage } => self.usage.add(usage),
// Subagent work is real spend on the same budget, so its usage
// counts. Its `Step`/`Token` must not: those describe the child's
// own turns and prose, not this run's.
@@ -153,6 +147,7 @@ impl RunReport {
pub(crate) fn finish(
self,
session_id: Option<&str>,
+ provider: Option<&str>,
model: &str,
duration_ms: u128,
final_text: Option<&str>,
@@ -176,11 +171,17 @@ impl RunReport {
num_turns: self.num_turns,
duration_ms: duration_ms as u64,
usage: ReportUsage {
- prompt_tokens: self.prompt_tokens,
- completion_tokens: self.completion_tokens,
- total_tokens: self.prompt_tokens + self.completion_tokens,
- cached_tokens: self.cached_tokens,
- cache_write_tokens: self.cache_write_tokens,
+ prompt_tokens: self.usage.prompt_tokens,
+ completion_tokens: self.usage.completion_tokens,
+ total_tokens: self.usage.total_tokens(),
+ cached_tokens: self.usage.cached_tokens,
+ cache_write_tokens: self.usage.cache_write_tokens,
+ // Priced from the model catalog the last `/models` listing
+ // cached. Absent for a model whose provider publishes no
+ // prices, rather than reported as zero.
+ estimated_cost_usd: self
+ .usage
+ .cost_usd(super::model_catalog::load().get(provider, model)),
},
}
}
@@ -220,6 +221,8 @@ struct ReportUsage {
total_tokens: u64,
cached_tokens: u64,
cache_write_tokens: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ estimated_cost_usd: Option<f64>,
}
/// A stable, machine-readable code for a failure. The loop stamps every
@@ -277,7 +280,13 @@ mod tests {
] {
report.observe(&ev);
}
- let out = value(report.finish(Some("3f7a91c2"), "tokamak-1-preview", 48213, Some("done")));
+ let out = value(report.finish(
+ Some("3f7a91c2"),
+ None,
+ "tokamak-1-preview",
+ 48213,
+ Some("done"),
+ ));
assert_eq!(out["type"], "result");
assert_eq!(out["is_error"], false);
@@ -309,7 +318,7 @@ mod tests {
] {
report.observe(&ev);
}
- let out = value(report.finish(Some("3f7a91c2"), "tokamak-1-preview", 1204, None));
+ let out = value(report.finish(Some("3f7a91c2"), None, "tokamak-1-preview", 1204, None));
assert_eq!(out["is_error"], true);
assert_eq!(out["result"], "I started reviewing auth.rs and");
@@ -337,7 +346,7 @@ mod tests {
] {
report.observe(&ev);
}
- let out = value(report.finish(None, "m", 1, None));
+ let out = value(report.finish(None, None, "m", 1, None));
assert_eq!(out["result"], "second turn prose");
assert_eq!(out["num_turns"], 2);
// Unclassifiable messages keep the code the loop stamped.
@@ -371,7 +380,7 @@ mod tests {
] {
report.observe(&ev);
}
- let out = value(report.finish(None, "m", 1, Some("answer")));
+ let out = value(report.finish(None, None, "m", 1, Some("answer")));
assert_eq!(out["num_turns"], 2);
assert_eq!(out["result"], "answer");
assert_eq!(out["usage"]["prompt_tokens"], 350);
@@ -379,6 +388,45 @@ mod tests {
assert_eq!(out["usage"]["total_tokens"], 385);
}
+ /// A priced model carries its estimated cost in the envelope, so a script
+ /// can budget without re-deriving prices; an unpriced one omits the field
+ /// rather than reporting the run as free.
+ #[test]
+ fn the_envelope_prices_the_run_when_the_catalog_knows_the_model() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let mut catalog = crate::core::cli::model_catalog::Catalog::default();
+ catalog.set_provider(
+ "tokamak",
+ std::collections::BTreeMap::from([(
+ "priced-model".to_string(),
+ crate::core::cli::model_catalog::ModelInfo {
+ prompt_usd: Some(0.000001),
+ completion_usd: Some(0.00001),
+ ..Default::default()
+ },
+ )]),
+ );
+ catalog.save().expect("seed catalog");
+
+ let mut report = RunReport::default();
+ report.observe(&StreamEvent::TurnUsage {
+ usage: usage(1_000_000, 100_000),
+ });
+ let out = value(report.finish(None, None, "priced-model", 1, Some("done")));
+ assert_eq!(out["usage"]["estimated_cost_usd"], 2.0);
+
+ let mut report = RunReport::default();
+ report.observe(&StreamEvent::TurnUsage {
+ usage: usage(1_000, 100),
+ });
+ let out = value(report.finish(None, None, "unknown-model", 1, Some("done")));
+ assert!(
+ out["usage"].get("estimated_cost_usd").is_none(),
+ "an unpriced model must not report a cost"
+ );
+ });
+ }
+
/// The printed order is part of the contract: a human reading the envelope
/// should hit `result` near the top, not alphabetically between `num_turns`
/// and `session_id`.
@@ -389,7 +437,7 @@ mod tests {
code: "error".to_string(),
message: "boom".to_string(),
});
- let printed = serde_json::to_string(&report.finish(None, "m", 1, None)).unwrap();
+ let printed = serde_json::to_string(&report.finish(None, None, "m", 1, None)).unwrap();
let order = [
"\"type\"",
"\"is_error\"",
@@ -441,7 +489,9 @@ mod tests {
))
.unwrap(),
);
- stream.push_str(&ndjson_line(&report.finish(None, "m", 1, Some("done\nand done"))).unwrap());
+ stream.push_str(
+ &ndjson_line(&report.finish(None, None, "m", 1, Some("done\nand done"))).unwrap(),
+ );
assert!(stream.ends_with('\n'));
let lines: Vec<&str> = stream.lines().collect();
@@ -477,7 +527,7 @@ mod tests {
code: "error".to_string(),
message: "[context-overflow] Upstream returned HTTP 400: too long".to_string(),
});
- let out = value(report.finish(None, "m", 1, None));
+ let out = value(report.finish(None, None, "m", 1, None));
assert_eq!(out["error"]["code"], "context_overflow");
}
}
diff --git a/src-tauri/src/core/cli/tokamak.rs b/src-tauri/src/core/cli/tokamak.rs
index 7eb304fac..5cb80fb37 100644
--- a/src-tauri/src/core/cli/tokamak.rs
+++ b/src-tauri/src/core/cli/tokamak.rs
@@ -99,6 +99,10 @@ async fn verify_key(api_key: &str) -> Result<Vec<String>, String> {
}
let parsed: serde_json::Value = serde_json::from_str(&body)
.map_err(|e| format!("Tokamak returned a response we could not read: {e}"))?;
+ // The listing carries per-model `context_length` and pricing; caching it
+ // 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))
}
@@ -227,6 +231,7 @@ pub async fn logout() -> Result<Logout, String> {
};
remove_provider(PROVIDER)?;
+ super::model_catalog::forget(PROVIDER);
Ok(match revoked {
true => Logout::ClearedAndRevoked,
false => Logout::ClearedOnly,
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 4fa84b940..52c8d87dc 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -2135,6 +2135,15 @@ struct App {
/// resends the whole prefix. Surfaced in `/context`.
turn_cached_tokens: u64,
turn_cache_write_tokens: u64,
+ /// Billable tokens per model across the whole session, for `/usage`. Summed
+ /// over every request, since that is what a provider bills; keyed by model
+ /// *and* provider, because a session that switches models is billed at two
+ /// price lists and two providers can serve one id at different rates.
+ session_usage: std::collections::BTreeMap<UsageKey, super::model_catalog::TokenUsage>,
+ /// Memoized `(model, the provider serving it)`. Resolving takes the
+ /// provider-config lock, which a turn in flight can hold, and a row keyed
+ /// on a momentary `None` would split one model's spend in two.
+ model_provider: Option<(String, Option<String>)>,
/// Transcript viewport rect from the last draw, for mapping mouse clicks
/// to rows.
transcript_rect: Rect,
@@ -2580,6 +2589,8 @@ impl App {
tokens_per_sec: None,
turn_output_tokens: 0,
turn_prompt_tokens: 0,
+ session_usage: std::collections::BTreeMap::new(),
+ model_provider: None,
turn_cached_tokens: 0,
turn_cache_write_tokens: 0,
transcript_rect: Rect::default(),
@@ -2687,6 +2698,8 @@ impl App {
self.turn_prompt_tokens = 0;
self.turn_cached_tokens = 0;
self.turn_cache_write_tokens = 0;
+ // `/usage` reports the session, and this is a new one.
+ self.session_usage.clear();
self.tokens_per_sec = None;
self.turn = (0, 0);
self.detail.clear();
@@ -4663,15 +4676,66 @@ impl App {
/// caller can decide whether a compaction is now warranted. The catalog
/// matching lives only in `model_capabilities`, never duplicated here.
fn refresh_context_window(&mut self) -> bool {
+ let provider = self.serving_provider();
let resolved = crate::core::cli::model_capabilities::resolve_context_window(
&self.model,
self.configured_context_window,
+ crate::core::cli::model_capabilities::reported_window(provider.as_deref(), &self.model),
);
let changed = resolved.tokens != self.context_window;
self.context_window = resolved.tokens;
self.context_window_source = resolved.source;
changed
}
+ /// Mark the memoized model -> provider answer as needing re-resolution
+ /// while keeping the answer itself. The value survives because
+ /// [`Self::serving_provider`] falls back to it when the provider-config
+ /// lock is busy; dropping the entry outright would hand that path a `None`
+ /// and split the model's spend across two `/usage` rows.
+ fn invalidate_serving_provider(&mut self) {
+ if let Some((model, _)) = self.model_provider.as_mut() {
+ // No real model id is empty, so this never matches on lookup.
+ model.clear();
+ }
+ }
+
+ /// The provider serving the current model, memoized against it. A busy
+ /// provider-config lock keeps the last known answer rather than falling to
+ /// `None`: an unqualified row prices the model against whichever provider
+ /// happens to list it, so a momentarily contended lock would otherwise
+ /// split one model's spend across two `/usage` rows, one of them priced
+ /// wrong or reported as unpriced. The memo is refreshed on the next call
+ /// that does get the lock.
+ fn serving_provider(&mut self) -> Option<String> {
+ if let Some((model, provider)) = &self.model_provider {
+ if model == &self.model {
+ return provider.clone();
+ }
+ }
+ let last_known = self
+ .model_provider
+ .as_ref()
+ .and_then(|(_, provider)| provider.clone());
+ let Some(args) = self.args.clone() else {
+ return last_known;
+ };
+ let Ok(pc) = args.provider_configs.try_lock() else {
+ return last_known;
+ };
+ let resolved = super::providers::provider_for_model(&self.model, &pc);
+ drop(pc);
+ self.model_provider = Some((self.model.clone(), resolved.clone()));
+ resolved
+ }
+
+ /// The `/usage` bucket one request bills against.
+ fn usage_key(&mut self) -> UsageKey {
+ UsageKey {
+ model: self.model.clone(),
+ provider: self.serving_provider(),
+ }
+ }
+
/// Header label for the current selection: `provider/model` when the bare
/// model id resolves to exactly one provider, so the reader can tell where
/// it is served from (the picker already shows the pair) instead of a bare
@@ -4731,6 +4795,7 @@ impl App {
turn_prompt_tokens: self.turn_prompt_tokens,
turn_cached_tokens: self.turn_cached_tokens,
turn_cache_write_tokens: self.turn_cache_write_tokens,
+ session_cost: session_cost(&self.session_usage),
}
}
}
@@ -4750,6 +4815,10 @@ struct ContextSnapshot {
turn_prompt_tokens: u64,
turn_cached_tokens: u64,
turn_cache_write_tokens: u64,
+ /// This session's estimated spend so far, and whether a model with no
+ /// published price was left out of it. Priced here, on the key path, so the
+ /// off-loop task does not re-read the model catalog.
+ session_cost: Option<(f64, bool)>,
}
/// The `/context` breakdown for the current session, computed from an owned
@@ -4881,6 +4950,7 @@ async fn compute_context_report(snapshot: ContextSnapshot) -> ContextReport {
cache_reported,
cached_tokens: snapshot.turn_cached_tokens,
cache_write_tokens: snapshot.turn_cache_write_tokens,
+ session_cost: snapshot.session_cost,
}
}
@@ -5302,6 +5372,10 @@ impl App {
event,
} => self.apply_subagent_event(&run_id, &name, *event),
StreamEvent::TurnUsage { usage } => {
+ // 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();
+ self.session_usage.entry(key).or_default().add(&usage);
self.turn_output_tokens += usage.completion_tokens.unwrap_or(0);
// Latest request's context, not a sum: each request resends the
// whole conversation, so adding them would be meaningless.
@@ -5409,6 +5483,12 @@ impl App {
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 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`
+ // and the `--output-format json` envelope disagree.
+ let key = self.usage_key();
+ self.session_usage.entry(key).or_default().add(&usage);
}
// Token/ToolResult, a child's live tool output (`ToolOutputDelta`)
// and any nested bracket are internal to the child run and not
@@ -6007,6 +6087,152 @@ fn estimate_token_count(messages: &[serde_json::Value]) -> u64 {
((total_chars / 4) as u64 + envelope).max(1)
}
+/// USD at the precision the amount deserves: sub-cent runs still need to read
+/// as a number rather than `$0.00`.
+fn format_usd(amount: f64) -> String {
+ if amount >= 1.0 {
+ format!("${amount:.2}")
+ } else if amount >= 0.01 {
+ format!("${amount:.3}")
+ } else if amount >= 0.00005 {
+ format!("${amount:.4}")
+ } else if amount > 0.0 {
+ // Below the 4th decimal a fixed precision prints `$0.0000`, which is
+ // the reads-as-free case this helper exists to avoid. Two significant
+ // digits keep a fraction of a cent legible without printing a dozen
+ // zeroes for every cheap session. Zero is excluded from the branch:
+ // `log10(0)` is infinite, and a genuine zero may print as one.
+ let places = ((-amount.log10()).ceil() as usize).saturating_add(1);
+ format!("${amount:.*}", places.min(12))
+ } else {
+ format!("${amount:.4}")
+ }
+}
+
+/// One `/usage` row's identity: a model plus the provider that billed it.
+/// Ordered by model first so the rows read as a model list even when one model
+/// was served by two providers.
+#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
+struct UsageKey {
+ model: String,
+ provider: Option<String>,
+}
+
+impl UsageKey {
+ /// How the row is labelled: `provider/model`, matching the header, unless
+ /// the id already carries its qualifier or no provider is known.
+ fn label(&self) -> String {
+ match &self.provider {
+ Some(provider) if !self.model.contains('/') => format!("{provider}/{}", self.model),
+ _ => self.model.clone(),
+ }
+ }
+}
+
+/// Total estimated cost across every model used, and whether any model was
+/// left out for want of published prices. `None` when nothing could be priced
+/// at all, which is what suppresses the cost line entirely.
+fn session_cost(
+ usage: &std::collections::BTreeMap<UsageKey, super::model_catalog::TokenUsage>,
+) -> Option<(f64, bool)> {
+ let catalog = super::model_catalog::load();
+ let mut total = 0.0;
+ let mut priced = false;
+ let mut unpriced = false;
+ for (key, model_usage) in usage {
+ match model_usage.cost_usd(catalog.get(key.provider.as_deref(), &key.model)) {
+ Some(cost) => {
+ total += cost;
+ priced = true;
+ }
+ None => unpriced = true,
+ }
+ }
+ 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.
+fn usage_lines(
+ usage: &std::collections::BTreeMap<UsageKey, super::model_catalog::TokenUsage>,
+) -> Vec<Vec<Span<'static>>> {
+ let catalog = super::model_catalog::load();
+ let mut rows = Vec::new();
+ let mut totals = super::model_catalog::TokenUsage::default();
+ let mut total_cost = 0.0;
+ let mut any_priced = false;
+ let mut any_unpriced = false;
+ for (key, model_usage) in usage {
+ let cost = model_usage.cost_usd(catalog.get(key.provider.as_deref(), &key.model));
+ match cost {
+ Some(c) => {
+ total_cost += c;
+ any_priced = true;
+ }
+ 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)),
+ Span::styled(
+ match 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(),
+ },
+ Style::new().yellow(),
+ ),
+ ]);
+ }
+ if rows.len() > 1 || any_priced {
+ rows.push(vec![
+ Span::styled("total ", Style::new().bold()),
+ Span::raw(usage_counts(&totals)),
+ Span::styled(
+ if any_priced {
+ format!(" ~{}", format_usd(total_cost))
+ } else {
+ String::new()
+ },
+ Style::new().yellow().bold(),
+ ),
+ ]);
+ }
+ if any_unpriced && any_priced {
+ rows.push(vec![Span::styled(
+ "the total excludes models with no published price",
+ Style::new().dim(),
+ )]);
+ }
+ rows
+}
+
+/// `N req · 12.3K in (8.1K cached) · 3.4K out`, the shape both the per-model
+/// rows and the total use.
+fn usage_counts(usage: &super::model_catalog::TokenUsage) -> String {
+ let mut line = format!(
+ "{} req · {} in",
+ usage.requests,
+ format_tokens(usage.prompt_tokens)
+ );
+ if usage.cached_tokens > 0 {
+ line.push_str(&format!(" ({} cached)", format_tokens(usage.cached_tokens)));
+ }
+ line.push_str(&format!(
+ " · {} out",
+ format_tokens(usage.completion_tokens)
+ ));
+ if usage.cache_write_tokens > 0 {
+ line.push_str(&format!(
+ " · {} cache write",
+ format_tokens(usage.cache_write_tokens)
+ ));
+ }
+ line
+}
+
/// One bank in the `/context` breakdown. `key` is the monochrome-safe category
/// marker; `label` is the compact uppercase name shown beside its bar.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -6039,6 +6265,9 @@ struct ContextReport {
cache_reported: bool,
cached_tokens: u64,
cache_write_tokens: u64,
+ /// Session spend and whether it is partial, from [`ContextSnapshot`].
+ /// `None` suppresses the cost line: no model in play publishes prices.
+ session_cost: Option<(f64, bool)>,
}
impl ContextReport {
@@ -6188,6 +6417,22 @@ fn cache_summary_line(report: &ContextReport) -> Option<String> {
}
}
+/// One-line session-spend readout for `/context`, or `None` when no model in
+/// play publishes prices. The window is a single request; this is what every
+/// request so far has cost, which is the number `/usage` breaks down per model.
+fn cost_summary_line(report: &ContextReport) -> Option<String> {
+ let (total, partial) = report.session_cost?;
+ let suffix = if partial {
+ " (excludes models with no published price)"
+ } else {
+ ""
+ };
+ Some(format!(
+ "Session cost (estimated): ~{}{suffix} - /usage for the breakdown",
+ format_usd(total)
+ ))
+}
+
/// Plain `/context` summary: current usage and autocompaction threshold first,
/// followed by seven equal-scale category bars.
fn context_lines(report: &ContextReport, width: usize) -> Vec<Line<'static>> {
@@ -6227,6 +6472,9 @@ fn context_lines(report: &ContextReport, width: usize) -> Vec<Line<'static>> {
if let Some(cache) = cache_summary_line(report) {
rows.push(vec![Span::styled(cache, Style::new().cyan())]);
}
+ if let Some(cost) = cost_summary_line(report) {
+ rows.push(vec![Span::styled(cost, Style::new().yellow())]);
+ }
rows.push(vec![Span::styled(
"Context breakdown (estimated)",
Style::new().dim(),
@@ -6334,6 +6582,9 @@ fn context_lines(report: &ContextReport, width: usize) -> Vec<Line<'static>> {
if let Some(cache) = cache_summary_line(report) {
rows.push(vec![Span::styled(cache, Style::new().cyan())]);
}
+ if let Some(cost) = cost_summary_line(report) {
+ rows.push(vec![Span::styled(cost, Style::new().yellow())]);
+ }
rows.push(Vec::new());
rows.push(vec![Span::styled(
"Context breakdown (estimated)",
@@ -8363,6 +8614,9 @@ pub async fn run(
mut args,
permission_requests,
model,
+ // Re-resolved from `App` as the model changes, so the session's initial
+ // answer is not carried into the picker's later selections.
+ provider: _,
smol_model,
limits,
show_reasoning,
@@ -9814,7 +10068,7 @@ fn clipboard_text() -> Result<String, String> {
super::secret_input::clipboard_text()
}
-fn handle_model_picker_key(app: &mut App, key: KeyEvent, ctrl: bool) {
+async fn handle_model_picker_key(app: &mut App, key: KeyEvent, ctrl: bool) {
if key.code == KeyCode::Esc
|| (ctrl && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')))
{
@@ -9822,6 +10076,13 @@ fn handle_model_picker_key(app: &mut App, key: KeyEvent, ctrl: bool) {
return;
}
+ // Re-list every provider from its endpoint. `Ctrl-R` rather than `r`: the
+ // models pane takes every unmodified character as search input.
+ if ctrl && key.code == KeyCode::Char('r') {
+ refresh_model_picker(app).await;
+ return;
+ }
+
let mut chosen = None;
if let Some(picker) = app.model_picker.as_mut() {
match key.code {
@@ -10043,7 +10304,7 @@ async fn handle_key(
}
if app.model_picker.is_some() {
- handle_model_picker_key(app, key, ctrl);
+ handle_model_picker_key(app, key, ctrl).await;
return;
}
@@ -10947,6 +11208,12 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
description: "Summarize older turns to free up context",
alias_of: None,
},
+ SlashCommand {
+ name: "/usage",
+ hint: "",
+ description: "Show this session's tokens and estimated cost, per model",
+ alias_of: None,
+ },
SlashCommand {
name: "/context",
hint: "",
@@ -11253,6 +11520,7 @@ async fn run_command(
}
"compact" => compact_command(app),
"context" => context_command(app),
+ "usage" => usage_command(app),
"threads" | "list" => match super::list_threads_in(&app.agent_dir) {
Ok(threads) if threads.is_empty() => {
app.note("no saved threads found");
@@ -11355,6 +11623,25 @@ fn context_command(app: &mut App) {
app.context_request = true;
}
+/// `/usage`: what this session has actually spent, per model. 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;
+ }
+ app.note("session usage");
+ for row in usage_lines(&app.session_usage) {
+ app.system_detail(row);
+ }
+ 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
@@ -13247,21 +13534,71 @@ fn open_thread_picker(app: &mut App) {
/// Open the `/model` hub listing the `provider / model` pairs this build can
/// actually run, with the current raw model pre-highlighted.
+///
+/// Opening it re-lists every provider not yet probed this session, so a roster
+/// captured at sign-in picks up what the endpoint has added since; `Ctrl-R`
+/// inside the picker forces that again ([`refresh_model_picker`]).
async fn open_model_picker(app: &mut App) {
let project_root = app.project_root.clone();
- match super::providers::fetch_missing_models(Some(&project_root), &mut app.probed_models).await
- {
- Ok(true) => {
- // The discovered ids now live on disk; refresh the session's
- // in-memory provider snapshot so a picked model resolves on the
- // next run without a restart (#8688 parallels the /login reload).
- reload_provider_configs(app).await;
- app.note("fetched models for provider(s) with no configured list");
- }
- Ok(_) => {}
+ let refreshed =
+ super::providers::refresh_models_once(Some(&project_root), &mut app.probed_models).await;
+ apply_model_refresh(app, refreshed, false).await;
+ show_model_picker(app);
+}
+
+/// `Ctrl-R` in the picker: re-list every reachable provider, ignoring the
+/// once-per-session guard (the user asked, and the guard exists only to keep an
+/// automatic probe cheap), then rebuild the picker in place.
+async fn refresh_model_picker(app: &mut App) {
+ let project_root = app.project_root.clone();
+ app.probed_models.clear();
+ let refreshed = super::providers::refresh_models(Some(&project_root), None).await;
+ apply_model_refresh(app, refreshed, true).await;
+ show_model_picker(app);
+}
+
+/// Report a probe and reload the session's provider snapshot when it changed
+/// anything. `explicit` is a user-triggered refresh, which reports its outcome
+/// even when nothing moved -- an automatic probe stays silent instead, since it
+/// runs on every first `/model` of a session.
+async fn apply_model_refresh(
+ app: &mut App,
+ refreshed: Result<super::providers::ModelRefresh, String>,
+ explicit: bool,
+) {
+ match refreshed {
+ Ok(refreshed) => {
+ if refreshed.changed_any() {
+ // The discovered ids now live on disk; refresh the session's
+ // in-memory provider snapshot so a picked model resolves on the
+ // next run without a restart (#8688 parallels the /login reload).
+ reload_provider_configs(app).await;
+ }
+ if explicit || refreshed.changed_any() || !refreshed.failed.is_empty() {
+ app.note(&refreshed.summary());
+ }
+ // A listing can move a model's window without moving the roster,
+ // and both the header gauge and compaction read it, so re-resolve
+ // now rather than leaving the old size until the model is switched.
+ app.invalidate_serving_provider();
+ if app.refresh_context_window() {
+ app.note(&format!(
+ "context window now {}K ({})",
+ app.context_window / 1000,
+ app.context_window_source.label()
+ ));
+ if app.should_auto_compact() {
+ app.compact_request = Some(CompactKind::Auto);
+ }
+ }
+ }
Err(e) => app.note(&format!("could not fetch models: {e}")),
}
- let pairs = super::providers::list_provider_models(Some(&project_root));
+}
+
+/// Build the picker from what is currently configured, replacing any open one.
+fn show_model_picker(app: &mut App) {
+ let pairs = super::providers::list_provider_models(Some(&app.project_root));
match ModelPicker::from_pairs(pairs, &app.model) {
Some(picker) => {
app.picker = None;
@@ -14242,6 +14579,9 @@ async fn reload_provider_configs(app: &mut App) {
) {
Ok(configs) => {
*args.provider_configs.lock().await = configs;
+ // The memoized model -> provider answer was resolved against the
+ // snapshot just replaced.
+ app.invalidate_serving_provider();
}
Err(e) => {
app.note(&format!(
@@ -16984,7 +17324,7 @@ fn draw_model_picker(f: &mut Frame, area: Rect, picker: &ModelPicker, current_mo
let rows = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(inner);
let body = rows[0];
let help = truncate(
- "Enter choose · Left/Right panes · Up/Down move · type to search · Esc close",
+ "Enter choose · Left/Right panes · Up/Down move · type to search · Ctrl-R refresh · Esc close",
rows[1].width as usize,
);
f.render_widget(
@@ -17583,25 +17923,11 @@ fn provider_label_for_model(
model: &str,
pc: &HashMap<String, crate::core::state::ProviderConfig>,
) -> String {
- use crate::core::cli::providers::is_cli_reachable;
- // Explicit `<provider>/<model>` form: verify the prefix names a provider.
- if let Some(sep) = model.find('/') {
- if pc.contains_key(&model[..sep]) {
- return model.to_string();
+ match crate::core::cli::providers::provider_for_model(model, pc) {
+ Some(name) if name != model && !model.starts_with(&format!("{name}/")) => {
+ format!("{name}/{model}")
}
- }
- // Bare id: find the (preferentially reachable, credentialed) provider that
- // offers it, matching `resolve_upstream_for_model`'s deterministic pick.
- let offers = |c: &&crate::core::state::ProviderConfig| c.models.iter().any(|m| m == model);
- let reachable = pc
- .iter()
- .filter(|(_, c)| is_cli_reachable(c) && offers(c))
- .min_by_key(|(name, c)| (std::cmp::Reverse(c.api_key.is_some()), (*name).clone()))
- .or_else(|| pc.iter().find(|(_, c)| offers(c)));
- match reachable {
- Some((name, _)) if name != model => format!("{name}/{model}"),
- Some(_) => model.to_string(),
- None => model.to_string(),
+ _ => model.to_string(),
}
}
@@ -23760,36 +24086,7 @@ mod tests {
let mut app = test_app();
// Give the app a provider_configs map that is stale (empty, as it
// would be on a fresh launch before login).
- let provider_configs: std::collections::HashMap<
- String,
- crate::core::state::ProviderConfig,
- > = std::collections::HashMap::new();
- let args = std::sync::Arc::new(super::OrchestrationArgs {
- client: crate::core::agent::upstream::agent_http_client(),
- provider_configs: std::sync::Arc::new(tokio::sync::Mutex::new(provider_configs)),
- mcp_servers: std::sync::Arc::new(tokio::sync::Mutex::new(
- std::collections::HashMap::new(),
- )),
- mcp_settings: std::sync::Arc::new(tokio::sync::Mutex::new(
- crate::core::mcp::models::McpSettings::default(),
- )),
- jan_data_folder: String::new(),
- permissions: tauri_plugin_agent_tools::permissions::ToolPermissions::default(),
- project_root: Some(app.project_root.clone()),
- permission_requests: std::sync::Arc::new(tokio::sync::Mutex::new(
- std::collections::HashMap::new(),
- )),
- ask_requests: None,
- todo_registry: None,
- system_prompt_override: None,
- subagents_enabled: true,
- max_parallel_subagents: 4,
- auto_approve: false,
- run_mode: crate::core::agent::plan::RunMode::Normal,
- session_id: None,
- sandbox: None,
- monitors: Some(app.monitor_set.clone()),
- });
+ let args = test_args(&app, std::collections::HashMap::new());
app.args = Some(args.clone());
// Build a dedicated multi-threaded runtime so we can .await
@@ -23816,6 +24113,78 @@ mod tests {
});
}
+ /// A contended provider-config lock must not re-key the session's usage
+ /// rows: without the last-known fallback the same model bills into a
+ /// `(model, Some(provider))` row and a `(model, None)` one, and the
+ /// unqualified row prices against whatever else lists the id - or reports
+ /// "(no published price)" for a model whose provider publishes prices.
+ #[test]
+ fn a_busy_provider_lock_keeps_the_usage_row_on_one_provider() {
+ let mut app = test_app();
+ app.model = "shared-model".into();
+ let mut provider_configs = std::collections::HashMap::new();
+ provider_configs.insert(
+ "tokamak".to_string(),
+ crate::core::state::ProviderConfig {
+ provider: "tokamak".into(),
+ base_url: Some("https://api.tokamak.sh/v1".into()),
+ api_key: Some("tk".into()),
+ models: vec!["shared-model".into()],
+ ..Default::default()
+ },
+ );
+ let args = test_args(&app, provider_configs);
+ app.args = Some(args.clone());
+
+ assert_eq!(app.usage_key().provider.as_deref(), Some("tokamak"));
+
+ // The config snapshot is being replaced (a refresh or a /login
+ // reload); the render path asks mid-write.
+ app.invalidate_serving_provider();
+ let rt = tokio::runtime::Runtime::new().expect("runtime");
+ let held = rt.block_on(args.provider_configs.lock());
+ assert_eq!(
+ app.usage_key().provider.as_deref(),
+ Some("tokamak"),
+ "a busy lock must keep the last known provider, not fall back to None"
+ );
+ drop(held);
+ }
+
+ /// Minimal `OrchestrationArgs` around a provider map, for tests that only
+ /// exercise provider resolution.
+ fn test_args(
+ app: &App,
+ provider_configs: std::collections::HashMap<String, crate::core::state::ProviderConfig>,
+ ) -> std::sync::Arc<super::OrchestrationArgs> {
+ std::sync::Arc::new(super::OrchestrationArgs {
+ client: crate::core::agent::upstream::agent_http_client(),
+ provider_configs: std::sync::Arc::new(tokio::sync::Mutex::new(provider_configs)),
+ mcp_servers: std::sync::Arc::new(tokio::sync::Mutex::new(
+ std::collections::HashMap::new(),
+ )),
+ mcp_settings: std::sync::Arc::new(tokio::sync::Mutex::new(
+ crate::core::mcp::models::McpSettings::default(),
+ )),
+ jan_data_folder: String::new(),
+ permissions: tauri_plugin_agent_tools::permissions::ToolPermissions::default(),
+ project_root: Some(app.project_root.clone()),
+ permission_requests: std::sync::Arc::new(tokio::sync::Mutex::new(
+ std::collections::HashMap::new(),
+ )),
+ ask_requests: None,
+ todo_registry: None,
+ system_prompt_override: None,
+ subagents_enabled: true,
+ max_parallel_subagents: 4,
+ auto_approve: false,
+ run_mode: crate::core::agent::plan::RunMode::Normal,
+ session_id: None,
+ sandbox: None,
+ monitors: Some(app.monitor_set.clone()),
+ })
+ }
+
#[test]
fn masked_key_is_bounded() {
let mut prompt = confirmed_paste_prompt();
@@ -25502,6 +25871,84 @@ mod tests {
});
}
+ /// `Ctrl-R` in the picker re-lists from the endpoint, so a roster that grew
+ /// since the session started is picked up without a restart -- and the `r`
+ /// must not land in the search query, which every other character does.
+ #[test]
+ fn model_picker_ctrl_r_relists_from_the_endpoint() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ // Two connections: the automatic probe on open, then the Ctrl-R.
+ let bodies = [
+ serde_json::json!({"data": [{"id": "old-model"}]}).to_string(),
+ serde_json::json!({"data": [
+ {"id": "old-model"},
+ {"id": "brand-new-model", "context_length": 700000}
+ ]})
+ .to_string(),
+ ];
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ std::thread::spawn(move || {
+ for (body, stream) in bodies.into_iter().zip(listener.incoming()) {
+ let Ok(mut stream) = stream else { continue };
+ let _ = std::io::Read::read(&mut stream, &mut [0u8; 4096]);
+ let resp = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ let _ = std::io::Write::write_all(&mut stream, resp.as_bytes());
+ }
+ });
+ crate::core::agent::global_config::set_provider(
+ "myprovider",
+ crate::core::agent::global_config::ProviderUpdate {
+ api_key: Some("k".into()),
+ base_url: Some(format!("http://{addr}/v1")),
+ models: Some(vec![]),
+ ..Default::default()
+ },
+ )
+ .expect("seed provider");
+
+ let mut app = test_app();
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ rt.block_on(super::run_command(&mut app, "model", &no_mcp()));
+ let picker = app.model_picker.as_ref().expect("model picker opened");
+ assert!(picker
+ .all_items
+ .iter()
+ .all(|i| i.model != "brand-new-model"));
+
+ rt.block_on(async {
+ press(&mut app, KeyCode::Char('r'), KeyModifiers::CONTROL).await;
+ });
+ let picker = app.model_picker.as_ref().expect("picker rebuilt");
+ assert!(
+ picker.query.is_empty(),
+ "Ctrl-R must not type into the search box"
+ );
+ assert!(
+ picker
+ .all_items
+ .iter()
+ .any(|i| i.model == "brand-new-model"),
+ "the re-listed model must be offered: {:?}",
+ picker
+ .all_items
+ .iter()
+ .map(|i| &i.model)
+ .collect::<Vec<_>>()
+ );
+ // The metadata rides along, which is what makes the window real
+ // rather than the conservative fallback.
+ assert_eq!(
+ crate::core::cli::model_capabilities::reported_window(None, "brand-new-model"),
+ Some(700_000)
+ );
+ });
+ }
+
/// A reachable-looking but dead provider (empty model list, unreachable
/// endpoint) must not break or block the `/model` picker: the fetch is
/// skipped with a note, and the picker still opens with what is reachable.
@@ -30566,9 +31013,248 @@ mod tests {
cache_reported: false,
cached_tokens: 0,
cache_write_tokens: 0,
+ session_cost: None,
+ }
+ }
+
+ /// Seed the model catalog with one priced model, the way a refresh or a
+ /// sign-in would.
+ fn seed_priced_model(provider: &str, model: &str) {
+ let mut catalog = crate::core::cli::model_catalog::Catalog::default();
+ catalog.set_provider(
+ provider,
+ std::collections::BTreeMap::from([(
+ model.to_string(),
+ crate::core::cli::model_catalog::ModelInfo {
+ context_length: Some(1_000_000),
+ prompt_usd: Some(0.000005),
+ completion_usd: Some(0.000025),
+ cache_read_usd: Some(0.0000005),
+ ..Default::default()
+ },
+ )]),
+ );
+ catalog.save().expect("seed catalog");
+ }
+
+ fn usage_key(provider: &str, model: &str) -> super::UsageKey {
+ super::UsageKey {
+ model: model.to_string(),
+ provider: Some(provider.to_string()),
}
}
+ fn usage_of(
+ requests: u64,
+ prompt: u64,
+ completion: u64,
+ cached: u64,
+ ) -> crate::core::cli::model_catalog::TokenUsage {
+ crate::core::cli::model_catalog::TokenUsage {
+ requests,
+ prompt_tokens: prompt,
+ completion_tokens: completion,
+ cached_tokens: cached,
+ cache_write_tokens: 0,
+ }
+ }
+
+ /// `/usage` prices each model at its own published rates and refuses to
+ /// count an unpriced one as free -- a total that silently omitted it would
+ /// read as the whole bill.
+ #[test]
+ fn usage_prices_each_model_and_flags_the_unpriced_ones() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ seed_priced_model("tokamak", "anthropic/claude-opus-5");
+ let usage = std::collections::BTreeMap::from([
+ (
+ usage_key("tokamak", "anthropic/claude-opus-5"),
+ usage_of(2, 100_000, 10_000, 40_000),
+ ),
+ (
+ usage_key("private-gateway", "private-gateway-model"),
+ usage_of(1, 5_000, 500, 0),
+ ),
+ ]);
+
+ let text: Vec<String> = super::usage_lines(&usage)
+ .iter()
+ .map(|row| row.iter().map(|s| s.content.to_string()).collect())
+ .collect();
+ let joined = text.join("\n");
+ assert!(joined.contains("2 req"), "{joined}");
+ assert!(joined.contains("(40K cached)"), "{joined}");
+ assert!(
+ joined.contains("no published price"),
+ "an unpriced model must say so: {joined}"
+ );
+ assert!(
+ joined.contains("the total excludes models with no published price"),
+ "{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;
+ let (total, partial) = super::session_cost(&usage).expect("a priced model");
+ assert!((total - expected).abs() < 1e-9, "{total} vs {expected}");
+ assert!(partial, "the unpriced model makes the total partial");
+ assert!(joined.contains(&super::format_usd(expected)), "{joined}");
+ });
+ }
+
+ /// With nothing priced there is no cost line at all, rather than a `$0.00`
+ /// that would read as a free session.
+ #[test]
+ fn an_unpriced_session_reports_no_cost() {
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let usage = std::collections::BTreeMap::from([(
+ usage_key("private-gateway", "private-gateway-model"),
+ usage_of(1, 5_000, 500, 0),
+ )]);
+ assert_eq!(super::session_cost(&usage), None);
+ let mut report = context_report(234_000, 35_000, [1, 1, 1, 1, 1]);
+ report.session_cost = None;
+ assert_eq!(super::cost_summary_line(&report), None);
+ });
+ }
+
+ /// The `/context` overlay carries the session spend, since the window it
+ /// describes is one request and the spend is every request so far.
+ #[test]
+ fn context_view_shows_the_session_cost() {
+ let mut report = context_report(234_000, 35_000, [6_049, 9_000, 2_149, 8_049, 95_253]);
+ report.session_cost = Some((0.4213, false));
+ let line = super::cost_summary_line(&report).expect("a priced session");
+ assert!(line.contains("$0.421"), "{line}");
+ assert!(line.contains("/usage"), "{line}");
+ assert!(!line.contains("excludes"), "{line}");
+
+ report.session_cost = Some((0.4213, true));
+ assert!(super::cost_summary_line(&report)
+ .expect("line")
+ .contains("excludes"));
+
+ let text = super::context_lines(&report, 100)
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.to_string())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(text.contains("Session cost (estimated)"), "{text}");
+ // The narrow layout carries it too: a small terminal still needs it.
+ let narrow = super::context_lines(&report, 30)
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.to_string())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(narrow.contains("Session cost"), "{narrow}");
+ }
+
+ /// Sub-cent spends must stay legible: `$0.00` is indistinguishable from
+ /// free, which is the one thing a cost readout may not imply.
+ #[test]
+ fn small_amounts_keep_enough_digits_to_read() {
+ assert_eq!(super::format_usd(12.3456), "$12.35");
+ assert_eq!(super::format_usd(0.4213), "$0.421");
+ assert_eq!(super::format_usd(0.0004), "$0.0004");
+ // Under the 4th decimal a fixed width would print `$0.0000`.
+ assert_eq!(super::format_usd(0.0000123), "$0.000012");
+ assert_eq!(super::format_usd(0.0000000456), "$0.000000046");
+ // A priced model that billed nothing yet is the one amount that may
+ // read as free.
+ assert_eq!(super::format_usd(0.0), "$0.0000");
+ }
+
+ /// The session totals are sums over every request, because that is what is
+ /// billed -- unlike `/context`'s window fill, which is the latest request
+ /// alone.
+ #[test]
+ fn session_usage_sums_every_request_of_the_turn() {
+ let mut app = test_app();
+ app.set_model("anthropic/claude-opus-5".to_string());
+ let usage = |prompt, completion| crate::core::agent::events::Usage {
+ prompt_tokens: Some(prompt),
+ completion_tokens: Some(completion),
+ total_tokens: None,
+ cached_tokens: Some(10),
+ cache_write_tokens: None,
+ };
+ app.apply(StreamEvent::TurnUsage {
+ usage: usage(100, 20),
+ });
+ app.apply(StreamEvent::TurnUsage {
+ usage: usage(300, 40),
+ });
+
+ let recorded = app
+ .session_usage
+ .values()
+ .next()
+ .expect("usage recorded under the current model");
+ assert_eq!(recorded.requests, 2);
+ assert_eq!(
+ recorded.prompt_tokens, 400,
+ "prompts are summed, not latched"
+ );
+ assert_eq!(recorded.completion_tokens, 60);
+ assert_eq!(recorded.cached_tokens, 20);
+ // The window fill stays the latest request's prompt.
+ assert_eq!(app.turn_prompt_tokens, 300);
+
+ // A new session starts a new bill.
+ app.reset_session();
+ assert!(app.session_usage.is_empty());
+ }
+
+ /// A subagent's tokens are spend on the same account, and `RunReport`
+ /// already counts them: leaving them out of `/usage` would make the TUI
+ /// total and the `--output-format json` envelope disagree.
+ #[test]
+ fn subagent_usage_counts_toward_the_session_total() {
+ let mut app = test_app();
+ app.set_model("anthropic/claude-opus-5".to_string());
+ let usage = |prompt: u64| crate::core::agent::events::Usage {
+ prompt_tokens: Some(prompt),
+ completion_tokens: Some(10),
+ total_tokens: None,
+ cached_tokens: None,
+ cache_write_tokens: None,
+ };
+ app.apply(StreamEvent::TurnUsage { usage: usage(100) });
+ start_subagent(&mut app, "r0", "alpha");
+ subagent_event(
+ &mut app,
+ "r0",
+ "alpha",
+ StreamEvent::TurnUsage { usage: usage(400) },
+ );
+
+ let recorded = app.session_usage.values().next().expect("usage recorded");
+ assert_eq!(recorded.requests, 2);
+ assert_eq!(recorded.prompt_tokens, 500);
+ assert_eq!(recorded.completion_tokens, 20);
+ // The parent's own window fill is untouched by the child's request.
+ assert_eq!(app.turn_prompt_tokens, 100);
+ }
+
+ /// `/usage` with nothing to report says so rather than printing an empty
+ /// table.
+ #[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"));
+ }
+
#[test]
fn context_view_shows_prompt_cache_when_reported() {
let mut report = context_report(234_000, 35_000, [6_049, 9_000, 2_149, 8_049, 95_253]);
@@ -34582,45 +35268,55 @@ mod tests {
#[test]
fn moving_to_a_larger_window_does_not_compact() {
- let mut app = test_app();
- app.context_window = 200_000;
- app.context_window_source =
- crate::core::cli::model_capabilities::ContextWindowSource::Catalog;
- app.tokens = 500_000;
- for i in 0..6 {
- app.history.push(serde_json::json!({
- "role": "user",
- "content": format!("msg{i}")
- }));
- }
- app.set_model("claude-sonnet-4-6".to_string());
+ // Isolated for the same reason as `set_model_notes_the_context_source`:
+ // the new window must come from the catalog, not a cached listing.
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let mut app = test_app();
+ app.context_window = 200_000;
+ app.context_window_source =
+ crate::core::cli::model_capabilities::ContextWindowSource::Catalog;
+ app.tokens = 500_000;
+ for i in 0..6 {
+ app.history.push(serde_json::json!({
+ "role": "user",
+ "content": format!("msg{i}")
+ }));
+ }
+ app.set_model("claude-sonnet-4-6".to_string());
- assert_eq!(app.context_window, 1_000_000);
- assert!(
- !app.should_auto_compact(),
- "the window grew past current usage"
- );
- assert_eq!(app.compact_request, None);
+ assert_eq!(app.context_window, 1_000_000);
+ assert!(
+ !app.should_auto_compact(),
+ "the window grew past current usage"
+ );
+ assert_eq!(app.compact_request, None);
+ });
}
+ /// Isolated from the real `~/.jan`: a cached `/models` listing there would
+ /// resolve these windows as `provider` and shadow the source under test.
#[test]
fn set_model_notes_the_context_source() {
- let mut app = test_app();
- app.set_model("claude-sonnet-4-6".to_string());
- let text: String = app.transcript.iter().map(row_text).collect();
- assert!(text.contains("claude-sonnet-4-6"), "got: {text}");
- assert!(text.contains("(context 1000K, catalog)"), "got: {text}");
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let mut app = test_app();
+ app.set_model("claude-sonnet-4-6".to_string());
+ let text: String = app.transcript.iter().map(row_text).collect();
+ assert!(text.contains("claude-sonnet-4-6"), "got: {text}");
+ assert!(text.contains("(context 1000K, catalog)"), "got: {text}");
+ });
}
#[test]
fn unknown_model_resolves_to_the_fallback_window() {
- let mut app = test_app();
- app.set_model("private-gateway-model".to_string());
- assert_eq!(app.context_window, 128_000);
- assert_eq!(
- app.context_window_source,
- crate::core::cli::model_capabilities::ContextWindowSource::Fallback
- );
+ crate::core::agent::global_config::with_temp_home(|_| {
+ let mut app = test_app();
+ app.set_model("private-gateway-model".to_string());
+ assert_eq!(app.context_window, 128_000);
+ assert_eq!(
+ app.context_window_source,
+ crate::core::cli::model_capabilities::ContextWindowSource::Fallback
+ );
+ });
}
#[test]