From 9df62ade05ebbdc9b745cb8ba5e203befc60d0b2 Mon Sep 17 00:00:00 2001 From: Tryanks Date: Wed, 2 Dec 2026 17:45:41 +0800 Subject: [PATCH] Claude: show the window Claude Code compacts against, and let 1M be chosen Claude Code 2.1.334 added an `auto` auto-compact window that compacts a 1M model such as Opus 5.5 near 400k (367k threshold) instead of 967k. Tcode sent no window for the model's default, so the CLI's `auto` took over silently while the meter and the window selector still said 1M, and choosing 1M sent nothing, so it could not be had back. - After each turn, ask `get_context_usage` and report its `maxTokens` as the session's window, so the meter counts against the window the CLI really compacts at. The session joins `auto` on its second request, which the read after that turn picks up. - A selector whose default is the model's largest window now defaults to "Auto", which sends no window and leaves the CLI to its own (its `auto`, or a size `/autocompact` saved). A size the person chooses, 1M included, is sent as `autoCompactWindow`. - The window dialog matches presets by value as well as by size, so "Auto" shows as checked and pending. The CLI's one-time `autoWindowAnnouncement` is only built for interactive sessions and first-party entrypoints, so it never reaches Tcode's headless sessions and there is nothing of it to show. --- crates/agent/src/claude.rs | 47 ++++++-- crates/agent/src/claude/control.rs | 4 + crates/agent/src/claude/requests.rs | 26 ++++ crates/agent/src/claude/tests.rs | 54 ++++++++- crates/agent/src/claude_manifest.rs | 112 +++++++++++++++--- .../src/composer/components/context_window.rs | 19 ++- 6 files changed, 228 insertions(+), 34 deletions(-) diff --git a/crates/agent/src/claude.rs b/crates/agent/src/claude.rs index 02b1e72db..8e300d3e8 100644 --- a/crates/agent/src/claude.rs +++ b/crates/agent/src/claude.rs @@ -671,7 +671,8 @@ struct ClaudeLaunchOptions { fast_mode: bool, ultracode: bool, auto_compact_window: Option, - /// The window is the bare slug's own, so `auto_compact_window` adds nothing. + /// The window is the bare slug's own and below its largest, so + /// `auto_compact_window` adds nothing. native_window: bool, } @@ -728,13 +729,20 @@ impl ClaudeLaunchOptions { let suffix = entry.map_or("", |entry| entry.context_window_suffix(window)); format!("{base}{suffix}") }); - // Anything below the model's largest window is enforced through - // `autoCompactWindow`: some bare slugs (e.g. Opus 5.5) already run at - // 1M, so a smaller selection must be told to compact early. - let largest = entry - .and_then(CatalogModel::largest_context_window) - .unwrap_or(window); - let auto_compact_window = (window < largest).then_some(window); + // A size the person chose is enforced through `autoCompactWindow`, + // the model's largest too: Claude Code's own `auto` (2.1.334) + // compacts a 1M model near 400k unless told otherwise. With no size + // chosen, a default below the largest is still enforced, because some + // bare slugs (e.g. Opus 5.5) run at more than that default. A model + // without window data is sent none. + let largest = entry.and_then(CatalogModel::largest_context_window); + let chosen = selections + .iter() + .find(|selection| selection.id == crate::context_window::OPTION_ID) + .and_then(|selection| crate::context_window::parse_tokens(&selection.value)) + .is_some(); + let auto_compact_window = + largest.and_then(|largest| (chosen || window < largest).then_some(window)); // `--settings` object: only supported/true keys are emitted. let fast_supported = spec.is_some_and(|spec| has_boolean_option(spec, "fastMode")); @@ -759,7 +767,11 @@ impl ClaudeLaunchOptions { fast_mode, ultracode, auto_compact_window, - native_window: entry.and_then(CatalogModel::default_context_window) == Some(window), + // Claude Code's `auto` lowers the window the slug opens only to a + // smaller size (2.1.334: 400k for 1M models), so a default below + // the model's largest is taken to run at exactly its own. + native_window: largest.is_some_and(|largest| window < largest) + && entry.and_then(CatalogModel::default_context_window) == Some(window), } } @@ -2147,6 +2159,12 @@ pub(crate) struct Mapper { pending_settings: Option, /// The `get_settings` read awaiting its answer. pending_settings_read: Option, + /// The `get_context_usage` read awaiting its answer. + pending_window_read: Option, + /// The window Claude Code compacts against, as `get_context_usage` last + /// said: its `auto` or `/autocompact` size, which the model's own + /// `contextWindow` in `modelUsage` does not show. + compact_window: Option, /// The skills init named: a pushed command list does not say which of /// its commands are skills. skills: Vec, @@ -2224,6 +2242,8 @@ impl Mapper { applied_settings: ClaudeLaunchOptions::default(), pending_settings: None, pending_settings_read: None, + pending_window_read: None, + compact_window: None, skills: Vec::new(), reported_model: None, reported_fast_mode: None, @@ -2677,6 +2697,11 @@ impl Mapper { .as_u64() }) .or(usage.context_window); + // The window the CLI compacts against is at most the model's. + usage.context_window = match (self.compact_window, usage.context_window) { + (Some(compact), Some(model)) => Some(compact.min(model)), + (compact, model) => compact.or(model), + }; usage.turn_processed_tokens = processed; // The timeline owns lifetime accumulation, including restored history. usage.total_processed_tokens = None; @@ -2725,6 +2750,10 @@ impl Mapper { status, usage, }); + // The turn may have moved the window: its first request enrolls the + // session in `auto`, and a size or model chosen since takes effect. + let read = self.window_read_request(); + self.outgoing.push(read); events } } diff --git a/crates/agent/src/claude/control.rs b/crates/agent/src/claude/control.rs index 78d268c8e..459577f24 100644 --- a/crates/agent/src/claude/control.rs +++ b/crates/agent/src/claude/control.rs @@ -22,6 +22,10 @@ impl Mapper { .into_iter() .collect(); } + if self.pending_window_read.as_deref() == Some(request_id) { + self.pending_window_read = None; + return self.on_window_read(response); + } if self.pending_settings_read.as_deref() == Some(request_id) { self.pending_settings_read = None; return self.on_settings_read(response); diff --git a/crates/agent/src/claude/requests.rs b/crates/agent/src/claude/requests.rs index 314fa6675..cd76d0eea 100644 --- a/crates/agent/src/claude/requests.rs +++ b/crates/agent/src/claude/requests.rs @@ -279,6 +279,32 @@ impl Mapper { message } + /// `get_context_usage`, whose `maxTokens` is the window the session + /// compacts against (2.1.334): `autoWindow` once the session is on + /// `auto`, a size from settings, or the model's own. + pub(super) fn window_read_request(&mut self) -> Value { + let message = self.control_request(json!({ "subtype": "get_context_usage" })); + self.pending_window_read = message["request_id"].as_str().map(str::to_owned); + message + } + + pub(super) fn on_window_read(&mut self, response: &Value) -> Vec { + let Some(window) = response + .pointer("/response/maxTokens") + .and_then(Value::as_u64) + .filter(|_| response.get("subtype").and_then(Value::as_str) == Some("success")) + else { + log::debug!("claude: get_context_usage gave no window: {response}"); + return Vec::new(); + }; + self.compact_window = Some(window); + if self.latest_usage.context_window == Some(window) { + return Vec::new(); + } + self.latest_usage.context_window = Some(window); + vec![AgentEvent::TokenUsage(self.latest_usage)] + } + pub(super) fn on_settings_read(&mut self, response: &Value) -> Vec { let applied = response .pointer("/response/applied") diff --git a/crates/agent/src/claude/tests.rs b/crates/agent/src/claude/tests.rs index 65fd5dbdd..435dc6ce0 100644 --- a/crates/agent/src/claude/tests.rs +++ b/crates/agent/src/claude/tests.rs @@ -1092,13 +1092,17 @@ fn context_window_launch_semantics() { }; let auto_compact = |launch: &ClaudeLaunchOptions| settings(launch)["autoCompactWindow"].clone(); - // Default window of a 1M-default profile: the bare slug already runs - // at 1M, so no suffix is sent (and none is needed for `1m` either). - for value in [None, Some(json!("1m"))] { + // A 1M-default profile with no size chosen, or `auto`, sends no window: + // Claude Code runs at its own (2.1.334 compacts near 400k). Choosing 1M + // sends it, as the bare slug already opens 1M without a suffix. + for value in [None, Some(json!("auto"))] { let launch = resolve("test-wide", value); assert_eq!(launch.model_id.as_deref(), Some("test-wide")); assert!(launch.settings_json.is_none()); } + let launch = resolve("test-wide", Some(json!("1m"))); + assert_eq!(launch.model_id.as_deref(), Some("test-wide")); + assert_eq!(auto_compact(&launch), json!(1_000_000)); assert_eq!(catalog.resolved_context_window("test-wide", &[]), 1_000_000); // A suffixed id still resolves to the same model. assert_eq!( @@ -1122,7 +1126,7 @@ fn context_window_launch_semantics() { } let launch = resolve("test-narrow", Some(json!("1m"))); assert_eq!(launch.model_id.as_deref(), Some("test-narrow[1m]")); - assert!(launch.settings_json.is_none()); + assert_eq!(auto_compact(&launch), json!(1_000_000)); let launch = resolve("test-narrow", Some(json!(500_000))); assert_eq!(launch.model_id.as_deref(), Some("test-narrow[1m]")); assert_eq!(auto_compact(&launch), json!(500_000)); @@ -1132,9 +1136,14 @@ fn context_window_launch_semantics() { catalog.resolved_context_window("test-fixed", &[]), 1_000_000 ); + for value in [None, Some(json!("auto"))] { + let launch = resolve("test-fixed", value); + assert_eq!(launch.model_id.as_deref(), Some("test-fixed")); + assert!(launch.settings_json.is_none()); + } let launch = resolve("test-fixed", Some(json!("1m"))); assert_eq!(launch.model_id.as_deref(), Some("test-fixed")); - assert!(launch.settings_json.is_none()); + assert_eq!(auto_compact(&launch), json!(1_000_000)); let launch = resolve("test-fixed", Some(json!(500_000))); assert_eq!(launch.model_id.as_deref(), Some("test-fixed")); assert_eq!(auto_compact(&launch), json!(500_000)); @@ -3039,6 +3048,41 @@ fn result_maps_to_turn_completed_with_usage() { )); } +/// The meter's window is the one Claude Code compacts against, not the +/// model's: on `auto` a 1M model reports `contextWindow` 1000000 in +/// `modelUsage` while `get_context_usage` gives `maxTokens` 400000 and +/// compacts at 367k. Shapes recorded from Claude Code 2.1.334 on Opus 5.5. +#[test] +fn the_window_is_the_one_claude_code_compacts_against() { + let result = r#"{"type":"result","subtype":"success","is_error":false,"usage":{"input_tokens":2,"cache_read_input_tokens":11952,"cache_creation_input_tokens":11829,"output_tokens":5},"modelUsage":{"claude-opus-5-5":{"contextWindow":1000000,"canonicalModel":"claude-opus-5-5"}}}"#; + let window = |events: &[AgentEvent]| { + events.iter().find_map(|event| match event { + AgentEvent::TurnCompleted { usage, .. } => usage.and_then(|usage| usage.context_window), + AgentEvent::TokenUsage(usage) => usage.context_window, + _ => None, + }) + }; + let mut m = Mapper::new(); + m.start_turn(); + assert_eq!(window(&feed(&mut m, result)), Some(1_000_000)); + let [read] = m.take_outgoing().try_into().expect("one read"); + assert_eq!(read["request"], json!({ "subtype": "get_context_usage" })); + let answer = |read: &Value| { + format!( + r#"{{"type":"control_response","response":{{"subtype":"success","request_id":"{}","response":{{"model":"claude-opus-5-5","maxTokens":400000,"rawMaxTokens":400000,"autoWindow":400000,"autoCompactThreshold":367000,"isAutoCompactEnabled":true,"totalTokens":23783}}}}}}"#, + read["request_id"].as_str().unwrap() + ) + }; + assert_eq!(window(&feed(&mut m, &answer(&read))), Some(400_000)); + + // The next turn reports the CLI's window from the start, and an + // unchanged answer adds nothing. + m.start_turn(); + assert_eq!(window(&feed(&mut m, result)), Some(400_000)); + let [read] = m.take_outgoing().try_into().expect("one read"); + assert!(feed(&mut m, &answer(&read)).is_empty()); +} + #[test] fn interrupted_result_status() { let mut idle = Mapper::new(); diff --git a/crates/agent/src/claude_manifest.rs b/crates/agent/src/claude_manifest.rs index 4f6544159..791d7ae1e 100644 --- a/crates/agent/src/claude_manifest.rs +++ b/crates/agent/src/claude_manifest.rs @@ -224,11 +224,13 @@ impl CatalogModel { }) } - /// Tokens of the default context window selection. + /// Tokens of the window the bare slug opens with no selection. pub(crate) fn default_context_window(&self) -> Option { self.runtime.fixed_context_window_tokens.or_else(|| { - let default = self.default_select("contextWindow")?; - self.runtime.context_window_tokens.get(default).copied() + match self.default_select("contextWindow")? { + AUTO_WINDOW => self.largest_context_window(), + default => self.runtime.context_window_tokens.get(default).copied(), + } }) } @@ -364,6 +366,55 @@ fn descriptor(option: &Value, skipped: &mut Vec) -> Option OptionDescriptor { let label = crate::context_window::format(tokens); @@ -452,6 +503,7 @@ fn catalog_model( { options.push(fixed_context_window_descriptor(tokens)); } + offer_auto_window(&mut options, &runtime); Ok(CatalogModel { spec: ModelSpec { is_default: defaults.get("chat").and_then(Value::as_str) == Some(slug.as_str()), @@ -1013,6 +1065,19 @@ mod tests { id: "contextWindow".into(), label: "Context Window".into(), options: vec![ + SelectOption { + value: AUTO_WINDOW.into(), + label: "Auto".into(), + description: Some( + "Claude Code's own window: its auto setting, or the size /autocompact saved" + .into(), + ), + unavailable: None, + speed: None, + summary: None, + approval: None, + apply: None, + }, SelectOption { value: "200k".into(), label: "200k".into(), @@ -1034,7 +1099,7 @@ mod tests { apply: None, }, ], - default_value: Some("1m".into()), + default_value: Some(AUTO_WINDOW.into()), role: crate::OptionRole::ContextWindow, apply: crate::ApplyTiming::Live, recommended: None, @@ -1057,23 +1122,38 @@ mod tests { permissive: None, } ); - // A fixed window still gets a selector, defaulting to that window. + // A fixed window still gets a selector, defaulting to the CLI's own. assert_eq!( catalog.model("test-fixed").unwrap().spec.options[2], OptionDescriptor::Select { id: "contextWindow".into(), label: "Context Window".into(), - options: vec![SelectOption { - value: "1m".into(), - label: "1M".into(), - description: None, - unavailable: None, - speed: None, - summary: None, - approval: None, - apply: None, - }], - default_value: Some("1m".into()), + options: vec![ + SelectOption { + value: AUTO_WINDOW.into(), + label: "Auto".into(), + description: Some( + "Claude Code's own window: its auto setting, or the size /autocompact saved" + .into(), + ), + unavailable: None, + speed: None, + summary: None, + approval: None, + apply: None, + }, + SelectOption { + value: "1m".into(), + label: "1M".into(), + description: None, + unavailable: None, + speed: None, + summary: None, + approval: None, + apply: None, + }, + ], + default_value: Some(AUTO_WINDOW.into()), role: crate::OptionRole::ContextWindow, apply: crate::ApplyTiming::Live, recommended: None, diff --git a/crates/ui/src/composer/components/context_window.rs b/crates/ui/src/composer/components/context_window.rs index 16006063b..e64fb4331 100644 --- a/crates/ui/src/composer/components/context_window.rs +++ b/crates/ui/src/composer/components/context_window.rs @@ -84,10 +84,21 @@ impl Render for ContextWindowDialog { return div().into_any_element(); }; let states = OptionStates::of(&composer); - let selected = states.running(&id).and_then(context_window::parse_tokens); - let pending = states.pending(&id).and_then(context_window::parse_tokens); + let running = states.running(&id); + let requested = states.pending(&id); + let selected = running.and_then(context_window::parse_tokens); + let pending = requested.and_then(context_window::parse_tokens); let note = states.unconfirmed_note(&id); let tokens_of = |value: &str| context_window::parse_tokens(&serde_json::json!(value)); + // A preset is named by its value, or by its size when it has one: a + // custom size equal to a preset is that preset. + let names = |value: Option<&serde_json::Value>, option: &str| { + value.is_some_and(|value| { + value.as_str() == Some(option) + || tokens_of(option) + .is_some_and(|tokens| context_window::parse_tokens(value) == Some(tokens)) + }) + }; let is_custom = |tokens: Option| { tokens.is_some_and(|tokens| { !options @@ -136,10 +147,10 @@ impl Render for ContextWindowDialog { if default_value.as_deref() == Some(option.value.as_str()) { label.push_str(&default_suffix); } - if pending.is_some() && tokens_of(&option.value) == pending { + if names(requested, &option.value) { label.push_str(&pending_suffix); } - let checked = selected.is_some() && tokens_of(&option.value) == selected; + let checked = names(running, &option.value); let store = self.store.clone(); let session_id = self.session_id.clone().unwrap_or_default(); let value = option.value.clone();