The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): a session chat stream delivers every worker-thread event before its terminal frames
Tekniume0c3743aff12
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex fb062a726d9..0449fa6edf4 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -1027,6 +1027,10 @@ class _SessionEventQueue:self.session_id = session_idself.run_id = run_idself.seq = 0+ # Cross-thread puts handed to the loop and not yet applied. The loop does not order them+ # against the worker future's completion, so the turn's terminal frames wait on flush().+ self._inflight = 0+ self._inflight_lock = threading.Lock()def payload(self, name: str, payload: dict[str, Any]) -> tuple[str, dict[str, Any]]:self.seq += 1@@ -1042,11 +1046,35 @@ class _SessionEventQueue:running_loop = asyncio.get_running_loop()except RuntimeError:running_loop = None- with suppress(RuntimeError):- if running_loop is self.loop:+ if running_loop is self.loop:+ self.queue.put_nowait(event)+ return+ with self._inflight_lock:+ self._inflight += 1++ def _apply() -> None:+ try:self.queue.put_nowait(event)- else:- self.loop.call_soon_threadsafe(self.queue.put_nowait, event)+ finally:+ self._settle_one()+ try:+ self.loop.call_soon_threadsafe(_apply)+ except RuntimeError: # loop closed: the stream is gone, nothing left to deliver to+ self._settle_one()++ def _settle_one(self) -> None:+ with self._inflight_lock:+ self._inflight -= 1++ async def flush(self) -> None:+ """Wait until every event a worker thread enqueued has reached the queue. Call it before+ the terminal frames: a commentary/delta/approval handed over before the worker returned+ otherwise lands after ``done``/``None`` and the reader never sees it."""+ while True:+ with self._inflight_lock:+ if not self._inflight:+ return+ await asyncio.sleep(0)def _room_grant_delegate(name: str):@@ -3615,6 +3643,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):tool_progress_callback=_tool_progress, interim_assistant_callback=_commentary,active_run_id=run_id, approval_notify_callback=approval_notify,approval_session_key=run_id, **ctx["run_kwargs"])+ await events.flush()is_dict = isinstance(result, dict)final_response = _resolve_media_to_data_urls(result.get("final_response", "") if is_dict else "")effective_session_id = result.get("session_id", session_id) if is_dict else session_id@@ -3647,6 +3676,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):self._active_run_agents.pop(run_id, None)self._run_approval_sessions.pop(run_id, None)self._release_run_owner_if_forgotten(run_id)+ await events.flush()await queue.put(_event_payload("done", {}))await queue.put(None)diff --git a/tests/gateway/test_session_api.py b/tests/gateway/test_session_api.pyindex 4789f955ec0..6f40b23f2ae 100644--- a/tests/gateway/test_session_api.py+++ b/tests/gateway/test_session_api.py@@ -1332,6 +1332,45 @@ async def test_session_stream_records_reply_text_for_post_disconnect_recovery(assert "the answer worth keeping" in response.text+async def test_worker_events_reach_the_session_stream_before_its_terminal_frames(adapter, session_db, monkeypatch):+ """A commentary the agent's worker thread hands to the loop before returning is delivered+ before ``assistant.completed``/``done``, however late the loop applies that hand-off (it is+ not ordered against the worker's own completion; CI saw it land after ``None`` and vanish)."""+ session_id = session_db.create_session("late-hop-session", "api_server")+ monkeypatch.setattr("gateway.run._load_gateway_config", dict)+ loop = asyncio.get_running_loop()+ real_threadsafe = loop.call_soon_threadsafe++ def late_queue_hops(callback, *args, **kwargs):+ # Only the hops that feed the session event queue arrive late; executor completions do not.+ target = getattr(callback, "__self__", None)+ if isinstance(target, asyncio.Queue) or getattr(callback, "__name__", "") == "_apply":+ return real_threadsafe(loop.call_later, 0.2, callback, *args)+ return real_threadsafe(callback, *args, **kwargs)+ monkeypatch.setattr(loop, "call_soon_threadsafe", late_queue_hops)++ def fake_create_agent(**kwargs):+ interim = kwargs["interim_assistant_callback"]++ class FakeAgent:+ provider, model = "openai-codex", "gpt-5"+ session_prompt_tokens = session_completion_tokens = session_total_tokens = 0++ def run_conversation(self, **_kw):+ interim("Checking the docs first.", already_streamed=False)+ return {"final_response": "Done.", "messages": [], "api_calls": 1}+ return FakeAgent()++ app = _create_session_app(adapter)+ with patch.object(adapter, "_create_agent", side_effect=fake_create_agent):+ async with TestClient(TestServer(app)) as cli:+ body = await (await cli.post(f"/api/sessions/{session_id}/chat/stream", json={"message": "go"})).text()+ names = [ln[7:] for ln in body.splitlines() if ln.startswith("event: ")]+ assert "assistant.commentary" in names, names+ assert names.index("assistant.commentary") < names.index("assistant.completed") < names.index("done"), names++@pytest.mark.asyncioasync def test_interim_commentary_reaches_session_sse_and_responses_stream(adapter, session_db, monkeypatch):"""Codex commentary / mid-turn assistant text is a typed ``assistant.commentary`` event on the