Skip to content

The agent that grows with you

fix(cli): subscribe the session a /resume or /sessions switch lands on

Daniel V. Baeckere0561116c600
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index 1662f9adef1..de76b833347 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -35,6 +35,8 @@ from hermes_cli.cli_agent_setup_mixin import _gateway_owned_id, _retire_agent
from hermes_cli.cli_commands_session_tools import (
CLICommandsSessionToolsMixin, _TTYBuf, _accent, _accent_line, _command_arg, _cp, _dim,
_dim_line, _gt, _lines, _pr, _probe, _rollback_kept, _save, _say_block, _shlex_args, _t, _tn)
+from hermes_cli.cli_session_switch import (
+ _end_current_session, _open_switched_session, _sync_agent_to_session)
from hermes_cli.browser_connect import (
DEFAULT_BROWSER_CDP_URL, discover_local_cdp_url, find_free_debug_port, is_browser_debug_ready,
launch_chrome_debug, local_port_in_use, manual_chrome_debug_command)
@@ -175,52 +177,7 @@ def _cron_api(**kwargs) -> dict:
return json.loads(cronjob_tool(**kwargs))
-# Session-switch plumbing shared by /resume and /branch.
-def _end_current_session(cli, reason: str) -> None:
- """Flush un-persisted messages, then end the current session row with ``reason``.
- Best-effort on both steps (the switch proceeds even if the DB write fails)."""
- if cli.agent:
- with suppress(Exception):
- cli.agent._flush_messages_to_session_db(
- cli.conversation_history, conversation_history=cli.conversation_history)
- with suppress(Exception):
- cli._session_db.end_session(cli.session_id, reason)
-
-
-def _sync_agent_to_session(cli, session_id: str, *, parent_session_id: str, reason: str) -> None:
- """Point an already-built agent at ``session_id`` after a /resume or /branch switch: reset
- per-session state, re-anchor the DB flush index, and notify memory providers with
- reset=False (their state stays valid and just targets the new id; parent keeps lineage)."""
- if not cli.agent:
- return
- cli.agent.session_id = session_id
- cli.agent.reset_session_state()
- if hasattr(cli.agent, "_last_flushed_db_idx"):
- cli.agent._last_flushed_db_idx = len(cli.conversation_history)
- if hasattr(cli.agent, "_todo_store"):
- with suppress(Exception):
- from tools.todo_tool import TodoStore
- cli.agent._todo_store = TodoStore()
- if hasattr(cli.agent, "_invalidate_system_prompt"):
- cli.agent._invalidate_system_prompt()
- with suppress(Exception):
- _mm = getattr(cli.agent, "_memory_manager", None)
- # Notify memory providers that session_id rotated to a fresh conversation. reset=True signals
- # providers to flush accumulated per-session state (_session_turns, _turn_counter, _document_id).
- # Fires BEFORE the plugin on_session_reset hook (shell hooks only see the new id; Python providers
- # see the transition). See #6672. When the old session has history, end-of-session extraction
- # (LLM-bound, seconds) and this switch are queued as ONE task on the memory manager's serialized
- # worker — end strictly before switch, without blocking /new (#16454). With no history there is
- # nothing to extract; switch inline as before.
- # Notify memory providers that session_id rotated to a resumed session. reset=False — the provider's
- # accumulated state is still valid; it just needs to target the new session_id for subsequent
- # writes. See #6672.
- # Notify memory providers that session_id forked to a new branch. reset=False — the branched session
- # carries the transcript forward, so provider state tracks the lineage. parent_session_id links the
- # branch back to the original. See #6672.
- if _mm is not None:
- _mm.on_session_switch(
- session_id, parent_session_id=parent_session_id or "", reset=False, reason=reason)
+# Session-switch plumbing (end, open, repoint) lives in ``hermes_cli/cli_session_switch.py``.
def _without_session_meta(messages) -> list:
@@ -926,7 +883,16 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):
return _cp(f" {kanban_refusal}")
read_id, target_id = target_id, _gateway_owned_id(self._session_db, target_id) # the receipt owner
if target_id == self.session_id:
+ # Already on it: a launch whose attach was refused lands here without a subscription,
+ # so open it before reporting.
+ if (refusal := _open_switched_session(self, target_id)):
+ return _cp(f" {_gt('resume.switch_failed')} {target_id} ({refusal})")
return _cp(f" {_t('resume.already_on')}")
+ # A switched-to session must be subscribed on this viewer before its first turn
+ # (``_open_switched_session``): the write side is the gateway's, and /resume can land
+ # before any agent exists.
+ if (refusal := _open_switched_session(self, target_id)):
+ return _cp(f" {_gt('resume.switch_failed')} {target_id} ({refusal})")
old_session_id = self.session_id
_end_current_session(self, "resumed_other")
self.session_id, self._resumed, self._pending_title = target_id, True, None
diff --git a/hermes_cli/cli_session_switch.py b/hermes_cli/cli_session_switch.py
new file mode 100644
index 00000000000..3baf4a6adc4
--- /dev/null
+++ b/hermes_cli/cli_session_switch.py
@@ -0,0 +1,93 @@
+"""Session-switch plumbing shared by /resume, /sessions and /branch.
+
+The switch itself lives in ``cli_commands_mixin``; the handoff it needs sits here: end the row
+being left, open the row being entered on this viewer, then repoint an already-built agent.
+"""
+from __future__ import annotations
+
+from contextlib import suppress
+
+# A gateway that answers with one of these has refused this viewer for the target session
+# (ownership, profile), so the switch must not move the chat onto it. Every other reason it can
+# answer (session_busy, runtime_coordination_required, storage_unavailable, unknown_execution,
+# admission_conflict, stale_generation, runtime_draining, not_found) is transient or
+# ownership-free: the switch proceeds as it always did and the turn reports what is left.
+_SWITCH_REFUSALS = frozenset({'permission_denied', 'profile_mismatch'})
+
+
+def _end_current_session(cli, reason: str) -> None:
+ """Flush un-persisted messages, then end the current session row with ``reason``.
+ Best-effort on both steps (the switch proceeds even if the DB write fails)."""
+ if cli.agent:
+ with suppress(Exception):
+ cli.agent._flush_messages_to_session_db(
+ cli.conversation_history, conversation_history=cli.conversation_history)
+ with suppress(Exception):
+ cli._session_db.end_session(cli.session_id, reason)
+
+
+def _open_switched_session(cli, session_id: str) -> str | None:
+ """Subscribe ``session_id`` on this viewer's connection before a switch commits.
+
+ Reads at the switch are local by design, the write side is a gateway verb: the gateway
+ refuses ``prompt.submit`` for a session its connection never resumed
+ (``gateway/session_controls.py``: ``submit`` -> ``permission_denied``). Startup resume and
+ the agent's ``session_id`` setter reach the store's ``attach``; a switch typed before the
+ first turn reaches neither, because ``_sync_agent_to_session`` only repoints an agent that
+ already exists, so the first prompt after the switch was refused instead of answering.
+
+ Returns ``None`` when the switch may proceed, else the refusal reason for the caller to
+ report. Printing stays with the caller: its copy and its seams are the handler's.
+ """
+ store = getattr(cli, "_session_db", None)
+ attach = getattr(store, "attach", None)
+ if not callable(attach):
+ return None
+ from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
+ try:
+ attach(session_id)
+ except GatewayRPCError as exc:
+ # The owner answered: only an ownership refusal stops the switch.
+ reason = str(exc)
+ return reason if reason in _SWITCH_REFUSALS else None
+ except GatewayClientError:
+ # No answer (unavailable, disconnected, timeout). The switch's reads are local, so it
+ # proceeds as before; the turn reports the lost connection itself.
+ return None
+ return None
+
+
+def _sync_agent_to_session(cli, session_id: str, *, parent_session_id: str, reason: str) -> None:
+ """Point an already-built agent at ``session_id`` after a /resume or /branch switch: reset
+ per-session state, re-anchor the DB flush index, and notify memory providers with
+ reset=False (their state stays valid and just targets the new id; parent keeps lineage)."""
+ if not cli.agent:
+ return
+ cli.agent.session_id = session_id
+ cli.agent.reset_session_state()
+ if hasattr(cli.agent, "_last_flushed_db_idx"):
+ cli.agent._last_flushed_db_idx = len(cli.conversation_history)
+ if hasattr(cli.agent, "_todo_store"):
+ with suppress(Exception):
+ from tools.todo_tool import TodoStore
+ cli.agent._todo_store = TodoStore()
+ if hasattr(cli.agent, "_invalidate_system_prompt"):
+ cli.agent._invalidate_system_prompt()
+ with suppress(Exception):
+ _mm = getattr(cli.agent, "_memory_manager", None)
+ # Notify memory providers that session_id rotated to a fresh conversation. reset=True signals
+ # providers to flush accumulated per-session state (_session_turns, _turn_counter, _document_id).
+ # Fires BEFORE the plugin on_session_reset hook (shell hooks only see the new id; Python providers
+ # see the transition). See #6672. When the old session has history, end-of-session extraction
+ # (LLM-bound, seconds) and this switch are queued as ONE task on the memory manager's serialized
+ # worker — end strictly before switch, without blocking /new (#16454). With no history there is
+ # nothing to extract; switch inline as before.
+ # Notify memory providers that session_id rotated to a resumed session. reset=False — the provider's
+ # accumulated state is still valid; it just needs to target the new session_id for subsequent
+ # writes. See #6672.
+ # Notify memory providers that session_id forked to a new branch. reset=False — the branched session
+ # carries the transcript forward, so provider state tracks the lineage. parent_session_id links the
+ # branch back to the original. See #6672.
+ if _mm is not None:
+ _mm.on_session_switch(
+ session_id, parent_session_id=parent_session_id or "", reset=False, reason=reason)
diff --git a/tests/hermes_cli/test_cli_resume_command.py b/tests/hermes_cli/test_cli_resume_command.py
index 3654996697d..115946fb5f8 100644
--- a/tests/hermes_cli/test_cli_resume_command.py
+++ b/tests/hermes_cli/test_cli_resume_command.py
@@ -239,3 +239,113 @@ class TestResumeFlushesBeforeEndSession:
conversation_history=[{"role": "user", "content": "hello"}, {"role": "assistant", "content": "hi"}],
)
cli_obj._session_db.end_session.assert_called_once()
+
+
+class TestResumeSubscribesTheTarget:
+ """A switched-to session must be subscribed on this viewer before its first turn.
+
+ The write side is the gateway's, and it refuses ``prompt.submit`` for a session its
+ connection never resumed (``gateway/session_controls.py``: ``submit`` ->
+ ``permission_denied``, reported by the CLI as a failed model request). The switch reached
+ ``GatewaySessionStore.attach`` only through the agent's ``session_id`` setter, which needs
+ an agent: a ``/resume`` or ``/sessions <n>`` typed before the first turn subscribed
+ nothing, so that turn was refused instead of answering.
+ """
+
+ def _cli_switching_to(self, target):
+ cli_obj = _make_cli()
+ cli_obj._session_db.get_session.return_value = {"id": target, "title": "T"}
+ cli_obj._session_db.get_resume_conversations.return_value = ([], [])
+ cli_obj._session_db.resolve_resume_session_id.return_value = target
+ return cli_obj
+
+ def test_resume_subscribes_the_target_without_an_agent(self):
+ cli_obj = self._cli_switching_to("target")
+ assert cli_obj.agent is None
+
+ with (
+ patch("hermes_cli.main._resolve_session_by_name_or_id", return_value="target"),
+ patch("cli._cprint"),
+ ):
+ cli_obj._handle_resume_command("/resume target")
+
+ assert cli_obj.session_id == "target"
+ cli_obj._session_db.attach.assert_called_once_with("target")
+
+ def test_sessions_command_subscribes_the_target(self):
+ # /sessions <id> delegates to /resume (cli_commands_mixin._handle_sessions_command).
+ cli_obj = self._cli_switching_to("target")
+
+ with (
+ patch("hermes_cli.main._resolve_session_by_name_or_id", return_value="target"),
+ patch("cli._cprint"),
+ ):
+ cli_obj._handle_sessions_command("/sessions target")
+
+ assert cli_obj.session_id == "target"
+ cli_obj._session_db.attach.assert_called_once_with("target")
+
+ def test_a_refused_subscription_keeps_the_current_session(self):
+ from agent.i18n import t
+
+ from hermes_cli.gateway_client import GatewayRPCError
+
+ cli_obj = self._cli_switching_to("target")
+ cli_obj._session_db.attach.side_effect = GatewayRPCError("permission_denied")
+
+ with (
+ patch("hermes_cli.main._resolve_session_by_name_or_id", return_value="target"),
+ patch("cli._cprint") as mock_cprint,
+ ):
+ cli_obj._handle_resume_command("/resume target")
+
+ assert cli_obj.session_id == "current_session"
+ printed = " ".join(str(call) for call in mock_cprint.call_args_list)
+ # The existing, already-translated catalog entry, not a raw key and not a new string.
+ assert t("gateway.resume.switch_failed") in printed
+ assert "target" in printed
+ assert "cli.commands." not in printed
+
+ def test_a_transient_refusal_does_not_block_the_switch(self):
+ # session_busy / runtime_coordination_required / storage_unavailable are retryable and
+ # ownership-free: the switch's reads are local, so it proceeds as it did before.
+ from hermes_cli.gateway_client import GatewayRPCError
+
+ cli_obj = self._cli_switching_to("target")
+ cli_obj._session_db.attach.side_effect = GatewayRPCError("session_busy")
+
+ with (
+ patch("hermes_cli.main._resolve_session_by_name_or_id", return_value="target"),
+ patch("cli._cprint"),
+ ):
+ cli_obj._handle_resume_command("/resume target")
+
+ assert cli_obj.session_id == "target"
+
+ def test_an_unreachable_gateway_does_not_block_the_switch(self):
+ from hermes_cli.gateway_client import GatewayClientError
+
+ cli_obj = self._cli_switching_to("target")
+ cli_obj._session_db.attach.side_effect = GatewayClientError("Gateway disconnected")
+
+ with (
+ patch("hermes_cli.main._resolve_session_by_name_or_id", return_value="target"),
+ patch("cli._cprint"),
+ ):
+ cli_obj._handle_resume_command("/resume target")
+
+ assert cli_obj.session_id == "target"
+
+ def test_already_on_still_opens_the_session(self):
+ cli_obj = _make_cli()
+ cli_obj._session_db.get_session.return_value = {"id": "current_session", "title": "T"}
+ cli_obj._session_db.resolve_resume_session_id.return_value = "current_session"
+
+ with (
+ patch("hermes_cli.main._resolve_session_by_name_or_id", return_value=None),
+ patch("cli._cprint"),
+ ):
+ cli_obj._handle_resume_command("/resume current_session")
+
+ assert cli_obj.session_id == "current_session"
+ cli_obj._session_db.attach.assert_called_once_with("current_session")
diff --git a/tests/hermes_cli/test_cli_resume_switch_guards.py b/tests/hermes_cli/test_cli_resume_switch_guards.py
new file mode 100644
index 00000000000..233dd64f1cb
--- /dev/null
+++ b/tests/hermes_cli/test_cli_resume_switch_guards.py
@@ -0,0 +1,276 @@
+"""/resume and /sessions session-switch subscription guards.
+
+Companion to ``tests/hermes_cli/test_cli_resume_command.py``, which already pins the
+baseline arms of the subscription fix (both switch spellings with no agent, the refusal
+abort, the already-on arm, the unreachable-gateway arm and the transient refusal that
+must not block the switch). This file guards the properties those arms leave open:
+
+* a refusal is atomic — the session being left is neither ended nor reloaded, and a live
+ agent is not repointed onto a session this viewer cannot write;
+* the refusal copy is a real catalog entry, not a raw dotted key;
+* the numbered-picker entry point (``_consume_pending_resume_selection`` -> the handler)
+ subscribes the session it selects, and its refusal keeps the current session;
+* a store without ``attach`` (no gateway facade) still switches;
+* the Kanban guard refuses *before* the new attach is attempted;
+* the sibling ``/branch`` still subscribes its child, and not the parent.
+
+``_open_switched_session`` (``hermes_cli/cli_session_switch.py``) is the seam: it subscribes
+``session_id`` on this viewer's connection and only then may the switch commit.
+"""
+
+from __future__ import annotations
+
+import types
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from agent.i18n import t
+from cli import HermesCLI
+from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
+
+
+def _make_cli():
+ """HermesCLI host double: ``_session_db`` is a MagicMock, so ``attach`` is observable."""
+ cli_obj = HermesCLI.__new__(HermesCLI)
+ cli_obj.session_id = "current_session"
+ cli_obj._resumed = False
+ cli_obj._pending_title = None
+ cli_obj.conversation_history = []
+ cli_obj.agent = None
+ cli_obj._session_db = MagicMock()
+ cli_obj._pending_resume_sessions = None
+ # _display_resumed_history reads resume_display; "minimal" short-circuits the recap.
+ cli_obj.resume_display = "minimal"
+ return cli_obj
+
+
+def _cli_switching_to(target):
+ cli_obj = _make_cli()
+ cli_obj._session_db.get_session.return_value = {"id": target, "title": "T"}
+ cli_obj._session_db.get_resume_conversations.return_value = ([], [])
+ cli_obj._session_db.resolve_resume_session_id.return_value = target
+ return cli_obj
+
+
+def _resume(cli_obj, cmd="/resume target"):
+ """Run ``/resume`` with the name resolver pinned; return the ``_cprint`` mock."""
+ with (
+ patch("hermes_cli.main._resolve_session_by_name_or_id", return_value="target"),
+ patch("cli._cprint") as mock_cprint,
+ ):
+ cli_obj._handle_resume_command(cmd)
+ return mock_cprint
+
+
+def _printed(mock_cprint):
+ return " ".join(str(call) for call in mock_cprint.call_args_list)
+
+
+class TestRefusalIsAtomic:
+ """A refused subscription must abort the whole switch, not half of it."""
+
+ def test_a_refused_subscription_does_not_end_or_reload_the_session_being_left(self):
+ cli_obj = _cli_switching_to("target")
+ cli_obj._session_db.attach.side_effect = GatewayRPCError("permission_denied")
+
+ _resume(cli_obj)
+
+ assert cli_obj.session_id == "current_session"
+ # The old row is ended only after the target is subscribed; on a refusal it is untouched,
+ # so history is not reloaded onto a session the viewer may not write.
+ cli_obj._session_db.end_session.assert_not_called()
+ cli_obj._session_db.get_resume_conversations.assert_not_called()
+ cli_obj._session_db.reopen_session.assert_not_called()
+
+ def test_a_refused_subscription_leaves_an_existing_agent_on_the_old_session(self):
+ cli_obj = _cli_switching_to("target")
+ agent = MagicMock()
+ agent.session_id = "current_session"
+ cli_obj.agent = agent
+ cli_obj._session_db.attach.side_effect = GatewayRPCError("permission_denied")
+
+ _resume(cli_obj)
+
+ # _sync_agent_to_session must not fire: repointing the live agent would flush the next
+ # turn's messages onto a session the gateway refuses.
+ assert agent.session_id == "current_session"
+ agent.reset_session_state.assert_not_called()
+ agent._flush_messages_to_session_db.assert_not_called()
+ cli_obj._session_db.end_session.assert_not_called()
+
+
+class TestRefusalCopy:
+ def test_the_refusal_copy_comes_from_the_catalog_not_a_raw_key(self):
+ cli_obj = _cli_switching_to("target")
+ cli_obj._session_db.attach.side_effect = GatewayRPCError("permission_denied")
+
+ mock_cprint = _resume(cli_obj)
+ printed = _printed(mock_cprint)
+
+ # The handler renders the existing `resume.switch_failed` entry the gateway shares
+ # verbatim (already translated in every catalog), and names the session it stayed on.
+ rendered = t("gateway.resume.switch_failed")
+ assert rendered != "gateway.resume.switch_failed", "the refusal copy is missing from the catalog"
+ assert rendered in printed
+ assert "target" in printed
+ assert "cli.commands." not in printed, "a raw catalog key reached the user"
+
+
+class TestNumberedPickerEntryPoint:
+ """A bare number after a bare /resume re-enters the handler; the select must subscribe too."""
+
+ def _armed_cli(self):
+ cli_obj = _make_cli()
+ sessions = [{"id": "sess_002", "title": "Coding"}, {"id": "sess_001", "title": "Research"}]
+ cli_obj._pending_resume_sessions = sessions
+ # The handler re-resolves the index through _list_recent_sessions.
+ cli_obj._list_recent_sessions = MagicMock(return_value=sessions)
+ cli_obj._session_db.get_session.return_value = {"id": "sess_001", "title": "Research"}
+ cli_obj._session_db.get_resume_conversations.return_value = ([], [])
+ cli_obj._session_db.resolve_resume_session_id.return_value = "sess_001"
+ return cli_obj
+
+ def test_the_numbered_picker_subscribes_the_selected_session_exactly_once(self):
+ cli_obj = self._armed_cli()
+
+ with patch("cli._cprint"):
+ consumed = cli_obj._consume_pending_resume_selection("2")
+
+ assert consumed is True
+ assert cli_obj.session_id == "sess_001"
+ # Exactly one attach for the switch's target, and never the session being left.
+ cli_obj._session_db.attach.assert_called_once_with("sess_001")
+
+ def test_the_numbered_picker_refusal_keeps_the_current_session(self):
+ cli_obj = self._armed_cli()
+ cli_obj._session_db.attach.side_effect = GatewayRPCError("permission_denied")
+
+ with patch("cli._cprint"):
+ consumed = cli_obj._consume_pending_resume_selection("2")
+
+ assert consumed is True
+ assert cli_obj.session_id == "current_session"
+ cli_obj._session_db.end_session.assert_not_called()
+ # One-shot prompt is still disarmed after the refused selection.
+ assert cli_obj._pending_resume_sessions is None
+
+
+class TestStoreWithoutAttach:
+ """Off the gateway facade there is no `attach`: the switch proceeds as it always did."""
+
+ @pytest.mark.parametrize("blank", ["delete", "none"])
+ def test_a_store_without_a_callable_attach_still_switches(self, blank):
+ cli_obj = _cli_switching_to("target")
+ if blank == "delete":
+ del cli_obj._session_db.attach
+ else:
+ cli_obj._session_db.attach = None
+
+ _resume(cli_obj)
+
+ assert cli_obj.session_id == "target"
+ # The committed switch still ends the row it left.
+ cli_obj._session_db.end_session.assert_called_once_with("current_session", "resumed_other")
+
+
+class TestKanbanGuardPrecedesTheAttach:
+ def test_the_kanban_guard_refuses_before_any_subscription(self, monkeypatch):
+ monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)
+ cli_obj = _cli_switching_to("target")
+ cli_obj._session_db.is_kanban_owned_session.return_value = True
+
+ mock_cprint = _resume(cli_obj)
+
+ assert cli_obj.session_id == "current_session"
+ cli_obj._session_db.attach.assert_not_called()
+ cli_obj._session_db.end_session.assert_not_called()
+ assert t("cli.resume.kanban_owned", session_id="target") in _printed(mock_cprint)
+
+
+class _Agent:
+ """Minimal agent double: no `_memory_manager`, no `_todo_store` (keeps the switch inert)."""
+
+ def __init__(self, sid):
+ self.session_id = sid
+ self._last_flushed_db_idx = 0
+
+ def _flush_messages_to_session_db(self, history, conversation_history=None):
+ pass
+
+ def reset_session_state(self):
+ pass
+
+
+class _ScriptedGateway:
+ """The store's connection: answers `session.resume` for the ids it knows and forks on branch."""
+
+ def __init__(self, child="child"):
+ self.child = child
+ self.final = False # the store's __bool__ reads connection.final
+ self.calls: list[tuple[str, dict]] = []
+ self.known = {"parent"}
+ self._states: dict[str, object] = {}
+
+ def call(self, method, **params):
+ self.calls.append((method, dict(params)))
+ if method == "session.resume":
+ sid = params["session_id"]
+ if sid not in self.known:
+ raise GatewayClientError("not_found")
+ return {"session_id": sid, "stored_session_id": sid, "messages": [], "revision": 1,
+ "execution_generation": 0, "subscription_id": "sub-" + sid, "info": {}}
+ if method == "session.mutate" and params.get("operation") == "branch":
+ self.known.add(self.child)
+ return {"branched_session_id": self.child, "copied_messages": 1}
+ return {"status": "ok"}
+
+ def state(self, sid):
+ return self._states.setdefault(sid, types.SimpleNamespace(adopt_snapshot=lambda _snapshot: None))
+
+
+def test_branch_still_subscribes_its_child_not_the_parent(monkeypatch, tmp_path):
+ """/branch shares _end_current_session/_sync_agent_to_session with /resume: the fix must not
+ cost the sibling command its child subscription (the child is opened by the store's branch)."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ from hermes_state import SessionDB
+ from hermes_cli.gateway_session_store import GatewaySessionStore
+
+ writer = SessionDB(db_path=tmp_path / "state.db")
+ writer.create_session("parent", source="local", model="m")
+ writer.set_session_title("parent", "Parent")
+ writer.append_message("parent", "user", "hi")
+ writer.close()
+
+ gateway = _ScriptedGateway()
+ store = GatewaySessionStore(gateway)
+ attached: list[str] = []
+ _real_attach = store.attach
+
+ def _recording_attach(session_id):
+ attached.append(session_id)
+ return _real_attach(session_id)
+
+ store.attach = _recording_attach
+
+ host = object.__new__(HermesCLI)
+ host._session_db = store
+ host._gateway_session_open = True
+ host.session_id = "parent"
+ host._agent_running = False
+ host.conversation_history = [{"role": "user", "content": "hi"}]
+ host.model = "m"
+ host.max_turns = 5
+ host.reasoning_config = {}
+ host._pending_title = None
+ host._resumed = False
+ host.agent = _Agent("parent")
+ host._new_session_id = lambda now, **kw: HermesCLI._new_session_id(host, now, **kw)
+
+ with patch("cli._cprint"):
+ host._handle_branch_command("/branch explore")
+
+ assert host.session_id == "child"
+ # The viewer is subscribed to its child, exactly once, and never to the session it left.
+ assert attached == ["child"]
+ assert set(store.snapshots) == {"child"}