Skip to content

The agent that grows with you

test: one invariant suite for mid-turn session-switch refusals + docs

teknium16671365fb2cc
diff --git a/tests/hermes_cli/test_branch_command.py b/tests/hermes_cli/test_branch_command.py
index c8cab5e8fcd..053e605e513 100644
--- a/tests/hermes_cli/test_branch_command.py
+++ b/tests/hermes_cli/test_branch_command.py
@@ -35,6 +35,7 @@ def cli_instance(tmp_path, session_db):
from unittest.mock import MagicMock
cli = MagicMock()
+ cli._agent_running = False # a bare MagicMock attribute is truthy and would trip the mid-turn guard
cli._session_db = session_db
cli.session_id = "20260403_120000_abc123"
cli.model = "anthropic/claude-sonnet-4.6"
diff --git a/tests/hermes_cli/test_branch_mid_turn_guard.py b/tests/hermes_cli/test_branch_mid_turn_guard.py
deleted file mode 100644
index e59f7652ce3..00000000000
--- a/tests/hermes_cli/test_branch_mid_turn_guard.py
+++ /dev/null
@@ -1,42 +0,0 @@
-"""Regression: /branch refuses mid-turn (cross-project proposal pi-8937, upstream pi#8937).
-
-An in-flight agent run flushes through the rotating session identity: /branch ends
-the parent session row and repoints ``agent.session_id`` via ``_sync_agent_to_session``,
-so the turn's remaining messages land on the freshly created branch instead of the
-session they belong to. ``/handoff`` already refuses this race mid-turn via
-``_handoff_prepare_session``; ``/branch`` must match that behavior.
-"""
-import sys
-from types import SimpleNamespace
-
-from hermes_cli import cli_commands_mixin
-
-
-def _make_cli(agent_running: bool):
- cli = object.__new__(cli_commands_mixin.CLICommandsMixin)
- cli._agent_running = agent_running
- cli.conversation_history = [{"role": "user", "content": "hello"}]
- cli._session_db = None
- return cli
-
-
-def test_branch_refuses_mid_turn(monkeypatch):
- printed = []
- monkeypatch.setattr(cli_commands_mixin, "_cp", lambda *lines: printed.extend(lines))
- monkeypatch.setitem(sys.modules, "cli", SimpleNamespace(_sync_process_session_id=lambda *a, **k: None))
- cli = _make_cli(agent_running=True)
-
- cli._handle_branch_command("/branch explore")
-
- assert any("busy" in line for line in printed), printed
-
-
-def test_branch_still_proceeds_when_idle(monkeypatch):
- printed = []
- monkeypatch.setattr(cli_commands_mixin, "_cp", lambda *lines: printed.extend(lines))
- monkeypatch.setitem(sys.modules, "cli", SimpleNamespace(_sync_process_session_id=lambda *a, **k: None))
- cli = _make_cli(agent_running=False)
-
- cli._handle_branch_command("/branch explore")
-
- assert printed and "busy" not in " ".join(printed), printed
diff --git a/tests/hermes_cli/test_resume_mid_turn_guard.py b/tests/hermes_cli/test_resume_mid_turn_guard.py
deleted file mode 100644
index 5967a1c636b..00000000000
--- a/tests/hermes_cli/test_resume_mid_turn_guard.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""regression tests for refusing /resume during an active agent turn."""
-
-import sys
-from types import SimpleNamespace
-
-from hermes_cli import cli_commands_mixin
-
-
-def _make_cli(agent_running: bool):
- cli = object.__new__(cli_commands_mixin.CLICommandsMixin)
- cli._agent_running = agent_running
- cli._session_db = None
- cli._pending_resume_sessions = None
- return cli
-
-
-def test_resume_refuses_mid_turn(monkeypatch):
- printed = []
- monkeypatch.setattr(cli_commands_mixin, "_cp", lambda *lines: printed.extend(lines))
- cli = _make_cli(agent_running=True)
-
- cli._handle_resume_command("/resume previous-session")
-
- assert printed == [
- " Agent is busy. Wait for the current turn to finish, then retry /resume."
- ]
-
-
-def test_resume_keeps_existing_idle_behavior(monkeypatch):
- printed = []
- monkeypatch.setattr(cli_commands_mixin, "_cp", lambda *lines: printed.extend(lines))
- monkeypatch.setitem(sys.modules, "cli", SimpleNamespace(_sync_process_session_id=lambda *a, **k: None))
- cli = _make_cli(agent_running=False)
-
- cli._handle_resume_command("/resume previous-session")
-
- assert printed
- assert "busy" not in " ".join(printed).lower()
diff --git a/tests/hermes_cli/test_session_switch_mid_turn_guard.py b/tests/hermes_cli/test_session_switch_mid_turn_guard.py
new file mode 100644
index 00000000000..e777a0de02c
--- /dev/null
+++ b/tests/hermes_cli/test_session_switch_mid_turn_guard.py
@@ -0,0 +1,66 @@
+"""/branch, /resume and /sessions <id> refuse to switch sessions while a turn is in flight.
+
+The classic CLI shares ONE agent object across sessions: a switch ends the current session row and
+repoints ``agent.session_id`` (``_sync_agent_to_session``), so a still-running turn would flush its
+remaining messages onto the switched-to session. ``/handoff`` already refuses mid-turn for the same
+reason; these commands must match it. See #112137.
+"""
+
+import pytest
+
+from cli import HermesCLI
+from hermes_cli import cli_commands_mixin
+
+
+class _Agent:
+ 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
+
+
+def cli(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ obj = object.__new__(HermesCLI)
+ obj._session_db, obj.session_id, obj.model, obj.max_turns = db, "parent", "m", 5
+ obj.reasoning_config, obj._pending_title, obj._resumed, obj._pending_resume_sessions = {}, None, False, None
+ obj.agent = _Agent("parent")
+ obj.conversation_history = [{"role": "user", "content": "hi"}]
+ for name in ("_transfer_session_yolo", "_restore_session_cwd", "_restore_session_yolo",
+ "_restore_session_model", "_display_resumed_history"):
+ setattr(obj, name, lambda *a, **k: None)
+ db.create_session(session_id="parent", source="cli", model="m")
+ db.append_message("parent", "user", "hi")
+ db.create_session(session_id="other", source="cli", model="m")
+ db.append_message("other", "user", "x")
+ obj.printed = []
+ monkeypatch.setattr(cli_commands_mixin, "_cp", lambda *lines: obj.printed.extend(lines))
+ yield obj
+ db.close()
+
+
[email protected]("command", ["/branch explore", "/resume other", "/sessions other"])
+def test_session_switch_refused_mid_turn(cli, command):
+ cli._agent_running = True
+ handler = {"/branch": cli._handle_branch_command, "/resume": cli._handle_resume_command,
+ "/sessions": cli._handle_sessions_command}[command.split()[0]]
+ handler(command)
+ assert "busy" in " ".join(cli.printed).lower()
+ assert cli.session_id == "parent" and cli.agent.session_id == "parent"
+ assert cli._session_db.get_session("parent")["end_reason"] is None
+
+
+def test_session_switch_proceeds_when_idle(cli):
+ cli._agent_running = False
+ cli._handle_branch_command("/branch explore")
+ assert cli.session_id != "parent" and cli.agent.session_id == cli.session_id
+ assert cli._session_db.get_session("parent")["end_reason"] == "branched"
diff --git a/website/docs/reference/slash-commands.md b/website/docs/reference/slash-commands.md
index e54e6f43c9d..c6803adacf7 100644
--- a/website/docs/reference/slash-commands.md
+++ b/website/docs/reference/slash-commands.md
@@ -58,7 +58,7 @@ Type `/` in the CLI to open the autocomplete menu. Built-in commands are case-in
| `/refine [focus]` | Run the background memory/skill self-improvement review **now** instead of waiting for the automatic post-turn trigger. Optional focus text steers the review (e.g. `/refine save the deploy workflow as a skill`). Runs in a background fork against a conversation snapshot — the live session and prompt cache are untouched; results are reported when done. |
| `/review [instructions]` | Spawn an independent, full-privilege reviewer subagent to review the work just discussed — a PR, code, docs, any artifact referenced in the last 10 chat messages. It investigates in the background (opens the PR, reads the diff, runs code) and its full review re-enters this session as a background-subagent completion the primary agent can act on. Pin a dedicated review model via `auxiliary.review` in config.yaml (defaults to your main model). See [Subagent Delegation](/user-guide/features/delegation#the-review-command). |
| `/moa <prompt>` | Run a single prompt through the default [Mixture of Agents](/user-guide/features/mixture-of-agents) preset, then restore your current model. One-shot — does not change your session model. |
-| `/resume [name]` | Resume a previously-named session |
+| `/resume [name]` | Resume a previously-named session. In the classic CLI this (and `/sessions <id>`) is refused while a turn is running — the CLI shares one agent across sessions, so switching mid-turn would file the rest of the running turn under the other session. |
| `/sessions` (TUI alias: `/switch`) | Classic CLI: browse and resume previous sessions in an interactive picker. TUI: open the live session switcher for currently open TUI sessions. Use `/sessions new` in the TUI to start another live session immediately. |
| `/egress [status]` | Show Docker egress proxy status — enabled/configured/running state, credential source, token mappings, uncovered providers, and next remediation step. Works in CLI, TUI, Desktop chat, and messaging gateway. |
| `/redraw` | Force a full UI repaint (recovers from terminal drift after tmux resize, mouse selection artifacts, etc.) |
@@ -67,7 +67,7 @@ Type `/` in the CLI to open the autocomplete menu. Built-in commands are case-in
| `/agents` (alias: `/tasks`) | Show active agents and running tasks across the current session. |
| `/bg <prompt>` | Run a prompt in a separate background session. The agent processes your prompt independently — your current session stays free for other work. Results appear as a panel when the task finishes. See [CLI Background Sessions](/user-guide/cli#background-sessions). |
| `/btw <question>` | Ask a quick side question **about the current conversation** without interrupting it. A one-shot auxiliary LLM call answers from a read-only snapshot of the transcript — the live session's history and prompt cache are untouched, and the current turn keeps running. For independent work with a fresh context, use `/bg`. |
-| `/branch [name]` (alias: `/fork`) | Branch the current session (explore a different path) |
+| `/branch [name]` (alias: `/fork`) | Branch the current session (explore a different path). Classic CLI: refused mid-turn like `/handoff` — wait for the current response to finish, then retry. |
| `/worktree [new [name]\|list]` | **CLI only.** Inspect or create isolated git worktrees mid-session (inspired by Copilot CLI's `/worktree new`). Bare `/worktree` shows the active worktree; `/worktree list` lists the repo's worktrees; `/worktree new [name]` creates a worktree under `.worktrees/` (branched from the freshly-fetched remote tip, honoring `worktree_sync`) and retargets the session's terminal and file tools into it. Named trees use your name (`hermes/<name>` branch); unnamed ones get a random `hermes-<id>`. On exit the tree is kept only if it has unpushed commits — same lifecycle as `hermes -w`. See [Git Worktrees](/user-guide/git-worktrees). |
| `/handoff <platform>` | **CLI only.** Hand the current session off to a messaging platform (Telegram, Discord, Slack, WhatsApp, Signal, Matrix). The gateway picks it up immediately, creates a fresh thread on platforms that support threads (Telegram topics, Discord text-channel threads, Slack and Matrix message-anchored threads), re-binds the destination to your CLI session_id so the full role-aware transcript replays, and forges a synthetic user turn so the agent confirms it's working in the new place. Your CLI exits cleanly on success with a `/resume` hint; resume locally any time with `/resume <title>`. Refused mid-turn. Requires the gateway to be running and a home channel configured for the target platform (`/sethome` from the destination chat). See [Cross-Platform Handoff](/user-guide/sessions#cross-platform-handoff). |
| `/journey [list\|delete <id>\|edit <id>]` (aliases: `/learning`, `/memory-graph`) | Open the learning journey timeline of learned skills + memories. Works in the classic CLI, as a TUI overlay, and in the desktop app (Star Map panel). Not available on messaging platforms. See [Learning Journey](/user-guide/features/memory#learning-journey-journey). |