The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): fan out and replay run SSE events
doniocode52a2835136d4
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex c1b3829abeb..4c1cb24b361 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -108,6 +108,37 @@ def _tool_completed_preview(result: Any, redact_sensitive_text: Callable[..., streturn preview if len(preview) <= limit else preview[: limit - 3] + "..."+class _RunStream:+ """Sequence and retain one run's events while fanning out to SSE clients."""++ def __init__(self) -> None:+ self.subscribers: set[asyncio.Queue] = set()+ self.backlog: list[tuple[int, Optional[Dict[str, Any]]]] = []+ self.next_seq = 0+ self.terminal = False++ def put_nowait(self, event: Optional[Dict[str, Any]]) -> None:+ if self.terminal:+ return+ seq = self.next_seq+ self.next_seq += 1+ self.backlog.append((seq, event))+ if event is None:+ self.terminal = True+ for queue in list(self.subscribers):+ queue.put_nowait((seq, event))++ def attach(+ self, last_seq: int = -1+ ) -> tuple[asyncio.Queue, list[tuple[int, Optional[Dict[str, Any]]]]]:+ queue: asyncio.Queue = asyncio.Queue()+ self.subscribers.add(queue)+ return queue, [(seq, event) for seq, event in self.backlog if seq > last_seq]++ def detach(self, queue: asyncio.Queue) -> None:+ self.subscribers.discard(queue)++def _remember_room_retention(request: "web.Request", claims: dict[str, Any]) -> None:value = float(claims.get("status_expires_at") or claims.get("expires_at") or 0)try:@@ -437,7 +468,7 @@ class _RunLaunch:owner: Anyrun_id: str- queue: "asyncio.Queue[Optional[Dict]]"+ queue: _RunStreamsession_id: strgateway_session_key: Optional[str]declared_selected: bool@@ -659,7 +690,7 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Ressession_history_delivery = not previous_response_id and not conversation_historyif not conversation_history and selected_session_id and not previous_response_id:conversation_history = await self._conversation_history_for_session(str(selected_session_id))- q = self._run_streams[run_id] = asyncio.Queue()+ q = self._run_streams[run_id] = _RunStream()created_at = self._run_streams_created[run_id] = time.time()self._run_approval_sessions[run_id] = run_id # approval session key (see _RunLaunch)initial_status = self._set_run_status(@@ -1024,15 +1055,35 @@ async def _handle_run_events(self, request: "web.Request", *, _api_server) -> "wawait asyncio.sleep(0.05)else:return _run_not_found(_api_server._openai_error, run_id)- q = self._run_streams[run_id]+ stream = self._run_streams[run_id]+ raw_last_seq = request.headers.get("Last-Event-ID") or request.query.get("last_seq")+ try:+ last_seq = max(-1, int(str(raw_last_seq).strip())) if raw_last_seq is not None else -1+ except (TypeError, ValueError):+ last_seq = -1+ q, replay = stream.attach(last_seq)self._run_stream_subscribers.add(run_id)response = web.StreamResponse(status=200, headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Accel-Buffering": "no"})++ async def _write_event(seq: int, event: Dict[str, Any]) -> None:+ payload = dict(event)+ payload["seq"] = seq+ await response.write(f"id: {seq}\n".encode() + _api_server._sse_frame(payload))+await response.prepare(request)try:+ for seq, event in replay:+ if event is None:+ await response.write(b": stream closed\n\n")+ return response+ await _write_event(seq, event)+ if stream.terminal:+ await response.write(b": stream closed\n\n")+ return responsewhile True:try:- event = await asyncio.wait_for(+ seq, event = await asyncio.wait_for(q.get(), timeout=_api_server.CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS)except asyncio.TimeoutError:await response.write(b": keepalive\n\n")@@ -1040,12 +1091,14 @@ async def _handle_run_events(self, request: "web.Request", *, _api_server) -> "wif event is None: # run finishedawait response.write(b": stream closed\n\n")break- await response.write(_api_server._sse_frame(event))+ await _write_event(seq, event)except Exception as exc:logger.debug("[api_server] SSE stream error for run %s: %s", run_id, exc)finally:- self._run_stream_subscribers.discard(run_id)- _drop_run_transport(self, run_id)+ stream.detach(q)+ if not stream.subscribers:+ self._run_stream_subscribers.discard(run_id)+ self._release_run_owner_if_forgotten(run_id)return responsediff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.pyindex 2da6536a166..c273bc4b6f2 100644--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@ -11,6 +11,7 @@ Covers:import asyncioimport hashlib+import jsonimport threadingimport timefrom unittest.mock import AsyncMock, MagicMock, patch@@ -138,6 +139,54 @@ def _make_slow_agent(**kwargs):return mock_agent, ready, interrupted+def _make_scripted_agent():+ """Return an agent factory whose delta callback and completion are test-controlled."""+ ready = threading.Event()+ release = threading.Event()+ callbacks = {}+ mock_agent = MagicMock()++ def create_agent(*args, **kwargs):+ callbacks["delta"] = kwargs["stream_delta_callback"]+ return mock_agent++ def run_conversation(**kwargs):+ ready.set()+ release.wait(timeout=5)+ return {"final_response": "done"}++ mock_agent.run_conversation.side_effect = run_conversation+ mock_agent.steer.return_value = True+ mock_agent.session_prompt_tokens = 0+ mock_agent.session_completion_tokens = 0+ mock_agent.session_total_tokens = 0+ return create_agent, callbacks, ready, release+++async def _read_sse_frame(response):+ lines = []+ while True:+ line = await response.content.readline()+ if not line:+ break+ lines.append(line.decode())+ if line == b"\n":+ break+ sequence = next(+ (int(line.removeprefix("id: ")) for line in lines if line.startswith("id: ")),+ None,+ )+ event = next(+ (+ json.loads(line.removeprefix("data: "))+ for line in lines+ if line.startswith("data: ")+ ),+ None,+ )+ return sequence, event++@pytest.fixturedef adapter():return _make_adapter()@@ -642,6 +691,95 @@ class TestRunEvents:assert completed["usage"]["cache_write_tokens"] == 42+ @pytest.mark.asyncio+ async def test_concurrent_subscribers_each_receive_delta_and_terminal(self, adapter):+ """Each SSE client observes the complete run instead of sharing one FIFO."""+ app = _create_runs_app(adapter)+ create_agent, callbacks, ready, release = _make_scripted_agent()++ async with TestClient(TestServer(app)) as cli:+ with patch.object(adapter, "_create_agent", side_effect=create_agent):+ started = await cli.post("/v1/runs", json={"input": "hello"})+ run_id = (await started.json())["run_id"]+ await asyncio.get_running_loop().run_in_executor(None, ready.wait, 5)++ first = await cli.get(f"/v1/runs/{run_id}/events")+ second = await cli.get(f"/v1/runs/{run_id}/events")+ callbacks["delta"]("shared")+ release.set()++ first_body, second_body = await asyncio.wait_for(+ asyncio.gather(first.text(), second.text()), timeout=5+ )++ for body in (first_body, second_body):+ events = [+ json.loads(line.removeprefix("data: "))+ for line in body.splitlines()+ if line.startswith("data: ")+ ]+ assert [event["event"] for event in events] == [+ "message.delta",+ "run.completed",+ ]+ assert events[0]["delta"] == "shared"++ @pytest.mark.asyncio+ async def test_reconnect_receives_exactly_missed_events_and_terminal(self, adapter):+ """Reconnect replays missed delta, steer, and terminal exactly once."""+ app = _create_runs_app(adapter)+ create_agent, callbacks, ready, release = _make_scripted_agent()++ async with TestClient(TestServer(app)) as cli:+ with patch.object(adapter, "_create_agent", side_effect=create_agent):+ started = await cli.post("/v1/runs", json={"input": "hello"})+ run_id = (await started.json())["run_id"]+ await asyncio.get_running_loop().run_in_executor(None, ready.wait, 5)++ first = await cli.get(f"/v1/runs/{run_id}/events")+ callbacks["delta"]("seen")+ seen_sequence, seen_event = await asyncio.wait_for(+ _read_sse_frame(first), timeout=5+ )+ assert seen_sequence is not None+ assert seen_event["delta"] == "seen"+ first.close()+ await asyncio.sleep(0.1)++ steered = await cli.post(+ f"/v1/runs/{run_id}/steer",+ json={"input": "missed guidance"},+ )+ assert steered.status == 200+ callbacks["delta"]("missed")+ release.set()+ await asyncio.sleep(0.1)+ resumed = await cli.get(+ f"/v1/runs/{run_id}/events",+ headers={"Last-Event-ID": str(seen_sequence)},+ )+ body = await asyncio.wait_for(resumed.text(), timeout=5)++ frames = []+ for block in body.split("\n\n"):+ data = next(+ (+ json.loads(line.removeprefix("data: "))+ for line in block.splitlines()+ if line.startswith("data: ")+ ),+ None,+ )+ if data is not None:+ frames.append(data)+ assert [event["event"] for event in frames] == [+ "run.steered",+ "message.delta",+ "run.completed",+ ]+ assert frames[0]["accepted"] is True+ assert frames[1]["delta"] == "missed"+@pytest.mark.asyncioasync def test_approval_resolve_all_is_scoped_to_target_run(self, auth_adapter):"""Same client session_id must not let one run approve another run's queue."""