diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py index f3c6f2f8e..9474b37e4 100644 --- a/deeptutor/services/session/turn_runtime.py +++ b/deeptutor/services/session/turn_runtime.py @@ -1766,7 +1766,6 @@ class TurnRuntimeManager: events=assistant_events, attachments=generated_attachments or None, ) - await self._flush_buffered_events(execution) turn_status, turn_error = _resolve_turn_outcome( assistant_events, pending_done_event, @@ -1812,6 +1811,17 @@ class TurnRuntimeManager: ) except Exception: logger.debug("Failed to generate session title", exc_info=True) + # Flush once every terminal/post-turn event (DONE, and the title + # ``session_meta`` above) has been published, not before: a + # client that reconnects after this task's ``finally`` pops + # ``execution`` from ``_executions`` falls back entirely to this + # persisted backlog, and ``subscribe_turn`` synthesises an + # id-less DONE when it finds none there -- permanently orphaning + # the just-persisted assistant reply from that client's + # reconcile path (it can still see the message after a full + # session reload, since the row itself is fine; only the + # targeted in-place swap is unreachable). + await self._flush_buffered_events(execution) except asyncio.CancelledError: if not stream_done_sent: await self._publish_live_event( diff --git a/tests/services/session/test_turn_event_flush.py b/tests/services/session/test_turn_event_flush.py index 8d40523a2..ef19b55d7 100644 --- a/tests/services/session/test_turn_event_flush.py +++ b/tests/services/session/test_turn_event_flush.py @@ -1,10 +1,11 @@ """Post-stream turn-event flush: batching, workspace mirror, PocketBase upload. The turn runtime buffers every live event in memory and persists the whole -batch after the stream drains, right before publishing DONE. Everything on -that path must stay O(1) round-trips w.r.t. the event count — per-event -commits/opens/POSTs sat between the last streamed token and the client's -spinner clearing (the "stuck on generating" report). +batch, including DONE and any post-turn ``session_meta`` title update, once +the turn has fully finished. Everything on that path must stay O(1) round +trips w.r.t. the event count — per-event commits/opens/POSTs sat between the +last streamed token and the client's spinner clearing (the "stuck on +generating" report). """ from __future__ import annotations diff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.py index d52dae524..42ca16dea 100644 --- a/tests/services/session/test_turn_runtime_subscribe.py +++ b/tests/services/session/test_turn_runtime_subscribe.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +from types import SimpleNamespace import pytest @@ -147,3 +148,89 @@ async def test_start_turn_clears_orphan_running_turn_before_create( persisted = await store.get_turn(stale["id"]) assert persisted is not None assert persisted["status"] == "failed" + + +@pytest.mark.asyncio +async def test_reconnect_after_turn_completion_still_carries_message_ids( + monkeypatch: pytest.MonkeyPatch, tmp_path +) -> None: + """A client that (re)subscribes after the turn already finished and its + in-process execution was cleaned up must still get the persisted-id + metadata on DONE, not just the bare status. + + This is the ``resume_from`` path: the WS drops mid-turn (network blip, + backgrounded tab) and reconnects after the turn has already completed + server-side. Without persisted ids on DONE, the reconnecting client can + never run its optimistic-id reconcile swap for that turn -- the + assistant reply stays a real, correctly-persisted row, but the client's + local tree treats it as unreachable until a full session reload. + """ + + store = SQLiteSessionStore(tmp_path / "reconnect.db") + runtime = TurnRuntimeManager(store) + + class FakeContextBuilder: + def __init__(self, *_args, **_kwargs) -> None: + pass + + async def build(self, **_kwargs): + return SimpleNamespace( + conversation_history=[], + conversation_summary="", + context_text="", + token_count=0, + budget=0, + ) + + class FakeOrchestrator: + async def handle(self, _context): + yield StreamEvent( + type=StreamEventType.CONTENT, + source="chat", + stage="responding", + content="hello there", + metadata={"call_kind": "llm_final_response"}, + ) + + async def _noop_title(**_kwargs): + return None + + monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace()) + monkeypatch.setattr( + "deeptutor.services.session.context_builder.ContextBuilder", + FakeContextBuilder, + ) + monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator) + monkeypatch.setattr(runtime, "_maybe_generate_session_title", _noop_title) + + session, turn = await runtime.start_turn( + { + "type": "start_turn", + "content": "what is 2+2?", + "session_id": None, + "capability": "chat", + "tools": [], + "knowledge_bases": [], + "attachments": [], + "language": "en", + "config": {}, + } + ) + turn_id = turn["id"] + + # No one ever subscribed while the turn ran -- ``_run_turn`` is an + # independent task started inside ``start_turn``, so it runs (and its + # ``finally`` pops ``execution`` from ``_executions``) regardless. + execution = runtime._executions[turn_id] + await execution.task + assert turn_id not in runtime._executions + + messages = await store.get_messages(session["id"]) + assert [m["role"] for m in messages] == ["user", "assistant"] + real_assistant_id = messages[1]["id"] + + # The client reconnects now and asks to catch up from the start. + events = [event async for event in runtime.subscribe_turn(turn_id, after_seq=0)] + done_events = [e for e in events if e["type"] == "done"] + assert len(done_events) == 1 + assert done_events[0]["metadata"].get("assistant_message_id") == real_assistant_id