diff --git a/native/gpui/src/screens/picker.rs b/native/gpui/src/screens/picker.rs index d50a1caa4f..9999724ff6 100644 --- a/native/gpui/src/screens/picker.rs +++ b/native/gpui/src/screens/picker.rs @@ -167,6 +167,14 @@ pub fn settle(c: &Cursor, rows: &[Section], own: &Cursor) -> Cursor { if let Some(m) = rows.iter().find(|s| s.action == "model").and_then(|s| s.choices.first()) { n.col = 1; n.set(1, &m.value, own); } n } +/// The model a cursor applies: its own when the provider lists it (or lists none yet), else the provider's default (""). +pub fn model_applied(c: &Cursor, rows: &[Section]) -> String { + if c.model.is_empty() { return String::new() } + match rows.iter().find(|s| s.action == "model") { + Some(s) if !s.choices.is_empty() && !s.choices.iter().any(|ch| ch.value == c.model) => String::new(), + _ => c.model.clone(), + } +} /// The effort a cursor applies: the one lit (an effort the model does not take is the agent's default; none when it takes none). pub fn effort_applied(c: &Cursor, rows: &[Section]) -> String { lit(&steps(&levels(rows, &c.model)), &c.effort).unwrap_or_else(|| c.effort.clone()) } /// The requests that apply a cursor against the thread's own: another agent is one switch carrying the model and any new effort, the same agent asks for what changed, nothing changed asks for nothing. @@ -252,8 +260,9 @@ pub fn shown(thread: &Value, pick: &Pick, favs: &[String]) -> Option { let mine = parse(&thread["picker"]); if mine.is_empty() { return None } let own = Cursor::own(&mine); let id = string(thread, "id"); - let cur = pick.cur.as_ref().filter(|(t, _)| *t == id).map_or_else(|| own.clone(), |(_, c)| c.clone()); + let mut cur = pick.cur.as_ref().filter(|(t, _)| *t == id).map_or_else(|| own.clone(), |(_, c)| c.clone()); let all = for_provider(&thread["picker"], &thread["pickerAgents"], &cur.provider); + cur.model = model_applied(&cur, &all); let (rows, hidden) = arrange(&all, &cur.provider, &pick.q, favs, &cur.model); Some(Shown { own, cur, all, rows, hidden }) } @@ -574,6 +583,7 @@ impl Backplane { /// Apply a cursor: an agent that cannot be used here is only shown (its column says why), never switched to. fn picker_apply(&self, mut c: Cursor, all: &[Section], own: &Cursor) { if !agent_ok(all, &c.provider) { return } + c.model = model_applied(&c, all); c.effort = effort_applied(&c, all); c.speed = speed_applied(&c, all); for cmd in plan(&c, own) { let _ = self.tx.try_send(cmd); } @@ -760,4 +770,18 @@ mod tests { assert_eq!(acts(plan(&far, &own)), [pair("provider", "codex\u{1f}gpt"), pair("speed", "fast")]); assert_eq!(cap(3, 3, 4), "←→"); assert_eq!(cap(0, 3, 4), "Tab"); assert_eq!(cap(3, 1, 3), "", "no keycap for a dial Tab cannot reach"); } + #[test] fn switching_provider_or_applying_cursor_never_sends_stale_model_across_providers() { + let (p, a) = fixture(); let s = parse(&p); let own = Cursor::own(&s); + let mut c = own.clone(); + c.set(0, "@codex", &own); + assert_eq!(c.provider, "@codex"); + assert_eq!(c.model, "", "switching provider clears previous provider's model"); + assert_eq!(acts(plan(&c, &own)), [pair("provider", "codex\u{1f}")]); + + let codex_rows = for_provider(&p, &a, "@codex"); + let stale = Cursor { col: 0, provider: "@codex".into(), model: "opus".into(), effort: "high".into(), speed: String::new() }; + assert_eq!(model_applied(&stale, &codex_rows), "", "stale claude model is cleared for codex"); + let valid = Cursor { model: "gpt".into(), ..stale }; + assert_eq!(model_applied(&valid, &codex_rows), "gpt"); + } } diff --git a/native/host/src/agents/launch.rs b/native/host/src/agents/launch.rs index edaec8f4ea..19ab4b7e3d 100644 --- a/native/host/src/agents/launch.rs +++ b/native/host/src/agents/launch.rs @@ -34,7 +34,8 @@ impl Agents { let asked = if s(a, "provider").is_empty() { if a.get("account").is_some() && !s(a, "account").eq_ignore_ascii_case("default") { String::new() } else { default_prov.clone() } } else { s(a, "provider").to_string() }; let chosen = match self.account_arg(a, &asked).await { Ok(c) => c, Err(e) => return fail(&e) }; let provider = chosen.as_ref().map(|c| c.provider.clone()).unwrap_or(if asked.is_empty() { default_prov.clone() } else { asked }); - let model = if !s(a, "model").is_empty() { s(a, "model").to_string() } else if s(a, "provider").is_empty() && provider == default_prov { default_model } else { String::new() }; + let raw_model = if !s(a, "model").is_empty() { s(a, "model").to_string() } else if s(a, "provider").is_empty() && provider == default_prov { default_model } else { String::new() }; + let model = crate::settings::models::sanitize_model_now(&provider, &raw_model); if provider != "claude" && super::providers::driver(&provider).is_none() { return fail(&format!("{provider} threads are not run by the Rust hub yet")) } let (now, report) = (now_s(), a.get("report").and_then(Value::as_bool).unwrap_or(true)); let seq = self.seq_n(); diff --git a/native/host/src/agents/mod.rs b/native/host/src/agents/mod.rs index e3c6e2ea27..b9983b6e27 100644 --- a/native/host/src/agents/mod.rs +++ b/native/host/src/agents/mod.rs @@ -189,7 +189,8 @@ impl Agents { }).await.unwrap_or_default() } pub async fn prompt_for(&self, th: &str, cwd: &str) -> String { - let (provider, model) = self.world().await.threads.get(th).map(|t| (t.provider.clone(), t.model.clone())).unwrap_or_default(); + let (provider, raw_model) = self.world().await.threads.get(th).map(|t| (t.provider.clone(), t.model.clone())).unwrap_or_default(); + let model = crate::settings::models::sanitize_model_now(&provider, &raw_model); self.prompt_context(th, cwd, &provider, &model, false).await.text() } async fn prompt_base(&self, th: &str, cwd: &str) -> String { @@ -521,7 +522,7 @@ impl RpcHandler for Rpc { let (cwd, provider, model) = { let world = self.0.world().await; let t = &world.threads[th]; - (world.cwd(th), t.provider.clone(), t.model.clone()) + (world.cwd(th), t.provider.clone(), crate::settings::models::sanitize_model_now(&t.provider, &t.model)) }; let home = hub.cfg.home.clone(); let standalone = provider == "antigravity" && !providers::agy::pinned(&home.to_string_lossy()); @@ -878,7 +879,7 @@ impl Actor { self.commit(ev).await; self.recent.push_back(msg.clone()); if self.recent.len() > RECENT { self.recent.pop_front(); } if midturn { self.unanswered_arm(&msg, &text, now); let agent = unanswered::wrap(&text); return self.steer_as(text, agent).await } return self.steer(text).await } - self.codex = codex; self.prov = t.provider.clone(); self.model = t.model.clone(); + self.codex = codex; self.prov = t.provider.clone(); self.model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); let was_running = self.cx.running || t.turn == "running"; // Ride.post: a turn that starts on an idle thread takes the mail waiting for it self.cx = cx; self.last_user = msg.clone(); self.cwd = cwd.clone(); let (now, th) = (now_s(), self.th.clone()); @@ -956,7 +957,7 @@ impl Actor { if self.cx.running || t.turn == "running" { return Err("the thread's turn is running".into()) } if t.provider != "claude" && providers::driver(&t.provider).is_none() { return Err(format!("{} threads are not run by the Rust hub yet", t.provider)) } let (now, th) = (now_s(), self.th.clone()); - self.codex = t.provider != "claude"; self.prov = t.provider.clone(); self.model = t.model.clone(); self.cx = cx; self.cwd = cwd.clone(); + self.codex = t.provider != "claude"; self.prov = t.provider.clone(); self.model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); self.cx = cx; self.cwd = cwd.clone(); let mut ev = vec![]; if taken { ev.push(json!({"$":"QueueTaken","thread":th,"at":now})) } ev.push(json!({"$":"TurnChanged","thread":th,"state":"running","at":now})); self.limit_seen = None; let handed = if taken { String::new() } else { self.handed(&mut ev, now).await }; // what was queued is `text` when it is all taken; otherwise the hand-overs go with this turn and the rest stays @@ -999,7 +1000,7 @@ impl Actor { let mut ev = vec![json!({"$":"ActivityLogged","thread":th,"act":hub_id("s", now, self.ag.seq()),"tone":"info","kind":"steer","summary":rules::steer_summary(&text),"at":now})]; let run = if ride.is_empty() { agent.clone() } else { ev.extend(codex::ride_done(&th, &ride, "with the steer", now)); if text.trim().is_empty() { codex::ride_input(&ride) } else { format!("{}\n\n{}", codex::ride_input(&ride), agent) } }; ev.push(json!({"$":"TurnChanged","thread":th,"state":"running","at":now})); - self.live_close().await; self.commit(ev).await; self.cwd = cwd.clone(); self.cx.running = true; self.codex = true; self.prov = t.provider.clone(); self.model = t.model.clone(); + self.live_close().await; self.commit(ev).await; self.cwd = cwd.clone(); self.cx.running = true; self.codex = true; self.prov = t.provider.clone(); self.model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); self.steering = true; self.codex_run(&t, &cwd, &run).await; self.steering = false; Ok(()) } @@ -1036,8 +1037,10 @@ impl Actor { } } } + let model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); + self.model = model.clone(); let gen = format!("{now}-{}", self.ag.seq()); self.ag.set_gen(&th, &gen); - let prompt = self.ag.prompt_context(&th, cwd, &t.provider, &t.model, self.person || !acct_env.is_empty()).await.text(); + let prompt = self.ag.prompt_context(&th, cwd, &t.provider, &model, self.person || !acct_env.is_empty()).await.text(); let (effort, think, session) = { let w = self.ag.world().await; (w.setting(&format!("effort.{th}")).to_string(), self.cx.think, w.threads.get(&th).map(|x| x.session.clone()).unwrap_or_else(|| t.session.clone())) }; let session = if self.person { String::new() } else { session_over.unwrap_or(session) }; // a copied session is never resumed in side-by-side mode; another login's is not either (`account_route`) // infinite context (agents/recall.rs): a new turn runs in a fresh session with the view ahead of its text; a steer keeps the running turn's session @@ -1045,7 +1048,7 @@ impl Actor { let session = if fresh { String::new() } else { session }; let text = if fresh { let v = self.ag.recall_view(&th).await; if v.is_empty() { text.to_string() } else { format!("{v}\n\n{text}") } } else { text.to_string() }; let url = self.ag.mcp.get().map(|m| m.url(&th, &gen)).unwrap_or_default(); - let (host, cwd2, text2, prov2, model2) = (self.ag.host.clone(), cwd.to_string(), text.to_string(), t.provider.clone(), t.model.clone()); + let (host, cwd2, text2, prov2, model2) = (self.ag.host.clone(), cwd.to_string(), text.to_string(), t.provider.clone(), model.clone()); let (body, imgs) = tokio::task::spawn_blocking(move || { let body = if text2.contains('$') { let ss = skills::scan_all(&skills::env_from(&host.user_home, &host.home, host.kistack.as_deref()), &cwd2); skills::prepare(&text2, &skills::for_model(&ss, &prov2, &model2), &prov2, false) } else { text2.clone() }; (body, inputs::att_paths(&text2).into_iter().filter(|p| !inputs::mime(p).is_empty()).collect::>()) }).await.unwrap_or_default(); if self.ag.stopped.load(Relaxed) || !self.ag.hub.cfg.home.exists() { return } let codex_home = if !cfg!(windows) { String::new() } @@ -1053,11 +1056,11 @@ impl Actor { else if self.ag.cli.test_mode() { String::new() } else if self.person { self.person_child().map(|pc| pc.home.join(".codex").to_string_lossy().into_owned()).unwrap_or_default() } else { std::env::var_os("CODEX_HOME").filter(|v| !v.is_empty()).map(|v| v.to_string_lossy().into_owned()).unwrap_or_else(|| std::path::Path::new(&self.ag.host.user_home).join(".codex").to_string_lossy().into_owned()) }; - let a = providers::TurnIn { thread: th.clone(), cwd: cwd.into(), home: self.ag.host.home.to_string_lossy().into_owned(), model: t.model.clone(), session, runtime: t.runtime.clone(), interaction: t.interaction.clone(), effort, think, text: body, images: imgs, prompt, mcp_url: url.clone(), pcbparts_url: String::new(), gen: gen.clone(), settings: { let w = self.ag.world().await; providers::SETTINGS.iter().map(|k| (k.to_string(), w.setting(k).to_string())).collect() }, mcp: crate::mcpx::svc::launch(&th, &t.provider, &url, cwd).await, speed: String::new(), speed_args: vec![], codex_home }; + let a = providers::TurnIn { thread: th.clone(), cwd: cwd.into(), home: self.ag.host.home.to_string_lossy().into_owned(), model: model.clone(), session, runtime: t.runtime.clone(), interaction: t.interaction.clone(), effort, think, text: body, images: imgs, prompt, mcp_url: url.clone(), pcbparts_url: String::new(), gen: gen.clone(), settings: { let w = self.ag.world().await; providers::SETTINGS.iter().map(|k| (k.to_string(), w.setting(k).to_string())).collect() }, mcp: crate::mcpx::svc::launch(&th, &t.provider, &url, cwd).await, speed: String::new(), speed_args: vec![], codex_home }; let a = providers::TurnIn { pcbparts_url: if a.mcp.pcbparts { crate::mcpx::gen::PCBPARTS.into() } else { String::new() }, ..a }; // the speed dial (agents/speed.rs): the mode the thread's model takes, passed the provider's way; recorded for the thread's usage (`turn.tier.`) let a = { let info = speed::info_now(); let want = self.ag.world().await.setting(&format!("speed.{th}")).to_string(); - let mode = speed::effective(&info, &t.provider, &t.model, &want); let how = speed::how(&info, &t.provider, &t.model, mode); + let mode = speed::effective(&info, &t.provider, &model, &want); let how = speed::how(&info, &t.provider, &model, mode); providers::TurnIn { model: how.model.unwrap_or(a.model.clone()), speed: mode.to_string(), speed_args: how.args, ..a } }; self.tier_set(&th, &a.speed, now).await; let mut driver = made.driver; @@ -1111,7 +1114,7 @@ impl Actor { self.commit(vec![set(format!("ride.{th}"), v.clone(), now)]).await; if running || !start { return Ok(()) } // a "running" Claude turn with no live process (after a restart) keeps the ride for its next start; a note alone waits for the next turn // Ride.start: an idle thread starts a turn with the waiting rides - self.cx = cx; self.cwd = cwd.clone(); self.codex = t.provider != "claude"; self.prov = t.provider.clone(); self.model = t.model.clone(); + self.cx = cx; self.cwd = cwd.clone(); self.codex = t.provider != "claude"; self.prov = t.provider.clone(); self.model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); let mut ev = codex::ride_done(&th, &v, "with a new turn", now); ev.push(json!({"$":"TurnChanged","thread":th,"state":"running","at":now})); self.commit(ev).await; self.cx.running = true; self.ag.stats.turns.fetch_add(1, Relaxed); // #1163: the folder is a repository and snapshotted before the turn's own captures and before the agent gets anything (snapguard.rs) if let Err(why) = self.ag.turn_guard_start(&th, &cwd, None).await { self.fail(why, "git", &hub_id("git", now_s(), self.ag.seq())).await; return Ok(()) } @@ -1189,8 +1192,9 @@ impl Actor { let th = self.th.clone(); let (cwd, msg, text, mut agent_text) = (cwd.to_string(), msg.to_string(), text.to_string(), agent_text.to_string()); // the thread's MCP servers are part of the key: a list changed in Settings > MCP (or by an agent) starts Claude again at its next turn, on the same session // the speed dial too: a thread turned to Fast starts Claude again at its next turn with fast mode in its settings, on the same session - let want = self.ag.world().await.setting(&format!("speed.{th}")).to_string(); let tier = speed::effective(&speed::info_now(), "claude", &t.model, &want); - let key = format!("{}|speed:{tier}|mcp:{}{}", rules::agent_key(&t.model, &t.runtime, &t.interaction, self.cx.think), crate::mcpx::svc::fingerprint(&th, "claude", &cwd).await, if self.ag.in_review(&th).await { "|review" } else { "" }); // a review runs with deny rules for design files (snapguard.rs): a change of mode starts Claude again + let model = crate::settings::models::sanitize_model_now("claude", &t.model); + let want = self.ag.world().await.setting(&format!("speed.{th}")).to_string(); let tier = speed::effective(&speed::info_now(), "claude", &model, &want); + let key = format!("{}|speed:{tier}|mcp:{}{}", rules::agent_key(&model, &t.runtime, &t.interaction, self.cx.think), crate::mcpx::svc::fingerprint(&th, "claude", &cwd).await, if self.ag.in_review(&th).await { "|review" } else { "" }); // a review runs with deny rules for design files (snapguard.rs): a change of mode starts Claude again self.tier_set(&th, tier, now).await; self.cx.tier_want = tier.to_string(); self.cx.tier = tier.to_string(); // a live process with a command still open (a turn in flight) is never replaced for a changed model/mode key: the message goes on its input (the CLI queues it) and the new key applies from the next process // infinite context (agents/recall.rs): a new turn (no command open: a message into a running turn goes on its input) starts a fresh session with the view @@ -1213,7 +1217,6 @@ impl Actor { let steer = std::mem::take(&mut self.steer_now); let bound = { let raw = self.ag.hub.setting(&crate::settings::accounts::binding_key(&th, "claude")).await.unwrap_or_default(); !serde_json::from_str::(&raw).ok().map_or(String::new(), |b| b["id"].as_str().unwrap_or("").to_string()).is_empty() }; let isolated = self.person || bound; // an account profile or the person mode runs Claude without the person's own skills and plugins - let model = t.model.clone(); let line = { let (text2, cwd2, host, uuid2) = (agent_text.clone(), cwd.clone(), self.ag.host.clone(), uuid.clone()); // Media.claude: images read, `$skill` mentions made real tokio::task::spawn_blocking(move || { let body = if text2.contains('$') { let ss = skills::scan_all(&skills::env_from(&host.user_home, &host.home, host.kistack.as_deref()), &cwd2); skills::prepare(&text2, &skills::for_model(&ss, "claude", &model), "claude", isolated) } else { text2.clone() }; let imgs = inputs::read_images(&text2); inputs::claude_line_p(&body, &imgs, &uuid2, steer) }).await.unwrap_or_default() }; let sent = self.live_proc.as_ref().map(|p| p.input.try_send(line)); @@ -1376,17 +1379,18 @@ impl Actor { } if std::mem::take(&mut self.recall_fresh) { session = String::new(); self.handover = false; } // a new turn with infinite context: a fresh session, the view goes with its message let gen = format!("{now}-{}", self.ag.seq()); // Hub.gen: the process's generation, which its MCP URL names - let prompt = self.ag.prompt_context(&th, cwd, &t.provider, &t.model, self.person || !acct_env.is_empty()).await.text(); + let model = crate::settings::models::sanitize_model_now("claude", &t.model); + let prompt = self.ag.prompt_context(&th, cwd, &t.provider, &model, self.person || !acct_env.is_empty()).await.text(); if self.ag.stopped.load(Relaxed) || !self.ag.hub.cfg.home.exists() { return Err("agents shut down".into()) } let own: Vec = self.ag.host.kistack.iter().chain(self.ag.host.bundled.iter()).map(|k| k.to_string_lossy().into_owned()).collect(); // KiStack's and Backplane's own skills let mut dirs = own.clone(); dirs.push(self.ag.host.home.join("attachments").to_string_lossy().into_owned()); let plugins = own; let (effort, think, want) = { let w = self.ag.world().await; (w.setting(&format!("effort.{th}")).to_string(), self.cx.think, w.setting(&format!("speed.{th}")).to_string()) }; - let speed = speed::effective(&speed::info_now(), "claude", &t.model, &want); + let speed = speed::effective(&speed::info_now(), "claude", &model, &want); let url = self.ag.mcp.get().map(|m| m.url(&th, &gen)).unwrap_or_default(); let mcp = crate::mcpx::svc::launch(&th, "claude", &url, cwd).await; let mut disallowed = mcp.disallowed.clone(); if self.ag.in_review(&th).await { disallowed.extend(snapguard::CLAUDE_DENY.iter().map(|x| x.to_string())) } // a review's design files are read-only to Claude's own tools too - let mut args = rules::claude_args(&rules::ArgsIn { model: &t.model, session: &session, runtime: &t.runtime, interaction: &t.interaction, prompt: &prompt, dirs: &dirs, effort: &effort, think, plugins: &plugins, mcp_url: &url, mcp_json: &mcp.claude, disallowed: &disallowed, speed }); + let mut args = rules::claude_args(&rules::ArgsIn { model: &model, session: &session, runtime: &t.runtime, interaction: &t.interaction, prompt: &prompt, dirs: &dirs, effort: &effort, think, plugins: &plugins, mcp_url: &url, mcp_json: &mcp.claude, disallowed: &disallowed, speed }); let mut keep = vec![]; // the files Claude reads at its start, removed when it ends // the MCP config holds the thread's key: on every platform it goes in a private file, never on the command line (`/proc//cmdline` is world-readable on Linux, F-009) { let name: String = th.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' }).collect(); diff --git a/native/host/src/agents/tasks.rs b/native/host/src/agents/tasks.rs index 218c2c8e59..0d1b29a243 100644 --- a/native/host/src/agents/tasks.rs +++ b/native/host/src/agents/tasks.rs @@ -29,7 +29,8 @@ impl Agents { let asked = if s(a, "provider").is_empty() { if a.get("account").is_some() && !s(a, "account").eq_ignore_ascii_case("default") { String::new() } else { t.provider.clone() } } else { s(a, "provider").to_string() }; let chosen = match self.account_arg(a, &asked).await { Ok(c) => c, Err(e) => return fail(&e) }; let provider = chosen.as_ref().map(|c| c.provider.clone()).unwrap_or(if asked.is_empty() { t.provider.clone() } else { asked }); - let model = if !s(a, "model").is_empty() { s(a, "model").to_string() } else if provider == t.provider { t.model.clone() } else { String::new() }; + let raw_model = if !s(a, "model").is_empty() { s(a, "model").to_string() } else if provider == t.provider { t.model.clone() } else { String::new() }; + let model = crate::settings::models::sanitize_model_now(&provider, &raw_model); if provider != "claude" && super::providers::driver(&provider).is_none() { return fail(&format!("{provider} threads are not run by the Rust hub yet")) } let (now, seq) = (now_s(), self.seq_n()); let (task, child, depth1) = (hub_id("k", now, seq), hub_id("t", now, seq + 1), depth + 1); diff --git a/native/host/src/agents/tools.rs b/native/host/src/agents/tools.rs index 9954317442..f9dc87c5c5 100644 --- a/native/host/src/agents/tools.rs +++ b/native/host/src/agents/tools.rs @@ -126,7 +126,8 @@ impl Agents { let (from, was_model, running) = { let w = self.world().await; match w.threads.get(target) { Some(t) => (t.provider.clone(), t.model.clone(), w.running(target)), None => return fail("No such thread.") } }; let to = { let p = sv(a, "provider").trim().to_lowercase(); if p.is_empty() { from.clone() } else { p } }; if to != "claude" && super::providers::driver(&to).is_none() { return fail(&format!("{to} is not a provider this hub runs (orchestrator_capabilities lists them)")) } - let model = match a.get("model") { Some(Value::String(m)) => m.trim().to_string(), Some(Value::Null) | None => if to == from { was_model.clone() } else { String::new() }, Some(_) => return fail("model is a string (empty for the provider's default)") }; + let raw_model = match a.get("model") { Some(Value::String(m)) => m.trim().to_string(), Some(Value::Null) | None => if to == from { was_model.clone() } else { String::new() }, Some(_) => return fail("model is a string (empty for the provider's default)") }; + let model = crate::settings::models::sanitize_model_now(&to, &raw_model); if running { return fail(if target == thread { "a thread's provider and model change between turns, and this is its turn: ask from another thread, or the person, once it ends" } else { "a provider changes between turns: that thread is running; thread_interrupt it first, or wait for its turn to end" }) } if to != from || model != was_model { let Some(h) = self.hub.rpc_for("thread.provider") else { return fail("switching providers is not available") }; @@ -235,14 +236,16 @@ impl Agents { if implement { if let Some(t) = t { let rt = if t.runtime.is_empty() { "full-access".to_string() } else { t.runtime.clone() }; - ev.push(json!({"$":"ModesSet","id":th,"runtime":rt,"interaction":"default","model":t.model,"at":now})); + let model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); + ev.push(json!({"$":"ModesSet","id":th,"runtime":rt,"interaction":"default","model":model,"at":now})); } if had_once { ev.push(json!({"$":"SettingSet","key":format!("plan.once.{th}"),"value":"","at":now})) } if !th.is_empty() { ev.push(json!({"$":"SettingSet","key":format!("plan.executing.{th}"),"value":"1","at":now})) } } else if let Some(ref fb) = revise { if let Some(t) = t { let rt = if t.runtime.is_empty() { "full-access".to_string() } else { t.runtime.clone() }; - ev.push(json!({"$":"ModesSet","id":th,"runtime":rt,"interaction":"plan","model":t.model,"at":now})); + let model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); + ev.push(json!({"$":"ModesSet","id":th,"runtime":rt,"interaction":"plan","model":model,"at":now})); if (had_ask_once || had_once) && !th.is_empty() { let flag = if t.turn == "running" { "2" } else { "1" }; ev.push(json!({"$":"SettingSet","key":format!("plan.once.{th}"),"value":flag,"at":now})); diff --git a/native/host/src/agents/wake.rs b/native/host/src/agents/wake.rs index 61387ce8ed..2727f41122 100644 --- a/native/host/src/agents/wake.rs +++ b/native/host/src/agents/wake.rs @@ -248,7 +248,10 @@ pub async fn plan_once_end(ag: &Arc, th: &str) { let (Some(next), Some(t)) = (next, t) else { return }; let now = now_s(); let mut ev = vec![json!({"$":"SettingSet","key":format!("plan.once.{th}"),"value":next,"at":now})]; - if next.is_empty() && t.interaction == "plan" { ev.push(json!({"$":"ModesSet","id":th,"runtime":if t.runtime.is_empty() { "full-access".to_string() } else { t.runtime.clone() },"interaction":"default","model":t.model,"at":now})) } + if next.is_empty() && t.interaction == "plan" { + let model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); + ev.push(json!({"$":"ModesSet","id":th,"runtime":if t.runtime.is_empty() { "full-access".to_string() } else { t.runtime.clone() },"interaction":"default","model":model,"at":now})) + } ag.commit_events(ev).await; } #[cfg(test)] diff --git a/native/host/src/bin/screen-audit.rs b/native/host/src/bin/screen-audit.rs index 2d8ed5338e..6f68effbaf 100644 --- a/native/host/src/bin/screen-audit.rs +++ b/native/host/src/bin/screen-audit.rs @@ -24,8 +24,9 @@ mod session { pub use crate::{composer, patch, select, pages}; } #[path="../present/tz.rs"] mod tz; #[path="../present/keys.rs"] mod keys; #[path="../settings/order_view.rs"] mod order_view; +#[path="../settings/model_compat.rs"] mod model_compat; // the speed dial's table (agents/speed.rs) asks for the detected models; the audit counts screens and detects none -mod settings { pub mod order { pub use crate::order_view::*; } pub mod models { pub fn info() -> String { String::new() } } } +mod settings { pub mod order { pub use crate::order_view::*; } pub mod models { pub fn info() -> String { String::new() } pub use crate::model_compat::{model_compatible, sanitize_model}; } } #[path="../present/thread.rs"] mod thread; #[path="../present/window.rs"] mod window; #[path="../present/audit_files.rs"] mod files; diff --git a/native/host/src/bots/rpc.rs b/native/host/src/bots/rpc.rs index 86495ebf8c..865d9bf636 100644 --- a/native/host/src/bots/rpc.rs +++ b/native/host/src/bots/rpc.rs @@ -220,7 +220,10 @@ impl Bots { if !name_ok(&name) { return vec![err(id, "a bot's name is 1 to 24 letters, digits, - or _")] } let w = self.world().await; if w.named(&name).is_some() { return vec![err(id, &format!("a bot named {name} already exists"))] } - let (provider, model) = (gsd(p, "provider", &crate::settings::models::default_now(&w.setting("agent.provider", "claude"), "")).to_string(), gsd(p, "model", &w.setting("agent.model", "")).to_string()); + let default_prov = crate::settings::models::default_now(&w.setting("agent.provider", "claude"), ""); + let provider = gsd(p, "provider", &default_prov).to_string(); + let default_model = if gs(p, "provider").is_empty() || provider == default_prov { w.setting("agent.model", "") } else { String::new() }; + let model = crate::settings::models::sanitize_model_now(&provider, gsd(p, "model", &default_model)); let (bot, th) = (self.id("b", now), self.id("t", now)); // the cat: a look given is the person's pick (kept whatever the name), else the name's; `color` the fur's ("#rrggbb", "" the coat's own) let (look, auto) = match gnat(p, "look") { Some(l) => (l % super::cat::LOOKS, false), None => (super::cat::look_of(&name), true) }; diff --git a/native/host/src/bots/swarm.rs b/native/host/src/bots/swarm.rs index 837557fef3..ea9a11976b 100644 --- a/native/host/src/bots/swarm.rs +++ b/native/host/src/bots/swarm.rs @@ -472,8 +472,9 @@ impl Bots { let Some(project) = project else { return fail("name the swarm's project (project_list)") }; let rid = self.id("r", now); let mut taken: Vec = vec![]; let mut plan = vec![]; let mut evs = vec![]; for (i, m) in ms.iter().enumerate() { - let (prov, model, role) = (gs(m, "provider"), gs(m, "model"), gs(m, "role")); - let nm = gate::short_name(role, prov, model, &taken); taken.push(nm.clone()); + let (prov, raw_model, role) = (gs(m, "provider"), gs(m, "model"), gs(m, "role")); + let model = crate::settings::models::sanitize_model_now(prov, raw_model); + let nm = gate::short_name(role, prov, &model, &taken); taken.push(nm.clone()); let tid = self.id("t", now); let key = format!("{THREAD}{tid}"); evs.push(json!({"$":"SettingSet","key":format!("room.member.{rid}.{key}"),"value":json!({"name":nm,"color":gate::color(i),"role":role,"provider":prov,"model":model}).to_string(),"at":now})); plan.push((tid, nm, m.clone())); @@ -494,7 +495,8 @@ impl Bots { for (tid, nm, m) in &plan { let peers: Vec = names.iter().filter(|x| *x != nm).cloned().collect(); let mut prompt = brief(&topic, &rid, &goal, nm, gs(m, "role"), &peers, false); if !seed.is_empty() { prompt.push_str(&format!("\n\nTo start with:\n{seed}")) } - let mut args = json!({"project":project,"prompt":prompt,"provider":gs(m, "provider"),"model":gs(m, "model"),"title":format!("{topic} · {nm}"),"subthread":false,"report":false,"_id":tid}); + let model = crate::settings::models::sanitize_model_now(gs(m, "provider"), gs(m, "model")); + let mut args = json!({"project":project,"prompt":prompt,"provider":gs(m, "provider"),"model":model,"title":format!("{topic} · {nm}"),"subthread":false,"report":false,"_id":tid}); if !gs(m, "account").is_empty() { args["account"] = m["account"].clone() } match self.inbox.launch(by, args).await { Ok(t) if &t == tid => started.push(json!({"thread":t,"name":nm})), Ok(t) => failed.push(format!("{nm}: started as {t}, not the id the room lists")), Err(e) => failed.push(format!("{nm}: {e}")) } } @@ -581,16 +583,17 @@ impl Bots { (true, json!({"room":r.id,"removed":th})) } "add" => { if r.members.len() >= MAX_MEMBERS { return fail(&format!("a swarm has at most {MAX_MEMBERS} members")) } let m = a.get("member").cloned().unwrap_or_else(|| json!({"provider":gs(a, "provider"),"model":gs(a, "model"),"role":gs(a, "role")})); + let (prov, model) = (gs(&m, "provider"), crate::settings::models::sanitize_model_now(gs(&m, "provider"), gs(&m, "model"))); let taken: Vec = names(&w, &r).into_iter().map(|x| x.1).collect(); - let nm = gate::short_name(gs(&m, "role"), gs(&m, "provider"), gs(&m, "model"), &taken); + let nm = gate::short_name(gs(&m, "role"), prov, &model, &taken); let tid = self.id("t", now); let key = format!("{THREAD}{tid}"); let ann = self.guard_post(&r.id, &format!("{nm} joined the swarm (added by {who})."), &[], true, now); let ann_id = gs(&ann, "id").to_string(); let ev = vec![r.set_ev(now, |x| x.members.push(key.clone())), - json!({"$":"SettingSet","key":format!("room.member.{}.{key}", r.id),"value":json!({"name":nm,"color":gate::color(r.members.len()),"role":gs(&m, "role"),"provider":gs(&m, "provider"),"model":gs(&m, "model")}).to_string(),"at":now}), + json!({"$":"SettingSet","key":format!("room.member.{}.{key}", r.id),"value":json!({"name":nm,"color":gate::color(r.members.len()),"role":gs(&m, "role"),"provider":prov,"model":model}).to_string(),"at":now}), json!({"$":"SettingSet","key":format!("room.joined.{}.{key}", r.id),"value":ann_id,"at":now}), ann]; if let Err(e) = self.hub.commit_many(&w.also(now, ev)).await { return fail(&format!("{e:#}")) } let project = r.project.clone(); drop(w); { let _w = self.world().await; } - let mut args = json!({"project":project,"prompt":brief(&r.name, &r.id, &r.goal, &nm, gs(&m, "role"), &taken, true),"provider":gs(&m, "provider"),"model":gs(&m, "model"),"title":format!("{} · {nm}", r.name),"subthread":false,"report":false,"_id":tid}); + let mut args = json!({"project":project,"prompt":brief(&r.name, &r.id, &r.goal, &nm, gs(&m, "role"), &taken, true),"provider":prov,"model":model,"title":format!("{} · {nm}", r.name),"subthread":false,"report":false,"_id":tid}); if !gs(&m, "account").is_empty() { args["account"] = m["account"].clone() } match self.inbox.launch(&r.by, args).await { Ok(t) => (true, json!({"room":r.id,"thread":t,"name":nm})), Err(e) => { let w = self.world().await; if let Some(r2) = w.room(&r.id).cloned() { let _ = self.hub.commit_many(&w.also(now_s(), vec![r2.set_ev(now_s(), |x| x.members.retain(|m| m != &key))])).await; } diff --git a/native/host/src/bots/tools.rs b/native/host/src/bots/tools.rs index 1c46b919f2..f3a011368d 100644 --- a/native/host/src/bots/tools.rs +++ b/native/host/src/bots/tools.rs @@ -338,7 +338,8 @@ impl Bots { if w.named(&name).is_some() { return fail(&format!("a bot named {name} already exists")) } let (bot, th) = (self.hub_id("b", now), self.hub_id("t", now)); let provider = { let p = gs(a, "provider"); if p.is_empty() { self.hub.model().await.threads.get(&b.thread).map(|t| t.provider.clone()).unwrap_or_default() } else { p.to_string() } }; - let evs = vec![json!({"$":"ThreadCreated","id":th,"project":"","title":name,"env":"local","branch":"","worktree":"","provider":provider,"model":gs(a, "model"),"at":now}), + let model = crate::settings::models::sanitize_model_now(&provider, gs(a, "model")); + let evs = vec![json!({"$":"ThreadCreated","id":th,"project":"","title":name,"env":"local","branch":"","worktree":"","provider":provider,"model":model,"at":now}), super::catrig::with(json!({"$":"BotSet","id":bot,"name":name,"thread":th,"look":super::cat::look_of(&name),"persona":gs(a, "persona"),"at":now}), super::cat::look_of(&name), true, ""), json!({"$":"SettingSet","key":format!("bot.parent.{bot}"),"value":b.id,"at":now})]; let evs = self.accounts_created(evs).await; diff --git a/native/host/src/bots/uber.rs b/native/host/src/bots/uber.rs index f64f59bcb7..6296f90ed0 100644 --- a/native/host/src/bots/uber.rs +++ b/native/host/src/bots/uber.rs @@ -201,7 +201,8 @@ impl Bots { let (look, auto, color) = super::catrig::of_event(&json!({"name": name, "look": look, "auto": offer["auto"], "color": offer["color"]})); if !super::rpc::name_ok(&name) || w.named(&name).is_some() { return vec![err(id, &format!("this machine has a bot called {name} already; rename it first"))] } let (bot, th) = (self.hub_id("b", now), self.hub_id("t", now)); - let (provider, model) = (crate::settings::models::default_now(&w.setting("agent.provider", "claude"), ""), w.setting("agent.model", "")); + let provider = crate::settings::models::default_now(&w.setting("agent.provider", "claude"), ""); + let model = crate::settings::models::sanitize_model_now(&provider, &w.setting("agent.model", "")); let mut ev = vec![json!({"$":"ThreadCreated","id":th,"project":"","title":name,"env":"local","branch":"","worktree":"","provider":provider,"model":model,"at":now}), super::catrig::with(json!({"$":"BotSet","id":bot,"name":name,"thread":th,"look":look,"persona":"","at":now}), look, auto, &color), json!({"$":"UberSet","bot":bot,"uid":uid,"at":now}), json!({"$":"SettingSet","key":"uber.offer","value":"","at":now})]; diff --git a/native/host/src/commands/give.rs b/native/host/src/commands/give.rs index 1c0934a5cf..dc51c820c2 100644 --- a/native/host/src/commands/give.rs +++ b/native/host/src/commands/give.rs @@ -80,6 +80,7 @@ async fn run(hub: &Arc, who: &Caller, job: Job) -> Result<(), String> { '>' => send(to.clone(), vec![handoff::card_event(to, &format!("{act}.in"), at, &card), said(src, &act, &format!("\"{name}\""), at)]).await, '%' => { let Some(h) = hub.rpc_for("thread.create") else { continue }; + let model = crate::settings::models::sanitize_model_now(&provider, &model); let r = h.call(hub, who, &json!(0), "thread.create", &json!({"project": to, "title": title, "provider": provider, "model": model})).await.into_iter().next().unwrap_or(Value::Null); let Some(th) = r["thread"].as_str().filter(|_| r["ok"] == true).map(str::to_string) else { failed = r["error"].as_str().unwrap_or("the new thread could not be made").to_string(); continue }; let modes = json!({"$":"ModesSet","id":th,"runtime":if runtime.is_empty() { "full-access" } else { &runtime },"interaction":if interaction.is_empty() { "default" } else { &interaction },"model":model,"at":at}); diff --git a/native/host/src/commands/plan.rs b/native/host/src/commands/plan.rs index 7edceebbd8..7e7c931932 100644 --- a/native/host/src/commands/plan.rs +++ b/native/host/src/commands/plan.rs @@ -289,8 +289,12 @@ fn create(f: &Fold, at: u64, id: &Value, p: &Value, new_root: Option<(&str, usiz let gs = |k: &str, d: &str| p.get(k).and_then(Value::as_str).unwrap_or(d).to_string(); let env = gs("env", f.get("thread.env", "auto")); let title = gs("title", "New thread"); - let provider = gs("provider", f.default_agent.as_deref().unwrap_or(f.get("agent.provider", "claude"))); - let model = gs("model", f.get("agent.model", "")); + let default_prov = f.default_agent.as_deref().unwrap_or(f.get("agent.provider", "claude")); + let explicit_prov = p.get("provider").and_then(Value::as_str); + let provider = explicit_prov.unwrap_or(default_prov).to_string(); + let default_model = if explicit_prov.is_some_and(|x| x != default_prov) { "" } else { f.get("agent.model", "") }; + let raw_model = p.get("model").and_then(Value::as_str).unwrap_or(default_model); + let model = crate::settings::models::sanitize_model_now(&provider, raw_model); let mode = if scratch || env == "local" { "local" } else { "worktree" }; let wt = if scratch { format!("{root}/{th}") } else { String::new() }; let mut ev = vec![json!({"$":"ThreadCreated","id":th,"project":project,"title":title,"env":mode,"branch":"","worktree":wt,"provider":provider,"model":model,"at":at})]; @@ -335,7 +339,8 @@ fn hold(f: &Fold, th: &str, at: u64) -> Vec { fn modes(f: &Fold, at: u64, id: &Value, p: &Value) -> Option { let th = s(p, "thread", ""); let t = f.threads.get(&th).cloned().unwrap_or_default(); let (rt, im, mo) = (if t.runtime.is_empty() { "full-access".to_string() } else { t.runtime.clone() }, if t.interaction.is_empty() { "default".to_string() } else { t.interaction.clone() }, t.model.clone()); - let mut ev = vec![json!({"$":"ModesSet","id":th,"runtime":runtime_of(&s(p, "runtime", &rt)),"interaction":if s(p, "interaction", &im) == "plan" { "plan" } else { "default" },"model":s(p, "model", &mo),"at":at})]; + let model = crate::settings::models::sanitize_model_now(&t.provider, &s(p, "model", &mo)); + let mut ev = vec![json!({"$":"ModesSet","id":th,"runtime":runtime_of(&s(p, "runtime", &rt)),"interaction":if s(p, "interaction", &im) == "plan" { "plan" } else { "default" },"model":model,"at":at})]; if p.get("interaction").is_some() && !f.setting(&format!("plan.once.{th}")).is_empty() { ev.push(json!({"$":"SettingSet","key":format!("plan.once.{th}"),"value":"","at":at})) } if p.get("model").is_some() { ev.extend(hold(f, &th, at)) } done(ev, id) @@ -382,9 +387,10 @@ fn buy(f: &Fold, at: u64, id: &Value, src: &str, b: &Buy) -> Option { let th = hub_id("t", at, f.n()); // the same folder, as a delegated task has; a source with no worktree of its own runs in the project folder, and a thread marked worktree with none would wait for one forever let env = if t.worktree.is_empty() { "local" } else { t.env.as_str() }; - let mut ev = vec![json!({"$":"ThreadCreated","id":th,"project":t.project,"title":buy_title(f, &t.project),"env":env,"branch":t.branch,"worktree":t.worktree,"provider":t.provider,"model":t.model,"at":at})]; + let model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); + let mut ev = vec![json!({"$":"ThreadCreated","id":th,"project":t.project,"title":buy_title(f, &t.project),"env":env,"branch":t.branch,"worktree":t.worktree,"provider":t.provider,"model":model,"at":at})]; ev.extend(account_created(f, &th, &t.provider, at)); ev.extend(account_forked(f, &th, src, at)); - ev.extend([json!({"$":"ModesSet","id":th,"runtime":if t.runtime.is_empty() { "full-access" } else { &t.runtime },"interaction":if t.interaction.is_empty() { "default" } else { &t.interaction },"model":t.model,"at":at}), + ev.extend([json!({"$":"ModesSet","id":th,"runtime":if t.runtime.is_empty() { "full-access" } else { &t.runtime },"interaction":if t.interaction.is_empty() { "default" } else { &t.interaction },"model":model,"at":at}), json!({"$":"SettingSet","key":format!("buy.{th}"),"value":src,"at":at}), json!({"$":"SettingSet","key":format!("buy.last.{src}"),"value":th,"at":at})]); Some(Plan { events: ev, reply: made(id, &th), stop: None, wt: None, scratch: None, act: Some(("post", th, "Buy it".to_string())) }) } @@ -395,11 +401,12 @@ fn fork(f: &Fold, at: u64, id: &Value, src: &str, cx: &Ctx) -> Option { let scratch = t.project == "scratch"; let root = f.projects.get(&t.project).map(|x| x.root.clone()).unwrap_or_default(); let env = if scratch || t.worktree.is_empty() { "local" } else { "worktree" }; let why = format!("This thread is a fork of \"{}\" ({src}). You continue its work from where it stands; its conversation so far, oldest first:", t.title); + let model = crate::settings::models::sanitize_model_now(&t.provider, &t.model); let mut ev = vec![ - json!({"$":"ThreadCreated","id":th,"project":t.project,"title":format!("Fork: {}", t.title),"env":env,"branch":"","worktree":if scratch { format!("{root}/{th}") } else { String::new() },"provider":t.provider,"model":t.model,"at":at})]; + json!({"$":"ThreadCreated","id":th,"project":t.project,"title":format!("Fork: {}", t.title),"env":env,"branch":"","worktree":if scratch { format!("{root}/{th}") } else { String::new() },"provider":t.provider,"model":model,"at":at})]; ev.extend(account_created(f, &th, &t.provider, at)); ev.extend([ - json!({"$":"ModesSet","id":th,"runtime":if t.runtime.is_empty() { "full-access" } else { &t.runtime },"interaction":if t.interaction.is_empty() { "default" } else { &t.interaction },"model":t.model,"at":at}), + json!({"$":"ModesSet","id":th,"runtime":if t.runtime.is_empty() { "full-access" } else { &t.runtime },"interaction":if t.interaction.is_empty() { "default" } else { &t.interaction },"model":model,"at":at}), json!({"$":"ThreadForked","id":th,"source":src,"at":at})]); ev.extend(account_forked(f, &th, src, at)); ev.extend([ @@ -431,6 +438,7 @@ fn switch(f: &Fold, at: u64, id: &Value, p: &Value, cx: &Ctx, auto: bool) -> Opt let from = f.threads.get(&th).map(|t| t.provider.clone()).unwrap_or_default(); // back to the provider the failover order moved it off, with no model named (Nov 11, Bub): the very model the thread asked for there, never the provider's default if model.is_empty() && from != to { let asked = crate::settings::fallback::Target::parse(f.setting(&format!("fallback.intent.{th}"))); if asked.provider == to { model = asked.model } } + model = crate::settings::models::sanitize_model_now(&to, &model); if running(f, &th) { return Some(Plan { events: vec![], reply: err(id, "a provider changes between turns: stop this one first"), stop: None, wt: None, scratch: None, act: None }) } // the same agent: the model and effort it names, if any (a picker that pressed an agent and then a model before it heard the first back asks this way) if from == to { diff --git a/native/host/src/commands/tests.rs b/native/host/src/commands/tests.rs index 5fea8c464e..d168ebbaea 100644 --- a/native/host/src/commands/tests.rs +++ b/native/host/src/commands/tests.rs @@ -714,3 +714,46 @@ async fn ask_on(h: &Arc, c: &mut crate::hub::Conn, m: &str, p: Value) -> (V assert_eq!(r2["errorCode"], crate::settings::provider_notice::SEND_GUARD_CODE); assert!(ev2.is_empty(), "refused project.start must log zero events: {ev2:?}"); } + +#[tokio::test] async fn mismatched_provider_and_model_are_sanitized_everywhere() { + let h = hub("mismatch").await; + // Persisted codex + opus (exact bug state) -> thread.create clears model to "" + h.commit(&json!({"$":"SettingSet","key":"agent.provider","value":"codex","at":9})).await.unwrap(); + h.commit(&json!({"$":"SettingSet","key":"agent.model","value":"opus","at":9})).await.unwrap(); + let (e, r) = ask(&h, "thread.create", json!({"project":"p1"})).await; + assert_eq!(r["ok"], true); + assert_eq!(e[0]["provider"], "codex"); + assert_eq!(e[0]["model"], "", "persisted codex+opus must sanitize to default"); + + // claude + opus default, explicit provider: "codex" -> must NOT inherit opus + h.commit(&json!({"$":"SettingSet","key":"agent.provider","value":"claude","at":10})).await.unwrap(); + let (e, r) = ask(&h, "thread.create", json!({"project":"p1","provider":"codex"})).await; + assert_eq!(r["ok"], true); + assert_eq!(e[0]["provider"], "codex"); + assert_eq!(e[0]["model"], "", "explicit codex must not inherit claude agent.model"); + + // Explicit thread.create {provider: "codex", model: "opus"} -> sanitized to "" + let (e, r) = ask(&h, "thread.create", json!({"project":"p1","provider":"codex","model":"opus"})).await; + assert_eq!(r["ok"], true); + let th_codex = r["thread"].as_str().unwrap().to_string(); + assert_eq!(e[0]["provider"], "codex"); + assert_eq!(e[0]["model"], "", "explicit codex+opus sanitized"); + h.commit_many(&e).await.unwrap(); + + // thread.modes with "opus" on a codex thread -> sanitized to "" + let (e, r) = ask(&h, "thread.modes", json!({"thread": th_codex, "model": "opus"})).await; + assert_eq!(r["ok"], true); + assert_eq!(e[0]["model"], "", "thread.modes must sanitize opus on codex"); + + // thread.provider switching to codex with model "opus" -> sanitized to "" + let (e, r) = ask(&h, "thread.provider", json!({"thread": "t1", "provider": "codex", "model": "opus"})).await; + assert_eq!(r["ok"], true); + assert_eq!(e.iter().find(|x| x["$"] == "ProviderSet").unwrap()["model"], "", "thread.provider must sanitize opus on codex"); + + // thread.fork on a persisted codex + opus thread -> fork gets model "" + h.commit(&json!({"$":"ThreadCreated","id":"tbad","project":"p1","title":"Bad","env":"local","branch":"","worktree":"","provider":"codex","model":"opus","at":11})).await.unwrap(); + let (e, r) = ask(&h, "thread.fork", json!({"thread": "tbad"})).await; + assert_eq!(r["ok"], true); + assert_eq!(e[0]["provider"], "codex"); + assert_eq!(e[0]["model"], "", "fork of persisted codex+opus clears model"); +} diff --git a/native/host/src/data/ext.rs b/native/host/src/data/ext.rs index 1c0a6360c7..2cc4bd05d4 100644 --- a/native/host/src/data/ext.rs +++ b/native/host/src/data/ext.rs @@ -61,10 +61,11 @@ async fn picker(hub: &Arc, p: &Value) -> Result { let setting = |k: &str| crate::statehost::policies().and_then(|x| x.with_state(|st| st.settings.get(k).cloned())).flatten().unwrap_or_default(); let pick = |k: &str, dflt: String| if p.get(k).is_some() { s(p, k).to_string() } else if th.is_empty() { dflt } else { s(&now, k).to_string() }; let provider = pick("provider", { let d = crate::settings::models::default_now(&setting("agent.provider"), &setting("accounts.inventory")); if d.is_empty() { "claude".into() } else { d } }); - let model = pick("model", if p.get("provider").is_some() { String::new() } else { setting("agent.model") }); + let raw_model = pick("model", if p.get("provider").is_some() { String::new() } else { setting("agent.model") }); // a thread's own account's catalog (the one the desktop's picker lists) over the hub's detected list let info: Value = serde_json::from_str(&crate::settings::models::info()).unwrap_or(Value::Null); let info = if !th.is_empty() && p.get("provider").is_none() { crate::statehost::policies().and_then(|x| x.with_state(|st| crate::present::keys::info_for_thread(st, th, &info))).unwrap_or(info) } else { info }; + let model = crate::settings::models::sanitize_model(&provider, &raw_model, info.is_object().then_some(&info)); let models: Value = serde_json::from_str(&crate::settings::models::all_of(&info)).unwrap_or(Value::Null); let mut out = picker_sections_of(&info, &models, &provider, &model, &pick("effort", String::new()), &pick("speed", String::new()), &pick("runtime", "approval-required".into())); // a thread's: its account and what that has left, the one chip's words as the desktop draws it (a new thread has no account yet) diff --git a/native/host/src/data/mod.rs b/native/host/src/data/mod.rs index 08e9cebc23..34d2254abb 100644 --- a/native/host/src/data/mod.rs +++ b/native/host/src/data/mod.rs @@ -159,7 +159,8 @@ fn thread_json(hub: &Hub, m: &crate::model::Model, id: &str, asks: &HashMap (String, u64) { + if let Some(ev) = out.iter().find(|e| e["key"].as_str() == Some(k)) { + return ( + ev["value"].as_str().unwrap_or("").to_string(), + ev["at"].as_u64().unwrap_or(0), + ); + } + local + .get(k) + .map(|e| (e.value.clone(), e.at)) + .unwrap_or_default() + }; + let (eff_prov_raw, eff_prov_at) = effective("agent.provider"); + let eff_prov = if eff_prov_raw.is_empty() { "claude" } else { eff_prov_raw.as_str() }; + let (eff_model, eff_model_at) = effective("agent.model"); + let info = crate::settings::models::info_value(); + if !eff_model.is_empty() + && !crate::settings::models::model_compatible(eff_prov, &eff_model, Some(&info)) + { + out.retain(|e| e["key"].as_str() != Some("agent.model")); + if local.get("agent.model").is_some_and(|e| { + !e.value.is_empty() + && !crate::settings::models::model_compatible(eff_prov, &e.value, Some(&info)) + }) { + out.push(json!({ + "$": "SettingSet", + "key": "agent.model", + "value": "", + "at": eff_prov_at.max(eff_model_at), + })); + } + } out } @@ -357,6 +389,31 @@ mod tests { assert!(evs.iter().any(|e| e["key"] == "agent.model" && e["value"] == "opus" && e["at"] == 50)); } + #[test] + fn merge_drops_or_clears_incompatible_agent_model_when_provider_is_codex() { + let mut local = BTreeMap::new(); + local.insert("agent.provider".into(), Entry { value: "codex".into(), at: 200 }); + local.insert("agent.model".into(), Entry { value: "opus".into(), at: 100 }); + let mut remote = BTreeMap::new(); + remote.insert("agent.model".into(), Entry { value: "opus".into(), at: 150 }); + let evs = merge(&local, &remote); + assert!(evs.iter().any(|e| e["key"] == "agent.model" && e["value"] == ""), "{evs:?}"); + + let mut local2 = BTreeMap::new(); + local2.insert("agent.provider".into(), Entry { value: "codex".into(), at: 200 }); + let evs2 = merge(&local2, &remote); + assert!(!evs2.iter().any(|e| e["key"] == "agent.model" && e["value"] == "opus"), "{evs2:?}"); + + // Remote incompatible model must NOT wipe a compatible local model + let mut local3 = BTreeMap::new(); + local3.insert("agent.provider".into(), Entry { value: "codex".into(), at: 200 }); + local3.insert("agent.model".into(), Entry { value: "gpt-6.1-sol".into(), at: 210 }); + let mut remote3 = BTreeMap::new(); + remote3.insert("agent.model".into(), Entry { value: "opus".into(), at: 250 }); + let evs3 = merge(&local3, &remote3); + assert!(!evs3.iter().any(|e| e["key"] == "agent.model"), "compatible local model must be preserved: {evs3:?}"); + } + #[tokio::test(flavor = "multi_thread")] async fn two_hub_settings_sync_round_trip_and_offline_catchup() { let (_da, a) = start("a").await; diff --git a/native/host/src/present/keys.rs b/native/host/src/present/keys.rs index 70498cd796..843148dd7d 100644 --- a/native/host/src/present/keys.rs +++ b/native/host/src/present/keys.rs @@ -210,12 +210,14 @@ pub fn combo(snapshot: &Value, provider: &str, model: &str, effort: &str, speed: /// The combined chip of a thread (`combo`), from the state. pub fn combo_of(st: &State, id: &str, now_s: u64) -> Value { let Some(t) = st.threads.get(id) else { return Value::Null }; + let info = crate::agents::speed::info_now(); + let model = crate::settings::models::sanitize_model(&t.provider, &t.model, info.is_object().then_some(&info)); let snap = allowance_of(st, id, &t.provider); let acct = account_of(st, id, &t.provider, &snap); let effort = st.settings.get(&format!("effort.{id}")).map(String::as_str).unwrap_or(""); let want = st.settings.get(&format!("speed.{id}")).map(String::as_str).unwrap_or(""); - let speed = if want.is_empty() { "" } else { crate::agents::speed::effective(&crate::agents::speed::info_now(), &t.provider, &t.model, want) }; - combo(&snap, &t.provider, &t.model, effort, speed, (&acct.0, &acct.1, acct.2), &super::thread::person_zone(st).unwrap_or_else(super::tz::Rule::utc), now_s) + let speed = if want.is_empty() { "" } else { crate::agents::speed::effective(&info, &t.provider, &model, want) }; + combo(&snap, &t.provider, &model, effort, speed, (&acct.0, &acct.1, acct.2), &super::thread::person_zone(st).unwrap_or_else(super::tz::Rule::utc), now_s) } /// The phones' picker for a thread on an account provider: an Account section (the CLI's own login, then each saved account of the provider, with what it has /// left; a press is `thread.pick {action: account, value: "\u{1f}"}`, "" the CLI's own) and a Usage section (the thread's account's windows with @@ -317,6 +319,8 @@ pub fn chip(provider: &str, model: &str, effort: &str, efforts: bool) -> String /// Mob.picker.ctx.loc: the model chip and its label, the model menu (the thread's provider's models, each with what its CLI calls it), the efforts its model /// takes and the agents (with what each is and whether it can be used). Without the hub's models info: the provider's default only. pub fn picker_with(provider: &str, model: &str, effort: &str, reading: &str, models: Option<&Value>) -> Value { + let model = crate::settings::models::sanitize_model(provider, model, models); + let model = model.as_str(); let label = format!("{} · {}{}{}", provider, if model.is_empty() { "default" } else { model }, if effort.is_empty() { String::new() } else { format!(" · {}", effort_label(effort)) }, usage_tail(provider, reading)); let choice = |l: String, v: &str, on: bool| json!({"label": l, "value": v, "on": on}); let es = model_efforts(models, provider, model); @@ -472,13 +476,14 @@ pub fn keys(st: &State, id: &str, now_s: u64, why: &str, models_text: Option<&st let get = |k: String| st.settings.get(&k).map(String::as_str).unwrap_or(""); let (models, agents) = picker_agents_of(models_text); let mine = models.as_deref().map(|i| info_for_thread(st, id, i)); - m.insert("picker".into(), with_speed(picker_with(&t.provider, &t.model, get(format!("effort.{id}")), get(format!("usage.{id}")), mine.as_ref()), mine.as_ref(), &t.provider, &t.model, get(format!("speed.{id}")))); + let model = crate::settings::models::sanitize_model(&t.provider, &t.model, mine.as_ref()); + m.insert("picker".into(), with_speed(picker_with(&t.provider, &model, get(format!("effort.{id}")), get(format!("usage.{id}")), mine.as_ref()), mine.as_ref(), &t.provider, &model, get(format!("speed.{id}")))); m.insert("pickerAgents".into(), agents); m.insert("claude".into(), json!(t.provider == "claude")); // "Plan first, this turn only" set (commands/plan.rs thread.planonce): the picker's toggle is on until the turn it was set for ends m.insert("planOnce".into(), json!(!get(format!("plan.once.{id}")).is_empty())); m.insert("planMode".into(), plan_mode(st, id)); - m.insert("allowance".into(), json!(allowance_text(&allowance_of(st, id, &t.provider), &t.provider, &t.model, now_s))); + m.insert("allowance".into(), json!(allowance_text(&allowance_of(st, id, &t.provider), &t.provider, &model, now_s))); m.insert("combo".into(), combo_of(st, id, now_s)); Some(m) } diff --git a/native/host/src/present/settings.rs b/native/host/src/present/settings.rs index e6ab3aa93f..0f3ebd8748 100644 --- a/native/host/src/present/settings.rs +++ b/native/host/src/present/settings.rs @@ -215,7 +215,9 @@ fn agents(st: &State, info: &Value) -> Vec { let models: Value = info["models"].as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null); let prov = set(st, "agent.provider", "claude"); let cli = models["about"][prov]["cli"].as_str().unwrap_or(""); - let model = set(st, "agent.model", ""); + let raw_model = set(st, "agent.model", ""); + let model_clean = crate::settings::models::sanitize_model(prov, raw_model, models.is_object().then_some(&models)); + let model = model_clean.as_str(); let updates = agent_updates(&models, info); let mut ids: Vec<&str> = vec![""]; ids.extend(models[prov].as_array().into_iter().flatten().filter_map(Value::as_str).take(12)); @@ -617,7 +619,9 @@ fn writing(st: &State, info: &Value) -> Vec { const TEXT: &[&str] = &["claude", "codex", "grok", "muse"]; let models: Value = info["models"].as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null); let prov = { let p = set(st, "text.provider", "claude").trim(); if TEXT.contains(&p) { p } else { "claude" } }; - let model = set(st, "text.model", "").trim(); + let raw_model = set(st, "text.model", "").trim(); + let model_clean = crate::settings::models::sanitize_model(prov, raw_model, models.is_object().then_some(&models)); + let model = model_clean.as_str(); let mut ids: Vec<&str> = vec![""]; ids.extend(models[prov].as_array().into_iter().flatten().filter_map(Value::as_str).take(12)); if !ids.contains(&model) { ids.push(model); } @@ -1711,6 +1715,9 @@ mod tests { assert_eq!(r[3]["note"], "opus: Opus 5.5"); assert_eq!(r[2]["buttons"][0]["on"], true, "claude is the default provider"); let r = page_rows(&st(&[("agent.provider", "codex")]), "agents", json!({})); assert_eq!(r[2]["note"], "codex is not installed"); + let r = page_rows(&st(&[("agent.provider", "codex"), ("agent.model", "opus")]), "agents", json!({})); + assert!(r[3]["note"].as_str().unwrap().starts_with("default:"), "mismatched agent.model sanitized on display: {}", r[3]); + assert!(!r[3]["buttons"].as_array().unwrap().iter().any(|b| b["label"] == "opus"), "no bogus opus chip under codex"); } #[test] fn the_boat_hub_rows_show_its_cost_and_warn_before_the_plan_runs_out() { diff --git a/native/host/src/settings/mod.rs b/native/host/src/settings/mod.rs index 739eebe7aa..de59e14301 100644 --- a/native/host/src/settings/mod.rs +++ b/native/host/src/settings/mod.rs @@ -43,6 +43,7 @@ pub mod misc; pub mod onboard; pub mod tools_install; pub mod models; +pub mod model_compat; pub mod models_probe; pub mod agent_versions; pub mod privacy; diff --git a/native/host/src/settings/model_compat.rs b/native/host/src/settings/model_compat.rs new file mode 100644 index 0000000000..0455768cba --- /dev/null +++ b/native/host/src/settings/model_compat.rs @@ -0,0 +1,272 @@ +//! Provider/model compatibility check and sanitizer. +//! +//! Ensures a model belonging to one provider (for example `opus` or `claude-opus-5-5` on `codex`) is never +//! stored or passed to the wrong provider. Pure so both `backplane-hub` and small bins like `screen-audit` +//! can share the exact same rule. + +use serde_json::Value; + +pub const PROVIDERS: &[&str] = &[ + "claude", + "codex", + "grok", + "muse", + "antigravity", + "opencode", + "pi", + "omp", +]; + +const CLAUDE_ALIASES: &[&str] = &["opus", "sonnet", "haiku", "fable", "mythos", "opusplan"]; + +const AGY_VARIANTS: &[&str] = &["minimal", "low", "medium", "high", "xhigh", "max", "thinking"]; + +fn strip_agy_variant(low: &str) -> &str { + match low.rsplit_once('-') { + Some((base, suf)) if !base.is_empty() && AGY_VARIANTS.contains(&suf) => base, + _ => low, + } +} + +fn is_o_series(low: &str) -> bool { + low.starts_with('o') + && low.as_bytes().get(1).is_some_and(|b| b.is_ascii_digit()) + && low + .as_bytes() + .get(2) + .map_or(true, |b| matches!(b, b'-' | b'.' | b'_')) +} + +fn model_prefix_owner(low: &str) -> Option<&'static str> { + let base = low.split('[').next().unwrap_or(low); + if base.starts_with("claude-") + || CLAUDE_ALIASES + .iter() + .any(|a| base == *a || base.starts_with(&format!("{a}-"))) + { + return Some("claude"); + } + if base.starts_with("gpt-oss-") { + return Some("antigravity"); + } + if base.starts_with("gpt-") + || base.starts_with("codex-") + || base == "codex" + || base.starts_with("chatgpt-") + || is_o_series(base) + { + return Some("codex"); + } + if base.starts_with("gemini-") { + return Some("antigravity"); + } + if base.starts_with("grok-") { + return Some("grok"); + } + if base.starts_with("muse-") { + return Some("muse"); + } + None +} + +fn catalog_contains(info: &Value, provider: &str, model: &str) -> bool { + info.get(provider) + .and_then(Value::as_array) + .is_some_and(|arr| { + arr.iter() + .filter_map(Value::as_str) + .any(|s| s.eq_ignore_ascii_case(model)) + }) +} + +fn catalog_other_has(info: &Value, provider: &str, model: &str) -> bool { + PROVIDERS + .iter() + .any(|&p| p != provider && catalog_contains(info, p, model)) +} + +/// Whether `model` is compatible with `provider` given the optional `models` info catalog. +/// +/// Order of checks: +/// 1. Empty / `"default"` is always compatible. +/// 2. Target provider's own catalog allow-list (including Antigravity variant-stripped base IDs). +/// 3. Prefix/syntax ownership (`provider/model` for opencode/pi/omp; Antigravity-hosted `gemini-*`/`claude-*`/`gpt-oss-*` +/// even when the catalog is cold; `claude-*`/aliases, `gpt-*`/`codex-*`/`o3`, `gemini-*`, `grok-*`, `muse-*`). +/// Checked before other-provider catalog exclusion so `("claude", "claude-opus-5-5")` stays valid even when Antigravity also lists it. +/// 4. Foreign catalog exclusion (rejects models listed under another provider's catalog when not listed here). +/// 5. Otherwise compatible (preserves uncached new models and generic test placeholders). +pub fn model_compatible(provider: &str, model: &str, models: Option<&Value>) -> bool { + let m = model.trim(); + if m.is_empty() || m.eq_ignore_ascii_case("default") { + return true; + } + let p_low = provider.trim().to_ascii_lowercase(); + let p = if p_low.is_empty() { + "claude" + } else { + p_low.as_str() + }; + let low = m.to_ascii_lowercase(); + + if models.is_some_and(|info| { + catalog_contains(info, p, m) + || (p == "antigravity" && catalog_contains(info, "antigravity", strip_agy_variant(&low))) + }) { + return true; + } + + if low.contains('/') { + return matches!(p, "opencode" | "pi" | "omp"); + } + if p == "antigravity" + && (low.starts_with("gemini-") + || low.starts_with("claude-") + || low.starts_with("gpt-oss-")) + { + return true; + } + if let Some(owner) = model_prefix_owner(&low) { + return owner == p; + } + + if models.is_some_and(|info| catalog_other_has(info, p, m)) { + return false; + } + + true +} + +/// Returns `model` trimmed if compatible with `provider`, otherwise `""` (the provider's default). +pub fn sanitize_model(provider: &str, model: &str, models: Option<&Value>) -> String { + let m = model.trim(); + if m.is_empty() || !model_compatible(provider, m, models) { + String::new() + } else { + m.to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn catalog() -> Value { + json!({ + "claude": ["opus", "claude-fable-5-2[1m]", "sonnet", "haiku"], + "codex": ["gpt-6.2-sol", "gpt-6.1-sol", "gpt-6-luna"], + "grok": ["grok-4.7", "grok-4.7-build-fast"], + "muse": ["muse-wonder-1.0", "muse-spark-1.3"], + "antigravity": ["gemini-4-neon", "gemini-3.8-flash", "claude-opus-5-5", "claude-sonnet-5-5", "gpt-oss-120b"], + "opencode": ["openai/gpt-6", "anthropic/claude-sonnet-5"], + "pi": ["inference-net/deepseek-v4.1-flash-1017-cyber"], + "omp": ["openai/gpt-6.1-sol"] + }) + } + + #[test] + fn rejects_claude_models_on_other_providers() { + let cat = catalog(); + for m in [ + "opus", + "sonnet", + "haiku", + "fable", + "mythos", + "opusplan", + "opus[1m]", + "claude-opus-5-5", + "claude-fable-5-2[1m]", + "opus-5-5", + ] { + for p in ["codex", "grok", "muse", "opencode", "pi", "omp"] { + assert!( + !model_compatible(p, m, Some(&cat)), + "{m} must be rejected on {p}" + ); + assert_eq!(sanitize_model(p, m, Some(&cat)), ""); + } + assert!( + model_compatible("claude", m, Some(&cat)), + "{m} must be accepted on claude" + ); + assert!( + model_compatible("claude", m, None), + "{m} must be accepted on claude without catalog" + ); + assert!( + !model_compatible("codex", m, None), + "{m} must be rejected on codex even without catalog" + ); + } + } + + #[test] + fn rejects_codex_gemini_grok_muse_cross_provider_pairs() { + let cat = catalog(); + for m in ["gpt-6.2-sol", "codex-mini", "codex", "chatgpt-4o", "o3", "o4-mini"] { + assert!(model_compatible("codex", m, Some(&cat)), "{m} on codex"); + for p in ["claude", "grok", "muse", "antigravity"] { + assert!(!model_compatible(p, m, Some(&cat)), "{m} rejected on {p}"); + } + } + for m in ["gemini-4-neon", "gemini-pro-orchestrator"] { + assert!(model_compatible("antigravity", m, Some(&cat))); + for p in ["claude", "codex", "grok", "muse"] { + assert!(!model_compatible(p, m, Some(&cat)), "{m} rejected on {p}"); + } + } + assert!(model_compatible("grok", "grok-4.7", Some(&cat))); + assert!(!model_compatible("codex", "grok-4.7", Some(&cat))); + assert!(model_compatible("muse", "muse-wonder-1.0", Some(&cat))); + assert!(!model_compatible("claude", "muse-wonder-1.0", Some(&cat))); + } + + #[test] + fn antigravity_cross_family_variants_cold_catalog_and_claude_full_id_work() { + let cat = catalog(); + assert!(model_compatible("antigravity", "claude-opus-5-5", Some(&cat))); + assert!(model_compatible("antigravity", "claude-opus-5-5-high", Some(&cat))); + assert!(model_compatible("antigravity", "claude-opus-5-5-high", None)); + assert!(model_compatible("antigravity", "claude-opus-5-5", None)); + assert!(model_compatible("antigravity", "gpt-oss-120b", Some(&cat))); + assert!(model_compatible("antigravity", "gpt-oss-120b", None)); + assert!(model_compatible("antigravity", "gpt-oss-120b-medium", Some(&cat))); + assert!(model_compatible("claude", "claude-opus-5-5", Some(&cat))); + assert!(model_compatible("claude", "opusplan", Some(&cat))); + assert!(!model_compatible("codex", "opusplan", Some(&cat))); + assert!(!model_compatible("antigravity", "opus", Some(&cat))); + assert!(!model_compatible("antigravity", "opus", None)); + assert!(!model_compatible("antigravity", "gpt-6.2-sol", Some(&cat))); + assert!(!model_compatible("codex", "gpt-oss-120b", Some(&cat))); + assert!(!model_compatible("codex", "claude-opus-5-5", Some(&cat))); + } + + #[test] + fn slash_models_only_for_multi_provider_harnesses() { + let cat = catalog(); + let slash = "inference-net/deepseek-v4.1-flash-1017-cyber"; + for p in ["opencode", "pi", "omp"] { + assert!(model_compatible(p, slash, Some(&cat)), "{slash} on {p}"); + } + for p in ["claude", "codex", "grok", "muse", "antigravity"] { + assert!(!model_compatible(p, slash, Some(&cat)), "{slash} rejected on {p}"); + } + } + + #[test] + fn foreign_catalog_only_id_rejected_and_placeholders_kept() { + let cat = json!({ + "claude": ["opus"], + "codex": ["custom-reasoning-alpha"] + }); + assert!(!model_compatible("claude", "custom-reasoning-alpha", Some(&cat))); + assert!(model_compatible("codex", "custom-reasoning-alpha", Some(&cat))); + assert!(model_compatible("codex", "", Some(&cat))); + assert!(model_compatible("codex", "default", Some(&cat))); + assert!(model_compatible("codex", "m", Some(&cat))); + assert!(model_compatible("claude", "m", Some(&cat))); + assert_eq!(sanitize_model("codex", " gpt-6.2-sol ", Some(&cat)), "gpt-6.2-sol"); + assert_eq!(sanitize_model("codex", "opus", Some(&cat)), ""); + } +} diff --git a/native/host/src/settings/models.rs b/native/host/src/settings/models.rs index 7318f0fd50..c7c7c7e685 100644 --- a/native/host/src/settings/models.rs +++ b/native/host/src/settings/models.rs @@ -3,13 +3,16 @@ //! installed (a stand-in test hub, a fresh machine) they are empty. The hub's detection (models_probe.rs) replaces the built-in value //! with what the machine's CLIs report (`set_live`); `info` and `all` answer the value in force. use serde_json::{json, Value}; -use std::sync::RwLock; +use std::sync::{Arc, OnceLock, RwLock}; + +pub use super::model_compat::{model_compatible, sanitize_model}; /// Claude Code's aliases, for a CLI that cannot say its own list. pub const CLAUDE: &[&str] = &["fable", "opus", "sonnet", "haiku"]; -/// The detected info and its `models.all`, once the hub has detected (or read its cache); None: the built-in value. -static LIVE: RwLock> = RwLock::new(None); +/// The detected info, its `models.all`, and parsed `Value`, once the hub has detected (or read its cache); None: the built-in value. +static LIVE: RwLock)>> = RwLock::new(None); +static BUILTIN_VAL: OnceLock> = OnceLock::new(); /// Whether the hub detects its agents' models (the binary's start, models_probe::start): a test hub keeps the built-in value and asks no CLI. static DETECTS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Whether this hub process has completed at least one live CLI probe (separate from `models.cache`'s persisted `"probed": true`). @@ -21,9 +24,10 @@ pub fn mark_probed() { PROBED_HERE.store(true, std::sync::atomic::Ordering::Rela /// The info in force becomes `info`; answers whether it changed. pub fn set_live(info: &str) -> bool { let mut g = LIVE.write().unwrap_or_else(|e| e.into_inner()); - if g.as_ref().map_or(false, |(i, _)| i == info) { return false } - let all = all_of(&serde_json::from_str::(info).unwrap_or(Value::Null)); - *g = Some((info.to_string(), all)); true + if g.as_ref().map_or(false, |(i, _, _)| i == info) { return false } + let parsed = serde_json::from_str::(info).unwrap_or(Value::Null); + let all = all_of(&parsed); + *g = Some((info.to_string(), all, Arc::new(parsed))); true } /// Agy.version: the pinned Antigravity agent. @@ -43,7 +47,18 @@ pub fn about() -> Value { } /// The info value in force (a JSON text, as the JS hub sends it): what the hub detected, else the built-in one. -pub fn info() -> String { LIVE.read().ok().and_then(|g| g.as_ref().map(|(i, _)| i.clone())).unwrap_or_else(builtin) } +pub fn info() -> String { LIVE.read().ok().and_then(|g| g.as_ref().map(|(i, _, _)| i.clone())).unwrap_or_else(builtin) } +/// Parsed `models` info value in force (cached). +pub fn info_value() -> Arc { + if let Ok(g) = LIVE.read() { + if let Some((_, _, v)) = g.as_ref() { return v.clone() } + } + BUILTIN_VAL.get_or_init(|| Arc::new(serde_json::from_str::(&builtin()).unwrap_or(Value::Null))).clone() +} +/// Sanitize `model` against `provider` using the live (or built-in) models catalog. +pub fn sanitize_model_now(provider: &str, model: &str) -> String { + sanitize_model(provider, model, Some(&info_value())) +} /// The info for a machine whose CLIs have not been asked: Claude's aliases and nothing else. pub fn builtin() -> String { json!({"claude":["fable","opus","sonnet","haiku"],"codex":[],"grok":[],"muse":[],"antigravity":[],"opencode":[],"pi":[],"omp":[], @@ -52,7 +67,7 @@ pub fn builtin() -> String { /// The `models.all` info (new, not in the JS hub): every provider's models as rows the `&` mention offers, `{provider: [{value, label, ok, why}]}`. `value` is the id the /// `model` actions use; `ok` is false, with `why`, when the agent cannot be used now (its CLI is not installed). Claude's list is built in and always usable. -pub fn all() -> String { LIVE.read().ok().and_then(|g| g.as_ref().map(|(_, a)| a.clone())).unwrap_or_else(|| all_of(&serde_json::from_str::(&builtin()).unwrap_or(Value::Null))) } +pub fn all() -> String { LIVE.read().ok().and_then(|g| g.as_ref().map(|(_, a, _)| a.clone())).unwrap_or_else(|| all_of(&serde_json::from_str::(&builtin()).unwrap_or(Value::Null))) } pub fn all_of(models: &Value) -> String { let mut out = serde_json::Map::new(); let Some(o) = models.as_object() else { return "{}".into() }; @@ -94,7 +109,7 @@ pub fn default_agent(chosen: &str, models: &Value, connected: &[String]) -> Stri } /// default_agent for the models info in force. pub fn default_now(chosen: &str, inventory: &str) -> String { - default_agent(chosen, &serde_json::from_str::(&info()).unwrap_or(Value::Null), &connected(inventory)) + default_agent(chosen, &info_value(), &connected(inventory)) } #[cfg(test)] diff --git a/native/host/src/settings/set.rs b/native/host/src/settings/set.rs index 4c45e70467..3c63e1a946 100644 --- a/native/host/src/settings/set.rs +++ b/native/host/src/settings/set.rs @@ -24,8 +24,39 @@ impl RpcHandler for SettingSet { // a zone is only right once its rule is known: person.tz goes through zone.set (settings/zone.rs), which looks the rule up and refuses a name that is not a zone if key == "person.tz" { if let Some(z) = hub.rpc_for("zone.set") { return z.call(hub, _who, id, "zone.set", &json!({"zone": value})).await } } if telemetry::reserved(key) { return vec![telemetry::legacy(hub, id, key, value).await] } + let info = super::models::info_value(); + if key == "agent.model" && !value.is_empty() { + let cur_prov = hub.setting("agent.provider").await.unwrap_or_default(); + let eff_prov = if cur_prov.is_empty() { "claude" } else { cur_prov.as_str() }; + if !super::models::model_compatible(eff_prov, value, Some(&info)) { + return vec![json!({"t":"reply","id":id,"ok":false,"error":format!("model {value} is not compatible with provider {eff_prov}")})]; + } + } let at = now_ms() / 1000; let mut batch = vec![json!({"$":"SettingSet","key":key,"value":value,"at":at})]; + if key == "agent.provider" { + let prev_prov = hub.setting("agent.provider").await.unwrap_or_default(); + let cur_model = hub.setting("agent.model").await.unwrap_or_default(); + let prev_norm = if prev_prov.is_empty() { "claude" } else { prev_prov.as_str() }; + let next_norm = if value.is_empty() { "claude" } else { value }; + if !cur_model.is_empty() && (next_norm != prev_norm || !super::models::model_compatible(next_norm, &cur_model, Some(&info))) { + batch.push(json!({"$":"SettingSet","key":"agent.model","value":"","at":at})); + } + } else if key == "text.provider" { + let prev_prov = hub.setting("text.provider").await.unwrap_or_default(); + let cur_model = hub.setting("text.model").await.unwrap_or_default(); + let prev_norm = if prev_prov.is_empty() { "claude" } else { prev_prov.as_str() }; + let next_norm = if value.is_empty() { "claude" } else { value }; + if !cur_model.is_empty() && (next_norm != prev_norm || !super::models::model_compatible(next_norm, &cur_model, Some(&info))) { + batch.push(json!({"$":"SettingSet","key":"text.model","value":"","at":at})); + } + } else if key == "fallback.add.provider" { + let prev_prov = hub.setting("fallback.add.provider").await.unwrap_or_default(); + let cur_model = hub.setting("fallback.add.model").await.unwrap_or_default(); + if !cur_model.is_empty() && cur_model != "default" && (value != prev_prov || !super::models::model_compatible(value, &cur_model, Some(&info))) { + batch.push(json!({"$":"SettingSet","key":"fallback.add.model","value":"default","at":at})); + } + } // a write to either fallback setting closes the open settings proposals in the same batch (Proposal.invalidate) if let Some(a) = &self.agents { let open: Vec = a.world().await.asks.iter().filter(|(_, k)| k.tool == super::proposal::TOOL).map(|(i, _)| i.clone()).collect(); let extra = super::proposal::invalidate(&batch.clone(), &open, at); batch.extend(extra); batch = super::proposal::with_pending(a, batch, at).await; } match hub.commit_many(&batch).await { @@ -103,4 +134,30 @@ mod tests { assert!(std::fs::read_to_string(home.join("events.jsonl")).unwrap().contains("\"key\":\"launch.input.t9\",\"value\":\"\""), "an empty write is logged"); let _ = rx.try_recv(); let _ = std::fs::remove_dir_all(&home); } + + #[tokio::test(flavor = "multi_thread")] async fn provider_change_clears_stale_model_and_incompatible_agent_model_is_refused() { + let home = crate::plat::tmp::dir("set-prov-model"); + let hub = start(&home).await; + assert_eq!(call(&hub, "setting.set", json!({"key":"agent.provider","value":"claude"})).await["ok"], true); + assert_eq!(call(&hub, "setting.set", json!({"key":"agent.model","value":"opus"})).await["ok"], true); + assert_eq!(hub.setting("agent.model").await.as_deref(), Some("opus")); + + // Switching agent.provider to codex clears agent.model atomically + assert_eq!(call(&hub, "setting.set", json!({"key":"agent.provider","value":"codex"})).await["ok"], true); + assert_eq!(hub.setting("agent.provider").await.as_deref(), Some("codex")); + assert_eq!(hub.setting("agent.model").await, None); + + // Trying to set a Claude model while agent.provider is codex is refused + let bad = call(&hub, "setting.set", json!({"key":"agent.model","value":"opus"})).await; + assert_eq!(bad["ok"], false, "{bad}"); + assert!(bad["error"].as_str().unwrap_or("").contains("not compatible"), "{bad}"); + assert_eq!(hub.setting("agent.model").await, None); + + // Switching text.provider clears stale text.model + assert_eq!(call(&hub, "setting.set", json!({"key":"text.provider","value":"claude"})).await["ok"], true); + assert_eq!(call(&hub, "setting.set", json!({"key":"text.model","value":"haiku"})).await["ok"], true); + assert_eq!(call(&hub, "setting.set", json!({"key":"text.provider","value":"codex"})).await["ok"], true); + assert_eq!(hub.setting("text.model").await, None); + let _ = std::fs::remove_dir_all(&home); + } }