DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
perf(chat): eliminate the post-stream "generating" stall
Bingxi Zhao (Frank)308a0606f960
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.pyindex ff02776d0..42e11902b 100644--- a/deeptutor/services/session/pocketbase_store.py+++ b/deeptutor/services/session/pocketbase_store.py@@ -4,16 +4,20 @@ PocketBase-backed session store.Implements SessionStoreProtocol using PocketBase collections for all durablestorage. The key performance design:-- All methods except ``append_turn_event`` make direct PocketBase HTTP calls.- These are called at most a handful of times per turn (create, get, update- status, add message) and the ~5–10 ms overhead is acceptable.--- ``append_turn_event`` returns immediately without writing to PocketBase.- The existing ``_mirror_event_to_workspace`` in turn_runtime.py already- appends every event to a local ``events.jsonl`` file. When- ``update_turn_status`` finalises a turn it reads that file and batch-posts- all events to PocketBase ``turn_events`` in a single request, trading- real-time durability for ~40× lower per-event latency during streaming.+- Most methods make direct PocketBase HTTP calls. These are called at most a+ handful of times per turn (create, get, update status, add message) and the+ ~5–10 ms overhead is acceptable.++- Turn events are the exception: they arrive hundreds at a time when the turn+ runtime flushes its in-memory buffer after the stream ends.+ ``append_turn_events`` therefore annotates the payloads and returns+ immediately, uploading the records to the ``turn_events`` collection in a+ background task — the turn's DONE event (and the client's spinner) must not+ wait on one HTTP round-trip per event. Durability is anchored elsewhere: the+ assistant message row already carries the full event list in+ ``events_json``, and turn_runtime mirrors the batch to a task-local+ ``events.jsonl``. The ``turn_events`` collection only serves post-turn trace+ replay, so eventual consistency is acceptable."""from __future__ import annotations@@ -21,14 +25,11 @@ from __future__ import annotationsimport asyncioimport jsonimport logging-from pathlib import Pathimport reimport timefrom typing import Anyimport uuid-from deeptutor.services.path_service import get_path_service-logger = logging.getLogger(__name__)_VALID_ID = re.compile(r"^[a-zA-Z0-9_-]+$")@@ -102,6 +103,13 @@ def _find_session_record(pb: Any, session_id: str, user_id: str) -> Any | None:class PocketBaseSessionStore:"""PocketBase-backed implementation of SessionStoreProtocol."""+ def __init__(self) -> None:+ # Strong refs to in-flight turn-event upload tasks: ``create_task``+ # results are weakly referenced by the loop, so without this a GC+ # could cancel an upload mid-flight. Tasks discard themselves on+ # completion.+ self._event_upload_tasks: set[asyncio.Task[None]] = set()+# ------------------------------------------------------------------# Sessions# ------------------------------------------------------------------@@ -321,8 +329,8 @@ class PocketBaseSessionStore:events: list[dict[str, Any]] | None = None,attachments: list[dict[str, Any]] | None = None,metadata: dict[str, Any] | None = None,- parent_message_id: int | None = None,- ) -> int:+ parent_message_id: int | str | None = None,+ ) -> int | str:# ``parent_message_id`` is accepted to match the protocol shape but is# not yet wired through PocketBase storage — branching only works on# the SQLite backend today.@@ -349,8 +357,11 @@ class PocketBaseSessionStore:try:record = await asyncio.to_thread(_add)- # Return a synthetic integer id using epoch ms- return int(now * 1000)+ # Return the real PocketBase record id — the same id+ # ``get_messages`` serves — so callers (e.g. the DONE-event+ # reconcile metadata) hand the frontend ids that match what a+ # later session fetch would return.+ return str(getattr(record, "id", "") or "")except Exception as exc:logger.warning(f"add_message failed: {exc}")return 0@@ -576,67 +587,8 @@ class PocketBaseSessionStore:logger.warning(f"update_turn_status failed: {exc}")return False- # Batch-flush turn events from local JSONL buffer to PocketBase on finalisation- if updated and finished_at is not None:- await self._flush_turn_events(tid)-return updated- async def _flush_turn_events(self, turn_id: str) -> None:- """- Read the local events.jsonl write-ahead buffer and batch-POST all- events to PocketBase turn_events collection in a single background call.- """- tid = _validate_id(turn_id, "turn_id")- try:- path_service = get_path_service()- # The JSONL file is written by _mirror_event_to_workspace; we look- # across all capability workspaces since we only have the turn_id.- workspace_root = path_service.get_user_root()- jsonl_files: list[Path] = list(workspace_root.rglob(f"{tid}/events.jsonl"))-- if not jsonl_files:- return-- events: list[dict[str, Any]] = []- for jsonl_path in jsonl_files:- try:- for line in jsonl_path.read_text(encoding="utf-8").splitlines():- line = line.strip()- if line:- events.append(json.loads(line))- except Exception as exc:- logger.debug(f"Could not read events.jsonl at {jsonl_path}: {exc}")-- if not events:- return-- def _batch_create():- pb = _pb()- for event in events:- try:- pb.collection("turn_events").create(- {- "turn_id": tid,- "session_id": event.get("session_id", ""),- "seq": int(event.get("seq", 0)),- "type": event.get("type", ""),- "source": event.get("source", ""),- "stage": event.get("stage", ""),- "content": str(event.get("content", ""))[:10000],- "metadata_json": event.get("metadata", {}),- "event_timestamp": float(event.get("timestamp", 0)),- }- )- except Exception as exc:- logger.debug(f"turn_events batch item failed: {exc}")-- await asyncio.to_thread(_batch_create)- logger.debug(f"Flushed {len(events)} turn events for {tid} to PocketBase")-- except Exception as exc:- logger.warning(f"_flush_turn_events failed for {turn_id}: {exc}")-def _turn_record_to_dict(self, record: Any) -> dict[str, Any]:turn_id = getattr(record, "turn_id", getattr(record, "id", ""))return {@@ -653,23 +605,72 @@ class PocketBaseSessionStore:}# ------------------------------------------------------------------- # Turn events — write-ahead only; batch flush handled in update_turn_status+ # Turn events — annotated synchronously, uploaded in the background# ------------------------------------------------------------------async def append_turn_event(self, turn_id: str, event: dict[str, Any]) -> dict[str, Any]:- """- Assign a monotonic seq number and return the annotated payload.+ """Single-event convenience wrapper over ``append_turn_events``."""+ persisted = await self.append_turn_events(turn_id, [event])+ return persisted[0]- Does NOT write to PocketBase immediately — the caller's- _mirror_event_to_workspace already appends to events.jsonl, which- is flushed to PocketBase in bulk when the turn is finalised.+ async def append_turn_events(+ self, turn_id: str, events: list[dict[str, Any]]+ ) -> list[dict[str, Any]]:+ """Annotate a turn's buffered events and upload them in the background.++ Returns the annotated payloads immediately: the caller (turn runtime)+ publishes DONE right after this flush, and one HTTP round-trip per+ event must not sit between the last streamed token and the client's+ spinner clearing. The upload task keeps running past DONE — see the+ module docstring for why eventual consistency is fine here."""- payload = dict(event)- payload.setdefault("turn_id", turn_id)- # Assign seq if not provided; use timestamp-based counter as fallback.- if not payload.get("seq"):- payload["seq"] = int(time.time() * 1000) % 1_000_000- return payload+ tid = _validate_id(turn_id, "turn_id")+ base_seq = int(time.time() * 1000) % 1_000_000+ payloads: list[dict[str, Any]] = []+ for offset, event in enumerate(events):+ payload = dict(event)+ payload.setdefault("turn_id", tid)+ # The runtime assigns live seqs in _publish_live_event; the+ # timestamp fallback only covers payloads that never went+ # through it.+ if not payload.get("seq"):+ payload["seq"] = base_seq + offset+ payloads.append(payload)+ if payloads:+ task = asyncio.create_task(self._upload_turn_events(tid, payloads))+ self._event_upload_tasks.add(task)+ task.add_done_callback(self._event_upload_tasks.discard)+ return payloads++ async def _upload_turn_events(self, turn_id: str, payloads: list[dict[str, Any]]) -> None:+ def _create_all() -> int:+ pb = _pb()+ created = 0+ for event in payloads:+ try:+ pb.collection("turn_events").create(+ {+ "turn_id": turn_id,+ "session_id": event.get("session_id", ""),+ "seq": int(event.get("seq", 0)),+ "type": event.get("type", ""),+ "source": event.get("source", ""),+ "stage": event.get("stage", ""),+ "content": str(event.get("content", ""))[:10000],+ "metadata_json": event.get("metadata", {}),+ "event_timestamp": float(event.get("timestamp", 0)),+ }+ )+ created += 1+ except Exception as exc:+ logger.debug(f"turn_events upload item failed: {exc}")+ return created++ try:+ created = await asyncio.to_thread(_create_all)+ logger.debug(f"Uploaded {created}/{len(payloads)} turn events for {turn_id}")+ except Exception as exc:+ logger.warning(f"Turn-event upload failed for {turn_id}: {exc}")async def get_turn_events(self, turn_id: str, after_seq: int = 0) -> list[dict[str, Any]]:"""Retrieve persisted turn events from PocketBase (post-turn replay)."""diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.pyindex e6cb184c3..0d704214a 100644--- a/deeptutor/services/session/protocol.py+++ b/deeptutor/services/session/protocol.py@@ -52,8 +52,8 @@ class SessionStoreProtocol(Protocol):events: list[dict[str, Any]] | None = None,attachments: list[dict[str, Any]] | None = None,metadata: dict[str, Any] | None = None,- parent_message_id: int | None = None,- ) -> int: ...+ parent_message_id: int | str | None = None,+ ) -> int | str: ...async def delete_message(self, message_id: int | str) -> bool: ...diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 7e6c478f2..5aee1ffcb 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -1579,7 +1579,10 @@ class TurnRuntimeManager:conversation_history = list(history_result.conversation_history)conversation_context_text = history_result.context_text- new_user_message_id: int | None = None+ # SQLite returns integer rowids; PocketBase returns its string+ # record ids. Both are opaque to this layer — they only flow into+ # ``parent_message_id`` chaining and the DONE reconcile metadata.+ new_user_message_id: int | str | None = Noneif persist_user_message:# Pass parent explicitly only when the FE pinned it (covers# both branched edits with a positive id and root edits@@ -1690,7 +1693,7 @@ class TurnRuntimeManager:# parent, we use it; otherwise we let the store auto-append# (legacy behavior).if new_user_message_id is not None:- await self.store.add_message(+ assistant_message_id = await self.store.add_message(session_id=session_id,role="assistant",content=assistant_content,@@ -1700,7 +1703,7 @@ class TurnRuntimeManager:parent_message_id=new_user_message_id,)elif branch_parent_explicit:- await self.store.add_message(+ assistant_message_id = await self.store.add_message(session_id=session_id,role="assistant",content=assistant_content,@@ -1710,7 +1713,7 @@ class TurnRuntimeManager:parent_message_id=branch_parent_id,)else:- await self.store.add_message(+ assistant_message_id = await self.store.add_message(session_id=session_id,role="assistant",content=assistant_content,@@ -1726,6 +1729,19 @@ class TurnRuntimeManager:source=capability_name,metadata={"status": "completed"},)+ # Attach the persisted row ids so the frontend can reconcile its+ # optimistic (negative) message ids with a targeted in-place swap+ # instead of refetching and re-rendering the whole session.+ persisted_ids = {+ key: value+ for key, value in (+ ("user_message_id", new_user_message_id),+ ("assistant_message_id", assistant_message_id),+ )+ if value+ }+ if persisted_ids:+ pending_done_event.metadata = {**pending_done_event.metadata, **persisted_ids}await self._publish_live_event(execution, pending_done_event)stream_done_sent = Trueif not is_regenerate:@@ -2011,41 +2027,66 @@ class TurnRuntimeManager:execution.turn_id,)return- for persisted in persisted_batch:- self._mirror_event_to_workspace(execution, persisted)+ await self._mirror_events_to_workspace(execution, persisted_batch)return- for index, payload in enumerate(events):- try:- persisted = await self.store.append_turn_event(execution.turn_id, payload)- except ValueError as exc:- # A turn can disappear when the session is deleted while the turn task- # is draining post-stream persistence. Avoid cascading failures. The- # turn will not come back, so drop the whole remaining batch with one- # summary line instead of logging once per buffered event.- if "Turn not found:" not in str(exc):- raise- logger.warning(- "Skip persisting %d buffered event(s) for missing turn %s (first: %s)",- len(events) - index,- execution.turn_id,- payload.get("type", ""),- )- break- self._mirror_event_to_workspace(execution, persisted)+ persisted_events: list[dict[str, Any]] = []+ try:+ for index, payload in enumerate(events):+ try:+ persisted = await self.store.append_turn_event(execution.turn_id, payload)+ except ValueError as exc:+ # A turn can disappear when the session is deleted while the turn+ # task is draining post-stream persistence. Avoid cascading+ # failures. The turn will not come back, so drop the whole+ # remaining batch with one summary line instead of logging once+ # per buffered event.+ if "Turn not found:" not in str(exc):+ raise+ logger.warning(+ "Skip persisting %d buffered event(s) for missing turn %s (first: %s)",+ len(events) - index,+ execution.turn_id,+ payload.get("type", ""),+ )+ break+ persisted_events.append(persisted)+ finally:+ # Mirror whatever actually persisted, even when the loop broke or+ # raised part-way — matches the previous per-event behaviour.+ await self._mirror_events_to_workspace(execution, persisted_events)++ async def _mirror_events_to_workspace(+ self, execution: _TurnExecution, payloads: list[dict[str, Any]]+ ) -> None:+ """Mirror turn events to the task-local ``events.jsonl`` under ``data/user/workspace``.++ One open/write for the whole batch, off the event loop: the previous+ per-event ``open()+append`` ran synchronously on the loop thread and+ stretched turn finalisation (and every other connection) on slow+ storage. ``to_thread`` copies contextvars, so the per-user path scope+ resolves the same as on the loop.+ """+ if not payloads:+ return+ await asyncio.to_thread(self._mirror_events_to_workspace_sync, execution, payloads)@staticmethod- def _mirror_event_to_workspace(execution: _TurnExecution, payload: dict[str, Any]) -> None:- """Mirror turn events to task-local ``events.jsonl`` files under ``data/user/workspace``."""+ def _mirror_events_to_workspace_sync(+ execution: _TurnExecution, payloads: list[dict[str, Any]]+ ) -> None:try:path_service = get_path_service()task_dir = path_service.get_task_workspace(execution.capability, execution.turn_id)task_dir.mkdir(parents=True, exist_ok=True)event_file = task_dir / "events.jsonl"+ lines = "".join(+ json.dumps(payload, ensure_ascii=False, default=str) + "\n" for payload in payloads+ )with open(event_file, "a", encoding="utf-8") as f:- f.write(json.dumps(payload, ensure_ascii=False, default=str) + "\n")+ f.write(lines)except Exception:- logger.debug("Failed to mirror turn event to workspace", exc_info=True)+ logger.debug("Failed to mirror turn events to workspace", exc_info=True)import threadingdiff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.pyindex 183a9fbea..29049f493 100644--- a/tests/api/test_unified_ws_turn_runtime.py+++ b/tests/api/test_unified_ws_turn_runtime.py@@ -200,6 +200,11 @@ async def test_turn_runtime_replays_events_and_materializes_messages(detail = await store.get_session_with_messages(session["id"])assert detail is not Noneassert [message["role"] for message in detail["messages"]] == ["user", "assistant"]+ # DONE carries the persisted row ids so the frontend can reconcile its+ # optimistic negative ids in place instead of refetching the session.+ user_row, assistant_row = detail["messages"]+ assert done_event["metadata"]["user_message_id"] == user_row["id"]+ assert done_event["metadata"]["assistant_message_id"] == assistant_row["id"]assert detail["messages"][0]["metadata"]["request_snapshot"]["persona"] == "socratic"assert detail["messages"][0]["metadata"]["request_snapshot"]["memoryReferences"] == ["summary"]assert detail["messages"][0]["metadata"]["request_snapshot"]["bookReferences"] == [diff --git a/tests/services/session/test_turn_event_flush.py b/tests/services/session/test_turn_event_flush.pynew file mode 100644index 000000000..8d40523a2--- /dev/null+++ b/tests/services/session/test_turn_event_flush.py@@ -0,0 +1,275 @@+"""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).+"""++from __future__ import annotations++import asyncio+from contextlib import contextmanager+import json+from pathlib import Path+import re++import pytest++from deeptutor.multi_user.context import reset_current_user, set_current_user+from deeptutor.multi_user.models import CurrentUser, UserScope+from deeptutor.services.session.pocketbase_store import PocketBaseSessionStore+from deeptutor.services.session.sqlite_store import SQLiteSessionStore+from deeptutor.services.session.turn_runtime import TurnRuntimeManager, _TurnExecution++pytestmark = pytest.mark.asyncio++_CLAUSE = re.compile(r'(\w+)\s*=\s*"([^"]*)"')+++# ---------------------------------------------------------------------------+# Fake PocketBase SDK (same shape as test_pocketbase_isolation.py)+# ---------------------------------------------------------------------------+++class _Record:+ def __init__(self, pb_id: str, data: dict) -> None:+ self.id = pb_id+ for key, value in data.items():+ setattr(self, key, value)+++class _Collection:+ def __init__(self) -> None:+ self._rows: list[_Record] = []+ self._seq = 0++ def _matches(self, record: _Record, query_params: dict | None) -> bool:+ flt = (query_params or {}).get("filter") or ""+ for field, expected in _CLAUSE.findall(flt):+ if str(getattr(record, field, "")) != expected:+ return False+ return True++ def create(self, data: dict) -> _Record:+ self._seq += 1+ record = _Record(f"pb{self._seq:04d}", data)+ self._rows.append(record)+ return record++ def get_full_list(self, query_params: dict | None = None) -> list[_Record]:+ return [r for r in self._rows if self._matches(r, query_params)]++ def update(self, pb_id: str, data: dict) -> _Record:+ record = next(r for r in self._rows if r.id == pb_id)+ for key, value in data.items():+ setattr(record, key, value)+ return record+++class _FakeClient:+ def __init__(self) -> None:+ self._collections: dict[str, _Collection] = {}++ def collection(self, name: str) -> _Collection:+ return self._collections.setdefault(name, _Collection())+++def fake_pb(monkeypatch):+ client = _FakeClient()+ monkeypatch.setattr(+ "deeptutor.services.pocketbase_client.get_pb_client", lambda: client, raising=True+ )+ return client+++@contextmanager+def as_user(uid: str):+ scope = UserScope(kind="user", user_id=uid, root=Path("/tmp") / uid) # noqa: S108+ token = set_current_user(CurrentUser(id=uid, username=uid, role="user", scope=scope))+ try:+ yield+ finally:+ reset_current_user(token)+++async def _drain_uploads(store: PocketBaseSessionStore) -> None:+ """Wait for the store's background turn-event uploads to finish."""+ tasks = list(store._event_upload_tasks)+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+ # Let the done-callbacks (set discard) run before returning.+ await asyncio.sleep(0)+++def _buffered(session_id: str, turn_id: str, count: int) -> list[dict]:+ return [+ {+ "type": "content",+ "source": "chat",+ "stage": "",+ "content": f"chunk-{i}",+ "metadata": {},+ "session_id": session_id,+ "turn_id": turn_id,+ "seq": i + 1,+ "timestamp": 1000.0 + i,+ }+ for i in range(count)+ ]+++# ---------------------------------------------------------------------------+# SQLite path: batch DB append + single-write workspace mirror+# ---------------------------------------------------------------------------+++def stub_workspace(monkeypatch, tmp_path):+ """Point the runtime's workspace mirror at an isolated tmp tree."""++ class _StubPathService:+ def get_task_workspace(self, feature: str, task_id: str) -> Path:+ return tmp_path / "workspace" / feature / task_id++ monkeypatch.setattr(+ "deeptutor.services.session.turn_runtime.get_path_service",+ lambda: _StubPathService(),+ )+ return tmp_path / "workspace"+++async def test_flush_mirrors_whole_batch_in_one_file_write(+ tmp_path, stub_workspace, monkeypatch+) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ session = await store.ensure_session(None)+ turn = await store.create_turn(session["id"], capability="chat")+ execution = _TurnExecution(+ turn_id=turn["id"],+ session_id=session["id"],+ capability="chat",+ payload={},+ )+ execution.events = _buffered(session["id"], turn["id"], 5)++ open_calls = 0+ real_open = open++ def counting_open(*args, **kwargs):+ nonlocal open_calls+ open_calls += 1+ return real_open(*args, **kwargs)++ # Scope the ``open`` patch to the flush itself so the assertions below+ # (and fixture teardown) run against the real builtin.+ with pytest.MonkeyPatch.context() as flush_patch:+ flush_patch.setattr("builtins.open", counting_open)+ await runtime._flush_buffered_events(execution)++ # All five events reach the DB and the jsonl mirror, via ONE file open.+ persisted = await store.get_turn_events(turn["id"])+ assert [event["content"] for event in persisted] == [f"chunk-{i}" for i in range(5)]+ mirror = stub_workspace / "chat" / turn["id"] / "events.jsonl"+ lines = [json.loads(line) for line in mirror.read_text().splitlines()]+ assert [line["content"] for line in lines] == [f"chunk-{i}" for i in range(5)]+ assert open_calls == 1+++async def test_flush_is_idempotent_per_execution(tmp_path, stub_workspace) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ session = await store.ensure_session(None)+ turn = await store.create_turn(session["id"], capability="chat")+ execution = _TurnExecution(+ turn_id=turn["id"],+ session_id=session["id"],+ capability="chat",+ payload={},+ )+ execution.events = _buffered(session["id"], turn["id"], 3)++ await runtime._flush_buffered_events(execution)+ await runtime._flush_buffered_events(execution)++ persisted = await store.get_turn_events(turn["id"])+ assert len(persisted) == 3+ mirror = stub_workspace / "chat" / turn["id"] / "events.jsonl"+ assert len(mirror.read_text().splitlines()) == 3+++async def test_flush_survives_turn_deleted_mid_drain(tmp_path, stub_workspace) -> None:+ """Deleting the session mid-flush must not raise out of the turn task."""+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ session = await store.ensure_session(None)+ turn = await store.create_turn(session["id"], capability="chat")+ execution = _TurnExecution(+ turn_id=turn["id"],+ session_id=session["id"],+ capability="chat",+ payload={},+ )+ execution.events = _buffered(session["id"], turn["id"], 2)+ await store.delete_session(session["id"])++ await runtime._flush_buffered_events(execution) # must not raise+++# ---------------------------------------------------------------------------+# PocketBase path: background upload, no rglob, no update_turn_status hook+# ---------------------------------------------------------------------------+++async def test_pb_append_turn_events_uploads_in_background(fake_pb) -> None:+ store = PocketBaseSessionStore()+ with as_user("alice"):+ events = _buffered("s1", "turn_1", 4)+ persisted = await store.append_turn_events("turn_1", events)++ # Annotated payloads come back synchronously with their seqs intact —+ # the runtime mirrors these to events.jsonl without waiting on HTTP.+ assert [payload["seq"] for payload in persisted] == [1, 2, 3, 4]++ await _drain_uploads(store)+ rows = fake_pb.collection("turn_events").get_full_list()+ assert sorted(int(row.seq) for row in rows) == [1, 2, 3, 4]+ assert all(row.turn_id == "turn_1" for row in rows)+ assert all(row.session_id == "s1" for row in rows)+++async def test_pb_append_turn_event_single_delegates_to_batch(fake_pb) -> None:+ store = PocketBaseSessionStore()+ with as_user("alice"):+ payload = await store.append_turn_event("turn_9", {"type": "content", "content": "x"})+ assert payload["turn_id"] == "turn_9"+ assert payload["seq"] # fallback seq assigned+ await _drain_uploads(store)+ rows = fake_pb.collection("turn_events").get_full_list()+ assert len(rows) == 1+++async def test_pb_update_turn_status_no_longer_flushes_events(fake_pb) -> None:+ """Finalising a turn only updates the row — the old events.jsonl rglob ++ per-event POST flush is gone (events flow through append_turn_events)."""+ store = PocketBaseSessionStore()+ with as_user("alice"):+ await store.create_session(title="t", session_id="s_flush")+ turn = await store.create_turn("s_flush", capability="chat")+ assert await store.update_turn_status(turn["turn_id"], "completed") is True+ await _drain_uploads(store)+ assert fake_pb.collection("turn_events").get_full_list() == []+++async def test_pb_add_message_returns_real_record_id(fake_pb) -> None:+ store = PocketBaseSessionStore()+ with as_user("alice"):+ await store.create_session(title="t", session_id="s_ids")+ message_id = await store.add_message("s_ids", "assistant", "hello")+ messages = await store.get_messages("s_ids")+ # The id handed back (and forwarded to the frontend via the DONE+ # reconcile metadata) must be the same id get_messages serves.+ assert message_id == messages[0]["id"]diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex acd48eb20..b1f6e42df 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -30,6 +30,7 @@ import {import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";import { normalizeMessageContent } from "@/lib/message-content";import { buildVisiblePath, tipMessageId } from "@/lib/message-branches";+import { reconcileTurnIds } from "@/lib/turn-reconcile";import {isNarrationMarker,recomputeAnswerContent,@@ -221,6 +222,13 @@ type Action =selectedBranches?: Record<string, number>;}| { type: "SET_SESSION_TITLE"; key: string; title: string }+ | {+ type: "RECONCILE_TURN";+ key: string;+ turnId?: string | null;+ userMessageId?: number | null;+ assistantMessageId?: number | null;+ }| { type: "DELETE_TURN"; key: string; messageId: number }| { type: "NEW_SESSION"; key: string }| {@@ -607,6 +615,33 @@ function reducer(state: ProviderState, action: Action): ProviderState {sidebarRefreshToken: state.sidebarRefreshToken + 1,};}+ case "RECONCILE_TURN": {+ // Swap the finished turn's optimistic (negative) message ids for the+ // persisted ids carried on the ``done`` event. This replaces the old+ // "refetch the whole session after every turn" reconcile, whose+ // hydrate + normalize + full re-render froze the tab for seconds on+ // long conversations.+ const session = state.sessions[action.key];+ if (!session) return state;+ const result = reconcileTurnIds(session.messages, session.selectedBranches, {+ turnId: action.turnId,+ userMessageId: action.userMessageId,+ assistantMessageId: action.assistantMessageId,+ });+ if (!result.changed) return state;+ return {+ ...state,+ sessions: {+ ...state.sessions,+ [action.key]: {+ ...session,+ messages: result.messages,+ selectedBranches: result.selectedBranches,+ updatedAt: Date.now(),+ },+ },+ };+ }case "SET_SELECTED_BRANCH": {const session = state.sessions[action.key];if (!session) return state;@@ -1071,14 +1106,36 @@ export function UnifiedChatProvider({// server's real ids after the turn finishes. Without this the// Edit button (which needs a real id to attach the new branch// under) and branch navigation (which keys off real ids) would- // stay disabled until the user navigates away and back.+ // stay disabled until the user navigates away and back. The+ // backend attaches the persisted ids to the ``done`` event, so+ // this is an in-place swap — refetching the whole session here+ // (the previous approach) re-downloaded, re-normalized, and+ // re-rendered the entire transcript after every turn, freezing+ // the tab for seconds on long conversations.if (status === "completed") {- const finishedSession = stateRef.current.sessions[effectiveKey];- const sessionId = finishedSession?.sessionId;- if (sessionId) {- loadSessionRef.current?.(sessionId).catch(() => {- /* non-fatal — local state remains usable */+ const doneMeta = event.metadata as {+ user_message_id?: number;+ assistant_message_id?: number;+ } | null;+ const assistantMessageId = doneMeta?.assistant_message_id ?? null;+ if (assistantMessageId != null) {+ dispatch({+ type: "RECONCILE_TURN",+ key: effectiveKey,+ turnId: event.turn_id || null,+ userMessageId: doneMeta?.user_message_id ?? null,+ assistantMessageId,});+ } else {+ // Older backend without ids on ``done`` — fall back to the+ // full session refetch.+ const finishedSession = stateRef.current.sessions[effectiveKey];+ const sessionId = finishedSession?.sessionId;+ if (sessionId) {+ loadSessionRef.current?.(sessionId).catch(() => {+ /* non-fatal — local state remains usable */+ });+ }}}return;diff --git a/web/hooks/useChatAutoScroll.ts b/web/hooks/useChatAutoScroll.tsindex 5e026f1e6..d9410171b 100644--- a/web/hooks/useChatAutoScroll.ts+++ b/web/hooks/useChatAutoScroll.ts@@ -88,11 +88,10 @@ export function useChatAutoScroll({composerHeight,]);- // Companion pin: a frame-aligned rAF loop that runs ONLY while the- // turn is streaming. ``useLayoutEffect`` above already pins on every- // page-level state change (new delta, new event, new message), but- // there is a class of height growth that doesn't bubble up to the- // page:+ // Companion pin: content-change-driven, active ONLY while the turn is+ // streaming. ``useLayoutEffect`` above already pins on every page-level+ // state change (new delta, new event, new message), but there is a class+ // of height growth that doesn't bubble up to the page://// 1. ``useSmoothStreamText`` advances the visible markdown inside// a child component between WebSocket deltas. Those frames@@ -101,43 +100,69 @@ export function useChatAutoScroll({// 2. KaTeX, code blocks, Mermaid, and the late-mount viewer// ``next/dynamic`` chunks all change the height of the message// area asynchronously when they finish hydrating mid-stream.+ // 3. Images/iframes finishing their network load grow the content+ // without mutating the DOM tree at all.//- // We can't use ``ResizeObserver`` on the scroll container itself- // because it observes border-box, not scrollHeight; overflow growth- // doesn't fire it. A short rAF loop scoped strictly to the- // streaming window costs ~60 cheap pins per second (each pin is a- // single attribute write, no React work) and is the simplest way- // to stay glued to the bottom edge regardless of WHY the inner- // content height changed.+ // We can't use ``ResizeObserver`` on the scroll container itself because+ // it observes border-box, not scrollHeight; overflow growth doesn't fire+ // it. This used to be a per-frame rAF loop instead — 60 unconditional+ // ``scrollHeight`` reads per second, each a forced synchronous layout of+ // the whole transcript, which grew with conversation length and kept the+ // main thread busy even in the idle window between the last token and the+ // turn's ``done`` event. A MutationObserver (cases 1–2) plus a capture-+ // phase ``load`` listener (case 3), coalesced to at most one pin per+ // frame, covers the same growth for a cost proportional to actual change.useEffect(() => {if (!isStreaming || !hasMessages) return;+ const container = containerRef.current;+ if (!container) return;let rafId = 0;- // ``scrollTop`` this loop last pinned. Before re-pinning we check whether- // the actual position has dropped below it: if so the user moved up by- // some means the gesture listeners below don't cover — dragging the- // scrollbar thumb, PageUp/Home, arrow keys — so we release the pin instead- // of yanking them back to the bottom (issue #649). Comparing against our- // own last write (rather than raw ``scrollTop``) is what makes this immune- // to the rAF-vs-user fight: content growth never lowers ``scrollTop`` (the- // container opts into ``overflow-anchor: none``), so a decrease is always- // user intent.+ // ``scrollTop`` this effect last pinned. A position below it means the+ // user moved up by some means the gesture listeners below don't cover —+ // dragging the scrollbar thumb, PageUp/Home, arrow keys — so we release+ // the pin instead of yanking them back to the bottom (issue #649).+ // Comparing against our own last write (rather than raw ``scrollTop``)+ // is what makes this immune to the pin-vs-user fight: content growth+ // never lowers ``scrollTop`` (the container opts into+ // ``overflow-anchor: none``), so a decrease is always user intent.let lastPinned: number | null = null;- const tick = () => {- if (shouldAutoScrollRef.current) {- const container = containerRef.current;- if (container) {- if (lastPinned !== null && container.scrollTop < lastPinned - 4) {- shouldAutoScrollRef.current = false;- } else {- container.scrollTop = container.scrollHeight;- lastPinned = container.scrollTop;- }- }++ const pin = () => {+ rafId = 0;+ if (!shouldAutoScrollRef.current) return;+ if (lastPinned !== null && container.scrollTop < lastPinned - 4) {+ shouldAutoScrollRef.current = false;+ return;+ }+ container.scrollTop = container.scrollHeight;+ lastPinned = container.scrollTop;+ };+ const schedule = () => {+ if (!rafId) rafId = requestAnimationFrame(pin);+ };+ // The user's own scrolls fire this too; our pins write+ // ``scrollTop === lastPinned`` so they never trip the release check.+ const onScroll = () => {+ if (lastPinned !== null && container.scrollTop < lastPinned - 4) {+ shouldAutoScrollRef.current = false;}- rafId = requestAnimationFrame(tick);};- rafId = requestAnimationFrame(tick);- return () => cancelAnimationFrame(rafId);++ const mo = new MutationObserver(schedule);+ mo.observe(container, {+ childList: true,+ subtree: true,+ characterData: true,+ });+ container.addEventListener("load", schedule, true);+ container.addEventListener("scroll", onScroll, { passive: true });+ schedule();+ return () => {+ mo.disconnect();+ container.removeEventListener("load", schedule, true);+ container.removeEventListener("scroll", onScroll);+ if (rafId) cancelAnimationFrame(rafId);+ };}, [isStreaming, hasMessages]);// After streaming ends, capability viewers loaded via ``next/dynamic``@@ -196,16 +221,16 @@ export function useChatAutoScroll({shouldAutoScrollRef.current = distanceFromBottom < 80;}, []);- // Intent-based release. The streaming rAF above re-pins to- // ``scrollHeight`` every frame, so the position-only ``handleScroll``- // check can NEVER observe the user trying to scroll up mid-stream: the- // pin snaps them back to the bottom before the ``scroll`` event is even- // handled, so ``distanceFromBottom`` always reads ~0 and the pin never- // releases — the viewport feels frozen. We therefore release the pin the- // instant we see an UPWARD scroll *gesture* (wheel up, or a touch drag- // that pulls earlier content into view), which is unambiguous user intent- // and independent of where the pin has parked the scroll position. Once- // released the rAF stops fighting, the user is free to browse, and+ // Intent-based release. During dense streaming the pin above re-snaps to+ // ``scrollHeight`` on every content change, so the position-only+ // ``handleScroll`` check can rarely observe the user trying to scroll up+ // mid-stream: the pin snaps them back to the bottom before the ``scroll``+ // event is even handled, so ``distanceFromBottom`` always reads ~0 and the+ // pin never releases — the viewport feels frozen. We therefore release the+ // pin the instant we see an UPWARD scroll *gesture* (wheel up, or a touch+ // drag that pulls earlier content into view), which is unambiguous user+ // intent and independent of where the pin has parked the scroll position.+ // Once released the pin stops fighting, the user is free to browse, and// ``handleScroll`` re-arms the pin when they return near the bottom.useEffect(() => {const container = containerRef.current;diff --git a/web/lib/turn-reconcile.ts b/web/lib/turn-reconcile.tsnew file mode 100644index 000000000..b62d46de0--- /dev/null+++ b/web/lib/turn-reconcile.ts@@ -0,0 +1,144 @@+/**+ * Reconcile optimistic (negative, client-generated) message ids with the+ * persisted ids the backend attaches to a turn's ``done`` event.+ *+ * Historically the chat context refetched the whole session after every turn+ * just to learn two ids — an O(conversation length) network + normalize ++ * re-render pass that froze the UI for seconds on long chats. This module is+ * the replacement: a targeted, pure, in-place id swap.+ *+ * Ids are typed ``number`` to match ``MessageItem``, but PocketBase-backed+ * deployments deliver string record ids at runtime (the long-standing+ * convention across ``hydrateMessages`` and the session API). All comparisons+ * here are identity-based, so both shapes flow through unchanged; only the+ * "is optimistic" check (`typeof id === "number" && id < 0`) is type-aware.+ */++export interface ReconcilableMessage {+ id?: number;+ role: "user" | "assistant" | "system";+ parentMessageId?: number | null;+ events?: Array<{ turn_id?: string }>;+}++export interface TurnPersistedIds {+ /** Turn the ids belong to — used to locate the right assistant bubble. */+ turnId?: string | null;+ /** Persisted id of the user row, absent on regenerate turns. */+ userMessageId?: number | null;+ /** Persisted id of the assistant row. */+ assistantMessageId?: number | null;+}++export interface ReconcileResult<T> {+ messages: T[];+ selectedBranches: Record<string, number>;+ changed: boolean;+}++function isOptimisticId(id: unknown): id is number {+ return typeof id === "number" && id < 0;+}++/**+ * Swap the turn's optimistic message ids for their persisted counterparts.+ *+ * Locates the turn's assistant bubble (last assistant message carrying an+ * event with ``turnId``; falls back to the last assistant message when the+ * turn id is unavailable) and the user message immediately preceding it.+ * Only optimistic (negative) ids are ever overwritten — rows that already+ * carry persisted ids (e.g. after a mid-turn session reload) are left+ * untouched, which also makes stale ``done`` replays harmless. All+ * ``parentMessageId`` pointers and ``selectedBranches`` entries referencing+ * a swapped id are remapped alongside it.+ *+ * Returns ``changed: false`` (with the original references) when there is+ * nothing to do, so the reducer can bail without a state update.+ */+export function reconcileTurnIds<T extends ReconcilableMessage>(+ messages: T[],+ selectedBranches: Record<string, number>,+ ids: TurnPersistedIds,+): ReconcileResult<T> {+ const unchanged: ReconcileResult<T> = {+ messages,+ selectedBranches,+ changed: false,+ };+ if (ids.assistantMessageId == null && ids.userMessageId == null) {+ return unchanged;+ }++ let assistantIndex = -1;+ for (let i = messages.length - 1; i >= 0; i--) {+ const message = messages[i];+ if (message.role !== "assistant") continue;+ if (ids.turnId) {+ const events = message.events;+ if (+ !Array.isArray(events) ||+ !events.some((event) => event?.turn_id === ids.turnId)+ ) {+ continue;+ }+ }+ assistantIndex = i;+ break;+ }+ if (assistantIndex === -1) return unchanged;++ // Old optimistic id → persisted id, applied to ids and parent pointers.+ const remap = new Map<number, number>();+ const assistant = messages[assistantIndex];+ if (ids.assistantMessageId != null && isOptimisticId(assistant.id)) {+ remap.set(assistant.id, ids.assistantMessageId);+ }+ if (ids.userMessageId != null) {+ for (let i = assistantIndex - 1; i >= 0; i--) {+ const message = messages[i];+ if (message.role !== "user") continue;+ if (isOptimisticId(message.id)) {+ remap.set(message.id, ids.userMessageId);+ }+ break;+ }+ }+ if (remap.size === 0) return unchanged;++ const nextMessages = messages.map((message) => {+ const nextId =+ message.id !== undefined ? remap.get(message.id) : undefined;+ const nextParent =+ message.parentMessageId != null+ ? remap.get(message.parentMessageId)+ : undefined;+ if (nextId === undefined && nextParent === undefined) return message;+ return {+ ...message,+ ...(nextId !== undefined ? { id: nextId } : {}),+ ...(nextParent !== undefined ? { parentMessageId: nextParent } : {}),+ };+ });++ let nextBranches = selectedBranches;+ const branchEntries = Object.entries(selectedBranches);+ if (branchEntries.length > 0) {+ let branchesChanged = false;+ const rebuilt: Record<string, number> = {};+ for (const [parentKey, childId] of branchEntries) {+ const parentAsNumber = Number(parentKey);+ const remappedParent = Number.isNaN(parentAsNumber)+ ? undefined+ : remap.get(parentAsNumber);+ const remappedChild = remap.get(childId);+ rebuilt[remappedParent !== undefined ? String(remappedParent) : parentKey] =+ remappedChild !== undefined ? remappedChild : childId;+ if (remappedParent !== undefined || remappedChild !== undefined) {+ branchesChanged = true;+ }+ }+ if (branchesChanged) nextBranches = rebuilt;+ }++ return { messages: nextMessages, selectedBranches: nextBranches, changed: true };+}diff --git a/web/tests/turn-reconcile.test.ts b/web/tests/turn-reconcile.test.tsnew file mode 100644index 000000000..005549c5e--- /dev/null+++ b/web/tests/turn-reconcile.test.ts@@ -0,0 +1,147 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ reconcileTurnIds,+ type ReconcilableMessage,+} from "../lib/turn-reconcile";++interface Msg extends ReconcilableMessage {+ content: string;+}++const TURN = "turn_abc";++function optimisticTurn(): Msg[] {+ return [+ { id: 10, role: "user", content: "earlier", parentMessageId: null },+ { id: 11, role: "assistant", content: "earlier reply", parentMessageId: 10 },+ { id: -2000, role: "user", content: "question", parentMessageId: 11 },+ {+ id: -2001,+ role: "assistant",+ content: "streamed answer",+ parentMessageId: -2000,+ events: [{ turn_id: TURN }],+ },+ ];+}++test("swaps optimistic user+assistant ids and parent pointers", () => {+ const input = optimisticTurn();+ const result = reconcileTurnIds(input, {}, {+ turnId: TURN,+ userMessageId: 12,+ assistantMessageId: 13,+ });+ assert.equal(result.changed, true);+ const [, , user, assistant] = result.messages;+ assert.equal(user.id, 12);+ assert.equal(assistant.id, 13);+ assert.equal(assistant.parentMessageId, 12);+ // Untouched rows keep their object identity (no needless re-renders).+ assert.equal(result.messages[0], input[0]);+ assert.equal(result.messages[1], input[1]);+});++test("does not touch rows that already carry persisted ids", () => {+ const messages: Msg[] = [+ { id: 20, role: "user", content: "q", parentMessageId: null },+ {+ id: 21,+ role: "assistant",+ content: "a",+ parentMessageId: 20,+ events: [{ turn_id: TURN }],+ },+ ];+ const result = reconcileTurnIds(messages, {}, {+ turnId: TURN,+ userMessageId: 99,+ assistantMessageId: 98,+ });+ assert.equal(result.changed, false);+ assert.equal(result.messages, messages);+});++test("a stale done replay for an old turn cannot restamp a newer turn", () => {+ const messages: Msg[] = [+ { id: 30, role: "user", content: "old q", parentMessageId: null },+ {+ id: 31,+ role: "assistant",+ content: "old a",+ parentMessageId: 30,+ events: [{ turn_id: "turn_old" }],+ },+ { id: -3000, role: "user", content: "new q", parentMessageId: 31 },+ {+ id: -3001,+ role: "assistant",+ content: "new streaming a",+ parentMessageId: -3000,+ events: [{ turn_id: "turn_new" }],+ },+ ];+ // done replay for turn_old: its bubble already has real ids → no-op, and+ // crucially the newer optimistic bubble is left alone.+ const result = reconcileTurnIds(messages, {}, {+ turnId: "turn_old",+ userMessageId: 77,+ assistantMessageId: 78,+ });+ assert.equal(result.changed, false);+});++test("regenerate turns reconcile the assistant id only", () => {+ const messages: Msg[] = [+ { id: 40, role: "user", content: "q", parentMessageId: null },+ {+ id: -4001,+ role: "assistant",+ content: "regenerated",+ parentMessageId: 40,+ events: [{ turn_id: TURN }],+ },+ ];+ const result = reconcileTurnIds(messages, {}, {+ turnId: TURN,+ userMessageId: null,+ assistantMessageId: 41,+ });+ assert.equal(result.changed, true);+ assert.equal(result.messages[1].id, 41);+ assert.equal(result.messages[0].id, 40);+});++test("falls back to the last assistant bubble when turn id is missing", () => {+ const result = reconcileTurnIds(optimisticTurn(), {}, {+ turnId: null,+ userMessageId: 12,+ assistantMessageId: 13,+ });+ assert.equal(result.changed, true);+ assert.equal(result.messages[3].id, 13);+});++test("remaps selectedBranches keys and values that used optimistic ids", () => {+ const branches = { "11": -2000, "-2000": -2001 };+ const result = reconcileTurnIds(optimisticTurn(), branches, {+ turnId: TURN,+ userMessageId: 12,+ assistantMessageId: 13,+ });+ assert.deepEqual(result.selectedBranches, { "11": 12, "12": 13 });+});++test("returns original references when there is nothing to reconcile", () => {+ const messages = optimisticTurn();+ const branches = { "11": -2000 };+ const result = reconcileTurnIds(messages, branches, {+ turnId: "turn_unknown",+ userMessageId: 12,+ assistantMessageId: 13,+ });+ assert.equal(result.changed, false);+ assert.equal(result.messages, messages);+ assert.equal(result.selectedBranches, branches);+});