The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(tui,desktop): approval and clarify cards wait until answered
Brooklyn Nicholsonbd501669cebe
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.pyindex 4fa93070e22..0b575999a98 100644--- a/tests/tui_gateway/test_protocol.py+++ b/tests/tui_gateway/test_protocol.py@@ -507,14 +507,19 @@ def test_late_response_and_lock_are_dropped_quietly(server):def _start_batch_clarify(server, buf, qids, timeout=None):+ """Open a batch ``clarify`` request: through ``_clarify_block`` (no deadline) by default, or straight+ through ``server_requests.send`` with *timeout* to exercise the generic batch-deadline semantics."""from tui_gateway import server_requestsbox = {}normalized = [{"qid": q, "id": "", "question": q, "choices": None, "choices_offered": [], "multi_select": False}for q in qids]- if timeout is not None:- server._clarify_timeout_seconds = lambda: timeout- thread = threading.Thread(- target=lambda: box.__setitem__("answer", server._clarify_block("s1", normalized)), daemon=True)+ if timeout is None:+ target = lambda: box.__setitem__("answer", server._clarify_block("s1", normalized)) # noqa: E731+ else:+ wire = [{"qid": q, "question": q, "choices": None, "multi_select": False} for q in qids]+ target = lambda: box.__setitem__("answer", server_requests.send( # noqa: E731+ "clarify", "s1", {"questions": wire}, timeout=timeout, qids=list(qids)))+ thread = threading.Thread(target=target, daemon=True)thread.start()return thread, box, _wait_open(server_requests, buf)@@ -543,16 +548,12 @@ def test_clarify_batch_locks_resolve_in_order_and_keep_partial_on_timeout(capturthread.join(timeout=5)assert box["answer"] == {"answers": {"q0": "y", "q1": ""}, "outcome": "submitted"}- # Deadline: locked answers survive, outcome timed_out, one request.cancel.- original_timeout = server._clarify_timeout_seconds- try:- thread, box, req = _start_batch_clarify(server, buf, ["q0", "q1"], timeout=1.5)- locked = server.handle_request({"id": "b1", "method": "clarify.lock",- "params": {"request_id": req.id, "question_id": "q0", "answer": "kept"}})- assert locked["result"]["status"] == "ok"- thread.join(timeout=5)- finally:- server._clarify_timeout_seconds = original_timeout+ # Deadline (generic server-request semantics): locked answers survive, outcome timed_out, one request.cancel.+ thread, box, req = _start_batch_clarify(server, buf, ["q0", "q1"], timeout=1.5)+ locked = server.handle_request({"id": "b1", "method": "clarify.lock",+ "params": {"request_id": req.id, "question_id": "q0", "answer": "kept"}})+ assert locked["result"]["status"] == "ok"+ thread.join(timeout=5)assert box["answer"] == {"answers": {"q0": "kept"}, "outcome": "timed_out"}cancels = [f for f in _frames(buf) if f.get("method") == "event" and f["params"]["type"] == "request.cancel"]assert [c["params"]["payload"]["id"] for c in cancels] == [req.id]diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 60dd57adbf4..3715c63d37c 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -11673,13 +11673,18 @@ def test_slash_exec_r7_read_commands_use_metadata_mirror_flag_on(monkeypatch):def test_prompt_submit_sets_approval_session_key(monkeypatch):+ """A TUI/Desktop turn binds its approval session key and holds its prompts open until answered:+ the approval window inside the turn is unbounded even with a short ``approvals.timeout``."""+ from tools import approval_contextfrom tools.approval import get_current_session_keycaptured = {}+ monkeypatch.setattr(approval_context, "_get_approval_config", lambda: {"timeout": 1})class _Agent:def run_conversation(self, prompt, conversation_history=None, stream_callback=None, **_kwargs):captured["session_key"] = get_current_session_key(default="")+ captured["approval_wait"] = approval_context.approval_wait_seconds()return {"final_response": "ok","messages": [{"role": "assistant", "content": "ok"}],@@ -11708,6 +11713,8 @@ def test_prompt_submit_sets_approval_session_key(monkeypatch):assert resp["result"]["status"] == "streaming"assert captured["session_key"] == "session-key"+ assert captured["approval_wait"] > 1+ assert approval_context.approval_wait_seconds() == 1 # unbound again once the turn endsdef test_prompt_submit_expands_context_refs(monkeypatch):@@ -21503,10 +21510,11 @@ def _capture_server_request(monkeypatch, result):return captured-def test_clarify_callback_uses_configured_timeout(monkeypatch):- """The TUI/desktop clarify bridge sends a ``clarify`` server request with the canonical clarify timeout- (via _clarify_timeout_seconds), and returns the response's ``answers`` and ``outcome``."""- monkeypatch.setattr(server, "_clarify_timeout_seconds", lambda: 42)+def test_clarify_callback_waits_until_answered(monkeypatch):+ """The TUI/desktop clarify bridge sends a ``clarify`` server request with no deadline — even when+ ``agent.clarify_timeout`` (the messaging-platform knob) is short — and returns the response's+ ``answers`` and ``outcome``."""+ monkeypatch.setattr("tools.clarify_gateway.get_clarify_timeout", lambda: 1)reply = {"answers": {"q0": "a"}, "outcome": "submitted"}captured = _capture_server_request(monkeypatch, reply)questions = [{"qid": "q0", "question": "Pick one", "choices": ["a", "b"], "multi_select": False}]@@ -21515,23 +21523,11 @@ def test_clarify_callback_uses_configured_timeout(monkeypatch):assert result == replyassert captured["method"] == "clarify" and captured["sid"] == "sid-1"- assert captured["timeout"] == 42+ assert captured["timeout"] is Noneassert captured["params"] == {"questions": questions}assert captured["qids"] == ["q0"]- ("configured", "expected"),- [(0, None), (-1, None), (42, 42)],-)-def test_clarify_timeout_seconds_maps_non_positive_to_unlimited(monkeypatch, configured, expected):- """A ``<= 0`` clarify timeout means unlimited and reaches the server request as None- (wait(None) waits forever) rather than an immediate wait(0) skip."""- monkeypatch.setattr("tools.clarify_gateway.get_clarify_timeout", lambda: configured)-- assert server._clarify_timeout_seconds() == expected--def test_build_persist_message_with_image_refs_without_images_returns_text(monkeypatch):"""#70720: when no images are attached the persisted message is the rawprompt — no @image directive prefix is introduced."""diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.pyindex 9a811ff756a..e55cc66fe90 100644--- a/tui_gateway/prompt_turn.py+++ b/tui_gateway/prompt_turn.py@@ -203,6 +203,7 @@ class _TurnScopes:"""Reset tokens for the thread/context scopes a turn binds (filled incrementally)."""approval: Any = None+ prompts: Any = None # approval/clarify prompts wait until answered (the user is at the app)session_tokens: list = dataclasses.field(default_factory=list)home: Any = None # per-turn HERMES_HOME override for a resumed remote profilesecret: Any = None@@ -661,9 +662,10 @@ def _prepare_turn_input(sid: str, session: dict, st: _TurnRun, text: Any, imagesfail-closed refusal scope). The config-model sync is skipped under a /model --onceoverride (not pinned as model_override, the sync would clobber it); a model pickedmid-turn is applied first so the explicit pick wins over a config change."""- from tools.approval_context import set_current_session_key+ from tools.approval_context import set_current_session_key, set_prompts_wait_for_answerscopes = st.scopesscopes.approval = set_current_session_key(session["session_key"])+ scopes.prompts = set_prompts_wait_for_answer()scopes.session_tokens = _set_session_context(session["session_key"], ui_session_id=sid)# Profile turn: that profile's home + secrets + terminal policy. Launch-profile turn: unscoped in a# single-profile process; once multiplexing is active (#68559 / #107422 residual) its OWN scope,@@ -1061,6 +1063,9 @@ def _finish_turn(sid: str, session: dict, st: _TurnRun) -> None:if scopes.approval is not None:from tools.approval_context import reset_current_session_keyreset_current_session_key(scopes.approval)+ if scopes.prompts is not None:+ from tools.approval_context import reset_prompts_wait_for_answer+ reset_prompts_wait_for_answer(scopes.prompts)if scopes.home is not None:reset_hermes_home_override(scopes.home)if scopes.secret is not None:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex c4c6a75caca..7e4454f978a 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -805,9 +805,9 @@ def _emit_approval_request(sid: str, data: dict | None) -> None:would otherwise echo verbatim to the TUI (third egress alongside chat platforms and the SSE/API stream).See #48456, #50767.- The wait is owned by ``tools.approval``'s queue (its own timeout, ``/approve all``, coalescing), so the request- is queue-backed: the response resolves the queue entry, and the entry's own resolution (any surface, timeout,- interrupt) withdraws the request with ``request.cancel``."""+ The wait is owned by ``tools.approval``'s queue (no deadline on TUI/Desktop turns, ``/approve all``, coalescing),+ so the request is queue-backed: the response resolves the queue entry, and the entry's own resolution (any+ surface, interrupt, session close) withdraws the request with ``request.cancel``."""from tui_gateway import server_requestsfrom tools import approval as _approvalpayload = _approval_request_payload(data)@@ -818,8 +818,8 @@ def _emit_approval_request(sid: str, data: dict | None) -> None:if result is None:# No client can answer this prompt: the request was never sent (the only attached client predates# server→client requests) or the client answered -32601 (no handler). Without withdrawing the- # queue entry the agent would idle for the whole approvals.timeout with no prompt anywhere- # (#112548). A withdrawal, not a deny: nobody refused the command.+ # queue entry the agent would idle on a prompt shown nowhere (#112548). A withdrawal, not a deny:+ # nobody refused the command.if request_id:_approval.withdraw_gateway_approval(session_key, request_id,"the attached client cannot answer approval requests "@@ -1371,24 +1371,16 @@ def _ask(method: str, sid: str, params: dict, timeout: float | None = 300) -> st-def _clarify_timeout_seconds() -> float | None:- """Clarify wait for the TUI/desktop bridge from the canonical config (gateway/CLI parity); 300s- historical default if config can't be read; ``<= 0`` = unlimited → None (never auto-skip)."""- with contextlib.suppress(Exception):- from tools.clarify_gateway import get_clarify_timeout- timeout = get_clarify_timeout()- return timeout if timeout > 0 else None- return 300--def _clarify_block(sid: str, questions: list[dict]) -> dict:"""Bridge the clarify tool callback onto one ``clarify`` server request carrying only the wire fields- (tool-side entries carry result-assembly keys too). Answers lock one at a time through ``clarify.lock``- (``null`` = skipped); the tool gets ``{"answers", "outcome"}`` — ``undelivered`` when no client took it."""+ (tool-side entries carry result-assembly keys too). No deadline: the TUI/Desktop card stays until the+ user answers, the turn is interrupted, or the session closes. Answers lock one at a time through+ ``clarify.lock`` (``null`` = skipped); the tool gets ``{"answers", "outcome"}`` — ``undelivered`` when no+ client took it."""from tui_gateway import server_requestswire = [{"qid": e["qid"], "question": e["question"], "choices": e["choices"], "multi_select": bool(e["multi_select"])}for e in questions]- result = server_requests.send("clarify", sid, {"questions": wire}, timeout=_clarify_timeout_seconds(),+ result = server_requests.send("clarify", sid, {"questions": wire}, timeout=None,qids=[e["qid"] for e in questions])return result or {"answers": {}, "outcome": "undelivered"}