Skip to content

The agent that grows with you

fix(tui_gateway): trim profile-scoped child-run registry to the salvage bar (#120212, salvage #120282)

teknium134846ee63006
diff --git a/tests/tui_gateway/test_history_inline_images.py b/tests/tui_gateway/test_history_inline_images.py
index 19ab24e616e..ce82a4def04 100644
--- a/tests/tui_gateway/test_history_inline_images.py
+++ b/tests/tui_gateway/test_history_inline_images.py
@@ -102,7 +102,7 @@ def test_resume_live_reattach_carries_the_switch(tmp_path, monkeypatch, inline_i
monkeypatch.setattr(srv, "_profile_home", lambda _p: None)
monkeypatch.setattr(srv, "_reattach_refusal", lambda *_a: None)
monkeypatch.setattr(srv, "_cancel_ws_orphan_reap", lambda *_a: None)
- monkeypatch.setattr(srv, "_child_run_active", lambda _key: False)
+ monkeypatch.setattr(srv, "_child_run_active", lambda *_a: False)
known = set(srv._sessions)
srv._sessions["live-sid"] = record
try:
diff --git a/tests/tui_gateway/test_resume_child_run_profile_scope.py b/tests/tui_gateway/test_resume_child_run_profile_scope.py
index 5c9e541cf23..edf5e907f78 100644
--- a/tests/tui_gateway/test_resume_child_run_profile_scope.py
+++ b/tests/tui_gateway/test_resume_child_run_profile_scope.py
@@ -72,6 +72,7 @@ def two_profiles(monkeypatch, tmp_path):
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)
+ monkeypatch.setattr(server, "_emit", lambda *a, **k: None)
known = set(server._sessions)
yield homes
with server._sessions_lock:
@@ -86,9 +87,11 @@ def _resume(**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)
+ """Register an in-flight child run the way the delegate relay does — a ``subagent.*``
+ progress event on a live PARENT sid owned by ``profile_home`` — so the read side is
+ exercised against the registry's real key form."""
+ server._sessions["parent-a"] = {"session_key": "parent-a", "profile_home": profile_home}
+ server._on_tool_progress("parent-a", "subagent.tool", "terminal", "ls", child_session_id=child_key)
def test_lazy_resume_refuses_child_id_active_under_another_profile(two_profiles):
diff --git a/tests/tui_gateway/test_session_db_ownership_teardown.py b/tests/tui_gateway/test_session_db_ownership_teardown.py
index 73284499282..73a2d7897af 100644
--- a/tests/tui_gateway/test_session_db_ownership_teardown.py
+++ b/tests/tui_gateway/test_session_db_ownership_teardown.py
@@ -276,7 +276,7 @@ def build_env(monkeypatch, tmp_path):
("_emit", lambda *a, **k: None),
("_schedule_mcp_late_refresh", lambda *a, **k: None),
("_session_source", lambda _current: None),
- ("_child_run_active", lambda _key: False),
+ ("_child_run_active", lambda *_a: False),
]:
if hasattr(server, name):
monkeypatch.setattr(server, name, value)
diff --git a/tests/tui_gateway/test_show_reasoning_display_gate.py b/tests/tui_gateway/test_show_reasoning_display_gate.py
index 76bf25fef06..8c7b635f84c 100644
--- a/tests/tui_gateway/test_show_reasoning_display_gate.py
+++ b/tests/tui_gateway/test_show_reasoning_display_gate.py
@@ -61,11 +61,11 @@ def test_child_mirror_skips_reasoning_delta_when_hidden(monkeypatch):
events = _capture(monkeypatch)
_session(monkeypatch, "child-sid", show_reasoning=False)
monkeypatch.setattr(
- server, "_find_live_session_by_key", lambda key: ("child-sid", {"agent": None, "show_reasoning": False})
+ server, "_find_live_session_by_key", lambda key, _home: ("child-sid", {"agent": None, "show_reasoning": False})
)
server._mirror_subagent_to_child(
- "subagent.thinking", {"child_session_id": "child-key", "text": "delegated thought"}
+ "subagent.thinking", {"child_session_id": "child-key", "text": "delegated thought"}, None
)
assert not any(event[0] == "reasoning.delta" for event in events)
diff --git a/tests/tui_gateway/test_subagent_child_mirror.py b/tests/tui_gateway/test_subagent_child_mirror.py
index bf39c56729c..7773334a326 100644
--- a/tests/tui_gateway/test_subagent_child_mirror.py
+++ b/tests/tui_gateway/test_subagent_child_mirror.py
@@ -54,10 +54,8 @@ def emits(server, monkeypatch):
def _relay(server, event_type, **payload):
- """Drive _on_tool_progress the way the delegate relay does. The parent record
- exists like any live turn's does (launch profile: no profile_home) — a parent
- that is already gone is the fail-closed path, covered in
- test_subagent_mirror_profile_isolation.py."""
+ """Drive _on_tool_progress the way the delegate relay does; the parent record
+ exists like any live turn's does (launch profile: no profile_home)."""
server._sessions.setdefault("parent-sid", {"session_key": "parent"})
server._on_tool_progress(
"parent-sid",
@@ -164,10 +162,10 @@ def test_stale_child_run_not_reported_active(server, emits):
pinning running=true on every future lazy resume of that child."""
server._active_child_runs[(None, "child-1")] = 0.0 # epoch — ancient
- assert server._child_run_active("child-1") is False
+ assert server._child_run_active("child-1", None) is False
_relay(server, "subagent.tool", tool_name="terminal", child_session_id="child-1")
- assert server._child_run_active("child-1") is True
+ assert server._child_run_active("child-1", None) is True
def test_prompt_submit_rejected_while_child_run_active(server, emits):
@@ -190,7 +188,7 @@ def test_prompt_submit_rejected_while_child_run_active(server, emits):
# Run completes → the same submit upgrades into a real conversation
# (passes the guard; fails later only because this test stubs no agent).
_relay(server, "subagent.complete", child_session_id="child-1", status="completed", summary="ok")
- assert server._child_run_active("child-1") is False
+ assert server._child_run_active("child-1", None) is False
def test_active_child_runs_registry_tracks_liveness(server, emits):
diff --git a/tests/tui_gateway/test_subagent_mirror_profile_isolation.py b/tests/tui_gateway/test_subagent_mirror_profile_isolation.py
deleted file mode 100644
index c0655d33f36..00000000000
--- a/tests/tui_gateway/test_subagent_mirror_profile_isolation.py
+++ /dev/null
@@ -1,221 +0,0 @@
-"""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, sid="parent-sid", **payload):
- """Drive _on_tool_progress the way the delegate relay does."""
- server._on_tool_progress(
- 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)
-
-
-def test_mirror_state_dict_is_scoped_per_profile(server, emits):
- # The mirror's per-child stream state (started flag, open tool) is keyed on
- # (home, key) too: with a bare key, B's relay found A's entry "already started"
- # and completed A's open tool verbatim into B's window — no message.start, and
- # A's tool payload (preview included) eavesdropped into another profile.
- server._sessions["parent-a"] = {"session_key": "parent", "profile_home": HOME_A}
- server._sessions["parent-b"] = {"session_key": "parent", "profile_home": HOME_B}
- server._sessions["live-a"] = {"session_key": "child-1", "profile_home": HOME_A, "agent": None}
- server._sessions["live-b"] = {"session_key": "child-1", "profile_home": HOME_B, "agent": None}
-
- _relay(server, "subagent.tool", sid="parent-a", tool_name="terminal",
- preview="SECRET-A: cat ~/.aws/credentials", child_session_id="child-1")
- _relay(server, "subagent.tool", sid="parent-b", tool_name="web_search",
- preview="b query", child_session_id="child-1")
-
- a = [(e, p) for e, s, p in emits if s == "live-a"]
- b = [(e, p) for e, s, p in emits if s == "live-b"]
- # Each window got its OWN synthetic turn: message.start then its parent's tool.
- assert [e for e, _ in a] == ["message.start", "tool.start"]
- assert [e for e, _ in b] == ["message.start", "tool.start"]
- assert a[1][1]["preview"] == "SECRET-A: cat ~/.aws/credentials"
- assert b[1][1]["name"] == "web_search"
- # A's open tool stays open under A's dimension — not completed by B's relay.
- assert server._child_mirrors[(HOME_A, "child-1")]["open_tool"]["name"] == "terminal"
-
-
-def test_gone_parent_record_fails_closed(server, emits):
- # Mid-run parent teardown (session.close pops unconditionally; the WS orphan reaper
- # force-pops mid-turn): the relaying sid is gone from _sessions, so the event cannot
- # be attributed to a profile. None is NOT a stand-in here — it is the launch profile,
- # a real dimension — so the unresolved event must bind nothing: no liveness row under
- # the launch dimension, no mirror into a same-key launch-profile window. The complete
- # still drains the row the child registered under its real home before the teardown.
- server._sessions["parent-a"] = {"session_key": "parent", "profile_home": HOME_A}
- server._sessions["launch-live"] = {"session_key": "child-1", "agent": None}
- _relay(server, "subagent.tool", sid="parent-a", tool_name="terminal",
- preview="ls", child_session_id="child-1")
- assert server._child_run_active("child-1", HOME_A)
-
- server._sessions.pop("parent-a")
- _relay(server, "subagent.tool", sid="parent-a", tool_name="terminal",
- preview="more", child_session_id="child-1")
-
- assert (None, "child-1") not in server._active_child_runs
- assert [(e, s) for e, s, _ in emits if s == "launch-live"] == []
- assert server._child_mirrors == {}
-
- _relay(server, "subagent.complete", sid="parent-a",
- child_session_id="child-1", status="completed", summary="done")
- assert server._active_child_runs == {}
-
-
-def test_lazy_build_guard_holds_only_the_owning_profile_lazy(server):
- # _start_agent_build's spectate guard (server.py): a lazy watch window stays lazy
- # only while the run is in flight under ITS OWN profile — a same-key run under
- # another profile must not pin this window lazy and starve its agent build.
- import threading
-
- server._mirror_subagent_to_child("subagent.tool", {"child_session_id": "child-1"}, HOME_A)
-
- lazy_b = {"session_key": "child-1", "profile_home": HOME_B, "lazy": True,
- "agent_ready": threading.Event()}
- server._start_agent_build("live-b", lazy_b)
- lazy_b["_agent_build_thread"].join(timeout=5) # no live-b in _sessions: the build abandons quietly
- assert lazy_b.get("agent_build_started") is True
- assert "lazy" not in lazy_b
-
- lazy_a = {"session_key": "child-1", "profile_home": HOME_A, "lazy": True,
- "agent_ready": threading.Event()}
- server._start_agent_build("live-a", lazy_a)
- assert lazy_a.get("agent_build_started") is None
- assert lazy_a.get("lazy") is True
-
-
-def test_submit_turn_guard_holds_only_the_owning_profile(server):
- # _lock_in_submit_turn's busy guard (methods_prompt.py): typing into a lazy watch
- # window is refused only while the in-flight child runs under the window's OWN
- # profile — another profile's same-key run does not fence this turn.
- import threading
-
- server._mirror_subagent_to_child("subagent.tool", {"child_session_id": "child-1"}, HOME_A)
-
- live_b = {"agent": None, "history_lock": threading.Lock(), "lazy": True,
- "running": False, "session_key": "child-1", "profile_home": HOME_B}
- err, _fields = server._lock_in_submit_turn("rid-b", "live-b", live_b, "hi", {}, False, [], None, None)
- assert err is None # admitted: B's window is not fenced by A's run
-
- live_a = {"agent": None, "history_lock": threading.Lock(), "lazy": True,
- "running": False, "session_key": "child-1", "profile_home": HOME_A}
- err_a, _fields = server._lock_in_submit_turn("rid-a", "live-a", live_a, "hi", {}, False, [], None, None)
- assert err_a["error"]["code"] == 4009
diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.py
index 2ac3d43b596..994871da381 100644
--- a/tui_gateway/agent_callbacks.py
+++ b/tui_gateway/agent_callbacks.py
@@ -15,70 +15,48 @@ from .method_ctx import bind_module
# Child-session live mirror: a delegated child's activity reaches the gateway only as
# relayed ``subagent.*`` events on the PARENT sid; translate them into native stream
# events on the CHILD sid (write_json routes by sid) so its own window is not silent.
-# Keyed like ``_active_child_runs``: the child runs under its PARENT's profile, and the
-# per-child stream state (open tool, started flag) must not leak across profiles sharing
-# a stored id — A's open tool would otherwise complete into B's window verbatim.
+# Both dicts are keyed on (profile_home, child key): stored ids are timestamps that exist in
+# several profiles' stores, and a child runs under its PARENT's profile — a bare-key hit let
+# profile B's lazy resume bind to A's in-flight run and receive its mirror (#120212).
_child_mirrors: dict[tuple[str | None, 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. 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.
+# lazy watch resume reports running=true during a silent long tool.
_active_child_runs: dict[tuple[str | None, str], float] = {}
-# The relaying parent's record is gone (session.close pops unconditionally; the WS orphan
-# reaper force-pops mid-turn): the event cannot be attributed to a profile, so it binds
-# NOTHING. None itself is a legal key dimension (the launch profile), so unresolvable is
-# a distinct sentinel rather than a None profile_home.
-_UNRESOLVED_PROFILE = object()
# 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_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))
+def _child_run_active(child_key: str, profile_home) -> bool:
+ """``profile_home`` is the caller's resolved home (Path / str / None = launch profile), never omitted."""
+ ts = _active_child_runs.get((str(profile_home) if profile_home else None, 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, profile_home=None) -> None:
+def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home) -> None:
child_key = str(payload.get("child_session_id") or "")
if not child_key:
return
- if profile_home is _UNRESOLVED_PROFILE:
- # Fail-closed: no liveness pin under the launch-profile dimension, no mirror into any
- # window. Rows this child registered earlier under its real home are still drained so a
- # mid-run parent teardown cannot strand them for the full stale window.
- if event_type == "subagent.complete":
- for key in [k for k in _active_child_runs if k[1] == child_key]:
- _active_child_runs.pop(key, None)
- with _child_mirrors_lock:
- for key in [k for k in _child_mirrors if k[1] == child_key]:
- _child_mirrors.pop(key, None)
- return
- home = _child_run_profile(profile_home)
+ key = (str(profile_home) if profile_home else None, child_key)
# Liveness registry first: accurate with no window open (one opened mid-run knows busy).
if event_type == "subagent.complete":
- _active_child_runs.pop((home, child_key), None)
+ _active_child_runs.pop(key, None)
else:
- _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, home)
+ _active_child_runs[key] = time.time()
+ # Mirror only into a live watch session of the OWNING profile that is 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, key[0])
if live is None or live[1].get("agent") is not None:
with _child_mirrors_lock:
- _child_mirrors.pop((home, child_key), None)
+ _child_mirrors.pop(key, None)
return
csid = live[0]
text = str(payload.get("text") or "")
with _child_mirrors_lock:
- st = _child_mirrors.setdefault((home, child_key), {"seq": 0, "open_tool": None, "started": False})
+ st = _child_mirrors.setdefault(key, {"seq": 0, "open_tool": None, "started": False})
if not st["started"]:
st["started"] = True
_emit("message.start", csid)
@@ -111,7 +89,7 @@ def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home=None)
else:
summary = str(payload.get("summary") or payload.get("text") or "")
_emit("message.complete", csid, {"text": summary})
- _child_mirrors.pop((home, child_key), None)
+ _child_mirrors.pop(key, None)
def _agent_presentation_enabled(sid: str, *, diagnostic: bool) -> bool:
diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.py
index 1b8d527b5bb..a1abdb3c21d 100644
--- a/tui_gateway/tool_progress.py
+++ b/tui_gateway/tool_progress.py
@@ -468,14 +468,11 @@ 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)
- # 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. A parent
- # record that is already gone (close / WS orphan reaper mid-turn) is unresolvable — pass the
- # sentinel so the mirror fails closed instead of folding the run into the launch profile.
- parent = _sessions.get(sid)
- _mirror_subagent_to_child(
- event_type, payload,
- parent.get("profile_home") if parent is not None else _UNRESOLVED_PROFILE)
+ # The child runs under the PARENT's profile: the mirror and its liveness registry are scoped to
+ # that home. A parent record already gone (close / WS orphan reap mid-turn) cannot be attributed
+ # to a profile — bind nothing rather than fold the run into the launch profile.
+ if (parent := _sessions.get(sid)) is not None:
+ _mirror_subagent_to_child(event_type, payload, parent.get("profile_home"))
# event_type -> (handler, requires): `requires` names the arg that must be truthy for the row to be