From b3bee041779e9417370b9a53353907740403f13f Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 17:12:50 -0600 Subject: [PATCH 1/7] feat(assistant): show each message's tokens and choose the effort on a ChatGPT plan --- apps/rustgis-cli/src/main.rs | 3 + crates/assistant/src/agent.rs | 26 +++++- crates/assistant/src/provider.rs | 102 +++++++++++++++++++++--- crates/assistant/src/tests.rs | 91 +++++++++++++++++++++ crates/ui-egui/src/assistant.rs | 23 ++++++ crates/ui-egui/src/assistantpane.rs | 27 +++++++ crates/ui-egui/src/assistantpictures.rs | 2 + crates/ui-egui/src/localagents.rs | 2 + crates/ui-touch/src/assistant.rs | 5 ++ docs/user-guide/assistant.md | 11 +++ 10 files changed, 281 insertions(+), 11 deletions(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index fbe7053bd2..c1ec71b64a 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -719,6 +719,9 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen allow }); show(&a); + if let Some(u) = a.usage() { + eprintln!("(tokens: {} in, {} out)", u.input, u.output); + } if a.transcript.iter().any(|e| matches!(e, Entry::Error(_))) { return Err("the assistant couldn't finish".into()); } diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 5357f80e7b..dfe996f123 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -166,6 +166,8 @@ pub struct Agent { allowed: Vec, /// The agents on this computer the model may delegate to ([`acp`]). harnesses: Vec<&'static acp::AgentSpec>, + /// The tokens this message's requests took, subagents' included ([`Agent::usage`]). + usage: provider::Usage, /// Model requests left for this message (a subagent shares its parent's budget). max_steps: u32, /// Agent threads on this computer, working or waiting for a follow-up. @@ -248,6 +250,7 @@ impl Agent { threads_started: 0, delegations: Vec::new(), reports: Vec::new(), + usage: provider::Usage::default(), max_steps: MAX_STEPS, } } @@ -336,6 +339,7 @@ impl Agent { _ => a.turns.push(Turn::User(message, Vec::new())), } a.steps = 0; + a.usage = provider::Usage::default(); a.retries = 0; a.overflow_compacted = false; a.send() @@ -465,6 +469,16 @@ impl Agent { Scope::assistant(self.conversation, self.live.clone()) } + /// The tokens the last message's requests took so far, as the provider counts them. `None` when + /// it doesn't say. + pub fn usage(&self) -> Option { + let mut usage = self.usage; + if let Some(child) = &self.child { + usage.add(child.usage); + } + (usage != provider::Usage::default()).then_some(usage) + } + /// Changes in the generation tell a caller its response is stale. pub fn generation(&self) -> u64 { self.generation @@ -477,6 +491,7 @@ impl Agent { self.turns.clear(); self.transcript.clear(); self.state = State::Idle; + self.usage = provider::Usage::default(); self.steps = 0; self.last_context.clear(); self.always.clear(); @@ -578,6 +593,7 @@ impl Agent { _ => self.turns.push(Turn::User(message, pictures)), } self.steps = 0; + self.usage = provider::Usage::default(); self.retries = 0; self.overflow_compacted = false; self.send() @@ -842,6 +858,7 @@ impl Agent { } self.retries = 0; if let Ok(reply) = &parsed { + self.usage.add(reply.usage.unwrap_or_default()); self.transcript.extend(reply.notes.iter().cloned().map(Entry::Note)); } if let State::Compacting { upto, resume } = self.state { @@ -1118,6 +1135,7 @@ impl Agent { let Some(child) = self.child.take() else { return Step::Done }; // Its steps count against this message's budget; its "always" approvals stay. self.steps = self.steps.saturating_add(child.steps); + self.usage.add(child.usage); for key in &child.always { if self.always.contains(key) { continue; @@ -1233,7 +1251,9 @@ impl Agent { if let Some(child) = self.child.as_mut() { child.stop(); self.show_child(); - self.child = None; + if let Some(child) = self.child.take() { + self.usage.add(child.usage); + } } self.halt(Entry::Note(Note::new("Stopped.")), "Stopped by the user.", "Stopped by the user."); } @@ -1283,7 +1303,9 @@ impl Agent { fn halt(&mut self, why: Entry, queued: &str, interrupted: &str) { self.live.0.store(false, Ordering::SeqCst); self.pending_policy = None; - self.child = None; + if let Some(child) = self.child.take() { + self.usage.add(child.usage); + } self.retrying_summary = None; self.retries = 0; self.preview = None; diff --git a/crates/assistant/src/provider.rs b/crates/assistant/src/provider.rs index 526545b966..0d0b58447b 100644 --- a/crates/assistant/src/provider.rs +++ b/crates/assistant/src/provider.rs @@ -232,12 +232,19 @@ pub struct Config { /// Whether the catalog offers reasoning for the selected model (`Some(false)` also turns it off /// for a Chat Completions model that refused it alongside tools: see [`refuses_reasoning_with_tools`]). pub reasoning: Option, + /// How hard the model thinks, as the ChatGPT catalog names it; empty for [`DEFAULT_EFFORT`]. + pub effort: String, + /// The efforts the catalog offers for the selected model; empty when it doesn't say. + pub efforts: Vec, /// OpenRouter routing excludes endpoints that collect request data by default. pub openrouter_private: bool, /// Requested tool output token estimate (default 10,000); the 24,000-token hard limit still applies. pub tool_output_token_limit: usize, } +/// The reasoning effort on a ChatGPT plan unless another is chosen. +pub const DEFAULT_EFFORT: &str = "medium"; + impl std::fmt::Debug for Config { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Config").field("provider", &self.provider).field("model", &self.model).finish_non_exhaustive() @@ -245,6 +252,18 @@ impl std::fmt::Debug for Config { } impl Config { + /// The effort requests ask for: the one chosen where the model takes it, else the default, else + /// the first it takes. + pub fn effort_sent(&self) -> &str { + // A catalog that doesn't say takes the default alone: another might be refused. + let takes = |e: &str| (self.efforts.is_empty() && e == DEFAULT_EFFORT) || self.efforts.iter().any(|x| x == e); + match self.effort.trim() { + chosen if takes(chosen) => chosen, + _ if takes(DEFAULT_EFFORT) => DEFAULT_EFFORT, + _ => self.efforts.first().map_or(DEFAULT_EFFORT, String::as_str), + } + } + /// The preset's defaults, with a key and base URL from the environment where set. A sign-in /// provider's account is not read here: its tokens are in the system keychain, which may block /// (`chatgpt::load_any`, then [`Config::sign_in`]). @@ -266,6 +285,8 @@ impl Config { client_id: String::new(), session: String::new(), reasoning: None, + effort: env("RUSTGIS_ASSISTANT_EFFORT").unwrap_or_default(), + efforts: Vec::new(), openrouter_private: env("RUSTGIS_OPENROUTER_DATA_COLLECTION").as_deref() != Some("allow"), tool_output_token_limit: env("RUSTGIS_ASSISTANT_TOOL_OUTPUT_TOKEN_LIMIT") .and_then(|s| s.parse().ok()) @@ -804,6 +825,40 @@ impl std::fmt::Display for Note { } } +/// The tokens a request took, as the provider counts them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Usage { + /// What was sent, cached or not. + pub input: u64, + /// What came back, reasoning included. + pub output: u64, +} + +impl Usage { + /// The counts in a reply, in whichever API's form it has them. `None` when it has none. + fn of(reply: &Value) -> Option { + let sum = |v: &Value, keys: &[&str]| { + let found: Vec = keys.iter().filter_map(|k| v.get(k).and_then(Value::as_u64)).collect(); + found.iter().copied().reduce(u64::saturating_add) + }; + let (input, output) = match (reply.get("usage"), reply.get("usageMetadata")) { + (Some(u), _) if u.is_object() => ( + // Anthropic's input_tokens leaves out what the cache read and wrote. + sum(u, &["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "prompt_tokens"]), + sum(u, &["output_tokens", "completion_tokens"]), + ), + (_, Some(u)) => (sum(u, &["promptTokenCount"]), sum(u, &["candidatesTokenCount", "thoughtsTokenCount"])), + _ => return None, + }; + (input.is_some() || output.is_some()).then(|| Usage { input: input.unwrap_or(0), output: output.unwrap_or(0) }) + } + + pub(crate) fn add(&mut self, more: Usage) { + self.input = self.input.saturating_add(more.input); + self.output = self.output.saturating_add(more.output); + } +} + /// A reply read from the provider. #[derive(Clone, Debug)] pub struct Reply { @@ -816,6 +871,8 @@ pub struct Reply { pub cut: Option, /// A failed terminal response accompanying partial text. pub failure: Option, + /// The tokens it took, if the provider says. + pub usage: Option, } /// Replies may be long (tables, explanations) but are never documents. @@ -861,7 +918,8 @@ fn parse_reply_inner(api: Api, resp: &HttpResponse) -> Result { e.request_id = resp.request_id().map(str::to_string); return Err(e); } - parse(&v).map_err(Error::from) + let usage = Usage::of(&v); + parse(&v).map(|r| Reply { usage, ..r }).map_err(Error::from) } // --------------------------------------------------------------------------------------------- @@ -927,6 +985,8 @@ fn stream_ended(api: Api, text: &str, events: &[Value]) -> bool { fn openai_assembled(events: &[Value]) -> Value { let (mut content, mut reasoning, mut finish) = (Value::Null, String::new(), Value::Null); let mut calls: Vec<(String, String, String)> = Vec::new(); + // The last chunk's, which has no choices. + let usage = events.iter().rev().find_map(|e| e.get("usage").filter(|u| u.is_object())); for e in events { for choice in e.get("choices").and_then(Value::as_array).into_iter().flatten() { let delta = choice.get("delta").unwrap_or(&Value::Null); @@ -993,7 +1053,7 @@ fn openai_assembled(events: &[Value]) -> Value { if !reasoning.is_empty() { message["reasoning_content"] = json!(reasoning); } - json!({"choices": [{"finish_reason": finish, "message": message}]}) + json!({"choices": [{"finish_reason": finish, "message": message}], "usage": usage}) } /// Anthropic events: content blocks started, extended by deltas (text, tool input JSON, @@ -1041,6 +1101,13 @@ fn anthropic_assembled(events: &[Value]) -> Value { for (k, v) in e.get("delta").and_then(Value::as_object).into_iter().flatten() { message[k] = v.clone(); } + // The counts at the end replace those of the start, kind by kind. + for (k, v) in e.get("usage").and_then(Value::as_object).into_iter().flatten().filter(|(_, v)| v.is_u64()) { + if !message["usage"].is_object() { + message["usage"] = json!({}); + } + message["usage"][k] = v.clone(); + } } _ => {} } @@ -1069,6 +1136,7 @@ fn gemini_assembled(events: &[Value]) -> Value { let mut parts: Vec = Vec::new(); let mut finish = Value::Null; let mut feedback = Value::Null; + let usage = events.iter().rev().find_map(|e| e.get("usageMetadata")); for e in events { if let Some(f) = e.get("promptFeedback") { feedback = f.clone(); @@ -1082,7 +1150,7 @@ fn gemini_assembled(events: &[Value]) -> Value { if parts.is_empty() && finish.is_null() { return json!({"promptFeedback": feedback}); } - json!({"candidates": [{"content": {"role": "model", "parts": parts}, "finishReason": finish}]}) + json!({"candidates": [{"content": {"role": "model", "parts": parts}, "finishReason": finish}], "usageMetadata": usage}) } /// A streamed reply's text so far, for showing while it arrives (what runs is read from the @@ -1236,6 +1304,11 @@ fn openai_request(cfg: &Config, system: &str, turns: &[Turn], tools: &[ToolDef]) .map(|t| json!({"type": "function", "function": {"name": t.name, "description": t.description, "parameters": t.schema}})) .collect(); let mut body = json!({"model": cfg.model.trim(), "messages": messages, "stream": true}); + // OpenAI counts a stream's tokens only when asked. Other servers aren't: some refuse fields + // they don't know. + if cfg.provider == "openai" && preset("openai").is_some_and(|p| cfg.base() == p.base_url) { + body["stream_options"] = json!({"include_usage": true}); + } if cfg.provider == "openrouter" && cfg.openrouter_private { body["provider"] = json!({"data_collection": "deny"}); } @@ -1417,7 +1490,7 @@ fn openai_reply(v: &Value) -> Result { if let Some(o) = native.as_object_mut() { o.retain(|k, _| matches!(k.as_str(), "role" | "content" | "tool_calls" | "reasoning_content")); } - Ok(Reply { text, calls, native, notes, cut, failure: None }) + Ok(Reply { text, calls, native, notes, cut, failure: None, usage: None }) } // --------------------------------------------------------------------------------------------- @@ -1478,7 +1551,7 @@ fn responses_request(cfg: &Config, system: &str, turns: &[Turn], tools: &[ToolDe }); // Older catalogs omit the capability; keep the existing behavior in that case. if cfg.reasoning != Some(false) { - body["reasoning"] = json!({"effort": "medium"}); + body["reasoning"] = json!({"effort": cfg.effort_sent()}); body["include"] = json!(["reasoning.encrypted_content"]); } if !functions.is_empty() { @@ -1638,7 +1711,7 @@ fn responses_reply(resp: &HttpResponse) -> Result { }) .collect(); let failure = (!completed && last.get("error").is_some_and(Value::is_object)).then(|| Error::response(&last, resp)); - Ok(Reply { text, calls, native: Value::Array(native), notes: Vec::new(), cut, failure }) + Ok(Reply { text, calls, native: Value::Array(native), notes: Vec::new(), cut, failure, usage: Usage::of(&last) }) } // --------------------------------------------------------------------------------------------- @@ -1765,7 +1838,7 @@ fn anthropic_reply(v: &Value) -> Result { if v.get("stop_reason").and_then(Value::as_str) == Some("refusal") { calls.clear(); } - Ok(Reply { text, calls, native: Value::Array(content.clone()), notes: Vec::new(), cut, failure: None }) + Ok(Reply { text, calls, native: Value::Array(content.clone()), notes: Vec::new(), cut, failure: None, usage: None }) } // --------------------------------------------------------------------------------------------- @@ -1905,7 +1978,7 @@ fn gemini_reply(v: &Value) -> Result { if native.get("role").is_none() { native["role"] = json!("model"); } - Ok(Reply { text, calls, native, notes: Vec::new(), cut, failure: None }) + Ok(Reply { text, calls, native, notes: Vec::new(), cut, failure: None, usage: None }) } /// `v` if it is an object, else an empty one (providers require objects for tool input). @@ -2006,6 +2079,8 @@ pub struct Model { pub name: String, /// Reasoning support, or unknown for older catalogs. pub reasoning: Option, + /// The reasoning efforts it takes; empty for catalogs that don't say. + pub efforts: Vec, } /// Reads the visible ChatGPT catalog, in server order. @@ -2025,7 +2100,15 @@ pub fn parse_catalog(resp: &HttpResponse) -> Result, Error> { .get("supports_reasoning") .and_then(Value::as_bool) .or_else(|| m.get("supported_reasoning_levels").and_then(Value::as_array).map(|a| !a.is_empty())); - Some(Model { id: id.into(), name: m.get("display_name").and_then(Value::as_str).unwrap_or(id).into(), reasoning }) + // Each a name, or an object with one. + let efforts = m.get("supported_reasoning_levels").and_then(Value::as_array).into_iter().flatten(); + let efforts = efforts + .filter_map(|l| l.as_str().or_else(|| l.get("effort").and_then(Value::as_str))) + .filter(|l| !l.is_empty() && l.len() <= 32) + .take(16) + .map(str::to_string) + .collect(); + Some(Model { id: id.into(), name: m.get("display_name").and_then(Value::as_str).unwrap_or(id).into(), reasoning, efforts }) }) .take(2000) .collect()) @@ -2035,6 +2118,7 @@ pub fn parse_catalog(resp: &HttpResponse) -> Result, Error> { pub fn use_catalog(cfg: &mut Config, models: &[Model], explicit: bool) { let selected = models.iter().find(|m| m.id == cfg.model).or_else(|| if explicit { None } else { models.first() }); cfg.reasoning = selected.and_then(|m| m.reasoning); + cfg.efforts = selected.map(|m| m.efforts.clone()).unwrap_or_default(); if let Some(model) = selected { cfg.model = model.id.clone(); } diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index d4d45f7faa..e82ef557ad 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -54,6 +54,8 @@ fn cfg(provider: &str) -> Config { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: crate::tools::DEFAULT_OUTPUT_TOKENS, } @@ -2502,6 +2504,95 @@ fn incomplete_responses_never_execute_or_replay_calls() { } } +#[test] +fn the_effort_chosen_is_sent_where_the_model_takes_it() { + let response = HttpResponse { + status: 200, + headers: vec![], + body: json!({"models": [ + {"slug":"both", "visibility":"list", "supported_reasoning_levels":[{"effort":"low"}, {"effort":"medium"}, "high", {"x":1}, 3]}, + {"slug":"high-only", "visibility":"list", "supported_reasoning_levels":["high"]}, + {"slug":"unsaid", "visibility":"list"} + ]}) + .to_string() + .into_bytes(), + }; + let models = parse_catalog(&response).unwrap(); + assert_eq!(models[0].efforts, ["low", "medium", "high"]); + let sent = |model: &str, effort: &str| { + let mut cfg = Config { model: model.into(), effort: effort.into(), ..chatgpt_cfg() }; + use_catalog(&mut cfg, &models, true); + body(&chat_request(&cfg, "hello", &[], &[]))["reasoning"]["effort"].as_str().unwrap().to_string() + }; + assert_eq!([sent("both", ""), sent("both", "high"), sent("both", "gone")], ["medium", "high", "medium"]); + assert_eq!([sent("high-only", ""), sent("high-only", "low")], ["high", "high"]); + assert_eq!([sent("unsaid", ""), sent("unsaid", "typo")], ["medium", "medium"]); +} + +#[test] +fn every_api_says_its_tokens_streamed_or_not() { + let http = |text: String| HttpResponse { status: 200, headers: vec![], body: text.into_bytes() }; + let stream = |events: &[Value]| http(events.iter().map(|e| format!("data: {e}\n\n")).collect()); + let usage = |api, r: HttpResponse| parse_reply(api, &r).unwrap().usage; + let want = Some(Usage { input: 120, output: 30 }); + + let counts = json!({"prompt_tokens": 120, "completion_tokens": 30, "total_tokens": 150}); + let mut plain = say("hi"); + assert_eq!(usage(Api::OpenAi, http(plain.to_string())), None); + plain["usage"] = counts.clone(); + assert_eq!(usage(Api::OpenAi, http(plain.to_string())), want); + let chunk = json!({"choices": [{"delta": {"content": "hi"}, "finish_reason": "stop"}], "usage": null}); + assert_eq!(usage(Api::OpenAi, stream(&[chunk.clone(), json!({"choices": [], "usage": counts})])), want); + assert_eq!(usage(Api::OpenAi, stream(&[chunk])), None); + + let start = json!({"type": "message_start", "message": {"usage": {"input_tokens": 20, "cache_read_input_tokens": 90, "cache_creation_input_tokens": 10, "output_tokens": 1}}}); + let block = json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": "hi"}}); + let end = json!({"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 30}}); + assert_eq!(usage(Api::Anthropic, stream(&[start, block, end, json!({"type": "message_stop"})])), want); + + let gemini = json!({"candidates": [{"content": {"parts": [{"text": "hi"}]}, "finishReason": "STOP"}], + "usageMetadata": {"promptTokenCount": 120, "candidatesTokenCount": 10, "thoughtsTokenCount": 20}}); + assert_eq!(usage(Api::Gemini, stream(&[gemini])), want); + + let done = json!({"type": "response.completed", "response": {"status": "completed", "output": [], "usage": {"input_tokens": 120, "output_tokens": 30}}}); + assert_eq!(usage(Api::Responses, stream(&[done])), want); + + // Nonsense counts are none. + for bad in [json!(3), json!([]), json!({"prompt_tokens": -1, "completion_tokens": "many"})] { + plain["usage"] = bad; + assert_eq!(usage(Api::OpenAi, http(plain.to_string())), None); + } + // Only OpenAI itself is asked for them. + let asks = |c: &Config| body(&chat_request(c, "s", &[], &[])).get("stream_options").is_some(); + let elsewhere = Config { base_url: "https://proxy.example/v1".into(), ..cfg("openai") }; + assert!(asks(&cfg("openai")) && !asks(&elsewhere) && !asks(&cfg("mistral")) && !asks(&cfg("custom"))); +} + +#[test] +fn a_messages_tokens_add_up_with_its_subagents() { + let mut s = sample(); + let mut a = Agent::new(cfg("openai"), &s); + let with = |mut reply: Value, input: u64| { + reply["usage"] = json!({"prompt_tokens": input, "completion_tokens": 1}); + ok(reply) + }; + a.ask("look", &s); + assert_eq!(a.usage(), None); + a.receive(a.generation(), with(call("1", "delegate", json!({"task": "look"})), 10), &mut s); + a.receive(a.generation(), with(call("2", "list_layers", json!({})), 200), &mut s); + assert_eq!(a.usage(), Some(Usage { input: 210, output: 2 }), "a subagent still at work counts"); + a.receive(a.generation(), with(say("seen"), 300), &mut s); + a.receive(a.generation(), with(say("done"), 4000), &mut s); + assert_eq!(a.usage(), Some(Usage { input: 4510, output: 4 })); + a.ask("again", &s); + assert_eq!(a.usage(), None, "counted by message"); + // A stop keeps what the subagent had taken. + a.receive(a.generation(), with(call("3", "delegate", json!({"task": "look"})), 10), &mut s); + a.receive(a.generation(), with(call("4", "list_layers", json!({})), 200), &mut s); + a.stop(); + assert_eq!(a.usage(), Some(Usage { input: 210, output: 2 })); +} + #[test] fn catalog_defaults_names_and_reasoning_capabilities() { let response = HttpResponse { diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 026a51b973..62912cc20f 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -143,6 +143,21 @@ impl AssistantState { self.agent.as_ref().map_or(&[], |a| a.transcript.as_slice()) } + /// The tokens the last message took so far, in words; `None` when the provider doesn't say. + pub fn usage_line(&self) -> Option { + let usage = self.agent.as_ref().and_then(Agent::usage)?; + // Digits in threes, apart by a space, which reads the same in every language. + let count = |n: u64| { + let digits = n.to_string(); + let threes: Vec = digits.as_bytes().rchunks(3).rev().map(|c| String::from_utf8_lossy(c).into_owned()).collect(); + threes.join(" ") + }; + Some(crate::i18n::fmt( + "Tokens for this message: {input} in, {output} out", + &[("input", &count(usage.input)), ("output", &count(usage.output))], + )) + } + /// The text so far of a reply still streaming in. pub fn preview(&self) -> Option<&str> { self.agent.as_ref().and_then(Agent::preview) @@ -270,6 +285,9 @@ fn load_config(app: &mut RustGisApp, provider: &str, ctx: &egui::Context) -> Con if provider == "openrouter" { c.openrouter_private = pref(app, provider::OPENROUTER_PRIVATE_PREF).as_deref() != Some("off"); } + if let Some(effort) = pref(app, &format!("assistant_effort_{provider}")).filter(|_| c.login()) { + c.effort = effort; + } if !c.login() { let legacy = pref(app, &format!("assistant_key_{provider}")); #[cfg(not(target_arch = "wasm32"))] @@ -513,6 +531,11 @@ pub(crate) fn save_config(app: &mut RustGisApp, c: &Config, ctx: &egui::Context) // A key from the environment stays there; a sign-in's tokens live in their own file. let from_env = Config::from_env(&c.provider).key; if c.login() { + let name = format!("assistant_effort_{}", c.provider); + // The environment's choice stays there, unless another was made here. + if c.effort != Config::from_env(&c.provider).effort || pref(app, &name).is_some() { + save_pref(app, &name, &c.effort); + } return; } let pref_key = format!("assistant_key_{}", c.provider); diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 2c13221779..0a0fcf0185 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -219,6 +219,22 @@ fn provider_settings(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, cfg: &mut Co }); }); ui.end_row(); + if cfg.login() && !signed_out && cfg.reasoning != Some(false) && !cfg.efforts.is_empty() { + let effort_label = ui.label(tl!("Effort")); + egui::ComboBox::from_id_salt("assistant_effort") + .selected_text(cfg.effort_sent().to_string()) + .show_ui(ui, |ui| { + for effort in cfg.efforts.clone() { + if ui.selectable_label(cfg.effort_sent() == effort, &effort).clicked() { + cfg.effort = effort; + } + } + }) + .response + .labelled_by(effort_label.id) + .on_hover_text(tl!("How much the model thinks before it answers. More is slower and uses more of your plan.")); + ui.end_row(); + } let preset = provider::preset(&cfg.provider); if !cfg.login() { let address_label = ui.label(tl!("Address")); @@ -829,6 +845,11 @@ fn transcript(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context } } } + if !app.assistant.busy() + && let Some(line) = app.assistant.usage_line() + { + ui.label(RichText::new(line).small().color(t.text_dim)); + } if app.assistant.waiting() { // The reply so far, as it streams in. if let Some(text) = app.assistant.preview() { @@ -1769,6 +1790,8 @@ pub(crate) mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; @@ -2253,6 +2276,8 @@ pub(crate) mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; @@ -2275,6 +2300,8 @@ pub(crate) mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; diff --git a/crates/ui-egui/src/assistantpictures.rs b/crates/ui-egui/src/assistantpictures.rs index ad8f1387e9..6dfd4c1713 100644 --- a/crates/ui-egui/src/assistantpictures.rs +++ b/crates/ui-egui/src/assistantpictures.rs @@ -523,6 +523,8 @@ mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; diff --git a/crates/ui-egui/src/localagents.rs b/crates/ui-egui/src/localagents.rs index 54e4508886..570f6905d2 100644 --- a/crates/ui-egui/src/localagents.rs +++ b/crates/ui-egui/src/localagents.rs @@ -683,6 +683,8 @@ mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index e3fbf1d6a7..f75fc1aa9b 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -446,6 +446,11 @@ fn messages(app: &RustGisApp, ui: &mut Ui, t: &Tokens) { } } } + if !app.assistant.busy() + && let Some(line) = app.assistant.usage_line() + { + ui.label(RichText::new(line).size(13.0).color(t.text_dim)); + } if app.assistant.waiting() { match app.assistant.preview() { Some(text) => { diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index 45877092aa..3b0bdb5b72 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -140,6 +140,17 @@ field changes the endpoint for providers other than ChatGPT; use the OpenAI-comp path (usually `/v1`) for local servers. Models that call tools well give the best results; small local models may stop early or skip steps. +### Tokens and effort + +After each message, the pane shows the tokens its requests took, subagents' included, as the +provider counts them. Tokens in are counted for every request, so a long run counts the +conversation many times, though providers usually charge less for what they had cached. Nothing +is shown for a server that doesn't report them. + +With a ChatGPT sign-in, **Effort** sets how much the model thinks before it answers, where the +model offers a choice (`medium` unless you choose). `RUSTGIS_ASSISTANT_EFFORT` sets it on the +command line. + ### OpenRouter private routing **Private routing** is on by default for OpenRouter. Every chat request, including summaries From 3a685f78bbdf2aea354b84705bdd699ac28dc20d Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 18:58:14 -0600 Subject: [PATCH 2/7] fix(assistant): partial token counts, the effort fallback, and a switch for the tokens line --- apps/rustgis-cli/src/main.rs | 3 ++- crates/assistant/src/agent.rs | 5 ++-- crates/assistant/src/provider.rs | 5 +++- crates/assistant/src/tests.rs | 13 +++++++--- crates/ui-egui/src/assistant.rs | 34 ++++++++++++++++++++---- crates/ui-egui/src/assistantpane.rs | 40 +++++++++++++++++++++++++++++ crates/ui-touch/src/assistant.rs | 4 +++ docs/user-guide/assistant.md | 6 +++-- 8 files changed, 95 insertions(+), 15 deletions(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index c1ec71b64a..fbf7ab5653 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -720,7 +720,8 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen }); show(&a); if let Some(u) = a.usage() { - eprintln!("(tokens: {} in, {} out)", u.input, u.output); + let least = if u.partial { "at least " } else { "" }; + eprintln!("(tokens: {least}{} in, {} out)", u.input, u.output); } if a.transcript.iter().any(|e| matches!(e, Entry::Error(_))) { return Err("the assistant couldn't finish".into()); diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index dfe996f123..66c7cd372a 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -476,7 +476,7 @@ impl Agent { if let Some(child) = &self.child { usage.add(child.usage); } - (usage != provider::Usage::default()).then_some(usage) + (usage.input > 0 || usage.output > 0).then_some(usage) } /// Changes in the generation tell a caller its response is stale. @@ -858,7 +858,8 @@ impl Agent { } self.retries = 0; if let Ok(reply) = &parsed { - self.usage.add(reply.usage.unwrap_or_default()); + // A request that doesn't say is noted, so the total isn't taken for the whole. + self.usage.add(reply.usage.unwrap_or(provider::Usage { partial: true, ..Default::default() })); self.transcript.extend(reply.notes.iter().cloned().map(Entry::Note)); } if let State::Compacting { upto, resume } = self.state { diff --git a/crates/assistant/src/provider.rs b/crates/assistant/src/provider.rs index 0d0b58447b..cedd1b2aff 100644 --- a/crates/assistant/src/provider.rs +++ b/crates/assistant/src/provider.rs @@ -832,6 +832,8 @@ pub struct Usage { pub input: u64, /// What came back, reasoning included. pub output: u64, + /// Some of the requests counted didn't say what they took: the counts are less than it was. + pub partial: bool, } impl Usage { @@ -850,12 +852,13 @@ impl Usage { (_, Some(u)) => (sum(u, &["promptTokenCount"]), sum(u, &["candidatesTokenCount", "thoughtsTokenCount"])), _ => return None, }; - (input.is_some() || output.is_some()).then(|| Usage { input: input.unwrap_or(0), output: output.unwrap_or(0) }) + (input.is_some() || output.is_some()).then(|| Usage { input: input.unwrap_or(0), output: output.unwrap_or(0), partial: false }) } pub(crate) fn add(&mut self, more: Usage) { self.input = self.input.saturating_add(more.input); self.output = self.output.saturating_add(more.output); + self.partial |= more.partial; } } diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index e82ef557ad..e582650818 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -2534,7 +2534,7 @@ fn every_api_says_its_tokens_streamed_or_not() { let http = |text: String| HttpResponse { status: 200, headers: vec![], body: text.into_bytes() }; let stream = |events: &[Value]| http(events.iter().map(|e| format!("data: {e}\n\n")).collect()); let usage = |api, r: HttpResponse| parse_reply(api, &r).unwrap().usage; - let want = Some(Usage { input: 120, output: 30 }); + let want = Some(Usage { input: 120, output: 30, partial: false }); let counts = json!({"prompt_tokens": 120, "completion_tokens": 30, "total_tokens": 150}); let mut plain = say("hi"); @@ -2580,17 +2580,22 @@ fn a_messages_tokens_add_up_with_its_subagents() { assert_eq!(a.usage(), None); a.receive(a.generation(), with(call("1", "delegate", json!({"task": "look"})), 10), &mut s); a.receive(a.generation(), with(call("2", "list_layers", json!({})), 200), &mut s); - assert_eq!(a.usage(), Some(Usage { input: 210, output: 2 }), "a subagent still at work counts"); + assert_eq!(a.usage(), Some(Usage { input: 210, output: 2, partial: false }), "a subagent still at work counts"); a.receive(a.generation(), with(say("seen"), 300), &mut s); a.receive(a.generation(), with(say("done"), 4000), &mut s); - assert_eq!(a.usage(), Some(Usage { input: 4510, output: 4 })); + assert_eq!(a.usage(), Some(Usage { input: 4510, output: 4, partial: false })); a.ask("again", &s); assert_eq!(a.usage(), None, "counted by message"); + // A request that doesn't say makes the total a lower bound. + a.receive(a.generation(), with(call("q", "list_layers", json!({})), 50), &mut s); + a.receive(a.generation(), ok(say("done")), &mut s); + assert_eq!(a.usage(), Some(Usage { input: 50, output: 1, partial: true })); + a.ask("again", &s); // A stop keeps what the subagent had taken. a.receive(a.generation(), with(call("3", "delegate", json!({"task": "look"})), 10), &mut s); a.receive(a.generation(), with(call("4", "list_layers", json!({})), 200), &mut s); a.stop(); - assert_eq!(a.usage(), Some(Usage { input: 210, output: 2 })); + assert_eq!(a.usage(), Some(Usage { input: 210, output: 2, partial: false })); } #[test] diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 62912cc20f..ded53b0388 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -108,6 +108,8 @@ pub struct AssistantState { pub(crate) retry: Option<(u64, web_time::Instant)>, /// The user lets the assistant hand tasks to local agents (Claude Code, Codex). pub(crate) local_agents: bool, + /// The tokens a message took are left out of the conversation (shown unless the user says). + pub(crate) hide_tokens: bool, /// Agent threads on this computer: their processes, windows and requests (desktop). #[cfg(not(target_arch = "wasm32"))] pub(crate) threads: crate::agentthreads::Threads, @@ -143,8 +145,12 @@ impl AssistantState { self.agent.as_ref().map_or(&[], |a| a.transcript.as_slice()) } - /// The tokens the last message took so far, in words; `None` when the provider doesn't say. + /// A line of the tokens the last message took so far, "at least" when some of its requests + /// didn't say; `None` when none did, or when the user turned the line off. pub fn usage_line(&self) -> Option { + if self.hide_tokens { + return None; + } let usage = self.agent.as_ref().and_then(Agent::usage)?; // Digits in threes, apart by a space, which reads the same in every language. let count = |n: u64| { @@ -152,10 +158,13 @@ impl AssistantState { let threes: Vec = digits.as_bytes().rchunks(3).rev().map(|c| String::from_utf8_lossy(c).into_owned()).collect(); threes.join(" ") }; - Some(crate::i18n::fmt( - "Tokens for this message: {input} in, {output} out", - &[("input", &count(usage.input)), ("output", &count(usage.output))], - )) + let counts = [("input", count(usage.input)), ("output", count(usage.output))]; + let counts = counts.each_ref().map(|(k, v)| (*k, v.as_str())); + Some(if usage.partial { + crate::i18n::fmt("Tokens for this message: at least {input} in, {output} out (some requests didn't say)", &counts) + } else { + crate::i18n::fmt("Tokens for this message: {input} in, {output} out", &counts) + }) } /// The text so far of a reply still streaming in. @@ -266,6 +275,20 @@ pub(crate) fn pref(app: &RustGisApp, key: &str) -> Option { app.services.load_pref.as_ref().and_then(|l| l(key)).filter(|v| !v.is_empty()) } +/// The preference that hides the tokens a message took ("off"), shown otherwise. +const TOKENS_PREF: &str = "assistant_show_tokens"; + +/// Shows or hides the tokens each message took, and remembers it. +pub fn show_tokens(app: &mut RustGisApp, show: bool) { + app.assistant.hide_tokens = !show; + save_pref(app, TOKENS_PREF, if show { "on" } else { "off" }); +} + +/// Whether the tokens each message took are shown. +pub fn showing_tokens(app: &RustGisApp) -> bool { + !app.assistant.hide_tokens +} + /// Saves a preference through the platform hook. pub(crate) fn save_pref(app: &RustGisApp, key: &str, value: &str) { if let Some(s) = &app.services.save_pref { @@ -346,6 +369,7 @@ pub(crate) fn ensure_loaded(app: &mut RustGisApp, ctx: &egui::Context) { } let mut agent = Agent::new(cfg, &app.session); app.assistant.local_agents = pref(app, "assistant_local_agents").as_deref() == Some("on"); + app.assistant.hide_tokens = pref(app, TOKENS_PREF).as_deref() == Some("off"); #[cfg(not(target_arch = "wasm32"))] { app.assistant.agents_auto = pref(app, "assistant_agents_auto").as_deref() == Some("on"); diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 0a0fcf0185..dfde4c4cfb 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -122,6 +122,14 @@ fn settings(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { { ui.label(RichText::new(tl!(why)).small().color(t.amber)); } + let mut tokens = assistant::showing_tokens(app); + if ui + .checkbox(&mut tokens, tl!("Show the tokens each message uses")) + .on_hover_text(tl!("As the provider counts them, under the last reply. Some servers don't say.")) + .changed() + { + assistant::show_tokens(app, tokens); + } #[cfg(not(target_arch = "wasm32"))] local_agents_setting(app, ui, t); #[cfg(not(target_arch = "wasm32"))] @@ -1342,6 +1350,38 @@ pub(crate) mod tests { ) } + /// The tokens a message took show under it, until the setting turns them off, which is kept. + #[test] + fn the_tokens_line_follows_its_setting() { + use egui_kittest::kittest::Queryable; + use std::sync::{Arc, Mutex}; + let mut app = plan_app(); + let saved = Arc::new(Mutex::new(Vec::new())); + let keep = saved.clone(); + app.services.save_pref = Some(Box::new(move |k, v| keep.lock().unwrap().push((k.to_string(), v.to_string())))); + let mut agent = Agent::new(Config { model: "m".into(), ..Config::from_env("custom") }, &app.session); + agent.ask("hi", &app.session); + let body = serde_json::json!({"choices": [{"message": {"role": "assistant", "content": "Hello."}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1234, "completion_tokens": 5}}); + let body = body.to_string().into_bytes(); + agent.receive(agent.generation(), Ok(HttpResponse { status: 200, body, headers: vec![] }), &mut app.session); + app.assistant.agent = Some(agent); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 860.0)).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h.get_by_label("Tokens for this message: 1 234 in, 5 out"); + h.get_by_label("Show the tokens each message uses").click(); + h.run_steps(4); + assert!(h.query_by_label("Tokens for this message: 1 234 in, 5 out").is_none()); + assert!(saved.lock().unwrap().contains(&("assistant_show_tokens".into(), "off".into()))); + } + /// The actual Remember checkbox goes through the deferred save path and deletes the stored key. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index f75fc1aa9b..4ce3b18fd3 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -672,6 +672,10 @@ fn settings_form(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat } } } + let tokens = assistant::showing_tokens(app); + if toggle_chip(ui, t, tl!("Show the tokens each message uses"), ui.available_width(), tokens) { + assistant::show_tokens(app, !tokens); + } if let Some(why) = cfg.missing() { ui.label(RichText::new(tl!(why)).size(14.0).color(t.amber)); } else if action(ui, t, if started { tl!("Done") } else { tl!("Start") }, ui.available_width(), true, true) { diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index 3b0bdb5b72..9a229b5ebe 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -145,10 +145,12 @@ small local models may stop early or skip steps. After each message, the pane shows the tokens its requests took, subagents' included, as the provider counts them. Tokens in are counted for every request, so a long run counts the conversation many times, though providers usually charge less for what they had cached. Nothing -is shown for a server that doesn't report them. +is shown for a server that doesn't report them, and "at least" when some of a message's requests +didn't. **Show the tokens each message uses** in the settings turns the line off. With a ChatGPT sign-in, **Effort** sets how much the model thinks before it answers, where the -model offers a choice (`medium` unless you choose). `RUSTGIS_ASSISTANT_EFFORT` sets it on the +model offers a choice: `medium` unless you choose, or the model's first level when it has no +`medium`. `RUSTGIS_ASSISTANT_EFFORT` sets it on the command line. ### OpenRouter private routing From 88a8b614f375c047d0c3497e9d42b64ef7a71565 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 19:56:13 -0600 Subject: [PATCH 3/7] fix(assistant): a failed or half-reported request makes the count partial --- apps/rustgis-cli/src/main.rs | 4 ++++ crates/assistant/src/agent.rs | 4 ++++ crates/assistant/src/provider.rs | 7 ++++++- crates/assistant/src/tests.rs | 11 +++++++++++ docs/user-guide/assistant.md | 4 ++-- 5 files changed, 27 insertions(+), 3 deletions(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index fbf7ab5653..59c85b6b79 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -676,6 +676,10 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen } let pictures = ask_pictures(args)?; eprintln!("[{} · {}]", cfg.provider, cfg.model); + // A level asked for that the model doesn't take isn't sent: said. + if cfg.login() && cfg.reasoning != Some(false) && !cfg.effort.trim().is_empty() && cfg.effort.trim() != cfg.effort_sent() { + eprintln!("rustgis-cli: {} doesn't offer the effort {:?}; {} is used", cfg.model, cfg.effort.trim(), cfg.effort_sent()); + } let yes = args.iter().any(|a| a == "--yes"); let trace_key = cfg.key.clone(); let mut a = Agent::new(cfg, s); diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 705d0f5a75..42e14d9d93 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -828,6 +828,10 @@ impl Agent { } self.preview = None; let parsed = resp.as_ref().map_err(Clone::clone).and_then(|r| provider::parse_reply(self.config.api(), r)); + // A request that failed may still have been charged for, without saying how much. + if parsed.is_err() { + self.usage.partial = true; + } if self.config.provider == "openrouter" && matches!(&parsed, Err(e) if e.status == Some(404) && { let detail = e.detail.to_ascii_lowercase(); diff --git a/crates/assistant/src/provider.rs b/crates/assistant/src/provider.rs index cedd1b2aff..e520565e55 100644 --- a/crates/assistant/src/provider.rs +++ b/crates/assistant/src/provider.rs @@ -852,7 +852,12 @@ impl Usage { (_, Some(u)) => (sum(u, &["promptTokenCount"]), sum(u, &["candidatesTokenCount", "thoughtsTokenCount"])), _ => return None, }; - (input.is_some() || output.is_some()).then(|| Usage { input: input.unwrap_or(0), output: output.unwrap_or(0), partial: false }) + // One count without the other is a total that is short, not a zero. + (input.is_some() || output.is_some()).then(|| Usage { + input: input.unwrap_or(0), + output: output.unwrap_or(0), + partial: input.is_none() || output.is_none(), + }) } pub(crate) fn add(&mut self, more: Usage) { diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 68d5f74a26..db1e6663ef 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -2585,6 +2585,10 @@ fn every_api_says_its_tokens_streamed_or_not() { let done = json!({"type": "response.completed", "response": {"status": "completed", "output": [], "usage": {"input_tokens": 120, "output_tokens": 30}}}); assert_eq!(usage(Api::Responses, stream(&[done])), want); + // One count without the other is short, not zero. + let mut half = say("hi"); + half["usage"] = json!({"prompt_tokens": 120}); + assert_eq!(usage(Api::OpenAi, http(half.to_string())), Some(Usage { input: 120, output: 0, partial: true })); // Nonsense counts are none. for bad in [json!(3), json!([]), json!({"prompt_tokens": -1, "completion_tokens": "many"})] { plain["usage"] = bad; @@ -2619,6 +2623,13 @@ fn a_messages_tokens_add_up_with_its_subagents() { a.receive(a.generation(), ok(say("done")), &mut s); assert_eq!(a.usage(), Some(Usage { input: 50, output: 1, partial: true })); a.ask("again", &s); + // A request that fails makes the total a lower bound too. + a.ask("again", &s); + a.receive(a.generation(), with(call("f", "list_layers", json!({})), 70), &mut s); + a.receive(a.generation(), Err("the connection closed".into()), &mut s); + assert!(a.usage().is_some_and(|u| u.partial && u.input == 70)); + a.stop(); + a.ask("once more", &s); // A stop keeps what the subagent had taken. a.receive(a.generation(), with(call("3", "delegate", json!({"task": "look"})), 10), &mut s); a.receive(a.generation(), with(call("4", "list_layers", json!({})), 200), &mut s); diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index 0061ac1afc..f7823be7ef 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -151,8 +151,8 @@ didn't. **Show the tokens each message uses** in the settings turns the line off With a ChatGPT sign-in, **Effort** sets how much the model thinks before it answers, where the model offers a choice: `medium` unless you choose, or the model's first level when it has no -`medium`. `RUSTGIS_ASSISTANT_EFFORT` sets it on the -command line. +`medium`. `RUSTGIS_ASSISTANT_EFFORT` sets it for the app and the command line until one is chosen +in the settings; a level the model doesn't list isn't sent, and the command line says so. ### OpenRouter private routing From 10da12caf1d30bc1c39b66f807a95bf328902a97 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 21:03:57 -0600 Subject: [PATCH 4/7] fix(assistant): a stopped request makes the count partial, and reports joining a message add to it --- apps/rustgis-cli/src/main.rs | 7 ++++++- crates/assistant/src/agent.rs | 11 +++++++++-- crates/assistant/src/tests.rs | 5 +++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index 59c85b6b79..cac830010d 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -678,7 +678,12 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen eprintln!("[{} · {}]", cfg.provider, cfg.model); // A level asked for that the model doesn't take isn't sent: said. if cfg.login() && cfg.reasoning != Some(false) && !cfg.effort.trim().is_empty() && cfg.effort.trim() != cfg.effort_sent() { - eprintln!("rustgis-cli: {} doesn't offer the effort {:?}; {} is used", cfg.model, cfg.effort.trim(), cfg.effort_sent()); + eprintln!( + "rustgis-cli: the effort {:?} isn't among those listed for {}; {} is used", + cfg.effort.trim(), + cfg.model, + cfg.effort_sent() + ); } let yes = args.iter().any(|a| a == "--yes"); let trace_key = cfg.key.clone(); diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 42e14d9d93..a0086e5724 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -336,10 +336,13 @@ impl Agent { } waiting.push_str(&message) } - _ => a.turns.push(Turn::User(message, Vec::new())), + _ => { + a.turns.push(Turn::User(message, Vec::new())); + // A turn of its own counts afresh; joining a message still waiting adds to it. + a.usage = provider::Usage::default(); + } } a.steps = 0; - a.usage = provider::Usage::default(); a.retries = 0; a.overflow_compacted = false; a.send() @@ -1264,6 +1267,10 @@ impl Agent { if !self.busy() { return; } + // A request stopped on its way may have been charged for without saying. + if matches!(self.state, State::Waiting | State::Compacting { .. }) { + self.usage.partial = true; + } if let Some(child) = self.child.as_mut() { child.stop(); self.show_child(); diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index db1e6663ef..07142efd59 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -2630,6 +2630,11 @@ fn a_messages_tokens_add_up_with_its_subagents() { assert!(a.usage().is_some_and(|u| u.partial && u.input == 70)); a.stop(); a.ask("once more", &s); + // A request stopped on its way makes it a lower bound. + a.receive(a.generation(), with(call("g", "list_layers", json!({})), 30), &mut s); + a.stop(); + assert!(a.usage().is_some_and(|u| u.partial && u.input == 30)); + a.ask("and again", &s); // A stop keeps what the subagent had taken. a.receive(a.generation(), with(call("3", "delegate", json!({"task": "look"})), 10), &mut s); a.receive(a.generation(), with(call("4", "list_layers", json!({})), 200), &mut s); From 306a9ff31ac44042895e49d40c3a9dc993203391 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 21:44:57 -0600 Subject: [PATCH 5/7] test(assistant): a stop with a subagent's request out is partial --- crates/assistant/src/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 07142efd59..ca201c18b1 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -2639,7 +2639,8 @@ fn a_messages_tokens_add_up_with_its_subagents() { a.receive(a.generation(), with(call("3", "delegate", json!({"task": "look"})), 10), &mut s); a.receive(a.generation(), with(call("4", "list_layers", json!({})), 200), &mut s); a.stop(); - assert_eq!(a.usage(), Some(Usage { input: 210, output: 2, partial: false })); + // Its request still out when stopped, the total is a lower bound. + assert_eq!(a.usage(), Some(Usage { input: 210, output: 2, partial: true })); } #[test] From 0fd1e7d9bcc8bea0bae4e2ade1c40e47b9bb1bf6 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 22:54:26 -0600 Subject: [PATCH 6/7] fix(assistant): a message joining a waiting turn adds to its count; the effort note is a notice --- apps/rustgis-cli/src/main.rs | 12 +++++++----- crates/assistant/src/agent.rs | 10 +++++++--- crates/assistant/src/tests.rs | 7 +++++++ docs/user-guide/assistant.md | 3 ++- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index cac830010d..9dbc63b201 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -678,12 +678,14 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen eprintln!("[{} · {}]", cfg.provider, cfg.model); // A level asked for that the model doesn't take isn't sent: said. if cfg.login() && cfg.reasoning != Some(false) && !cfg.effort.trim().is_empty() && cfg.effort.trim() != cfg.effort_sent() { - eprintln!( - "rustgis-cli: the effort {:?} isn't among those listed for {}; {} is used", - cfg.effort.trim(), - cfg.model, - cfg.effort_sent() + let mark = s.notice_mark(); + s.notify( + format!("the effort {:?} isn't among those listed for {}; {} is used", cfg.effort.trim(), cfg.model, cfg.effort_sent()), + false, ); + for n in s.notices_since(mark) { + eprintln!("rustgis-cli: {}", n.text); + } } let yes = args.iter().any(|a| a == "--yes"); let trace_key = cfg.key.clone(); diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index a0086e5724..79fe191ad7 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -166,7 +166,8 @@ pub struct Agent { allowed: Vec, /// The agents on this computer the model may delegate to ([`acp`]). harnesses: Vec<&'static acp::AgentSpec>, - /// The tokens this message's requests took, subagents' included ([`Agent::usage`]). + /// The tokens this message's requests took, subagents' included; agent threads on this + /// computer bill their own ([`Agent::usage`]). usage: provider::Usage, /// Model requests left for this message (a subagent shares its parent's budget). max_steps: u32, @@ -593,10 +594,13 @@ impl Agent { ))); } } - _ => self.turns.push(Turn::User(message, pictures)), + _ => { + self.turns.push(Turn::User(message, pictures)); + // A turn of its own counts afresh; joining one still waiting adds to its count. + self.usage = provider::Usage::default(); + } } self.steps = 0; - self.usage = provider::Usage::default(); self.retries = 0; self.overflow_compacted = false; self.send() diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index ca201c18b1..3ca366bc66 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -2623,6 +2623,13 @@ fn a_messages_tokens_add_up_with_its_subagents() { a.receive(a.generation(), ok(say("done")), &mut s); assert_eq!(a.usage(), Some(Usage { input: 50, output: 1, partial: true })); a.ask("again", &s); + // A message joining the turn a compaction left adds to the summary's count. + a.stop(); + assert!(matches!(a.compact(), Step::Send(_))); + a.receive(a.generation(), with(say("Summary: looked at the layers."), 40), &mut s); + a.ask("go on", &s); + assert!(a.usage().is_some_and(|u| u.input == 40), "{:?}", a.usage()); + a.stop(); // A request that fails makes the total a lower bound too. a.ask("again", &s); a.receive(a.generation(), with(call("f", "list_layers", json!({})), 70), &mut s); diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index f7823be7ef..f794894b4b 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -143,7 +143,8 @@ small local models may stop early or skip steps. ### Tokens and effort -After each message, the pane shows the tokens its requests took, subagents' included, as the +After each message, the pane shows the tokens its requests took, subagents' included (agent +threads on this computer bill their own and aren't counted), as the provider counts them. Tokens in are counted for every request, so a long run counts the conversation many times, though providers usually charge less for what they had cached. Nothing is shown for a server that doesn't report them, and "at least" when some of a message's requests From cc0ff11dcbcde5ab483dc1742b4f0dc3943e8a31 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 1 Dec 2026 23:12:41 -0600 Subject: [PATCH 7/7] test(assistant): start afresh after the compaction case --- crates/assistant/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 3ca366bc66..2fade6d487 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -2629,7 +2629,7 @@ fn a_messages_tokens_add_up_with_its_subagents() { a.receive(a.generation(), with(say("Summary: looked at the layers."), 40), &mut s); a.ask("go on", &s); assert!(a.usage().is_some_and(|u| u.input == 40), "{:?}", a.usage()); - a.stop(); + a.clear(); // A request that fails makes the total a lower bound too. a.ask("again", &s); a.receive(a.generation(), with(call("f", "list_layers", json!({})), 70), &mut s);