Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): prompt/prefix caching for the agent core (#8967)
Akarshan Biswas38491c73d123
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rsindex 7701acf0e..2bdaa1d64 100644--- a/src-tauri/src/core/agent/compaction.rs+++ b/src-tauri/src/core/agent/compaction.rs@@ -28,6 +28,24 @@ questions. Omit pleasantries and redundant tool output. Write only the summary."const FALLBACK_NOTE: &str = "[Earlier conversation was omitted to fit the model's context window.]";+/// Leading text of every compaction summary message (the model summary and the+/// [`FALLBACK_NOTE`] path both carry it). Kept as a constant so+/// [`is_compaction_summary`] and `set_system_prompt` recognise a summary without+/// re-hardcoding the string: a summary is a `system` message, but unlike the+/// rebuilt stable/volatile prompt it must survive the next turn's+/// `set_system_prompt`, or compaction would save the current run and then throw+/// its own condensed history away.+pub(crate) const SUMMARY_MARKER: &str = "[Summary of earlier conversation, condensed to save context]";++/// Whether `msg` is a compaction summary that must be preserved across turns.+pub(crate) fn is_compaction_summary(msg: &Value) -> bool {+ role(msg) == "system"+ && msg+ .get("content")+ .and_then(|c| c.as_str())+ .is_some_and(|c| c.starts_with(SUMMARY_MARKER))+}+/// Character budget for the transcript handed to the summarizer (~12K tokens)./// Compaction runs *because* the conversation overflowed, so replaying it whole/// would guarantee the summarizer overflows too: the dropped span is rendered to@@ -99,7 +117,7 @@ pub(crate) async fn compact_conversation(out.extend_from_slice(system_msgs);out.push(json!({"role": "system",- "content": format!("[Summary of earlier conversation, condensed to save context]\n\n{summary}")+ "content": format!("{SUMMARY_MARKER}\n\n{summary}")}));out.extend_from_slice(kept);Ok(out)diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex 5b460ecb2..b0fccda76 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -284,20 +284,45 @@ fn arg_name(args: &serde_json::Value) -> String {.unwrap_or_default()}-#[derive(Clone, Debug, serde::Serialize)]+#[derive(Clone, Debug, Default, serde::Serialize)]pub struct Usage {pub prompt_tokens: Option<u64>,pub completion_tokens: Option<u64>,pub total_tokens: Option<u64>,+ /// Prompt tokens served from the provider's prompt cache (a read/hit).+ /// OpenAI reports it under `prompt_tokens_details.cached_tokens`; Anthropic+ /// under `cache_read_input_tokens`. A thrashing cache shows here as a low+ /// value against a high `prompt_tokens`.+ pub cached_tokens: Option<u64>,+ /// Prompt tokens written into the provider cache this request (a write).+ /// Only Anthropic bills this separately (`cache_creation_input_tokens`);+ /// absent for providers that do not distinguish reads from writes.+ pub cache_write_tokens: Option<u64>,}impl Usage {pub(crate) fn from_completion(completion: &serde_json::Value) -> Option<Self> {let usage = completion.get("usage")?;+ let cached_tokens = usage+ .get("prompt_tokens_details")+ .and_then(|d| d.get("cached_tokens"))+ .and_then(|v| v.as_u64())+ .or_else(|| usage.get("cache_read_input_tokens").and_then(|v| v.as_u64()));+ let cache_write_tokens = usage+ .get("cache_creation_input_tokens")+ .and_then(|v| v.as_u64())+ .or_else(|| {+ usage+ .get("prompt_tokens_details")+ .and_then(|d| d.get("cache_creation_tokens"))+ .and_then(|v| v.as_u64())+ });Some(Self {prompt_tokens: usage.get("prompt_tokens").and_then(|v| v.as_u64()),completion_tokens: usage.get("completion_tokens").and_then(|v| v.as_u64()),total_tokens: usage.get("total_tokens").and_then(|v| v.as_u64()),+ cached_tokens,+ cache_write_tokens,})}}@@ -531,4 +556,56 @@ mod tests {assert!(Usage::from_completion(&json!({ "choices": [] })).is_none());}++ #[test]+ fn usage_parses_openai_cached_tokens() {+ let parsed = Usage::from_completion(&json!({+ "usage": {+ "prompt_tokens": 100,+ "completion_tokens": 5,+ "total_tokens": 105,+ "prompt_tokens_details": { "cached_tokens": 80 }+ }+ }))+ .unwrap();+ assert_eq!(parsed.cached_tokens, Some(80));+ assert_eq!(parsed.cache_write_tokens, None);+ }++ #[test]+ fn usage_parses_anthropic_cache_read_and_write() {+ let parsed = Usage::from_completion(&json!({+ "usage": {+ "prompt_tokens": 100,+ "cache_read_input_tokens": 60,+ "cache_creation_input_tokens": 40+ }+ }))+ .unwrap();+ assert_eq!(parsed.cached_tokens, Some(60));+ assert_eq!(parsed.cache_write_tokens, Some(40));+ }++ #[test]+ fn usage_parses_nested_cache_creation_tokens() {+ let parsed = Usage::from_completion(&json!({+ "usage": {+ "prompt_tokens": 100,+ "prompt_tokens_details": { "cached_tokens": 60, "cache_creation_tokens": 40 }+ }+ }))+ .unwrap();+ assert_eq!(parsed.cached_tokens, Some(60));+ assert_eq!(parsed.cache_write_tokens, Some(40));+ }++ #[test]+ fn usage_cache_fields_none_when_absent() {+ let parsed = Usage::from_completion(&json!({+ "usage": { "prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15 }+ }))+ .unwrap();+ assert_eq!(parsed.cached_tokens, None);+ assert_eq!(parsed.cache_write_tokens, None);+ }}diff --git a/src-tauri/src/core/agent/genai_bridge.rs b/src-tauri/src/core/agent/genai_bridge.rsindex ff2ecee46..d18532e2c 100644--- a/src-tauri/src/core/agent/genai_bridge.rs+++ b/src-tauri/src/core/agent/genai_bridge.rs@@ -550,6 +550,20 @@ fn completion_json(if let Some(v) = u.total_tokens {usage_obj.insert("total_tokens".into(), serde_json::json!(v));}+ if let Some(details) = u.prompt_tokens_details.as_ref() {+ // Keep both counters under `prompt_tokens_details` rather than+ // mixing an Anthropic-native top-level key into a chat-shaped usage.+ let mut d = serde_json::Map::new();+ if let Some(v) = details.cached_tokens {+ d.insert("cached_tokens".into(), serde_json::json!(v));+ }+ if let Some(v) = details.cache_creation_tokens {+ d.insert("cache_creation_tokens".into(), serde_json::json!(v));+ }+ if !d.is_empty() {+ usage_obj.insert("prompt_tokens_details".into(), serde_json::Value::Object(d));+ }+ }if !usage_obj.is_empty() {completion.insert("usage".into(), serde_json::Value::Object(usage_obj));}diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex f86fa9271..ab0d47927 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -21,8 +21,8 @@ use crate::core::agent::upstream::{arguments_are_executable, collect_mcp_openai_tools, copy_optional_chat_params,drop_malformed_tool_calls, execute_mcp_tool_calls, extract_choice_message, extract_tool_calls,load_assistant_config, parse_openai_messages, repair_dangling_tool_calls,- resolve_api_type_for_model, resolve_upstream_for_model, set_system_prompt,- stream_openai_chat_completions,+ insert_volatile_system, resolve_api_type_for_model, resolve_upstream_for_model,+ set_system_prompt, stream_openai_chat_completions,};use crate::core::server::converters::{converter_for, UpstreamConverter};#[cfg(not(feature = "cli"))]@@ -1997,7 +1997,14 @@ async fn orchestrate_inner(.as_deref().map(|root| resolve_run_settings(root, *sandbox));- let mut system_prompt = build_run_system_prompt(+ // The stable system prompt: identity, guidelines, environment, skills and+ // the memory catalog. Byte-identical across the turns of a session (within a+ // day), so it is kept as system message 0 and never mixed with per-turn+ // content -- that is what lets a provider cache this long prefix. Volatile+ // per-turn context (date, query memory recall, plan/todo state) is collected+ // separately below and emitted as a second system message so it cannot+ // invalidate the cached prefix above.+ let stable_system = build_run_system_prompt(assistant_instructions.as_deref(),system_prompt_override.as_deref(),project_root.as_deref(),@@ -2005,30 +2012,24 @@ async fn orchestrate_inner(*subagents_enabled,settings.as_ref().is_some_and(|s| s.sandbox),);++ let mut volatile_parts: Vec<String> = Vec::new();+ // Always tell the model today's date, including isolated child runs.+ volatile_parts.push(format!(+ "Today's date is {}.",+ chrono::Local::now().format("%Y-%m-%d")+ ));// Normal parent runs recall project memory for the current query before it// is indexed. Child runs keep their isolated history and skip memory.if system_prompt_override.is_none() {if let Some(root) = project_root {if let Some(query) = latest_user_text(&conversation_messages) {if let Some(mem) = crate::core::agent::memory::retrieve_block(root, &query) {- system_prompt = Some(match system_prompt {- Some(s) => format!("{s}\n\n{mem}"),- None => mem,- });+ volatile_parts.push(mem);}}}}- // Always tell the model today's date, including isolated child runs.- let date_line = format!(- "Today's date is {}.",- chrono::Local::now().format("%Y-%m-%d")- );- let system_prompt = match system_prompt {- Some(sys) => format!("{date_line}\n\n{sys}"),- None => date_line,- };- let system_prompt = Some(system_prompt);// Child (subagent) runs are excluded via `system_prompt_override`, the// same gate the memory-recall block above uses to distinguish a// top-level run from a subagent's isolated context.@@ -2043,25 +2044,19 @@ async fn orchestrate_inner(let eager_todo_plan = run_mode != crate::core::agent::plan::RunMode::Plan&& system_prompt_override.is_none()&& should_force_goal_todo_plan(goal_mode, todo_registry).await;- let system_prompt = if run_mode == crate::core::agent::plan::RunMode::Plan {- let addendum = crate::core::agent::plan::plan_mode_prompt_addendum();- Some(match system_prompt {- Some(sys) => format!("{sys}\n\n{addendum}"),- None => addendum.to_string(),- })+ if run_mode == crate::core::agent::plan::RunMode::Plan {+ volatile_parts.push(crate::core::agent::plan::plan_mode_prompt_addendum().to_string());} else if let Some(addendum) = todo_prompt_addendum(eager_todo_plan, todo_registry).await {- // Child (subagent) runs are excluded via `system_prompt_override`, the- // same gate the memory-recall block above uses to distinguish a- // top-level run from a subagent's isolated context.- Some(match system_prompt {- Some(sys) => format!("{sys}\n\n{addendum}"),- None => addendum.to_string(),- })- } else {- system_prompt- };- if let Some(sys) = system_prompt {+ volatile_parts.push(addendum.to_string());+ }++ if let Some(sys) = stable_system {set_system_prompt(&mut conversation_messages, &sys);+ insert_volatile_system(&mut conversation_messages, &volatile_parts.join("\n\n"));+ } else {+ // No stable prompt (an isolated child run with no override): the+ // volatile block is all there is, so it stands in as message 0.+ set_system_prompt(&mut conversation_messages, &volatile_parts.join("\n\n"));}// Paired with the addendum above: force the model's very first tool call// to actually be `todo` rather than leaving compliance up to a prompt it@@ -3061,6 +3056,51 @@ mod tests {use std::collections::VecDeque;use std::sync::Mutex as StdMutex;+ /// The cache-prefix contract from #340: across turns the system prompt at+ /// message 0 and the tool schema must be byte-identical, so a provider can+ /// cache them; only the volatile message 1 (date, memory recall, plan state)+ /// changes. A regression here silently defeats prompt caching, which no+ /// functional test would catch.+ #[test]+ fn system_prefix_and_tools_are_byte_identical_across_turns() {+ let tools = vec![json!({+ "type": "function",+ "function": {+ "name": "bash",+ "description": "run a shell command",+ "parameters": {"type": "object"}+ }+ })];+ let body = json!({});++ let mut turn1 = vec![json!({"role": "user", "content": "first"})];+ set_system_prompt(&mut turn1, "STABLE PREFIX");+ insert_volatile_system(&mut turn1, "Today's date is 2026-09-16.");+ let req1 = build_completion_request("m", &turn1, &tools, &body, None);++ // A later turn: the conversation has grown and the volatile block differs.+ let mut turn2 = vec![+ json!({"role": "user", "content": "first"}),+ json!({"role": "assistant", "content": "reply"}),+ json!({"role": "user", "content": "second"}),+ ];+ set_system_prompt(&mut turn2, "STABLE PREFIX");+ insert_volatile_system(+ &mut turn2,+ "Today's date is 2026-09-17.\n\n# Recalled memory\n- a note",+ );+ let req2 = build_completion_request("m", &turn2, &tools, &body, None);++ let node0 = |r: &serde_json::Value| serde_json::to_string(&r["messages"][0]).unwrap();+ let tools_of = |r: &serde_json::Value| serde_json::to_string(&r["tools"]).unwrap();+ assert_eq!(node0(&req1), node0(&req2), "node 0 must be byte-stable");+ assert_eq!(tools_of(&req1), tools_of(&req2), "tools must be byte-stable");+ assert_ne!(+ req1["messages"][1], req2["messages"][1],+ "the volatile block is expected to differ"+ );+ }+struct MockModel {responses: StdMutex<VecDeque<serde_json::Value>>,// Every request this mock was invoked with, in order -- lets a testdiff --git a/src-tauri/src/core/agent/session.rs b/src-tauri/src/core/agent/session.rsindex 5cc102e06..cd9b274b5 100644--- a/src-tauri/src/core/agent/session.rs+++ b/src-tauri/src/core/agent/session.rs@@ -79,6 +79,7 @@ mod tests {prompt_tokens: None,completion_tokens: None,total_tokens: total,+ ..Default::default()})}@@ -91,6 +92,7 @@ mod tests {prompt_tokens: Some(prompt_tokens),completion_tokens: Some(completion_tokens),total_tokens: Some(total_tokens),+ ..Default::default()})}diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex e3dd3cd30..478535cec 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -310,7 +310,14 @@ pub(crate) fn drop_malformed_tool_calls(messages: &mut Vec<serde_json::Value>) -}pub(crate) fn set_system_prompt(messages: &mut Vec<serde_json::Value>, system_prompt: &str) {- messages.retain(|m| m.get("role").and_then(|r| r.as_str()) != Some("system"));+ // Drop the previous run's rebuilt system prompt, but keep compaction+ // summaries: they are `system` messages, yet they carry condensed history+ // that this turn must not throw away. Without this the next turn strips the+ // summary and compaction only ever helped the run that produced it.+ messages.retain(|m| {+ m.get("role").and_then(|r| r.as_str()) != Some("system")+ || crate::core::agent::compaction::is_compaction_summary(m)+ });messages.insert(0,serde_json::json!({@@ -320,6 +327,29 @@ pub(crate) fn set_system_prompt(messages: &mut Vec<serde_json::Value>, system_pr);}+/// Insert per-turn context as a second system message right after the stable+/// system prompt, without touching it. The stable prompt (identity, guidelines,+/// environment, skills, memory catalog) is byte-identical across the turns of a+/// session, so keeping it as message 0 lets a provider cache that long prefix;+/// the volatile content (date, query-specific memory recall, plan/todo state)+/// changes every turn and lives here where it cannot invalidate that prefix.+/// Assumes `set_system_prompt` has already placed the stable prompt at index 0.+pub(crate) fn insert_volatile_system(messages: &mut Vec<serde_json::Value>, content: &str) {+ let has_leading_system = messages+ .first()+ .and_then(|m| m.get("role"))+ .and_then(|r| r.as_str())+ == Some("system");+ let idx = usize::from(has_leading_system);+ messages.insert(+ idx,+ serde_json::json!({+ "role": "system",+ "content": content+ }),+ );+}+pub(crate) fn extract_tool_calls(response: &serde_json::Value) -> Vec<serde_json::Value> {response.get("choices")@@ -1507,6 +1537,61 @@ mod tests {use super::*;use serde_json::json;+ #[test]+ fn volatile_system_follows_the_stable_prompt_and_leaves_it_byte_stable() {+ let mut msgs = vec![json!({ "role": "user", "content": "hi" })];+ set_system_prompt(&mut msgs, "STABLE");+ insert_volatile_system(&mut msgs, "date + memory");+ assert_eq!(msgs[0]["role"], "system");+ assert_eq!(msgs[0]["content"], "STABLE");+ assert_eq!(msgs[1]["role"], "system");+ assert_eq!(msgs[1]["content"], "date + memory");+ assert_eq!(msgs[2]["role"], "user");++ // A second turn with different volatile content must not disturb node 0.+ let mut next = vec![+ json!({ "role": "user", "content": "hi" }),+ json!({ "role": "assistant", "content": "yo" }),+ json!({ "role": "user", "content": "again" }),+ ];+ set_system_prompt(&mut next, "STABLE");+ insert_volatile_system(&mut next, "different date");+ assert_eq!(next[0], msgs[0]);+ }++ #[test]+ fn compaction_summary_survives_the_next_turn_rebuild() {+ let marker = crate::core::agent::compaction::SUMMARY_MARKER;+ // The history a turn inherits after a mid-run compaction: previous+ // rebuilt system prompt, its volatile message, the summary, kept tail.+ let mut history = vec![+ json!({ "role": "system", "content": "OLD STABLE" }),+ json!({ "role": "system", "content": "old date" }),+ json!({ "role": "system", "content": format!("{marker}\n\ncondensed") }),+ json!({ "role": "assistant", "content": "kept" }),+ json!({ "role": "user", "content": "new question" }),+ ];+ set_system_prompt(&mut history, "NEW STABLE");+ insert_volatile_system(&mut history, "new date");+ assert_eq!(history[0]["content"], "NEW STABLE");+ assert_eq!(history[1]["content"], "new date");+ assert!(history[2]["content"]+ .as_str()+ .unwrap()+ .starts_with(marker));+ assert_eq!(history[3]["content"], "kept");+ assert_eq!(history[4]["content"], "new question");+ }++ #[test]+ fn volatile_system_stands_in_as_node_zero_when_no_stable_prompt() {+ let mut msgs = vec![json!({ "role": "user", "content": "hi" })];+ insert_volatile_system(&mut msgs, "date only");+ assert_eq!(msgs[0]["role"], "system");+ assert_eq!(msgs[0]["content"], "date only");+ assert_eq!(msgs[1]["role"], "user");+ }+fn sink() -> (mpsc::UnboundedSender<StreamEvent>,mpsc::UnboundedReceiver<StreamEvent>,diff --git a/src-tauri/src/core/cli/run_report.rs b/src-tauri/src/core/cli/run_report.rsindex 3200b200c..ef3947673 100644--- a/src-tauri/src/core/cli/run_report.rs+++ b/src-tauri/src/core/cli/run_report.rs@@ -35,6 +35,8 @@ pub(crate) struct RunReport {num_turns: u32,prompt_tokens: u64,completion_tokens: u64,+ cached_tokens: u64,+ cache_write_tokens: u64,}impl RunReport {@@ -64,6 +66,8 @@ impl RunReport {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);}// Subagent work is real spend on the same budget, so its usage// counts. Its `Step`/`Token` must not: those describe the child's@@ -114,6 +118,8 @@ impl RunReport {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,},}}@@ -151,6 +157,8 @@ struct ReportUsage {prompt_tokens: u64,completion_tokens: u64,total_tokens: u64,+ cached_tokens: u64,+ cache_write_tokens: u64,}/// A stable, machine-readable code for a failure. The loop stamps every@@ -178,6 +186,7 @@ mod tests {prompt_tokens: Some(prompt),completion_tokens: Some(completion),total_tokens: Some(prompt + completion),+ ..Default::default()}}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex bbd06bb46..0f3bec203 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -2093,6 +2093,12 @@ struct App {turn_output_tokens: u64,/// Context size of the current turn's most recent request.turn_prompt_tokens: u64,+ /// Prompt tokens the provider served from its cache on the most recent+ /// request (a cache read/hit), and the tokens it wrote into the cache.+ /// Latest request, not a sum: like `turn_prompt_tokens`, each request+ /// resends the whole prefix. Surfaced in `/context`.+ turn_cached_tokens: u64,+ turn_cache_write_tokens: u64,/// Transcript viewport rect from the last draw, for mapping mouse clicks/// to rows.transcript_rect: Rect,@@ -2535,6 +2541,8 @@ impl App {tokens_per_sec: None,turn_output_tokens: 0,turn_prompt_tokens: 0,+ turn_cached_tokens: 0,+ turn_cache_write_tokens: 0,transcript_rect: Rect::default(),last_scroll: 0,row_index: Vec::new(),@@ -2626,6 +2634,8 @@ impl App {// An empty history is exactly known, not an estimate of anything.self.tokens_estimated = false;self.turn_prompt_tokens = 0;+ self.turn_cached_tokens = 0;+ self.turn_cache_write_tokens = 0;self.tokens_per_sec = None;self.turn = (0, 0);self.detail.clear();@@ -2654,6 +2664,8 @@ impl App {fn invalidate_token_provenance(&mut self) {self.tokens_estimated = true;self.turn_prompt_tokens = 0;+ self.turn_cached_tokens = 0;+ self.turn_cache_write_tokens = 0;}/// Drop any selection, and with it a copy armed but not yet lifted out of a@@ -4648,6 +4660,8 @@ impl App {},tokens_estimated: self.tokens_estimated,turn_prompt_tokens: self.turn_prompt_tokens,+ turn_cached_tokens: self.turn_cached_tokens,+ turn_cache_write_tokens: self.turn_cache_write_tokens,}}}@@ -4665,6 +4679,8 @@ struct ContextSnapshot {history_estimate: u64,tokens_estimated: bool,turn_prompt_tokens: u64,+ turn_cached_tokens: u64,+ turn_cache_write_tokens: u64,}/// The `/context` breakdown for the current session, computed from an owned@@ -4779,6 +4795,10 @@ async fn compute_context_report(snapshot: ContextSnapshot) -> ContextReport {});let reported = !snapshot.tokens_estimated && snapshot.turn_prompt_tokens > 0;+ // The cache figures share the fill's provenance: they describe the same+ // measured request, so a fall-back-to-estimate turn has no cache line.+ let cache_reported =+ reported && (snapshot.turn_cached_tokens > 0 || snapshot.turn_cache_write_tokens > 0);ContextReport {model_id: snapshot.model,window: snapshot.context_window,@@ -4789,6 +4809,9 @@ async fn compute_context_report(snapshot: ContextSnapshot) -> ContextReport {},fill_reported: reported,segments,+ cache_reported,+ cached_tokens: snapshot.turn_cached_tokens,+ cache_write_tokens: snapshot.turn_cache_write_tokens,}}@@ -5215,6 +5238,13 @@ impl App {// whole conversation, so adding them would be meaningless.if let Some(prompt) = usage.prompt_tokens {self.turn_prompt_tokens = prompt;+ // Cache read/write for the same request. Only overwrite when+ // the provider reported a value, so a provider that omits the+ // fields leaves the last known figures rather than zeroing.+ self.turn_cached_tokens = usage.cached_tokens.unwrap_or(self.turn_cached_tokens);+ self.turn_cache_write_tokens = usage+ .cache_write_tokens+ .unwrap_or(self.turn_cache_write_tokens);// Keep the header's context gauge live during the turn// instead of jumping only when the run ends.self.tokens = prompt + usage.completion_tokens.unwrap_or(0);@@ -5356,6 +5386,8 @@ impl App {self.tokens_per_sec = None;self.turn_output_tokens = 0;self.turn_prompt_tokens = 0;+ self.turn_cached_tokens = 0;+ self.turn_cache_write_tokens = 0;self.scrollback = 0;self.todo_call_this_turn = false;self.todo_ok_this_turn = false;@@ -5931,6 +5963,13 @@ struct ContextReport {/// Content categories plus free space and the autocompact buffer. Always/// exactly the seven bars rendered by the context view.segments: Vec<ContextSegment>,+ /// Prompt-cache read/write from the most recent request, and whether the+ /// provider reported either. `false` when the provider surfaces no cache+ /// fields (every plain OpenAI-compatible endpoint that caches implicitly+ /// without reporting), which suppresses the cache line entirely.+ cache_reported: bool,+ cached_tokens: u64,+ cache_write_tokens: u64,}impl ContextReport {@@ -6051,6 +6090,35 @@ fn context_bank_bar(percent: f64, width: usize) -> (String, String) {(filled, empty)}+/// One-line prompt-cache readout for `/context`, or `None` when the provider+/// reported no cache activity. `read` as a share of the prompt is the number+/// that matters: it says how much of the prefix the provider actually served+/// from cache on the last request, i.e. whether prefix caching is working.+fn cache_summary_line(report: &ContextReport) -> Option<String> {+ if !report.cache_reported {+ return None;+ }+ // Clamped: normally `cached_tokens` is a subset of `fill` (prompt_tokens),+ // but a raw Anthropic-shaped usage reports a prompt that excludes the cache+ // read, which would push the share past 100%.+ let read_pct = if report.fill > 0 {+ (report.cached_tokens as f64 / report.fill as f64 * 100.0).min(100.0)+ } else {+ 0.0+ };+ let read = format_tokens(report.cached_tokens);+ if report.cache_write_tokens > 0 {+ Some(format!(+ "Prompt cache (last request): {read} read ({read_pct:.0}% of prompt), {} written",+ format_tokens(report.cache_write_tokens)+ ))+ } else {+ Some(format!(+ "Prompt cache (last request): {read} read ({read_pct:.0}% of prompt)"+ ))+ }+}+/// 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>> {@@ -6086,11 +6154,14 @@ fn context_lines(report: &ContextReport, width: usize) -> Vec<Line<'static>> {format!("{} before auto-compact", format_tokens(headroom)),Style::new().bold(),)],- vec![Span::styled(- "Context breakdown (estimated)",- Style::new().dim(),- )],];+ if let Some(cache) = cache_summary_line(report) {+ rows.push(vec![Span::styled(cache, Style::new().cyan())]);+ }+ rows.push(vec![Span::styled(+ "Context breakdown (estimated)",+ Style::new().dim(),+ )]);for (segment, percent) in report.segments.iter()@@ -6191,6 +6262,9 @@ fn context_lines(report: &ContextReport, width: usize) -> Vec<Line<'static>> {),Style::new().bold(),)]);+ if let Some(cache) = cache_summary_line(report) {+ rows.push(vec![Span::styled(cache, Style::new().cyan())]);+ }rows.push(Vec::new());rows.push(vec![Span::styled("Context breakdown (estimated)",@@ -28971,6 +29045,7 @@ mod tests {prompt_tokens: Some(12_800 + i as u64 * 12_800),completion_tokens: Some(100),total_tokens: Some(12_900),+ ..Default::default()},},);@@ -29671,6 +29746,7 @@ mod tests {prompt_tokens: Some(120),completion_tokens: Some(8),total_tokens: Some(128),+ ..Default::default()}),);assert_eq!(app.turn_prompt_tokens, 120);@@ -29697,6 +29773,7 @@ mod tests {prompt_tokens: Some(40_000),completion_tokens: Some(500),total_tokens: Some(40_500),+ ..Default::default()},});}@@ -29881,9 +29958,46 @@ mod tests {fill: used,fill_reported: false,segments,+ cache_reported: false,+ cached_tokens: 0,+ cache_write_tokens: 0,}}+ #[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]);+ report.fill = 120_000;+ report.fill_reported = true;+ report.cache_reported = true;+ report.cached_tokens = 90_000;+ report.cache_write_tokens = 12_000;++ let text = context_lines(&report, 80)+ .iter()+ .map(line_text)+ .collect::<Vec<_>>()+ .join("\n");+ assert!(+ text.contains("Prompt cache (last request): 90K read (75% of prompt), 12K written"),+ "{text}"+ );+ }++ #[test]+ fn context_view_hides_prompt_cache_when_not_reported() {+ let mut report = context_report(234_000, 35_000, [6_049, 9_000, 2_149, 8_049, 95_253]);+ report.fill = 120_000;+ report.fill_reported = true;+ // cache_reported stays false (a plain OpenAI-compatible provider).+ let text = context_lines(&report, 80)+ .iter()+ .map(line_text)+ .collect::<Vec<_>>()+ .join("\n");+ assert!(!text.contains("Prompt cache"), "{text}");+ }+#[test]fn context_view_uses_consistent_language_and_aligned_bars() {let mut report = context_report(234_000, 35_000, [6_049, 9_000, 2_149, 8_049, 95_253]);@@ -30080,6 +30194,7 @@ mod tests {prompt_tokens: Some(90_000),completion_tokens: Some(10),total_tokens: Some(90_010),+ ..Default::default()},});assert!(@@ -30104,6 +30219,7 @@ mod tests {prompt_tokens: Some(120_000),completion_tokens: Some(10),total_tokens: Some(120_010),+ ..Default::default()},});assert!(app.context_report().await.fill_reported);diff --git a/src-tauri/src/core/server/converters.rs b/src-tauri/src/core/server/converters.rsindex cac9ffc71..7ae74de36 100644--- a/src-tauri/src/core/server/converters.rs+++ b/src-tauri/src/core/server/converters.rs@@ -92,12 +92,32 @@ use std::collections::HashMap;/// not chat/completions (OpenAI `/v1/responses`, Google `generateContent`,/// Anthropic `/v1/messages`); the proxy selects one by `ProviderConfig.api_type`/// and otherwise forwards verbatim.+/// How a provider engages its prompt cache. The gate that decides whether a+/// request carries an explicit cache key: `Implicit` providers (OpenAI, Google,+/// and every plain OpenAI-compatible endpoint) cache a stable prefix on their+/// own, so no key is emitted -- emitting an unknown one risks a strict endpoint+/// rejecting the whole request. `Explicit` providers (Anthropic) only cache when+/// the request marks a breakpoint, which `convert_request` places on the stable+/// system prefix and the tools.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CacheCapability {+ Implicit,+ Explicit,+}+pub trait UpstreamConverter: Send + Sync {/// Path suffix appended to the provider `base_url`. Derived from the request/// body because some APIs encode the model and action in the URL (Google:/// `/models/{model}:streamGenerateContent?alt=sse`).fn upstream_path(&self, body: &Value) -> String;+ /// Whether this provider needs an explicit cache breakpoint in the request.+ /// Defaults to `Implicit` so no converter accidentally emits a cache key a+ /// strict endpoint would reject; Anthropic overrides it.+ fn cache_capability(&self) -> CacheCapability {+ CacheCapability::Implicit+ }+/// Authorization header for the upstream request. Defaults to OpenAI-style/// `Authorization: Bearer`; providers using a different scheme (Google:/// `x-goog-api-key`) override this.@@ -161,6 +181,11 @@ pub struct StreamState {pub finished: bool,/// Prompt tokens captured early (Anthropic sends them in `message_start`).pub input_tokens: i64,+ /// Cache read/write tokens, also in `message_start`. Kept beside+ /// `input_tokens` so the terminal `message_delta` can fold them into the+ /// chat-shaped usage.+ pub cache_read_tokens: i64,+ pub cache_write_tokens: i64,}/// Fronts OpenAI's `/v1/responses` API, exposing it as chat/completions so the@@ -846,6 +871,14 @@ impl UpstreamConverter for GoogleGenerateContentConverter {/// Anthropic requires a `max_tokens`; chat/completions may omit it.const ANTHROPIC_DEFAULT_MAX_TOKENS: i64 = 4096;+/// Rough lower bound, in characters, on a prefix Anthropic will actually cache+/// (~1024 tokens at 4 chars/token, matching the `estimate_token_count`+/// heuristic used elsewhere). A `cache_control` breakpoint on a block smaller+/// than this is a no-op Anthropic ignores, so the converter skips it -- which+/// also avoids marking the small volatile block promoted to index 0 on a bare+/// child run that has no stable prompt.+const ANTHROPIC_MIN_CACHEABLE_CHARS: usize = 4096;+/// Fronts Anthropic's `/v1/messages` API. Auth is `x-api-key` plus a fixed/// `anthropic-version` header. The registered provider `base_url` should include/// the version prefix, e.g. `https://api.anthropic.com/v1`.@@ -867,6 +900,42 @@ impl AnthropicMessagesConverter {pub fn new_oauth() -> Self {Self { oauth: true }}++ /// Build the `system` field. `Implicit` keeps the joined-string form.+ /// `Explicit` emits an array of text blocks and marks the stable prompt with+ /// a cache breakpoint. The stable prompt is the first system block, except+ /// when an OAuth billing header occupies index 0 -- the agent keeps its long+ /// byte-stable prompt in that first non-header block, while the volatile+ /// per-turn block and any compaction summary follow and are left uncached.+ ///+ /// The `Implicit` guard is defensive only: `AnthropicMessagesConverter`+ /// always reports `Explicit`. It exists so the marker never escapes if a+ /// future converter reuses this helper -- there is no runtime toggle.+ fn system_value(&self, blocks: Vec<String>) -> Value {+ if self.cache_capability() != CacheCapability::Explicit {+ return json!(blocks.join("\n\n"));+ }+ let stable_idx = usize::from(self.oauth && blocks.len() > 1);+ // Only breakpoint a block large enough for Anthropic to cache. When the+ // agent has no stable prompt (a bare child run), the small volatile+ // block is promoted to index 0; marking it would buy a cache *write*+ // every turn at the 1.25x rate with a near-zero hit rate, so skip it.+ let breakpoint = blocks+ .get(stable_idx)+ .is_some_and(|b| b.len() >= ANTHROPIC_MIN_CACHEABLE_CHARS);+ let arr: Vec<Value> = blocks+ .into_iter()+ .enumerate()+ .map(|(i, text)| {+ let mut block = json!({ "type": "text", "text": text });+ if breakpoint && i == stable_idx {+ block["cache_control"] = json!({ "type": "ephemeral" });+ }+ block+ })+ .collect();+ json!(arr)+ }}@@ -882,12 +951,40 @@ fn map_anthropic_finish(reason: &str, saw_tool: bool) -> &'static str {}}-fn anthropic_usage(input_tokens: i64, output_tokens: i64) -> Value {- json!({- "prompt_tokens": input_tokens,+fn anthropic_usage(input_tokens: i64, cache_read: i64, cache_write: i64, output_tokens: i64) -> Value {+ // Anthropic's `input_tokens` excludes both cache figures, whereas+ // chat/completions `prompt_tokens` includes them (genai normalises the same+ // way). Without this the prompt count silently shrinks by the cached prefix+ // the moment caching is enabled, and the cache read/write never reach+ // `Usage`. Emitted in the chat shape `Usage::from_completion` already reads,+ // and only when non-zero so a no-cache response is byte-identical to before.+ let prompt = input_tokens + cache_read + cache_write;+ let mut usage = json!({+ "prompt_tokens": prompt,"completion_tokens": output_tokens,- "total_tokens": input_tokens + output_tokens,- })+ "total_tokens": prompt + output_tokens,+ });+ if cache_read > 0 {+ usage["prompt_tokens_details"] = json!({ "cached_tokens": cache_read });+ }+ if cache_write > 0 {+ usage["cache_creation_input_tokens"] = json!(cache_write);+ }+ usage+}++/// Read Anthropic's two cache counters from a `usage` object (`message_start`+/// for the stream, the top-level `usage` for a non-stream response).+fn anthropic_cache_tokens(usage: Option<&Value>) -> (i64, i64) {+ let read = usage+ .and_then(|u| u.get("cache_read_input_tokens"))+ .and_then(|v| v.as_i64())+ .unwrap_or(0);+ let write = usage+ .and_then(|u| u.get("cache_creation_input_tokens"))+ .and_then(|v| v.as_i64())+ .unwrap_or(0);+ (read, write)}/// Append `blocks` to the last message when it shares `role`, else start a new@@ -921,6 +1018,10 @@ impl UpstreamConverter for AnthropicMessagesConverter {}}+ fn cache_capability(&self) -> CacheCapability {+ CacheCapability::Explicit+ }+fn auth_header(&self, key: &str) -> (&'static str, String) {if self.oauth {("authorization", format!("Bearer {key}"))@@ -1028,11 +1129,11 @@ impl UpstreamConverter for AnthropicMessagesConverter {}out["messages"] = json!(messages);if !system.is_empty() {- out["system"] = json!(system.join("\n\n"));+ out["system"] = self.system_value(system);}if let Some(tools) = body.get("tools").and_then(|t| t.as_array()) {- let mapped: Vec<Value> = tools+ let mut mapped: Vec<Value> = tools.iter().filter_map(|t| {let func = t.get("function")?;@@ -1044,6 +1145,15 @@ impl UpstreamConverter for AnthropicMessagesConverter {}).collect();if !mapped.is_empty() {+ // Tools sit at the head of Anthropic's cache prefix and are+ // stable for the whole session, so a breakpoint on the last one+ // caches the entire tool schema. Guarded by the capability so+ // the marker is emitted only where the provider reads it.+ if self.cache_capability() == CacheCapability::Explicit {+ if let Some(last) = mapped.last_mut() {+ last["cache_control"] = json!({ "type": "ephemeral" });+ }+ }out["tools"] = json!(mapped);}}@@ -1119,6 +1229,7 @@ impl UpstreamConverter for AnthropicMessagesConverter {let usage = upstream.get("usage");let input_tokens = usage.and_then(|u| u.get("input_tokens")).and_then(|v| v.as_i64()).unwrap_or(0);let output_tokens = usage.and_then(|u| u.get("output_tokens")).and_then(|v| v.as_i64()).unwrap_or(0);+ let (cache_read, cache_write) = anthropic_cache_tokens(usage);json!({"id": upstream.get("id").cloned().unwrap_or_else(|| json!("chatcmpl-proxy")),@@ -1130,7 +1241,7 @@ impl UpstreamConverter for AnthropicMessagesConverter {"message": message,"finish_reason": finish_reason,}],- "usage": anthropic_usage(input_tokens, output_tokens),+ "usage": anthropic_usage(input_tokens, cache_read, cache_write, output_tokens),})}@@ -1161,6 +1272,9 @@ impl UpstreamConverter for AnthropicMessagesConverter {if let Some(t) = msg.get("usage").and_then(|u| u.get("input_tokens")).and_then(|v| v.as_i64()) {state.input_tokens = t;}+ let (read, write) = anthropic_cache_tokens(msg.get("usage"));+ state.cache_read_tokens = read;+ state.cache_write_tokens = write;}}"content_block_start" => {@@ -1230,7 +1344,12 @@ impl UpstreamConverter for AnthropicMessagesConverter {.and_then(|u| u.get("output_tokens")).and_then(|v| v.as_i64()).unwrap_or(0);- let usage = anthropic_usage(state.input_tokens, output_tokens);+ let usage = anthropic_usage(+ state.input_tokens,+ state.cache_read_tokens,+ state.cache_write_tokens,+ output_tokens,+ );out.push(chunk_str_with_usage(state, json!({}), Some(finish), Some(&usage)));out.push("[DONE]".to_string());state.finished = true;@@ -1299,11 +1418,24 @@ fn convert_usage(usage: Option<&Value>) -> Value {.get("total_tokens").and_then(|v| v.as_i64()).unwrap_or(prompt + completion);- json!({+ let mut out = json!({"prompt_tokens": prompt,"completion_tokens": completion,"total_tokens": total,- })+ });+ // Responses reports cache reads under `input_tokens_details.cached_tokens`,+ // and unlike Anthropic its `input_tokens` already includes them, so only the+ // detail is forwarded (no compensation). Surfaced in the chat shape+ // `Usage::from_completion` reads, so `/context` shows the cache line here too.+ if let Some(cached) = u+ .get("input_tokens_details")+ .and_then(|d| d.get("cached_tokens"))+ .and_then(|v| v.as_i64())+ .filter(|c| *c > 0)+ {+ out["prompt_tokens_details"] = json!({ "cached_tokens": cached });+ }+ out}#[cfg(test)]@@ -1841,6 +1973,12 @@ mod anthropic_messages_tests {AnthropicMessagesConverter::new()}+ /// A stable system prompt large enough to clear `ANTHROPIC_MIN_CACHEABLE_CHARS`+ /// so the cache breakpoint is actually placed.+ fn big_system() -> String {+ "S".repeat(ANTHROPIC_MIN_CACHEABLE_CHARS + 100)+ }+#[test]fn oauth_auth_and_headers_use_bearer_plus_code_beta() {let c = AnthropicMessagesConverter::new_oauth();@@ -1893,7 +2031,9 @@ mod anthropic_messages_tests {});let out = conv().convert_request(&body);assert_eq!(out["model"], json!("claude-sonnet-4"));- assert_eq!(out["system"], json!("be brief"));+ // A tiny system prompt is below Anthropic's min cacheable size, so it is+ // emitted as a block array with no breakpoint.+ assert_eq!(out["system"], json!([{"type": "text", "text": "be brief"}]));assert_eq!(out["max_tokens"], json!(ANTHROPIC_DEFAULT_MAX_TOKENS));assert_eq!(out["messages"],@@ -1908,25 +2048,29 @@ mod anthropic_messages_tests {// OAuth account token to lightweight models (429 on sonnet) regardless// of the account's real plan. The oauth converter must mirror that or// heavy models fail under the Claude Code alias.+ let prompt = big_system();let body = json!({"model": "claude-sonnet-5","messages": [- {"role": "system", "content": "be brief"},+ {"role": "system", "content": prompt},{"role": "user", "content": "hi"}]});let plain = conv().convert_request(&body);- assert_eq!(plain["system"], json!("be brief"));+ assert_eq!(plain["system"][0]["text"], json!(prompt));+ assert_eq!(plain["system"][0]["cache_control"], json!({"type": "ephemeral"}));let oauth_body = AnthropicMessagesConverter::new_oauth().convert_request(&body);- let sys = oauth_body["system"].as_str().unwrap();- assert!(- sys.starts_with("x-anthropic-billing-header: cc_version="),- "oauth request must inject the billing header first: {sys}"- );- assert!(sys.contains("cc_entrypoint=sdk-cli;"));- // The real system prompt is still carried after the billing marker.- assert!(sys.contains("be brief"));+ let sys = oauth_body["system"].as_array().unwrap();+ // The billing header is block 0 and stays uncached; the real system+ // prompt is block 1 and carries the cache breakpoint.+ assert!(sys[0]["text"]+ .as_str()+ .unwrap()+ .starts_with("x-anthropic-billing-header: cc_version="));+ assert!(sys[0].get("cache_control").is_none());+ assert_eq!(sys[1]["text"], json!(prompt));+ assert_eq!(sys[1]["cache_control"], json!({"type": "ephemeral"}));}#[test]@@ -1978,11 +2122,86 @@ mod anthropic_messages_tests {let out = conv().convert_request(&body);assert_eq!(out["tools"],- json!([{"name": "f", "description": "d", "input_schema": {"type": "object"}}])+ json!([{+ "name": "f",+ "description": "d",+ "input_schema": {"type": "object"},+ "cache_control": {"type": "ephemeral"}+ }]));assert_eq!(out["tool_choice"], json!({"type": "any"}));}+ #[test]+ fn cache_breakpoint_lands_on_the_stable_block_only() {+ // The agent's shape after #340/#343: stable prompt, volatile per-turn+ // block, compaction summary -- all system messages. Only the stable+ // first block may carry the breakpoint; volatile and summary change and+ // must stay uncached.+ let stable = big_system();+ let body = json!({+ "model": "claude-sonnet-4",+ "messages": [+ {"role": "system", "content": stable},+ {"role": "system", "content": "Today's date is 2026-09-16."},+ {"role": "system", "content": "[Summary of earlier conversation, condensed to save context]\n\nx"},+ {"role": "user", "content": "hi"}+ ]+ });+ let sys = conv().convert_request(&body)["system"].as_array().unwrap().clone();+ assert_eq!(sys.len(), 3);+ assert_eq!(sys[0]["text"], json!(stable));+ assert_eq!(sys[0]["cache_control"], json!({"type": "ephemeral"}));+ assert!(sys[1].get("cache_control").is_none());+ assert!(sys[2].get("cache_control").is_none());+ }++ #[test]+ fn anthropic_cached_system_block_is_byte_identical_across_turns() {+ // #344: the cached block (system[0], carrying cache_control) must be+ // byte-for-byte identical across turns for Anthropic's cache to hit,+ // even as the volatile block and conversation change.+ let stable = big_system();+ let turn1 = json!({+ "model": "claude-sonnet-4",+ "messages": [+ {"role": "system", "content": stable},+ {"role": "system", "content": "Today's date is 2026-09-16."},+ {"role": "user", "content": "first"}+ ]+ });+ let turn2 = json!({+ "model": "claude-sonnet-4",+ "messages": [+ {"role": "system", "content": stable},+ {"role": "system", "content": "Today's date is 2026-09-17.\n\nrecalled note"},+ {"role": "user", "content": "first"},+ {"role": "assistant", "content": "reply"},+ {"role": "user", "content": "second"}+ ]+ });+ let block1 = conv().convert_request(&turn1)["system"][0].clone();+ let block2 = conv().convert_request(&turn2)["system"][0].clone();+ assert_eq!(+ serde_json::to_string(&block1).unwrap(),+ serde_json::to_string(&block2).unwrap()+ );+ assert_eq!(block1["cache_control"], json!({"type": "ephemeral"}));+ }++ #[test]+ fn implicit_converters_emit_no_cache_control() {+ assert_eq!(conv().cache_capability(), CacheCapability::Explicit);+ assert_eq!(+ OpenAIResponsesConverter::new().cache_capability(),+ CacheCapability::Implicit+ );+ assert_eq!(+ GoogleGenerateContentConverter::new().cache_capability(),+ CacheCapability::Implicit+ );+ }+#[test]fn request_maps_named_tool_choice() {let body = json!({@@ -2067,6 +2286,42 @@ mod anthropic_messages_tests {assert!(state.finished);}+ #[test]+ fn stream_folds_cache_tokens_into_prompt_tokens() {+ // Anthropic reports cache read/write in message_start, excluded from+ // input_tokens. The chat-shaped usage must add them back into+ // prompt_tokens and expose them where `Usage::from_completion` reads.+ let c = conv();+ let mut state = StreamState::default();+ c.convert_stream_event(+ &ev(+ "message_start",+ json!({"message": {"id": "m", "model": "claude-sonnet-4", "usage": {+ "input_tokens": 10,+ "cache_read_input_tokens": 80,+ "cache_creation_input_tokens": 40+ }}}),+ ),+ &mut state,+ );+ let done = c.convert_stream_event(+ &ev("message_delta", json!({"delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 5}})),+ &mut state,+ );+ let usage: Value = serde_json::from_str(&done[0]).unwrap();+ let usage = &usage["usage"];+ assert_eq!(usage["prompt_tokens"], json!(130));+ assert_eq!(usage["total_tokens"], json!(135));+ assert_eq!(usage["prompt_tokens_details"]["cached_tokens"], json!(80));+ assert_eq!(usage["cache_creation_input_tokens"], json!(40));++ let parsed =+ crate::core::agent::events::Usage::from_completion(&json!({"usage": usage})).unwrap();+ assert_eq!(parsed.cached_tokens, Some(80));+ assert_eq!(parsed.cache_write_tokens, Some(40));+ assert_eq!(parsed.prompt_tokens, Some(130));+ }+#[test]fn stream_tool_use_emits_header_and_argument_deltas() {let c = conv();