Skip to content

The agent that grows with you

feat(desktop): expose structured session controls

Jerry Gooch8cb2bcc8c147
diff --git a/tests/tui_gateway/test_session_control.py b/tests/tui_gateway/test_session_control.py
new file mode 100644
index 00000000000..549bc7fcf61
--- /dev/null
+++ b/tests/tui_gateway/test_session_control.py
@@ -0,0 +1,499 @@
+"""Behavioral contract tests for Desktop session-control JSON-RPC methods."""
+
+from __future__ import annotations
+
+import importlib
+import json
+import threading
+import time
+import uuid
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+def hermes_home(tmp_path, monkeypatch):
+ """Give the persisted control managers an isolated database for every test."""
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ from hermes_cli import goals
+
+ goals._DB_CACHE.clear()
+ yield home
+ goals._DB_CACHE.clear()
+
+
+def server(hermes_home, monkeypatch):
+ with patch.dict(
+ "sys.modules",
+ {
+ "hermes_cli.env_loader": MagicMock(),
+ "hermes_cli.banner": MagicMock(),
+ },
+ ):
+ mod = importlib.import_module("tui_gateway.server")
+ monkeypatch.setattr(mod, "_hermes_home", hermes_home)
+ monkeypatch.setattr(mod, "_cfg_cache", None)
+ monkeypatch.setattr(mod, "_cfg_mtime", None)
+ monkeypatch.setattr(mod, "_cfg_path", None)
+ yield mod
+ mod._sessions.clear()
+ mod._pending.clear()
+ mod._answers.clear()
+
+
+def session(server):
+ sid = f"sid-control-{uuid.uuid4().hex}"
+ key = f"control-{uuid.uuid4().hex}"
+ entry = {
+ "session_key": key,
+ "history": [],
+ "history_lock": threading.Lock(),
+ "history_version": 0,
+ "running": False,
+ "attached_images": [],
+ "cols": 120,
+ "agent": None,
+ "created_at": time.time(),
+ }
+ server._sessions[sid] = entry
+ yield sid, key, entry
+ from hermes_cli.goals import GoalManager
+ from hermes_cli.heartbeat import HeartbeatManager
+ from hermes_cli.loops import LoopManager
+
+ GoalManager(key).clear()
+ LoopManager(key).clear()
+ HeartbeatManager(key).clear()
+
+
+def _call(server, method, *, rid=91, **params):
+ return server._methods[method](rid, params)
+
+
+def _control(server, sid):
+ return _call(server, "session.control.read", session_id=sid)["result"]["control"]
+
+
+def _error(response):
+ assert "error" in response
+ return response["error"]
+
+
+def _observe_dispatch(server, monkeypatch):
+ calls = []
+ original = server._methods["command.dispatch"]
+
+ def observe(rid, params):
+ calls.append((rid, dict(params)))
+ return original(rid, params)
+
+ monkeypatch.setitem(server._methods, "command.dispatch", observe)
+ return calls
+
+
+def _forbid_dispatch(server, monkeypatch):
+ def forbidden(_rid, _params):
+ raise AssertionError("manager-only action must not call command.dispatch")
+
+ monkeypatch.setitem(server._methods, "command.dispatch", forbidden)
+
+
+def _save_goal(key, **overrides):
+ from hermes_cli.goals import GoalState, save_goal
+
+ fields = {
+ "goal": "Finish the desktop control card",
+ "status": "active",
+ "turns_used": 3,
+ "max_turns": 12,
+ "created_at": 100.0,
+ "last_turn_at": 200.0,
+ }
+ fields.update(overrides)
+ state = GoalState(**fields)
+ save_goal(key, state)
+ return state
+
+
+def _save_loop(key, **overrides):
+ from hermes_cli.loops import LoopState, save_loop
+
+ fields = {
+ "prompt": "Check the deployment",
+ "status": "active",
+ "mode": "interval",
+ "interval_seconds": 300,
+ "current_delay": 300,
+ "created_at": 100.0,
+ "next_due_at": 400.0,
+ }
+ fields.update(overrides)
+ state = LoopState(**fields)
+ save_loop(key, state)
+ return state
+
+
+def _save_heartbeat(key, **overrides):
+ from hermes_cli.heartbeat import HeartbeatState, save_heartbeat
+
+ fields = {
+ "prompt": "Check the deployment",
+ "interval_seconds": 600,
+ "status": "active",
+ "created_at": 100.0,
+ "last_fired_at": 150.0,
+ "fire_count": 2,
+ }
+ fields.update(overrides)
+ state = HeartbeatState(**fields)
+ save_heartbeat(key, state)
+ return state
+
+
+class TestStructuredRead:
+ def test_methods_are_registered_and_empty_snapshot_is_stable(self, server, session):
+ sid, _, _ = session
+ assert {"session.control.read", "session.control"} <= set(server._methods)
+ first = _control(server, sid)
+ second = _control(server, sid)
+ assert first == second
+ assert first == {
+ "goal": None,
+ "loop": None,
+ "heartbeat": None,
+ "revision": "",
+ "updated_at": 0,
+ }
+
+ def test_goal_contract_subgoals_and_gates_are_structured_and_sanitized(self, server, session):
+ from hermes_cli.goals import GoalContract, GoalGate
+
+ sid, key, _ = session
+ contract = GoalContract(outcome="Card is correct", verification="Run focused tests")
+ _save_goal(
+ key,
+ contract=contract,
+ subgoals=["Keep command routing narrow", "Document event hydration seam"],
+ gates=[GoalGate(
+ command="scripts/run_tests.sh tests/tui_gateway/test_session_control.py",
+ timeout_seconds=90,
+ max_retries=2,
+ attempts=1,
+ last_exit_code=1,
+ last_output_tail="private output must stay private",
+ last_failed_fingerprint="secret-fingerprint",
+ )],
+ )
+
+ goal = _control(server, sid)["goal"]
+ assert goal["title"] == "Finish the desktop control card"
+ assert goal["contract"] == contract.to_dict()
+ assert goal["subgoals"] == ["Keep command routing narrow", "Document event hydration seam"]
+ assert goal["gates"] == [{
+ "command": "scripts/run_tests.sh tests/tui_gateway/test_session_control.py",
+ "timeout_seconds": 90,
+ "max_retries": 2,
+ "attempts": 1,
+ "last_exit_code": 1,
+ }]
+ serialized = json.dumps(goal)
+ for forbidden in (
+ "last_output_tail", "last_failed_fingerprint", "private output", "secret-fingerprint",
+ "route", "session_id", "credential", "api_key",
+ ):
+ assert forbidden not in serialized
+
+ def test_wait_barrier_is_absolute_and_unchanged_reads_do_not_count_down(self, server, session, monkeypatch):
+ sid, key, _ = session
+ _save_goal(key, waiting_until=2_000.0, waiting_reason="rate limit")
+ clock = SimpleNamespace(now=1_000.0)
+ monkeypatch.setattr(server, "time", SimpleNamespace(time=lambda: clock.now))
+
+ first = _control(server, sid)
+ clock.now = 1_001.0
+ second = _control(server, sid)
+
+ assert first == second
+ assert first["goal"]["wait_barrier"] == {
+ "type": "until", "until_at": 2_000.0, "reason": "rate limit",
+ }
+ assert "remaining_seconds" not in first["goal"]["wait_barrier"]
+
+ @pytest.mark.parametrize(
+ ("kind", "setup"),
+ [
+ ("goal", lambda key: _save_goal(key)),
+ ("loop", lambda key: _save_loop(key)),
+ ("heartbeat", lambda key: _save_heartbeat(key)),
+ ],
+ )
+ def test_revision_is_stable_then_changes_for_each_visible_control(self, server, session, kind, setup):
+ sid, key, _ = session
+ setup(key)
+ before = _control(server, sid)
+ assert isinstance(before["revision"], str)
+ assert len(before["revision"]) == 64
+ assert before == _control(server, sid)
+
+ if kind == "goal":
+ _save_goal(key, goal="A visible replacement goal")
+ elif kind == "loop":
+ _save_loop(key, prompt="A visibly changed loop prompt")
+ else:
+ _save_heartbeat(key, prompt="A visibly changed heartbeat prompt")
+
+ assert _control(server, sid)["revision"] != before["revision"]
+
+ def test_session_and_pid_wait_barriers_keep_absolute_targets(self, server, session):
+ sid, key, _ = session
+ _save_goal(key, waiting_on_session="bg-session", waiting_reason="CI")
+ assert _control(server, sid)["goal"]["wait_barrier"] == {
+ "type": "session", "target": "bg-session", "reason": "CI",
+ }
+ _save_goal(key, waiting_on_pid=4242, waiting_reason="build")
+ assert _control(server, sid)["goal"]["wait_barrier"] == {
+ "type": "pid", "target": 4242, "reason": "build",
+ }
+
+
+ ("action", "name", "arg", "status"),
+ [
+ ("goal.pause", "goal", "pause", "active"),
+ ("goal.resume", "goal", "resume", "paused"),
+ ("goal.clear", "goal", "clear", "active"),
+ ("loop.pause", "loop", "pause", "active"),
+ ("loop.resume", "loop", "resume", "paused"),
+ ("loop.stop", "loop", "stop", "active"),
+ ],
+)
+def test_dispatched_actions_use_exact_mapping_and_caller_rpc_id(
+ server, session, monkeypatch, action, name, arg, status,
+):
+ sid, key, _ = session
+ if name == "goal":
+ _save_goal(key, status=status)
+ else:
+ _save_loop(key, status=status)
+ calls = _observe_dispatch(server, monkeypatch)
+
+ response = _call(server, "session.control", rid=743, session_id=sid, action=action)
+
+ assert "result" in response
+ assert calls == [(743, {"session_id": sid, "name": name, "arg": arg})]
+
+
+class TestDispatcherBackedMutations:
+ def test_goal_pause_resume_clear_mutate_real_persisted_state(self, server, session):
+ sid, key, _ = session
+ _save_goal(key, status="active", turns_used=8)
+
+ paused = _call(server, "session.control", session_id=sid, action="goal.pause")
+ assert paused["result"]["control"]["goal"]["status"] == "paused"
+
+ resumed = _call(server, "session.control", session_id=sid, action="goal.resume")
+ assert resumed["result"]["dispatch"]["type"] == "send"
+ assert resumed["result"]["dispatch"]["message"]
+ assert resumed["result"]["dispatch"]["notice"]
+ assert resumed["result"]["dispatch"]["display"] == "/goal resume"
+ assert resumed["result"]["control"]["goal"]["status"] == "active"
+
+ cleared = _call(server, "session.control", session_id=sid, action="goal.clear")
+ assert cleared["result"]["control"]["goal"] is None
+
+ def test_loop_pause_resume_stop_mutate_real_persisted_state(self, server, session):
+ sid, key, _ = session
+ _save_loop(key)
+
+ paused = _call(server, "session.control", session_id=sid, action="loop.pause")
+ assert paused["result"]["control"]["loop"]["status"] == "paused"
+
+ resumed = _call(server, "session.control", session_id=sid, action="loop.resume")
+ assert resumed["result"]["control"]["loop"]["status"] == "active"
+
+ stopped = _call(server, "session.control", session_id=sid, action="loop.stop")
+ assert stopped["result"]["control"]["loop"] is None
+
+
+class TestManagerOnlyMutations:
+ def test_subgoal_add_remove_clear_are_real_one_based_mutations_without_dispatch(self, server, session, monkeypatch):
+ from hermes_cli.goals import load_goal
+
+ sid, key, _ = session
+ _save_goal(key, subgoals=["First criterion"])
+ _forbid_dispatch(server, monkeypatch)
+
+ added = _call(server, "session.control", session_id=sid, action="subgoal.add", args={"text": "Second criterion"})
+ assert added["result"]["dispatch"]["output"] == "✓ Added subgoal 2: Second criterion"
+ assert load_goal(key).subgoals == ["First criterion", "Second criterion"]
+
+ removed = _call(server, "session.control", session_id=sid, action="subgoal.remove", args={"index": 1})
+ assert removed["result"]["dispatch"]["output"] == "✓ Removed subgoal 1: First criterion"
+ assert load_goal(key).subgoals == ["Second criterion"]
+
+ cleared = _call(server, "session.control", session_id=sid, action="subgoal.clear")
+ assert cleared["result"]["dispatch"]["output"] == "✓ Cleared 1 subgoal."
+ assert load_goal(key).subgoals == []
+
+ def test_subgoal_requires_a_goal_and_valid_arguments_without_dispatch(self, server, session, monkeypatch):
+ sid, key, _ = session
+ _forbid_dispatch(server, monkeypatch)
+ assert _error(_call(server, "session.control", session_id=sid, action="subgoal.add", args={"text": "criterion"}))["code"] == 4004
+
+ _save_goal(key, subgoals=["Only criterion"])
+ for args in (
+ {"text": " "},
+ {"index": "1"},
+ {"index": 1.5},
+ {"index": True},
+ {"index": 0},
+ {"index": 2},
+ ):
+ action = "subgoal.add" if "text" in args else "subgoal.remove"
+ assert _error(_call(server, "session.control", session_id=sid, action=action, args=args))["code"] == 4004
+
+ def test_goal_unwait_clears_the_real_barrier_without_dispatch(self, server, session, monkeypatch):
+ from hermes_cli.goals import GoalManager
+
+ sid, key, _ = session
+ _save_goal(key)
+ GoalManager(key).wait_for_seconds(60, reason="backoff")
+ _forbid_dispatch(server, monkeypatch)
+
+ response = _call(server, "session.control", session_id=sid, action="goal.unwait")
+ assert response["result"]["dispatch"]["output"] == "▶ Wait barrier cleared — goal loop resumes."
+ assert GoalManager(key).state.waiting_until == 0.0
+
+ def test_heartbeat_pause_resume_clear_and_no_heartbeat_messages_do_not_dispatch(self, server, session, monkeypatch):
+ sid, key, _ = session
+ _forbid_dispatch(server, monkeypatch)
+ assert _call(server, "session.control", session_id=sid, action="heartbeat.pause")["result"]["dispatch"]["output"] == "No heartbeat set."
+ assert _call(server, "session.control", session_id=sid, action="heartbeat.resume")["result"]["dispatch"]["output"] == "No heartbeat to resume."
+ assert _call(server, "session.control", session_id=sid, action="heartbeat.clear")["result"]["dispatch"]["output"] == "No heartbeat set."
+
+ _save_heartbeat(key, status="active", last_fired_at=1.0)
+ paused = _call(server, "session.control", session_id=sid, action="heartbeat.pause")
+ assert paused["result"]["dispatch"]["output"] == "⏸ Heartbeat paused: Check the deployment"
+ assert paused["result"]["control"]["heartbeat"]["status"] == "paused"
+
+ resumed = _call(server, "session.control", session_id=sid, action="heartbeat.resume")
+ assert resumed["result"]["dispatch"]["output"] == "▶ Heartbeat resumed (every 10m): Check the deployment"
+ assert resumed["result"]["control"]["heartbeat"]["last_fired_at"] > 1.0
+
+ cleared = _call(server, "session.control", session_id=sid, action="heartbeat.clear")
+ assert cleared["result"]["dispatch"]["output"] == "✓ Heartbeat cleared."
+ assert cleared["result"]["control"]["heartbeat"] is None
+
+
+class TestErrorsAndEvents:
+ @pytest.mark.parametrize(
+ ("action", "args"),
+ [
+ ("", {}),
+ ("not.allowed", {}),
+ ("goal.gate.add", {"command": "echo should-not-run"}),
+ ("subgoal.add", []),
+ ],
+ )
+ def test_invalid_actions_and_malformed_args_return_4004_without_dispatch(self, server, session, monkeypatch, action, args):
+ sid, _, _ = session
+ _forbid_dispatch(server, monkeypatch)
+ assert _error(_call(server, "session.control", session_id=sid, action=action, args=args))["code"] == 4004
+
+ def test_unknown_session_returns_4001(self, server):
+ assert _error(_call(server, "session.control", session_id="gone", action="goal.pause"))["code"] == 4001
+ assert _error(_call(server, "session.control.read", session_id="gone"))["code"] == 4001
+
+ def test_dispatch_error_emits_no_update(self, server, session, monkeypatch):
+ sid, key, _ = session
+ _save_goal(key)
+ emitted = []
+ monkeypatch.setattr(server, "_emit", lambda *event: emitted.append(event))
+ monkeypatch.setitem(server._methods, "command.dispatch", lambda rid, params: server._err(rid, 4018, "dispatch failed"))
+
+ response = _call(server, "session.control", session_id=sid, action="goal.pause")
+ assert _error(response)["code"] == 4018
+ assert emitted == []
+
+ def test_adapter_error_becomes_4004_and_emits_no_update(self, server, session, monkeypatch):
+ from hermes_cli.goals import GoalManager
+
+ sid, key, _ = session
+ _save_goal(key)
+ emitted = []
+ monkeypatch.setattr(server, "_emit", lambda *event: emitted.append(event))
+ monkeypatch.setattr(GoalManager, "add_subgoal", lambda self, text: (_ for _ in ()).throw(RuntimeError("blocked")))
+
+ response = _call(server, "session.control", session_id=sid, action="subgoal.add", args={"text": "criterion"})
+ assert _error(response)["code"] == 4004
+ assert emitted == []
+
+ def test_success_response_snapshot_is_exactly_the_one_update_event(self, server, session, monkeypatch):
+ sid, key, _ = session
+ _save_goal(key)
+ emitted = []
+ monkeypatch.setattr(server, "_emit", lambda event, event_sid, payload=None: emitted.append((event, event_sid, payload)))
+
+ response = _call(server, "session.control", session_id=sid, action="goal.pause")
+ assert emitted == [("session.control.update", sid, {"control": response["result"]["control"]})]
+
+ def test_dispatch_envelope_preserves_all_user_visible_fields(self, server, session, monkeypatch):
+ sid, key, _ = session
+ _save_goal(key, status="paused")
+ expected = {
+ "type": "send",
+ "output": "already-rendered output",
+ "notice": "Goal resumed",
+ "message": "Continue toward the goal.",
+ "display": "/goal resume",
+ }
+ monkeypatch.setitem(
+ server._methods,
+ "command.dispatch",
+ lambda rid, params: {"jsonrpc": "2.0", "id": rid, "result": expected},
+ )
+
+ response = _call(server, "session.control", session_id=sid, action="goal.resume")
+ assert response["result"]["dispatch"] == expected
+
+ def test_emit_failure_must_not_turn_mutation_into_rpc_error(self, server, session, monkeypatch):
+ """Event delivery is best-effort: a failing _emit must not swallow an
+ already-applied mutation. The persisted goal must be paused, the RPC
+ response must carry the correct snapshot and dispatch envelope, and the
+ emission error must be debug-logged rather than propagated."""
+ from hermes_cli.goals import GoalManager
+
+ sid, key, _ = session
+ _save_goal(key, status="active")
+ monkeypatch.setattr(
+ server, "_emit", lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("emit broken")),
+ )
+
+ response = _call(server, "session.control", session_id=sid, action="goal.pause")
+
+ assert "result" in response, f"_emit failure leaked as RPC error: {response}"
+ assert response["result"]["control"]["goal"]["status"] == "paused"
+ assert response["result"]["dispatch"]["type"] == "exec"
+ assert response["result"]["dispatch"]["output"]
+ assert GoalManager(key).state.status == "paused"
+
+ def test_snapshot_failure_after_mutation_does_not_emit_an_all_null_fallback(self, server, session, monkeypatch):
+ from hermes_cli.goals import GoalManager
+
+ sid, key, _ = session
+ _save_goal(key)
+ emitted = []
+ monkeypatch.setattr(server, "_emit", lambda *event: emitted.append(event))
+ monkeypatch.setattr(server, "_snapshot_control", lambda _key: (_ for _ in ()).throw(RuntimeError("storage failed")))
+
+ response = _call(server, "session.control", session_id=sid, action="goal.pause")
+ assert _error(response)["code"] == 5031
+ assert GoalManager(key).state.status == "paused"
+ assert emitted == []
diff --git a/tui_gateway/methods_session_control.py b/tui_gateway/methods_session_control.py
new file mode 100644
index 00000000000..b1a7b7e12ca
--- /dev/null
+++ b/tui_gateway/methods_session_control.py
@@ -0,0 +1,388 @@
+"""Structured Desktop controls for persisted goal, loop, and heartbeat state.
+
+``session.control.read`` is a stable, allowlisted view of one live session.
+``session.control`` accepts a closed set of intent-level actions: goal and
+loop actions use their existing TUI command handlers, while controls without a
+TUI command use the public manager API. A successful action emits one matching
+``session.control.update`` event.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import time
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+method = _registry.method
+_profile_scoped = _registry.profile_scoped
+
+logger = logging.getLogger(__name__)
+
+
+_ACTION_COMMAND_MAP: dict[str, tuple[str, str]] = {
+ "goal.pause": ("goal", "pause"),
+ "goal.resume": ("goal", "resume"),
+ "goal.clear": ("goal", "clear"),
+ "loop.pause": ("loop", "pause"),
+ "loop.resume": ("loop", "resume"),
+ "loop.stop": ("loop", "stop"),
+}
+
+_MANAGER_ACTIONS = frozenset({
+ "goal.unwait",
+ "subgoal.add",
+ "subgoal.remove",
+ "subgoal.clear",
+ "heartbeat.pause",
+ "heartbeat.resume",
+ "heartbeat.clear",
+})
+
+_VALID_ACTIONS = frozenset(_ACTION_COMMAND_MAP) | _MANAGER_ACTIONS
+
+
+def _safe_goal_snapshot(state) -> dict | None:
+ """Return only stable, frontend-safe GoalState fields."""
+ if state is None or state.status == "cleared":
+ return None
+ snapshot = {
+ "title": state.goal,
+ "status": state.status,
+ "turns_used": state.turns_used,
+ "max_turns": state.max_turns,
+ "contract": state.contract.to_dict(),
+ "subgoals": list(state.subgoals),
+ "gates": [
+ {
+ "command": gate.command,
+ "timeout_seconds": gate.timeout_seconds,
+ "max_retries": gate.max_retries,
+ "attempts": gate.attempts,
+ "last_exit_code": gate.last_exit_code,
+ }
+ for gate in state.gates
+ ],
+ }
+ if state.created_at:
+ snapshot["created_at"] = state.created_at
+ if state.last_turn_at:
+ snapshot["updated_at"] = state.last_turn_at
+ if state.paused_reason:
+ snapshot["paused_reason"] = state.paused_reason
+ if state.last_verdict:
+ snapshot["last_verdict"] = state.last_verdict
+ if state.last_reason:
+ snapshot["last_reason"] = state.last_reason
+ if barrier := _extract_wait_barrier(state):
+ snapshot["wait_barrier"] = barrier
+ return snapshot
+
+
+def _extract_wait_barrier(state) -> dict | None:
+ """Expose absolute barriers; countdown presentation belongs to the client."""
+ reason = state.waiting_reason or ""
+ if state.waiting_until and time.time() < state.waiting_until:
+ return {"type": "until", "until_at": state.waiting_until, "reason": reason}
+ if state.waiting_on_session is not None:
+ return {"type": "session", "target": state.waiting_on_session, "reason": reason}
+ if state.waiting_on_pid is not None:
+ return {"type": "pid", "target": state.waiting_on_pid, "reason": reason}
+ return None
+
+
+def _safe_loop_snapshot(state, *, deferred_by_goal: bool) -> dict | None:
+ """Return allowlisted persisted LoopState fields, never its route."""
+ if state is None or state.status == "cleared":
+ return None
+ snapshot = {
+ "prompt": state.prompt,
+ "status": state.status,
+ "mode": state.mode,
+ "interval_seconds": state.interval_seconds,
+ "current_delay": state.current_delay,
+ "times": state.times,
+ "until": state.until,
+ "max_ticks": state.max_ticks,
+ "ticks_fired": state.ticks_fired,
+ "created_at": state.created_at,
+ "last_fired_at": state.last_fired_at,
+ "next_due_at": state.next_due_at,
+ "awaiting_response": state.awaiting_response,
+ "deferred_by_goal": deferred_by_goal,
+ }
+ if state.paused_reason:
+ snapshot["paused_reason"] = state.paused_reason
+ if state.last_stop_reason:
+ snapshot["last_stop_reason"] = state.last_stop_reason
+ return snapshot
+
+
+def _safe_heartbeat_snapshot(state) -> dict | None:
+ """Return only the persisted HeartbeatState fields the Desktop renders."""
+ if state is None or state.status == "cleared":
+ return None
+ return {
+ "prompt": state.prompt,
+ "status": state.status,
+ "interval_seconds": state.interval_seconds,
+ "created_at": state.created_at,
+ "last_fired_at": state.last_fired_at,
+ "fire_count": state.fire_count,
+ }
+
+
+def _snapshot_control(session_key: str) -> dict:
+ """Serialize persisted session-control state once, without wall-clock churn."""
+ goal_state = _load_goal_state(session_key)
+ loop_state = _load_loop_state(session_key)
+ heartbeat_state = _load_heartbeat_state(session_key)
+ deferred_by_goal = bool(
+ loop_state is not None
+ and loop_state.status == "active"
+ and goal_state is not None
+ and goal_state.status == "active"
+ and _goal_blocks_loop_tick(session_key)
+ )
+ goal = _safe_goal_snapshot(goal_state)
+ loop = _safe_loop_snapshot(loop_state, deferred_by_goal=deferred_by_goal)
+ heartbeat = _safe_heartbeat_snapshot(heartbeat_state)
+ return {
+ "goal": goal,
+ "loop": loop,
+ "heartbeat": heartbeat,
+ "revision": _snapshot_revision(goal, loop, heartbeat),
+ "updated_at": _snapshot_updated_at(goal_state, loop_state, heartbeat_state),
+ }
+
+
+def _snapshot_revision(goal, loop, heartbeat) -> str:
+ """Hash canonical visible state so equal reads always have equal revisions."""
+ if goal is None and loop is None and heartbeat is None:
+ return ""
+ canonical = json.dumps(
+ {"goal": goal, "loop": loop, "heartbeat": heartbeat},
+ ensure_ascii=False,
+ separators=(",", ":"),
+ sort_keys=True,
+ )
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
+
+
+def _snapshot_updated_at(goal_state, loop_state, heartbeat_state):
+ """Use only persisted timestamps; reads never manufacture a new timestamp."""
+ candidates = []
+ for state, fields in (
+ (goal_state, ("created_at", "last_turn_at")),
+ (loop_state, ("created_at", "last_fired_at")),
+ (heartbeat_state, ("created_at", "last_fired_at")),
+ ):
+ if state is not None:
+ candidates.extend(value for field in fields if (value := getattr(state, field, 0)))
+ return max(candidates) if candidates else 0
+
+
+def _load_goal_state(session_key):
+ from hermes_cli.goals import load_goal
+
+ return load_goal(session_key)
+
+
+def _load_loop_state(session_key):
+ from hermes_cli.loops import load_loop
+
+ return load_loop(session_key)
+
+
+def _load_heartbeat_state(session_key):
+ from hermes_cli.heartbeat import load_heartbeat
+
+ return load_heartbeat(session_key)
+
+
+def _goal_blocks_loop_tick(session_key: str) -> bool:
+ from hermes_cli.loops import goal_blocks_loop_tick
+
+ return goal_blocks_loop_tick(session_key)
+
+
+@method("session.control.read")
+@_profile_scoped
+def _(rid, params: dict) -> dict:
+ """Return the current stable control snapshot for a live session."""
+ session, err = _sess_nowait(params, rid)
+ if err:
+ return err
+ session_key = str(session.get("session_key") or "")
+ if not session_key:
+ return _err(rid, 4001, "session has no stored key")
+ try:
+ return _ok(rid, {"control": _snapshot_control(session_key)})
+ except Exception as exc:
+ logger.debug("session.control.read failed: %s", exc, exc_info=True)
+ return _err(rid, 5031, f"session.control.read failed: {exc}")
+
+
+@method("session.control")
+@_profile_scoped
+def _(rid, params: dict) -> dict:
+ """Run one allowlisted control action and emit its exact resulting snapshot."""
+ raw_action = params.get("action")
+ if not isinstance(raw_action, str) or not (action := raw_action.strip()):
+ return _err(rid, 4004, "action is required")
+ if action.startswith("goal.gate"):
+ return _err(rid, 4004, "gate actions are not allowed through session.control")
+ if action not in _VALID_ACTIONS:
+ return _err(rid, 4004, f"unknown action: {action}")
+
+ if "args" in params:
+ args = params["args"]
+ if not isinstance(args, dict):
+ return _err(rid, 4004, "args must be an object")
+ else:
+ args = {}
+ validated, validation_error = _validate_action_args(rid, action, args)
+ if validation_error:
+ return validation_error
+
+ session, err = _sess_nowait(params, rid)
+ if err:
+ return err
+ session_key = str(session.get("session_key") or "")
+ if not session_key:
+ return _err(rid, 4001, "session has no stored key")
+
+ try:
+ if action in _ACTION_COMMAND_MAP:
+ name, arg = _ACTION_COMMAND_MAP[action]
+ action_result = _dispatch_command(rid, session_id=params.get("session_id") or "", name=name, arg=arg)
+ else:
+ action_result = _execute_manager_action(session_key, action, validated)
+ except (RuntimeError, ValueError, IndexError) as exc:
+ return _err(rid, 4004, _manager_error_message(action, exc))
+
+ if "error" in action_result:
+ return action_result
+
+ try:
+ control = _snapshot_control(session_key)
+ except Exception as exc:
+ logger.debug("session.control snapshot after %s failed: %s", action, exc, exc_info=True)
+ return _err(rid, 5031, f"session.control snapshot failed: {exc}")
+
+ try:
+ _emit("session.control.update", params.get("session_id") or "", {"control": control})
+ except Exception as exc:
+ logger.debug("session.control.update emit failed (best-effort): %s", exc, exc_info=True)
+ return _ok(rid, {"control": control, "dispatch": _dispatch_envelope(action_result)})
+
+
+def _validate_action_args(rid, action: str, args: dict):
+ """Validate the only actions with input before any manager is constructed."""
+ if action == "subgoal.add":
+ text = args.get("text")
+ if not isinstance(text, str) or not (text := text.strip()):
+ return None, _err(rid, 4004, "subgoal text is required")
+ return {"text": text}, None
+ if action == "subgoal.remove":
+ index = args.get("index")
+ if type(index) is not int:
+ return None, _err(rid, 4004, "subgoal index must be an integer")
+ if index < 1:
+ return None, _err(rid, 4004, "subgoal index must be >= 1")
+ return {"index": index}, None
+ return {}, None
+
+
+def _dispatch_command(rid, *, session_id: str, name: str, arg: str) -> dict:
+ """Delegate a fixed intent to the existing TUI command dispatcher."""
+ handler = _methods.get("command.dispatch")
+ if handler is None:
+ return _err(rid, 5031, "command.dispatch unavailable")
+ try:
+ return handler(rid, {"session_id": session_id, "name": name, "arg": arg})
+ except Exception as exc:
+ logger.debug("command.dispatch %s %s failed: %s", name, arg, exc, exc_info=True)
+ return _err(rid, 5031, f"dispatch failed: {exc}")
+
+
+def _execute_manager_action(session_key: str, action: str, args: dict) -> dict:
+ """Use manager APIs for controls that have no TUI command handler."""
+ if action == "goal.unwait":
+ return _execute_goal_unwait(session_key)
+ if action.startswith("subgoal."):
+ return _execute_subgoal_action(session_key, action, args)
+ return _execute_heartbeat_action(session_key, action)
+
+
+def _execute_goal_unwait(session_key: str) -> dict:
+ from hermes_cli.goals import GoalManager
+
+ manager = GoalManager(session_id=session_key)
+ output = "▶ Wait barrier cleared — goal loop resumes." if manager.stop_waiting() else "No wait barrier set."
+ return {"result": {"type": "exec", "output": output}}
+
+
+def _execute_subgoal_action(session_key: str, action: str, args: dict) -> dict:
+ from hermes_cli.goals import GoalManager
+
+ manager = GoalManager(session_id=session_key)
+ if action == "subgoal.add":
+ text = manager.add_subgoal(args["text"])
+ return {"result": {"type": "exec", "output": f"✓ Added subgoal {len(manager.state.subgoals)}: {text}"}}
+ if action == "subgoal.remove":
+ index = args["index"]
+ text = manager.remove_subgoal(index)
+ return {"result": {"type": "exec", "output": f"✓ Removed subgoal {index}: {text}"}}
+ count = manager.clear_subgoals()
+ output = f"✓ Cleared {count} subgoal{'s' if count != 1 else ''}." if count else "No subgoals to clear."
+ return {"result": {"type": "exec", "output": output}}
+
+
+def _execute_heartbeat_action(session_key: str, action: str) -> dict:
+ from hermes_cli.heartbeat import HeartbeatManager, format_interval
+
+ manager = HeartbeatManager(session_id=session_key)
+ if action == "heartbeat.pause":
+ state = manager.pause()
+ output = f"⏸ Heartbeat paused: {state.prompt}" if state else "No heartbeat set."
+ elif action == "heartbeat.resume":
+ state = manager.resume()
+ output = (
+ f"▶ Heartbeat resumed (every {format_interval(state.interval_seconds)}): {state.prompt}"
+ if state else "No heartbeat to resume."
+ )
+ elif action == "heartbeat.clear":
+ output = "✓ Heartbeat cleared." if manager.clear() else "No heartbeat set."
+ else:
+ return _err(None, 4004, f"unknown heartbeat action: {action}")
+ return {"result": {"type": "exec", "output": output}}
+
+
+def _manager_error_message(action: str, exc: Exception) -> str:
+ prefixes = {
+ "subgoal.add": "/subgoal",
+ "subgoal.remove": "/subgoal remove",
+ "subgoal.clear": "/subgoal clear",
+ }
+ return f"{prefixes.get(action, action)}: {exc}"
+
+
+def _dispatch_envelope(response: dict) -> dict:
+ """Keep the command result's user-visible envelope without adding model-facing data."""
+ result = response.get("result") or {}
+ return {
+ "type": result.get("type"),
+ "output": result.get("output"),
+ "notice": result.get("notice"),
+ "message": result.get("message"),
+ "display": result.get("display"),
+ }
+
+
+def register(server) -> None:
+ """Rebind this module's handlers onto the server namespace."""
+ bind_module(globals(), server, skip=("_",))
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 33ebf7ba25d..316ad72ba1d 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -3207,7 +3207,8 @@ from . import ( # noqa: E402
methods_config_set as _methods_config_set, methods_images as _methods_images,
methods_profiles as _methods_profiles, methods_prompt as _methods_prompt, methods_session as _methods_session,
methods_tools as _methods_tools, prompt_turn as _prompt_turn, billing_view as _billing_view,
- methods_projects as _methods_projects, methods_session_foreign as _methods_session_foreign)
+ methods_projects as _methods_projects, methods_session_foreign as _methods_session_foreign,
+ methods_session_control as _methods_session_control)
for _m in (
_session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,
@@ -3216,6 +3217,7 @@ for _m in (
_methods_complete_helpers, _methods_slash, _methods_voice, _methods_browser,
_methods_browser_control, _methods_session, _methods_prompt, _methods_config,
_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,
- _methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign):
+ _methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,
+ _methods_session_control):
_m.register(sys.modules[__name__])
del _m