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
1 change: 0 additions & 1 deletion crates/agent/examples/probe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@ async fn run_probe(
let opts = SessionOptions {
cwd,
model,
abort_on_model_fallback: true,
resume: None,
fork: false,
binary_path: None,
Expand Down
214 changes: 126 additions & 88 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,11 +109,7 @@ pub async fn start(opts: SessionOptions) -> Result<SessionHandle, AgentError> {
// Resolve model-scoped launch options from the persisted selections
// (effort/context/fast/thinking are launch-time only; mid-session changes
// ride the resume-restart machinery).
let launch = ClaudeLaunchOptions::resolve(
opts.model.as_deref(),
&opts.option_selections,
opts.abort_on_model_fallback,
);
let launch = ClaudeLaunchOptions::resolve(opts.model.as_deref(), &opts.option_selections);
let base_permission_mode = permission_mode_flag(opts.approval_mode);
let launch_permission_mode = initial_permission_mode(opts.approval_mode, opts.interaction_mode);
// Launch arguments are deliberately appended last, so the tracker must
Expand DownExpand Up@@ -317,25 +313,7 @@ struct ClaudeLaunchOptions {
ultrathink: bool,
}

fn fallback_guard_models(model: &str) -> Vec<String> {
let base = model.split('[').next().unwrap_or(model);
let primary = if base.contains("fable") {
"fable"
} else {
base
};
let mut allow = vec![primary.to_string()];
for extra in ["sonnet", "haiku"] {
if !allow.iter().any(|m| m == extra) {
allow.push(extra.to_string());
}
}
allow
}

fn launch_settings_json(
model: Option<&str>,
abort_on_model_fallback: bool,
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
Expand All@@ -350,23 +328,12 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if abort_on_model_fallback && let Some(model) = model {
settings.insert(
"availableModels".into(),
json!(fallback_guard_models(model)),
);
settings.insert("switchModelsOnFlag".into(), json!(false));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}

impl ClaudeLaunchOptions {
fn resolve(
model: Option<&str>,
selections: &[OptionSelection],
abort_on_model_fallback: bool,
) -> Self {
fn resolve(model: Option<&str>, selections: &[OptionSelection]) -> Self {
let spec = model.and_then(model_spec);
let raw_effort = selection_str(selections, "reasoningEffort");
let resolved_effort = resolve_claude_effort(spec.as_ref(), raw_effort.as_deref());
Expand DownExpand Up@@ -399,13 +366,7 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(
model,
abort_on_model_fallback,
thinking,
fast_mode,
ultracode,
);
let settings_json = launch_settings_json(thinking, fast_mode, ultracode);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -1025,6 +986,13 @@ struct PendingRewind {
conversation: bool,
}

fn served_model_is_fallback(expected: &str, served: &str) -> bool {
(expected.contains("fable") && served.contains("opus"))
|| (served.contains("opus-4-8")
&& expected.contains("opus")
&& !expected.contains("opus-4-8"))
}

pub(crate) struct Mapper {
session_started: bool,
current_message_id: Option<String>,
Expand DownExpand Up@@ -1095,6 +1063,8 @@ pub(crate) struct Mapper {
last_served_model: Option<String>,
/// Model selected for this session, used when Claude reports a synthetic refusal message.
expected_model: Option<String>,
/// Whether a served-model mismatch was already reported for the active turn.
fallback_detected: bool,
/// Latest structured stop reason for the active turn.
stop_reason: Option<String>,
/// Classifier category captured from the active turn's structured refusal details.
Expand DownExpand Up@@ -1158,6 +1128,7 @@ impl Mapper {
native_rewind,
last_served_model: None,
expected_model,
fallback_detected: false,
stop_reason: None,
pending_refusal_category: None,
warned_stop_reason: None,
Expand All@@ -1180,6 +1151,7 @@ impl Mapper {
self.current_turn_id = Some(id.clone());
self.awaiting_turn_checkpoint = self.native_rewind;
self.exit_plan_captured = false;
self.fallback_detected = false;
self.stop_reason = None;
self.pending_refusal_category = None;
self.warned_stop_reason = None;
Expand DownExpand Up@@ -1464,14 +1436,15 @@ impl Mapper {
events
}

fn on_model_refusal_fallback(&self, msg: &Value) -> Vec<AgentEvent> {
fn on_model_refusal_fallback(&mut self, msg: &Value) -> Vec<AgentEvent> {
let (Some(expected), Some(actual)) = (
msg.get("original_model").and_then(Value::as_str),
msg.get("fallback_model").and_then(Value::as_str),
) else {
log::debug!("claude: ignoring malformed model_refusal_fallback");
return Vec::new();
};
self.fallback_detected = true;
vec![AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: actual.to_owned(),
Expand DownExpand Up@@ -1755,14 +1728,41 @@ impl Mapper {
.and_then(Value::as_str)
.map(ClassifierCategory::parse);
}
if let Some(model) = message.get("model").and_then(Value::as_str)
&& self.last_served_model.as_deref() != Some(model)
{
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
if let Some(model) = message.get("model").and_then(Value::as_str) {
if !self.fallback_detected
&& let Some(expected) = self.expected_model.as_deref()
{
let normalized_expected = expected
.split('[')
.next()
.unwrap_or(expected)
.to_ascii_lowercase();
let normalized_served = model
.split('[')
.next()
.unwrap_or(model)
.to_ascii_lowercase();
if served_model_is_fallback(&normalized_expected, &normalized_served) {
self.fallback_detected = true;
out.push(AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: model.to_owned(),
category: None,
checkpoint_id: None,
parent_tool_use_id: msg
.get("parent_tool_use_id")
.and_then(Value::as_str)
.map(str::to_owned),
});
}
}
if self.last_served_model.as_deref() != Some(model) {
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
}
}
out.extend(self.observe_stop_reason(message.get("stop_reason").and_then(Value::as_str)));
let msg_id = message
Expand DownExpand Up@@ -3149,6 +3149,81 @@ mod tests {
);
}

#[test]
fn served_model_fallback_family_rule() {
let cases = [
("claude-fable-5", "claude-opus-4-8", true),
("claude-fable-5", "claude-opus-5", true),
("claude-opus-5", "claude-opus-4-8", true),
("claude-opus-4-8", "claude-opus-4-8", false),
("claude-fable-5", "claude-fable-5", false),
("claude-fable-5", "claude-sonnet-4-5", false),
("claude-fable-5", "claude-haiku-4-5", false),
("anything", "<synthetic>", false),
];
for (expected, served, is_fallback) in cases {
assert_eq!(
served_model_is_fallback(expected, served),
is_fallback,
"expected={expected}, served={served}"
);
}

let expected = "claude-opus-5[1m]";
let normalized_expected = expected.split('[').next().unwrap_or(expected);
assert!(served_model_is_fallback(
normalized_expected,
"claude-opus-4-8"
));
}

#[test]
fn assistant_model_mismatch_emits_one_fallback_per_turn() {
let mut mapper = Mapper::new_configured(
false,
InteractionMode::Build,
"default",
"default".into(),
ApprovalMode::Supervised,
false,
Some("claude-fable-5".into()),
);
mapper.start_turn();

let first = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-1","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert_eq!(
first
.iter()
.filter(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
.count(),
1
);
assert!(first.iter().any(|event| matches!(
event,
AgentEvent::ModelFallbackDetected {
expected,
actual,
category: None,
checkpoint_id: None,
parent_tool_use_id: None,
} if expected == "claude-fable-5"
&& actual == "claude-opus-4-8"
)));

let second = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-2","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert!(
!second
.iter()
.any(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
);
}

#[test]
fn classifier_refusal_result_emits_turn_blocked() {
let mut mapper = Mapper::new_configured(
Expand DownExpand Up@@ -3403,7 +3478,6 @@ mod tests {
value: json!(true),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-4-8"));
assert_eq!(launch.effort.as_deref(), Some("xhigh"));
Expand All@@ -3426,7 +3500,6 @@ mod tests {
value: json!("1m"),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.effort, None);
Expand All@@ -3440,47 +3513,12 @@ mod tests {
id: "thinking".into(),
value: json!(true),
}],
false,
);
let settings: Value =
serde_json::from_str(launch.settings_json.as_deref().unwrap()).unwrap();
assert_eq!(settings["alwaysThinkingEnabled"], true);
}

#[test]
fn fallback_guard_settings_merge_with_launch_settings() {
let parse = |model, thinking, fast_mode, ultracode| -> Value {
serde_json::from_str(
launch_settings_json(Some(model), true, thinking, fast_mode, ultracode)
.as_deref()
.unwrap(),
)
.unwrap()
};

let fable = parse("claude-fable-5", Some(true), true, true);
assert_eq!(
fable["availableModels"],
json!(["fable", "sonnet", "haiku"])
);
assert_eq!(fable["switchModelsOnFlag"], false);
assert_eq!(fable["alwaysThinkingEnabled"], true);
assert_eq!(fable["fastMode"], true);
assert_eq!(fable["ultracode"], true);

let opus = parse("claude-opus-5", None, false, false);
assert_eq!(
opus["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);

let opus_1m = parse("claude-opus-5[1m]", None, false, false);
assert_eq!(
opus_1m["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);
}

#[test]
fn todo_write_maps_to_plan_updated() {
let mut m = Mapper::new();
Expand Down
1 change: 0 additions & 1 deletion crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -393,7 +393,6 @@ pub struct SessionOptions {
pub cwd: PathBuf,
/// Provider-native model id; `None` = provider default.
pub model: Option<String>,
pub abort_on_model_fallback: bool,
pub resume: Option<ResumeCursor>,
/// Fork the resumed provider session instead of continuing it in place.
/// This is meaningful only when `resume` is present.
Expand Down
3 changes: 2 additions & 1 deletion crates/runtime/src/app/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,10 +344,11 @@ impl AppState {
.filter(|active| active.meta.id == session_id)
.is_some_and(|active| {
active.queue.clear();
active.timeline.mark_idle();
active.shutdown_to_idle();
true
});
if is_active {
self.interrupt(cx);
self.emit_domain(
Topic::SessionStatus {
session_id: session_id.to_owned(),
Expand Down
1 change: 0 additions & 1 deletion crates/runtime/src/app/providers.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -779,7 +779,6 @@ pub(super) fn session_options(
SessionOptions {
cwd: meta.cwd.clone(),
model: meta.model.clone(),
abort_on_model_fallback: settings.abort_on_model_fallback,
resume: meta.resume_cursor.clone(),
fork: meta.pending_fork,
binary_path: provider_settings.binary_path.clone(),
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
1 change: 0 additions & 1 deletion crates/agent/examples/probe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@ async fn run_probe(
let opts = SessionOptions {
cwd,
model,
abort_on_model_fallback: true,
resume: None,
fork: false,
binary_path: None,
Expand Down
214 changes: 126 additions & 88 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,11 +109,7 @@ pub async fn start(opts: SessionOptions) -> Result<SessionHandle, AgentError> {
// Resolve model-scoped launch options from the persisted selections
// (effort/context/fast/thinking are launch-time only; mid-session changes
// ride the resume-restart machinery).
let launch = ClaudeLaunchOptions::resolve(
opts.model.as_deref(),
&opts.option_selections,
opts.abort_on_model_fallback,
);
let launch = ClaudeLaunchOptions::resolve(opts.model.as_deref(), &opts.option_selections);
let base_permission_mode = permission_mode_flag(opts.approval_mode);
let launch_permission_mode = initial_permission_mode(opts.approval_mode, opts.interaction_mode);
// Launch arguments are deliberately appended last, so the tracker must
Expand DownExpand Up@@ -317,25 +313,7 @@ struct ClaudeLaunchOptions {
ultrathink: bool,
}

fn fallback_guard_models(model: &str) -> Vec<String> {
let base = model.split('[').next().unwrap_or(model);
let primary = if base.contains("fable") {
"fable"
} else {
base
};
let mut allow = vec![primary.to_string()];
for extra in ["sonnet", "haiku"] {
if !allow.iter().any(|m| m == extra) {
allow.push(extra.to_string());
}
}
allow
}

fn launch_settings_json(
model: Option<&str>,
abort_on_model_fallback: bool,
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
Expand All@@ -350,23 +328,12 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if abort_on_model_fallback && let Some(model) = model {
settings.insert(
"availableModels".into(),
json!(fallback_guard_models(model)),
);
settings.insert("switchModelsOnFlag".into(), json!(false));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}

impl ClaudeLaunchOptions {
fn resolve(
model: Option<&str>,
selections: &[OptionSelection],
abort_on_model_fallback: bool,
) -> Self {
fn resolve(model: Option<&str>, selections: &[OptionSelection]) -> Self {
let spec = model.and_then(model_spec);
let raw_effort = selection_str(selections, "reasoningEffort");
let resolved_effort = resolve_claude_effort(spec.as_ref(), raw_effort.as_deref());
Expand DownExpand Up@@ -399,13 +366,7 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(
model,
abort_on_model_fallback,
thinking,
fast_mode,
ultracode,
);
let settings_json = launch_settings_json(thinking, fast_mode, ultracode);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -1025,6 +986,13 @@ struct PendingRewind {
conversation: bool,
}

fn served_model_is_fallback(expected: &str, served: &str) -> bool {
(expected.contains("fable") && served.contains("opus"))
|| (served.contains("opus-4-8")
&& expected.contains("opus")
&& !expected.contains("opus-4-8"))
}

pub(crate) struct Mapper {
session_started: bool,
current_message_id: Option<String>,
Expand DownExpand Up@@ -1095,6 +1063,8 @@ pub(crate) struct Mapper {
last_served_model: Option<String>,
/// Model selected for this session, used when Claude reports a synthetic refusal message.
expected_model: Option<String>,
/// Whether a served-model mismatch was already reported for the active turn.
fallback_detected: bool,
/// Latest structured stop reason for the active turn.
stop_reason: Option<String>,
/// Classifier category captured from the active turn's structured refusal details.
Expand DownExpand Up@@ -1158,6 +1128,7 @@ impl Mapper {
native_rewind,
last_served_model: None,
expected_model,
fallback_detected: false,
stop_reason: None,
pending_refusal_category: None,
warned_stop_reason: None,
Expand All@@ -1180,6 +1151,7 @@ impl Mapper {
self.current_turn_id = Some(id.clone());
self.awaiting_turn_checkpoint = self.native_rewind;
self.exit_plan_captured = false;
self.fallback_detected = false;
self.stop_reason = None;
self.pending_refusal_category = None;
self.warned_stop_reason = None;
Expand DownExpand Up@@ -1464,14 +1436,15 @@ impl Mapper {
events
}

fn on_model_refusal_fallback(&self, msg: &Value) -> Vec<AgentEvent> {
fn on_model_refusal_fallback(&mut self, msg: &Value) -> Vec<AgentEvent> {
let (Some(expected), Some(actual)) = (
msg.get("original_model").and_then(Value::as_str),
msg.get("fallback_model").and_then(Value::as_str),
) else {
log::debug!("claude: ignoring malformed model_refusal_fallback");
return Vec::new();
};
self.fallback_detected = true;
vec![AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: actual.to_owned(),
Expand DownExpand Up@@ -1755,14 +1728,41 @@ impl Mapper {
.and_then(Value::as_str)
.map(ClassifierCategory::parse);
}
if let Some(model) = message.get("model").and_then(Value::as_str)
&& self.last_served_model.as_deref() != Some(model)
{
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
if let Some(model) = message.get("model").and_then(Value::as_str) {
if !self.fallback_detected
&& let Some(expected) = self.expected_model.as_deref()
{
let normalized_expected = expected
.split('[')
.next()
.unwrap_or(expected)
.to_ascii_lowercase();
let normalized_served = model
.split('[')
.next()
.unwrap_or(model)
.to_ascii_lowercase();
if served_model_is_fallback(&normalized_expected, &normalized_served) {
self.fallback_detected = true;
out.push(AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: model.to_owned(),
category: None,
checkpoint_id: None,
parent_tool_use_id: msg
.get("parent_tool_use_id")
.and_then(Value::as_str)
.map(str::to_owned),
});
}
}
if self.last_served_model.as_deref() != Some(model) {
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
}
}
out.extend(self.observe_stop_reason(message.get("stop_reason").and_then(Value::as_str)));
let msg_id = message
Expand DownExpand Up@@ -3149,6 +3149,81 @@ mod tests {
);
}

#[test]
fn served_model_fallback_family_rule() {
let cases = [
("claude-fable-5", "claude-opus-4-8", true),
("claude-fable-5", "claude-opus-5", true),
("claude-opus-5", "claude-opus-4-8", true),
("claude-opus-4-8", "claude-opus-4-8", false),
("claude-fable-5", "claude-fable-5", false),
("claude-fable-5", "claude-sonnet-4-5", false),
("claude-fable-5", "claude-haiku-4-5", false),
("anything", "<synthetic>", false),
];
for (expected, served, is_fallback) in cases {
assert_eq!(
served_model_is_fallback(expected, served),
is_fallback,
"expected={expected}, served={served}"
);
}

let expected = "claude-opus-5[1m]";
let normalized_expected = expected.split('[').next().unwrap_or(expected);
assert!(served_model_is_fallback(
normalized_expected,
"claude-opus-4-8"
));
}

#[test]
fn assistant_model_mismatch_emits_one_fallback_per_turn() {
let mut mapper = Mapper::new_configured(
false,
InteractionMode::Build,
"default",
"default".into(),
ApprovalMode::Supervised,
false,
Some("claude-fable-5".into()),
);
mapper.start_turn();

let first = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-1","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert_eq!(
first
.iter()
.filter(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
.count(),
1
);
assert!(first.iter().any(|event| matches!(
event,
AgentEvent::ModelFallbackDetected {
expected,
actual,
category: None,
checkpoint_id: None,
parent_tool_use_id: None,
} if expected == "claude-fable-5"
&& actual == "claude-opus-4-8"
)));

let second = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-2","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert!(
!second
.iter()
.any(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
);
}

#[test]
fn classifier_refusal_result_emits_turn_blocked() {
let mut mapper = Mapper::new_configured(
Expand DownExpand Up@@ -3403,7 +3478,6 @@ mod tests {
value: json!(true),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-4-8"));
assert_eq!(launch.effort.as_deref(), Some("xhigh"));
Expand All@@ -3426,7 +3500,6 @@ mod tests {
value: json!("1m"),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.effort, None);
Expand All@@ -3440,47 +3513,12 @@ mod tests {
id: "thinking".into(),
value: json!(true),
}],
false,
);
let settings: Value =
serde_json::from_str(launch.settings_json.as_deref().unwrap()).unwrap();
assert_eq!(settings["alwaysThinkingEnabled"], true);
}

#[test]
fn fallback_guard_settings_merge_with_launch_settings() {
let parse = |model, thinking, fast_mode, ultracode| -> Value {
serde_json::from_str(
launch_settings_json(Some(model), true, thinking, fast_mode, ultracode)
.as_deref()
.unwrap(),
)
.unwrap()
};

let fable = parse("claude-fable-5", Some(true), true, true);
assert_eq!(
fable["availableModels"],
json!(["fable", "sonnet", "haiku"])
);
assert_eq!(fable["switchModelsOnFlag"], false);
assert_eq!(fable["alwaysThinkingEnabled"], true);
assert_eq!(fable["fastMode"], true);
assert_eq!(fable["ultracode"], true);

let opus = parse("claude-opus-5", None, false, false);
assert_eq!(
opus["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);

let opus_1m = parse("claude-opus-5[1m]", None, false, false);
assert_eq!(
opus_1m["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);
}

#[test]
fn todo_write_maps_to_plan_updated() {
let mut m = Mapper::new();
Expand Down
1 change: 0 additions & 1 deletion crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -393,7 +393,6 @@ pub struct SessionOptions {
pub cwd: PathBuf,
/// Provider-native model id; `None` = provider default.
pub model: Option<String>,
pub abort_on_model_fallback: bool,
pub resume: Option<ResumeCursor>,
/// Fork the resumed provider session instead of continuing it in place.
/// This is meaningful only when `resume` is present.
Expand Down
3 changes: 2 additions & 1 deletion crates/runtime/src/app/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,10 +344,11 @@ impl AppState {
.filter(|active| active.meta.id == session_id)
.is_some_and(|active| {
active.queue.clear();
active.timeline.mark_idle();
active.shutdown_to_idle();
true
});
if is_active {
self.interrupt(cx);
self.emit_domain(
Topic::SessionStatus {
session_id: session_id.to_owned(),
Expand Down
1 change: 0 additions & 1 deletion crates/runtime/src/app/providers.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -779,7 +779,6 @@ pub(super) fn session_options(
SessionOptions {
cwd: meta.cwd.clone(),
model: meta.model.clone(),
abort_on_model_fallback: settings.abort_on_model_fallback,
resume: meta.resume_cursor.clone(),
fork: meta.pending_fork,
binary_path: provider_settings.binary_path.clone(),
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
1 change: 0 additions & 1 deletion crates/agent/examples/probe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@ async fn run_probe(
let opts = SessionOptions {
cwd,
model,
abort_on_model_fallback: true,
resume: None,
fork: false,
binary_path: None,
Expand Down
214 changes: 126 additions & 88 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,11 +109,7 @@ pub async fn start(opts: SessionOptions) -> Result<SessionHandle, AgentError> {
// Resolve model-scoped launch options from the persisted selections
// (effort/context/fast/thinking are launch-time only; mid-session changes
// ride the resume-restart machinery).
let launch = ClaudeLaunchOptions::resolve(
opts.model.as_deref(),
&opts.option_selections,
opts.abort_on_model_fallback,
);
let launch = ClaudeLaunchOptions::resolve(opts.model.as_deref(), &opts.option_selections);
let base_permission_mode = permission_mode_flag(opts.approval_mode);
let launch_permission_mode = initial_permission_mode(opts.approval_mode, opts.interaction_mode);
// Launch arguments are deliberately appended last, so the tracker must
Expand DownExpand Up@@ -317,25 +313,7 @@ struct ClaudeLaunchOptions {
ultrathink: bool,
}

fn fallback_guard_models(model: &str) -> Vec<String> {
let base = model.split('[').next().unwrap_or(model);
let primary = if base.contains("fable") {
"fable"
} else {
base
};
let mut allow = vec![primary.to_string()];
for extra in ["sonnet", "haiku"] {
if !allow.iter().any(|m| m == extra) {
allow.push(extra.to_string());
}
}
allow
}

fn launch_settings_json(
model: Option<&str>,
abort_on_model_fallback: bool,
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
Expand All@@ -350,23 +328,12 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if abort_on_model_fallback && let Some(model) = model {
settings.insert(
"availableModels".into(),
json!(fallback_guard_models(model)),
);
settings.insert("switchModelsOnFlag".into(), json!(false));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}

impl ClaudeLaunchOptions {
fn resolve(
model: Option<&str>,
selections: &[OptionSelection],
abort_on_model_fallback: bool,
) -> Self {
fn resolve(model: Option<&str>, selections: &[OptionSelection]) -> Self {
let spec = model.and_then(model_spec);
let raw_effort = selection_str(selections, "reasoningEffort");
let resolved_effort = resolve_claude_effort(spec.as_ref(), raw_effort.as_deref());
Expand DownExpand Up@@ -399,13 +366,7 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(
model,
abort_on_model_fallback,
thinking,
fast_mode,
ultracode,
);
let settings_json = launch_settings_json(thinking, fast_mode, ultracode);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -1025,6 +986,13 @@ struct PendingRewind {
conversation: bool,
}

fn served_model_is_fallback(expected: &str, served: &str) -> bool {
(expected.contains("fable") && served.contains("opus"))
|| (served.contains("opus-4-8")
&& expected.contains("opus")
&& !expected.contains("opus-4-8"))
}

pub(crate) struct Mapper {
session_started: bool,
current_message_id: Option<String>,
Expand DownExpand Up@@ -1095,6 +1063,8 @@ pub(crate) struct Mapper {
last_served_model: Option<String>,
/// Model selected for this session, used when Claude reports a synthetic refusal message.
expected_model: Option<String>,
/// Whether a served-model mismatch was already reported for the active turn.
fallback_detected: bool,
/// Latest structured stop reason for the active turn.
stop_reason: Option<String>,
/// Classifier category captured from the active turn's structured refusal details.
Expand DownExpand Up@@ -1158,6 +1128,7 @@ impl Mapper {
native_rewind,
last_served_model: None,
expected_model,
fallback_detected: false,
stop_reason: None,
pending_refusal_category: None,
warned_stop_reason: None,
Expand All@@ -1180,6 +1151,7 @@ impl Mapper {
self.current_turn_id = Some(id.clone());
self.awaiting_turn_checkpoint = self.native_rewind;
self.exit_plan_captured = false;
self.fallback_detected = false;
self.stop_reason = None;
self.pending_refusal_category = None;
self.warned_stop_reason = None;
Expand DownExpand Up@@ -1464,14 +1436,15 @@ impl Mapper {
events
}

fn on_model_refusal_fallback(&self, msg: &Value) -> Vec<AgentEvent> {
fn on_model_refusal_fallback(&mut self, msg: &Value) -> Vec<AgentEvent> {
let (Some(expected), Some(actual)) = (
msg.get("original_model").and_then(Value::as_str),
msg.get("fallback_model").and_then(Value::as_str),
) else {
log::debug!("claude: ignoring malformed model_refusal_fallback");
return Vec::new();
};
self.fallback_detected = true;
vec![AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: actual.to_owned(),
Expand DownExpand Up@@ -1755,14 +1728,41 @@ impl Mapper {
.and_then(Value::as_str)
.map(ClassifierCategory::parse);
}
if let Some(model) = message.get("model").and_then(Value::as_str)
&& self.last_served_model.as_deref() != Some(model)
{
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
if let Some(model) = message.get("model").and_then(Value::as_str) {
if !self.fallback_detected
&& let Some(expected) = self.expected_model.as_deref()
{
let normalized_expected = expected
.split('[')
.next()
.unwrap_or(expected)
.to_ascii_lowercase();
let normalized_served = model
.split('[')
.next()
.unwrap_or(model)
.to_ascii_lowercase();
if served_model_is_fallback(&normalized_expected, &normalized_served) {
self.fallback_detected = true;
out.push(AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: model.to_owned(),
category: None,
checkpoint_id: None,
parent_tool_use_id: msg
.get("parent_tool_use_id")
.and_then(Value::as_str)
.map(str::to_owned),
});
}
}
if self.last_served_model.as_deref() != Some(model) {
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
}
}
out.extend(self.observe_stop_reason(message.get("stop_reason").and_then(Value::as_str)));
let msg_id = message
Expand DownExpand Up@@ -3149,6 +3149,81 @@ mod tests {
);
}

#[test]
fn served_model_fallback_family_rule() {
let cases = [
("claude-fable-5", "claude-opus-4-8", true),
("claude-fable-5", "claude-opus-5", true),
("claude-opus-5", "claude-opus-4-8", true),
("claude-opus-4-8", "claude-opus-4-8", false),
("claude-fable-5", "claude-fable-5", false),
("claude-fable-5", "claude-sonnet-4-5", false),
("claude-fable-5", "claude-haiku-4-5", false),
("anything", "<synthetic>", false),
];
for (expected, served, is_fallback) in cases {
assert_eq!(
served_model_is_fallback(expected, served),
is_fallback,
"expected={expected}, served={served}"
);
}

let expected = "claude-opus-5[1m]";
let normalized_expected = expected.split('[').next().unwrap_or(expected);
assert!(served_model_is_fallback(
normalized_expected,
"claude-opus-4-8"
));
}

#[test]
fn assistant_model_mismatch_emits_one_fallback_per_turn() {
let mut mapper = Mapper::new_configured(
false,
InteractionMode::Build,
"default",
"default".into(),
ApprovalMode::Supervised,
false,
Some("claude-fable-5".into()),
);
mapper.start_turn();

let first = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-1","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert_eq!(
first
.iter()
.filter(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
.count(),
1
);
assert!(first.iter().any(|event| matches!(
event,
AgentEvent::ModelFallbackDetected {
expected,
actual,
category: None,
checkpoint_id: None,
parent_tool_use_id: None,
} if expected == "claude-fable-5"
&& actual == "claude-opus-4-8"
)));

let second = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-2","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert!(
!second
.iter()
.any(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
);
}

#[test]
fn classifier_refusal_result_emits_turn_blocked() {
let mut mapper = Mapper::new_configured(
Expand DownExpand Up@@ -3403,7 +3478,6 @@ mod tests {
value: json!(true),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-4-8"));
assert_eq!(launch.effort.as_deref(), Some("xhigh"));
Expand All@@ -3426,7 +3500,6 @@ mod tests {
value: json!("1m"),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.effort, None);
Expand All@@ -3440,47 +3513,12 @@ mod tests {
id: "thinking".into(),
value: json!(true),
}],
false,
);
let settings: Value =
serde_json::from_str(launch.settings_json.as_deref().unwrap()).unwrap();
assert_eq!(settings["alwaysThinkingEnabled"], true);
}

#[test]
fn fallback_guard_settings_merge_with_launch_settings() {
let parse = |model, thinking, fast_mode, ultracode| -> Value {
serde_json::from_str(
launch_settings_json(Some(model), true, thinking, fast_mode, ultracode)
.as_deref()
.unwrap(),
)
.unwrap()
};

let fable = parse("claude-fable-5", Some(true), true, true);
assert_eq!(
fable["availableModels"],
json!(["fable", "sonnet", "haiku"])
);
assert_eq!(fable["switchModelsOnFlag"], false);
assert_eq!(fable["alwaysThinkingEnabled"], true);
assert_eq!(fable["fastMode"], true);
assert_eq!(fable["ultracode"], true);

let opus = parse("claude-opus-5", None, false, false);
assert_eq!(
opus["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);

let opus_1m = parse("claude-opus-5[1m]", None, false, false);
assert_eq!(
opus_1m["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);
}

#[test]
fn todo_write_maps_to_plan_updated() {
let mut m = Mapper::new();
Expand Down
1 change: 0 additions & 1 deletion crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -393,7 +393,6 @@ pub struct SessionOptions {
pub cwd: PathBuf,
/// Provider-native model id; `None` = provider default.
pub model: Option<String>,
pub abort_on_model_fallback: bool,
pub resume: Option<ResumeCursor>,
/// Fork the resumed provider session instead of continuing it in place.
/// This is meaningful only when `resume` is present.
Expand Down
3 changes: 2 additions & 1 deletion crates/runtime/src/app/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,10 +344,11 @@ impl AppState {
.filter(|active| active.meta.id == session_id)
.is_some_and(|active| {
active.queue.clear();
active.timeline.mark_idle();
active.shutdown_to_idle();
true
});
if is_active {
self.interrupt(cx);
self.emit_domain(
Topic::SessionStatus {
session_id: session_id.to_owned(),
Expand Down
1 change: 0 additions & 1 deletion crates/runtime/src/app/providers.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -779,7 +779,6 @@ pub(super) fn session_options(
SessionOptions {
cwd: meta.cwd.clone(),
model: meta.model.clone(),
abort_on_model_fallback: settings.abort_on_model_fallback,
resume: meta.resume_cursor.clone(),
fork: meta.pending_fork,
binary_path: provider_settings.binary_path.clone(),
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
1 change: 0 additions & 1 deletion crates/agent/examples/probe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@ async fn run_probe(
let opts = SessionOptions {
cwd,
model,
abort_on_model_fallback: true,
resume: None,
fork: false,
binary_path: None,
Expand Down
214 changes: 126 additions & 88 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,11 +109,7 @@ pub async fn start(opts: SessionOptions) -> Result<SessionHandle, AgentError> {
// Resolve model-scoped launch options from the persisted selections
// (effort/context/fast/thinking are launch-time only; mid-session changes
// ride the resume-restart machinery).
let launch = ClaudeLaunchOptions::resolve(
opts.model.as_deref(),
&opts.option_selections,
opts.abort_on_model_fallback,
);
let launch = ClaudeLaunchOptions::resolve(opts.model.as_deref(), &opts.option_selections);
let base_permission_mode = permission_mode_flag(opts.approval_mode);
let launch_permission_mode = initial_permission_mode(opts.approval_mode, opts.interaction_mode);
// Launch arguments are deliberately appended last, so the tracker must
Expand DownExpand Up@@ -317,25 +313,7 @@ struct ClaudeLaunchOptions {
ultrathink: bool,
}

fn fallback_guard_models(model: &str) -> Vec<String> {
let base = model.split('[').next().unwrap_or(model);
let primary = if base.contains("fable") {
"fable"
} else {
base
};
let mut allow = vec![primary.to_string()];
for extra in ["sonnet", "haiku"] {
if !allow.iter().any(|m| m == extra) {
allow.push(extra.to_string());
}
}
allow
}

fn launch_settings_json(
model: Option<&str>,
abort_on_model_fallback: bool,
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
Expand All@@ -350,23 +328,12 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if abort_on_model_fallback && let Some(model) = model {
settings.insert(
"availableModels".into(),
json!(fallback_guard_models(model)),
);
settings.insert("switchModelsOnFlag".into(), json!(false));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}

impl ClaudeLaunchOptions {
fn resolve(
model: Option<&str>,
selections: &[OptionSelection],
abort_on_model_fallback: bool,
) -> Self {
fn resolve(model: Option<&str>, selections: &[OptionSelection]) -> Self {
let spec = model.and_then(model_spec);
let raw_effort = selection_str(selections, "reasoningEffort");
let resolved_effort = resolve_claude_effort(spec.as_ref(), raw_effort.as_deref());
Expand DownExpand Up@@ -399,13 +366,7 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(
model,
abort_on_model_fallback,
thinking,
fast_mode,
ultracode,
);
let settings_json = launch_settings_json(thinking, fast_mode, ultracode);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -1025,6 +986,13 @@ struct PendingRewind {
conversation: bool,
}

fn served_model_is_fallback(expected: &str, served: &str) -> bool {
(expected.contains("fable") && served.contains("opus"))
|| (served.contains("opus-4-8")
&& expected.contains("opus")
&& !expected.contains("opus-4-8"))
}

pub(crate) struct Mapper {
session_started: bool,
current_message_id: Option<String>,
Expand DownExpand Up@@ -1095,6 +1063,8 @@ pub(crate) struct Mapper {
last_served_model: Option<String>,
/// Model selected for this session, used when Claude reports a synthetic refusal message.
expected_model: Option<String>,
/// Whether a served-model mismatch was already reported for the active turn.
fallback_detected: bool,
/// Latest structured stop reason for the active turn.
stop_reason: Option<String>,
/// Classifier category captured from the active turn's structured refusal details.
Expand DownExpand Up@@ -1158,6 +1128,7 @@ impl Mapper {
native_rewind,
last_served_model: None,
expected_model,
fallback_detected: false,
stop_reason: None,
pending_refusal_category: None,
warned_stop_reason: None,
Expand All@@ -1180,6 +1151,7 @@ impl Mapper {
self.current_turn_id = Some(id.clone());
self.awaiting_turn_checkpoint = self.native_rewind;
self.exit_plan_captured = false;
self.fallback_detected = false;
self.stop_reason = None;
self.pending_refusal_category = None;
self.warned_stop_reason = None;
Expand DownExpand Up@@ -1464,14 +1436,15 @@ impl Mapper {
events
}

fn on_model_refusal_fallback(&self, msg: &Value) -> Vec<AgentEvent> {
fn on_model_refusal_fallback(&mut self, msg: &Value) -> Vec<AgentEvent> {
let (Some(expected), Some(actual)) = (
msg.get("original_model").and_then(Value::as_str),
msg.get("fallback_model").and_then(Value::as_str),
) else {
log::debug!("claude: ignoring malformed model_refusal_fallback");
return Vec::new();
};
self.fallback_detected = true;
vec![AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: actual.to_owned(),
Expand DownExpand Up@@ -1755,14 +1728,41 @@ impl Mapper {
.and_then(Value::as_str)
.map(ClassifierCategory::parse);
}
if let Some(model) = message.get("model").and_then(Value::as_str)
&& self.last_served_model.as_deref() != Some(model)
{
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
if let Some(model) = message.get("model").and_then(Value::as_str) {
if !self.fallback_detected
&& let Some(expected) = self.expected_model.as_deref()
{
let normalized_expected = expected
.split('[')
.next()
.unwrap_or(expected)
.to_ascii_lowercase();
let normalized_served = model
.split('[')
.next()
.unwrap_or(model)
.to_ascii_lowercase();
if served_model_is_fallback(&normalized_expected, &normalized_served) {
self.fallback_detected = true;
out.push(AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: model.to_owned(),
category: None,
checkpoint_id: None,
parent_tool_use_id: msg
.get("parent_tool_use_id")
.and_then(Value::as_str)
.map(str::to_owned),
});
}
}
if self.last_served_model.as_deref() != Some(model) {
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
}
}
out.extend(self.observe_stop_reason(message.get("stop_reason").and_then(Value::as_str)));
let msg_id = message
Expand DownExpand Up@@ -3149,6 +3149,81 @@ mod tests {
);
}

#[test]
fn served_model_fallback_family_rule() {
let cases = [
("claude-fable-5", "claude-opus-4-8", true),
("claude-fable-5", "claude-opus-5", true),
("claude-opus-5", "claude-opus-4-8", true),
("claude-opus-4-8", "claude-opus-4-8", false),
("claude-fable-5", "claude-fable-5", false),
("claude-fable-5", "claude-sonnet-4-5", false),
("claude-fable-5", "claude-haiku-4-5", false),
("anything", "<synthetic>", false),
];
for (expected, served, is_fallback) in cases {
assert_eq!(
served_model_is_fallback(expected, served),
is_fallback,
"expected={expected}, served={served}"
);
}

let expected = "claude-opus-5[1m]";
let normalized_expected = expected.split('[').next().unwrap_or(expected);
assert!(served_model_is_fallback(
normalized_expected,
"claude-opus-4-8"
));
}

#[test]
fn assistant_model_mismatch_emits_one_fallback_per_turn() {
let mut mapper = Mapper::new_configured(
false,
InteractionMode::Build,
"default",
"default".into(),
ApprovalMode::Supervised,
false,
Some("claude-fable-5".into()),
);
mapper.start_turn();

let first = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-1","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert_eq!(
first
.iter()
.filter(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
.count(),
1
);
assert!(first.iter().any(|event| matches!(
event,
AgentEvent::ModelFallbackDetected {
expected,
actual,
category: None,
checkpoint_id: None,
parent_tool_use_id: None,
} if expected == "claude-fable-5"
&& actual == "claude-opus-4-8"
)));

let second = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-2","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert!(
!second
.iter()
.any(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
);
}

#[test]
fn classifier_refusal_result_emits_turn_blocked() {
let mut mapper = Mapper::new_configured(
Expand DownExpand Up@@ -3403,7 +3478,6 @@ mod tests {
value: json!(true),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-4-8"));
assert_eq!(launch.effort.as_deref(), Some("xhigh"));
Expand All@@ -3426,7 +3500,6 @@ mod tests {
value: json!("1m"),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.effort, None);
Expand All@@ -3440,47 +3513,12 @@ mod tests {
id: "thinking".into(),
value: json!(true),
}],
false,
);
let settings: Value =
serde_json::from_str(launch.settings_json.as_deref().unwrap()).unwrap();
assert_eq!(settings["alwaysThinkingEnabled"], true);
}

#[test]
fn fallback_guard_settings_merge_with_launch_settings() {
let parse = |model, thinking, fast_mode, ultracode| -> Value {
serde_json::from_str(
launch_settings_json(Some(model), true, thinking, fast_mode, ultracode)
.as_deref()
.unwrap(),
)
.unwrap()
};

let fable = parse("claude-fable-5", Some(true), true, true);
assert_eq!(
fable["availableModels"],
json!(["fable", "sonnet", "haiku"])
);
assert_eq!(fable["switchModelsOnFlag"], false);
assert_eq!(fable["alwaysThinkingEnabled"], true);
assert_eq!(fable["fastMode"], true);
assert_eq!(fable["ultracode"], true);

let opus = parse("claude-opus-5", None, false, false);
assert_eq!(
opus["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);

let opus_1m = parse("claude-opus-5[1m]", None, false, false);
assert_eq!(
opus_1m["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);
}

#[test]
fn todo_write_maps_to_plan_updated() {
let mut m = Mapper::new();
Expand Down
1 change: 0 additions & 1 deletion crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -393,7 +393,6 @@ pub struct SessionOptions {
pub cwd: PathBuf,
/// Provider-native model id; `None` = provider default.
pub model: Option<String>,
pub abort_on_model_fallback: bool,
pub resume: Option<ResumeCursor>,
/// Fork the resumed provider session instead of continuing it in place.
/// This is meaningful only when `resume` is present.
Expand Down
3 changes: 2 additions & 1 deletion crates/runtime/src/app/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,10 +344,11 @@ impl AppState {
.filter(|active| active.meta.id == session_id)
.is_some_and(|active| {
active.queue.clear();
active.timeline.mark_idle();
active.shutdown_to_idle();
true
});
if is_active {
self.interrupt(cx);
self.emit_domain(
Topic::SessionStatus {
session_id: session_id.to_owned(),
Expand Down
1 change: 0 additions & 1 deletion crates/runtime/src/app/providers.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -779,7 +779,6 @@ pub(super) fn session_options(
SessionOptions {
cwd: meta.cwd.clone(),
model: meta.model.clone(),
abort_on_model_fallback: settings.abort_on_model_fallback,
resume: meta.resume_cursor.clone(),
fork: meta.pending_fork,
binary_path: provider_settings.binary_path.clone(),
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
1 change: 0 additions & 1 deletion crates/agent/examples/probe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@ async fn run_probe(
let opts = SessionOptions {
cwd,
model,
abort_on_model_fallback: true,
resume: None,
fork: false,
binary_path: None,
Expand Down
214 changes: 126 additions & 88 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,11 +109,7 @@ pub async fn start(opts: SessionOptions) -> Result<SessionHandle, AgentError> {
// Resolve model-scoped launch options from the persisted selections
// (effort/context/fast/thinking are launch-time only; mid-session changes
// ride the resume-restart machinery).
let launch = ClaudeLaunchOptions::resolve(
opts.model.as_deref(),
&opts.option_selections,
opts.abort_on_model_fallback,
);
let launch = ClaudeLaunchOptions::resolve(opts.model.as_deref(), &opts.option_selections);
let base_permission_mode = permission_mode_flag(opts.approval_mode);
let launch_permission_mode = initial_permission_mode(opts.approval_mode, opts.interaction_mode);
// Launch arguments are deliberately appended last, so the tracker must
Expand DownExpand Up@@ -317,25 +313,7 @@ struct ClaudeLaunchOptions {
ultrathink: bool,
}

fn fallback_guard_models(model: &str) -> Vec<String> {
let base = model.split('[').next().unwrap_or(model);
let primary = if base.contains("fable") {
"fable"
} else {
base
};
let mut allow = vec![primary.to_string()];
for extra in ["sonnet", "haiku"] {
if !allow.iter().any(|m| m == extra) {
allow.push(extra.to_string());
}
}
allow
}

fn launch_settings_json(
model: Option<&str>,
abort_on_model_fallback: bool,
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
Expand All@@ -350,23 +328,12 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if abort_on_model_fallback && let Some(model) = model {
settings.insert(
"availableModels".into(),
json!(fallback_guard_models(model)),
);
settings.insert("switchModelsOnFlag".into(), json!(false));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}

impl ClaudeLaunchOptions {
fn resolve(
model: Option<&str>,
selections: &[OptionSelection],
abort_on_model_fallback: bool,
) -> Self {
fn resolve(model: Option<&str>, selections: &[OptionSelection]) -> Self {
let spec = model.and_then(model_spec);
let raw_effort = selection_str(selections, "reasoningEffort");
let resolved_effort = resolve_claude_effort(spec.as_ref(), raw_effort.as_deref());
Expand DownExpand Up@@ -399,13 +366,7 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(
model,
abort_on_model_fallback,
thinking,
fast_mode,
ultracode,
);
let settings_json = launch_settings_json(thinking, fast_mode, ultracode);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -1025,6 +986,13 @@ struct PendingRewind {
conversation: bool,
}

fn served_model_is_fallback(expected: &str, served: &str) -> bool {
(expected.contains("fable") && served.contains("opus"))
|| (served.contains("opus-4-8")
&& expected.contains("opus")
&& !expected.contains("opus-4-8"))
}

pub(crate) struct Mapper {
session_started: bool,
current_message_id: Option<String>,
Expand DownExpand Up@@ -1095,6 +1063,8 @@ pub(crate) struct Mapper {
last_served_model: Option<String>,
/// Model selected for this session, used when Claude reports a synthetic refusal message.
expected_model: Option<String>,
/// Whether a served-model mismatch was already reported for the active turn.
fallback_detected: bool,
/// Latest structured stop reason for the active turn.
stop_reason: Option<String>,
/// Classifier category captured from the active turn's structured refusal details.
Expand DownExpand Up@@ -1158,6 +1128,7 @@ impl Mapper {
native_rewind,
last_served_model: None,
expected_model,
fallback_detected: false,
stop_reason: None,
pending_refusal_category: None,
warned_stop_reason: None,
Expand All@@ -1180,6 +1151,7 @@ impl Mapper {
self.current_turn_id = Some(id.clone());
self.awaiting_turn_checkpoint = self.native_rewind;
self.exit_plan_captured = false;
self.fallback_detected = false;
self.stop_reason = None;
self.pending_refusal_category = None;
self.warned_stop_reason = None;
Expand DownExpand Up@@ -1464,14 +1436,15 @@ impl Mapper {
events
}

fn on_model_refusal_fallback(&self, msg: &Value) -> Vec<AgentEvent> {
fn on_model_refusal_fallback(&mut self, msg: &Value) -> Vec<AgentEvent> {
let (Some(expected), Some(actual)) = (
msg.get("original_model").and_then(Value::as_str),
msg.get("fallback_model").and_then(Value::as_str),
) else {
log::debug!("claude: ignoring malformed model_refusal_fallback");
return Vec::new();
};
self.fallback_detected = true;
vec![AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: actual.to_owned(),
Expand DownExpand Up@@ -1755,14 +1728,41 @@ impl Mapper {
.and_then(Value::as_str)
.map(ClassifierCategory::parse);
}
if let Some(model) = message.get("model").and_then(Value::as_str)
&& self.last_served_model.as_deref() != Some(model)
{
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
if let Some(model) = message.get("model").and_then(Value::as_str) {
if !self.fallback_detected
&& let Some(expected) = self.expected_model.as_deref()
{
let normalized_expected = expected
.split('[')
.next()
.unwrap_or(expected)
.to_ascii_lowercase();
let normalized_served = model
.split('[')
.next()
.unwrap_or(model)
.to_ascii_lowercase();
if served_model_is_fallback(&normalized_expected, &normalized_served) {
self.fallback_detected = true;
out.push(AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: model.to_owned(),
category: None,
checkpoint_id: None,
parent_tool_use_id: msg
.get("parent_tool_use_id")
.and_then(Value::as_str)
.map(str::to_owned),
});
}
}
if self.last_served_model.as_deref() != Some(model) {
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
}
}
out.extend(self.observe_stop_reason(message.get("stop_reason").and_then(Value::as_str)));
let msg_id = message
Expand DownExpand Up@@ -3149,6 +3149,81 @@ mod tests {
);
}

#[test]
fn served_model_fallback_family_rule() {
let cases = [
("claude-fable-5", "claude-opus-4-8", true),
("claude-fable-5", "claude-opus-5", true),
("claude-opus-5", "claude-opus-4-8", true),
("claude-opus-4-8", "claude-opus-4-8", false),
("claude-fable-5", "claude-fable-5", false),
("claude-fable-5", "claude-sonnet-4-5", false),
("claude-fable-5", "claude-haiku-4-5", false),
("anything", "<synthetic>", false),
];
for (expected, served, is_fallback) in cases {
assert_eq!(
served_model_is_fallback(expected, served),
is_fallback,
"expected={expected}, served={served}"
);
}

let expected = "claude-opus-5[1m]";
let normalized_expected = expected.split('[').next().unwrap_or(expected);
assert!(served_model_is_fallback(
normalized_expected,
"claude-opus-4-8"
));
}

#[test]
fn assistant_model_mismatch_emits_one_fallback_per_turn() {
let mut mapper = Mapper::new_configured(
false,
InteractionMode::Build,
"default",
"default".into(),
ApprovalMode::Supervised,
false,
Some("claude-fable-5".into()),
);
mapper.start_turn();

let first = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-1","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert_eq!(
first
.iter()
.filter(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
.count(),
1
);
assert!(first.iter().any(|event| matches!(
event,
AgentEvent::ModelFallbackDetected {
expected,
actual,
category: None,
checkpoint_id: None,
parent_tool_use_id: None,
} if expected == "claude-fable-5"
&& actual == "claude-opus-4-8"
)));

let second = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-2","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert!(
!second
.iter()
.any(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
);
}

#[test]
fn classifier_refusal_result_emits_turn_blocked() {
let mut mapper = Mapper::new_configured(
Expand DownExpand Up@@ -3403,7 +3478,6 @@ mod tests {
value: json!(true),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-4-8"));
assert_eq!(launch.effort.as_deref(), Some("xhigh"));
Expand All@@ -3426,7 +3500,6 @@ mod tests {
value: json!("1m"),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.effort, None);
Expand All@@ -3440,47 +3513,12 @@ mod tests {
id: "thinking".into(),
value: json!(true),
}],
false,
);
let settings: Value =
serde_json::from_str(launch.settings_json.as_deref().unwrap()).unwrap();
assert_eq!(settings["alwaysThinkingEnabled"], true);
}

#[test]
fn fallback_guard_settings_merge_with_launch_settings() {
let parse = |model, thinking, fast_mode, ultracode| -> Value {
serde_json::from_str(
launch_settings_json(Some(model), true, thinking, fast_mode, ultracode)
.as_deref()
.unwrap(),
)
.unwrap()
};

let fable = parse("claude-fable-5", Some(true), true, true);
assert_eq!(
fable["availableModels"],
json!(["fable", "sonnet", "haiku"])
);
assert_eq!(fable["switchModelsOnFlag"], false);
assert_eq!(fable["alwaysThinkingEnabled"], true);
assert_eq!(fable["fastMode"], true);
assert_eq!(fable["ultracode"], true);

let opus = parse("claude-opus-5", None, false, false);
assert_eq!(
opus["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);

let opus_1m = parse("claude-opus-5[1m]", None, false, false);
assert_eq!(
opus_1m["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);
}

#[test]
fn todo_write_maps_to_plan_updated() {
let mut m = Mapper::new();
Expand Down
1 change: 0 additions & 1 deletion crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -393,7 +393,6 @@ pub struct SessionOptions {
pub cwd: PathBuf,
/// Provider-native model id; `None` = provider default.
pub model: Option<String>,
pub abort_on_model_fallback: bool,
pub resume: Option<ResumeCursor>,
/// Fork the resumed provider session instead of continuing it in place.
/// This is meaningful only when `resume` is present.
Expand Down
3 changes: 2 additions & 1 deletion crates/runtime/src/app/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,10 +344,11 @@ impl AppState {
.filter(|active| active.meta.id == session_id)
.is_some_and(|active| {
active.queue.clear();
active.timeline.mark_idle();
active.shutdown_to_idle();
true
});
if is_active {
self.interrupt(cx);
self.emit_domain(
Topic::SessionStatus {
session_id: session_id.to_owned(),
Expand Down
1 change: 0 additions & 1 deletion crates/runtime/src/app/providers.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -779,7 +779,6 @@ pub(super) fn session_options(
SessionOptions {
cwd: meta.cwd.clone(),
model: meta.model.clone(),
abort_on_model_fallback: settings.abort_on_model_fallback,
resume: meta.resume_cursor.clone(),
fork: meta.pending_fork,
binary_path: provider_settings.binary_path.clone(),
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
1 change: 0 additions & 1 deletion crates/agent/examples/probe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@ async fn run_probe(
let opts = SessionOptions {
cwd,
model,
abort_on_model_fallback: true,
resume: None,
fork: false,
binary_path: None,
Expand Down
214 changes: 126 additions & 88 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,11 +109,7 @@ pub async fn start(opts: SessionOptions) -> Result<SessionHandle, AgentError> {
// Resolve model-scoped launch options from the persisted selections
// (effort/context/fast/thinking are launch-time only; mid-session changes
// ride the resume-restart machinery).
let launch = ClaudeLaunchOptions::resolve(
opts.model.as_deref(),
&opts.option_selections,
opts.abort_on_model_fallback,
);
let launch = ClaudeLaunchOptions::resolve(opts.model.as_deref(), &opts.option_selections);
let base_permission_mode = permission_mode_flag(opts.approval_mode);
let launch_permission_mode = initial_permission_mode(opts.approval_mode, opts.interaction_mode);
// Launch arguments are deliberately appended last, so the tracker must
Expand DownExpand Up@@ -317,25 +313,7 @@ struct ClaudeLaunchOptions {
ultrathink: bool,
}

fn fallback_guard_models(model: &str) -> Vec<String> {
let base = model.split('[').next().unwrap_or(model);
let primary = if base.contains("fable") {
"fable"
} else {
base
};
let mut allow = vec![primary.to_string()];
for extra in ["sonnet", "haiku"] {
if !allow.iter().any(|m| m == extra) {
allow.push(extra.to_string());
}
}
allow
}

fn launch_settings_json(
model: Option<&str>,
abort_on_model_fallback: bool,
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
Expand All@@ -350,23 +328,12 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if abort_on_model_fallback && let Some(model) = model {
settings.insert(
"availableModels".into(),
json!(fallback_guard_models(model)),
);
settings.insert("switchModelsOnFlag".into(), json!(false));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}

impl ClaudeLaunchOptions {
fn resolve(
model: Option<&str>,
selections: &[OptionSelection],
abort_on_model_fallback: bool,
) -> Self {
fn resolve(model: Option<&str>, selections: &[OptionSelection]) -> Self {
let spec = model.and_then(model_spec);
let raw_effort = selection_str(selections, "reasoningEffort");
let resolved_effort = resolve_claude_effort(spec.as_ref(), raw_effort.as_deref());
Expand DownExpand Up@@ -399,13 +366,7 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(
model,
abort_on_model_fallback,
thinking,
fast_mode,
ultracode,
);
let settings_json = launch_settings_json(thinking, fast_mode, ultracode);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -1025,6 +986,13 @@ struct PendingRewind {
conversation: bool,
}

fn served_model_is_fallback(expected: &str, served: &str) -> bool {
(expected.contains("fable") && served.contains("opus"))
|| (served.contains("opus-4-8")
&& expected.contains("opus")
&& !expected.contains("opus-4-8"))
}

pub(crate) struct Mapper {
session_started: bool,
current_message_id: Option<String>,
Expand DownExpand Up@@ -1095,6 +1063,8 @@ pub(crate) struct Mapper {
last_served_model: Option<String>,
/// Model selected for this session, used when Claude reports a synthetic refusal message.
expected_model: Option<String>,
/// Whether a served-model mismatch was already reported for the active turn.
fallback_detected: bool,
/// Latest structured stop reason for the active turn.
stop_reason: Option<String>,
/// Classifier category captured from the active turn's structured refusal details.
Expand DownExpand Up@@ -1158,6 +1128,7 @@ impl Mapper {
native_rewind,
last_served_model: None,
expected_model,
fallback_detected: false,
stop_reason: None,
pending_refusal_category: None,
warned_stop_reason: None,
Expand All@@ -1180,6 +1151,7 @@ impl Mapper {
self.current_turn_id = Some(id.clone());
self.awaiting_turn_checkpoint = self.native_rewind;
self.exit_plan_captured = false;
self.fallback_detected = false;
self.stop_reason = None;
self.pending_refusal_category = None;
self.warned_stop_reason = None;
Expand DownExpand Up@@ -1464,14 +1436,15 @@ impl Mapper {
events
}

fn on_model_refusal_fallback(&self, msg: &Value) -> Vec<AgentEvent> {
fn on_model_refusal_fallback(&mut self, msg: &Value) -> Vec<AgentEvent> {
let (Some(expected), Some(actual)) = (
msg.get("original_model").and_then(Value::as_str),
msg.get("fallback_model").and_then(Value::as_str),
) else {
log::debug!("claude: ignoring malformed model_refusal_fallback");
return Vec::new();
};
self.fallback_detected = true;
vec![AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: actual.to_owned(),
Expand DownExpand Up@@ -1755,14 +1728,41 @@ impl Mapper {
.and_then(Value::as_str)
.map(ClassifierCategory::parse);
}
if let Some(model) = message.get("model").and_then(Value::as_str)
&& self.last_served_model.as_deref() != Some(model)
{
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
if let Some(model) = message.get("model").and_then(Value::as_str) {
if !self.fallback_detected
&& let Some(expected) = self.expected_model.as_deref()
{
let normalized_expected = expected
.split('[')
.next()
.unwrap_or(expected)
.to_ascii_lowercase();
let normalized_served = model
.split('[')
.next()
.unwrap_or(model)
.to_ascii_lowercase();
if served_model_is_fallback(&normalized_expected, &normalized_served) {
self.fallback_detected = true;
out.push(AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: model.to_owned(),
category: None,
checkpoint_id: None,
parent_tool_use_id: msg
.get("parent_tool_use_id")
.and_then(Value::as_str)
.map(str::to_owned),
});
}
}
if self.last_served_model.as_deref() != Some(model) {
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
}
}
out.extend(self.observe_stop_reason(message.get("stop_reason").and_then(Value::as_str)));
let msg_id = message
Expand DownExpand Up@@ -3149,6 +3149,81 @@ mod tests {
);
}

#[test]
fn served_model_fallback_family_rule() {
let cases = [
("claude-fable-5", "claude-opus-4-8", true),
("claude-fable-5", "claude-opus-5", true),
("claude-opus-5", "claude-opus-4-8", true),
("claude-opus-4-8", "claude-opus-4-8", false),
("claude-fable-5", "claude-fable-5", false),
("claude-fable-5", "claude-sonnet-4-5", false),
("claude-fable-5", "claude-haiku-4-5", false),
("anything", "<synthetic>", false),
];
for (expected, served, is_fallback) in cases {
assert_eq!(
served_model_is_fallback(expected, served),
is_fallback,
"expected={expected}, served={served}"
);
}

let expected = "claude-opus-5[1m]";
let normalized_expected = expected.split('[').next().unwrap_or(expected);
assert!(served_model_is_fallback(
normalized_expected,
"claude-opus-4-8"
));
}

#[test]
fn assistant_model_mismatch_emits_one_fallback_per_turn() {
let mut mapper = Mapper::new_configured(
false,
InteractionMode::Build,
"default",
"default".into(),
ApprovalMode::Supervised,
false,
Some("claude-fable-5".into()),
);
mapper.start_turn();

let first = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-1","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert_eq!(
first
.iter()
.filter(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
.count(),
1
);
assert!(first.iter().any(|event| matches!(
event,
AgentEvent::ModelFallbackDetected {
expected,
actual,
category: None,
checkpoint_id: None,
parent_tool_use_id: None,
} if expected == "claude-fable-5"
&& actual == "claude-opus-4-8"
)));

let second = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-2","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert!(
!second
.iter()
.any(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
);
}

#[test]
fn classifier_refusal_result_emits_turn_blocked() {
let mut mapper = Mapper::new_configured(
Expand DownExpand Up@@ -3403,7 +3478,6 @@ mod tests {
value: json!(true),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-4-8"));
assert_eq!(launch.effort.as_deref(), Some("xhigh"));
Expand All@@ -3426,7 +3500,6 @@ mod tests {
value: json!("1m"),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.effort, None);
Expand All@@ -3440,47 +3513,12 @@ mod tests {
id: "thinking".into(),
value: json!(true),
}],
false,
);
let settings: Value =
serde_json::from_str(launch.settings_json.as_deref().unwrap()).unwrap();
assert_eq!(settings["alwaysThinkingEnabled"], true);
}

#[test]
fn fallback_guard_settings_merge_with_launch_settings() {
let parse = |model, thinking, fast_mode, ultracode| -> Value {
serde_json::from_str(
launch_settings_json(Some(model), true, thinking, fast_mode, ultracode)
.as_deref()
.unwrap(),
)
.unwrap()
};

let fable = parse("claude-fable-5", Some(true), true, true);
assert_eq!(
fable["availableModels"],
json!(["fable", "sonnet", "haiku"])
);
assert_eq!(fable["switchModelsOnFlag"], false);
assert_eq!(fable["alwaysThinkingEnabled"], true);
assert_eq!(fable["fastMode"], true);
assert_eq!(fable["ultracode"], true);

let opus = parse("claude-opus-5", None, false, false);
assert_eq!(
opus["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);

let opus_1m = parse("claude-opus-5[1m]", None, false, false);
assert_eq!(
opus_1m["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);
}

#[test]
fn todo_write_maps_to_plan_updated() {
let mut m = Mapper::new();
Expand Down
1 change: 0 additions & 1 deletion crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -393,7 +393,6 @@ pub struct SessionOptions {
pub cwd: PathBuf,
/// Provider-native model id; `None` = provider default.
pub model: Option<String>,
pub abort_on_model_fallback: bool,
pub resume: Option<ResumeCursor>,
/// Fork the resumed provider session instead of continuing it in place.
/// This is meaningful only when `resume` is present.
Expand Down
3 changes: 2 additions & 1 deletion crates/runtime/src/app/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,10 +344,11 @@ impl AppState {
.filter(|active| active.meta.id == session_id)
.is_some_and(|active| {
active.queue.clear();
active.timeline.mark_idle();
active.shutdown_to_idle();
true
});
if is_active {
self.interrupt(cx);
self.emit_domain(
Topic::SessionStatus {
session_id: session_id.to_owned(),
Expand Down
1 change: 0 additions & 1 deletion crates/runtime/src/app/providers.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -779,7 +779,6 @@ pub(super) fn session_options(
SessionOptions {
cwd: meta.cwd.clone(),
model: meta.model.clone(),
abort_on_model_fallback: settings.abort_on_model_fallback,
resume: meta.resume_cursor.clone(),
fork: meta.pending_fork,
binary_path: provider_settings.binary_path.clone(),
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
1 change: 0 additions & 1 deletion crates/agent/examples/probe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@ async fn run_probe(
let opts = SessionOptions {
cwd,
model,
abort_on_model_fallback: true,
resume: None,
fork: false,
binary_path: None,
Expand Down
214 changes: 126 additions & 88 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,11 +109,7 @@ pub async fn start(opts: SessionOptions) -> Result<SessionHandle, AgentError> {
// Resolve model-scoped launch options from the persisted selections
// (effort/context/fast/thinking are launch-time only; mid-session changes
// ride the resume-restart machinery).
let launch = ClaudeLaunchOptions::resolve(
opts.model.as_deref(),
&opts.option_selections,
opts.abort_on_model_fallback,
);
let launch = ClaudeLaunchOptions::resolve(opts.model.as_deref(), &opts.option_selections);
let base_permission_mode = permission_mode_flag(opts.approval_mode);
let launch_permission_mode = initial_permission_mode(opts.approval_mode, opts.interaction_mode);
// Launch arguments are deliberately appended last, so the tracker must
Expand DownExpand Up@@ -317,25 +313,7 @@ struct ClaudeLaunchOptions {
ultrathink: bool,
}

fn fallback_guard_models(model: &str) -> Vec<String> {
let base = model.split('[').next().unwrap_or(model);
let primary = if base.contains("fable") {
"fable"
} else {
base
};
let mut allow = vec![primary.to_string()];
for extra in ["sonnet", "haiku"] {
if !allow.iter().any(|m| m == extra) {
allow.push(extra.to_string());
}
}
allow
}

fn launch_settings_json(
model: Option<&str>,
abort_on_model_fallback: bool,
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
Expand All@@ -350,23 +328,12 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if abort_on_model_fallback && let Some(model) = model {
settings.insert(
"availableModels".into(),
json!(fallback_guard_models(model)),
);
settings.insert("switchModelsOnFlag".into(), json!(false));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}

impl ClaudeLaunchOptions {
fn resolve(
model: Option<&str>,
selections: &[OptionSelection],
abort_on_model_fallback: bool,
) -> Self {
fn resolve(model: Option<&str>, selections: &[OptionSelection]) -> Self {
let spec = model.and_then(model_spec);
let raw_effort = selection_str(selections, "reasoningEffort");
let resolved_effort = resolve_claude_effort(spec.as_ref(), raw_effort.as_deref());
Expand DownExpand Up@@ -399,13 +366,7 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(
model,
abort_on_model_fallback,
thinking,
fast_mode,
ultracode,
);
let settings_json = launch_settings_json(thinking, fast_mode, ultracode);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -1025,6 +986,13 @@ struct PendingRewind {
conversation: bool,
}

fn served_model_is_fallback(expected: &str, served: &str) -> bool {
(expected.contains("fable") && served.contains("opus"))
|| (served.contains("opus-4-8")
&& expected.contains("opus")
&& !expected.contains("opus-4-8"))
}

pub(crate) struct Mapper {
session_started: bool,
current_message_id: Option<String>,
Expand DownExpand Up@@ -1095,6 +1063,8 @@ pub(crate) struct Mapper {
last_served_model: Option<String>,
/// Model selected for this session, used when Claude reports a synthetic refusal message.
expected_model: Option<String>,
/// Whether a served-model mismatch was already reported for the active turn.
fallback_detected: bool,
/// Latest structured stop reason for the active turn.
stop_reason: Option<String>,
/// Classifier category captured from the active turn's structured refusal details.
Expand DownExpand Up@@ -1158,6 +1128,7 @@ impl Mapper {
native_rewind,
last_served_model: None,
expected_model,
fallback_detected: false,
stop_reason: None,
pending_refusal_category: None,
warned_stop_reason: None,
Expand All@@ -1180,6 +1151,7 @@ impl Mapper {
self.current_turn_id = Some(id.clone());
self.awaiting_turn_checkpoint = self.native_rewind;
self.exit_plan_captured = false;
self.fallback_detected = false;
self.stop_reason = None;
self.pending_refusal_category = None;
self.warned_stop_reason = None;
Expand DownExpand Up@@ -1464,14 +1436,15 @@ impl Mapper {
events
}

fn on_model_refusal_fallback(&self, msg: &Value) -> Vec<AgentEvent> {
fn on_model_refusal_fallback(&mut self, msg: &Value) -> Vec<AgentEvent> {
let (Some(expected), Some(actual)) = (
msg.get("original_model").and_then(Value::as_str),
msg.get("fallback_model").and_then(Value::as_str),
) else {
log::debug!("claude: ignoring malformed model_refusal_fallback");
return Vec::new();
};
self.fallback_detected = true;
vec![AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: actual.to_owned(),
Expand DownExpand Up@@ -1755,14 +1728,41 @@ impl Mapper {
.and_then(Value::as_str)
.map(ClassifierCategory::parse);
}
if let Some(model) = message.get("model").and_then(Value::as_str)
&& self.last_served_model.as_deref() != Some(model)
{
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
if let Some(model) = message.get("model").and_then(Value::as_str) {
if !self.fallback_detected
&& let Some(expected) = self.expected_model.as_deref()
{
let normalized_expected = expected
.split('[')
.next()
.unwrap_or(expected)
.to_ascii_lowercase();
let normalized_served = model
.split('[')
.next()
.unwrap_or(model)
.to_ascii_lowercase();
if served_model_is_fallback(&normalized_expected, &normalized_served) {
self.fallback_detected = true;
out.push(AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: model.to_owned(),
category: None,
checkpoint_id: None,
parent_tool_use_id: msg
.get("parent_tool_use_id")
.and_then(Value::as_str)
.map(str::to_owned),
});
}
}
if self.last_served_model.as_deref() != Some(model) {
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
}
}
out.extend(self.observe_stop_reason(message.get("stop_reason").and_then(Value::as_str)));
let msg_id = message
Expand DownExpand Up@@ -3149,6 +3149,81 @@ mod tests {
);
}

#[test]
fn served_model_fallback_family_rule() {
let cases = [
("claude-fable-5", "claude-opus-4-8", true),
("claude-fable-5", "claude-opus-5", true),
("claude-opus-5", "claude-opus-4-8", true),
("claude-opus-4-8", "claude-opus-4-8", false),
("claude-fable-5", "claude-fable-5", false),
("claude-fable-5", "claude-sonnet-4-5", false),
("claude-fable-5", "claude-haiku-4-5", false),
("anything", "<synthetic>", false),
];
for (expected, served, is_fallback) in cases {
assert_eq!(
served_model_is_fallback(expected, served),
is_fallback,
"expected={expected}, served={served}"
);
}

let expected = "claude-opus-5[1m]";
let normalized_expected = expected.split('[').next().unwrap_or(expected);
assert!(served_model_is_fallback(
normalized_expected,
"claude-opus-4-8"
));
}

#[test]
fn assistant_model_mismatch_emits_one_fallback_per_turn() {
let mut mapper = Mapper::new_configured(
false,
InteractionMode::Build,
"default",
"default".into(),
ApprovalMode::Supervised,
false,
Some("claude-fable-5".into()),
);
mapper.start_turn();

let first = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-1","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert_eq!(
first
.iter()
.filter(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
.count(),
1
);
assert!(first.iter().any(|event| matches!(
event,
AgentEvent::ModelFallbackDetected {
expected,
actual,
category: None,
checkpoint_id: None,
parent_tool_use_id: None,
} if expected == "claude-fable-5"
&& actual == "claude-opus-4-8"
)));

let second = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-2","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert!(
!second
.iter()
.any(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
);
}

#[test]
fn classifier_refusal_result_emits_turn_blocked() {
let mut mapper = Mapper::new_configured(
Expand DownExpand Up@@ -3403,7 +3478,6 @@ mod tests {
value: json!(true),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-4-8"));
assert_eq!(launch.effort.as_deref(), Some("xhigh"));
Expand All@@ -3426,7 +3500,6 @@ mod tests {
value: json!("1m"),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.effort, None);
Expand All@@ -3440,47 +3513,12 @@ mod tests {
id: "thinking".into(),
value: json!(true),
}],
false,
);
let settings: Value =
serde_json::from_str(launch.settings_json.as_deref().unwrap()).unwrap();
assert_eq!(settings["alwaysThinkingEnabled"], true);
}

#[test]
fn fallback_guard_settings_merge_with_launch_settings() {
let parse = |model, thinking, fast_mode, ultracode| -> Value {
serde_json::from_str(
launch_settings_json(Some(model), true, thinking, fast_mode, ultracode)
.as_deref()
.unwrap(),
)
.unwrap()
};

let fable = parse("claude-fable-5", Some(true), true, true);
assert_eq!(
fable["availableModels"],
json!(["fable", "sonnet", "haiku"])
);
assert_eq!(fable["switchModelsOnFlag"], false);
assert_eq!(fable["alwaysThinkingEnabled"], true);
assert_eq!(fable["fastMode"], true);
assert_eq!(fable["ultracode"], true);

let opus = parse("claude-opus-5", None, false, false);
assert_eq!(
opus["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);

let opus_1m = parse("claude-opus-5[1m]", None, false, false);
assert_eq!(
opus_1m["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);
}

#[test]
fn todo_write_maps_to_plan_updated() {
let mut m = Mapper::new();
Expand Down
1 change: 0 additions & 1 deletion crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -393,7 +393,6 @@ pub struct SessionOptions {
pub cwd: PathBuf,
/// Provider-native model id; `None` = provider default.
pub model: Option<String>,
pub abort_on_model_fallback: bool,
pub resume: Option<ResumeCursor>,
/// Fork the resumed provider session instead of continuing it in place.
/// This is meaningful only when `resume` is present.
Expand Down
3 changes: 2 additions & 1 deletion crates/runtime/src/app/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,10 +344,11 @@ impl AppState {
.filter(|active| active.meta.id == session_id)
.is_some_and(|active| {
active.queue.clear();
active.timeline.mark_idle();
active.shutdown_to_idle();
true
});
if is_active {
self.interrupt(cx);
self.emit_domain(
Topic::SessionStatus {
session_id: session_id.to_owned(),
Expand Down
1 change: 0 additions & 1 deletion crates/runtime/src/app/providers.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -779,7 +779,6 @@ pub(super) fn session_options(
SessionOptions {
cwd: meta.cwd.clone(),
model: meta.model.clone(),
abort_on_model_fallback: settings.abort_on_model_fallback,
resume: meta.resume_cursor.clone(),
fork: meta.pending_fork,
binary_path: provider_settings.binary_path.clone(),
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
1 change: 0 additions & 1 deletion crates/agent/examples/probe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,7 +245,6 @@ async fn run_probe(
let opts = SessionOptions {
cwd,
model,
abort_on_model_fallback: true,
resume: None,
fork: false,
binary_path: None,
Expand Down
214 changes: 126 additions & 88 deletions crates/agent/src/claude.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -109,11 +109,7 @@ pub async fn start(opts: SessionOptions) -> Result<SessionHandle, AgentError> {
// Resolve model-scoped launch options from the persisted selections
// (effort/context/fast/thinking are launch-time only; mid-session changes
// ride the resume-restart machinery).
let launch = ClaudeLaunchOptions::resolve(
opts.model.as_deref(),
&opts.option_selections,
opts.abort_on_model_fallback,
);
let launch = ClaudeLaunchOptions::resolve(opts.model.as_deref(), &opts.option_selections);
let base_permission_mode = permission_mode_flag(opts.approval_mode);
let launch_permission_mode = initial_permission_mode(opts.approval_mode, opts.interaction_mode);
// Launch arguments are deliberately appended last, so the tracker must
Expand DownExpand Up@@ -317,25 +313,7 @@ struct ClaudeLaunchOptions {
ultrathink: bool,
}

fn fallback_guard_models(model: &str) -> Vec<String> {
let base = model.split('[').next().unwrap_or(model);
let primary = if base.contains("fable") {
"fable"
} else {
base
};
let mut allow = vec![primary.to_string()];
for extra in ["sonnet", "haiku"] {
if !allow.iter().any(|m| m == extra) {
allow.push(extra.to_string());
}
}
allow
}

fn launch_settings_json(
model: Option<&str>,
abort_on_model_fallback: bool,
thinking: Option<bool>,
fast_mode: bool,
ultracode: bool,
Expand All@@ -350,23 +328,12 @@ fn launch_settings_json(
if ultracode {
settings.insert("ultracode".into(), json!(true));
}
if abort_on_model_fallback && let Some(model) = model {
settings.insert(
"availableModels".into(),
json!(fallback_guard_models(model)),
);
settings.insert("switchModelsOnFlag".into(), json!(false));
}
(!settings.is_empty())
.then(|| serde_json::to_string(&Value::Object(settings)).unwrap_or_default())
}

impl ClaudeLaunchOptions {
fn resolve(
model: Option<&str>,
selections: &[OptionSelection],
abort_on_model_fallback: bool,
) -> Self {
fn resolve(model: Option<&str>, selections: &[OptionSelection]) -> Self {
let spec = model.and_then(model_spec);
let raw_effort = selection_str(selections, "reasoningEffort");
let resolved_effort = resolve_claude_effort(spec.as_ref(), raw_effort.as_deref());
Expand DownExpand Up@@ -399,13 +366,7 @@ impl ClaudeLaunchOptions {
None
};

let settings_json = launch_settings_json(
model,
abort_on_model_fallback,
thinking,
fast_mode,
ultracode,
);
let settings_json = launch_settings_json(thinking, fast_mode, ultracode);

ClaudeLaunchOptions {
model_id,
Expand DownExpand Up@@ -1025,6 +986,13 @@ struct PendingRewind {
conversation: bool,
}

fn served_model_is_fallback(expected: &str, served: &str) -> bool {
(expected.contains("fable") && served.contains("opus"))
|| (served.contains("opus-4-8")
&& expected.contains("opus")
&& !expected.contains("opus-4-8"))
}

pub(crate) struct Mapper {
session_started: bool,
current_message_id: Option<String>,
Expand DownExpand Up@@ -1095,6 +1063,8 @@ pub(crate) struct Mapper {
last_served_model: Option<String>,
/// Model selected for this session, used when Claude reports a synthetic refusal message.
expected_model: Option<String>,
/// Whether a served-model mismatch was already reported for the active turn.
fallback_detected: bool,
/// Latest structured stop reason for the active turn.
stop_reason: Option<String>,
/// Classifier category captured from the active turn's structured refusal details.
Expand DownExpand Up@@ -1158,6 +1128,7 @@ impl Mapper {
native_rewind,
last_served_model: None,
expected_model,
fallback_detected: false,
stop_reason: None,
pending_refusal_category: None,
warned_stop_reason: None,
Expand All@@ -1180,6 +1151,7 @@ impl Mapper {
self.current_turn_id = Some(id.clone());
self.awaiting_turn_checkpoint = self.native_rewind;
self.exit_plan_captured = false;
self.fallback_detected = false;
self.stop_reason = None;
self.pending_refusal_category = None;
self.warned_stop_reason = None;
Expand DownExpand Up@@ -1464,14 +1436,15 @@ impl Mapper {
events
}

fn on_model_refusal_fallback(&self, msg: &Value) -> Vec<AgentEvent> {
fn on_model_refusal_fallback(&mut self, msg: &Value) -> Vec<AgentEvent> {
let (Some(expected), Some(actual)) = (
msg.get("original_model").and_then(Value::as_str),
msg.get("fallback_model").and_then(Value::as_str),
) else {
log::debug!("claude: ignoring malformed model_refusal_fallback");
return Vec::new();
};
self.fallback_detected = true;
vec![AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: actual.to_owned(),
Expand DownExpand Up@@ -1755,14 +1728,41 @@ impl Mapper {
.and_then(Value::as_str)
.map(ClassifierCategory::parse);
}
if let Some(model) = message.get("model").and_then(Value::as_str)
&& self.last_served_model.as_deref() != Some(model)
{
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
if let Some(model) = message.get("model").and_then(Value::as_str) {
if !self.fallback_detected
&& let Some(expected) = self.expected_model.as_deref()
{
let normalized_expected = expected
.split('[')
.next()
.unwrap_or(expected)
.to_ascii_lowercase();
let normalized_served = model
.split('[')
.next()
.unwrap_or(model)
.to_ascii_lowercase();
if served_model_is_fallback(&normalized_expected, &normalized_served) {
self.fallback_detected = true;
out.push(AgentEvent::ModelFallbackDetected {
expected: expected.to_owned(),
actual: model.to_owned(),
category: None,
checkpoint_id: None,
parent_tool_use_id: msg
.get("parent_tool_use_id")
.and_then(Value::as_str)
.map(str::to_owned),
});
}
}
if self.last_served_model.as_deref() != Some(model) {
self.last_served_model = Some(model.to_owned());
out.push(AgentEvent::ServedModel {
model: model.to_owned(),
reason: None,
});
}
}
out.extend(self.observe_stop_reason(message.get("stop_reason").and_then(Value::as_str)));
let msg_id = message
Expand DownExpand Up@@ -3149,6 +3149,81 @@ mod tests {
);
}

#[test]
fn served_model_fallback_family_rule() {
let cases = [
("claude-fable-5", "claude-opus-4-8", true),
("claude-fable-5", "claude-opus-5", true),
("claude-opus-5", "claude-opus-4-8", true),
("claude-opus-4-8", "claude-opus-4-8", false),
("claude-fable-5", "claude-fable-5", false),
("claude-fable-5", "claude-sonnet-4-5", false),
("claude-fable-5", "claude-haiku-4-5", false),
("anything", "<synthetic>", false),
];
for (expected, served, is_fallback) in cases {
assert_eq!(
served_model_is_fallback(expected, served),
is_fallback,
"expected={expected}, served={served}"
);
}

let expected = "claude-opus-5[1m]";
let normalized_expected = expected.split('[').next().unwrap_or(expected);
assert!(served_model_is_fallback(
normalized_expected,
"claude-opus-4-8"
));
}

#[test]
fn assistant_model_mismatch_emits_one_fallback_per_turn() {
let mut mapper = Mapper::new_configured(
false,
InteractionMode::Build,
"default",
"default".into(),
ApprovalMode::Supervised,
false,
Some("claude-fable-5".into()),
);
mapper.start_turn();

let first = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-1","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert_eq!(
first
.iter()
.filter(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
.count(),
1
);
assert!(first.iter().any(|event| matches!(
event,
AgentEvent::ModelFallbackDetected {
expected,
actual,
category: None,
checkpoint_id: None,
parent_tool_use_id: None,
} if expected == "claude-fable-5"
&& actual == "claude-opus-4-8"
)));

let second = feed(
&mut mapper,
r#"{"type":"assistant","message":{"id":"msg-fallback-2","model":"claude-opus-4-8","content":[]},"parent_tool_use_id":null}"#,
);
assert!(
!second
.iter()
.any(|event| matches!(event, AgentEvent::ModelFallbackDetected { .. }))
);
}

#[test]
fn classifier_refusal_result_emits_turn_blocked() {
let mut mapper = Mapper::new_configured(
Expand DownExpand Up@@ -3403,7 +3478,6 @@ mod tests {
value: json!(true),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-opus-4-8"));
assert_eq!(launch.effort.as_deref(), Some("xhigh"));
Expand All@@ -3426,7 +3500,6 @@ mod tests {
value: json!("1m"),
},
],
false,
);
assert_eq!(launch.model_id.as_deref(), Some("claude-fable-5[1m]"));
assert_eq!(launch.effort, None);
Expand All@@ -3440,47 +3513,12 @@ mod tests {
id: "thinking".into(),
value: json!(true),
}],
false,
);
let settings: Value =
serde_json::from_str(launch.settings_json.as_deref().unwrap()).unwrap();
assert_eq!(settings["alwaysThinkingEnabled"], true);
}

#[test]
fn fallback_guard_settings_merge_with_launch_settings() {
let parse = |model, thinking, fast_mode, ultracode| -> Value {
serde_json::from_str(
launch_settings_json(Some(model), true, thinking, fast_mode, ultracode)
.as_deref()
.unwrap(),
)
.unwrap()
};

let fable = parse("claude-fable-5", Some(true), true, true);
assert_eq!(
fable["availableModels"],
json!(["fable", "sonnet", "haiku"])
);
assert_eq!(fable["switchModelsOnFlag"], false);
assert_eq!(fable["alwaysThinkingEnabled"], true);
assert_eq!(fable["fastMode"], true);
assert_eq!(fable["ultracode"], true);

let opus = parse("claude-opus-5", None, false, false);
assert_eq!(
opus["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);

let opus_1m = parse("claude-opus-5[1m]", None, false, false);
assert_eq!(
opus_1m["availableModels"],
json!(["claude-opus-5", "sonnet", "haiku"])
);
}

#[test]
fn todo_write_maps_to_plan_updated() {
let mut m = Mapper::new();
Expand Down
1 change: 0 additions & 1 deletion crates/agent/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -393,7 +393,6 @@ pub struct SessionOptions {
pub cwd: PathBuf,
/// Provider-native model id; `None` = provider default.
pub model: Option<String>,
pub abort_on_model_fallback: bool,
pub resume: Option<ResumeCursor>,
/// Fork the resumed provider session instead of continuing it in place.
/// This is meaningful only when `resume` is present.
Expand Down
3 changes: 2 additions & 1 deletion crates/runtime/src/app/events.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,10 +344,11 @@ impl AppState {
.filter(|active| active.meta.id == session_id)
.is_some_and(|active| {
active.queue.clear();
active.timeline.mark_idle();
active.shutdown_to_idle();
true
});
if is_active {
self.interrupt(cx);
self.emit_domain(
Topic::SessionStatus {
session_id: session_id.to_owned(),
Expand Down
1 change: 0 additions & 1 deletion crates/runtime/src/app/providers.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -779,7 +779,6 @@ pub(super) fn session_options(
SessionOptions {
cwd: meta.cwd.clone(),
model: meta.model.clone(),
abort_on_model_fallback: settings.abort_on_model_fallback,
resume: meta.resume_cursor.clone(),
fork: meta.pending_fork,
binary_path: provider_settings.binary_path.clone(),
Expand Down
Loading