Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 186 additions & 15 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -317,6 +317,7 @@ fn launch_settings_json(
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
auto_compact_window: Option<u64>,
) -> Option<String> {
let mut settings = serde_json::Map::new();
if let Some(thinking) = thinking {
Expand All@@ -328,6 +329,9 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if let Some(window) = auto_compact_window {
settings.insert("autoCompactWindow".into(), json!(window));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}
Expand All@@ -341,14 +345,22 @@ impl ClaudeLaunchOptions {
let ultracode = resolved_effort.as_deref() == Some("ultracode");
let effort = normalize_claude_cli_effort(resolved_effort.as_deref(), model);

// Model id: append `[1m]` when the 1M context window is selected.
let window = resolved_context_window(model.unwrap_or_default(), selections);
let native_window = native_context_window(model.unwrap_or_default());
let effective_model_window = if native_window == 200_000 && window > native_window {
1_000_000
} else {
native_window
};
let model_id = model.map(|m| {
if selection_str(selections, "contextWindow").as_deref() == Some("1m") {
format!("{m}[1m]")
let base = m.strip_suffix("[1m]").unwrap_or(m);
if native_window == 200_000 && window > native_window {
format!("{base}[1m]")
} else {
m.to_owned()
base.to_owned()
}
});
let auto_compact_window = (window < effective_model_window).then_some(window);

// `--settings` object: only supported/true keys are emitted.
let fast_supported = spec
Expand All@@ -366,7 +378,8 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(thinking, fast_mode, ultracode);
let settings_json =
launch_settings_json(thinking, fast_mode, ultracode, auto_compact_window);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -2861,7 +2874,7 @@ fn reasoning(values: &[&str], default: &str) -> OptionDescriptor {
}
}

fn context_window() -> OptionDescriptor {
fn context_window(default: &str) -> OptionDescriptor {
OptionDescriptor::Select {
id: "contextWindow".to_owned(),
label: "Context Window".to_owned(),
Expand All@@ -2877,10 +2890,61 @@ fn context_window() -> OptionDescriptor {
description: None,
},
],
default_value: Some("200k".to_owned()),
default_value: Some(default.to_owned()),
}
}

/// Parse a Claude context-window selection into a validated token count.
pub fn parse_context_window_tokens(value: &Value) -> Option<u64> {
let tokens = match value {
Value::Number(number) => number.as_u64()?,
Value::String(value) => {
let value = value.trim().to_ascii_lowercase();
if let Some(value) = value.strip_suffix('k') {
value.parse::<u64>().ok()?.checked_mul(1_000)?
} else if let Some(value) = value.strip_suffix('m') {
value.parse::<u64>().ok()?.checked_mul(1_000_000)?
} else {
let value = value.parse::<u64>().ok()?;
if value < 1_000 {
value.checked_mul(1_000)?
} else {
value
}
}
}
_ => return None,
};
(100_000..=1_000_000).contains(&tokens).then_some(tokens)
}

/// Return the model's native context-window size in tokens.
pub fn native_context_window(model_id: &str) -> u64 {
match model_id.strip_suffix("[1m]").unwrap_or(model_id) {
"claude-fable-5" | "claude-fable-5-1" | "claude-opus-5" | "claude-sonnet-5"
| "claude-opus-4-7" | "claude-opus-4-8" => 1_000_000,
_ => 200_000,
}
}

/// Format a context-window token count for display.
pub fn format_context_window(tokens: u64) -> String {
if tokens == 1_000_000 {
"1M".to_owned()
} else {
format!("{}k", tokens / 1_000)
}
}

/// Resolve the selected context window, falling back to the model's native size.
pub fn resolved_context_window(model_id: &str, selections: &[OptionSelection]) -> u64 {
selections
.iter()
.find(|selection| selection.id == "contextWindow")
.and_then(|selection| parse_context_window_tokens(&selection.value))
.unwrap_or_else(|| native_context_window(model_id))
}

fn boolean(id: &str, label: &str) -> OptionDescriptor {
OptionDescriptor::Boolean {
id: id.to_owned(),
Expand DownExpand Up@@ -2918,7 +2982,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2937,7 +3001,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2957,7 +3021,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2977,6 +3041,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2988,6 +3053,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"xhigh",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2996,7 +3062,7 @@ fn built_in_models() -> Vec<ModelSpec> {
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("200k"),
],
),
model(
Expand All@@ -3015,15 +3081,15 @@ fn built_in_models() -> Vec<ModelSpec> {
&["low", "medium", "high", "xhigh", "max", "ultrathink"],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
"claude-sonnet-4-6",
"Claude Sonnet 4.6",
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
context_window(),
context_window("200k"),
],
),
model(
Expand DownExpand Up@@ -3490,9 +3556,114 @@ mod tests {
assert_eq!(crate::process::parse_semver("nonsense"), None);
}

#[test]
fn parse_context_window_values() {
assert_eq!(parse_context_window_tokens(&json!("200k")), Some(200_000));
assert_eq!(parse_context_window_tokens(&json!("1m")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("1M")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("500k")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500000")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!(750_000)), Some(750_000));
assert_eq!(parse_context_window_tokens(&json!(99_999)), None);
assert_eq!(parse_context_window_tokens(&json!(1_000_001)), None);
assert_eq!(parse_context_window_tokens(&json!("99k")), None);
assert_eq!(parse_context_window_tokens(&json!("1001k")), None);
assert_eq!(parse_context_window_tokens(&json!("garbage")), None);
assert_eq!(parse_context_window_tokens(&json!(-200_000)), None);
assert_eq!(parse_context_window_tokens(&json!(null)), None);
assert_eq!(native_context_window("claude-opus-5[1m]"), 1_000_000);
assert_eq!(native_context_window("claude-sonnet-4-6[1m]"), 200_000);
assert_eq!(format_context_window(200_000), "200k");
assert_eq!(format_context_window(750_000), "750k");
assert_eq!(format_context_window(1_000_000), "1M");
}

#[test]
fn catalog_context_window_defaults_match_native_windows() {
let default = |model_id: &str| {
model_spec(model_id)
.unwrap()
.options
.into_iter()
.find_map(|option| match option {
OptionDescriptor::Select {
id, default_value, ..
} if id == "contextWindow" => default_value,
_ => None,
})
};

for model_id in [
"claude-fable-5",
"claude-fable-5-1",
"claude-opus-5",
"claude-sonnet-5",
"claude-opus-4-7",
"claude-opus-4-8",
] {
assert_eq!(default(model_id).as_deref(), Some("1m"));
}
for model_id in ["claude-sonnet-4-6", "claude-opus-4-6"] {
assert_eq!(default(model_id).as_deref(), Some("200k"));
}
assert_eq!(default("claude-haiku-4-5"), None);
assert_eq!(default("claude-opus-4-5"), None);
}

#[test]
fn context_window_launch_semantics() {
let resolve = |model, value: Option<Value>| {
let selections = value
.map(|value| {
vec![OptionSelection {
id: "contextWindow".into(),
value,
}]
})
.unwrap_or_default();
ClaudeLaunchOptions::resolve(Some(model), &selections)
};
let auto_compact = |launch: &ClaudeLaunchOptions| {
launch.settings_json.as_deref().map(|settings| {
serde_json::from_str::<Value>(settings).unwrap()["autoCompactWindow"].clone()
})
};

let launch = resolve("claude-opus-5", Some(json!("200k")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(200_000)));

let launch = resolve("claude-opus-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-opus-5", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

let launch = resolve("claude-sonnet-4-6", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-sonnet-4-6", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

for value in [Some(json!("200k")), None] {
let launch = resolve("claude-sonnet-4-6", value);
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6"));
assert!(launch.settings_json.is_none());
}

let launch = resolve("claude-fable-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert!(launch.settings_json.is_none());
}

#[test]
fn launch_options_resolve_effort_context_and_settings() {
// 1M context suffix + ultracode → effort xhigh + settings.ultracode.
// Ultracode → effort xhigh + settings.ultracode.
let launch = ClaudeLaunchOptions::resolve(
Some("claude-opus-4-8"),
&[
Expand DownExpand Up@@ -3528,7 +3699,7 @@ mod tests {
},
],
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert_eq!(launch.effort, None);
assert!(launch.ultrathink);
assert!(launch.settings_json.is_none());
Expand Down
5 changes: 5 additions & 0 deletions crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1171,6 +1171,11 @@ pub enum AgentEvent {
/// The provider compacted its context window (Claude `system/compact_boundary`;
/// Codex `contextCompaction` item). Rendered as a "Context compacted" work-log row.
ContextCompacted,
/// A tcode-level context-window change. This is never emitted by an adapter;
/// the runtime persists it after the user message that selected the window.
ContextWindowChanged {
window: u64,
},
/// Structured plan / task list for the sidebar (Codex `turn/plan/updated`,
/// Claude `TodoWrite`). Replaces the current turn's plan wholesale.
PlanUpdated {
Expand Down
9 changes: 9 additions & 0 deletions crates/core/src/relay.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -234,6 +234,15 @@ fn render_turn(number: usize, entries: &[&TimelineEntry], timeline: &Timeline) -
EntryContent::ContextCompacted => {
activity(&mut body, "context", "provider", "compacted")
}
EntryContent::ContextWindowChanged { window } => activity(
&mut body,
"context",
"provider",
&format!(
"window set to {}",
agent::claude::format_context_window(*window)
),
),
EntryContent::ModelChanged { .. } => {}
EntryContent::Item(ItemContent::WebSearch { query }) => activity(
&mut body,
Expand Down
25 changes: 25 additions & 0 deletions crates/core/src/session.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -429,6 +429,10 @@ pub enum EntryContent {
},
/// The provider compacted its context window (a "Context compacted" work-log row).
ContextCompacted,
/// The user changed the context window for the next provider turn.
ContextWindowChanged {
window: u64,
},
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand DownExpand Up@@ -856,6 +860,16 @@ impl Timeline {
turn,
}));
}
AgentEvent::ContextWindowChanged { window } => {
let turn = self.ensure_turn(ts);
let id = self.synthetic_id("context-window");
self.entries.push(Arc::new(TimelineEntry {
id,
content: EntryContent::ContextWindowChanged { window: *window },
ts,
turn,
}));
}
// Session metadata (composer menus) — not folded into the timeline.
// Session metadata (composer menus / traits picker) — held on the
// active session, not folded into the timeline.
Expand DownExpand Up@@ -1415,6 +1429,17 @@ mod tests {
));
}

#[test]
fn context_window_change_folds_into_the_timeline() {
let timeline =
Timeline::fold_events([AgentEvent::ContextWindowChanged { window: 500_000 }]);

assert!(timeline.entries.iter().any(|entry| matches!(
entry.content,
EntryContent::ContextWindowChanged { window: 500_000 }
)));
}

#[test]
fn structured_user_input_blocks_until_resolution_or_turn_end() {
let request = AgentEvent::UserInputRequested {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 186 additions & 15 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -317,6 +317,7 @@ fn launch_settings_json(
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
auto_compact_window: Option<u64>,
) -> Option<String> {
let mut settings = serde_json::Map::new();
if let Some(thinking) = thinking {
Expand All@@ -328,6 +329,9 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if let Some(window) = auto_compact_window {
settings.insert("autoCompactWindow".into(), json!(window));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}
Expand All@@ -341,14 +345,22 @@ impl ClaudeLaunchOptions {
let ultracode = resolved_effort.as_deref() == Some("ultracode");
let effort = normalize_claude_cli_effort(resolved_effort.as_deref(), model);

// Model id: append `[1m]` when the 1M context window is selected.
let window = resolved_context_window(model.unwrap_or_default(), selections);
let native_window = native_context_window(model.unwrap_or_default());
let effective_model_window = if native_window == 200_000 && window > native_window {
1_000_000
} else {
native_window
};
let model_id = model.map(|m| {
if selection_str(selections, "contextWindow").as_deref() == Some("1m") {
format!("{m}[1m]")
let base = m.strip_suffix("[1m]").unwrap_or(m);
if native_window == 200_000 && window > native_window {
format!("{base}[1m]")
} else {
m.to_owned()
base.to_owned()
}
});
let auto_compact_window = (window < effective_model_window).then_some(window);

// `--settings` object: only supported/true keys are emitted.
let fast_supported = spec
Expand All@@ -366,7 +378,8 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(thinking, fast_mode, ultracode);
let settings_json =
launch_settings_json(thinking, fast_mode, ultracode, auto_compact_window);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -2861,7 +2874,7 @@ fn reasoning(values: &[&str], default: &str) -> OptionDescriptor {
}
}

fn context_window() -> OptionDescriptor {
fn context_window(default: &str) -> OptionDescriptor {
OptionDescriptor::Select {
id: "contextWindow".to_owned(),
label: "Context Window".to_owned(),
Expand All@@ -2877,10 +2890,61 @@ fn context_window() -> OptionDescriptor {
description: None,
},
],
default_value: Some("200k".to_owned()),
default_value: Some(default.to_owned()),
}
}

/// Parse a Claude context-window selection into a validated token count.
pub fn parse_context_window_tokens(value: &Value) -> Option<u64> {
let tokens = match value {
Value::Number(number) => number.as_u64()?,
Value::String(value) => {
let value = value.trim().to_ascii_lowercase();
if let Some(value) = value.strip_suffix('k') {
value.parse::<u64>().ok()?.checked_mul(1_000)?
} else if let Some(value) = value.strip_suffix('m') {
value.parse::<u64>().ok()?.checked_mul(1_000_000)?
} else {
let value = value.parse::<u64>().ok()?;
if value < 1_000 {
value.checked_mul(1_000)?
} else {
value
}
}
}
_ => return None,
};
(100_000..=1_000_000).contains(&tokens).then_some(tokens)
}

/// Return the model's native context-window size in tokens.
pub fn native_context_window(model_id: &str) -> u64 {
match model_id.strip_suffix("[1m]").unwrap_or(model_id) {
"claude-fable-5" | "claude-fable-5-1" | "claude-opus-5" | "claude-sonnet-5"
| "claude-opus-4-7" | "claude-opus-4-8" => 1_000_000,
_ => 200_000,
}
}

/// Format a context-window token count for display.
pub fn format_context_window(tokens: u64) -> String {
if tokens == 1_000_000 {
"1M".to_owned()
} else {
format!("{}k", tokens / 1_000)
}
}

/// Resolve the selected context window, falling back to the model's native size.
pub fn resolved_context_window(model_id: &str, selections: &[OptionSelection]) -> u64 {
selections
.iter()
.find(|selection| selection.id == "contextWindow")
.and_then(|selection| parse_context_window_tokens(&selection.value))
.unwrap_or_else(|| native_context_window(model_id))
}

fn boolean(id: &str, label: &str) -> OptionDescriptor {
OptionDescriptor::Boolean {
id: id.to_owned(),
Expand DownExpand Up@@ -2918,7 +2982,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2937,7 +3001,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2957,7 +3021,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2977,6 +3041,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2988,6 +3053,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"xhigh",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2996,7 +3062,7 @@ fn built_in_models() -> Vec<ModelSpec> {
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("200k"),
],
),
model(
Expand All@@ -3015,15 +3081,15 @@ fn built_in_models() -> Vec<ModelSpec> {
&["low", "medium", "high", "xhigh", "max", "ultrathink"],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
"claude-sonnet-4-6",
"Claude Sonnet 4.6",
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
context_window(),
context_window("200k"),
],
),
model(
Expand DownExpand Up@@ -3490,9 +3556,114 @@ mod tests {
assert_eq!(crate::process::parse_semver("nonsense"), None);
}

#[test]
fn parse_context_window_values() {
assert_eq!(parse_context_window_tokens(&json!("200k")), Some(200_000));
assert_eq!(parse_context_window_tokens(&json!("1m")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("1M")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("500k")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500000")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!(750_000)), Some(750_000));
assert_eq!(parse_context_window_tokens(&json!(99_999)), None);
assert_eq!(parse_context_window_tokens(&json!(1_000_001)), None);
assert_eq!(parse_context_window_tokens(&json!("99k")), None);
assert_eq!(parse_context_window_tokens(&json!("1001k")), None);
assert_eq!(parse_context_window_tokens(&json!("garbage")), None);
assert_eq!(parse_context_window_tokens(&json!(-200_000)), None);
assert_eq!(parse_context_window_tokens(&json!(null)), None);
assert_eq!(native_context_window("claude-opus-5[1m]"), 1_000_000);
assert_eq!(native_context_window("claude-sonnet-4-6[1m]"), 200_000);
assert_eq!(format_context_window(200_000), "200k");
assert_eq!(format_context_window(750_000), "750k");
assert_eq!(format_context_window(1_000_000), "1M");
}

#[test]
fn catalog_context_window_defaults_match_native_windows() {
let default = |model_id: &str| {
model_spec(model_id)
.unwrap()
.options
.into_iter()
.find_map(|option| match option {
OptionDescriptor::Select {
id, default_value, ..
} if id == "contextWindow" => default_value,
_ => None,
})
};

for model_id in [
"claude-fable-5",
"claude-fable-5-1",
"claude-opus-5",
"claude-sonnet-5",
"claude-opus-4-7",
"claude-opus-4-8",
] {
assert_eq!(default(model_id).as_deref(), Some("1m"));
}
for model_id in ["claude-sonnet-4-6", "claude-opus-4-6"] {
assert_eq!(default(model_id).as_deref(), Some("200k"));
}
assert_eq!(default("claude-haiku-4-5"), None);
assert_eq!(default("claude-opus-4-5"), None);
}

#[test]
fn context_window_launch_semantics() {
let resolve = |model, value: Option<Value>| {
let selections = value
.map(|value| {
vec![OptionSelection {
id: "contextWindow".into(),
value,
}]
})
.unwrap_or_default();
ClaudeLaunchOptions::resolve(Some(model), &selections)
};
let auto_compact = |launch: &ClaudeLaunchOptions| {
launch.settings_json.as_deref().map(|settings| {
serde_json::from_str::<Value>(settings).unwrap()["autoCompactWindow"].clone()
})
};

let launch = resolve("claude-opus-5", Some(json!("200k")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(200_000)));

let launch = resolve("claude-opus-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-opus-5", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

let launch = resolve("claude-sonnet-4-6", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-sonnet-4-6", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

for value in [Some(json!("200k")), None] {
let launch = resolve("claude-sonnet-4-6", value);
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6"));
assert!(launch.settings_json.is_none());
}

let launch = resolve("claude-fable-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert!(launch.settings_json.is_none());
}

#[test]
fn launch_options_resolve_effort_context_and_settings() {
// 1M context suffix + ultracode → effort xhigh + settings.ultracode.
// Ultracode → effort xhigh + settings.ultracode.
let launch = ClaudeLaunchOptions::resolve(
Some("claude-opus-4-8"),
&[
Expand DownExpand Up@@ -3528,7 +3699,7 @@ mod tests {
},
],
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert_eq!(launch.effort, None);
assert!(launch.ultrathink);
assert!(launch.settings_json.is_none());
Expand Down
5 changes: 5 additions & 0 deletions crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1171,6 +1171,11 @@ pub enum AgentEvent {
/// The provider compacted its context window (Claude `system/compact_boundary`;
/// Codex `contextCompaction` item). Rendered as a "Context compacted" work-log row.
ContextCompacted,
/// A tcode-level context-window change. This is never emitted by an adapter;
/// the runtime persists it after the user message that selected the window.
ContextWindowChanged {
window: u64,
},
/// Structured plan / task list for the sidebar (Codex `turn/plan/updated`,
/// Claude `TodoWrite`). Replaces the current turn's plan wholesale.
PlanUpdated {
Expand Down
9 changes: 9 additions & 0 deletions crates/core/src/relay.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -234,6 +234,15 @@ fn render_turn(number: usize, entries: &[&TimelineEntry], timeline: &Timeline) -
EntryContent::ContextCompacted => {
activity(&mut body, "context", "provider", "compacted")
}
EntryContent::ContextWindowChanged { window } => activity(
&mut body,
"context",
"provider",
&format!(
"window set to {}",
agent::claude::format_context_window(*window)
),
),
EntryContent::ModelChanged { .. } => {}
EntryContent::Item(ItemContent::WebSearch { query }) => activity(
&mut body,
Expand Down
25 changes: 25 additions & 0 deletions crates/core/src/session.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -429,6 +429,10 @@ pub enum EntryContent {
},
/// The provider compacted its context window (a "Context compacted" work-log row).
ContextCompacted,
/// The user changed the context window for the next provider turn.
ContextWindowChanged {
window: u64,
},
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand DownExpand Up@@ -856,6 +860,16 @@ impl Timeline {
turn,
}));
}
AgentEvent::ContextWindowChanged { window } => {
let turn = self.ensure_turn(ts);
let id = self.synthetic_id("context-window");
self.entries.push(Arc::new(TimelineEntry {
id,
content: EntryContent::ContextWindowChanged { window: *window },
ts,
turn,
}));
}
// Session metadata (composer menus) — not folded into the timeline.
// Session metadata (composer menus / traits picker) — held on the
// active session, not folded into the timeline.
Expand DownExpand Up@@ -1415,6 +1429,17 @@ mod tests {
));
}

#[test]
fn context_window_change_folds_into_the_timeline() {
let timeline =
Timeline::fold_events([AgentEvent::ContextWindowChanged { window: 500_000 }]);

assert!(timeline.entries.iter().any(|entry| matches!(
entry.content,
EntryContent::ContextWindowChanged { window: 500_000 }
)));
}

#[test]
fn structured_user_input_blocks_until_resolution_or_turn_end() {
let request = AgentEvent::UserInputRequested {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 186 additions & 15 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -317,6 +317,7 @@ fn launch_settings_json(
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
auto_compact_window: Option<u64>,
) -> Option<String> {
let mut settings = serde_json::Map::new();
if let Some(thinking) = thinking {
Expand All@@ -328,6 +329,9 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if let Some(window) = auto_compact_window {
settings.insert("autoCompactWindow".into(), json!(window));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}
Expand All@@ -341,14 +345,22 @@ impl ClaudeLaunchOptions {
let ultracode = resolved_effort.as_deref() == Some("ultracode");
let effort = normalize_claude_cli_effort(resolved_effort.as_deref(), model);

// Model id: append `[1m]` when the 1M context window is selected.
let window = resolved_context_window(model.unwrap_or_default(), selections);
let native_window = native_context_window(model.unwrap_or_default());
let effective_model_window = if native_window == 200_000 && window > native_window {
1_000_000
} else {
native_window
};
let model_id = model.map(|m| {
if selection_str(selections, "contextWindow").as_deref() == Some("1m") {
format!("{m}[1m]")
let base = m.strip_suffix("[1m]").unwrap_or(m);
if native_window == 200_000 && window > native_window {
format!("{base}[1m]")
} else {
m.to_owned()
base.to_owned()
}
});
let auto_compact_window = (window < effective_model_window).then_some(window);

// `--settings` object: only supported/true keys are emitted.
let fast_supported = spec
Expand All@@ -366,7 +378,8 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(thinking, fast_mode, ultracode);
let settings_json =
launch_settings_json(thinking, fast_mode, ultracode, auto_compact_window);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -2861,7 +2874,7 @@ fn reasoning(values: &[&str], default: &str) -> OptionDescriptor {
}
}

fn context_window() -> OptionDescriptor {
fn context_window(default: &str) -> OptionDescriptor {
OptionDescriptor::Select {
id: "contextWindow".to_owned(),
label: "Context Window".to_owned(),
Expand All@@ -2877,10 +2890,61 @@ fn context_window() -> OptionDescriptor {
description: None,
},
],
default_value: Some("200k".to_owned()),
default_value: Some(default.to_owned()),
}
}

/// Parse a Claude context-window selection into a validated token count.
pub fn parse_context_window_tokens(value: &Value) -> Option<u64> {
let tokens = match value {
Value::Number(number) => number.as_u64()?,
Value::String(value) => {
let value = value.trim().to_ascii_lowercase();
if let Some(value) = value.strip_suffix('k') {
value.parse::<u64>().ok()?.checked_mul(1_000)?
} else if let Some(value) = value.strip_suffix('m') {
value.parse::<u64>().ok()?.checked_mul(1_000_000)?
} else {
let value = value.parse::<u64>().ok()?;
if value < 1_000 {
value.checked_mul(1_000)?
} else {
value
}
}
}
_ => return None,
};
(100_000..=1_000_000).contains(&tokens).then_some(tokens)
}

/// Return the model's native context-window size in tokens.
pub fn native_context_window(model_id: &str) -> u64 {
match model_id.strip_suffix("[1m]").unwrap_or(model_id) {
"claude-fable-5" | "claude-fable-5-1" | "claude-opus-5" | "claude-sonnet-5"
| "claude-opus-4-7" | "claude-opus-4-8" => 1_000_000,
_ => 200_000,
}
}

/// Format a context-window token count for display.
pub fn format_context_window(tokens: u64) -> String {
if tokens == 1_000_000 {
"1M".to_owned()
} else {
format!("{}k", tokens / 1_000)
}
}

/// Resolve the selected context window, falling back to the model's native size.
pub fn resolved_context_window(model_id: &str, selections: &[OptionSelection]) -> u64 {
selections
.iter()
.find(|selection| selection.id == "contextWindow")
.and_then(|selection| parse_context_window_tokens(&selection.value))
.unwrap_or_else(|| native_context_window(model_id))
}

fn boolean(id: &str, label: &str) -> OptionDescriptor {
OptionDescriptor::Boolean {
id: id.to_owned(),
Expand DownExpand Up@@ -2918,7 +2982,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2937,7 +3001,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2957,7 +3021,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2977,6 +3041,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2988,6 +3053,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"xhigh",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2996,7 +3062,7 @@ fn built_in_models() -> Vec<ModelSpec> {
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("200k"),
],
),
model(
Expand All@@ -3015,15 +3081,15 @@ fn built_in_models() -> Vec<ModelSpec> {
&["low", "medium", "high", "xhigh", "max", "ultrathink"],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
"claude-sonnet-4-6",
"Claude Sonnet 4.6",
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
context_window(),
context_window("200k"),
],
),
model(
Expand DownExpand Up@@ -3490,9 +3556,114 @@ mod tests {
assert_eq!(crate::process::parse_semver("nonsense"), None);
}

#[test]
fn parse_context_window_values() {
assert_eq!(parse_context_window_tokens(&json!("200k")), Some(200_000));
assert_eq!(parse_context_window_tokens(&json!("1m")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("1M")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("500k")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500000")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!(750_000)), Some(750_000));
assert_eq!(parse_context_window_tokens(&json!(99_999)), None);
assert_eq!(parse_context_window_tokens(&json!(1_000_001)), None);
assert_eq!(parse_context_window_tokens(&json!("99k")), None);
assert_eq!(parse_context_window_tokens(&json!("1001k")), None);
assert_eq!(parse_context_window_tokens(&json!("garbage")), None);
assert_eq!(parse_context_window_tokens(&json!(-200_000)), None);
assert_eq!(parse_context_window_tokens(&json!(null)), None);
assert_eq!(native_context_window("claude-opus-5[1m]"), 1_000_000);
assert_eq!(native_context_window("claude-sonnet-4-6[1m]"), 200_000);
assert_eq!(format_context_window(200_000), "200k");
assert_eq!(format_context_window(750_000), "750k");
assert_eq!(format_context_window(1_000_000), "1M");
}

#[test]
fn catalog_context_window_defaults_match_native_windows() {
let default = |model_id: &str| {
model_spec(model_id)
.unwrap()
.options
.into_iter()
.find_map(|option| match option {
OptionDescriptor::Select {
id, default_value, ..
} if id == "contextWindow" => default_value,
_ => None,
})
};

for model_id in [
"claude-fable-5",
"claude-fable-5-1",
"claude-opus-5",
"claude-sonnet-5",
"claude-opus-4-7",
"claude-opus-4-8",
] {
assert_eq!(default(model_id).as_deref(), Some("1m"));
}
for model_id in ["claude-sonnet-4-6", "claude-opus-4-6"] {
assert_eq!(default(model_id).as_deref(), Some("200k"));
}
assert_eq!(default("claude-haiku-4-5"), None);
assert_eq!(default("claude-opus-4-5"), None);
}

#[test]
fn context_window_launch_semantics() {
let resolve = |model, value: Option<Value>| {
let selections = value
.map(|value| {
vec![OptionSelection {
id: "contextWindow".into(),
value,
}]
})
.unwrap_or_default();
ClaudeLaunchOptions::resolve(Some(model), &selections)
};
let auto_compact = |launch: &ClaudeLaunchOptions| {
launch.settings_json.as_deref().map(|settings| {
serde_json::from_str::<Value>(settings).unwrap()["autoCompactWindow"].clone()
})
};

let launch = resolve("claude-opus-5", Some(json!("200k")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(200_000)));

let launch = resolve("claude-opus-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-opus-5", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

let launch = resolve("claude-sonnet-4-6", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-sonnet-4-6", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

for value in [Some(json!("200k")), None] {
let launch = resolve("claude-sonnet-4-6", value);
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6"));
assert!(launch.settings_json.is_none());
}

let launch = resolve("claude-fable-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert!(launch.settings_json.is_none());
}

#[test]
fn launch_options_resolve_effort_context_and_settings() {
// 1M context suffix + ultracode → effort xhigh + settings.ultracode.
// Ultracode → effort xhigh + settings.ultracode.
let launch = ClaudeLaunchOptions::resolve(
Some("claude-opus-4-8"),
&[
Expand DownExpand Up@@ -3528,7 +3699,7 @@ mod tests {
},
],
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert_eq!(launch.effort, None);
assert!(launch.ultrathink);
assert!(launch.settings_json.is_none());
Expand Down
5 changes: 5 additions & 0 deletions crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1171,6 +1171,11 @@ pub enum AgentEvent {
/// The provider compacted its context window (Claude `system/compact_boundary`;
/// Codex `contextCompaction` item). Rendered as a "Context compacted" work-log row.
ContextCompacted,
/// A tcode-level context-window change. This is never emitted by an adapter;
/// the runtime persists it after the user message that selected the window.
ContextWindowChanged {
window: u64,
},
/// Structured plan / task list for the sidebar (Codex `turn/plan/updated`,
/// Claude `TodoWrite`). Replaces the current turn's plan wholesale.
PlanUpdated {
Expand Down
9 changes: 9 additions & 0 deletions crates/core/src/relay.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -234,6 +234,15 @@ fn render_turn(number: usize, entries: &[&TimelineEntry], timeline: &Timeline) -
EntryContent::ContextCompacted => {
activity(&mut body, "context", "provider", "compacted")
}
EntryContent::ContextWindowChanged { window } => activity(
&mut body,
"context",
"provider",
&format!(
"window set to {}",
agent::claude::format_context_window(*window)
),
),
EntryContent::ModelChanged { .. } => {}
EntryContent::Item(ItemContent::WebSearch { query }) => activity(
&mut body,
Expand Down
25 changes: 25 additions & 0 deletions crates/core/src/session.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -429,6 +429,10 @@ pub enum EntryContent {
},
/// The provider compacted its context window (a "Context compacted" work-log row).
ContextCompacted,
/// The user changed the context window for the next provider turn.
ContextWindowChanged {
window: u64,
},
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand DownExpand Up@@ -856,6 +860,16 @@ impl Timeline {
turn,
}));
}
AgentEvent::ContextWindowChanged { window } => {
let turn = self.ensure_turn(ts);
let id = self.synthetic_id("context-window");
self.entries.push(Arc::new(TimelineEntry {
id,
content: EntryContent::ContextWindowChanged { window: *window },
ts,
turn,
}));
}
// Session metadata (composer menus) — not folded into the timeline.
// Session metadata (composer menus / traits picker) — held on the
// active session, not folded into the timeline.
Expand DownExpand Up@@ -1415,6 +1429,17 @@ mod tests {
));
}

#[test]
fn context_window_change_folds_into_the_timeline() {
let timeline =
Timeline::fold_events([AgentEvent::ContextWindowChanged { window: 500_000 }]);

assert!(timeline.entries.iter().any(|entry| matches!(
entry.content,
EntryContent::ContextWindowChanged { window: 500_000 }
)));
}

#[test]
fn structured_user_input_blocks_until_resolution_or_turn_end() {
let request = AgentEvent::UserInputRequested {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 186 additions & 15 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -317,6 +317,7 @@ fn launch_settings_json(
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
auto_compact_window: Option<u64>,
) -> Option<String> {
let mut settings = serde_json::Map::new();
if let Some(thinking) = thinking {
Expand All@@ -328,6 +329,9 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if let Some(window) = auto_compact_window {
settings.insert("autoCompactWindow".into(), json!(window));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}
Expand All@@ -341,14 +345,22 @@ impl ClaudeLaunchOptions {
let ultracode = resolved_effort.as_deref() == Some("ultracode");
let effort = normalize_claude_cli_effort(resolved_effort.as_deref(), model);

// Model id: append `[1m]` when the 1M context window is selected.
let window = resolved_context_window(model.unwrap_or_default(), selections);
let native_window = native_context_window(model.unwrap_or_default());
let effective_model_window = if native_window == 200_000 && window > native_window {
1_000_000
} else {
native_window
};
let model_id = model.map(|m| {
if selection_str(selections, "contextWindow").as_deref() == Some("1m") {
format!("{m}[1m]")
let base = m.strip_suffix("[1m]").unwrap_or(m);
if native_window == 200_000 && window > native_window {
format!("{base}[1m]")
} else {
m.to_owned()
base.to_owned()
}
});
let auto_compact_window = (window < effective_model_window).then_some(window);

// `--settings` object: only supported/true keys are emitted.
let fast_supported = spec
Expand All@@ -366,7 +378,8 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(thinking, fast_mode, ultracode);
let settings_json =
launch_settings_json(thinking, fast_mode, ultracode, auto_compact_window);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -2861,7 +2874,7 @@ fn reasoning(values: &[&str], default: &str) -> OptionDescriptor {
}
}

fn context_window() -> OptionDescriptor {
fn context_window(default: &str) -> OptionDescriptor {
OptionDescriptor::Select {
id: "contextWindow".to_owned(),
label: "Context Window".to_owned(),
Expand All@@ -2877,10 +2890,61 @@ fn context_window() -> OptionDescriptor {
description: None,
},
],
default_value: Some("200k".to_owned()),
default_value: Some(default.to_owned()),
}
}

/// Parse a Claude context-window selection into a validated token count.
pub fn parse_context_window_tokens(value: &Value) -> Option<u64> {
let tokens = match value {
Value::Number(number) => number.as_u64()?,
Value::String(value) => {
let value = value.trim().to_ascii_lowercase();
if let Some(value) = value.strip_suffix('k') {
value.parse::<u64>().ok()?.checked_mul(1_000)?
} else if let Some(value) = value.strip_suffix('m') {
value.parse::<u64>().ok()?.checked_mul(1_000_000)?
} else {
let value = value.parse::<u64>().ok()?;
if value < 1_000 {
value.checked_mul(1_000)?
} else {
value
}
}
}
_ => return None,
};
(100_000..=1_000_000).contains(&tokens).then_some(tokens)
}

/// Return the model's native context-window size in tokens.
pub fn native_context_window(model_id: &str) -> u64 {
match model_id.strip_suffix("[1m]").unwrap_or(model_id) {
"claude-fable-5" | "claude-fable-5-1" | "claude-opus-5" | "claude-sonnet-5"
| "claude-opus-4-7" | "claude-opus-4-8" => 1_000_000,
_ => 200_000,
}
}

/// Format a context-window token count for display.
pub fn format_context_window(tokens: u64) -> String {
if tokens == 1_000_000 {
"1M".to_owned()
} else {
format!("{}k", tokens / 1_000)
}
}

/// Resolve the selected context window, falling back to the model's native size.
pub fn resolved_context_window(model_id: &str, selections: &[OptionSelection]) -> u64 {
selections
.iter()
.find(|selection| selection.id == "contextWindow")
.and_then(|selection| parse_context_window_tokens(&selection.value))
.unwrap_or_else(|| native_context_window(model_id))
}

fn boolean(id: &str, label: &str) -> OptionDescriptor {
OptionDescriptor::Boolean {
id: id.to_owned(),
Expand DownExpand Up@@ -2918,7 +2982,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2937,7 +3001,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2957,7 +3021,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2977,6 +3041,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2988,6 +3053,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"xhigh",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2996,7 +3062,7 @@ fn built_in_models() -> Vec<ModelSpec> {
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("200k"),
],
),
model(
Expand All@@ -3015,15 +3081,15 @@ fn built_in_models() -> Vec<ModelSpec> {
&["low", "medium", "high", "xhigh", "max", "ultrathink"],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
"claude-sonnet-4-6",
"Claude Sonnet 4.6",
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
context_window(),
context_window("200k"),
],
),
model(
Expand DownExpand Up@@ -3490,9 +3556,114 @@ mod tests {
assert_eq!(crate::process::parse_semver("nonsense"), None);
}

#[test]
fn parse_context_window_values() {
assert_eq!(parse_context_window_tokens(&json!("200k")), Some(200_000));
assert_eq!(parse_context_window_tokens(&json!("1m")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("1M")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("500k")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500000")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!(750_000)), Some(750_000));
assert_eq!(parse_context_window_tokens(&json!(99_999)), None);
assert_eq!(parse_context_window_tokens(&json!(1_000_001)), None);
assert_eq!(parse_context_window_tokens(&json!("99k")), None);
assert_eq!(parse_context_window_tokens(&json!("1001k")), None);
assert_eq!(parse_context_window_tokens(&json!("garbage")), None);
assert_eq!(parse_context_window_tokens(&json!(-200_000)), None);
assert_eq!(parse_context_window_tokens(&json!(null)), None);
assert_eq!(native_context_window("claude-opus-5[1m]"), 1_000_000);
assert_eq!(native_context_window("claude-sonnet-4-6[1m]"), 200_000);
assert_eq!(format_context_window(200_000), "200k");
assert_eq!(format_context_window(750_000), "750k");
assert_eq!(format_context_window(1_000_000), "1M");
}

#[test]
fn catalog_context_window_defaults_match_native_windows() {
let default = |model_id: &str| {
model_spec(model_id)
.unwrap()
.options
.into_iter()
.find_map(|option| match option {
OptionDescriptor::Select {
id, default_value, ..
} if id == "contextWindow" => default_value,
_ => None,
})
};

for model_id in [
"claude-fable-5",
"claude-fable-5-1",
"claude-opus-5",
"claude-sonnet-5",
"claude-opus-4-7",
"claude-opus-4-8",
] {
assert_eq!(default(model_id).as_deref(), Some("1m"));
}
for model_id in ["claude-sonnet-4-6", "claude-opus-4-6"] {
assert_eq!(default(model_id).as_deref(), Some("200k"));
}
assert_eq!(default("claude-haiku-4-5"), None);
assert_eq!(default("claude-opus-4-5"), None);
}

#[test]
fn context_window_launch_semantics() {
let resolve = |model, value: Option<Value>| {
let selections = value
.map(|value| {
vec![OptionSelection {
id: "contextWindow".into(),
value,
}]
})
.unwrap_or_default();
ClaudeLaunchOptions::resolve(Some(model), &selections)
};
let auto_compact = |launch: &ClaudeLaunchOptions| {
launch.settings_json.as_deref().map(|settings| {
serde_json::from_str::<Value>(settings).unwrap()["autoCompactWindow"].clone()
})
};

let launch = resolve("claude-opus-5", Some(json!("200k")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(200_000)));

let launch = resolve("claude-opus-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-opus-5", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

let launch = resolve("claude-sonnet-4-6", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-sonnet-4-6", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

for value in [Some(json!("200k")), None] {
let launch = resolve("claude-sonnet-4-6", value);
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6"));
assert!(launch.settings_json.is_none());
}

let launch = resolve("claude-fable-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert!(launch.settings_json.is_none());
}

#[test]
fn launch_options_resolve_effort_context_and_settings() {
// 1M context suffix + ultracode → effort xhigh + settings.ultracode.
// Ultracode → effort xhigh + settings.ultracode.
let launch = ClaudeLaunchOptions::resolve(
Some("claude-opus-4-8"),
&[
Expand DownExpand Up@@ -3528,7 +3699,7 @@ mod tests {
},
],
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert_eq!(launch.effort, None);
assert!(launch.ultrathink);
assert!(launch.settings_json.is_none());
Expand Down
5 changes: 5 additions & 0 deletions crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1171,6 +1171,11 @@ pub enum AgentEvent {
/// The provider compacted its context window (Claude `system/compact_boundary`;
/// Codex `contextCompaction` item). Rendered as a "Context compacted" work-log row.
ContextCompacted,
/// A tcode-level context-window change. This is never emitted by an adapter;
/// the runtime persists it after the user message that selected the window.
ContextWindowChanged {
window: u64,
},
/// Structured plan / task list for the sidebar (Codex `turn/plan/updated`,
/// Claude `TodoWrite`). Replaces the current turn's plan wholesale.
PlanUpdated {
Expand Down
9 changes: 9 additions & 0 deletions crates/core/src/relay.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -234,6 +234,15 @@ fn render_turn(number: usize, entries: &[&TimelineEntry], timeline: &Timeline) -
EntryContent::ContextCompacted => {
activity(&mut body, "context", "provider", "compacted")
}
EntryContent::ContextWindowChanged { window } => activity(
&mut body,
"context",
"provider",
&format!(
"window set to {}",
agent::claude::format_context_window(*window)
),
),
EntryContent::ModelChanged { .. } => {}
EntryContent::Item(ItemContent::WebSearch { query }) => activity(
&mut body,
Expand Down
25 changes: 25 additions & 0 deletions crates/core/src/session.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -429,6 +429,10 @@ pub enum EntryContent {
},
/// The provider compacted its context window (a "Context compacted" work-log row).
ContextCompacted,
/// The user changed the context window for the next provider turn.
ContextWindowChanged {
window: u64,
},
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand DownExpand Up@@ -856,6 +860,16 @@ impl Timeline {
turn,
}));
}
AgentEvent::ContextWindowChanged { window } => {
let turn = self.ensure_turn(ts);
let id = self.synthetic_id("context-window");
self.entries.push(Arc::new(TimelineEntry {
id,
content: EntryContent::ContextWindowChanged { window: *window },
ts,
turn,
}));
}
// Session metadata (composer menus) — not folded into the timeline.
// Session metadata (composer menus / traits picker) — held on the
// active session, not folded into the timeline.
Expand DownExpand Up@@ -1415,6 +1429,17 @@ mod tests {
));
}

#[test]
fn context_window_change_folds_into_the_timeline() {
let timeline =
Timeline::fold_events([AgentEvent::ContextWindowChanged { window: 500_000 }]);

assert!(timeline.entries.iter().any(|entry| matches!(
entry.content,
EntryContent::ContextWindowChanged { window: 500_000 }
)));
}

#[test]
fn structured_user_input_blocks_until_resolution_or_turn_end() {
let request = AgentEvent::UserInputRequested {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 186 additions & 15 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -317,6 +317,7 @@ fn launch_settings_json(
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
auto_compact_window: Option<u64>,
) -> Option<String> {
let mut settings = serde_json::Map::new();
if let Some(thinking) = thinking {
Expand All@@ -328,6 +329,9 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if let Some(window) = auto_compact_window {
settings.insert("autoCompactWindow".into(), json!(window));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}
Expand All@@ -341,14 +345,22 @@ impl ClaudeLaunchOptions {
let ultracode = resolved_effort.as_deref() == Some("ultracode");
let effort = normalize_claude_cli_effort(resolved_effort.as_deref(), model);

// Model id: append `[1m]` when the 1M context window is selected.
let window = resolved_context_window(model.unwrap_or_default(), selections);
let native_window = native_context_window(model.unwrap_or_default());
let effective_model_window = if native_window == 200_000 && window > native_window {
1_000_000
} else {
native_window
};
let model_id = model.map(|m| {
if selection_str(selections, "contextWindow").as_deref() == Some("1m") {
format!("{m}[1m]")
let base = m.strip_suffix("[1m]").unwrap_or(m);
if native_window == 200_000 && window > native_window {
format!("{base}[1m]")
} else {
m.to_owned()
base.to_owned()
}
});
let auto_compact_window = (window < effective_model_window).then_some(window);

// `--settings` object: only supported/true keys are emitted.
let fast_supported = spec
Expand All@@ -366,7 +378,8 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(thinking, fast_mode, ultracode);
let settings_json =
launch_settings_json(thinking, fast_mode, ultracode, auto_compact_window);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -2861,7 +2874,7 @@ fn reasoning(values: &[&str], default: &str) -> OptionDescriptor {
}
}

fn context_window() -> OptionDescriptor {
fn context_window(default: &str) -> OptionDescriptor {
OptionDescriptor::Select {
id: "contextWindow".to_owned(),
label: "Context Window".to_owned(),
Expand All@@ -2877,10 +2890,61 @@ fn context_window() -> OptionDescriptor {
description: None,
},
],
default_value: Some("200k".to_owned()),
default_value: Some(default.to_owned()),
}
}

/// Parse a Claude context-window selection into a validated token count.
pub fn parse_context_window_tokens(value: &Value) -> Option<u64> {
let tokens = match value {
Value::Number(number) => number.as_u64()?,
Value::String(value) => {
let value = value.trim().to_ascii_lowercase();
if let Some(value) = value.strip_suffix('k') {
value.parse::<u64>().ok()?.checked_mul(1_000)?
} else if let Some(value) = value.strip_suffix('m') {
value.parse::<u64>().ok()?.checked_mul(1_000_000)?
} else {
let value = value.parse::<u64>().ok()?;
if value < 1_000 {
value.checked_mul(1_000)?
} else {
value
}
}
}
_ => return None,
};
(100_000..=1_000_000).contains(&tokens).then_some(tokens)
}

/// Return the model's native context-window size in tokens.
pub fn native_context_window(model_id: &str) -> u64 {
match model_id.strip_suffix("[1m]").unwrap_or(model_id) {
"claude-fable-5" | "claude-fable-5-1" | "claude-opus-5" | "claude-sonnet-5"
| "claude-opus-4-7" | "claude-opus-4-8" => 1_000_000,
_ => 200_000,
}
}

/// Format a context-window token count for display.
pub fn format_context_window(tokens: u64) -> String {
if tokens == 1_000_000 {
"1M".to_owned()
} else {
format!("{}k", tokens / 1_000)
}
}

/// Resolve the selected context window, falling back to the model's native size.
pub fn resolved_context_window(model_id: &str, selections: &[OptionSelection]) -> u64 {
selections
.iter()
.find(|selection| selection.id == "contextWindow")
.and_then(|selection| parse_context_window_tokens(&selection.value))
.unwrap_or_else(|| native_context_window(model_id))
}

fn boolean(id: &str, label: &str) -> OptionDescriptor {
OptionDescriptor::Boolean {
id: id.to_owned(),
Expand DownExpand Up@@ -2918,7 +2982,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2937,7 +3001,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2957,7 +3021,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2977,6 +3041,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2988,6 +3053,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"xhigh",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2996,7 +3062,7 @@ fn built_in_models() -> Vec<ModelSpec> {
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("200k"),
],
),
model(
Expand All@@ -3015,15 +3081,15 @@ fn built_in_models() -> Vec<ModelSpec> {
&["low", "medium", "high", "xhigh", "max", "ultrathink"],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
"claude-sonnet-4-6",
"Claude Sonnet 4.6",
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
context_window(),
context_window("200k"),
],
),
model(
Expand DownExpand Up@@ -3490,9 +3556,114 @@ mod tests {
assert_eq!(crate::process::parse_semver("nonsense"), None);
}

#[test]
fn parse_context_window_values() {
assert_eq!(parse_context_window_tokens(&json!("200k")), Some(200_000));
assert_eq!(parse_context_window_tokens(&json!("1m")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("1M")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("500k")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500000")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!(750_000)), Some(750_000));
assert_eq!(parse_context_window_tokens(&json!(99_999)), None);
assert_eq!(parse_context_window_tokens(&json!(1_000_001)), None);
assert_eq!(parse_context_window_tokens(&json!("99k")), None);
assert_eq!(parse_context_window_tokens(&json!("1001k")), None);
assert_eq!(parse_context_window_tokens(&json!("garbage")), None);
assert_eq!(parse_context_window_tokens(&json!(-200_000)), None);
assert_eq!(parse_context_window_tokens(&json!(null)), None);
assert_eq!(native_context_window("claude-opus-5[1m]"), 1_000_000);
assert_eq!(native_context_window("claude-sonnet-4-6[1m]"), 200_000);
assert_eq!(format_context_window(200_000), "200k");
assert_eq!(format_context_window(750_000), "750k");
assert_eq!(format_context_window(1_000_000), "1M");
}

#[test]
fn catalog_context_window_defaults_match_native_windows() {
let default = |model_id: &str| {
model_spec(model_id)
.unwrap()
.options
.into_iter()
.find_map(|option| match option {
OptionDescriptor::Select {
id, default_value, ..
} if id == "contextWindow" => default_value,
_ => None,
})
};

for model_id in [
"claude-fable-5",
"claude-fable-5-1",
"claude-opus-5",
"claude-sonnet-5",
"claude-opus-4-7",
"claude-opus-4-8",
] {
assert_eq!(default(model_id).as_deref(), Some("1m"));
}
for model_id in ["claude-sonnet-4-6", "claude-opus-4-6"] {
assert_eq!(default(model_id).as_deref(), Some("200k"));
}
assert_eq!(default("claude-haiku-4-5"), None);
assert_eq!(default("claude-opus-4-5"), None);
}

#[test]
fn context_window_launch_semantics() {
let resolve = |model, value: Option<Value>| {
let selections = value
.map(|value| {
vec![OptionSelection {
id: "contextWindow".into(),
value,
}]
})
.unwrap_or_default();
ClaudeLaunchOptions::resolve(Some(model), &selections)
};
let auto_compact = |launch: &ClaudeLaunchOptions| {
launch.settings_json.as_deref().map(|settings| {
serde_json::from_str::<Value>(settings).unwrap()["autoCompactWindow"].clone()
})
};

let launch = resolve("claude-opus-5", Some(json!("200k")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(200_000)));

let launch = resolve("claude-opus-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-opus-5", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

let launch = resolve("claude-sonnet-4-6", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-sonnet-4-6", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

for value in [Some(json!("200k")), None] {
let launch = resolve("claude-sonnet-4-6", value);
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6"));
assert!(launch.settings_json.is_none());
}

let launch = resolve("claude-fable-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert!(launch.settings_json.is_none());
}

#[test]
fn launch_options_resolve_effort_context_and_settings() {
// 1M context suffix + ultracode → effort xhigh + settings.ultracode.
// Ultracode → effort xhigh + settings.ultracode.
let launch = ClaudeLaunchOptions::resolve(
Some("claude-opus-4-8"),
&[
Expand DownExpand Up@@ -3528,7 +3699,7 @@ mod tests {
},
],
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert_eq!(launch.effort, None);
assert!(launch.ultrathink);
assert!(launch.settings_json.is_none());
Expand Down
5 changes: 5 additions & 0 deletions crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1171,6 +1171,11 @@ pub enum AgentEvent {
/// The provider compacted its context window (Claude `system/compact_boundary`;
/// Codex `contextCompaction` item). Rendered as a "Context compacted" work-log row.
ContextCompacted,
/// A tcode-level context-window change. This is never emitted by an adapter;
/// the runtime persists it after the user message that selected the window.
ContextWindowChanged {
window: u64,
},
/// Structured plan / task list for the sidebar (Codex `turn/plan/updated`,
/// Claude `TodoWrite`). Replaces the current turn's plan wholesale.
PlanUpdated {
Expand Down
9 changes: 9 additions & 0 deletions crates/core/src/relay.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -234,6 +234,15 @@ fn render_turn(number: usize, entries: &[&TimelineEntry], timeline: &Timeline) -
EntryContent::ContextCompacted => {
activity(&mut body, "context", "provider", "compacted")
}
EntryContent::ContextWindowChanged { window } => activity(
&mut body,
"context",
"provider",
&format!(
"window set to {}",
agent::claude::format_context_window(*window)
),
),
EntryContent::ModelChanged { .. } => {}
EntryContent::Item(ItemContent::WebSearch { query }) => activity(
&mut body,
Expand Down
25 changes: 25 additions & 0 deletions crates/core/src/session.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -429,6 +429,10 @@ pub enum EntryContent {
},
/// The provider compacted its context window (a "Context compacted" work-log row).
ContextCompacted,
/// The user changed the context window for the next provider turn.
ContextWindowChanged {
window: u64,
},
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand DownExpand Up@@ -856,6 +860,16 @@ impl Timeline {
turn,
}));
}
AgentEvent::ContextWindowChanged { window } => {
let turn = self.ensure_turn(ts);
let id = self.synthetic_id("context-window");
self.entries.push(Arc::new(TimelineEntry {
id,
content: EntryContent::ContextWindowChanged { window: *window },
ts,
turn,
}));
}
// Session metadata (composer menus) — not folded into the timeline.
// Session metadata (composer menus / traits picker) — held on the
// active session, not folded into the timeline.
Expand DownExpand Up@@ -1415,6 +1429,17 @@ mod tests {
));
}

#[test]
fn context_window_change_folds_into_the_timeline() {
let timeline =
Timeline::fold_events([AgentEvent::ContextWindowChanged { window: 500_000 }]);

assert!(timeline.entries.iter().any(|entry| matches!(
entry.content,
EntryContent::ContextWindowChanged { window: 500_000 }
)));
}

#[test]
fn structured_user_input_blocks_until_resolution_or_turn_end() {
let request = AgentEvent::UserInputRequested {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 186 additions & 15 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -317,6 +317,7 @@ fn launch_settings_json(
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
auto_compact_window: Option<u64>,
) -> Option<String> {
let mut settings = serde_json::Map::new();
if let Some(thinking) = thinking {
Expand All@@ -328,6 +329,9 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if let Some(window) = auto_compact_window {
settings.insert("autoCompactWindow".into(), json!(window));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}
Expand All@@ -341,14 +345,22 @@ impl ClaudeLaunchOptions {
let ultracode = resolved_effort.as_deref() == Some("ultracode");
let effort = normalize_claude_cli_effort(resolved_effort.as_deref(), model);

// Model id: append `[1m]` when the 1M context window is selected.
let window = resolved_context_window(model.unwrap_or_default(), selections);
let native_window = native_context_window(model.unwrap_or_default());
let effective_model_window = if native_window == 200_000 && window > native_window {
1_000_000
} else {
native_window
};
let model_id = model.map(|m| {
if selection_str(selections, "contextWindow").as_deref() == Some("1m") {
format!("{m}[1m]")
let base = m.strip_suffix("[1m]").unwrap_or(m);
if native_window == 200_000 && window > native_window {
format!("{base}[1m]")
} else {
m.to_owned()
base.to_owned()
}
});
let auto_compact_window = (window < effective_model_window).then_some(window);

// `--settings` object: only supported/true keys are emitted.
let fast_supported = spec
Expand All@@ -366,7 +378,8 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(thinking, fast_mode, ultracode);
let settings_json =
launch_settings_json(thinking, fast_mode, ultracode, auto_compact_window);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -2861,7 +2874,7 @@ fn reasoning(values: &[&str], default: &str) -> OptionDescriptor {
}
}

fn context_window() -> OptionDescriptor {
fn context_window(default: &str) -> OptionDescriptor {
OptionDescriptor::Select {
id: "contextWindow".to_owned(),
label: "Context Window".to_owned(),
Expand All@@ -2877,10 +2890,61 @@ fn context_window() -> OptionDescriptor {
description: None,
},
],
default_value: Some("200k".to_owned()),
default_value: Some(default.to_owned()),
}
}

/// Parse a Claude context-window selection into a validated token count.
pub fn parse_context_window_tokens(value: &Value) -> Option<u64> {
let tokens = match value {
Value::Number(number) => number.as_u64()?,
Value::String(value) => {
let value = value.trim().to_ascii_lowercase();
if let Some(value) = value.strip_suffix('k') {
value.parse::<u64>().ok()?.checked_mul(1_000)?
} else if let Some(value) = value.strip_suffix('m') {
value.parse::<u64>().ok()?.checked_mul(1_000_000)?
} else {
let value = value.parse::<u64>().ok()?;
if value < 1_000 {
value.checked_mul(1_000)?
} else {
value
}
}
}
_ => return None,
};
(100_000..=1_000_000).contains(&tokens).then_some(tokens)
}

/// Return the model's native context-window size in tokens.
pub fn native_context_window(model_id: &str) -> u64 {
match model_id.strip_suffix("[1m]").unwrap_or(model_id) {
"claude-fable-5" | "claude-fable-5-1" | "claude-opus-5" | "claude-sonnet-5"
| "claude-opus-4-7" | "claude-opus-4-8" => 1_000_000,
_ => 200_000,
}
}

/// Format a context-window token count for display.
pub fn format_context_window(tokens: u64) -> String {
if tokens == 1_000_000 {
"1M".to_owned()
} else {
format!("{}k", tokens / 1_000)
}
}

/// Resolve the selected context window, falling back to the model's native size.
pub fn resolved_context_window(model_id: &str, selections: &[OptionSelection]) -> u64 {
selections
.iter()
.find(|selection| selection.id == "contextWindow")
.and_then(|selection| parse_context_window_tokens(&selection.value))
.unwrap_or_else(|| native_context_window(model_id))
}

fn boolean(id: &str, label: &str) -> OptionDescriptor {
OptionDescriptor::Boolean {
id: id.to_owned(),
Expand DownExpand Up@@ -2918,7 +2982,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2937,7 +3001,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2957,7 +3021,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2977,6 +3041,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2988,6 +3053,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"xhigh",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2996,7 +3062,7 @@ fn built_in_models() -> Vec<ModelSpec> {
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("200k"),
],
),
model(
Expand All@@ -3015,15 +3081,15 @@ fn built_in_models() -> Vec<ModelSpec> {
&["low", "medium", "high", "xhigh", "max", "ultrathink"],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
"claude-sonnet-4-6",
"Claude Sonnet 4.6",
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
context_window(),
context_window("200k"),
],
),
model(
Expand DownExpand Up@@ -3490,9 +3556,114 @@ mod tests {
assert_eq!(crate::process::parse_semver("nonsense"), None);
}

#[test]
fn parse_context_window_values() {
assert_eq!(parse_context_window_tokens(&json!("200k")), Some(200_000));
assert_eq!(parse_context_window_tokens(&json!("1m")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("1M")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("500k")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500000")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!(750_000)), Some(750_000));
assert_eq!(parse_context_window_tokens(&json!(99_999)), None);
assert_eq!(parse_context_window_tokens(&json!(1_000_001)), None);
assert_eq!(parse_context_window_tokens(&json!("99k")), None);
assert_eq!(parse_context_window_tokens(&json!("1001k")), None);
assert_eq!(parse_context_window_tokens(&json!("garbage")), None);
assert_eq!(parse_context_window_tokens(&json!(-200_000)), None);
assert_eq!(parse_context_window_tokens(&json!(null)), None);
assert_eq!(native_context_window("claude-opus-5[1m]"), 1_000_000);
assert_eq!(native_context_window("claude-sonnet-4-6[1m]"), 200_000);
assert_eq!(format_context_window(200_000), "200k");
assert_eq!(format_context_window(750_000), "750k");
assert_eq!(format_context_window(1_000_000), "1M");
}

#[test]
fn catalog_context_window_defaults_match_native_windows() {
let default = |model_id: &str| {
model_spec(model_id)
.unwrap()
.options
.into_iter()
.find_map(|option| match option {
OptionDescriptor::Select {
id, default_value, ..
} if id == "contextWindow" => default_value,
_ => None,
})
};

for model_id in [
"claude-fable-5",
"claude-fable-5-1",
"claude-opus-5",
"claude-sonnet-5",
"claude-opus-4-7",
"claude-opus-4-8",
] {
assert_eq!(default(model_id).as_deref(), Some("1m"));
}
for model_id in ["claude-sonnet-4-6", "claude-opus-4-6"] {
assert_eq!(default(model_id).as_deref(), Some("200k"));
}
assert_eq!(default("claude-haiku-4-5"), None);
assert_eq!(default("claude-opus-4-5"), None);
}

#[test]
fn context_window_launch_semantics() {
let resolve = |model, value: Option<Value>| {
let selections = value
.map(|value| {
vec![OptionSelection {
id: "contextWindow".into(),
value,
}]
})
.unwrap_or_default();
ClaudeLaunchOptions::resolve(Some(model), &selections)
};
let auto_compact = |launch: &ClaudeLaunchOptions| {
launch.settings_json.as_deref().map(|settings| {
serde_json::from_str::<Value>(settings).unwrap()["autoCompactWindow"].clone()
})
};

let launch = resolve("claude-opus-5", Some(json!("200k")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(200_000)));

let launch = resolve("claude-opus-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-opus-5", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

let launch = resolve("claude-sonnet-4-6", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-sonnet-4-6", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

for value in [Some(json!("200k")), None] {
let launch = resolve("claude-sonnet-4-6", value);
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6"));
assert!(launch.settings_json.is_none());
}

let launch = resolve("claude-fable-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert!(launch.settings_json.is_none());
}

#[test]
fn launch_options_resolve_effort_context_and_settings() {
// 1M context suffix + ultracode → effort xhigh + settings.ultracode.
// Ultracode → effort xhigh + settings.ultracode.
let launch = ClaudeLaunchOptions::resolve(
Some("claude-opus-4-8"),
&[
Expand DownExpand Up@@ -3528,7 +3699,7 @@ mod tests {
},
],
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert_eq!(launch.effort, None);
assert!(launch.ultrathink);
assert!(launch.settings_json.is_none());
Expand Down
5 changes: 5 additions & 0 deletions crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1171,6 +1171,11 @@ pub enum AgentEvent {
/// The provider compacted its context window (Claude `system/compact_boundary`;
/// Codex `contextCompaction` item). Rendered as a "Context compacted" work-log row.
ContextCompacted,
/// A tcode-level context-window change. This is never emitted by an adapter;
/// the runtime persists it after the user message that selected the window.
ContextWindowChanged {
window: u64,
},
/// Structured plan / task list for the sidebar (Codex `turn/plan/updated`,
/// Claude `TodoWrite`). Replaces the current turn's plan wholesale.
PlanUpdated {
Expand Down
9 changes: 9 additions & 0 deletions crates/core/src/relay.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -234,6 +234,15 @@ fn render_turn(number: usize, entries: &[&TimelineEntry], timeline: &Timeline) -
EntryContent::ContextCompacted => {
activity(&mut body, "context", "provider", "compacted")
}
EntryContent::ContextWindowChanged { window } => activity(
&mut body,
"context",
"provider",
&format!(
"window set to {}",
agent::claude::format_context_window(*window)
),
),
EntryContent::ModelChanged { .. } => {}
EntryContent::Item(ItemContent::WebSearch { query }) => activity(
&mut body,
Expand Down
25 changes: 25 additions & 0 deletions crates/core/src/session.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -429,6 +429,10 @@ pub enum EntryContent {
},
/// The provider compacted its context window (a "Context compacted" work-log row).
ContextCompacted,
/// The user changed the context window for the next provider turn.
ContextWindowChanged {
window: u64,
},
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand DownExpand Up@@ -856,6 +860,16 @@ impl Timeline {
turn,
}));
}
AgentEvent::ContextWindowChanged { window } => {
let turn = self.ensure_turn(ts);
let id = self.synthetic_id("context-window");
self.entries.push(Arc::new(TimelineEntry {
id,
content: EntryContent::ContextWindowChanged { window: *window },
ts,
turn,
}));
}
// Session metadata (composer menus) — not folded into the timeline.
// Session metadata (composer menus / traits picker) — held on the
// active session, not folded into the timeline.
Expand DownExpand Up@@ -1415,6 +1429,17 @@ mod tests {
));
}

#[test]
fn context_window_change_folds_into_the_timeline() {
let timeline =
Timeline::fold_events([AgentEvent::ContextWindowChanged { window: 500_000 }]);

assert!(timeline.entries.iter().any(|entry| matches!(
entry.content,
EntryContent::ContextWindowChanged { window: 500_000 }
)));
}

#[test]
fn structured_user_input_blocks_until_resolution_or_turn_end() {
let request = AgentEvent::UserInputRequested {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 186 additions & 15 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -317,6 +317,7 @@ fn launch_settings_json(
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
auto_compact_window: Option<u64>,
) -> Option<String> {
let mut settings = serde_json::Map::new();
if let Some(thinking) = thinking {
Expand All@@ -328,6 +329,9 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if let Some(window) = auto_compact_window {
settings.insert("autoCompactWindow".into(), json!(window));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}
Expand All@@ -341,14 +345,22 @@ impl ClaudeLaunchOptions {
let ultracode = resolved_effort.as_deref() == Some("ultracode");
let effort = normalize_claude_cli_effort(resolved_effort.as_deref(), model);

// Model id: append `[1m]` when the 1M context window is selected.
let window = resolved_context_window(model.unwrap_or_default(), selections);
let native_window = native_context_window(model.unwrap_or_default());
let effective_model_window = if native_window == 200_000 && window > native_window {
1_000_000
} else {
native_window
};
let model_id = model.map(|m| {
if selection_str(selections, "contextWindow").as_deref() == Some("1m") {
format!("{m}[1m]")
let base = m.strip_suffix("[1m]").unwrap_or(m);
if native_window == 200_000 && window > native_window {
format!("{base}[1m]")
} else {
m.to_owned()
base.to_owned()
}
});
let auto_compact_window = (window < effective_model_window).then_some(window);

// `--settings` object: only supported/true keys are emitted.
let fast_supported = spec
Expand All@@ -366,7 +378,8 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(thinking, fast_mode, ultracode);
let settings_json =
launch_settings_json(thinking, fast_mode, ultracode, auto_compact_window);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -2861,7 +2874,7 @@ fn reasoning(values: &[&str], default: &str) -> OptionDescriptor {
}
}

fn context_window() -> OptionDescriptor {
fn context_window(default: &str) -> OptionDescriptor {
OptionDescriptor::Select {
id: "contextWindow".to_owned(),
label: "Context Window".to_owned(),
Expand All@@ -2877,10 +2890,61 @@ fn context_window() -> OptionDescriptor {
description: None,
},
],
default_value: Some("200k".to_owned()),
default_value: Some(default.to_owned()),
}
}

/// Parse a Claude context-window selection into a validated token count.
pub fn parse_context_window_tokens(value: &Value) -> Option<u64> {
let tokens = match value {
Value::Number(number) => number.as_u64()?,
Value::String(value) => {
let value = value.trim().to_ascii_lowercase();
if let Some(value) = value.strip_suffix('k') {
value.parse::<u64>().ok()?.checked_mul(1_000)?
} else if let Some(value) = value.strip_suffix('m') {
value.parse::<u64>().ok()?.checked_mul(1_000_000)?
} else {
let value = value.parse::<u64>().ok()?;
if value < 1_000 {
value.checked_mul(1_000)?
} else {
value
}
}
}
_ => return None,
};
(100_000..=1_000_000).contains(&tokens).then_some(tokens)
}

/// Return the model's native context-window size in tokens.
pub fn native_context_window(model_id: &str) -> u64 {
match model_id.strip_suffix("[1m]").unwrap_or(model_id) {
"claude-fable-5" | "claude-fable-5-1" | "claude-opus-5" | "claude-sonnet-5"
| "claude-opus-4-7" | "claude-opus-4-8" => 1_000_000,
_ => 200_000,
}
}

/// Format a context-window token count for display.
pub fn format_context_window(tokens: u64) -> String {
if tokens == 1_000_000 {
"1M".to_owned()
} else {
format!("{}k", tokens / 1_000)
}
}

/// Resolve the selected context window, falling back to the model's native size.
pub fn resolved_context_window(model_id: &str, selections: &[OptionSelection]) -> u64 {
selections
.iter()
.find(|selection| selection.id == "contextWindow")
.and_then(|selection| parse_context_window_tokens(&selection.value))
.unwrap_or_else(|| native_context_window(model_id))
}

fn boolean(id: &str, label: &str) -> OptionDescriptor {
OptionDescriptor::Boolean {
id: id.to_owned(),
Expand DownExpand Up@@ -2918,7 +2982,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2937,7 +3001,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2957,7 +3021,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2977,6 +3041,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2988,6 +3053,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"xhigh",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2996,7 +3062,7 @@ fn built_in_models() -> Vec<ModelSpec> {
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("200k"),
],
),
model(
Expand All@@ -3015,15 +3081,15 @@ fn built_in_models() -> Vec<ModelSpec> {
&["low", "medium", "high", "xhigh", "max", "ultrathink"],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
"claude-sonnet-4-6",
"Claude Sonnet 4.6",
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
context_window(),
context_window("200k"),
],
),
model(
Expand DownExpand Up@@ -3490,9 +3556,114 @@ mod tests {
assert_eq!(crate::process::parse_semver("nonsense"), None);
}

#[test]
fn parse_context_window_values() {
assert_eq!(parse_context_window_tokens(&json!("200k")), Some(200_000));
assert_eq!(parse_context_window_tokens(&json!("1m")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("1M")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("500k")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500000")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!(750_000)), Some(750_000));
assert_eq!(parse_context_window_tokens(&json!(99_999)), None);
assert_eq!(parse_context_window_tokens(&json!(1_000_001)), None);
assert_eq!(parse_context_window_tokens(&json!("99k")), None);
assert_eq!(parse_context_window_tokens(&json!("1001k")), None);
assert_eq!(parse_context_window_tokens(&json!("garbage")), None);
assert_eq!(parse_context_window_tokens(&json!(-200_000)), None);
assert_eq!(parse_context_window_tokens(&json!(null)), None);
assert_eq!(native_context_window("claude-opus-5[1m]"), 1_000_000);
assert_eq!(native_context_window("claude-sonnet-4-6[1m]"), 200_000);
assert_eq!(format_context_window(200_000), "200k");
assert_eq!(format_context_window(750_000), "750k");
assert_eq!(format_context_window(1_000_000), "1M");
}

#[test]
fn catalog_context_window_defaults_match_native_windows() {
let default = |model_id: &str| {
model_spec(model_id)
.unwrap()
.options
.into_iter()
.find_map(|option| match option {
OptionDescriptor::Select {
id, default_value, ..
} if id == "contextWindow" => default_value,
_ => None,
})
};

for model_id in [
"claude-fable-5",
"claude-fable-5-1",
"claude-opus-5",
"claude-sonnet-5",
"claude-opus-4-7",
"claude-opus-4-8",
] {
assert_eq!(default(model_id).as_deref(), Some("1m"));
}
for model_id in ["claude-sonnet-4-6", "claude-opus-4-6"] {
assert_eq!(default(model_id).as_deref(), Some("200k"));
}
assert_eq!(default("claude-haiku-4-5"), None);
assert_eq!(default("claude-opus-4-5"), None);
}

#[test]
fn context_window_launch_semantics() {
let resolve = |model, value: Option<Value>| {
let selections = value
.map(|value| {
vec![OptionSelection {
id: "contextWindow".into(),
value,
}]
})
.unwrap_or_default();
ClaudeLaunchOptions::resolve(Some(model), &selections)
};
let auto_compact = |launch: &ClaudeLaunchOptions| {
launch.settings_json.as_deref().map(|settings| {
serde_json::from_str::<Value>(settings).unwrap()["autoCompactWindow"].clone()
})
};

let launch = resolve("claude-opus-5", Some(json!("200k")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(200_000)));

let launch = resolve("claude-opus-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-opus-5", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

let launch = resolve("claude-sonnet-4-6", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-sonnet-4-6", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

for value in [Some(json!("200k")), None] {
let launch = resolve("claude-sonnet-4-6", value);
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6"));
assert!(launch.settings_json.is_none());
}

let launch = resolve("claude-fable-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert!(launch.settings_json.is_none());
}

#[test]
fn launch_options_resolve_effort_context_and_settings() {
// 1M context suffix + ultracode → effort xhigh + settings.ultracode.
// Ultracode → effort xhigh + settings.ultracode.
let launch = ClaudeLaunchOptions::resolve(
Some("claude-opus-4-8"),
&[
Expand DownExpand Up@@ -3528,7 +3699,7 @@ mod tests {
},
],
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert_eq!(launch.effort, None);
assert!(launch.ultrathink);
assert!(launch.settings_json.is_none());
Expand Down
5 changes: 5 additions & 0 deletions crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1171,6 +1171,11 @@ pub enum AgentEvent {
/// The provider compacted its context window (Claude `system/compact_boundary`;
/// Codex `contextCompaction` item). Rendered as a "Context compacted" work-log row.
ContextCompacted,
/// A tcode-level context-window change. This is never emitted by an adapter;
/// the runtime persists it after the user message that selected the window.
ContextWindowChanged {
window: u64,
},
/// Structured plan / task list for the sidebar (Codex `turn/plan/updated`,
/// Claude `TodoWrite`). Replaces the current turn's plan wholesale.
PlanUpdated {
Expand Down
9 changes: 9 additions & 0 deletions crates/core/src/relay.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -234,6 +234,15 @@ fn render_turn(number: usize, entries: &[&TimelineEntry], timeline: &Timeline) -
EntryContent::ContextCompacted => {
activity(&mut body, "context", "provider", "compacted")
}
EntryContent::ContextWindowChanged { window } => activity(
&mut body,
"context",
"provider",
&format!(
"window set to {}",
agent::claude::format_context_window(*window)
),
),
EntryContent::ModelChanged { .. } => {}
EntryContent::Item(ItemContent::WebSearch { query }) => activity(
&mut body,
Expand Down
25 changes: 25 additions & 0 deletions crates/core/src/session.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -429,6 +429,10 @@ pub enum EntryContent {
},
/// The provider compacted its context window (a "Context compacted" work-log row).
ContextCompacted,
/// The user changed the context window for the next provider turn.
ContextWindowChanged {
window: u64,
},
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand DownExpand Up@@ -856,6 +860,16 @@ impl Timeline {
turn,
}));
}
AgentEvent::ContextWindowChanged { window } => {
let turn = self.ensure_turn(ts);
let id = self.synthetic_id("context-window");
self.entries.push(Arc::new(TimelineEntry {
id,
content: EntryContent::ContextWindowChanged { window: *window },
ts,
turn,
}));
}
// Session metadata (composer menus) — not folded into the timeline.
// Session metadata (composer menus / traits picker) — held on the
// active session, not folded into the timeline.
Expand DownExpand Up@@ -1415,6 +1429,17 @@ mod tests {
));
}

#[test]
fn context_window_change_folds_into_the_timeline() {
let timeline =
Timeline::fold_events([AgentEvent::ContextWindowChanged { window: 500_000 }]);

assert!(timeline.entries.iter().any(|entry| matches!(
entry.content,
EntryContent::ContextWindowChanged { window: 500_000 }
)));
}

#[test]
fn structured_user_input_blocks_until_resolution_or_turn_end() {
let request = AgentEvent::UserInputRequested {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 186 additions & 15 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -317,6 +317,7 @@ fn launch_settings_json(
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
auto_compact_window: Option<u64>,
) -> Option<String> {
let mut settings = serde_json::Map::new();
if let Some(thinking) = thinking {
Expand All@@ -328,6 +329,9 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if let Some(window) = auto_compact_window {
settings.insert("autoCompactWindow".into(), json!(window));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}
Expand All@@ -341,14 +345,22 @@ impl ClaudeLaunchOptions {
let ultracode = resolved_effort.as_deref() == Some("ultracode");
let effort = normalize_claude_cli_effort(resolved_effort.as_deref(), model);

// Model id: append `[1m]` when the 1M context window is selected.
let window = resolved_context_window(model.unwrap_or_default(), selections);
let native_window = native_context_window(model.unwrap_or_default());
let effective_model_window = if native_window == 200_000 && window > native_window {
1_000_000
} else {
native_window
};
let model_id = model.map(|m| {
if selection_str(selections, "contextWindow").as_deref() == Some("1m") {
format!("{m}[1m]")
let base = m.strip_suffix("[1m]").unwrap_or(m);
if native_window == 200_000 && window > native_window {
format!("{base}[1m]")
} else {
m.to_owned()
base.to_owned()
}
});
let auto_compact_window = (window < effective_model_window).then_some(window);

// `--settings` object: only supported/true keys are emitted.
let fast_supported = spec
Expand All@@ -366,7 +378,8 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(thinking, fast_mode, ultracode);
let settings_json =
launch_settings_json(thinking, fast_mode, ultracode, auto_compact_window);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -2861,7 +2874,7 @@ fn reasoning(values: &[&str], default: &str) -> OptionDescriptor {
}
}

fn context_window() -> OptionDescriptor {
fn context_window(default: &str) -> OptionDescriptor {
OptionDescriptor::Select {
id: "contextWindow".to_owned(),
label: "Context Window".to_owned(),
Expand All@@ -2877,10 +2890,61 @@ fn context_window() -> OptionDescriptor {
description: None,
},
],
default_value: Some("200k".to_owned()),
default_value: Some(default.to_owned()),
}
}

/// Parse a Claude context-window selection into a validated token count.
pub fn parse_context_window_tokens(value: &Value) -> Option<u64> {
let tokens = match value {
Value::Number(number) => number.as_u64()?,
Value::String(value) => {
let value = value.trim().to_ascii_lowercase();
if let Some(value) = value.strip_suffix('k') {
value.parse::<u64>().ok()?.checked_mul(1_000)?
} else if let Some(value) = value.strip_suffix('m') {
value.parse::<u64>().ok()?.checked_mul(1_000_000)?
} else {
let value = value.parse::<u64>().ok()?;
if value < 1_000 {
value.checked_mul(1_000)?
} else {
value
}
}
}
_ => return None,
};
(100_000..=1_000_000).contains(&tokens).then_some(tokens)
}

/// Return the model's native context-window size in tokens.
pub fn native_context_window(model_id: &str) -> u64 {
match model_id.strip_suffix("[1m]").unwrap_or(model_id) {
"claude-fable-5" | "claude-fable-5-1" | "claude-opus-5" | "claude-sonnet-5"
| "claude-opus-4-7" | "claude-opus-4-8" => 1_000_000,
_ => 200_000,
}
}

/// Format a context-window token count for display.
pub fn format_context_window(tokens: u64) -> String {
if tokens == 1_000_000 {
"1M".to_owned()
} else {
format!("{}k", tokens / 1_000)
}
}

/// Resolve the selected context window, falling back to the model's native size.
pub fn resolved_context_window(model_id: &str, selections: &[OptionSelection]) -> u64 {
selections
.iter()
.find(|selection| selection.id == "contextWindow")
.and_then(|selection| parse_context_window_tokens(&selection.value))
.unwrap_or_else(|| native_context_window(model_id))
}

fn boolean(id: &str, label: &str) -> OptionDescriptor {
OptionDescriptor::Boolean {
id: id.to_owned(),
Expand DownExpand Up@@ -2918,7 +2982,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2937,7 +3001,7 @@ fn built_in_models() -> Vec<ModelSpec> {
],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2957,7 +3021,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("1m"),
],
),
model(
Expand All@@ -2977,6 +3041,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"high",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2988,6 +3053,7 @@ fn built_in_models() -> Vec<ModelSpec> {
"xhigh",
),
boolean("fastMode", "Fast Mode"),
context_window("1m"),
],
),
model(
Expand All@@ -2996,7 +3062,7 @@ fn built_in_models() -> Vec<ModelSpec> {
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
boolean("fastMode", "Fast Mode"),
context_window(),
context_window("200k"),
],
),
model(
Expand All@@ -3015,15 +3081,15 @@ fn built_in_models() -> Vec<ModelSpec> {
&["low", "medium", "high", "xhigh", "max", "ultrathink"],
"high",
),
context_window(),
context_window("1m"),
],
),
model(
"claude-sonnet-4-6",
"Claude Sonnet 4.6",
vec![
reasoning(&["low", "medium", "high", "max", "ultrathink"], "high"),
context_window(),
context_window("200k"),
],
),
model(
Expand DownExpand Up@@ -3490,9 +3556,114 @@ mod tests {
assert_eq!(crate::process::parse_semver("nonsense"), None);
}

#[test]
fn parse_context_window_values() {
assert_eq!(parse_context_window_tokens(&json!("200k")), Some(200_000));
assert_eq!(parse_context_window_tokens(&json!("1m")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("1M")), Some(1_000_000));
assert_eq!(parse_context_window_tokens(&json!("500k")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500000")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!("500")), Some(500_000));
assert_eq!(parse_context_window_tokens(&json!(750_000)), Some(750_000));
assert_eq!(parse_context_window_tokens(&json!(99_999)), None);
assert_eq!(parse_context_window_tokens(&json!(1_000_001)), None);
assert_eq!(parse_context_window_tokens(&json!("99k")), None);
assert_eq!(parse_context_window_tokens(&json!("1001k")), None);
assert_eq!(parse_context_window_tokens(&json!("garbage")), None);
assert_eq!(parse_context_window_tokens(&json!(-200_000)), None);
assert_eq!(parse_context_window_tokens(&json!(null)), None);
assert_eq!(native_context_window("claude-opus-5[1m]"), 1_000_000);
assert_eq!(native_context_window("claude-sonnet-4-6[1m]"), 200_000);
assert_eq!(format_context_window(200_000), "200k");
assert_eq!(format_context_window(750_000), "750k");
assert_eq!(format_context_window(1_000_000), "1M");
}

#[test]
fn catalog_context_window_defaults_match_native_windows() {
let default = |model_id: &str| {
model_spec(model_id)
.unwrap()
.options
.into_iter()
.find_map(|option| match option {
OptionDescriptor::Select {
id, default_value, ..
} if id == "contextWindow" => default_value,
_ => None,
})
};

for model_id in [
"claude-fable-5",
"claude-fable-5-1",
"claude-opus-5",
"claude-sonnet-5",
"claude-opus-4-7",
"claude-opus-4-8",
] {
assert_eq!(default(model_id).as_deref(), Some("1m"));
}
for model_id in ["claude-sonnet-4-6", "claude-opus-4-6"] {
assert_eq!(default(model_id).as_deref(), Some("200k"));
}
assert_eq!(default("claude-haiku-4-5"), None);
assert_eq!(default("claude-opus-4-5"), None);
}

#[test]
fn context_window_launch_semantics() {
let resolve = |model, value: Option<Value>| {
let selections = value
.map(|value| {
vec![OptionSelection {
id: "contextWindow".into(),
value,
}]
})
.unwrap_or_default();
ClaudeLaunchOptions::resolve(Some(model), &selections)
};
let auto_compact = |launch: &ClaudeLaunchOptions| {
launch.settings_json.as_deref().map(|settings| {
serde_json::from_str::<Value>(settings).unwrap()["autoCompactWindow"].clone()
})
};

let launch = resolve("claude-opus-5", Some(json!("200k")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(200_000)));

let launch = resolve("claude-opus-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-opus-5", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-5"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

let launch = resolve("claude-sonnet-4-6", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert!(launch.settings_json.is_none());

let launch = resolve("claude-sonnet-4-6", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6[1m]"));
assert_eq!(auto_compact(&launch), Some(json!(500_000)));

for value in [Some(json!("200k")), None] {
let launch = resolve("claude-sonnet-4-6", value);
assert_eq!(launch.model_id.as_deref(), Some("claude-sonnet-4-6"));
assert!(launch.settings_json.is_none());
}

let launch = resolve("claude-fable-5", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert!(launch.settings_json.is_none());
}

#[test]
fn launch_options_resolve_effort_context_and_settings() {
// 1M context suffix + ultracode → effort xhigh + settings.ultracode.
// Ultracode → effort xhigh + settings.ultracode.
let launch = ClaudeLaunchOptions::resolve(
Some("claude-opus-4-8"),
&[
Expand DownExpand Up@@ -3528,7 +3699,7 @@ mod tests {
},
],
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5"));
assert_eq!(launch.effort, None);
assert!(launch.ultrathink);
assert!(launch.settings_json.is_none());
Expand Down
5 changes: 5 additions & 0 deletions crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1171,6 +1171,11 @@ pub enum AgentEvent {
/// The provider compacted its context window (Claude `system/compact_boundary`;
/// Codex `contextCompaction` item). Rendered as a "Context compacted" work-log row.
ContextCompacted,
/// A tcode-level context-window change. This is never emitted by an adapter;
/// the runtime persists it after the user message that selected the window.
ContextWindowChanged {
window: u64,
},
/// Structured plan / task list for the sidebar (Codex `turn/plan/updated`,
/// Claude `TodoWrite`). Replaces the current turn's plan wholesale.
PlanUpdated {
Expand Down
9 changes: 9 additions & 0 deletions crates/core/src/relay.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -234,6 +234,15 @@ fn render_turn(number: usize, entries: &[&TimelineEntry], timeline: &Timeline) -
EntryContent::ContextCompacted => {
activity(&mut body, "context", "provider", "compacted")
}
EntryContent::ContextWindowChanged { window } => activity(
&mut body,
"context",
"provider",
&format!(
"window set to {}",
agent::claude::format_context_window(*window)
),
),
EntryContent::ModelChanged { .. } => {}
EntryContent::Item(ItemContent::WebSearch { query }) => activity(
&mut body,
Expand Down
25 changes: 25 additions & 0 deletions crates/core/src/session.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -429,6 +429,10 @@ pub enum EntryContent {
},
/// The provider compacted its context window (a "Context compacted" work-log row).
ContextCompacted,
/// The user changed the context window for the next provider turn.
ContextWindowChanged {
window: u64,
},
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand DownExpand Up@@ -856,6 +860,16 @@ impl Timeline {
turn,
}));
}
AgentEvent::ContextWindowChanged { window } => {
let turn = self.ensure_turn(ts);
let id = self.synthetic_id("context-window");
self.entries.push(Arc::new(TimelineEntry {
id,
content: EntryContent::ContextWindowChanged { window: *window },
ts,
turn,
}));
}
// Session metadata (composer menus) — not folded into the timeline.
// Session metadata (composer menus / traits picker) — held on the
// active session, not folded into the timeline.
Expand DownExpand Up@@ -1415,6 +1429,17 @@ mod tests {
));
}

#[test]
fn context_window_change_folds_into_the_timeline() {
let timeline =
Timeline::fold_events([AgentEvent::ContextWindowChanged { window: 500_000 }]);

assert!(timeline.entries.iter().any(|entry| matches!(
entry.content,
EntryContent::ContextWindowChanged { window: 500_000 }
)));
}

#[test]
fn structured_user_input_blocks_until_resolution_or_turn_end() {
let request = AgentEvent::UserInputRequested {
Expand Down
Loading