Skip to content

The agent that grows with you

fix(tui_gateway): make server request settlement atomic

KoNit-K434c57554341
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index 601872d5dd3..8074cbd9dc1 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -313,6 +313,53 @@ def test_server_request_round_trip_uses_response_frame(capture):
assert not server_requests._open
+def test_response_settlement_wins_over_a_later_cancel(capture):
+ """A response and cancellation may race; the first settlement owns the result."""
+ from tui_gateway import server_requests
+
+ req = server_requests.ServerRequest("s1", "sudo", {})
+ with server_requests._lock:
+ server_requests._open[req.id] = req
+
+ assert server_requests.resolve_response({"id": req.id, "result": {"value": "yes"}})
+ assert server_requests.cancel("s1") == 0
+ assert req.answered is True
+ assert req.result == {"value": "yes"}
+ assert req.event.is_set()
+
+
+def test_final_clarify_lock_settlement_wins_over_a_later_cancel(capture):
+ """Batch clarify's lock-based resolution follows the same first-settlement rule."""
+ from tui_gateway import server_requests
+
+ req = server_requests.ServerRequest("s1", "clarify", {}, qids=["q1"])
+ with server_requests._lock:
+ server_requests._open[req.id] = req
+
+ assert server_requests.lock_answer(req.id, "q1", "yes") == []
+ assert server_requests.cancel("s1") == 0
+ assert req.answered is True
+ assert req.result == {"answers": {"q1": "yes"}}
+ assert req.event.is_set()
+
+
+def test_server_request_error_response_fails_fast(capture):
+ """A shared-channel client without a handler answers -32601 instead of waiting for the deadline."""
+ from tui_gateway import server_requests
+
+ box = {}
+ thread = threading.Thread(
+ target=lambda: box.setdefault("result", server_requests.send("sudo", "s1", {}, 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
+
+
@pytest.mark.parametrize("method", ["secret", "sudo", "terminal.read", "tour"])
def test_server_request_timeout_emits_one_request_cancel(capture, method):
from tui_gateway import server_requests
diff --git a/tui_gateway/server_requests.py b/tui_gateway/server_requests.py
index 99c38450ba8..2cd6cfd11c6 100644
--- a/tui_gateway/server_requests.py
+++ b/tui_gateway/server_requests.py
@@ -149,23 +149,25 @@ def resolve_response(frame: dict) -> bool:
req = _open.get(rid)
if req is None:
return False
- if req.on_result is not None:
- _open.pop(rid, None)
- if "error" in frame:
- logger.debug("server request %s (%s) answered with error: %s", rid, req.method, frame.get("error"))
- req.result, req.answered = None, False
- else:
- result = frame.get("result")
- req.result = result if isinstance(result, dict) else {}
- if req.qids and "answers" in req.result:
- # Batch clarify: answers locked early via clarify.lock belong to the final set even when
- # the closing response only carries the tail the user answered last.
- answers = req.result.get("answers")
- merged = dict(req.locked)
- if isinstance(answers, dict):
- merged.update(answers)
- req.result = {**req.result, "answers": merged}
- req.answered = True
+ # Removing the request and committing its outcome are one settlement.
+ # ``cancel()`` also settles under this lock, so the first side to get
+ # here wins instead of a later cancellation overwriting a response.
+ _open.pop(rid, None)
+ if "error" in frame:
+ logger.debug("server request %s (%s) answered with error: %s", rid, req.method, frame.get("error"))
+ req.result, req.answered = None, False
+ else:
+ result = frame.get("result")
+ req.result = result if isinstance(result, dict) else {}
+ if req.qids and "answers" in req.result:
+ # Batch clarify: answers locked early via clarify.lock belong to the final set even when
+ # the closing response only carries the tail the user answered last.
+ answers = req.result.get("answers")
+ merged = dict(req.locked)
+ if isinstance(answers, dict):
+ merged.update(answers)
+ req.result = {**req.result, "answers": merged}
+ req.answered = True
if req.on_result is not None:
req.on_result(req.result)
req.event.set()
@@ -186,6 +188,7 @@ def lock_answer(request_id: str, question_id: str, answer: str) -> list[str] | N
remaining = [qid for qid in req.qids if qid not in req.locked]
if not remaining:
req.result, req.answered = {"answers": dict(req.locked)}, True
+ _open.pop(request_id, None)
if not remaining:
req.event.set()
return remaining
@@ -199,8 +202,8 @@ def cancel(sid: str | None = None, reason: str = "interrupted") -> int:
targets = [req for req in _open.values() if sid is None or req.sid == sid]
for req in targets:
_open.pop(req.id, None)
+ req.result, req.answered = None, False
for req in targets:
- req.result, req.answered = None, False
if req.on_result is not None:
req.on_result(None)
req.event.set()
diff --git a/website/docs/developer-guide/programmatic-integration.md b/website/docs/developer-guide/programmatic-integration.md
index c69beea972a..1444270e205 100644
--- a/website/docs/developer-guide/programmatic-integration.md
+++ b/website/docs/developer-guide/programmatic-integration.md
@@ -86,7 +86,7 @@ Approvals, clarify questions, sudo/secret prompts, vault unlock, MCP setup and t
→ {"jsonrpc":"2.0","id":"srq-7","result":{"choice":"once"}}
```
-Methods: `approval` → `{choice}`; `clarify` → `{answer}` (single) or `{answers}` / `{}` cancel (batch, with `clarify.lock` to lock one answer early); `sudo`, `secret`, `vault.code`, `vault.unlock` → `{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.
+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.
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.