The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a --global /model keeps the session override under a channel_overrides model; report a failed stale-override cleanup
teknium103d40f8939d0
diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.pyindex 331c84a1865..53ede6ad552 100644--- a/gateway/slash_commands_model.py+++ b/gateway/slash_commands_model.py@@ -198,8 +198,8 @@ class GatewayModelCommandsMixin:) -> Optional[str]:"""Persist a committed switch: session DB, next-turn note, config write-through, override map.- Returns the config-write error for a ``--global`` switch whose ``config.yaml`` write failed- (the switch then stays a session override), else ``None``.+ Returns the warning for a ``--global`` switch whose ``config.yaml`` write or stale-override+ cleanup failed (the switch then stays a session override), else ``None``."""from hermes_cli.model_switch import format_model_for_display@@ -251,13 +251,18 @@ class GatewayModelCommandsMixin:await _persist_model_switch_to_config(result, ctx.config_path)except Exception as e:logger.warning("Failed to persist model switch: %s", e)- global_error = str(e) or type(e).__name__- if ctx.persist_global and global_error is None:- self._session_model_overrides.pop(ctx.session_key, None)+ global_error = f"config.yaml not updated ({str(e) or type(e).__name__})"+ # Precedence is session > channel_overrides > config.yaml: in a chat with a channel_overrides+ # model/provider the session override must stay, or the next turn runs the channel model.+ if ctx.persist_global and global_error is None and self._channel_override_for(source) is None:try:await self.async_session_store.set_model_override(ctx.session_key, None)- except Exception:- logger.debug("Failed to clear persisted session model override", exc_info=True)+ except Exception as e:+ # Store still holds the stale copy: keep memory in agreement and report it (#100314).+ logger.warning("Failed to clear persisted session model override: %s", e)+ global_error = f"saved to config.yaml, but the stale session override was not cleared ({e})"+ else:+ self._session_model_overrides.pop(ctx.session_key, None)# Non-secret write-through so the override survives a restart (api_key/api_mode are# re-resolved on rehydration); a --once override must NOT outlive a restart.# Write-through the non-secret parts (model/provider/base_url) to the session store so the override@@ -323,7 +328,7 @@ class GatewayModelCommandsMixin:lines.append(t("gateway.model.warning_prefix", warning=result.warning_message))if ctx.persist_global and global_error is not None:# Never claim a clean global commit the disk did not take (#100314).- lines.append(t("gateway.model.warning_prefix", warning=f"config.yaml not updated ({global_error})"))+ lines.append(t("gateway.model.warning_prefix", warning=global_error))lines.append(t("gateway.model.session_only_hint"))elif ctx.persist_global:lines.append(t("gateway.model.saved_global"))@@ -344,6 +349,18 @@ class GatewayModelCommandsMixin:async with self._model_switch_lock():return await self._commit_model_switch_locked(result, ctx, source=source, picker=picker)+ def _channel_override_for(self, source):+ """This chat's ``channel_overrides`` entry (model/provider), or None."""+ from gateway.run import _get_channel_override+ cfg = getattr(self, "config", None)+ if not cfg or source is None:+ return None+ return _get_channel_override(+ cfg, source.platform, str(source.chat_id) if source.chat_id else "",+ thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,+ parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,+ )+def _model_switch_lock(self) -> asyncio.Lock:"""Runner-wide lock over a /model command's read-resolve-commit. Slash commands bypass the busyguard while no agent runs, so a second /model on the same (or another) session otherwisediff --git a/tests/gateway/test_model_picker_persist.py b/tests/gateway/test_model_picker_persist.pyindex c374506281b..719db5697b8 100644--- a/tests/gateway/test_model_picker_persist.py+++ b/tests/gateway/test_model_picker_persist.py@@ -361,3 +361,49 @@ async def test_concurrent_model_commands_commit_in_issue_order(tmp_path, monkeypassert yaml.safe_load(cfg_path.read_text(encoding="utf-8"))["model"]["default"] == "model-A"assert runner._session_model_override(session_key)["model"] == "model-B"assert runner.session_store.get_model_override(session_key)["model"] == "model-B"+++async def test_global_switch_keeps_session_override_under_channel_override(tmp_path, monkeypatch):+ """Precedence is session /model > channel_overrides > config.yaml. In a chat whose+ ``channel_overrides`` names a model, a ``--global`` pick must NOT drop the session override:+ config.yaml alone would lose to the channel model on the next turn while the confirmation+ claims the switch to gpt-5.5 (#100314 follow-up)."""+ from gateway.config import ChannelOverride, GatewayConfig, PlatformConfig++ _setup_isolated_home(tmp_path, monkeypatch, {"default": "old-model", "provider": "openrouter"})+ runner = _make_store_runner(_FakePickerAdapter(), tmp_path / "sessions", monkeypatch)+ runner.config = GatewayConfig(platforms={Platform.TELEGRAM: PlatformConfig(+ enabled=True, channel_overrides={"12345": ChannelOverride(model="channel-model")})})+ source = _make_event("x").source+ runner.session_store.get_or_create_session(source)++ confirmation = await _typed_global(runner)++ assert "gpt-5.5" in confirmation+ model, _runtime = runner._resolve_session_agent_runtime(source=source)+ assert model == "gpt-5.5", f"next turn would run {model!r} while the confirmation says gpt-5.5"+ assert runner.session_store.get_model_override(runner._session_key_for_source(source))["model"] == "gpt-5.5"+++async def test_global_switch_reports_failed_stale_override_cleanup(tmp_path, monkeypatch):+ """config.yaml written but the stale session override could not be cleared from the store: the+ in-memory override stays (memory agrees with the store's copy surviving) and the confirmation+ warns instead of claiming a clean 'Saved to config.yaml' (#100314 acceptance)."""+ _setup_isolated_home(tmp_path, monkeypatch, {"default": "old-model", "provider": "openrouter"})+ runner = _make_store_runner(_FakePickerAdapter(), tmp_path / "sessions", monkeypatch)+ source = _make_event("x").source+ session_key = runner._session_key_for_source(source)+ runner.session_store.get_or_create_session(source)++ def _locked(key, override):+ raise OSError("store locked")++ monkeypatch.setattr(runner.session_store, "set_model_override", _locked)++ confirmation = await _typed_global(runner)++ assert "store locked" in confirmation+ assert "Saved to config.yaml" not in confirmation+ assert runner._session_model_override(session_key)["model"] == "gpt-5.5"diff --git a/website/docs/reference/slash-commands.md b/website/docs/reference/slash-commands.mdindex 2d21128096d..9e480050904 100644--- a/website/docs/reference/slash-commands.md+++ b/website/docs/reference/slash-commands.md@@ -245,7 +245,7 @@ The messaging gateway supports the following built-in commands inside Telegram,| `/new [name]` (alias: `/reset`) | Start a new session (fresh session ID + history). Optional `[name]` sets the initial session title. Append `now`, `--yes`, or `-y` to skip the confirmation modal — e.g. `/reset now`, `/new --yes my-experiment`. || `/status` | Show session info, followed by a local **Session recap** block (recent turn counts, top tools used, files touched, latest prompt + reply). || `/stop` | Kill all running background processes and interrupt the running agent. |-| `/model [provider:model]` | Show or change the model. Supports provider switches (`/model zai:glm-5`), custom endpoints (`/model custom:model`), named custom providers (`/model custom:local:qwen`), auto-detect (`/model custom`), OpenRouter account presets (`/model @preset/<slug>` — account-scoped, skips the public model-listing check), and user-defined aliases (`/model fav`, `/model grok` — see [Custom model aliases](#custom-model-aliases)). Use `--global` to persist the change to config.yaml; a successful `--global` pick (typed or picker) also drops this chat's session-only override, so config.yaml alone decides the model after a gateway restart. **Note:** `/model` can only switch between already-configured providers. To add a new provider or set up API keys, use `hermes model` from your terminal (outside the chat session). **Cost note:** a mid-session model switch resets the prompt cache (the cache key includes the model), so the next message re-reads the whole conversation at full input price. |+| `/model [provider:model]` | Show or change the model. Supports provider switches (`/model zai:glm-5`), custom endpoints (`/model custom:model`), named custom providers (`/model custom:local:qwen`), auto-detect (`/model custom`), OpenRouter account presets (`/model @preset/<slug>` — account-scoped, skips the public model-listing check), and user-defined aliases (`/model fav`, `/model grok` — see [Custom model aliases](#custom-model-aliases)). Use `--global` to persist the change to config.yaml; a successful `--global` pick (typed or picker) also drops this chat's session-only override, so config.yaml alone decides the model after a gateway restart (a chat with a `channel_overrides` model keeps the override, since the channel setting would otherwise outrank config.yaml; the CLI/TUI deliberately keep their per-session pin so resume restores the model that chat used). **Note:** `/model` can only switch between already-configured providers. To add a new provider or set up API keys, use `hermes model` from your terminal (outside the chat session). **Cost note:** a mid-session model switch resets the prompt cache (the cache key includes the model), so the next message re-reads the whole conversation at full input price. || `/codex-runtime [auto\|codex_app_server\|on\|off]` | Toggle the optional [Codex app-server runtime](../user-guide/features/codex-app-server-runtime). Persists to `model.openai_runtime` in config.yaml and evicts the cached agent so the next message picks up the new runtime. Effective on next session. || `/personality [name]` | Set a personality overlay for the session. `/personality none` (or `default` / `neutral`) clears it. || `/fast [normal\|fast\|auto\|cold\|status]` | Fast mode — OpenAI Priority Processing / Anthropic Fast Mode. `auto`/`cold` open a bounded fast window per turn / per session. |diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/slash-commands.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/slash-commands.mdindex e69f30697d8..d2176c9f609 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/slash-commands.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/slash-commands.md@@ -204,7 +204,7 @@ hermes config set model.aliases.grok x-ai/grok-4| `/reset` | 重置对话历史。 || `/status` | 显示会话信息,随后显示本地**会话摘要**块(近期轮次数、最常用工具、访问的文件、最新 prompt + 回复)。 || `/stop` | 终止所有正在运行的后台进程并中断运行中的 agent。 |-| `/model [provider:model]` | 显示或更改模型。支持提供商切换(`/model zai:glm-5`)、自定义端点(`/model custom:model`)、命名自定义提供商(`/model custom:local:qwen`)、自动检测(`/model custom`),以及用户自定义别名(`/model fav`、`/model grok`——见[自定义模型别名](#custom-model-aliases))。使用 `--global` 将更改持久化到 config.yaml;成功的 `--global` 选择(键入或选择器)还会清除本聊天的仅会话覆盖,因此网关重启后仅由 config.yaml 决定模型。**注意:** `/model` 只能在已配置的提供商之间切换。如需添加新提供商或设置 API 密钥,请在终端(聊天会话外)运行 `hermes model`。 |+| `/model [provider:model]` | 显示或更改模型。支持提供商切换(`/model zai:glm-5`)、自定义端点(`/model custom:model`)、命名自定义提供商(`/model custom:local:qwen`)、自动检测(`/model custom`),以及用户自定义别名(`/model fav`、`/model grok`——见[自定义模型别名](#custom-model-aliases))。使用 `--global` 将更改持久化到 config.yaml;成功的 `--global` 选择(键入或选择器)还会清除本聊天的仅会话覆盖,因此网关重启后仅由 config.yaml 决定模型(设有 `channel_overrides` 模型的聊天会保留该覆盖,否则频道设置会优先于 config.yaml;CLI/TUI 则有意保留各自的会话固定,以便恢复时沿用该聊天所用的模型)。**注意:** `/model` 只能在已配置的提供商之间切换。如需添加新提供商或设置 API 密钥,请在终端(聊天会话外)运行 `hermes model`。 || `/codex-runtime [auto\|codex_app_server\|on\|off]` | 切换可选的 [Codex app-server runtime](../user-guide/features/codex-app-server-runtime)。持久化到 config.yaml 中的 `model.openai_runtime` 并驱逐缓存的 agent,使下一条消息使用新 runtime。下次会话生效。 || `/personality [name]` | 为会话设置 personality 覆盖层。 || `/fast [normal\|fast\|status]` | 切换快速模式——OpenAI Priority Processing / Anthropic Fast Mode。 |