The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): concurrent /model commands commit in issue order
teknium1d4d383ee6394
diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.pyindex bdf86281cbf..331c84a1865 100644--- a/gateway/slash_commands_model.py+++ b/gateway/slash_commands_model.py@@ -337,7 +337,25 @@ class GatewayModelCommandsMixin:self, result, ctx: _ModelSwitchContext, *, source, picker: bool = False) -> str:"""Apply a resolved switch (cached agent, session, config) and build the confirmation; shared- by the typed path and the picker callback (``picker=True`` never carries --once)."""+ by the typed path and the picker callback (``picker=True`` never carries --once).++ Entry for the picker / cost-confirm callbacks, which fire outside ``_handle_model_command``+ and take the switch lock themselves; the typed path already holds it."""+ async with self._model_switch_lock():+ return await self._commit_model_switch_locked(result, ctx, source=source, picker=picker)++ def _model_switch_lock(self) -> asyncio.Lock:+ """Runner-wide lock over a /model command's read-resolve-commit. Slash commands bypass the busy+ guard while no agent runs, so a second /model on the same (or another) session otherwise+ interleaves with the first's store/config awaits: two ``--global`` picks left config.yaml on+ whichever thread wrote last and a ``--global`` cleanup wiped a session pick issued after it+ (#100314). Lazy: the runner is built without __init__ in tests."""+ lock = self.__dict__.get("_model_switch_lock_obj")+ if lock is None:+ lock = self.__dict__["_model_switch_lock_obj"] = asyncio.Lock()+ return lock++ async def _commit_model_switch_locked(self, result, ctx: _ModelSwitchContext, *, source, picker: bool) -> str:one_turn = False if picker else ctx.one_turnerror = self._switch_cached_agent_model(result, ctx, picker)if error is not None:@@ -461,7 +479,12 @@ class GatewayModelCommandsMixin:)async def _handle_model_command(self, event: MessageEvent) -> Optional[str]:- """Handle /model command — switch model."""+ """Handle /model command — switch model. Taken under the switch lock BEFORE the first await so+ concurrent commands commit in issue order (see ``_model_switch_lock``)."""+ async with self._model_switch_lock():+ return await self._handle_model_command_locked(event)++ async def _handle_model_command_locked(self, event: MessageEvent) -> Optional[str]:from gateway.run import _hermes_homefrom hermes_cli.model_switch import parse_model_switch_args, resolve_persist_behavior@@ -514,7 +537,7 @@ class GatewayModelCommandsMixin:guard_fired, guard_reply = await self._model_selection_guard_reply(event, ctx, result)if guard_fired:return guard_reply- return await self._commit_model_switch(result, ctx, source=source)+ return await self._commit_model_switch_locked(result, ctx, source=source, picker=False)# -------------------------------------------------- /codex-runtime, /personalitydiff --git a/tests/gateway/test_model_picker_persist.py b/tests/gateway/test_model_picker_persist.pyindex 5b4a336e444..c374506281b 100644--- a/tests/gateway/test_model_picker_persist.py+++ b/tests/gateway/test_model_picker_persist.py@@ -19,6 +19,7 @@ callback and assert ``config.yaml`` is (or isn't) updated — exercising the exaclosure the PR changed, against a real temp ``HERMES_HOME``."""+import asyncioimport typesimport yaml@@ -331,3 +332,32 @@ async def test_global_switch_keeps_session_override_when_config_write_fails(tmp_assert "disk full" in confirmationassert runner._session_model_override(session_key)["model"] == "gpt-5.5"assert runner.session_store.get_model_override(session_key)["model"] == "gpt-5.5"+++async def test_concurrent_model_commands_commit_in_issue_order(tmp_path, monkeypatch):+ """Two /model commands on one session dispatched concurrently (a second slash command bypasses the+ busy guard while no agent runs) must commit as if issued serially: a ``--global`` pick followed by+ a session pick leaves config.yaml on the global model AND the session override on the later pick,+ instead of the global cleanup wiping it; memory and durable store agree (#100314)."""+ from hermes_cli.model_switch import ModelSwitchResult++ def _switch(**kw):+ return ModelSwitchResult(success=True, new_model=kw["raw_input"], target_provider="openrouter",+ provider_changed=False, api_key="sk-test", base_url="https://openrouter.ai/api/v1",+ api_mode="chat_completions", provider_label="OpenRouter",+ is_global=kw.get("is_global", False))++ cfg_path = _setup_isolated_home(tmp_path, monkeypatch, {"default": "old-model", "provider": "openrouter"})+ monkeypatch.setattr("hermes_cli.model_switch.switch_model", _switch)+ 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)++ await asyncio.gather(runner._handle_model_command(_make_event("/model model-A --global")),+ runner._handle_model_command(_make_event("/model model-B")))++ assert 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"