The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): scope child-run registry and live mirror to the owning profile
liuhao1024aee0c679650e
diff --git a/tests/tui_gateway/test_resume_child_run_profile_scope.py b/tests/tui_gateway/test_resume_child_run_profile_scope.pynew file mode 100644index 00000000000..5c9e541cf23--- /dev/null+++ b/tests/tui_gateway/test_resume_child_run_profile_scope.py@@ -0,0 +1,111 @@+"""The child-run liveness registry must be profile-scoped on the resume path.++Stored session ids are timestamps that exist in several profiles' stores. A lazy+``session.resume`` trusts ``_child_run_active`` to skip database verification+for a subagent window whose first flush has not landed yet — so a bare-key+registry hit let an authenticated client on Profile B resume Profile A's+actively-running child id: the gateway accepted it without verifying B's+database ownership and mirrored A's live turn into B's transport (#120212).++Pinned here, in both directions:++* a lazy resume for a child id that is only active under ANOTHER profile is+ refused with the same "session not found" as any id missing from the+ caller's own store (fail-closed);+* a lazy resume under the OWNING profile still bypasses the database lookup+ and opens the watch window, as before.+"""++from __future__ import annotations++import pytest++from tui_gateway import server+++class _EmptyDB:+ """Stand-in for ``hermes_state.SessionDB``: the caller's own store, which+ holds no row for the foreign child id."""++ def __init__(self, db_path=None, **_kwargs):+ self.db_path = db_path+ self.closed = 0++ def close(self):+ self.closed += 1++ def get_session(self, _target):+ return None++ def get_session_by_title(self, _target):+ return None++ def resolve_resume_session_id(self, target):+ return target++ def reopen_session(self, _target):+ return None++ def get_resume_conversations(self, _target):+ return ([], [])++ def get_ancestor_display_prefix(self, _target):+ return []++ def get_messages_as_conversation(self, _target, **_kwargs):+ return []+++def two_profiles(monkeypatch, tmp_path):+ homes = {}+ for name in ("a", "b"):+ home = tmp_path / name+ home.mkdir()+ homes[name] = home+ monkeypatch.setattr(server, "_profile_home", lambda profile: homes.get(profile))+ monkeypatch.setattr(server, "_profile_configured_cwd", lambda _home: str(tmp_path))+ monkeypatch.setattr("hermes_state_registry.acquire", _EmptyDB)+ monkeypatch.setattr(server, "_find_live_session_by_key", lambda _key, *_a, **_k: None)+ monkeypatch.setattr(server, "_schedule_agent_build", lambda *a, **k: None)+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda *a, **k: None)+ monkeypatch.setattr(server, "_maybe_schedule_auto_continue", lambda *a, **k: None)+ monkeypatch.setattr(server, "_default_session_cwd", lambda *a, **k: str(tmp_path))+ monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)+ known = set(server._sessions)+ yield homes+ with server._sessions_lock:+ for sid in [s for s in server._sessions if s not in known]:+ server._sessions.pop(sid, None)+++def _resume(**params):+ return server.handle_request(+ {"id": "1", "method": "session.resume", "params": params}+ )+++def _seed_active_run(server, profile_home, child_key):+ """Register an in-flight child run the way the delegate relay does, so the+ read side is exercised against the registry's real key form."""+ server._mirror_subagent_to_child("subagent.tool", {"child_session_id": child_key}, profile_home)+++def test_lazy_resume_refuses_child_id_active_under_another_profile(two_profiles):+ _seed_active_run(server, str(two_profiles["a"]), "child-key")+ try:+ resp = _resume(session_id="child-key", profile="b", lazy=True)+ finally:+ server._active_child_runs.clear()++ assert resp["error"]["code"] == 4007+++def test_lazy_resume_still_opens_watch_window_under_owning_profile(two_profiles):+ _seed_active_run(server, str(two_profiles["a"]), "child-key")+ try:+ resp = _resume(session_id="child-key", profile="a", lazy=True)+ finally:+ server._active_child_runs.clear()++ assert "error" not in respdiff --git a/tests/tui_gateway/test_resume_live_profile_scope.py b/tests/tui_gateway/test_resume_live_profile_scope.pyindex d23e89e37c1..31ab1d67897 100644--- a/tests/tui_gateway/test_resume_live_profile_scope.py+++ b/tests/tui_gateway/test_resume_live_profile_scope.py@@ -64,7 +64,7 @@ def homes(monkeypatch, tmp_path):monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda *a, **k: None)monkeypatch.setattr(server, "_maybe_schedule_auto_continue", lambda *a, **k: None)monkeypatch.setattr(server, "_default_session_cwd", lambda *a, **k: str(tmp_path))- monkeypatch.setattr(server, "_child_run_active", lambda _key: False)+ monkeypatch.setattr(server, "_child_run_active", lambda *a, **k: False)monkeypatch.setattr(server, "_live_session_payload", lambda sid, session, **_k: {"session_id": sid, "message_count": 0, "messages": [], "info": {}})diff --git a/tests/tui_gateway/test_session_resume_db_ownership.py b/tests/tui_gateway/test_session_resume_db_ownership.pyindex f03ea6b6613..d0778933f03 100644--- a/tests/tui_gateway/test_session_resume_db_ownership.py+++ b/tests/tui_gateway/test_session_resume_db_ownership.py@@ -205,7 +205,7 @@ def test_resume_closes_profile_db_on_live_session_fast_path(profile_dbs, monkeyp"_live_session_payload",lambda sid, session, **_k: {"session_id": sid, "message_count": 0, "messages": [], "info": {}},)- monkeypatch.setattr(server, "_child_run_active", lambda _key: False)+ monkeypatch.setattr(server, "_child_run_active", lambda *a, **k: False)resp = _resume(session_id="s1", profile="work")diff --git a/tests/tui_gateway/test_subagent_child_mirror.py b/tests/tui_gateway/test_subagent_child_mirror.pyindex 8b1681e6ca7..d0dbe96dcc3 100644--- a/tests/tui_gateway/test_subagent_child_mirror.py+++ b/tests/tui_gateway/test_subagent_child_mirror.py@@ -152,13 +152,13 @@ def test_upgraded_child_session_not_mirrored(server, emits):assert [(e, s) for e, s, _ in emits] == [("subagent.tool", "parent-sid")]assert server._child_mirrors == {}# Liveness registry still updates — it serves resume, not the mirror.- assert "child-1" in server._active_child_runs+ assert (None, "child-1") in server._active_child_runsdef test_stale_child_run_not_reported_active(server, emits):"""A leaked registry entry (lost completion event) must age out instead ofpinning running=true on every future lazy resume of that child."""- server._active_child_runs["child-1"] = 0.0 # epoch — ancient+ server._active_child_runs[(None, "child-1")] = 0.0 # epoch — ancientassert server._child_run_active("child-1") is False@@ -194,13 +194,13 @@ def test_active_child_runs_registry_tracks_liveness(server, emits):open), and completion clears it — lazy watch resumes read this registry toreport running=true while the child is silent inside a long tool call."""_relay(server, "subagent.start", preview="go", child_session_id="child-1")- assert "child-1" in server._active_child_runs+ assert (None, "child-1") in server._active_child_runs_relay(server, "subagent.tool", tool_name="terminal", child_session_id="child-1")- assert "child-1" in server._active_child_runs+ assert (None, "child-1") in server._active_child_runs_relay(server, "subagent.complete", child_session_id="child-1", status="completed", summary="ok")- assert "child-1" not in server._active_child_runs+ assert (None, "child-1") not in server._active_child_runsdef test_start_mirrors_as_immediate_header_line(server, emits):diff --git a/tests/tui_gateway/test_subagent_mirror_profile_isolation.py b/tests/tui_gateway/test_subagent_mirror_profile_isolation.pynew file mode 100644index 00000000000..8c69a2ffd0c--- /dev/null+++ b/tests/tui_gateway/test_subagent_mirror_profile_isolation.py@@ -0,0 +1,128 @@+"""Profile scoping of the child-session live mirror (#120212).++The delegated child runs under its PARENT's profile, so both the liveness+registry and the live-session lookup during mirroring are keyed on that+profile home. A watch window on another profile that happens to share the+child's stored id must not bind to the run — neither by mirroring the relaid+``subagent.*`` events into its transport nor by reporting the run active.+"""++from __future__ import annotations++from unittest.mock import MagicMock, patch++import pytest+++def server():+ # Mocks are scoped to the initial import only (see+ # tests/tui_gateway/test_protocol.py for the rationale).+ with patch.dict(+ "sys.modules",+ {+ "hermes_constants": MagicMock(+ get_hermes_home=MagicMock(return_value="/tmp/hermes_test_mirror_scope")+ ),+ "hermes_cli.env_loader": MagicMock(),+ "hermes_cli.banner": MagicMock(),+ "hermes_state": MagicMock(),+ },+ ):+ import importlib++ mod = importlib.import_module("tui_gateway.server")++ yield mod+ mod._sessions.clear()+ __import__("tui_gateway.server_requests", fromlist=["x"]).reset_for_tests()+ mod._child_mirrors.clear()+ mod._active_child_runs.clear()+++def emits(server, monkeypatch):+ captured: list = []+ monkeypatch.setattr(+ server,+ "_emit",+ lambda event, sid, payload=None: captured.append((event, sid, payload)),+ )+ monkeypatch.setattr(server, "_tool_progress_enabled", lambda sid: True)+ return captured+++HOME_A = "/profiles/a"+HOME_B = "/profiles/b"+++def _relay(server, event_type, **payload):+ """Drive _on_tool_progress the way the delegate relay does."""+ server._on_tool_progress(+ "parent-sid",+ event_type,+ payload.pop("tool_name", None),+ payload.pop("preview", None),+ None,+ goal="research X",+ task_count=1,+ task_index=0,+ **payload,+ )+++def test_foreign_profile_watch_window_is_not_bound(server, emits):+ # The parent (and its child) run under profile A; a live watch session with+ # the same stored key exists under profile B.+ server._sessions["parent-sid"] = {"session_key": "parent", "profile_home": HOME_A}+ server._sessions["live-b"] = {"session_key": "child-1", "profile_home": HOME_B, "agent": None}++ _relay(server, "subagent.tool", tool_name="terminal", preview="ls", child_session_id="child-1")++ # Only the parent-sid relay event: nothing mirrored into B's window...+ assert [(e, s) for e, s, _ in emits] == [("subagent.tool", "parent-sid")]+ assert server._child_mirrors == {}+ # ...and the liveness registry is keyed under A, not B nor the launch profile.+ assert (HOME_A, "child-1") in server._active_child_runs+ assert not server._child_run_active("child-1", HOME_B)+ assert not server._child_run_active("child-1")+++def test_owning_profile_watch_window_still_mirrors(server, emits):+ server._sessions["parent-sid"] = {"session_key": "parent", "profile_home": HOME_A}+ server._sessions["live-a"] = {"session_key": "child-1", "profile_home": HOME_A, "agent": None}++ _relay(server, "subagent.tool", tool_name="terminal", preview="ls", child_session_id="child-1")++ child = [(e, p) for e, s, p in emits if s == "live-a"]+ assert [e for e, _ in child] == ["message.start", "tool.start"]+ assert server._child_run_active("child-1", HOME_A)+++def test_launch_profile_run_not_reported_active_for_named_profile(server, emits):+ # A parent on the launch profile (no profile_home) with no window open.+ server._sessions["parent-sid"] = {"session_key": "parent"}++ _relay(server, "subagent.tool", tool_name="terminal", child_session_id="child-2")++ assert server._child_run_active("child-2")+ assert not server._child_run_active("child-2", HOME_A)+++def test_complete_clears_only_the_owning_profiles_entry(server, emits):+ server._sessions["parent-sid"] = {"session_key": "parent", "profile_home": HOME_A}+ server._sessions["live-b"] = {"session_key": "child-1", "profile_home": HOME_B, "agent": None}++ _relay(server, "subagent.tool", tool_name="terminal", child_session_id="child-1")+ # A second relay from a DIFFERENT profile's parent with the same child id+ # registers (HOME_B, "child-1") without disturbing A's entry.+ server._sessions["parent-sid"] = {"session_key": "parent", "profile_home": HOME_B}+ _relay(server, "subagent.tool", tool_name="terminal", child_session_id="child-1")+ assert server._child_run_active("child-1", HOME_A)+ assert server._child_run_active("child-1", HOME_B)++ server._sessions["parent-sid"] = {"session_key": "parent", "profile_home": HOME_B}+ _relay(server, "subagent.complete", child_session_id="child-1", status="completed", summary="done")++ assert server._child_run_active("child-1", HOME_A)+ assert not server._child_run_active("child-1", HOME_B)diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.pyindex 8444ea736eb..e462f899a5b 100644--- a/tui_gateway/agent_callbacks.py+++ b/tui_gateway/agent_callbacks.py@@ -18,31 +18,40 @@ from .method_ctx import bind_module_child_mirrors: dict[str, dict] = {}_child_mirrors_lock = threading.Lock()# Child sids with a run in flight (refreshed per relayed event, popped on complete) so a-# lazy watch resume reports running=true during a silent long tool.-_active_child_runs: dict[str, float] = {}+# lazy watch resume reports running=true during a silent long tool. Keyed on the child's+# profile home: stored ids are timestamps that exist in several profiles' stores, so a+# bare-key hit would report ANOTHER profile's run as active here.+_active_child_runs: dict[tuple[str | None, str], float] = {}# Anything quiet this long lost its completion event — don't pin "running"._CHILD_RUN_STALE_S = 3600.0_CHILD_DELTA_EVENTS = {"subagent.thinking": "reasoning.delta", "subagent.text": "message.delta","subagent.start": "message.delta"}-def _child_run_active(child_key: str) -> bool:- ts = _active_child_runs.get(child_key)+def _child_run_profile(profile_home) -> str | None:+ """Normalize a profile home (Path from resume ctx, str from session records) to the+ same form ``_live_profile_matches`` compares against."""+ return str(profile_home) if profile_home else None+++def _child_run_active(child_key: str, profile_home=None) -> bool:+ ts = _active_child_runs.get((_child_run_profile(profile_home), child_key))return ts is not None and (time.time() - ts) < _CHILD_RUN_STALE_S-def _mirror_subagent_to_child(event_type: str, payload: dict) -> None:+def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home=None) -> None:child_key = str(payload.get("child_session_id") or "")if not child_key:return+ home = _child_run_profile(profile_home)# Liveness registry first: accurate with no window open (one opened mid-run knows busy).if event_type == "subagent.complete":- _active_child_runs.pop(child_key, None)+ _active_child_runs.pop((home, child_key), None)else:- _active_child_runs[child_key] = time.time()+ _active_child_runs[(home, child_key)] = time.time()# Mirror only into a live watch session NOT upgraded to a full agent (an upgraded one owns# a real native stream). Either way drop state so a reopened window starts fresh.- live = _find_live_session_by_key(child_key)+ live = _find_live_session_by_key(child_key, home)if live is None or live[1].get("agent") is not None:with _child_mirrors_lock:_child_mirrors.pop(child_key, None)diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex c2a2edb60c3..fb8674e4390 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -536,7 +536,8 @@ def _lock_in_submit_turn(return _err(rid, 5035, "backend is retiring; reconnect to continue"), fields# A watch session's run lives in the PARENT turn (own running flag False); typing# mid-run would build a second agent racing the child on the same stored session.- if session.get("lazy") and _child_run_active(str(session.get("session_key") or "")):+ if session.get("lazy") and _child_run_active(+ str(session.get("session_key") or ""), session.get("profile_home") or None):return _err(rid, 4009, "subagent still running — wait for it to finish"), fieldsif is_truthy_value(params.get("confirm_truncate")) and not has_truncation:return _err(diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex d0291a15520..ba926978167 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -733,7 +733,7 @@ def _resume_locate(ctx: _Resume) -> dict | None:if ctx.found:ctx.target = ctx.found["id"]return None- if ctx.lazy and _child_run_active(ctx.target):+ if ctx.lazy and _child_run_active(ctx.target, ctx.profile_home):# Fresh subagent watch window: `subagent.start` relays BEFORE the child's first DB flush. Proceed lazily# with empty history — the live mirror streams the turn and the row exists by upgrade time.ctx.found = {}@@ -803,7 +803,7 @@ def _resume_reuse_live_locked(ctx: _Resume, sid: str, session: dict) -> dict:payload.update(messages=[], hydrating=bool(session.get("resume_hydrating")),message_count=int(session.get("resume_message_count") or payload["message_count"]))# A lazy watch session never owns a run loop — overlay the child-run registry.- if session.get("agent") is None and _child_run_active(ctx.target):+ if session.get("agent") is None and _child_run_active(ctx.target, ctx.profile_home):payload.update(running=True, status="streaming")return _ok(ctx.rid, payload)@@ -841,7 +841,7 @@ def _resume_lazy(ctx: _Resume) -> dict:if (reused := ctx.claim(sid, record)) is not None:return reused# A child mid-run emits no session events — liveness comes from the relay registry.- running = _child_run_active(ctx.target)+ running = _child_run_active(ctx.target, ctx.profile_home)# Display uses the VERBATIM child-only projection so model-invisible rows survive; repaired ``history``# still feeds live replay.display = historydiff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 4489008cb64..715fa025334 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1108,7 +1108,8 @@ def _start_agent_build(sid: str, session: dict) -> None:return# A lazy watch session spectating an in-flight child must stay lazy so the subagent live-mirror keeps# flowing (it bails once agent is set); incidental RPCs via _sess() would upgrade it mid-stream.- if session.get("lazy") and _child_run_active(str(session.get("session_key") or "")):+ if session.get("lazy") and _child_run_active(+ str(session.get("session_key") or ""), session.get("profile_home") or None):returnwith session.setdefault("agent_build_lock", threading.Lock()):if ready.is_set() or session.get("agent_build_started"):diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.pyindex 7e9e25bc487..4be767cef09 100644--- a/tui_gateway/tool_progress.py+++ b/tui_gateway/tool_progress.py@@ -468,7 +468,9 @@ def _progress_subagent(sid: str, name: str, preview, kw, event_type):# (keyed off the child sid); on the parent it's hundreds of ignored frames, so skip it.if event_type != "subagent.text":_emit(event_type, sid, payload)- _mirror_subagent_to_child(event_type, payload)+ # The child runs under the parent's profile: scope the mirror and its liveness registry+ # to that home so a same-key session in another profile cannot bind to this run.+ _mirror_subagent_to_child(event_type, payload, (_sessions.get(sid) or {}).get("profile_home"))# event_type -> (handler, requires): `requires` names the arg that must be truthy for the row to be