The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): key the mirror state dict per profile and fail closed on a gone parent
liuhao10243adcebe10874
diff --git a/tests/tui_gateway/test_subagent_child_mirror.py b/tests/tui_gateway/test_subagent_child_mirror.pyindex d0dbe96dcc3..bf39c56729c 100644--- a/tests/tui_gateway/test_subagent_child_mirror.py+++ b/tests/tui_gateway/test_subagent_child_mirror.py@@ -54,7 +54,11 @@ def emits(server, monkeypatch):def _relay(server, event_type, **payload):- """Drive _on_tool_progress the way the delegate relay does."""+ """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."""+ server._sessions.setdefault("parent-sid", {"session_key": "parent"})server._on_tool_progress("parent-sid",event_type,@@ -125,7 +129,7 @@ def test_live_child_session_gets_native_stream(server, emits):def test_window_closed_midrun_drops_state_then_fresh_turn_on_reopen(server, emits):server._sessions["live-1"] = {"session_key": "child-1", "agent": None}_relay(server, "subagent.tool", tool_name="terminal", child_session_id="child-1")- assert "child-1" in server._child_mirrors+ assert (None, "child-1") in server._child_mirrors# Window closes → live session gone → state dropped on the next event.server._sessions.clear()diff --git a/tests/tui_gateway/test_subagent_mirror_profile_isolation.py b/tests/tui_gateway/test_subagent_mirror_profile_isolation.pyindex 8c69a2ffd0c..c0655d33f36 100644--- a/tests/tui_gateway/test_subagent_mirror_profile_isolation.py+++ b/tests/tui_gateway/test_subagent_mirror_profile_isolation.py@@ -56,10 +56,10 @@ HOME_A = "/profiles/a"HOME_B = "/profiles/b"-def _relay(server, event_type, **payload):+def _relay(server, event_type, sid="parent-sid", **payload):"""Drive _on_tool_progress the way the delegate relay does."""server._on_tool_progress(- "parent-sid",+ sid,event_type,payload.pop("tool_name", None),payload.pop("preview", None),@@ -126,3 +126,96 @@ def test_complete_clears_only_the_owning_profiles_entry(server, emits):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"] == 4009diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.pyindex e462f899a5b..2ac3d43b596 100644--- a/tui_gateway/agent_callbacks.py+++ b/tui_gateway/agent_callbacks.py@@ -15,13 +15,21 @@ 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.-_child_mirrors: dict[str, dict] = {}+# 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.+_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._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",@@ -43,6 +51,17 @@ 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)+ returnhome = _child_run_profile(profile_home)# Liveness registry first: accurate with no window open (one opened mid-run knows busy).if event_type == "subagent.complete":@@ -54,12 +73,12 @@ def _mirror_subagent_to_child(event_type: str, payload: dict, profile_home=None)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)+ _child_mirrors.pop((home, child_key), None)returncsid = live[0]text = str(payload.get("text") or "")with _child_mirrors_lock:- st = _child_mirrors.setdefault(child_key, {"seq": 0, "open_tool": None, "started": False})+ st = _child_mirrors.setdefault((home, child_key), {"seq": 0, "open_tool": None, "started": False})if not st["started"]:st["started"] = True_emit("message.start", csid)@@ -92,7 +111,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(child_key, None)+ _child_mirrors.pop((home, child_key), None)def _agent_presentation_enabled(sid: str, *, diagnostic: bool) -> bool:diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.pyindex 4be767cef09..1b8d527b5bb 100644--- a/tui_gateway/tool_progress.py+++ b/tui_gateway/tool_progress.py@@ -469,8 +469,13 @@ def _progress_subagent(sid: str, name: str, preview, kw, event_type):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.- _mirror_subagent_to_child(event_type, payload, (_sessions.get(sid) or {}).get("profile_home"))+ # 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)# event_type -> (handler, requires): `requires` names the arg that must be truthy for the row to be