Skip to content

The agent that grows with you

fix(tui_gateway): a queued model switch crosses the compute-host boundary

Brooklyn Nicholsone85706cba780
diff --git a/tests/tui_gateway/test_compute_host_pending_model_switch.py b/tests/tui_gateway/test_compute_host_pending_model_switch.py
new file mode 100644
index 00000000000..85c40a0adac
--- /dev/null
+++ b/tests/tui_gateway/test_compute_host_pending_model_switch.py
@@ -0,0 +1,80 @@
+"""Regression tests for #79509: a model switch on a compute-host (turn-isolation)
+session must cross the process boundary and be applied by the CHILD's live agent.
+
+On an isolated session the live agent lives in the compute-host child; the serving
+process sees ``session["agent"] is None``. Before the fix, ``config.set model``:
+
+- busy: stashed ``pending_model_switch`` for a turn thread whose
+ ``_apply_pending_model_switch`` pops it and returns early server-side, so the
+ pick was silently dropped;
+- idle: built a SECOND agent inside the serving process and switched that copy,
+ while every actual turn ran in the child on the old model.
+
+The fix carries the stash in the turn frame (copied, not popped), the child adopts
+it, its turn thread applies it, and ``_on_compute_host_turn_done`` clears the
+server-side stash only after a successful isolated turn.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+
+from tui_gateway import server
+
+
+def _session(**extra):
+ base = dict(
+ agent=None, agent_ready=threading.Event(), session_key="s1-key", history=[],
+ history_version=0, history_lock=threading.Lock(), running=False,
+ attached_images=[], image_counter=0, cols=80, slash_worker=None,
+ show_reasoning=False, tool_progress_mode="all", inflight_turn=None,
+ created_at=time.time(), last_active=time.time())
+ base.update(extra)
+ return base
+
+
+def test_config_set_model_defers_on_compute_host_session(monkeypatch):
+ """Idle isolated session: config.set model must stash, not direct-apply."""
+ session = _session(_compute_host_active=True)
+ server._sessions["sid-cfgset"] = session
+ build_calls = []
+ monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: build_calls.append(a))
+ try:
+ resp = server.handle_request(
+ {"id": "1", "method": "config.set",
+ "params": {"session_id": "sid-cfgset", "key": "model", "value": "anthropic/claude-sonnet-4.6"}})
+ assert resp["result"].get("deferred") is True
+ assert session["pending_model_switch"]["raw"] == "anthropic/claude-sonnet-4.6"
+ # The broken path built a second agent inside the server process.
+ assert build_calls == []
+ finally:
+ server._sessions.pop("sid-cfgset", None)
+
+
+def test_compute_host_turn_frame_carries_pending_switch():
+ session = _session(pending_model_switch={"raw": "anthropic/claude-sonnet-4.6",
+ "display_model": "anthropic/claude-sonnet-4.6"})
+ frame = server._compute_host_turn_frame("r1", "sid", session, "hello")
+ assert frame["pending_model_switch"]["raw"] == "anthropic/claude-sonnet-4.6"
+ # Copied, not popped — the fail-open in-process path may still need it.
+ assert session["pending_model_switch"]["raw"] == "anthropic/claude-sonnet-4.6"
+
+
+def test_compute_host_turn_done_clears_pending_switch_on_success(monkeypatch):
+ monkeypatch.setattr(server, "_emit", lambda *a, **k: None)
+ session = _session(running=True, pending_model_switch={"raw": "anthropic/claude-sonnet-4.6"})
+ server._sessions["sid-done"] = session
+ try:
+ server._on_compute_host_turn_done(
+ "r1", "sid-done", session, {"type": "turn.end", "session_info_emitted": True})
+ assert "pending_model_switch" not in session
+ # An errored turn must KEEP the stash for the fail-open path.
+ session["pending_model_switch"] = {"raw": "anthropic/claude-sonnet-4.6"}
+ session["running"] = True
+ server._on_compute_host_turn_done(
+ "r1", "sid-done", session,
+ {"type": "turn.error", "message": "boom", "session_info_emitted": True})
+ assert session["pending_model_switch"]["raw"] == "anthropic/claude-sonnet-4.6"
+ finally:
+ server._sessions.pop("sid-done", None)
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index 5902e1b2cfe..f3326839b28 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -318,6 +318,11 @@ class ComputeHost:
session = self._build_server_session(server, frame, sid)
if isinstance(frame.get("attached_images"), list):
session["attached_images"] = list(frame.get("attached_images") or [])
+ # A model switch queued on the host side while this session was busy rides
+ # the turn frame; adopt it here so the child's turn thread applies it via
+ # _apply_pending_model_switch — in the child the live agent exists.
+ if frame.get("pending_model_switch"):
+ session["pending_model_switch"] = dict(frame["pending_model_switch"])
return session
def _build_server_session(self, server: Any, frame: dict[str, Any], sid: str) -> dict:
@@ -400,6 +405,10 @@ class ComputeHost:
session["profile_home"] = profile_home or session.get("profile_home")
if frame.get("model_override") is not None:
session["model_override"] = frame.get("model_override")
+ # See _ensure_server_session's existing-session branch — a queued model
+ # switch crosses the process boundary and applies at this child's turn start.
+ if frame.get("pending_model_switch"):
+ session["pending_model_switch"] = dict(frame["pending_model_switch"])
return session
def _handle_reload_mcp(self, frame: dict[str, Any]) -> None:
diff --git a/tui_gateway/compute_host_bridge.py b/tui_gateway/compute_host_bridge.py
index 41d636bd270..26060806b1e 100644
--- a/tui_gateway/compute_host_bridge.py
+++ b/tui_gateway/compute_host_bridge.py
@@ -65,6 +65,13 @@ def _compute_host_turn_frame(
"context_cwd_is_launch_artifact": _context_cwd_is_launch_artifact(session),
"profile_home": session.get("profile_home") or "",
"model_override": session.get("model_override"),
+ # A model switch queued while the session was busy (config.set model ->
+ # pending_model_switch) must cross the process boundary — the live agent is in
+ # the compute host, and the server-side _apply_pending_model_switch would
+ # pop-and-drop it against agent=None. COPIED (not popped): the stash is
+ # cleared only after a successful isolated turn (_on_compute_host_turn_done),
+ # so the fail-open in-process path can still apply it if the host dispatch fails.
+ "pending_model_switch": session.get("pending_model_switch"),
"reasoning_config_override": session.get("create_reasoning_override"),
"service_tier_override": session.get("create_service_tier_override"),
"source": _session_source(session), "attached_images": attached_images,
@@ -241,6 +248,11 @@ def _on_compute_host_turn_done(rid: str, sid: str, session: dict, frame: dict) -
session["last_active"] = time.time()
_clear_inflight_turn(session)
session.pop("_compute_host_open_request", None)
+ # The isolated turn carried the queued model switch to the compute host, whose
+ # turn thread applied it. Clear the server-side stash so it isn't re-forwarded
+ # (kept on error so the fail-open in-process path can still apply it).
+ if frame.get("type") != "turn.error":
+ session.pop("pending_model_switch", None)
if frame.get("type") == "turn.error":
message = str(frame.get("message") or "compute host turn failed")
_emit("message.complete", sid, {"text": f"Error: {message}", "status": "error"})
diff --git a/tui_gateway/methods_config_set.py b/tui_gateway/methods_config_set.py
index 7e5f2d4ffc9..493ab6f4391 100644
--- a/tui_gateway/methods_config_set.py
+++ b/tui_gateway/methods_config_set.py
@@ -113,7 +113,13 @@ def _set_model(rid, params, key, value, session):
from hermes_cli.model_switch import parse_model_switch_args
sid = params.get("session_id", "")
parsed_flags = parse_model_switch_args(value)
- if session.get("running"):
+ # Compute-host sessions ALWAYS defer, busy or idle. Their live agent is in
+ # the child process — the direct path below would build a SECOND agent in
+ # the server, switch that copy, and leave the child (which handles every
+ # turn) on the old model: checkmark shows the pick, requests keep the old
+ # model. The stash crosses the boundary in the turn frame and the child's
+ # turn thread applies it (_apply_pending_model_switch).
+ if session.get("running") or session.get("_compute_host_active"):
return _stash_pending_model_switch(rid, key, value, session, confirmed, parsed_flags)
explicit_provider = parsed_flags.explicit_provider
failed_agent_init = session.get("agent") is None and session.get("agent_error") is not None