Skip to content

The agent that grows with you

fix(tui_gateway): old app builds no longer stall the agent on clarify/approval; late approval choices count

teknium1f9d178f78ed8
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index b702cb98840..a3990d6bf8d 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -1378,6 +1378,12 @@ export interface PingResult {
export interface GatewayCapabilitiesResult {
per_session_exclusive_submit: boolean
}
+export interface ClientCapabilitiesParams {
+ server_requests?: boolean
+}
+export interface ClientCapabilitiesResult {
+ server_requests: string[]
+}
/** ``word`` is the token under the cursor (``@`` prefix = context reference); ``cwd`` / ``session_id`` pick the directory the listing resolves against. */
export interface CompletePathParams {
profile?: string | null
@@ -4216,6 +4222,8 @@ export interface RpcMethods {
'clarify.lock': { params: ClarifyLockParams; result: ClarifyLockResult }
/** Run ``hermes <argv>`` non-interactively and capture its output; ``blocked`` explains a refusal. */
'cli.exec': { params: CliExecParams; result: CliExecResult }
+ /** What the calling client handles, sent once per connection (after gateway.ready); returns the server→client request methods this backend may send. */
+ 'client.capabilities': { params: ClientCapabilitiesParams; result: ClientCapabilitiesResult }
/** Save the host clipboard image into the session and queue it for the next turn. */
'clipboard.paste': { params: ClipboardPasteParams; result: AttachedImageResult }
/** Run a quick/plugin/bundle/skill/built-in slash command and answer a structured directive. */
@@ -4633,6 +4641,7 @@ export const RPC_METHODS = [
'browser.manage',
'clarify.lock',
'cli.exec',
+ 'client.capabilities',
'clipboard.paste',
'command.dispatch',
'command.resolve',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 241b5e495bc..ddd394afbbf 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -366,6 +366,24 @@
}
}
},
+ {
+ "name": "client.capabilities",
+ "summary": "What the calling client handles, sent once per connection (after gateway.ready); returns the server\u2192client request methods this backend may send.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ClientCapabilitiesParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ClientCapabilitiesResult"
+ }
+ }
+ },
{
"name": "clipboard.paste",
"summary": "Save the host clipboard image into the session and queue it for the next turn.",
@@ -7131,6 +7149,35 @@
"title": "CliExecResult",
"type": "object"
},
+ "ClientCapabilitiesParams": {
+ "additionalProperties": false,
+ "properties": {
+ "server_requests": {
+ "default": false,
+ "title": "Server Requests",
+ "type": "boolean"
+ }
+ },
+ "title": "ClientCapabilitiesParams",
+ "type": "object"
+ },
+ "ClientCapabilitiesResult": {
+ "additionalProperties": false,
+ "properties": {
+ "server_requests": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Server Requests",
+ "type": "array"
+ }
+ },
+ "required": [
+ "server_requests"
+ ],
+ "title": "ClientCapabilitiesResult",
+ "type": "object"
+ },
"ClipboardPasteParams": {
"additionalProperties": false,
"properties": {
diff --git a/apps/shared/src/json-rpc-channel.test.ts b/apps/shared/src/json-rpc-channel.test.ts
index da8189d86e3..adc1f3b8c2f 100644
--- a/apps/shared/src/json-rpc-channel.test.ts
+++ b/apps/shared/src/json-rpc-channel.test.ts
@@ -173,6 +173,25 @@ describe('JsonRpcRequestChannel', () => {
// Server→client requests (tui_gateway/server_requests.py): the backend asks,
// the client answers with a RESPONSE frame carrying the same id.
+ it('advertises server-request support once per gateway.ready and shrugs off an older backend', () => {
+ // A backend that never hears client.capabilities treats a WebSocket client as a build older than
+ // server→client requests and fails every clarify/approval for it at once (tui_gateway/server_requests.py).
+ const channel = new JsonRpcRequestChannel({ requestIdPrefix: 'c' })
+ const { sent, transport, last } = spyTransport()
+
+ channel.attach(transport)
+ channel.handleFrame(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'session.info', session_id: 's' } }))
+ expect(sent).toHaveLength(0)
+
+ channel.handleFrame(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: {} } }))
+ expect(sent).toHaveLength(1)
+ expect(JSON.parse(sent[0])).toMatchObject({ method: 'client.capabilities', params: { server_requests: true } })
+
+ // An older backend answers -32601: nothing rejects out of the channel.
+ channel.handleFrame(JSON.stringify({ error: { code: -32601, message: 'unknown method' }, id: last().id, jsonrpc: '2.0' }))
+ expect(sent).toHaveLength(1)
+ })
+
it('routes a server request to the first accepting handler and answers -32601 when nobody accepts', () => {
const unhandled: string[] = []
const channel = new JsonRpcRequestChannel({ onUnhandledRequest: req => void unhandled.push(req.method) })
diff --git a/apps/shared/src/json-rpc-channel.ts b/apps/shared/src/json-rpc-channel.ts
index 20de1e393e1..38910c9576e 100644
--- a/apps/shared/src/json-rpc-channel.ts
+++ b/apps/shared/src/json-rpc-channel.ts
@@ -468,12 +468,28 @@ export class JsonRpcRequestChannel {
}
if (frame.method === 'event' && frame.params && typeof (frame.params as GatewayEvent).type === 'string') {
+ if ((frame.params as GatewayEvent).type === 'gateway.ready') {
+ this.advertiseCapabilities()
+ }
+
this.options.onEvent?.(frame.params as GatewayEvent)
}
return frame
}
+ /**
+ * Tell the backend, once per connection generation, that this client answers
+ * server→client requests (a handler result or `-32601`). Without it a
+ * backend treats a WebSocket client as a build that predates server requests
+ * and fails every clarify/approval/… for it immediately instead of stalling
+ * the agent for the full deadline. An older backend answers `-32601` here;
+ * that is ignored.
+ */
+ private advertiseCapabilities(): void {
+ this.request('client.capabilities', { server_requests: true }).catch(() => undefined)
+ }
+
/**
* Begin the `gateway.ping` keepalive on the bound transport. Only call when
* `gateway.ready.heartbeat` advertised support — an older backend would
diff --git a/tests/tools/test_approval_gateway_wait_late_choice.py b/tests/tools/test_approval_gateway_wait_late_choice.py
new file mode 100644
index 00000000000..22e9c2abdae
--- /dev/null
+++ b/tests/tools/test_approval_gateway_wait_late_choice.py
@@ -0,0 +1,49 @@
+"""A gateway approval choice that lands after the deadline check is an answer, not a timeout (#112548).
+
+``_await_gateway_decision`` polls the entry's event with a deadline; ``resolve_gateway_approval`` may
+commit a choice between the poll giving up and the entry leaving the queue. The verdict must be the
+choice committed under the approval lock — the client was acked ``ok`` for it — never "timeout".
+"""
+
+from tools import approval as mod
+from tools import approval_gateway_wait as wait_mod
+
+
+SESSION_KEY = "approval-late-choice"
+APPROVAL = {"command": "rm -rf build", "description": "d", "pattern_key": "dangerous", "pattern_keys": ["dangerous"]}
+
+
+def _clear():
+ mod._gateway_queues.clear()
+ mod._gateway_notify_cbs.clear()
+
+
+def test_choice_landing_after_the_deadline_check_is_resolved(monkeypatch):
+ _clear()
+ hooks: list[tuple[str, dict]] = []
+ monkeypatch.setattr(wait_mod._ctx, "_fire_approval_hook", lambda name, **kw: hooks.append((name, kw)))
+
+ def deadline_passed_then_user_answered(event, session_key, *, interrupt_log):
+ # The poll loop has already decided "timeout"; the user's /approve lands before the entry leaves the queue.
+ assert mod.resolve_gateway_approval(session_key, "once") == 1
+ return "timeout"
+
+ monkeypatch.setattr(wait_mod, "_poll_event", deadline_passed_then_user_answered)
+
+ decision = wait_mod._await_gateway_decision(SESSION_KEY, lambda data: None, APPROVAL)
+
+ assert decision == {"resolved": True, "choice": "once", "reason": None}
+ assert hooks[-1][0] == "post_approval_response" and hooks[-1][1]["choice"] == "once"
+ assert SESSION_KEY not in mod._gateway_queues
+
+
+def test_plain_timeout_still_reports_unresolved(monkeypatch):
+ _clear()
+ monkeypatch.setattr(wait_mod._ctx, "_fire_approval_hook", lambda name, **kw: None)
+ monkeypatch.setattr(wait_mod, "_poll_event", lambda event, session_key, *, interrupt_log: "timeout")
+
+ decision = wait_mod._await_gateway_decision(SESSION_KEY, lambda data: None, APPROVAL)
+
+ assert decision == {"resolved": False, "choice": None, "reason": None}
+ # Nothing is left for a late /approve to hit: the client learns nothing was pending.
+ assert mod.resolve_gateway_approval(SESSION_KEY, "once") == 0
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index d061362515d..966a8bae458 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -360,21 +360,77 @@ def test_send_returns_an_answer_committed_after_the_deadline_expired(capture, mo
assert not server_requests._open
-def test_server_request_error_response_fails_fast(capture):
- """A shared-channel client without a handler answers -32601 instead of waiting for the deadline."""
+def _silent_ws():
+ """A WebSocket client build that predates server→client requests: receives the frame, never answers."""
+ from tui_gateway.ws import WSTransport
+
+ class _SilentWS(WSTransport):
+ def __init__(self):
+ self._ws, self._loop, self._peer, self._auth_identity = object(), None, "test", None
+ self.frames: list[dict] = []
+
+ def write(self, obj):
+ self.frames.append(obj)
+ return True
+
+ def close(self):
+ pass
+
+ return _SilentWS()
+
+
+def _ws_session(server, sid, peer):
+ server._sessions[sid] = {"session_key": sid, "transport": peer, "history": [], "history_lock": threading.Lock(),
+ "agent_ready": None}
+
+
+def test_server_request_fails_fast_for_a_ws_client_that_never_advertised(server):
+ """A WebSocket client that never sent ``client.capabilities`` cannot answer, so send() returns the
+ error-response shape (None) at once instead of stalling the agent for the deadline (#112548).
+ The frame is never written; nothing is left open for a reconnect replay."""
+ from tui_gateway import server_requests
+
+ peer = _silent_ws()
+ _ws_session(server, "ws-old", peer)
+ t0 = time.monotonic()
+ assert server_requests.send("clarify", "ws-old", {"question": "q?", "choices": None, "multi_select": False},
+ timeout=5) is None
+ assert time.monotonic() - t0 < 1
+ assert peer.frames == []
+ assert server_requests.open_requests("ws-old") == []
+ settled = []
+ server_requests.send_async("approval", "ws-old", {"request_id": "r1", "command": "rm", "description": "",
+ "pattern_key": "", "pattern_keys": []}, settled.append)
+ assert settled == [None]
+
+
+def test_server_request_waits_for_a_ws_client_that_advertised(server):
+ """``client.capabilities {server_requests: true}`` on the connection marks it answerable: the frame is
+ written and the wait is a real one (here: answered by the response frame)."""
from tui_gateway import server_requests
+ from tui_gateway.transport import bind_transport, reset_transport
+
+ peer = _silent_ws()
+ _ws_session(server, "ws-new", peer)
+ token = bind_transport(peer)
+ try:
+ response = server.handle_request({"id": 1, "method": "client.capabilities", "params": {"server_requests": True}})
+ finally:
+ reset_transport(token)
+ assert "clarify" in response["result"]["server_requests"]
box = {}
- thread = threading.Thread(
- target=lambda: box.setdefault("result", server_requests.send("sudo", "s1", {}, timeout=5)),
- daemon=True,
- )
+ thread = threading.Thread(target=lambda: box.setdefault("r", server_requests.send("sudo", "ws-new", {}, timeout=5)),
+ daemon=True)
thread.start()
req = _wait_open(server_requests)
- assert server_requests.resolve_response({"id": req.id, "error": {"code": -32601}})
- thread.join(timeout=1)
- assert not thread.is_alive()
- assert box["result"] is None
+ assert peer.frames[-1]["id"] == req.id
+ assert server.dispatch({"jsonrpc": "2.0", "id": req.id, "result": {"value": "yes"}}) is None
+ thread.join(timeout=5)
+ assert box["r"] == {"value": "yes"}
+ # Disconnect forgets the advertisement; the next connection must advertise again.
+ server.unregister_live_transport(peer)
+ assert server_requests.answers_requests(peer) is False
@pytest.mark.parametrize("method", ["secret", "sudo", "terminal.read", "tour"])
diff --git a/tools/approval_gateway_wait.py b/tools/approval_gateway_wait.py
index f433713229e..d7d55801d3c 100644
--- a/tools/approval_gateway_wait.py
+++ b/tools/approval_gateway_wait.py
@@ -166,8 +166,14 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,
register_prepared_approval(session_key, entry)
_approval._gateway_queues.setdefault(session_key, []).append(entry)
- def _drop_entry(reason: str) -> None:
+ def _drop_entry(state: str) -> str | None:
+ """Leave the queue and return the choice committed so far. Reading ``entry.result`` and
+ removing the entry are one critical section under the approval lock: ``resolve_gateway_approval``
+ commits under the same lock, so a choice that landed after the deadline check but before this
+ removal is still ours to honour, and one arriving later finds no entry (the client is told
+ nothing was pending instead of being acked "ok" while the agent denies)."""
with _approval._lock:
+ choice = entry.result
queue = _approval._gateway_queues.get(session_key, [])
if entry in queue:
queue.remove(entry)
@@ -176,9 +182,10 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,
settle, entry.settle = entry.settle, None
if settle is not None:
try:
- settle(reason)
+ settle("answered" if choice is not None and state != "interrupted" else state)
except Exception:
logger.debug("approval settle hook failed", exc_info=True)
+ return choice
# Plugins hear about the request before the gateway does (real-time observers).
_ctx._fire_approval_hook("pre_approval_request", **payload)
@@ -195,12 +202,16 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,
state = _poll_event(entry.event, session_key,
interrupt_log="Approval wait interrupted — returning deny for session %s")
cancelled = _cancel_cause(state, entry)
- choice = entry.result
if state == "interrupted":
- # Our own decision stays a fail-closed deny; coalesced followers wake with the
- # cause instead of a deny nobody issued.
- choice, entry.cancelled = "deny", cancelled
+ # Coalesced followers wake with the cause instead of a deny nobody issued.
+ entry.cancelled = cancelled
entry.event.set()
- _drop_entry("answered" if state == "set" else state)
+ choice = _drop_entry(state)
+ if state == "interrupted":
+ # Our own decision stays a fail-closed deny.
+ choice = "deny"
+ # A choice that landed in the gap between the deadline check and leaving the queue is an answer,
+ # not a timeout (#112548) — the same first-settlement rule as server_requests.send().
+ resolved = state != "timeout" or choice is not None
extra = {"cancelled": cancelled} if cancelled else {}
- return _finish(payload, state != "timeout", choice, entry.reason, **extra)
+ return _finish(payload, resolved, choice, entry.reason, **extra)
diff --git a/tui_gateway/AGENTS.md b/tui_gateway/AGENTS.md
index c11c14be742..221144206a2 100644
--- a/tui_gateway/AGENTS.md
+++ b/tui_gateway/AGENTS.md
@@ -26,7 +26,10 @@ is the facade with the method/event catalog; methods live in `methods_*.py` sibl
`event_publisher.py` / `event_replay.py`, server→client requests in `server_requests.py` (`send()` blocks
the agent thread until the response frame with the same `srq-<n>` id arrives; `cancel*` withdraws with a
`request.cancel` event; `open_requests(sid)` is what `session.resume` / `session.events.since` replay so a
-reconnecting client re-renders the still-open questions). Desktop reaches the same server over WebSocket
+reconnecting client re-renders the still-open questions). A client says once per connection that it
+answers them (`client.capabilities {server_requests: true}`, sent by the shared channel on `gateway.ready`);
+a WebSocket client that never did is an app build older than server→client requests, and `send()` fails
+fast for it instead of stalling the agent for the deadline. Desktop reaches the same server over WebSocket
via `apps/shared` (`JsonRpcGatewayClient`, `onRequest`). New RPC = a new `methods_<topic>.py` or an entry
in an existing topical sibling, registered in the table — no `if method == ...` chain (root shape rules).
diff --git a/tui_gateway/contracts/liveness.py b/tui_gateway/contracts/liveness.py
index f9e3c7cbe7b..a449a30c25a 100644
--- a/tui_gateway/contracts/liveness.py
+++ b/tui_gateway/contracts/liveness.py
@@ -24,3 +24,20 @@ class GatewayCapabilitiesResult(Result):
method("gateway.capabilities", params=PingParams, result=GatewayCapabilitiesResult,
doc="What THIS build enforces (a client withholds a feature unless advertised).")
+
+
+class ClientCapabilitiesParams(Params):
+ #: The client answers server→client requests (clarify, approval, sudo, …) — with a result or a -32601
+ #: error for methods it has no handler for. A WebSocket client that never says so is treated as a
+ #: build older than server→client requests and every such request fails fast for it.
+ server_requests: bool = False
+
+
+class ClientCapabilitiesResult(Result):
+ #: Server→client request methods this backend may send.
+ server_requests: list[str]
+
+
+method("client.capabilities", params=ClientCapabilitiesParams, result=ClientCapabilitiesResult,
+ doc="What the calling client handles, sent once per connection (after gateway.ready); returns the "
+ "server→client request methods this backend may send.")
diff --git a/tui_gateway/methods_voice.py b/tui_gateway/methods_voice.py
index d13a6c3c858..8bac5d5b2e0 100644
--- a/tui_gateway/methods_voice.py
+++ b/tui_gateway/methods_voice.py
@@ -439,6 +439,17 @@ def _(rid, params: dict) -> dict:
return _ok(rid, {"per_session_exclusive_submit": bool(PER_SESSION_EXCLUSIVE_SUBMIT)})
+@method("client.capabilities")
+def _(rid, params: dict) -> dict:
+ """What the calling client handles. ``server_requests: true`` marks this connection as one that answers
+ server→client requests; a WebSocket client that never sends it gets every such request failed fast
+ instead of stalling the agent for the deadline (#112548)."""
+ from tui_gateway import server_requests
+ from tui_gateway.contracts import registry as contracts
+ server_requests.advertise(_caller_transport(), bool(params.get("server_requests")))
+ return _ok(rid, {"server_requests": sorted(contracts.SERVER_REQUESTS)})
+
+
@method("ping")
def _(rid, params: dict) -> dict:
"""Cheapest liveness probe, answered on the WS reader thread (works while every agent is mid-turn)
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index dadbbd85925..59313a47743 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -640,7 +640,8 @@ def _emit(event: str, sid: str, payload: dict | None = None) -> bool:
from tui_gateway import server_requests as _server_requests # noqa: E402
-_server_requests.bind_sinks(lambda frame: write_json(frame), lambda event, sid, payload: _emit(event, sid, payload))
+_server_requests.bind_sinks(lambda frame: write_json(frame), lambda event, sid, payload: _emit(event, sid, payload),
+ lambda sid: _session_client_answers_requests(sid))
# Live WS peer transports (maintained by tui_gateway.ws): the only route for session-less background
@@ -660,6 +661,7 @@ def unregister_live_transport(transport: Transport | None) -> None:
"""Stop tracking a transport (call on disconnect). Idempotent."""
with _live_transports_lock:
_live_transports.discard(transport)
+ _server_requests.forget(transport)
def _broadcast_global_event(event: str, payload: dict | None = None) -> None:
diff --git a/tui_gateway/server_requests.py b/tui_gateway/server_requests.py
index 7a9ae4b6edb..5aaa044fe22 100644
--- a/tui_gateway/server_requests.py
+++ b/tui_gateway/server_requests.py
@@ -20,6 +20,12 @@ has to carry "a question still waiting for an answer".
Batch clarify keeps per-question locks (``clarify.lock`` → :func:`lock_answer`): answers stay
editable until every question is locked, locked answers survive a timeout, and the last lock
resolves the request with the full answer set.
+
+Capability: a client says once per connection that it answers server→client requests
+(``client.capabilities {server_requests: true}`` → :func:`advertise`). A WebSocket client that never
+did is a build older than this half of the protocol — it drops the frame silently and the agent
+would wait the full deadline (clarify's 300s) for nothing — so :func:`send` / :func:`send_async`
+return the same ``None`` an error response produces without writing the frame (#112548).
"""
from __future__ import annotations
@@ -73,11 +79,47 @@ _open: dict[str, ServerRequest] = {}
# fixtures that patch ``sys.modules`` around the server import.
_write: Callable[[dict], Any] = lambda frame: None # noqa: E731
_emit: Callable[[str, str, dict], Any] = lambda event, sid, payload: None # noqa: E731
+# ``answerable(sid)``: False only when every client attached to the session is a build that never
+# advertised handling server→client requests (session_transports.py::_session_client_answers_requests).
+_answerable: Callable[[str], bool] = lambda sid: True # noqa: E731
+
+# Client transports that sent ``client.capabilities {server_requests: true}`` (identity set: StdioTransport
+# has __slots__ and cannot be weak-referenced; ws.py forgets a peer on disconnect).
+_answering_clients: set = set()
+
+
+def bind_sinks(write_json: Callable[[dict], Any], emit: Callable[[str, str, dict], Any],
+ answerable: Callable[[str], bool]) -> None:
+ global _write, _emit, _answerable
+ _write, _emit, _answerable = write_json, emit, answerable
+
+
+def advertise(transport: Any, server_requests: bool) -> None:
+ """Record whether *transport*'s client answers server→client requests (``client.capabilities``)."""
+ with _lock:
+ if server_requests:
+ _answering_clients.add(transport)
+ else:
+ _answering_clients.discard(transport)
-def bind_sinks(write_json: Callable[[dict], Any], emit: Callable[[str, str, dict], Any]) -> None:
- global _write, _emit
- _write, _emit = write_json, emit
+def forget(transport: Any) -> None:
+ """Drop a disconnected transport's advertisement."""
+ with _lock:
+ _answering_clients.discard(transport)
+
+
+def answers_requests(transport: Any) -> bool:
+ with _lock:
+ return transport in _answering_clients
+
+
+def _unanswerable(method: str, sid: str) -> bool:
+ if _answerable(sid):
+ return False
+ logger.info("server request %s for %s not sent: the attached client predates server→client requests "
+ "(update the Hermes app)", method, sid)
+ return True
def _emit_cancel(req: ServerRequest, reason: str) -> None:
@@ -107,6 +149,8 @@ def send(method: str, sid: str, params: dict, *, timeout: float | None,
cancelled, 0 → return immediately, > 0 → bounded wait. A batch (``qids``) that times out
returns ``{"answers": <locked so far>, "timed_out": True}`` instead of None.
"""
+ if _unanswerable(method, sid):
+ return None
req = ServerRequest(sid, method, params, qids=qids)
_register(req)
try:
@@ -139,6 +183,9 @@ def send_async(method: str, sid: str, params: dict, on_result: Callable[[dict |
"""Send one request whose wait is owned elsewhere (the approval queue's own timeout). ``on_result``
runs on the dispatching thread when the response lands. Returns ``settle(reason)``: call it when
the underlying wait ends; if the request is still open it is withdrawn with ``request.cancel``."""
+ if _unanswerable(method, sid):
+ on_result(None)
+ return lambda reason: None
req = ServerRequest(sid, method, params, on_result=on_result)
_register(req)
@@ -255,3 +302,4 @@ def is_response_frame(obj: Any) -> bool:
def reset_for_tests() -> None:
with _lock:
_open.clear()
+ _answering_clients.clear()
diff --git a/tui_gateway/session_transports.py b/tui_gateway/session_transports.py
index 07d5ecfe3ad..383e16e9eaf 100644
--- a/tui_gateway/session_transports.py
+++ b/tui_gateway/session_transports.py
@@ -35,6 +35,18 @@ def _session_has_live_transport(session: dict | None, *, excluding=None) -> bool
return any(peer is not excluding for peer in _session_live_transports(session))
+def _session_client_answers_requests(sid: str) -> bool:
+ """Whether a server→client request for *sid* can be answered: False only when every live WebSocket
+ client attached to the session is a build that never sent ``client.capabilities`` (Desktop / dashboard
+ update separately from this backend; the stdio TUI ships with it). No attached client is still True — the
+ question waits in ``open_requests`` for the reconnect replay. Compute-host relays and other non-client
+ transports never count."""
+ from tui_gateway import server_requests
+ from tui_gateway.ws import WSTransport
+ clients = [peer for peer in _session_live_transports(_sessions.get(sid)) if isinstance(peer, WSTransport)]
+ return not clients or any(server_requests.answers_requests(peer) for peer in clients)
+
+
def _warn_foreign_login(session: dict, transport) -> None:
"""Ownership is not enforced; a second login sharing a session is only logged, and the agent keeps the
creator's user id."""
diff --git a/website/docs/developer-guide/programmatic-integration.md b/website/docs/developer-guide/programmatic-integration.md
index 1444270e205..351dba363bb 100644
--- a/website/docs/developer-guide/programmatic-integration.md
+++ b/website/docs/developer-guide/programmatic-integration.md
@@ -47,6 +47,7 @@ session.activate session.close session.interrupt
session.history session.compress session.branch
session.title session.usage session.status
clarify.lock config.set / config.get commands.catalog
+client.capabilities gateway.capabilities ping
command.resolve command.dispatch cli.exec
reload.mcp reload.env process.stop
delegation.status subagent.interrupt subagent.steer
@@ -88,6 +89,8 @@ Approvals, clarify questions, sudo/secret prompts, vault unlock, MCP setup and t
Methods: `approval` → `{choice}`; `clarify` → `{answer}` (single) or `{answers}` / `{}` cancel (batch, with `clarify.lock` to lock one answer early); `sudo`, `secret`, `vault.code`, `vault.unlock_prompt` → `{value}`; `connection` → `{settled_by, targets}` (the `manage_connections` card: one outcome per target); `terminal.read`, `window.read`, `preview.act`, `tour` → `{value}` (JSON text). Respond with a JSON-RPC error (`-32601`) for a method your host does not implement so the agent fails fast instead of waiting out the timeout.
+**Advertise that you answer them.** Once per connection, after `gateway.ready`, call `client.capabilities` with `{"server_requests": true}`; the result lists the request methods this backend may send. A WebSocket client that never does is treated as a build that predates server→client requests: the gateway fails every such request for it immediately (the agent sees the same "no answer" an error response produces) instead of stalling for the full deadline. A session with no client attached is not affected — its open questions wait in `open_requests` for the reconnect replay. The stdio TUI, the desktop app and the dashboard advertise through the shared `JsonRpcRequestChannel`.
+
When the gateway withdraws a question (timeout, interrupt, answered from another surface) it emits `request.cancel` `{ id, method, reason }`; clear only the matching prompt. `session.resume` / `session.activate` results and `session.events.since` carry `open_requests` — the still-open frames — so a reconnecting client re-renders (and can still answer) them.
### Rebuilding the in-flight turn on reconnect