From b19922b71d9f0feaba627cf6fa8118bb4c99e0c0 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 21:17:35 +0800 Subject: [PATCH] fix(agents): keep the context ring on the window Claude Code reports (#5902) A result's modelUsage can give a model a larger contextWindow (1M) than the window Claude Code counts and compacts against (get_context_usage maxTokens, 400k), so the ring and the Context window details disagreed. The window get_context_usage reports, when the details or a compaction read it, now wins for that model. --- crates/ide-agent/src/native/claude/mod.rs | 11 +++++++++- crates/ide-agent/src/native/claude/tests.rs | 18 ++++++++++++++++ .../ide-agent/src/native/claude/translate.rs | 21 ++++++++++++------- 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/crates/ide-agent/src/native/claude/mod.rs b/crates/ide-agent/src/native/claude/mod.rs index 86707de5bf..0593db892a 100644 --- a/crates/ide-agent/src/native/claude/mod.rs +++ b/crates/ide-agent/src/native/claude/mod.rs @@ -505,7 +505,16 @@ impl Shim { "_openidea/context_usage" => { let session = self.session(¶ms)?; let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?; - rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal) + let usage = rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)?; + // The meter shows the same numbers as these details from now on. + let n = |k: &str| usage.get(k).and_then(Value::as_u64); + if let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) { + let update = session.st.lock().tr.on_context_usage(used, size); + if let Some(shim) = session.shim() { + shim.notify(vec![update]); + } + } + Ok(usage) } "_openidea/stop_task" => { let session = self.session(¶ms)?; diff --git a/crates/ide-agent/src/native/claude/tests.rs b/crates/ide-agent/src/native/claude/tests.rs index 5c5151fb16..b7a6f58519 100644 --- a/crates/ide-agent/src/native/claude/tests.rs +++ b/crates/ide-agent/src/native/claude/tests.rs @@ -1148,6 +1148,24 @@ fn a_compaction_replaces_the_context_usage() { assert!(t.on_result(&result).is_empty()); } +#[test] +fn claude_codes_own_window_wins_over_the_results_context_window() { + let mut t = Translator::new("s", PathBuf::from("/w"), true); + let assistant = |model: &str| { + json!({"type": "assistant", "parent_tool_use_id": null, + "message": {"id": "m1", "model": model, "content": [], "usage": {"input_tokens": 900, "output_tokens": 100}}}) + }; + t.on_message(&assistant("x")); + let result = json!({"modelUsage": {"x": {"contextWindow": 1_000_000}, "y": {"contextWindow": 200_000}}}); + assert_eq!(t.on_result(&result)[0].update["size"], 1_000_000); + // `get_context_usage` reports the window Claude Code compacts against. + assert_eq!(t.on_context_usage(1000, 400_000).update["size"], 400_000); + assert_eq!(t.on_result(&result)[0].update["size"], 400_000); + // Another model: its own window again until Claude Code reports one for it. + t.on_message(&assistant("y")); + assert_eq!(t.on_result(&result)[0].update["size"], 200_000); +} + #[test] fn rate_limits_and_cost() { let mut t = Translator::new("s", PathBuf::from("/w"), false); diff --git a/crates/ide-agent/src/native/claude/translate.rs b/crates/ide-agent/src/native/claude/translate.rs index 7fb89dde2f..e0636b656f 100644 --- a/crates/ide-agent/src/native/claude/translate.rs +++ b/crates/ide-agent/src/native/claude/translate.rs @@ -58,6 +58,10 @@ pub(super) struct Translator { pub used: Option, pub model: Option, windows: HashMap, + /// The window Claude Code itself counts against (`get_context_usage` `maxTokens`) and the + /// model it was read for. It can be smaller than the model's `contextWindow` in a `result` + /// (its compaction threshold follows this one), so it wins while the model is the same. + context_max: Option<(Option, u64)>, /// The session's cost so far in USD, as the last `result` reported it. cost_usd: Option, } @@ -77,6 +81,7 @@ impl Translator { used: None, model: None, windows: HashMap::new(), + context_max: None, cost_usd: None, } } @@ -571,6 +576,7 @@ impl Translator { /// The context usage Claude Code reports (`get_context_usage`), as a usage update. pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update { self.used = Some(used); + self.context_max = Some((self.model.clone(), size)); let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size }); if let Some(amount) = self.cost_usd { update["cost"] = json!({ "amount": amount, "currency": "USD" }); @@ -580,13 +586,14 @@ impl Translator { fn usage_update(&self) -> Option { let used = self.used?; - let size = self - .model - .as_ref() - .and_then(|m| { - self.windows - .get(m) - .or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v)) + let own = self.context_max.as_ref().filter(|(model, _)| *model == self.model).map(|(_, size)| size); + let size = own + .or_else(|| { + self.model.as_ref().and_then(|m| { + self.windows + .get(m) + .or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v)) + }) }) .or_else(|| (self.windows.len() == 1).then(|| self.windows.values().next()).flatten())?; let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });