The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a batch clarify keeps its locked answers on timeout, interrupt and cancel
Teknium833f11d752c5
diff --git a/gateway/session_clarify_batch.py b/gateway/session_clarify_batch.pyindex 16afdeda66a..abd48e475f5 100644--- a/gateway/session_clarify_batch.py+++ b/gateway/session_clarify_batch.py@@ -36,5 +36,7 @@ def ask_clarify_batch(turn, questions) -> dict:return {"answers": {}, "outcome": "cancelled"}known = {entry["qid"] for entry in questions}clean = {qid: (value if isinstance(value, str) else None) for qid, value in answers.items() if qid in known}- outcome = result.get("outcome") if result.get("outcome") in ("submitted", "timed_out", "cancelled") else "submitted"+ # ``session_sudo_prompt`` settles a batch with its terminal outcome (an absent outcome on a frame+ # that carried answers is ``submitted``; a cancel-all or error is ``cancelled``).+ outcome = result.get("outcome") if result.get("outcome") in ("submitted", "timed_out", "cancelled") else "cancelled"return {"answers": clean, "outcome": outcome}diff --git a/gateway/session_sudo_prompt.py b/gateway/session_sudo_prompt.pyindex e50aaaebc4f..304458932ad 100644--- a/gateway/session_sudo_prompt.py+++ b/gateway/session_sudo_prompt.py@@ -36,6 +36,7 @@ class _Pending:_lock = threading.Lock()_open: dict[str, _Pending] = {}+_OUTCOMES = ("submitted", "timed_out", "cancelled")def is_response_frame(frame) -> bool:@@ -44,6 +45,20 @@ def is_response_frame(frame) -> bool:and frame["id"].startswith("srq-") and ("result" in frame or "error" in frame))+def _settle_batch(locked, result):+ """A batch clarify's terminal result: answers locked early belong to the final set whatever ends+ the wait, as main's ``server_requests`` merged them. A closing frame with an ``answers`` dict lays+ its answers over the locks (the frame wins per question) and keeps its own outcome (``submitted``+ when it names none); a frame without one (Ink Esc, Desktop Skip) or an error is a cancel-all."""+ if isinstance(result, dict) and isinstance(result.get("answers"), dict):+ outcome = result.get("outcome")+ if outcome not in _OUTCOMES:+ outcome = "submitted"+ return {**result, "answers": {**locked, **result["answers"]}, "outcome": outcome}+ outcome = result.get("outcome") if isinstance(result, dict) else None+ return {"answers": locked, "outcome": outcome if outcome in ("timed_out", "cancelled") else "cancelled"}++def resolve(frame, *, session_ok=lambda session_id: True) -> bool:"""Settle the open request *frame* answers; False when nothing (here) waits for that id.``session_ok`` lets the caller refuse an answer from a connection not entitled to that session."""@@ -52,12 +67,10 @@ def resolve(frame, *, session_ok=lambda session_id: True) -> bool:if pending is None or not session_ok(pending.session_id):return False_open.pop(frame["id"], None)+ locked = dict(pending.locked) if pending.qids is not None else Noneresult = frame.get("result") if "error" not in frame else None- if pending.qids is not None and pending.locked and isinstance(result, dict):- # Answers locked early belong to the final set even when the closing frame omits them- # (a cancel after two locks keeps those two), as main's ``server_requests`` merged them.- answers = result.get("answers") if isinstance(result.get("answers"), dict) else {}- result = {**result, "answers": {**pending.locked, **answers}}+ if locked is not None:+ result = _settle_batch(locked, result)value = result.get("value") if isinstance(result, dict) else ""pending.value = value if isinstance(value, str) else ""pending.result = result if isinstance(result, dict) else None@@ -82,7 +95,8 @@ def ask_viewer_result(events, session_id, method, params, *, cancelled=lambda: Fqids=None):"""The same round trip for a structured answer (``clarify``: ``ClarifyResult``): the viewer's``result`` dict, or None on interrupt, timeout, an error response or no attached viewer.- ``qids`` makes it a batch: ``lock_answer`` (the ``clarify.lock`` verb) answers it per question."""+ ``qids`` makes it a batch, which always ends with ``{answers: <locked so far>, outcome}`` once+ asked: ``lock_answer`` (the ``clarify.lock`` verb) answers it per question."""pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout, qids=qids)return pending.result if pending is not None else None@@ -128,13 +142,18 @@ def _ask(events, session_id, method, params, *, cancelled, timeout, qids=None):breakwith _lock:still_open = _open.pop(request_id, None) is pending+ if still_open and pending.qids is not None:+ # A batch keeps every answer locked before the wait ended (main's sidecar: "locked+ # answers survive a timeout"); sudo/secret have no question ids and stay unanswered.+ pending.result = {"answers": dict(pending.locked),+ "outcome": "cancelled" if reason == "interrupted" else "timed_out"}if still_open:# The same teardown main's renderers key on (``request.cancel``): the card closes and a# timed-out password prompt says so.with contextlib.suppress(Exception):events.publish(session_id, {"id": request_id, "method": method, "reason": reason},event_type="request.cancel")- return None+ return pending if pending.qids is not None else Nonereturn pendingdiff --git a/tests/gateway/test_clarify_lock_keeps_locked_answers.py b/tests/gateway/test_clarify_lock_keeps_locked_answers.pynew file mode 100644index 00000000000..38c0dd9ed22--- /dev/null+++ b/tests/gateway/test_clarify_lock_keeps_locked_answers.py@@ -0,0 +1,83 @@+"""A batch answer already locked with ``clarify.lock`` survives every way the wait can end, as on main's+sidecar (``tui_gateway/server_requests.py``: "locked answers survive a timeout"): a timeout returns+``{answers: <locked so far>, outcome: timed_out}``, an interrupt returns them with ``cancelled``, and a+cancel-all closing frame (Ink Esc / Desktop Skip: no ``answers``) keeps them and reports ``cancelled``,+never ``submitted``. Driven through the real dispatcher against a real ``ask_clarify_batch`` wait.+"""+import asyncio++import pytest++from tests.gateway.test_clarify_lock_owner import _lock, _start_batch, _wait_for+from tests.gateway.test_surface_admission import _authority+++async def _locked_then(tmp_path, monkeypatch, end):+ from gateway.session_controls import AuthorityConnection++ async def answer(event):+ return 'ok'+ authority = await _authority(tmp_path, monkeypatch, answer)+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})+ try:+ await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})+ peer, worker, out = _start_batch(authority)+ await _wait_for(lambda: any(f.get('method') == 'clarify' for f in peer.frames))+ rid = next(f['id'] for f in peer.frames if f.get('method') == 'clarify')+ assert (await _lock(connection, rid, 'q0', 'blue', 2))['result'] == {'status': 'ok', 'remaining': ['q1']}+ end(connection, rid, worker)+ await asyncio.to_thread(worker.join, 10)+ assert not worker.is_alive()+ return out, peer+ finally:+ await connection.close()+++def _frame_of(worker):+ import sys+ frame = sys._current_frames()[worker.ident]+ while frame is not None and 'turn' not in frame.f_locals:+ frame = frame.f_back+ return frame.f_locals['turn']+++async def test_a_timeout_keeps_the_answer_already_locked(tmp_path, monkeypatch):+ from tools import clarify_gateway+ monkeypatch.setattr(clarify_gateway, 'get_clarify_timeout', lambda: 1)+ out, peer = await _locked_then(tmp_path, monkeypatch, lambda *a: None)+ assert out == {'answers': {'q0': 'blue'}, 'outcome': 'timed_out'}, out+ # The open cards still close.+ assert any(f.get('params', {}).get('type') == 'request.cancel' for f in peer.frames)+++async def test_an_interrupt_keeps_the_answer_already_locked(tmp_path, monkeypatch):+ def interrupt(connection, rid, worker):+ _frame_of(worker)._ctx.agent_holder[0]._interrupt_requested = True+ out, _peer = await _locked_then(tmp_path, monkeypatch, interrupt)+ assert out == {'answers': {'q0': 'blue'}, 'outcome': 'cancelled'}, out+++async def test_a_cancel_all_after_a_lock_keeps_the_answer_and_reports_cancelled(tmp_path, monkeypatch):+ def skip(connection, rid, worker):+ connection._resolve_response({'jsonrpc': '2.0', 'id': rid, 'result': {}})+ out, _peer = await _locked_then(tmp_path, monkeypatch, skip)+ assert out == {'answers': {'q0': 'blue'}, 'outcome': 'cancelled'}, out+++async def test_a_partial_closing_frame_after_a_lock_is_submitted_with_both(tmp_path, monkeypatch):+ def submit_tail(connection, rid, worker):+ connection._resolve_response({'jsonrpc': '2.0', 'id': rid, 'result': {'answers': {'q1': 'large'}}})+ out, _peer = await _locked_then(tmp_path, monkeypatch, submit_tail)+ assert out == {'answers': {'q0': 'blue', 'q1': 'large'}, 'outcome': 'submitted'}, out+++async def test_an_error_frame_after_a_lock_keeps_the_answer(tmp_path, monkeypatch):+ def fail(connection, rid, worker):+ connection._resolve_response({'jsonrpc': '2.0', 'id': rid, 'error': {'code': -32603, 'message': 'x'}})+ out, _peer = await _locked_then(tmp_path, monkeypatch, fail)+ assert out == {'answers': {'q0': 'blue'}, 'outcome': 'cancelled'}, out