Skip to content

The agent that grows with you

fix(sessions): preserve explicit Bot Chat model overrides

fangliquanflqa16d45828f7f
diff --git a/tests/tui_gateway/test_custom_provider_session_persistence.py b/tests/tui_gateway/test_custom_provider_session_persistence.py
index 00ed7fe5ec2..283641d969f 100644
--- a/tests/tui_gateway/test_custom_provider_session_persistence.py
+++ b/tests/tui_gateway/test_custom_provider_session_persistence.py
@@ -561,18 +561,73 @@ class TestRoomPlumbingRuntimeOverrides:
# --- Regression: bot DM stuck on a stale provider pin (GH #89497 class) ------
#
-# Bot-Mode canonical chats (the ONE forever DM per bot) and room plumbing
-# sessions are plugin-owned scratch conversations. They are created with the
-# explicit ``follow_profile_config`` contract so resume ALWAYS rebuilds from
-# the member profile's CURRENT config — restoring the stored model/provider
-# pin from an old row is what left bot DMs stuck on a stale provider (e.g.
-# "out of Nous credits" after the profile was switched to ollama-cloud) while
-# the same bot worked fine in rooms. Normal 1:1 user chats keep the
-# stored-runtime restore (opening an older chat must show the model it
-# actually used).
+# Room plumbing always follows the member profile. Canonical Bot Chats follow it
+# by default, but a composer pick remains chat-scoped until a later profile model
+# edit supersedes it. Normal 1:1 user chats always keep their stored runtime.
class TestFollowProfileConfigRuntimeOverrides:
+ def test_composer_override_survives_while_profile_model_is_unchanged(self, monkeypatch):
+ """An explicit Bot Chat pick outranks the unchanged profile default."""
+ import tui_gateway.server as server
+
+ monkeypatch.setattr(server, "_config_model_target", lambda: ("profile/default", "nous"))
+ row = {
+ "title": "Bot Chat",
+ "model": "openai/gpt-5.6-luna-pro",
+ "model_config": json.dumps(
+ {
+ "model": "openai/gpt-5.6-luna-pro",
+ "provider": "nous",
+ "reasoning_config": {"effort": "xhigh"},
+ "follow_profile_config": True,
+ "composer_override_profile": {"model": "profile/default", "provider": "nous"},
+ }
+ ),
+ }
+
+ overrides = server._stored_session_runtime_overrides(row)
+
+ assert overrides["model_override"]["model"] == "openai/gpt-5.6-luna-pro"
+ assert overrides["reasoning_config_override"] == {"effort": "xhigh"}
+
+ def test_profile_model_change_supersedes_composer_override_on_resume_and_live(self, monkeypatch):
+ """Changing the Bot profile invalidates both stored and live chat pins."""
+ import tui_gateway.server as server
+
+ monkeypatch.setattr(server, "_config_model_target", lambda: ("profile/new-default", "nous"))
+ row = {
+ "title": "Bot Chat",
+ "model": "openai/gpt-5.6-luna-pro",
+ "model_config": json.dumps(
+ {
+ "model": "openai/gpt-5.6-luna-pro",
+ "provider": "nous",
+ "follow_profile_config": True,
+ "composer_override_profile": {"model": "profile/old-default", "provider": "nous"},
+ }
+ ),
+ }
+ assert server._stored_session_runtime_overrides(row) == {}
+
+ session = {
+ "agent": types.SimpleNamespace(model="openai/gpt-5.6-luna-pro", provider="nous"),
+ "model_override": {"model": "openai/gpt-5.6-luna-pro", "provider": "nous"},
+ "composer_override_profile": {"model": "profile/old-default", "provider": "nous"},
+ "config_model_seen": ("profile/old-default", "nous"),
+ }
+ apply_switch = MagicMock()
+ monkeypatch.setattr(server, "_apply_model_switch", apply_switch)
+
+ server._sync_agent_model_with_config("sid", session)
+
+ assert "model_override" not in session
+ assert session["composer_override_profile"] is None
+ apply_switch.assert_called_once_with(
+ "sid", session, "profile/new-default --provider nous",
+ confirm_expensive_model=True, pin_session_override=False, persist_override=False,
+ )
+
def test_marked_row_returns_no_overrides(self):
"""A row carrying the follow_profile_config marker never restores a
stored provider pin — resume falls back to the profile's CURRENT
diff --git a/tests/tui_gateway/test_make_agent_provider.py b/tests/tui_gateway/test_make_agent_provider.py
index 4108bb2596c..f3e4b8c2a2a 100644
--- a/tests/tui_gateway/test_make_agent_provider.py
+++ b/tests/tui_gateway/test_make_agent_provider.py
@@ -109,7 +109,10 @@ def test_apply_model_switch_does_not_leak_process_env():
"HERMES_INFERENCE_PROVIDER",
)
- sess_b = {"agent": _FakeAgent(), "session_key": "k-B", "model_override": None}
+ sess_b = {
+ "agent": _FakeAgent(), "session_key": "k-B", "model_override": None,
+ "follow_profile_config": True,
+ }
sess_a = {"agent": _FakeAgent(), "session_key": "k-A", "model_override": None}
with (
@@ -122,6 +125,7 @@ def test_apply_model_switch_does_not_leak_process_env():
patch("tui_gateway.server._restart_slash_worker"),
patch("tui_gateway.server._session_info", return_value={}),
patch("hermes_cli.model_switch.persist_model_selection") as mock_persist,
+ patch("tui_gateway.server._config_model_target", return_value=("minimax/m3", "minimax")),
):
before = {k: os.environ.get(k) for k in env_keys}
result = server._apply_model_switch("sidB", sess_b, "glm-5.1")
@@ -135,6 +139,7 @@ def test_apply_model_switch_does_not_leak_process_env():
# Target session recorded a per-session override.
assert sess_b["model_override"]["model"] == "zai/glm-5.1"
assert sess_b["model_override"]["provider"] == "zai"
+ assert sess_b["composer_override_profile"] == {"model": "minimax/m3", "provider": "minimax"}
# The switched agent mutated in place.
assert sess_b["agent"].model == "zai/glm-5.1"
# Sibling session is completely untouched.
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 138c1b25e44..3c9033b28dd 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -529,10 +529,22 @@ class _Resume:
``overrides`` restores the stored model/provider/reasoning/tier so the deferred build matches eager."""
if overrides is not None:
extra.update(model_override=overrides.get("model_override"), resume_runtime_overrides=overrides or None)
- return _deferred_session_record(
+ model_config = _parse_model_config(self.found.get("model_config"), quiet=True) if self.found else {}
+ title = str((self.found or {}).get("title") or "").strip()
+ follows_profile = bool(model_config.get("follow_profile_config") or title == "Bot Chat")
+ else:
+ model_config, follows_profile = {}, False
+ record = _deferred_session_record(
self.target, cols=self.cols, cwd=cwd, history=history, lease=None, source=source,
close_on_disconnect=_flag(self.params, "close_on_disconnect"),
profile_home=self.profile_home, explicit_cwd=bool(self.profile_resume_cwd), **extra)
+ if follows_profile:
+ record.update(
+ follow_profile_config=True,
+ composer_override_profile=(model_config.get("composer_override_profile")
+ if overrides and overrides.get("model_override") else None),
+ )
+ return record
def claim(self, sid: str, record: dict) -> dict | None:
"""Register ``record`` live under the resume lock, or reuse a concurrent winner's session."""
@@ -835,6 +847,12 @@ def _resume_eager(ctx: _Resume) -> dict:
if (session := _sessions.get(sid)) is not None:
if stored_runtime_overrides.get("model_override") is not None:
session["model_override"] = stored_runtime_overrides["model_override"]
+ model_config = _parse_model_config(ctx.found.get("model_config"), quiet=True)
+ if model_config.get("follow_profile_config") or str(ctx.found.get("title") or "").strip() == "Bot Chat":
+ session["follow_profile_config"] = True
+ session["composer_override_profile"] = (
+ model_config.get("composer_override_profile")
+ if stored_runtime_overrides.get("model_override") else None)
# Each turn re-binds HERMES_HOME (mid-turn memory/skills reads); lease claimed lazily on turn 1.
if ctx.profile_home is not None:
session["profile_home"] = str(ctx.profile_home)
diff --git a/tui_gateway/model_switch.py b/tui_gateway/model_switch.py
index 37d57766942..2b24bb6579c 100644
--- a/tui_gateway/model_switch.py
+++ b/tui_gateway/model_switch.py
@@ -292,6 +292,13 @@ def _apply_model_switch(
session["model_override"] = {
"model": result.new_model, "provider": result.target_provider,
"base_url": result.base_url, "api_key": result.api_key, "api_mode": result.api_mode}
+ if not persist_global and session.get("follow_profile_config"):
+ profile_model, profile_provider = _config_model_target()
+ session["composer_override_profile"] = {
+ "model": profile_model, "provider": profile_provider}
+ if agent:
+ # _commit_agent_switch persists before the session pin and its provenance exist.
+ _persist_live_session_runtime(session)
if persist_global:
from hermes_cli.model_switch import persist_model_selection
persist_model_selection(result)
@@ -368,19 +375,35 @@ def _sync_agent_model_with_config(sid: str, session: dict) -> None:
"""Adopt a config.yaml model change at turn start (like gateways do per message). Sessions
pinned with /model keep their choice; a failed switch keeps the current model."""
agent = session.get("agent")
- if agent is None or session.get("model_override"):
+ if agent is None:
return
target = _config_model_target()
if not target[0]:
return
seen = session.get("config_model_seen")
+ if target == seen:
+ return
+ superseded_pin = None
+ if session.get("model_override"):
+ composer_profile = session.get("composer_override_profile")
+ pinned_profile = (
+ str(composer_profile.get("model") or "").strip(),
+ str(composer_profile.get("provider") or "").strip(),
+ ) if isinstance(composer_profile, dict) else None
+ if pinned_profile is None or pinned_profile == target:
+ return
+ # A later profile edit supersedes the canonical chat's explicit pick. Clearing both fields lets
+ # the normal config-sync path switch now and prevents the old composer pick resurfacing on rebuild.
+ superseded_pin = session.pop("model_override"), composer_profile
+ session["composer_override_profile"] = None
# Record first so a broken config gets one attempt per edit, not per turn.
session["config_model_seen"] = target
model, provider = target
# Already on the configured model (resumed before first sync, or a config revert after
# a failed switch): adopt without switching.
- if target == seen or (
- model == getattr(agent, "model", "") and (not provider or provider == getattr(agent, "provider", ""))):
+ if model == getattr(agent, "model", "") and (not provider or provider == getattr(agent, "provider", "")):
+ if superseded_pin is not None:
+ _persist_live_session_runtime(session)
return
raw = f"{model} --provider {provider}" if provider else model
try:
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 69a3ccf5d1a..e4a5555ec0d 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1505,15 +1505,21 @@ def _parse_model_config(raw, *, quiet: bool = False) -> dict:
def _stored_session_runtime_overrides(row: dict | None) -> dict:
"""Runtime fields persisted with a stored session (model column, ``billing_provider``, JSON ``model_config``):
resume restores the model/provider/reasoning THAT chat used, not the global pick. Plugin-owned Bot-Mode
- sessions are exempt and rebuild from the member profile's CURRENT config (a stale provider pin left
- room bots "out of Nous credits" after a profile switch); signals: ``room_plumbing`` /
- ``follow_profile_config`` markers, the legacy hidden + "Group:" title, the title exactly "Bot Chat"."""
+ sessions normally rebuild from the member profile's CURRENT config (a stale provider pin left room bots
+ "out of Nous credits" after a profile switch). A canonical Bot Chat may instead restore an explicit
+ composer pick while the profile model it diverged from remains unchanged."""
if not row:
return {}
model_config = _parse_model_config(row.get("model_config"), quiet=True)
_row_title = str(row.get("title") or "").strip()
- if (model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))
- or model_config.get("follow_profile_config") or _row_title == "Bot Chat"):
+ room_plumbing = model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))
+ follows_profile = model_config.get("follow_profile_config") or _row_title == "Bot Chat"
+ composer_profile = model_config.get("composer_override_profile")
+ composer_profile_matches = isinstance(composer_profile, dict) and (
+ str(composer_profile.get("model") or "").strip(),
+ str(composer_profile.get("provider") or "").strip(),
+ ) == _config_model_target()
+ if room_plumbing or (follows_profile and not composer_profile_matches):
return {}
overrides: dict = {}
field = lambda k: str(model_config.get(k) or "").strip()
@@ -1594,6 +1600,10 @@ def _persist_live_session_runtime(session: dict | None) -> None:
try:
row = db.get_session(session_key) or {}
model_config = _runtime_model_config(agent, _parse_model_config(row.get("model_config")))
+ if isinstance(composer_profile := session.get("composer_override_profile"), dict):
+ model_config["composer_override_profile"] = composer_profile
+ elif "composer_override_profile" in session:
+ model_config.pop("composer_override_profile", None)
if (tier_override := session.get("create_service_tier_override")) is not None:
# agent.service_tier is None for explicit normal; without this the distinction is erased on every persist.
model_config["service_tier"] = tier_override or "normal"
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index e06bbb2b034..e7953475729 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -234,11 +234,13 @@ def _workdir_row_model_config(session: dict) -> tuple[str, dict]:
# Same ``_branched_from`` marker the TUI /branch uses (list_sessions_rich + sidebar nesting).
if parent_session_id := session.get("parent_session_id"):
model_config["_branched_from"] = parent_session_id
- # Bot-Mode canonical chats / room plumbing are plugin-owned scratch conversations whose runtime must ALWAYS follow
- # the member profile's CURRENT config, never the provider pinned at first write (see _stored_session_runtime_overrides).
+ # Room plumbing always follows the member profile. Canonical Bot Chats do too until the composer records an
+ # explicit chat-scoped pick plus the profile model it diverged from (see _stored_session_runtime_overrides).
for flag in ("room_plumbing", "follow_profile_config"):
if session.get(flag):
model_config[flag] = True
+ if isinstance(composer_profile := session.get("composer_override_profile"), dict):
+ model_config["composer_override_profile"] = composer_profile
return row_model, model_config