The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): replay an already-pending approval to an exact streaming retry
Tekniumfcff21c301e6
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex 52b0b4e5a27..791df0b94c1 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -337,9 +337,17 @@ _CONTROL_EVENTS = frozenset({'approval.request', 'approval.settled', 'clarify.re@contextmanagerdef observe_api_controls(admitted, sink):"""Project the same approval/clarify prompts WS viewers receive to ``sink(type, payload)``- for the admission's lifetime; ``sink`` runs on the publishing thread under the stream lock."""+ for the admission's lifetime; ``sink`` runs under the stream lock.++ An exact retry joins an admission whose prompt may already be pending: it was published+ before this observer existed, so it is replayed from the shared pending controls (the+ source ``GET /v1/runs/{id}`` reports). Subscribing and snapshotting in ONE stream-lock hold+ is the consistent cut: prompts are registered and answered under that lock, so each one is+ either in the snapshot or arrives live (never both), and one already answered is absent."""+ from hermes_state_runtime import get_session_admissionauthority, ref, row = admitted- events = authority.sessions[ref.session_id].event_stream+ live = authority.sessions[ref.session_id]+ events = live.event_streamdef observer(frame):params = frame['params']@@ -347,6 +355,10 @@ def observe_api_controls(admitted, sink):sink(params['type'], params.get('payload') or {})with events.lock:events.observers.add(observer)+ current = get_session_admission(authority.db, admission_id=row['admission_id']) or row+ if current['status'] == 'started':+ for prompt in live.controls.snapshot(ref.session_id, current['generation']):+ sink(prompt['kind'] + '.request', prompt)try:yieldfinally:diff --git a/tests/gateway/test_chat_completions_approval.py b/tests/gateway/test_chat_completions_approval.pyindex c261c2e2443..ca165bf5f65 100644--- a/tests/gateway/test_chat_completions_approval.py+++ b/tests/gateway/test_chat_completions_approval.py@@ -123,3 +123,43 @@ async def test_canonical_streamed_approval_reaches_sse_and_resolves_via_runs_endassert (await approval.json())["status"] == "resolved"await asyncio.wait_for(resp.text(), 10)assert decisions and decisions[0]["choice"] == "once"+++async def test_exact_streamed_retry_replays_the_already_pending_approval(api, owner, monkeypatch):+ """A client that disconnects while an approval is pending and retries the unchanged request+ (same session, Idempotency-Key, auth scope) reuses the admission under a new completion id.+ The prompt was published before the retry subscribed, so the retry stream must replay it from+ the authority's pending controls, or an SSE-only client waits on a prompt it never sees."""+ monkeypatch.setattr("tools.approval_context._get_approval_timeout", lambda: 15)+ decisions = []+ owner.runner._handle_message = _canonical_approval_turn(owner, decisions)+ api._api_key = "pending-retry-key-long-enough"+ headers = {"Authorization": "Bearer " + api._api_key, "X-Hermes-Session-Id": "retry-sse",+ "Idempotency-Key": "retry-once"}+ body = {"model": "hermes-agent", "stream": True, "messages": [{"role": "user", "content": "hi"}]}+ app = _create_app(api)+ app.router.add_post("/v1/runs/{run_id}/approval", api._handle_run_approval)+ async with TestClient(TestServer(app)) as cli:+ first = await cli.post("/v1/chat/completions", json=body, headers=headers)+ assert first.status == 200, await first.text()+ original = await asyncio.wait_for(_sse_event(first, "approval.request"), 10)+ assert original, "first stream never saw the approval"+ first.close() # disconnect while the prompt is still pending+ retry = await cli.post("/v1/chat/completions", json=body, headers=headers)+ assert retry.status == 200, await retry.text()+ replayed = await asyncio.wait_for(_sse_event(retry, "approval.request"), 5)+ assert replayed["request_id"] == original["request_id"]+ assert replayed["execution_generation"] == original["execution_generation"]+ assert replayed["run_id"].startswith("chatcmpl") and replayed["run_id"] != original["run_id"]+ approval = await cli.post(f"/v1/runs/{replayed['run_id']}/approval", json={+ "request_id": replayed["request_id"], "execution_generation": replayed["execution_generation"],+ "choice": "once"}, headers={"Authorization": headers["Authorization"]})+ assert approval.status == 200, await approval.text()+ assert (await approval.json())["status"] == "resolved"+ text = await asyncio.wait_for(retry.text(), 10)+ assert "[DONE]" in text and text.count("event: approval.request") == 0 # replayed exactly once+ assert [d["choice"] for d in decisions] == ["once"]+ with owner.db._read_ctx() as conn:+ rows = conn.execute("SELECT status FROM session_admissions WHERE principal_id='api'").fetchall()+ assert [r[0] for r in rows] == ["terminal"]