The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): broadcast approval.cancelled when reap/teardown drop pending prompts
Brooklyn Nicholson591e3a7ce126
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.tsindex 79e873c2489..f448a38a771 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts@@ -13,7 +13,7 @@ import {type PetChangeMeta,setChangeEventsAvailable} from '@/store/live-sync'-import { clearAllPrompts } from '@/store/prompts'+import { clearAllPrompts, clearApprovalRequest } from '@/store/prompts'import { markRuntimeGone } from '@/store/runtime-gone'import { dropSessionState, unbindTileRuntime } from '@/store/session-states'// Leaf import (not the `@/themes` barrel) to avoid pulling the ThemeProvider@@ -94,6 +94,31 @@ export function handleLifecycleEvent(ctx: GatewayEventContext): boolean {return true}+ if (event.type === 'approval.cancelled') {+ // The backend dropped pending approvals for a session being interrupted or+ // torn down (#106678) — the deny-resolve is otherwise silent, so a parked+ // prompt card would keep offering Approve/Reject against an approval that+ // no longer exists (the backend answers resolved: 0 and the click looks+ // dead). Clear the parked prompts; the turn's BLOCKED tool result is the+ // in-transcript signal, same as the timeout path.+ const cancelled = (event as GatewayEvent<'approval.cancelled'>).payload+ const runtimeId = String(cancelled?.session_id ?? '')+ const requestIds = (cancelled?.request_ids ?? []).map(id => String(id)).filter(Boolean)++ if (runtimeId && requestIds.length > 0) {+ // A request-id mismatch is a no-op in clear(), so a cancelled id can+ // never wipe a newer prompt re-armed by a live turn on the same session.+ for (const requestId of requestIds) {+ clearApprovalRequest(runtimeId, requestId)+ }+ } else if (runtimeId) {+ // No correlation ids on the wire — drop the session's prompt wholesale.+ clearAllPrompts(runtimeId)+ }++ return true+ }+if (event.type === 'session.reclaimed') {// The backend reclaimed a live session we may still be holding (idle// TTL, LRU cap, or the WS-orphan reap). Without this the runtime iddiff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 8b657edcac1..42f540bcd41 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4684,6 +4684,14 @@ export interface SessionReclaimedPayload {stored_session_id: stringreason: string}+/** ``session_lifecycle._announce_cancelled_gateway_approvals`` (broadcast). One frame for every pending approval dropped by an interrupt / reap / teardown (#106678) — the deny-resolve is silent without it, so a reconnecting client's prompt looks lost rather than cancelled. ``cancelled_count`` is the number of dropped entries; ``request_ids`` omits empty/missing ids, so the two can disagree when an entry has no request_id. */+export interface ApprovalCancelledPayload {+ session_id: string+ stored_session_id: string+ reason: string+ cancelled_count: number+ request_ids: string[]+}export interface SessionControlUpdatePayload {control: SessionControlSnapshot}@@ -5667,6 +5675,8 @@ export const SERVER_REQUEST_METHODS = [export interface BackendGatewayEventMap {/** Output chunk from an agent-owned background process. */'agent.terminal.output': TerminalOutputPayload+ /** Pending gateway approvals were dropped by interrupt/reap/teardown; the wait resolved as deny (not a user refusal). */+ 'approval.cancelled': ApprovalCancelledPayload/** A /background side agent finished. */'background.complete': SideAgentCompletePayload/** Device-flow URL + code for the billing scope step-up; the client opens the browser. */@@ -5817,6 +5827,7 @@ export interface BackendGatewayEventMap {export type BackendGatewayEventName = keyof BackendGatewayEventMapexport const GATEWAY_EVENT_TYPES = ['agent.terminal.output',+ 'approval.cancelled','background.complete','billing.step_up.verification','bot_relay.outbox.pending',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 2cec2bb8dd4..4cfbe7a93c9 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -4908,6 +4908,44 @@"title": "AgentsListResult","type": "object"},+ "ApprovalCancelledPayload": {+ "additionalProperties": false,+ "description": "``session_lifecycle._announce_cancelled_gateway_approvals`` (broadcast).\n\nOne frame for every pending approval dropped by an interrupt / reap / teardown (#106678) \u2014 the\ndeny-resolve is silent without it, so a reconnecting client's prompt looks lost rather than cancelled.\n``cancelled_count`` is the number of dropped entries; ``request_ids`` omits empty/missing ids, so the\ntwo can disagree when an entry has no request_id.",+ "properties": {+ "session_id": {+ "title": "Session Id",+ "type": "string"+ },+ "stored_session_id": {+ "title": "Stored Session Id",+ "type": "string"+ },+ "reason": {+ "title": "Reason",+ "type": "string"+ },+ "cancelled_count": {+ "title": "Cancelled Count",+ "type": "integer"+ },+ "request_ids": {+ "items": {+ "type": "string"+ },+ "title": "Request Ids",+ "type": "array"+ }+ },+ "required": [+ "session_id",+ "stored_session_id",+ "reason",+ "cancelled_count",+ "request_ids"+ ],+ "title": "ApprovalCancelledPayload",+ "type": "object"+ },"ApprovalChoice": {"enum": ["once",@@ -39187,6 +39225,18 @@}]},+ {+ "name": "approval.cancelled",+ "summary": "Pending gateway approvals were dropped by interrupt/reap/teardown; the wait resolved as deny (not a user refusal).",+ "params": [+ {+ "name": "payload",+ "schema": {+ "$ref": "#/components/schemas/ApprovalCancelledPayload"+ }+ }+ ]+ },{"name": "background.complete","summary": "A /background side agent finished.",diff --git a/tests/tui_gateway/test_approval_cancelled_on_reap.py b/tests/tui_gateway/test_approval_cancelled_on_reap.pynew file mode 100644index 00000000000..2b0bedda1c0--- /dev/null+++ b/tests/tui_gateway/test_approval_cancelled_on_reap.py@@ -0,0 +1,167 @@+"""Pending gateway approvals dropped by interrupt/reap/teardown must be loud, not silent (#106678).++``_interrupt_session_turn`` deny-resolves ``tools.approval._gateway_queues`` so the agent thread+unblocks (silence is not consent), and ``_teardown_session`` pops the queue via+``unregister_gateway_notify``. Before the ``approval.cancelled`` broadcast the drop was invisible:+a reconnecting client saw its parked prompt card answer ``resolved: 0`` (or a bare 4001 on+``approval.pending``), so the prompt looked lost rather than cancelled and the user had no signal+the command would never run.++Contracts here: interrupt/reap with a pending entry broadcasts ``approval.cancelled`` (session ids,+reason, request ids/count) BEFORE the deny-resolve drains the queue, an empty queue stays silent, an+explicit user deny does not emit this event, a broadcast failure still deny-resolves, and teardown+of a session still holding a pending approval broadcasts too.+"""++from __future__ import annotations++import pytest++from tui_gateway import server+from tools.approval import _gateway_queues, list_gateway_approvals, resolve_gateway_approval+from tools.approval_gateway_wait import _ApprovalEntry+++SESSION_KEY = "20260909_120000_aaaaaa"+SID = "live-loud-deny"+REQUEST_ID = "req-loud-deny-1"+++def captured(monkeypatch):+ events = []+ monkeypatch.setattr(+ server, "_broadcast_global_event", lambda ev, payload=None: events.append((ev, payload))+ )+ # Teardown's real work (finalize, agent close) is out of scope — this is+ # about what reaches the client.+ monkeypatch.setattr(server, "_finalize_session", lambda *a, **k: None)+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *_a, **_k: False)+ monkeypatch.setattr(server, "_clear_pending", lambda *_a, **_k: None)+ return events+++def session():+ return {+ "_sid": SID,+ "session_key": SESSION_KEY,+ "history": [],+ "history_lock": __import__("threading").Lock(),+ "running": False,+ "queued_prompt": None,+ "agent": None,+ }+++def pending_entry():+ entry = _ApprovalEntry({"command": "rm -rf /tmp/x", "request_id": REQUEST_ID})+ _gateway_queues.setdefault(SESSION_KEY, []).append(entry)+ try:+ yield entry+ finally:+ _gateway_queues.pop(SESSION_KEY, None)+++def _cancelled_events(captured):+ return [(ev, payload) for ev, payload in captured if ev == "approval.cancelled"]+++def test_interrupt_with_pending_broadcasts_approval_cancelled(captured, session, pending_entry):+ """RED on main: the deny-resolve happens, but nothing tells the client the prompt died."""+ server._interrupt_session_turn(SID, session, request_id=f"client-gone-{SID}", orphan=True)++ cancelled = _cancelled_events(captured)+ assert cancelled, "interrupt/reap must broadcast approval.cancelled when it drops a pending prompt"+ _event, payload = cancelled[0]+ assert payload["session_id"] == SID+ assert payload["stored_session_id"] == SESSION_KEY+ assert payload["reason"] == "ws_orphan_reap"+ assert payload["cancelled_count"] == 1+ assert REQUEST_ID in payload["request_ids"]+ assert pending_entry.result == "deny"+ assert pending_entry.event.is_set()+ assert list_gateway_approvals(SESSION_KEY) == []+++def test_interrupt_empty_queue_emits_nothing(captured, session):+ """CONTROL: no pending approvals -> keep the historical silent interrupt."""+ _gateway_queues.pop(SESSION_KEY, None)++ server._interrupt_session_turn(SID, session)++ assert _cancelled_events(captured) == []+++def test_explicit_user_deny_does_not_emit_cancelled(captured, pending_entry):+ """CONTROL: /deny and approval.respond stay on the existing resolve path."""+ count = resolve_gateway_approval(SESSION_KEY, "deny")++ assert count == 1+ assert pending_entry.result == "deny"+ assert _cancelled_events(captured) == []+++def test_broadcast_failure_still_deny_resolves(monkeypatch, session, pending_entry):+ """Fail-open: a wedged peer must not leave the agent thread blocked on the queue."""++ def _boom(*_a, **_k):+ raise RuntimeError("transport gone")++ monkeypatch.setattr(server, "_broadcast_global_event", _boom)+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda *_a, **_k: False)+ monkeypatch.setattr(server, "_clear_pending", lambda *_a, **_k: None)++ server._interrupt_session_turn(SID, session, request_id=f"client-gone-{SID}", orphan=True)++ assert pending_entry.result == "deny"+ assert pending_entry.event.is_set()+++def test_user_interrupt_reason_is_interrupt(captured, session, pending_entry):+ """session.interrupt (orphan=False, even with a client-gone request_id) labels interrupt, not reap."""+ server._interrupt_session_turn(SID, session, request_id=f"client-gone-{SID}")++ cancelled = _cancelled_events(captured)+ assert cancelled+ assert cancelled[0][1]["reason"] == "interrupt"+ assert pending_entry.result == "deny"+++def test_orphan_kwarg_labels_ws_orphan_reap_without_client_gone_prefix(captured, session, pending_entry):+ """The reason comes from orphan=, not request_id prefix sniffing."""+ server._interrupt_session_turn(SID, session, request_id="interrupt-manual", orphan=True)++ cancelled = _cancelled_events(captured)+ assert cancelled+ assert cancelled[0][1]["reason"] == "ws_orphan_reap"+ assert pending_entry.result == "deny"+++def test_teardown_with_pending_broadcasts_approval_cancelled(captured, session, pending_entry):+ """close_on_disconnect / idle reclaim can drop the queue via unregister without an interrupt."""+ server._teardown_session(session, end_reason="ws_orphan_reap")++ cancelled = _cancelled_events(captured)+ assert cancelled, "teardown must broadcast approval.cancelled when it drops a pending prompt"+ _event, payload = cancelled[0]+ assert payload["session_id"] == SID+ assert payload["stored_session_id"] == SESSION_KEY+ assert payload["reason"] == "ws_orphan_reap"+ assert payload["cancelled_count"] == 1+ assert REQUEST_ID in payload["request_ids"]+ assert list_gateway_approvals(SESSION_KEY) == []+++def test_teardown_without_pending_stays_silent(captured, session):+ server._teardown_session(session, end_reason="ws_orphan_reap")++ assert _cancelled_events(captured) == []+++def test_interrupt_missing_session_key_does_not_crash(captured):+ """Fail-open: a session dict without session_key must not raise out of interrupt."""+ session = {"history_lock": __import__("threading").Lock(), "running": False}+ server._interrupt_session_turn(SID, session)+ assert _cancelled_events(captured) == []diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex 1b26695406a..78690c6a665 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -397,6 +397,26 @@ class SessionReclaimedPayload(Payload):event("session.reclaimed", SessionReclaimedPayload, doc="The backend reclaimed a live session out from under its clients.")+class ApprovalCancelledPayload(Payload):+ """``session_lifecycle._announce_cancelled_gateway_approvals`` (broadcast).++ One frame for every pending approval dropped by an interrupt / reap / teardown (#106678) — the+ deny-resolve is silent without it, so a reconnecting client's prompt looks lost rather than cancelled.+ ``cancelled_count`` is the number of dropped entries; ``request_ids`` omits empty/missing ids, so the+ two can disagree when an entry has no request_id.+ """++ session_id: str+ stored_session_id: str+ reason: str # interrupt | ws_orphan_reap | idle_timeout | lru_evict | tui_close | ...+ cancelled_count: int+ request_ids: list[str]+++event("approval.cancelled", ApprovalCancelledPayload,+ doc="Pending gateway approvals were dropped by interrupt/reap/teardown; the wait resolved as deny (not a user refusal).")++class SessionControlUpdatePayload(Payload):control: SessionControlSnapshotdiff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.pyindex 366bdc95761..473a3b62303 100644--- a/tui_gateway/session_lifecycle.py+++ b/tui_gateway/session_lifecycle.py@@ -466,6 +466,38 @@ def _announce_session_reclaimed(session: dict, end_reason: str) -> None:logger.debug("session.reclaimed broadcast failed", exc_info=True)+def _announce_cancelled_gateway_approvals(session: dict, reason: str, *, session_id: str = "") -> None:+ """Tell connected clients pending gateway approvals are being dropped (interrupt/reap/teardown, #106678).++ Broadcast, not session-targeted: reap/interrupt run on timer threads with no live transport or contextvar,+ so ``_emit`` would miss detached clients (same as ``session.reclaimed``). Fail-open by design: a missing+ session key, an empty queue, and a broadcast failure never raise — the deny-resolve / teardown must proceed+ either way (silence in the notice channel must not strand the agent thread or the session teardown).+ """+ session_key = str(session.get("session_key") or "")+ if not session_key:+ return+ try:+ from tools.approval import list_gateway_approvals+ pending = list_gateway_approvals(session_key)+ except Exception:+ logger.debug("list_gateway_approvals failed", exc_info=True)+ return+ if not pending:+ return+ request_ids = [str(item.get("request_id") or "") for item in pending]+ request_ids = [rid for rid in request_ids if rid]+ try:+ _broadcast_global_event("approval.cancelled", {+ "session_id": str(session_id or session.get("_sid") or ""),+ "stored_session_id": session_key,+ "reason": reason,+ "cancelled_count": len(pending),+ "request_ids": request_ids})+ except Exception:+ logger.debug("approval.cancelled broadcast failed", exc_info=True)++def _teardown_session(session: dict | None, *, end_reason: str = "tui_close") -> None:"""Fully tear down a session: finalize, unregister notifier, close agent (``session.close`` + WS reaper). Theslash-worker is closed in ``_finalize_session`` (the single chokepoint), NOT here. Idempotent via ``_finalized``."""@@ -473,6 +505,10 @@ def _teardown_session(session: dict | None, *, end_reason: str = "tui_close") ->return_finalize_session(session, end_reason=end_reason)_announce_session_reclaimed(session, end_reason)+ with contextlib.suppress(Exception):+ # Same user-visible hole as the interrupt's deny-resolve (#106678): a pending prompt+ # popped by unregister must not just vanish from every surface without a notice.+ _announce_cancelled_gateway_approvals(session, end_reason)with contextlib.suppress(Exception):from tools.approval import unregister_gateway_notify# One approval callback per key: after a takeover it is the new runtime's registration.@@ -633,9 +669,15 @@ def _ws_session_is_orphaned(session: dict | None) -> bool:return bool(_ws_session_is_detached(session) and not session.get("running"))-def _interrupt_session_turn(sid: str, session: dict, *, request_id: str | None = None) -> bool:+def _interrupt_session_turn(+ sid: str, session: dict, *, request_id: str | None = None, orphan: bool = False,+) -> bool:"""Apply the shared ``session.interrupt`` contract to one claimed session; returns whether the compute-host control- channel was used. The WS orphan reaper reuses this so a dead client gets the same partial-history/queue semantics."""+ channel was used. The WS orphan reaper reuses this so a dead client gets the same partial-history/queue semantics.++ ``orphan=True`` (reaper path) labels dropped approvals ``ws_orphan_reap``; the label comes from the+ caller, never from request_id prefix sniffing — a future orphan caller may use another id (#106678).+ """use_compute_host = _session_uses_compute_host(session)should_interrupt = bool(session.get("running"))run_thread_alive = False@@ -686,6 +728,12 @@ def _interrupt_session_turn(sid: str, session: dict, *, request_id: str | None =_clear_inflight_turn(session)_clear_pending(sid)with contextlib.suppress(Exception):+ # Deny-resolve every pending approval so no agent thread blocks on the queue. The+ # deny is silent without the broadcast: a reconnecting client sees a bare 4001 on+ # approval.pending and the prompt looks lost rather than cancelled (#106678).+ # Announce BEFORE the queue is drained, or there is nothing left to name.+ reason = "ws_orphan_reap" if orphan else "interrupt"+ _announce_cancelled_gateway_approvals(session, reason, session_id=sid)from tools.approval import resolve_gateway_approvalresolve_gateway_approval(session["session_key"], "deny", resolve_all=True)return use_compute_host@@ -885,7 +933,8 @@ def _schedule_ws_orphan_reap(_pending_ws_reaps.pop(sid, None)if interrupt_session is not None:try:- isolated = _interrupt_session_turn(sid, interrupt_session, request_id=f"client-gone-{sid}")+ isolated = _interrupt_session_turn(+ sid, interrupt_session, request_id=f"client-gone-{sid}", orphan=True)logger.info("client_gone sid=%s action=interrupt turn_isolation=%s", sid, isolated)except Exception:logger.exception("client_gone interrupt failed sid=%s", sid)