From ad73e8f1c2f434f5b677c5bee318ae8790430e92 Mon Sep 17 00:00:00 2001 From: hermes Date: Thu, 1 Oct 2026 12:15:39 +0000 Subject: [PATCH] model switch also switches provider (gpt models were sent to the Claude API) --- crates/hx-ai/src/models.rs | 22 +++++++++ crates/hx-cli/src/main.rs | 18 +++++++- crates/hx-cli/src/rpc.rs | 38 +++++++++++---- crates/hx-tui/src/lib.rs | 94 ++++++++++++++++++++++++++++++++++---- tests/e2e.sh | 8 ++++ tests/fake_anthropic.py | 8 +++- tests/tui_smoke.py | 4 +- 7 files changed, 171 insertions(+), 21 deletions(-) diff --git a/crates/hx-ai/src/models.rs b/crates/hx-ai/src/models.rs index 569fb3b..a5f4df9 100644 --- a/crates/hx-ai/src/models.rs +++ b/crates/hx-ai/src/models.rs @@ -78,6 +78,23 @@ pub fn window(models: &[ModelInfo], id: &str) -> u64 { }) } +/// Provider serving `id`: catalog entry, else by name (`claude-*` vs OpenAI families). +pub fn kind_of(models: &[ModelInfo], id: &str) -> Option { + if let Some(m) = models.iter().find(|m| m.id == id) { + return Some(m.kind); + } + let openai = id.starts_with("gpt-") + || id.starts_with("codex") + || (id.starts_with('o') && id[1..].starts_with(|c: char| c.is_ascii_digit())); + if id.starts_with("claude") { + Some(Kind::Claude) + } else if openai { + Some(Kind::Codex) + } else { + None + } +} + /// Auto-compaction threshold: 90% of the window, leaving room for the reply. pub fn compact_threshold(window: u64, max_output: u32) -> usize { (window * 9 / 10).min(window.saturating_sub(max_output as u64)) as usize @@ -156,6 +173,11 @@ mod tests { ms.extend(fallback(Kind::Codex)); assert_eq!(default_for(Kind::Codex, &ms), "gpt-5.6-sol"); assert_eq!(compact_threshold(1_000_000, 16_384), 900_000); + assert_eq!(kind_of(&ms, "gpt-5.6-terra"), Some(Kind::Codex), "catalog"); + assert_eq!(kind_of(&[], "gpt-7"), Some(Kind::Codex), "by name"); + assert_eq!(kind_of(&[], "o4-mini"), Some(Kind::Codex)); + assert_eq!(kind_of(&[], "claude-x"), Some(Kind::Claude)); + assert_eq!(kind_of(&[], "opus"), None); assert_eq!(compact_threshold(20_000, 16_384), 3_616); } } diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 9df9eff..c322733 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -324,6 +324,11 @@ async fn main() -> Result<()> { .or(kinds.first().copied()) .unwrap_or(Kind::Claude); let models = catalog(&kinds).await; + // an explicit model picks its provider unless --provider says otherwise + let kind = match (&cli.provider, cli.model.as_deref().or(cfg.model.as_deref())) { + (None, Some(m)) => hx_ai::models::kind_of(&models, m).unwrap_or(kind), + _ => kind, + }; let model = cli.model.or(cfg.model).unwrap_or_else(|| { match kind { Kind::Claude => cfg.claude_model.clone(), @@ -455,7 +460,18 @@ async fn main() -> Result<()> { } let specs = command_specs(&mcp, &cwd, &models, &kinds); if cli.mode == Mode::Rpc { - let r = rpc::serve(agent, abort, specs, hx_tui::project_files(&cwd), dir).await; + let r = rpc::serve( + agent, + abort, + rpc::Ctx { + specs, + files: hx_tui::project_files(&cwd), + session_dir: dir, + models: models.clone(), + make_provider: provider, + }, + ) + .await; mgr.shutdown().await; return r; } diff --git a/crates/hx-cli/src/rpc.rs b/crates/hx-cli/src/rpc.rs index e3a5a24..4b05add 100644 --- a/crates/hx-cli/src/rpc.rs +++ b/crates/hx-cli/src/rpc.rs @@ -47,13 +47,22 @@ fn reply(id: &Value, r: Result) { /// `state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`, /// `complete {line, cursor?}` (cursor = byte offset, default end), `sessions {scope?: project|all}`, /// `new`, `resume {path}`. One prompt at a time. -pub async fn serve( - mut agent: Agent, - abort: AbortHandle, - specs: Vec, - files: Vec, - session_dir: std::path::PathBuf, -) -> Result<()> { +pub struct Ctx { + pub specs: Vec, + pub files: Vec, + pub session_dir: std::path::PathBuf, + pub models: Vec, + pub make_provider: fn(hx_ai::auth::Kind) -> hx_ai::Result>, +} + +pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> { + let Ctx { + specs, + files, + session_dir, + models, + make_provider, + } = cx; agent.bus.add(Notify); let agent = Arc::new(Mutex::new(agent)); let busy = Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -136,10 +145,19 @@ pub async fn serve( .map(|_| json!({})) .map_err(|e| e.to_string()), "set_model" => match p["model"].as_str() { - Some(m) => { - a.model = m.into(); - Ok(json!({"model": m})) + // switch provider too when the model belongs to another one + Some(m) => match hx_ai::models::kind_of(&models, m) { + Some(k) => make_provider(k).map(|prov| { + a.provider = prov; + a.model = m.into(); + json!({"model": m, "provider": format!("{k:?}").to_lowercase()}) + }), + None => { + a.model = m.into(); + Ok(json!({"model": m})) + } } + .map_err(|e| e.to_string()), None => Err("params.model required".into()), }, "compact" => a diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 21fc48c..ff12fae 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -650,14 +650,31 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { } "model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))), "model" => { - let mut a = agent.lock().await; - a.model = arg.into(); - set_window(app, &mut a, models, auto_compact); - app.model = arg.into(); - app.t.push(Item::Info(format!( - "model → {arg} · context {}k", - hx_ai::models::window(models, arg) / 1000 - ))); + // a model belongs to one provider: switch provider with it + let k = hx_ai::models::kind_of(models, arg).unwrap_or(app.kind); + let p = if k == app.kind { + Ok(None) + } else { + make_provider(k).map(Some).map_err(|e| e.to_string()) + }; + match p { + Ok(p) => { + let mut a = agent.lock().await; + if let Some(p) = p { + a.provider = p; + app.kind = k; + app.quota = None; + } + a.model = arg.into(); + set_window(app, &mut a, models, auto_compact); + app.model = arg.into(); + app.t.push(Item::Info(format!( + "model → {arg} ({k:?}) · context {}k", + hx_ai::models::window(models, arg) / 1000 + ))); + } + Err(e) => app.t.push(Item::Error(format!("/model {arg}: {e}"))), + } } "provider" => match arg .parse::() @@ -1456,6 +1473,67 @@ mod tests { assert_eq!(until(10_030, 10_000), "1m"); } + #[tokio::test] + async fn model_switch_follows_provider() { + use std::sync::atomic::{AtomicUsize, Ordering}; + static CODEX_CALLS: AtomicUsize = AtomicUsize::new(0); + let t = tempfile::tempdir().unwrap(); + let (agent, _) = Agent::new( + Arc::new(NoProvider), + Default::default(), + hx_core::session::Session::open(t.path().join("s.jsonl")).unwrap(), + hx_core::tool::ToolCtx { + cwd: t.path().into(), + state: Default::default(), + }, + ); + let agent = Arc::new(Mutex::new(agent)); + let (tx, _rx) = mpsc::unbounded_channel(); + let mut models = hx_ai::models::fallback(Kind::Claude); + models.extend(hx_ai::models::fallback(Kind::Codex)); + let ls: LspStatus = Box::new(|| Box::pin(async { vec![] })); + let cmds: Commands = Box::new(|_, _| None); + let mut app = test_app(); + app.kind = Kind::Claude; + + // codex not logged in: error, nothing changes + let fail: MakeProvider = + Box::new(|_| Err(hx_ai::Error::Http("not logged in to Codex".into()))); + let ctx = Ctx { + agent: &agent, + tx: &tx, + make_provider: &fail, + models: &models, + auto_compact: true, + cwd: t.path(), + lsp_status: &ls, + commands: &cmds, + }; + submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await; + assert_eq!((app.kind, app.model.as_str()), (Kind::Claude, "m1")); + assert!(matches!(app.t.items.last(), Some(Item::Error(e)) if e.contains("not logged in"))); + + let ok: MakeProvider = Box::new(|k| { + assert_eq!(k, Kind::Codex); + CODEX_CALLS.fetch_add(1, Ordering::SeqCst); + Ok(Arc::new(NoProvider)) + }); + let ctx = Ctx { + make_provider: &ok, + ..ctx + }; + submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await; + assert_eq!( + (app.kind, app.model.as_str()), + (Kind::Codex, "gpt-5.6-terra") + ); + assert_eq!(agent.lock().await.model, "gpt-5.6-terra"); + assert_eq!(CODEX_CALLS.load(Ordering::SeqCst), 1); + // same provider: no new client + submit(&mut app, "/model gpt-5.6-luna".into(), &ctx).await; + assert_eq!(CODEX_CALLS.load(Ordering::SeqCst), 1); + } + struct NoProvider; #[async_trait::async_trait] impl Provider for NoProvider { diff --git a/tests/e2e.sh b/tests/e2e.sh index e050ec9..a5a2285 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -18,4 +18,12 @@ echo "$log" | grep -q '"auth": "Bearer fake-token"' echo "$log" | grep -q 'oauth-2025-04-20' echo "$log" | grep -q 'hi from hx' # bash tool result sent back to the model ls "$tmp/home/.hx/sessions/"*/*.jsonl > /dev/null +# a GPT model goes to the Codex endpoint, not to the Claude API (both logged in) +echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999},"codex":{"access":"cx-token","refresh":"r","expires":99999999999999,"account_id":"acc"}}' > "$tmp/home/.hx/auth.json" +HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port" "$root/target/debug/hx" -m gpt-5.6-terra -p "hi" > /dev/null 2> "$tmp/err" || true +curl -s "http://127.0.0.1:$port/" | python3 -c ' +import json, sys +last = json.load(sys.stdin)[-1] +assert last["path"].endswith("/responses") and last["body"]["model"] == "gpt-5.6-terra" and last["auth"] == "Bearer cx-token", last +' || { echo "FAIL: gpt model not routed to codex"; cat "$tmp/err"; exit 1; } echo "e2e ok" diff --git a/tests/fake_anthropic.py b/tests/fake_anthropic.py index 369babe..e224201 100644 --- a/tests/fake_anthropic.py +++ b/tests/fake_anthropic.py @@ -23,7 +23,13 @@ class H(http.server.BaseHTTPRequestHandler): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers["content-length"]))) - LOG.append({"auth": self.headers.get("authorization"), "beta": self.headers.get("anthropic-beta"), "body": body}) + LOG.append({"path": self.path, "auth": self.headers.get("authorization"), "beta": self.headers.get("anthropic-beta"), "body": body}) + if self.path.endswith("/responses"): + # Codex route: only the request matters to the tests + self.send_response(400) + self.end_headers() + self.wfile.write(b'{"detail": "fake codex"}') + return turn = TURNS[min(len(LOG) - 1, len(TURNS) - 1)] self.send_response(200) self.send_header("anthropic-ratelimit-unified-5h-utilization", "0.42") diff --git a/tests/tui_smoke.py b/tests/tui_smoke.py index 102c075..33e091f 100644 --- a/tests/tui_smoke.py +++ b/tests/tui_smoke.py @@ -69,7 +69,9 @@ check("quota in footer", "5h 42%") send(b"/usage\r") check("usage report", "58% left, resets in 2h1") send(b"/model claude-opus-5-5\r") -check("model switch", "model → claude-opus-5-5 · context 1000k") +check("model switch", "model → claude-opus-5-5 (Claude) · context 1000k") +send(b"/model gpt-5.6-sol\r") +check("gpt model needs codex login", "not logged in to Codex") send(b"/model claude-sonnet-5-6-preview\r") check("live catalog window", "context 2000k") check("live catalog cached", "") if os.path.exists(f"{tmp}/home/.hx/models-claude.json") else (print("FAIL no model cache"), globals().update(ok=False)) -- 2.54.1