diff --git a/tests/tui_gateway/test_subagent_snapshot.py b/tests/tui_gateway/test_subagent_snapshot.py index feaf235ccb..ca10d98cf1 100644 --- a/tests/tui_gateway/test_subagent_snapshot.py +++ b/tests/tui_gateway/test_subagent_snapshot.py @@ -30,6 +30,7 @@ def test_snapshot_projects_only_this_sessions_runtime_records(runtime): from tools import async_delegation as bg from tools.delegate_tool_child_run import _register_child from tools.delegate_tool_registry import _unregister_subagent + from tools.delegate_tool_progress import _build_child_progress_callback server, owner, transport, call = runtime release = threading.Event() @@ -52,11 +53,16 @@ def test_snapshot_projects_only_this_sessions_runtime_records(runtime): foreign = SimpleNamespace(_subagent_id="foreign", _delegate_depth=1, model="test") _register_child(foreign, None, "foreign secret", owner_session_id="other", owner_transport=transport, owner_session_record={}) + progress = _build_child_progress_callback(0, "owned task", + SimpleNamespace(tool_progress_callback=lambda *a, **kw: None), subagent_id="child") + progress("tool.started", "read_file") + progress("tool.completed", "read_file") try: snapshot = call("subagent.list")["result"] assert [s["subagent_id"] for s in snapshot["subagents"]] == ["child"] - assert snapshot["delegations"][0]["delegation_id"] == did - assert snapshot["delegations"][0]["subagent_ids"] == ["child"] + assert snapshot["subagents"][0]["last_tool"] == "read_file" + assert snapshot["delegations"] == [] + assert snapshot["subagents"][0]["tool_count"] == 1 wire = json.dumps(snapshot) assert "private handoff" not in wire and "foreign secret" not in wire assert "owner_transport" not in wire and "session_key" not in wire @@ -109,3 +115,36 @@ def test_live_tail_and_steer_share_exact_owner_and_end_with_child(runtime): "subagent_id": "child", "available": False, "text": "", "truncated": False} finally: _unregister_subagent("child") + + + +def test_interrupt_requires_exact_live_owner_but_direct_helper_stays_legacy(runtime): + from tools.delegate_tool_child_run import _register_child + from tools.delegate_tool_registry import interrupt_subagent, _unregister_subagent + + server, owner, transport, call = runtime + stopped = [] + child = SimpleNamespace(_subagent_id="child", _delegate_depth=1, model="test", + hard_interrupt=lambda message: stopped.append(message)) + _register_child(child, None, "owned", owner_session_id="ui-owner", + owner_transport=transport, owner_session_record=owner) + try: + for params in ({"session_id": ""}, {"session_id": "missing"}, + {"via": SimpleNamespace(write=lambda frame: True)}): + reply = call("subagent.interrupt", subagent_id="child", **params) + assert "error" in reply or not reply["result"]["found"] + assert stopped == [] + server._sessions["foreign"] = {**owner} + assert not call("subagent.interrupt", session_id="foreign", subagent_id="child")["result"]["found"] + server._sessions["ui-owner"] = {**owner} + assert not call("subagent.interrupt", subagent_id="child")["result"]["found"] + assert stopped == [] + server._sessions["ui-owner"] = owner + assert call("subagent.interrupt", subagent_id="child")["result"]["found"] + assert len(stopped) == 1 + assert interrupt_subagent("child") + assert len(stopped) == 2 + _unregister_subagent("child") + assert not call("subagent.interrupt", subagent_id="child")["result"]["found"] + finally: + _unregister_subagent("child") diff --git a/tui_gateway/AGENTS.md b/tui_gateway/AGENTS.md index fda09b48d7..bb571fd345 100644 --- a/tui_gateway/AGENTS.md +++ b/tui_gateway/AGENTS.md @@ -43,10 +43,11 @@ existing topical sibling, registered in the table — no `if method == ...` chai `subagent.list({session_id})` returns `{subagents, delegations}` for the calling transport's live session. Live child records are pinned to the exact session -record and transport; background records use their captured `origin_ui_session_id` -so compression does not hide ongoing work. Both lists are allowlisted projections: -no dispatch context, results, callbacks, or routing keys are sent. Clients hydrate -from this snapshot on their existing poll and avoid updates when unchanged. +record and transport. `last_tool` is the last started tool, not an in-flight +indicator. Async completion units are not agents and lack exact generation authority; +`delegations` remains an empty array for wire compatibility. No dispatch context, +results, callbacks, or routing keys are sent. Clients hydrate from this snapshot +on their existing poll and avoid updates when unchanged. `subagent.tail({session_id, subagent_id})` returns `{subagent_id, available, text, truncated}`: the last 16 KiB of the live child's @@ -56,6 +57,10 @@ This is live-only, not persisted completion history. Invalid session/transport returns error 4001. `subagent.steer({session_id, subagent_id, text})` remains the shared control: `status: queued` acknowledges acceptance, not delivery; final boundary races are reported by the existing runtime as `missed_steer`. +`subagent.interrupt({session_id, subagent_id})` requires the same exact live +session/transport/generation ownership, including for subtree members. Missing +RPC session authority is rejected; direct in-process `interrupt_subagent(id)` +retains its legacy unscoped contract. ## Slash command flow diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py index a1eaff2bf4..e12cdab1bf 100644 --- a/tui_gateway/methods_session.py +++ b/tui_gateway/methods_session.py @@ -2033,14 +2033,6 @@ def _(rid, params: dict) -> dict: return _ok(rid, {"paused": set_spawn_paused(bool(params.get("paused", True)))}) -@method("subagent.interrupt") -def _(rid, params: dict) -> dict: - from tools.delegate_tool import interrupt_subagent - if not (subagent_id := _str_param(params, "subagent_id")): - return _err(rid, 4000, "subagent_id required") - return _ok(rid, {"found": interrupt_subagent(subagent_id), "subagent_id": subagent_id}) - - @method("subagent.steer") def _(rid, params: dict) -> dict: """Queue steering text into a live delegated child (the in-flight tool call is never cut). "queued" diff --git a/tui_gateway/methods_subagents.py b/tui_gateway/methods_subagents.py index 53547df19e..97b8eb02c4 100644 --- a/tui_gateway/methods_subagents.py +++ b/tui_gateway/methods_subagents.py @@ -11,10 +11,7 @@ method = _registry.method _SUBAGENT_SNAPSHOT_FIELDS = ( "subagent_id", "parent_id", "depth", "goal", "delegation_id", "model", - "started_at", "status", "tool_count", "current_tool", "accepting_steer", -) -_ASYNC_SNAPSHOT_FIELDS = ( - "delegation_id", "goal", "role", "model", "status", "dispatched_at", "completed_at", "is_batch", + "started_at", "status", "tool_count", "last_tool", "accepting_steer", ) _SUBAGENT_TAIL_BYTES = 16384 @@ -35,25 +32,37 @@ def _(rid, params): transport, owner = _current_session_steer_authority(session_id) if transport is None or owner is None: return _err(rid, 4001, "session not found or not owned by this transport") - from tools.async_delegation import _records, _records_lock - live = _owned_subagent_records(session_id, transport, owner) - # Read only projected fields, without invoking unrelated sessions' progress callbacks. - with _records_lock: - delegations = [] - for record in _records.values(): - if record.get("origin_ui_session_id") != session_id: - continue - item = {key: record.get(key) for key in _ASYNC_SNAPSHOT_FIELDS} - item["subagent_ids"] = [r["subagent_id"] for r in live - if r.get("delegation_id") == record.get("delegation_id")] - delegations.append(item) return _ok(rid, { "subagents": [{key: r.get(key) for key in _SUBAGENT_SNAPSHOT_FIELDS} for r in live], - "delegations": delegations, + "delegations": [], }) +@method("subagent.interrupt") +def _(rid, params): + from agent.interrupt_compat import request_hard_interrupt + + subagent_id = _str_param(params, "subagent_id") + if not subagent_id: + return _err(rid, 4000, "subagent_id required") + session_id = _str_param(params, "session_id") + transport, owner = _current_session_steer_authority(session_id) + if transport is None or owner is None: + return _err(rid, 4001, "session not found or not owned by this transport") + record = next((r for r in _owned_subagent_records(session_id, transport, owner) + if r.get("subagent_id") == subagent_id), None) + agent = record.get("agent") if record else None + # Interrupt the authorized object, never re-resolve a globally recyclable id. + found = False + if agent is not None: + try: + found = bool(request_hard_interrupt(agent, f"Interrupted via TUI ({subagent_id})")) + except Exception: + logger.debug("subagent interrupt failed", exc_info=True) + return _ok(rid, {"found": found, "subagent_id": subagent_id}) + + @method("subagent.tail") def _(rid, params): session_id = _str_param(params, "session_id") diff --git a/ui-tui/src/app/agentRoster.ts b/ui-tui/src/app/agentRoster.ts index 01711d2190..f30ba1c1d5 100644 --- a/ui-tui/src/app/agentRoster.ts +++ b/ui-tui/src/app/agentRoster.ts @@ -38,7 +38,7 @@ export function mergeAgentRoster(events: SubagentProgress[], data: SubagentListR // Snapshot replies may predate progress/completion events already rendered. status: previous && previous.status !== 'queued' ? previous.status : s.status === 'queued' ? 'queued' : 'running', toolCount: Math.max(s.tool_count ?? 0, previous?.toolCount ?? 0), - tools: previous?.tools.length ? previous.tools : s.current_tool ? [s.current_tool] : [] + tools: previous?.tools.length ? previous.tools : s.last_tool ? [s.last_tool] : [] }) } diff --git a/ui-tui/src/components/agentsOverlay.tsx b/ui-tui/src/components/agentsOverlay.tsx index d44bda719d..be5505e33e 100644 --- a/ui-tui/src/components/agentsOverlay.tsx +++ b/ui-tui/src/components/agentsOverlay.tsx @@ -696,7 +696,7 @@ export function AgentsOverlay({ gw, initialHistoryIndex = 0, onClose, t }: Agent } } - const interrupt = (id: string) => gw.request('subagent.interrupt', { subagent_id: id }) + const interrupt = (id: string) => gw.request('subagent.interrupt', { session_id: sid, subagent_id: id }) const killOne = (id: string) => guardLive(() => { diff --git a/ui-tui/src/gatewayTypes.ts b/ui-tui/src/gatewayTypes.ts index 7de5b462a4..4b0b0be85c 100644 --- a/ui-tui/src/gatewayTypes.ts +++ b/ui-tui/src/gatewayTypes.ts @@ -617,7 +617,7 @@ export interface SubagentListResponse { started_at?: number | null status?: string | null tool_count?: number | null - current_tool?: string | null + last_tool?: string | null }[] delegations: AsyncDelegationRecord[] }