diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index b3d0c6730..84dc1e419 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -53,6 +53,7 @@ _MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024 _MAX_INLINE_TRACE_DETAIL_BYTES = 32 * 1024 _WEBUI_TURN_ID_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") _WEBUI_REPLAY_IDENTITY_KEY = "_webui_replay_identity" +_WEBUI_PROJECTION_RECEIPTS_KEY = "_webui_projection_receipts" _WEBUI_TRACE_DETAIL_UNSAFE_KEY = "_webui_trace_detail_unsafe" _WEBUI_TRACE_DETAIL_REF_RE = re.compile( r"^(?P\d{1,12})\.(?Phistory-[0-9a-f]{20})$" @@ -199,6 +200,11 @@ class _SessionBackfillTurn(NamedTuple): assistant_records: tuple[dict[str, Any], ...] +class _ProjectionReceipt(TypedDict): + turn_id: str + ranges: list[list[int]] + + class _DeferredTraceGroup(NamedTuple): start: int stop: int @@ -243,8 +249,32 @@ def _stream_key(record: dict[str, Any], stream: str) -> tuple[str, str, str]: return turn_id, phase, stream_id +def _projection_receipts(records: Sequence[Mapping[str, Any]]) -> list[_ProjectionReceipt]: + """Compress actual represented facts by turn, without covering missing sequences.""" + members: dict[str, set[int]] = {} + for record in records: + turn_id, sequence = record.get("turn_id"), record.get("turn_seq") + if ( + isinstance(turn_id, str) and turn_id + and isinstance(sequence, int) and not isinstance(sequence, bool) and sequence >= 0 + ): + members.setdefault(turn_id, set()).add(sequence) + receipts: list[_ProjectionReceipt] = [] + for turn_id, sequences in members.items(): + ranges: list[list[int]] = [] + for sequence in sorted(sequences): + if ranges and ranges[-1][1] + 1 == sequence: + ranges[-1][1] = sequence + else: + ranges.append([sequence, sequence]) + receipts.append({"turn_id": turn_id, "ranges": ranges}) + return receipts + + def _compact_completed_stream_deltas( turn: list[dict[str, Any]], + *, + include_projection_receipts: bool = False, ) -> tuple[list[dict[str, Any]], int]: """Fold transport deltas into canonical end records for a completed turn.""" if not turn or turn[-1].get("event") != "turn_end": @@ -271,6 +301,10 @@ def _compact_completed_stream_deltas( completed["text"] = "".join( str(chunk.get("text") or "") for _, chunk in chunks ) + if include_projection_receipts: + receipts = _projection_receipts([*(chunk for _, chunk in chunks), record]) + if receipts: + completed[_WEBUI_PROJECTION_RECEIPTS_KEY] = receipts replacements[index] = completed dropped_indexes.update(chunk_index for chunk_index, _ in chunks) @@ -388,7 +422,7 @@ def _select_transcript_page( ) stats.parsed_records += len(turn) stats.source_bytes += ref.byte_count if safe else _records_bytes(turn) - turn, dropped = _compact_completed_stream_deltas(turn) + turn, dropped = _compact_completed_stream_deltas(turn, include_projection_receipts=True) stats.compacted_delta_records += dropped if not safe: stats.truncated_oversized_turn = True @@ -1254,7 +1288,7 @@ def build_webui_trace_detail_response( turn = _transcript_turn_at_ordinal(session_key, ordinal, history=history) if turn is None: return None - turn, _ = _compact_completed_stream_deltas(turn) + turn, _ = _compact_completed_stream_deltas(turn, include_projection_receipts=True) lines = _records_with_replay_identity(turn, turn_ordinal=ordinal) for group in _client_projection_deferred_trace_groups(lines).values(): first = lines[group.start] @@ -1309,6 +1343,9 @@ def _client_projection_common_fields(record: dict[str, Any]) -> dict[str, Any]: created_at_ms = _valid_created_at_ms(record.get("created_at_ms")) if created_at_ms is not None: fields["created_at_ms"] = created_at_ms + receipts = record.get(_WEBUI_PROJECTION_RECEIPTS_KEY) + if receipts: + fields["projection_receipts"] = receipts return fields @@ -1598,6 +1635,9 @@ def _client_projection_events( ) event["text"] = _trace_summary(last_text) event.pop("tool_events", None) + receipts = _projection_receipts(lines[group.start:group.stop]) + if receipts: + event["projection_receipts"] = receipts if detail_ref is not None: event["trace_detail"] = { "ref": detail_ref, diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py index e572e4404..75f3d1689 100644 --- a/tests/utils/test_webui_transcript.py +++ b/tests/utils/test_webui_transcript.py @@ -214,6 +214,86 @@ def test_event_projection_augments_complete_stream_text(history, tmp_path, monke ] +@pytest.mark.parametrize( + ("delta_event", "end_event", "phase"), + [("delta", "stream_end", "answer"), ("reasoning_delta", "reasoning_end", "reasoning")], +) +def test_thread_response_preserves_optional_stream_ids(history, delta_event, end_event, phase) -> None: + key = "websocket:stream-identity" + history.append(key, {"event": "user", "text": "question", "turn_id": "turn-stream"}) + for stream_id in ("wire-first", "wire-second", None): + for event in (delta_event, end_event): + history.append(key, { + "event": event, + "turn_id": "turn-stream", + "turn_phase": phase, + "text": "part", + **({"stream_id": stream_id} if stream_id is not None else {}), + }) + original_rows = history.read(key) + + payload = history.build(key) + + assert payload is not None + stream_events = payload["events"][1:] + assert [event["event"] for event in stream_events] == [delta_event, end_event] * 3 + assert [event.get("stream_id") for event in stream_events] == [ + "wire-first", "wire-first", "wire-second", "wire-second", None, None, + ] + assert all("stream_id" not in event for event in stream_events[-2:]) + assert all("projection_receipts" not in event for event in stream_events) + assert history.read(key) == original_rows + + +@pytest.mark.parametrize( + ("delta_event", "end_event", "phase"), + [("delta", "stream_end", "answer"), ("reasoning_delta", "reasoning_end", "reasoning")], +) +@pytest.mark.parametrize("completed_text", [None, "canonical text"]) +def test_thread_response_receipts_for_folded_legacy_deltas( + history, delta_event, end_event, phase, completed_text, +) -> None: + key = "websocket:folded-receipts" + primary_text = completed_text or "first second last" + rows = [ + {"event": "user", "text": "question", "turn_phase": "user", "turn_seq": 1}, + {"event": delta_event, "text": "first ", "stream_id": "primary", "turn_seq": 3}, + {"event": delta_event, "text": "second", "stream_id": "primary", "turn_seq": 4}, + {"event": "message", "kind": "progress", "text": "tool()", "turn_phase": "activity", "turn_seq": 5}, + {"event": delta_event, "text": "other", "stream_id": "secondary", "turn_seq": 6}, + {"event": delta_event, "text": " last", "stream_id": "primary", "turn_seq": 8}, + {"event": end_event, "stream_id": "primary", "turn_seq": 9, + **({"text": completed_text} if completed_text is not None else {})}, + {"event": end_event, "stream_id": "secondary", "turn_seq": 10}, + {"event": "turn_end", "turn_phase": "complete", "turn_seq": 11}, + ] + for row in rows: + history.append(key, {"turn_id": "turn-folded", "turn_phase": phase, **row}) + original_rows = history.read(key) + stats = TranscriptReplayStats() + + payload = history.build(key, stats=stats) + + assert payload is not None + assert stats.compacted_delta_records == 4 + ends = [event for event in payload["events"] if event["event"] == end_event] + assert [(event["stream_id"], event["turn_seq"], event["text"]) for event in ends] == [ + ("primary", 9, primary_text), ("secondary", 10, "other"), + ] + assert [event["projection_receipts"] for event in ends] == [ + [{"turn_id": "turn-folded", "ranges": [[3, 4], [8, 9]]}], + [{"turn_id": "turn-folded", "ranges": [[6, 6], [10, 10]]}], + ] + assert history.read(key) == original_rows + # Migration compaction retains its existing record format, without HTTP metadata. + assert transcript_module.compact_legacy_records(original_rows) == [ + original_rows[0], original_rows[3], + {**original_rows[6], "text": primary_text}, + {**original_rows[7], "text": "other"}, + original_rows[8], + ] + + def test_event_projection_defers_trace_details_without_legacy_fallback(history, tmp_path, monkeypatch, ) -> None: @@ -372,6 +452,35 @@ def test_many_short_trace_rows_are_bounded_and_resolved(history, tmp_path, monke assert detail["events"][-1]["text"] == f"tool_{trace_count - 1}(value)" +def test_thread_response_summary_receipts_preserve_holes_and_turn_membership(history) -> None: + key = "websocket:summary-receipts" + history.append(key, {"event": "user", "text": "run tools", "turn_id": "turn-T", "turn_seq": 1}) + members = [("turn-T", 3), ("turn-T", 4), ("turn-U", 2), ("turn-T", 8)] + for turn_id, sequence in members: + history.append(key, { + "event": "message", "kind": "progress", "text": f'exec({"x" * 10_000})', + "turn_id": turn_id, "turn_seq": sequence, "turn_phase": "activity", + }) + history.append(key, {"event": "turn_end", "turn_id": "turn-T", "turn_seq": 9}) + original_rows = history.read(key) + + payload = history.build(key) + + assert payload is not None + assert len(payload["events"]) == 3 + summary = payload["events"][1] + assert summary["trace_detail"]["traceCount"] == len(members) + assert summary["projection_receipts"] == [ + {"turn_id": "turn-T", "ranges": [[3, 4], [8, 8]]}, + {"turn_id": "turn-U", "ranges": [[2, 2]]}, + ] + assert (summary["turn_id"], summary["turn_seq"]) == members[0] + detail = history.trace(key, summary["trace_detail"]["ref"]) + assert detail is not None + assert [(event["turn_id"], event["turn_seq"]) for event in detail["events"]] == members + assert history.read(key) == original_rows + + def test_transcript_revision_tracks_artifacts_and_variants(history, tmp_path, monkeypatch) -> None: monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) key = "websocket:revision" diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index f1e8cdbec..20e9d2d35 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -28,6 +28,7 @@ import { ChatFailureFixture } from "./chat-failure-fixture"; import { ThreadLoadingFixture } from "./thread-loading-fixture"; import { AnswerOrderFixture } from "./answer-order-fixture"; import { SidebarActivityFixture } from "./sidebar-activity-fixture"; +import { HistoryHydrationFixture } from "./history-hydration-fixture"; const history: UIMessage[] = [ { id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 }, @@ -176,6 +177,8 @@ createRoot(document.getElementById("root")!).render( ? : parameters.get("case") === "typography" ? + : parameters.get("case") === "history-hydration" + ? : parameters.get("case") === "history-boundary" ? : parameters.get("case") === "diagrams" diff --git a/webui/browser/history-hydration-fixture.tsx b/webui/browser/history-hydration-fixture.tsx new file mode 100644 index 000000000..6c56444ba --- /dev/null +++ b/webui/browser/history-hydration-fixture.tsx @@ -0,0 +1,66 @@ +import { useEffect, useRef, useState } from "react"; + +import { ThreadShell } from "@/components/thread/ThreadShell"; +import { settings } from "@/dev/gallery/settings"; +import { NanobotClient } from "@/lib/nanobot-client"; +import type { ChatSummary, ConnectionStatus } from "@/lib/types"; +import { ClientProvider } from "@/providers/ClientProvider"; + +const sessions: ChatSummary[] = ["a", "b"].map((suffix) => ({ + key: `websocket:nan311-${suffix}`, + channel: "websocket", + chatId: `nan311-${suffix}`, + createdAt: null, + updatedAt: null, + preview: "", +})); + +// Synthetic backend-boundary reproduction, not an original user recording. +export function HistoryHydrationFixture() { + const [client] = useState(() => new NanobotClient({ + url: `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/nan311-fixture-ws`, + reconnect: false, + })); + const [status, setStatus] = useState("idle"); + const [session, setSession] = useState(sessions[0]!); + const receiptRef = useRef(null); + + useEffect(() => { + // Observers provide a wire-delivery barrier even when painting is paused. + // They never consume transcript replay, project events, or supply body rows. + const observers = sessions.map(({ chatId }) => client.onChat(chatId, (event) => { + if (!receiptRef.current) return; + const sequence = "turn_seq" in event ? event.turn_seq ?? "-" : "-"; + const turn = "turn_id" in event ? event.turn_id ?? "-" : "-"; + receiptRef.current.textContent = `${chatId}/${turn}/${event.event}/${sequence}`; + })); + const unsubscribe = client.onStatus(setStatus); + client.connect(); + return () => { + observers.forEach((dispose) => dispose()); + unsubscribe(); + client.close(); + }; + }, [client]); + + return +
+
+

Synthetic NAN-311 history hydration fixture — not a user recording.

+ + {status} + {session.chatId} + Awaiting frame +
+ {status === "open" && {}} settingsSnapshot={settings} + />} +
+
; +} diff --git a/webui/browser/history-hydration.spec.ts b/webui/browser/history-hydration.spec.ts new file mode 100644 index 000000000..007a84b3b --- /dev/null +++ b/webui/browser/history-hydration.spec.ts @@ -0,0 +1,293 @@ +import { expect, test, type Locator, type Page, type Route, type WebSocketRoute } from "@playwright/test"; + +import type { InboundEvent, ThreadProjectionEvent, UITurnPhase, WebuiThreadPersistedPayload } from "../src/lib/types"; + +// Controlled synthetic backend traffic, not a replay of an original user recording. +// Every body assertion goes through the real socket/client/provider/ThreadShell path. +const A = "nan311-a"; +const B = "nan311-b"; +const TURN = "nan311-active-turn"; +const STARTED_AT = Date.parse("2026-10-21T00:00:00Z") / 1000; +const LIVE = "Live answer from the controlled wire"; +const EARLY = "Independent closed segment before the live answer."; + +function at(turn: string, sequence: number, phase: UITurnPhase, chatId = A) { + return { chat_id: chatId, turn_id: turn, turn_seq: sequence, turn_phase: phase }; +} + +function input(turn: string, text: string, chatId = A): ThreadProjectionEvent { + return { ...at(turn, 0, "user", chatId), event: "user_message", text, starts_turn: true, + active_turn_id: turn, started_at: STARTED_AT, created_at_ms: STARTED_AT * 1000 }; +} + +function delta(sequence: number, text: string, streamId = "live-wire"): ThreadProjectionEvent { + return { ...at(TURN, sequence, "answer"), event: "delta", stream_id: streamId, text }; +} + +function end(sequence: number, text: string, streamId: string, merge = false): ThreadProjectionEvent { + return { ...at(TURN, sequence, "answer"), event: "stream_end", stream_id: streamId, text, + ...(merge ? { resuming: true, merge_next: true } : { resuming: true }) }; +} + +function closedTurn(turn: string, question: string, answer: string, chatId = A): ThreadProjectionEvent[] { + return [input(turn, question, chatId), + { ...at(turn, 1, "answer", chatId), event: "message", text: answer }, + { ...at(turn, 2, "complete", chatId), event: "turn_end" }]; +} + +function history(events: ThreadProjectionEvent[], options: { + before?: string; more?: boolean; offset?: number; active?: string; chatId?: string; +} = {}): WebuiThreadPersistedPayload { + return { + schemaVersion: 3, projection: "events", sessionKey: `websocket:${options.chatId ?? A}`, + events: events.map((event, index) => ({ ...event, + projection_id: `synthetic:${event.turn_id}:${event.event}:${event.turn_seq ?? index}`, + })), + completed_turn_ids: events.filter((event) => event.event === "turn_end").map((event) => event.turn_id!), + active_turn_id: options.active ?? null, has_pending_tool_calls: false, + page: { before_cursor: options.before ?? null, after_cursor: null, + has_more_before: options.more ?? false, has_more_after: false, + user_message_offset: options.offset ?? 0, loaded_event_count: events.length, + truncated_oversized_turn: false }, + }; +} + +function liveFirstHistory() { + return history([ + ...closedTurn("nan311-prefix-turn", "Historical prefix question", "Historical prefix answer."), + input(TURN, "Active synthetic question"), + end(2, EARLY, "early-wire"), + { ...at(TURN, 3, "activity"), event: "message", kind: "tool_hint", text: "Synthetic history checkpoint" }, + end(6, LIVE, "live-wire", true), + ], { before: "nan311-before-2", more: true, offset: 2, active: TURN }); +} + +interface HistoryRead { + chatId: string; + before: string | null; + after: string | null; + route: Route; +} + +async function installBackend(page: Page) { + const reads: HistoryRead[] = []; + const attached: string[] = []; + const unexpected: unknown[] = []; + const errors: string[] = []; + let socket: WebSocketRoute | undefined; + page.on("pageerror", (error) => errors.push(error.message)); + await page.route("**/api/commands", (route) => route.fulfill({ json: { commands: [] } })); + await page.route((url) => /^\/api\/sessions\/websocket:nan311-[ab]\/webui-thread$/.test(decodeURIComponent(url.pathname)), (route) => { + const url = new URL(route.request().url()); + reads.push({ chatId: decodeURIComponent(url.pathname.split("/")[3]!).slice("websocket:".length), + before: url.searchParams.get("before"), after: url.searchParams.get("after"), route }); + // Deliberately leave this request pending until the test releases this exact page. + }); + await page.routeWebSocket((url) => url.pathname === "/nan311-fixture-ws", (wire) => { + socket = wire; + wire.onMessage((raw) => { + const frame = JSON.parse(raw.toString()) as { type?: string; chat_id?: string }; + if (frame.type === "attach" && [A, B].includes(frame.chat_id ?? "")) { + attached.push(frame.chat_id!); + wire.send(JSON.stringify({ event: "attached", chat_id: frame.chat_id })); + } else unexpected.push(frame); + }); + wire.send(JSON.stringify({ event: "ready", chat_id: A, client_id: "nan311-synthetic-client" })); + }); + return { + reads, + async read(chatId = A, before: string | null = null, occurrence = 0) { + const matching = () => reads.filter((read) => read.chatId === chatId && read.before === before && read.after === null); + await expect.poll(() => matching().length, { message: `Awaiting controlled ${chatId} history before=${before}` }).toBeGreaterThan(occurrence); + return matching()[occurrence]!; + }, + async release(read: HistoryRead, payload: WebuiThreadPersistedPayload) { + await read.route.fulfill({ json: payload }); + }, + async send(event: InboundEvent) { + expect(socket, "The fixture must establish its genuine WebSocket before input").toBeDefined(); + socket!.send(JSON.stringify(event)); + const turn = "turn_id" in event ? event.turn_id ?? "-" : "-"; + const sequence = "turn_seq" in event ? event.turn_seq ?? "-" : "-"; + // The fixture's non-consuming observer acknowledges client dispatch, not a model installation. + await expect(page.getByLabel("Synthetic frame receipt")).toHaveText(`${"chat_id" in event ? event.chat_id : "-"}/${turn}/${event.event}/${sequence}`); + }, + async ready() { + await expect(page.getByLabel("Synthetic transport status")).toHaveText("open"); + await expect.poll(() => attached.includes(A)).toBe(true); + }, + healthy() { + expect(unexpected, "No unimplemented socket mutations should be needed by this fixture").toEqual([]); + expect(errors, "The real ThreadShell must not throw in the browser").toEqual([]); + }, + }; +} + +type Backend = Awaited>; + +async function openFixture(page: Page, width = 1440) { + await page.setViewportSize({ width, height: 900 }); + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.addInitScript(() => { + localStorage.setItem("nanobot.locale", "en"); + localStorage.setItem("nanobot_debug_ws", "0"); + }); + const backend = await installBackend(page); + await page.goto("/browser/fixture.html?case=history-hydration"); + await expect(page.getByText("Synthetic NAN-311 history hydration fixture — not a user recording.", { exact: true })).toBeVisible(); + await backend.ready(); + return { backend, body: page.getByTestId("thread-message-region") }; +} + +async function requestOlder(page: Page, backend: Backend, body: Locator, before: string) { + await body.hover(); + await page.mouse.wheel(0, -10_000); + await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeLessThanOrEqual(1); + // If the first wheel only reached the head, this second genuine wheel arms the boundary. + await page.mouse.wheel(0, -120); + const read = await backend.read(A, before); + await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeVisible(); + return read; +} + +async function expectBefore(body: Locator, first: string, second: string) { + const text = await body.innerText(); + expect(text.indexOf(first), `${first} must be in the rendered body`).toBeGreaterThanOrEqual(0); + expect(text.indexOf(second), `${second} must follow ${first}`).toBeGreaterThan(text.indexOf(first)); +} + +for (const width of [1440, 390]) { + test(`synthetic live-first latest admits its prefix without refresh, then prepends two cursor pages (${width}px)`, async ({ page }) => { + const { backend, body } = await openFixture(page, width); + const latest = await backend.read(); + await backend.send(input(TURN, "Active synthetic question")); + await backend.send(delta(5, LIVE)); + await expect(body.getByText(LIVE, { exact: true })).toBeVisible(); + await expect(body.getByText("Historical prefix question", { exact: true })).toHaveCount(0); + + await backend.release(latest, liveFirstHistory()); + await expect(body.getByText("Historical prefix question", { exact: true })).toBeVisible(); + await expect(body.getByText(EARLY, { exact: true })).toBeVisible(); + await expect(body.getByText(LIVE, { exact: true })).toHaveCount(1); + await expectBefore(body, "Historical prefix question", EARLY); + await expectBefore(body, EARLY, LIVE); + expect(backend.reads.filter((read) => read.before === null)).toHaveLength(1); + + const older = await requestOlder(page, backend, body, "nan311-before-2"); + await backend.release(older, history(closedTurn("nan311-older-turn", "Older page question", "Older page answer."), + { before: "nan311-before-1", more: true, offset: 1 })); + const olderQuestion = body.getByText("Older page question", { exact: true }); + await expect(olderQuestion).toBeVisible(); + await olderQuestion.scrollIntoViewIfNeeded(); + await expect(olderQuestion).toBeInViewport(); + await expectBefore(body, "Older page question", "Historical prefix question"); + + // Reaching the new head may already prefetch this cursor; keep its response held either way. + const earliest = await requestOlder(page, backend, body, "nan311-before-1"); + await backend.release(earliest, history(closedTurn("nan311-earliest-turn", "Earliest page question", "Earliest page answer."))); + const firstQuestion = body.getByText("Earliest page question", { exact: true }); + await expect(firstQuestion).toBeVisible(); + await firstQuestion.scrollIntoViewIfNeeded(); + await expect(firstQuestion).toBeInViewport(); + await expectBefore(body, "Earliest page question", "Older page question"); + + await backend.send(delta(7, " — fresh continuation")); + await expect(body.getByText(`${LIVE} — fresh continuation`, { exact: true })).toHaveCount(1); + await expect(body.getByText(LIVE, { exact: true })).toHaveCount(0); + expect(backend.reads.map((read) => read.before)).toEqual([null, "nan311-before-2", "nan311-before-1"]); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width); + backend.healthy(); + }); +} + +test("synthetic HTTP-first cumulative text suppresses delayed covered chunks but keeps the fresh continuation", async ({ page }) => { + const { backend, body } = await openFixture(page); + const latest = await backend.read(); + const canonical = "Canonical answer"; + await backend.release(latest, history([input(TURN, "HTTP-first question"), end(3, canonical, "resume-wire", true)], { active: TURN })); + await expect(body.getByText(canonical, { exact: true })).toBeVisible(); + + await backend.send(delta(1, "Canonical ", "resume-wire")); + await backend.send(delta(2, "answer", "resume-wire")); + await backend.send(delta(4, " plus fresh continuation", "resume-wire")); + // A normal control frame drains pending text; fresh text is a positive paint checkpoint. + await backend.send({ event: "goal_status", chat_id: A, turn_id: TURN, status: "running", started_at: STARTED_AT }); + const continued = `${canonical} plus fresh continuation`; + await expect(body.getByText(continued, { exact: true })).toHaveCount(1); + // A delayed cumulative end must not reset the now-newer foreground cursor either. + await backend.send(end(3, canonical, "resume-wire", true)); + await backend.send(delta(5, " after delayed end", "resume-wire")); + await expect(body.getByText(`${continued} after delayed end`, { exact: true })).toHaveCount(1); + await expect(body.getByText(canonical, { exact: true })).toHaveCount(0); + expect(backend.reads).toHaveLength(1); + backend.healthy(); +}); + +test("synthetic cache return retains unpainted chunks and the absent conversation's buffered wire tail", async ({ page }) => { + const { backend, body } = await openFixture(page); + const initial = history([input(TURN, "Cache question"), end(3, "Cache answer", "cache-wire", true)], { active: TURN }); + await backend.release(await backend.read(), initial); + await expect(body.getByText("Cache answer", { exact: true })).toBeVisible(); + await backend.send(delta(4, " painted", "cache-wire")); + await expect(body.getByText("Cache answer painted", { exact: true })).toBeVisible(); + + // Freeze the actual production paint throttle, not the transport or the model. + await page.clock.install({ time: new Date("2026-10-21T00:00:00Z") }); + await page.clock.pauseAt(new Date("2026-10-21T00:00:10Z")); + await backend.send(delta(5, " buffered", "cache-wire")); + await expect(body.getByText("Cache answer painted buffered", { exact: true })).toHaveCount(0); + // Dispatch the public navigation button without an actionability rAF while paint is frozen. + await page.getByRole("button", { name: "Conversation B", exact: true }).dispatchEvent("click"); + await expect(page.getByLabel("Synthetic active conversation")).toHaveText(B); + await backend.release(await backend.read(B), history(closedTurn("nan311-b-turn", "Other conversation question", "Other conversation answer.", B), { chatId: B })); + await expect(body.getByText("Other conversation answer.", { exact: true })).toBeVisible(); + await expect(body.getByText("Cache answer painted", { exact: true })).toHaveCount(0); + await backend.send(delta(6, " while-away", "cache-wire")); + + await page.getByRole("button", { name: "Conversation A", exact: true }).dispatchEvent("click"); + await expect(page.getByLabel("Synthetic active conversation")).toHaveText(A); + const revalidation = await backend.read(A, null, 1); + // Still-pending HTTP cannot heal a lost cache entry; the received unpainted tail must already be present. + await expect(body.getByText(/Cache answer painted buffered/)).toHaveCount(1); + await backend.send(delta(7, " returned", "cache-wire")); + await page.clock.resume(); + const restored = "Cache answer painted buffered while-away returned"; + await expect(body.getByText(restored, { exact: true })).toHaveCount(1); + + await backend.release(revalidation, history([ + ...closedTurn("nan311-return-prefix", "Return-only historical question", "Return-only historical prefix."), + ...initial.events, + ], { active: TURN })); + await expect(body.getByText("Return-only historical prefix.", { exact: true })).toBeVisible(); + await backend.send(delta(8, " after revalidation", "cache-wire")); + await expect(body.getByText(`${restored} after revalidation`, { exact: true })).toHaveCount(1); + await expectBefore(body, "Return-only historical prefix.", `${restored} after revalidation`); + expect(backend.reads.map((read) => read.chatId)).toEqual([A, B, A]); + backend.healthy(); +}); + +test("synthetic same-text independent segments in the active turn both appear before the unique live source", async ({ page }) => { + const { backend, body } = await openFixture(page); + const latest = await backend.read(); + const repeated = "Repeated independent segment."; + const foreground = "Unique foreground source"; + await backend.send(input(TURN, "Same-text segments question")); + await backend.send(delta(8, foreground)); + await expect(body.getByText(foreground, { exact: true })).toBeVisible(); + await backend.release(latest, history([ + input(TURN, "Same-text segments question"), + end(2, repeated, "independent-wire-a"), + { ...at(TURN, 3, "activity"), event: "message", kind: "tool_hint", text: "Synthetic boundary A" }, + end(5, repeated, "independent-wire-b"), + { ...at(TURN, 6, "activity"), event: "message", kind: "tool_hint", text: "Synthetic boundary B" }, + end(9, foreground, "live-wire", true), + ], { active: TURN })); + await expect(body.getByText(repeated, { exact: true })).toHaveCount(2); + for (const segment of await body.getByText(repeated, { exact: true }).all()) await expect(segment).toBeVisible(); + await expectBefore(body, repeated, foreground); + await backend.send(delta(10, " continues")); + await expect(body.getByText(`${foreground} continues`, { exact: true })).toHaveCount(1); + await expect(body.getByText(repeated, { exact: true })).toHaveCount(2); + expect(backend.reads).toHaveLength(1); + backend.healthy(); +}); diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index 6801fab30..dac7e9c9d 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -33,7 +33,6 @@ import { ThreadLoadingSkeleton } from "@/components/thread/ThreadLoadingSkeleton import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice"; import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport"; import { useNanobotStream, type SendAttachment, type SendOptions } from "@/hooks/useNanobotStream"; -import { useSessionHistory } from "@/hooks/useSessions"; import { useFilePreviewState, type FilePreviewState, type FilePreviewStore } from "@/hooks/useFilePreviewState"; import { ApiError, @@ -45,7 +44,6 @@ import { fetchSettings, fetchWorkspaces, fetchWorkspaceDirectories, - fetchWebuiThreadTraceDetail, listSlashCommands, } from "@/lib/api"; import { @@ -58,7 +56,7 @@ import { installedMcpPresetsFromPayload, isMcpPresetsPayload, } from "@/lib/mcp-preset-events"; -import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client"; +import type { StreamError } from "@/lib/nanobot-client"; import type { ChatSummary, FilePreviewPayload, @@ -75,49 +73,10 @@ import type { import { projectThreadEvents } from "@/lib/thread-event-projection"; import { projectWebuiThreadMessages } from "@/lib/thread-display-projection"; import { ThreadMessageCache } from "@/lib/thread-message-cache"; -import { copyThreadCheckpoint, createThreadCheckpoint, type ThreadCheckpoint } from "@/lib/thread-checkpoint"; -import { canonicalRunSnapshot, completedAssistantTurnIds } from "@/lib/canonical-run-snapshot"; import { providerDisplayLabel } from "@/lib/provider-brand"; import { cn } from "@/lib/utils"; import { useClient } from "@/providers/ClientProvider"; -type MessageShape = Pick; - -interface PendingCanonicalHydrate { - source: "initial" | "refresh"; - historyLineage: number; - historyVersion: number; - runGeneration: number; - uiBaseline: MessageShape[]; - uiLineage: number | null; - uiRevision: number; -} - -interface PendingHistoryLineageCommit { - lineage: number; - messages: UIMessage[]; -} - -interface PendingCanonicalCommit { - canonicalSnapshot: CanonicalRunSnapshot; - completedTurnIds: string[]; - expectedUiRevision: number; - historyLineage: number; - historyVersion: number; - hydrate: PendingCanonicalHydrate; - messages: UIMessage[]; - previousMessages: UIMessage[]; -} - -function sameMessageShape(a: MessageShape, b: MessageShape): boolean { - return ( - a.role === b.role - && (a.kind ?? "") === (b.kind ?? "") - && a.content === b.content - && (!a.turnId || !b.turnId || a.turnId === b.turnId) - ); -} - function latestComposerContextUsage(messages: UIMessage[]): ComposerContextUsage | null { for (let index = messages.length - 1; index >= 0; index -= 1) { const message = messages[index]; @@ -199,140 +158,6 @@ function recentComposerRoundUsage(messages: UIMessage[]): ComposerRoundUsage[] { return recent.reverse(); } -function snapshotPreservesMessage( - current: MessageShape, - candidate: MessageShape, - allowCompletedTurnReplacement: boolean, -): boolean { - if (sameMessageShape(current, candidate)) return true; - if ( - allowCompletedTurnReplacement - && current.role === "assistant" - && candidate.role === current.role - && (candidate.kind ?? "") === (current.kind ?? "") - && !!current.turnId - && candidate.turnId === current.turnId - ) { - return true; - } - return ( - current.role === "assistant" - && current.isStreaming === true - && candidate.role === current.role - && (candidate.kind ?? "") === (current.kind ?? "") - && (!current.turnId || !candidate.turnId || candidate.turnId === current.turnId) - && candidate.content.startsWith(current.content) - ); -} - -function durableMessageShape(message: UIMessage): MessageShape | null { - if (message.kind === "trace") return null; - if (message.role !== "user" && message.role !== "assistant") return null; - if (message.role === "assistant" && !message.content.trim() && !message.media?.length) { - return null; - } - return { - role: message.role, - kind: message.kind, - content: message.content, - isStreaming: message.isStreaming, - turnId: message.turnId, - }; -} - -function durableMessageShapes(messages: UIMessage[]): MessageShape[] { - return messages - .map(durableMessageShape) - .filter((message): message is MessageShape => message !== null); -} - -function preservesMessageShapes( - expected: MessageShape[], - candidates: MessageShape[], - allowCompletedTurnReplacement: boolean, -): boolean { - let cursor = 0; - let previousCandidate: MessageShape | null = null; - for (const message of expected) { - if ( - allowCompletedTurnReplacement - && previousCandidate?.role === "assistant" - && message.role === "assistant" - && !!message.turnId - && message.turnId === previousCandidate.turnId - ) { - // A delayed websocket delta can briefly create a second bubble after an - // HTTP completion snapshot. The completed replay is authoritative for - // that turn, so both local fragments may map to its single assistant row. - continue; - } - let found = false; - while (cursor < candidates.length) { - const candidate = candidates[cursor]; - cursor += 1; - if (snapshotPreservesMessage(message, candidate, allowCompletedTurnReplacement)) { - found = true; - previousCandidate = candidate; - break; - } - } - if (!found) return false; - } - return true; -} - -function preservesDurableMessages( - current: UIMessage[], - snapshot: UIMessage[], - allowCompletedTurnReplacement = false, -): boolean { - // Canonical history refreshes can race with live websocket messages after fork/send. - // Never accept a refreshed snapshot that drops a user/assistant message already shown. - const expected = durableMessageShapes(current); - if (expected.length === 0) return true; - return preservesMessageShapes( - expected, - durableMessageShapes(snapshot), - allowCompletedTurnReplacement, - ); -} - -function resetDropsPostRequestDurableTail( - baseline: MessageShape[], - current: UIMessage[], - snapshot: UIMessage[], -): boolean { - const currentDurable = durableMessageShapes(current); - let stablePrefixLength = 0; - while ( - stablePrefixLength < baseline.length - && stablePrefixLength < currentDurable.length - && sameMessageShape(baseline[stablePrefixLength], currentDurable[stablePrefixLength]) - ) { - stablePrefixLength += 1; - } - const postRequestTail = currentDurable.slice(stablePrefixLength); - if (postRequestTail.length === 0) return false; - return !preservesMessageShapes( - postRequestTail, - durableMessageShapes(snapshot), - true, - ); -} - -function isStaleThreadSnapshot( - current: UIMessage[], - snapshot: UIMessage[], - allowCompletedTurnReplacement = false, -): boolean { - if (current.length === 0) return false; - if (snapshot.length === 0) return true; - if (!preservesDurableMessages(current, snapshot, allowCompletedTurnReplacement)) return true; - if (snapshot.length >= current.length) return false; - if (allowCompletedTurnReplacement) return false; - return snapshot.every((message, index) => sameMessageShape(current[index], message)); -} - function latestActiveTurnId(messages: UIMessage[], runStartedAt: number | null): string | null { for (let index = messages.length - 1; index >= 0; index -= 1) { const message = messages[index]; @@ -363,122 +188,6 @@ function hasInlineDeliveryError( )); } -function replaceCanonicalCompletedTurns( - current: UIMessage[], - canonical: UIMessage[], - completedTurnIds: readonly string[], -): UIMessage[] { - const completed = new Set(completedTurnIds); - const represented = new Set(canonical.flatMap((message) => ( - message.turnId && completed.has(message.turnId) ? [message.turnId] : [] - ))); - if (!current.some((message) => message.turnId && represented.has(message.turnId))) { - return current; - } - const retained: UIMessage[] = []; - const originalPositions = new Map(); - for (const message of current) { - if (message.turnId && represented.has(message.turnId)) { - if (!originalPositions.has(message.turnId)) { - originalPositions.set(message.turnId, retained.length); - } - } else { - retained.push(message); - } - } - // Supplemental inputs may have their own turn identity between two answer - // segments. Match those retained rows as anchors so completed rows keep the - // canonical chronology instead of being grouped at the first turn row. - type AnchorQueue = { indices: number[]; offset: number }; - type ShapeAnchors = { - all: AnchorQueue; - byTurnId: Map; - }; - const anchorIndex = new Map>(); - for (let index = 0; index < retained.length; index += 1) { - const message = retained[index]; - const shape = JSON.stringify([message.role, message.kind ?? ""]); - let byContent = anchorIndex.get(shape); - if (!byContent) { - byContent = new Map(); - anchorIndex.set(shape, byContent); - } - let positions = byContent.get(message.content); - if (!positions) { - positions = { - all: { indices: [], offset: 0 }, - byTurnId: new Map(), - }; - byContent.set(message.content, positions); - } - positions.all.indices.push(index); - const turnId = message.turnId || undefined; - const queue = positions.byTurnId.get(turnId) ?? { indices: [], offset: 0 }; - queue.indices.push(index); - positions.byTurnId.set(turnId, queue); - } - let cursor = 0; - let fallbackBoundary = 0; - const firstAnchor = (queue: AnchorQueue | undefined, minimumIndex: number): number => { - if (!queue) return retained.length; - while (queue.offset < queue.indices.length && queue.indices[queue.offset] < minimumIndex) { - queue.offset += 1; - } - return queue.indices[queue.offset] ?? retained.length; - }; - const anchors = canonical.map((message) => { - if (message.turnId && represented.has(message.turnId)) { - // Keep anonymous matches after this turn's retained pagination prefix. - fallbackBoundary = Math.max(fallbackBoundary, originalPositions.get(message.turnId) ?? 0); - return -1; - } - const positions = anchorIndex - .get(JSON.stringify([message.role, message.kind ?? ""])) - ?.get(message.content); - const exactIndex = message.turnId - ? firstAnchor(positions?.byTurnId.get(message.turnId), cursor) - : retained.length; - const index = exactIndex < retained.length - ? exactIndex - : firstAnchor( - message.turnId ? positions?.byTurnId.get(undefined) : positions?.all, - Math.max(cursor, fallbackBoundary), - ); - if (index === retained.length) return -1; - cursor = index + 1; - return index; - }); - const nextAnchors = new Array(anchors.length); - let nextAnchor: number | undefined; - for (let index = anchors.length - 1; index >= 0; index -= 1) { - nextAnchors[index] = nextAnchor; - if (anchors[index] >= 0) nextAnchor = anchors[index]; - } - const insertions = new Map(); - let precedingAnchor = 0; - let previousInsertionPosition = 0; - for (let index = 0; index < canonical.length; index += 1) { - if (anchors[index] >= 0) precedingAnchor = anchors[index] + 1; - const message = canonical[index]; - if (!message.turnId || !represented.has(message.turnId)) continue; - const position = Math.max( - previousInsertionPosition, - nextAnchors[index] ?? Math.max( - precedingAnchor, - originalPositions.get(message.turnId) ?? precedingAnchor, - ), - ); - previousInsertionPosition = position; - const rows = insertions.get(position) ?? []; - rows.push(message); - insertions.set(position, rows); - } - return retained.flatMap((message, index) => [ - ...insertions.get(index) ?? [], - message, - ]).concat(insertions.get(retained.length) ?? []); -} - const FILE_PREVIEW_DEFAULT_WIDTH = 544; const FILE_PREVIEW_MIN_WIDTH = 360; const FILE_PREVIEW_MAX_WIDTH = 860; @@ -782,25 +491,6 @@ export function ThreadShell({ () => sessions.filter((candidate) => candidate.key !== historyKey), [historyKey, sessions], ); - const { - messages: historical, - loading, - error: historyError, - loadingOlder, - olderError, - loadOlder, - hasMoreBefore, - userMessageOffset, - hasPendingToolCalls, - completedTurnIds, - completionIdsProvided, - continuity: historyContinuity, - lineage: historyLineage, - activeTurnId: historyActiveTurnId, - refresh: refreshHistory, - version: historyVersion, - forkBoundaryMessageCount, - } = useSessionHistory(historyKey); const { client, getToken, ingressLimits, modelName, token, webuiCapabilities } = useClient(); const favoriteWorkspaceProject = useCallback( async (path: string, pinned: boolean) => { @@ -884,37 +574,12 @@ export function ThreadShell({ )); const messageCacheRef = useRef(messageCache ?? localMessageCacheRef.current); messageCacheRef.current = messageCache ?? localMessageCacheRef.current; - const pendingCanonicalHydrateRef = useRef>(new Map()); - const pendingCanonicalCommitRef = useRef>(new Map()); - const pendingHistoryLineageCommitRef = useRef>( - new Map(), - ); - const completedCanonicalHydrateVersionRef = useRef>(new Map()); - const committedHistoryLineageRef = useRef>(new Map()); const sessionKeyByChatIdRef = useRef>(new Map()); - const traceDetailRequestsRef = useRef>>(new Map()); - const activeHistoryKeyRef = useRef(historyKey); - activeHistoryKeyRef.current = historyKey; - const currentUiMessagesRef = useRef(null); - const uiRevisionRef = useRef(0); - const olderPageStartRef = useRef<{ historyKey: string; client: typeof client; visibleFirstId: string | null } | null>(null); - const showTemporaryChatControl = - !hideHeader && !session && !loading && !!onTemporaryChatEnabledChange; - - const initial = useMemo(() => { - const cached = chatId ? messageCacheRef.current.get(chatId) : undefined; - return cached - ? copyThreadCheckpoint(cached, replaceCanonicalCompletedTurns(cached.projection.messages, historical, completedTurnIds)) - : createThreadCheckpoint(historical); - }, [chatId, completedTurnIds, historical]); const handleTurnEnd = useCallback(() => { if (chatId) activeViewportTurnByChatIdRef.current.delete(chatId); setSubmittedViewportTurnId(null); onTurnEnd?.(); }, [chatId, onTurnEnd]); - const handleStreamDetach = useCallback((checkpoint: ThreadCheckpoint) => { - if (chatId) messageCacheRef.current.set(chatId, checkpoint); - }, [chatId]); const { messages, messagesReady, @@ -928,104 +593,46 @@ export function ThreadShell({ send, transcribeAudio, stop, - reconcileTurnComplete, - setMessages, - getCheckpoint, + history: { + loading, + error: historyError, + loadingOlder, + olderError, + hasMoreBefore, + userMessageOffset, + hasPendingToolCalls, + completedTurnIds, + activeTurnId: historyActiveTurnId, + version: historyVersion, + forkBoundaryMessageCount, + }, + refreshHistory, + loadOlder, + loadTraceDetails: loadBodyTraceDetails, streamError, dismissStreamError, } = useNanobotStream( - chatId, initial.projection.messages, hasPendingToolCalls, handleTurnEnd, handleStreamDetach, completedTurnIds, initial, + chatId, undefined, false, handleTurnEnd, undefined, undefined, + { key: historyKey, cache: messageCacheRef.current }, ); const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]); - const normalizedHistory = useMemo(() => projectWebuiThreadMessages(historical), [historical]); - // The response can arrive one commit before its messages reach the viewport. - const initialHistoryLoading = loading || (normalizedHistory.length > 0 && displayMessages.length === 0); + const initialHistoryLoading = loading; + const showTemporaryChatControl = + !hideHeader && !session && !loading && !!onTemporaryChatEnabledChange; const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages); const updateNavigationMessages = promptNavigation.updateMessages; - const olderPageProjectionPending = Boolean( - olderPageStartRef.current?.historyKey === historyKey - && olderPageStartRef.current.client === client - && !loadingOlder - && !olderError - && normalizedHistory[0]?.id !== olderPageStartRef.current.visibleFirstId - && displayMessages[0]?.id !== normalizedHistory[0]?.id, - ); - useLayoutEffect(() => { - const pending = olderPageStartRef.current; - if (pending && (pending.historyKey !== historyKey || pending.client !== client)) { - olderPageStartRef.current = null; - } - if (!historyKey) { - olderPageStartRef.current = null; - } else if (loadingOlder) { - // The request may finish before this shell commits the rendered projection. - if (!olderPageStartRef.current) { - olderPageStartRef.current = { - historyKey, - client, - visibleFirstId: normalizedHistory[0]?.id ?? null, - }; - } - } else if (olderError || !olderPageProjectionPending) { - olderPageStartRef.current = null; - } - }, [client, displayMessages, historyKey, loadingOlder, olderError, olderPageProjectionPending, normalizedHistory]); - const loadTraceDetails = useCallback(async (refs: string[]) => { - const requestKey = historyKey; - if (!requestKey) return; - const requests: Promise[] = []; - for (const ref of refs) { - const requestId = `${requestKey}:${ref}`; - const existing = traceDetailRequestsRef.current.get(requestId); - if (existing) { - requests.push(existing); - continue; - } - const request = fetchWebuiThreadTraceDetail(getToken(), requestKey, ref) - .then((detail) => { - if (activeHistoryKeyRef.current !== requestKey) return; - const projected = projectThreadEvents(detail.events); - const hydrate = (current: UIMessage[]) => current.flatMap((message) => { - if (message.traceDetail?.ref !== ref) return [message]; - return projected.map((replacement) => ({ - ...replacement, - activitySegmentId: message.activitySegmentId ?? replacement.activitySegmentId, - })); - }); - setMessages(hydrate); - updateNavigationMessages(hydrate); - }) - .catch((error: unknown) => { - if (activeHistoryKeyRef.current !== requestKey) return; - throw error; - }) - .finally(() => { - traceDetailRequestsRef.current.delete(requestId); - }); - traceDetailRequestsRef.current.set(requestId, request); - requests.push(request); + const details = await loadBodyTraceDetails(refs); + for (const detail of details) { + const projected = projectThreadEvents(detail.events); + updateNavigationMessages((current) => current.flatMap((message) => ( + message.traceDetail?.ref === detail.ref + ? projected.map((row) => ({ ...row, activitySegmentId: message.activitySegmentId })) + : [message] + ))); } - await Promise.all(requests); - }, [getToken, historyKey, setMessages, updateNavigationMessages]); - - useEffect(() => () => { - activeHistoryKeyRef.current = null; - }, []); - - useLayoutEffect(() => { - if (currentUiMessagesRef.current === messages) return; - currentUiMessagesRef.current = messages; - uiRevisionRef.current += 1; - if (!chatId) return; - const lineageCommit = pendingHistoryLineageCommitRef.current.get(chatId); - if (!lineageCommit) return; - pendingHistoryLineageCommitRef.current.delete(chatId); - if (lineageCommit.messages === messages) { - committedHistoryLineageRef.current.set(chatId, lineageCommit.lineage); - } - }, [chatId, messages]); + }, [loadBodyTraceDetails, updateNavigationMessages]); useEffect(() => { if (chatId && historyKey) sessionKeyByChatIdRef.current.set(chatId, historyKey); @@ -1282,231 +889,15 @@ export function ThreadShell({ }); }, [client, refreshModelSettings]); - useEffect(() => { - if (!historyKey || !chatId) return; - pendingCanonicalHydrateRef.current.set(chatId, { - source: "initial", - historyLineage, - historyVersion, - runGeneration: client.getRunGeneration(chatId), - uiBaseline: durableMessageShapes(initial.projection.messages), - uiLineage: committedHistoryLineageRef.current.get(chatId) ?? null, - uiRevision: uiRevisionRef.current, - }); - // Capture the request's run generation when entering a conversation, before - // its history response can race with another send or running event. - }, [chatId, client, historyKey]); - - const canonicalCompletedTurnIds = useMemo(() => Array.from(new Set([ - ...completedTurnIds, - ...(!completionIdsProvided && !hasPendingToolCalls && historyActiveTurnId === null - ? completedAssistantTurnIds(normalizedHistory) - : []), - ])), [completedTurnIds, completionIdsProvided, hasPendingToolCalls, normalizedHistory, historyActiveTurnId]); - const lastRunTurnId = chatId ? client.getRunTurnId(chatId) : null; const completedRunTurnId = chatId && lastRunTurnId && client.isRunCompleted(chatId, lastRunTurnId) ? lastRunTurnId : null; const queueCompletedTurnIds = useMemo(() => { - const canonical = hasPendingToolCalls ? [] : canonicalCompletedTurnIds; + const canonical = hasPendingToolCalls ? [] : completedTurnIds; // Live terminal facts can release the queue before the history refresh finishes. return completedRunTurnId && !canonical.includes(completedRunTurnId) ? [...canonical, completedRunTurnId] : canonical; - }, [canonicalCompletedTurnIds, completedRunTurnId, hasPendingToolCalls]); - - useEffect(() => { - if (!historyKey || !chatId || loading) return; - const pendingCanonicalHydrate = pendingCanonicalHydrateRef.current.get(chatId); - const shouldReconcileRun = ( - pendingCanonicalHydrate !== undefined - && historyVersion > pendingCanonicalHydrate.historyVersion - && !hasPendingToolCalls - && ( - pendingCanonicalHydrate.source === "refresh" - || ( - (historical.length > 0 || completedTurnIds.length > 0) - && (isStreaming || runStartedAt !== null || client.hasUnsettledRun(chatId)) - ) - ) - ); - // Completion is a fact about a turn, even when a newer local turn prevents - // this snapshot from settling the conversation's current run. - client.fenceCanonicalCompletedTurns(chatId, canonicalCompletedTurnIds); - const keepLiveMessages = (current: UIMessage[]) => { - const reconciled = projectWebuiThreadMessages( - replaceCanonicalCompletedTurns(current, normalizedHistory, canonicalCompletedTurnIds), - ); - const firstId = reconciled[0]?.id; - const prefixLength = normalizedHistory.findIndex((message) => message.id === firstId); - return prefixLength > 0 - ? [...normalizedHistory.slice(0, prefixLength), ...reconciled] - : reconciled; - }; - if (shouldReconcileRun && pendingCanonicalHydrate) { - const authoritativeReset = ( - pendingCanonicalHydrate.uiLineage !== null - && historyLineage !== pendingCanonicalHydrate.uiLineage - && ( - historyContinuity === "reset" - || ( - pendingCanonicalHydrate.source === "refresh" - && historyContinuity === "overlap" - && historyLineage === pendingCanonicalHydrate.historyLineage - ) - ) - ); - const responseUiRevision = uiRevisionRef.current; - const resetDropsRenderedTail = ( - authoritativeReset - && responseUiRevision !== pendingCanonicalHydrate.uiRevision - && resetDropsPostRequestDurableTail( - pendingCanonicalHydrate.uiBaseline, - messages, - normalizedHistory, - ) - ); - if ( - authoritativeReset - ? resetDropsRenderedTail - : isStaleThreadSnapshot(messages, normalizedHistory, true) - ) { - setMessages((current) => keepLiveMessages(current)); - return; - } - const canonicalSnapshot = canonicalRunSnapshot( - normalizedHistory, - hasPendingToolCalls, - historyActiveTurnId, - completionIdsProvided, - ); - if (!client.canReconcileCanonicalCompletion( - chatId, - pendingCanonicalHydrate.runGeneration, - canonicalCompletedTurnIds, - canonicalSnapshot, - )) { - setMessages((current) => keepLiveMessages(current)); - return; - } - pendingCanonicalCommitRef.current.set(chatId, { - canonicalSnapshot, - completedTurnIds: canonicalCompletedTurnIds, - expectedUiRevision: responseUiRevision + 1, - historyLineage, - historyVersion, - hydrate: pendingCanonicalHydrate, - messages: normalizedHistory, - previousMessages: keepLiveMessages(messages), - }); - setMessages((current) => { - if (current !== messages) return current; - if ( - authoritativeReset - ? resetDropsRenderedTail - : isStaleThreadSnapshot(current, normalizedHistory, true) - ) { - return keepLiveMessages(current); - } - return normalizedHistory; - }); - return; - } - const reconciledMessages = keepLiveMessages(messages); - const adoptsNormalizedHistory = ( - (!hasPendingToolCalls || messages.length === 0) - && !isStaleThreadSnapshot(reconciledMessages, normalizedHistory, true) - ); - if (adoptsNormalizedHistory) { - pendingHistoryLineageCommitRef.current.set(chatId, { - lineage: historyLineage, - messages: normalizedHistory, - }); - } - setMessages((current) => { - const reconciled = keepLiveMessages(current); - return (hasPendingToolCalls && current.length > 0) - || isStaleThreadSnapshot(reconciled, normalizedHistory, true) - ? reconciled - : normalizedHistory; - }); - }, [ - loading, - chatId, - client, - completedTurnIds, - canonicalCompletedTurnIds, - completionIdsProvided, - historical, - normalizedHistory, - historyVersion, - historyContinuity, - historyLineage, - historyActiveTurnId, - hasPendingToolCalls, - historyKey, - ]); - - useLayoutEffect(() => { - if (!historyKey || !chatId) return; - const commit = pendingCanonicalCommitRef.current.get(chatId); - if (!commit) return; - if ( - commit.historyVersion !== historyVersion - || commit.historyLineage !== historyLineage - || commit.messages !== messages - ) { - pendingCanonicalCommitRef.current.delete(chatId); - return; - } - if (pendingCanonicalHydrateRef.current.get(chatId) !== commit.hydrate) { - pendingCanonicalCommitRef.current.delete(chatId); - return; - } - if ( - uiRevisionRef.current !== commit.expectedUiRevision - || !client.reconcileCanonicalCompletion( - chatId, - commit.hydrate.runGeneration, - commit.completedTurnIds, - commit.canonicalSnapshot, - ) - ) { - pendingCanonicalCommitRef.current.delete(chatId); - const fallback = replaceCanonicalCompletedTurns( - messageCacheRef.current.get(chatId)?.projection.messages ?? commit.previousMessages, - commit.messages, - commit.completedTurnIds, - ); - messageCacheRef.current.set(chatId, copyThreadCheckpoint(getCheckpoint(), fallback)); - setMessages((current) => current === commit.messages ? fallback : current); - return; - } - pendingCanonicalHydrateRef.current.delete(chatId); - pendingCanonicalCommitRef.current.delete(chatId); - committedHistoryLineageRef.current.set(chatId, historyLineage); - completedCanonicalHydrateVersionRef.current.set(chatId, historyVersion); - }, [chatId, client, getCheckpoint, historyKey, historyLineage, historyVersion, messages, setMessages]); - - useEffect(() => { - if (!historyKey || !chatId || hasPendingToolCalls) return; - if (completedCanonicalHydrateVersionRef.current.get(chatId) !== historyVersion) return; - completedCanonicalHydrateVersionRef.current.delete(chatId); - reconcileTurnComplete(); - }, [chatId, hasPendingToolCalls, historyKey, historyVersion, messages, reconcileTurnComplete]); - - const refreshCanonicalHistory = useCallback(() => { - if (!historyKey || !chatId) return; - pendingCanonicalHydrateRef.current.set(chatId, { - source: "refresh", - historyLineage, - historyVersion, - runGeneration: client.getRunGeneration(chatId), - uiBaseline: durableMessageShapes(currentUiMessagesRef.current ?? []), - uiLineage: committedHistoryLineageRef.current.get(chatId) ?? null, - uiRevision: uiRevisionRef.current, - }); - refreshHistory(); - }, [chatId, client, historyKey, historyLineage, historyVersion, refreshHistory]); + }, [completedTurnIds, completedRunTurnId, hasPendingToolCalls]); useEffect(() => { if (!historyKey || !chatId) return; @@ -1516,9 +907,9 @@ export function ThreadShell({ // A turn-end thread refresh can arrive while the viewport is easing the // final layout change. User-driven scrolling already disables following, // so keep an active programmatic follow alive across canonical hydration. - refreshCanonicalHistory(); + refreshHistory(); }); - }, [chatId, client, historyKey, refreshCanonicalHistory]); + }, [chatId, client, historyKey, refreshHistory]); const wasPageHiddenRef = useRef(document.visibilityState === "hidden"); useEffect(() => { @@ -1538,7 +929,7 @@ export function ThreadShell({ ) { return; } - refreshCanonicalHistory(); + refreshHistory(); }; document.addEventListener("visibilitychange", refreshOnReturn); return () => document.removeEventListener("visibilitychange", refreshOnReturn); @@ -1549,7 +940,7 @@ export function ThreadShell({ historyKey, historyError, loading, - refreshCanonicalHistory, + refreshHistory, turnActive, ]); @@ -1560,20 +951,10 @@ export function ThreadShell({ refreshOnNextOpen = true; return; } - if (refreshOnNextOpen) refreshCanonicalHistory(); + if (refreshOnNextOpen) refreshHistory(); refreshOnNextOpen = false; }); - }, [client, refreshCanonicalHistory]); - - useEffect(() => { - if (chatId) return; - setMessages(projectWebuiThreadMessages(historical)); - }, [chatId, historical, setMessages]); - - useEffect(() => { - if (!chatId || !messagesReady || loading) return; - messageCacheRef.current.set(chatId, getCheckpoint()); - }, [chatId, getCheckpoint, loading, messages, messagesReady]); + }, [client, refreshHistory]); // The landing composer queues the first message while `new_chat` is in flight. // Only the chat created for that send may consume it; selecting another chat @@ -1850,8 +1231,6 @@ export function ThreadShell({ const forkedChatId = await onForkChat(chatId, beforeUserIndex); if (!forkedChatId) return; messageCacheRef.current.delete(forkedChatId); - pendingCanonicalHydrateRef.current.delete(forkedChatId); - completedCanonicalHydrateVersionRef.current.delete(forkedChatId); }, [chatId, onForkChat], ); @@ -2096,7 +1475,7 @@ export function ThreadShell({ slashCommands={availableSlashCommands} forkBoundaryMessageCount={forkBoundaryMessageCount} hasMoreBefore={hasMoreBefore} - loadingOlder={loadingOlder || olderPageProjectionPending} + loadingOlder={loadingOlder} olderError={olderError} userMessageOffset={userMessageOffset} onLoadOlder={loadOlder} diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 6b4e8c0b5..142223c01 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -1,22 +1,25 @@ import { acceptsCompactionPhase } from "../../../packages/client-events/notifications"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { copyThreadCheckpoint, createThreadCheckpoint, type ThreadCheckpoint } from "@/lib/thread-checkpoint"; import { useThreadVisibility } from "@/hooks/useThreadVisibility"; import { useClient } from "@/providers/ClientProvider"; import { hasPendingAgentActivity } from "@/lib/activity-timeline"; +import { ApiError, fetchWebuiThread, fetchWebuiThreadTraceDetail } from "@/lib/api"; +import { fetchLatestWebuiThread } from "@/lib/latest-thread-request"; +import { persistedCanonicalRunState } from "@/lib/canonical-run-snapshot"; +import { webuiThreadCache } from "@/lib/webui-thread-cache"; +import { ThreadTranscript, type ThreadPaging, type ThreadRead, type ThreadTranscriptSnapshot } from "@/lib/thread-transcript"; +import type { ThreadMessageCache } from "@/lib/thread-message-cache"; import type { StreamError } from "@/lib/nanobot-client"; import { clearThreadProjectionActivity, closeThreadProjectionAnswer, finalizeStreamedTurn, - projectThreadEvent, resetThreadProjectionCursor, turnFieldsFromEvent, } from "@/lib/thread-event-projection"; import type { ThreadProjectionEvent, - ThreadProjectionState, UIMessageTurnFields, } from "@/lib/thread-event-projection"; import { formatQuotedUserMessage } from "@/lib/user-message-quote"; @@ -46,12 +49,7 @@ const VISIBLE_STREAM_FLUSH_INTERVAL_MS = 50; const EMPTY_INITIAL_MESSAGES: UIMessage[] = []; const EMPTY_COMPLETED_TURN_IDS: readonly string[] = []; -/** - * Subscribe to a chat by ID. Returns the in-memory message list for the chat, - * a streaming flag, and a ``send`` function. Initial history must be seeded - * separately (e.g. via ``fetchWebuiThread``) since the server only replays - * live events. - */ +/** Own the received transcript, accepting fetched pages and live events together. */ /** Payload passed to ``send`` when the user attaches one or more files. * * ``media`` is handed to the wire client verbatim; ``preview`` powers the @@ -131,14 +129,21 @@ function appendProjectedSessionInput( return [...messages, row]; } +function createTranscript(messages: UIMessage[], saved: ThreadTranscriptSnapshot | undefined, historyKey: string | null) { + const owner = new ThreadTranscript(messages, saved); + // The first paint must not enter the welcome layout while history is pending. + owner.paging = { ...owner.paging, loading: !!historyKey && owner.paging.version === 0 }; + return owner; +} + export function useNanobotStream( chatId: string | null, initialMessages: UIMessage[] = EMPTY_INITIAL_MESSAGES, hasPendingToolCalls = false, onTurnEnd?: () => void, - onStreamDetach?: (checkpoint: ThreadCheckpoint) => void, + onStreamDetach?: (messages: UIMessage[]) => void, completedTurnIds: readonly string[] = EMPTY_COMPLETED_TURN_IDS, - initialCheckpoint?: ThreadCheckpoint, + history?: { key: string | null; cache?: ThreadMessageCache }, ): { messages: UIMessage[]; /** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */ @@ -160,11 +165,10 @@ export function useNanobotStream( ) => SubmittedTurn | null; transcribeAudio: (dataUrl: string, options?: { durationMs?: number }) => Promise; stop: () => void; - /** Mark an accepted canonical snapshot as the definitive end of the active turn. */ - reconcileTurnComplete: () => void; - setMessages: React.Dispatch>; - /** Flush received chunks and capture a resumable copy, independently of paint. */ - getCheckpoint: () => ThreadCheckpoint; + history: ThreadPaging; + refreshHistory: () => void; + loadOlder: () => Promise; + loadTraceDetails: (refs: string[]) => Promise>; /** Latest transport-level fault raised since the last ``dismissStreamError``. * ``null`` when there is nothing to show. */ streamError: StreamError | null; @@ -172,27 +176,32 @@ export function useNanobotStream( * notification or starts a fresh action). */ dismissStreamError: () => void; } { - const { client } = useClient(); + const { client, getToken } = useClient(); + const historyKey = history?.key ?? null; + const messageCache = history?.cache; + const [initialTranscript] = useState(() => createTranscript(initialMessages, + chatId ? messageCache?.get(chatId) : undefined, historyKey)); + const transcriptRef = useRef(initialTranscript); + const [historyState, setHistoryState] = useState(initialTranscript.paging); + const publishHistory = useCallback(() => setHistoryState(transcriptRef.current.paging), []); + const [refreshSeq, setRefreshSeq] = useState(0); + const refreshHistory = useCallback(() => setRefreshSeq((value) => value + 1), []); const threadVisible = useThreadVisibility(); const threadVisibleRef = useRef(threadVisible); threadVisibleRef.current = threadVisible; - const [initialState] = useState(() => initialCheckpoint - ? copyThreadCheckpoint(initialCheckpoint, initialMessages) - : createThreadCheckpoint(initialMessages)); - const projectionRef = useRef(initialState.projection); - const sideChannelTurnIdsRef = useRef(initialState.sideChannelTurnIds); const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null; - const [messages, setRenderedMessages] = useState(initialMessages); + const [messages, setRenderedMessages] = useState(initialTranscript.messages); const messagesRef = useRef(messages); // Keep received state ahead of React's batched render: navigation can unmount // this hook after a stream flush but before the queued render commits. const setMessages = useCallback>>((update) => { const next = typeof update === "function" ? update(messagesRef.current) : update; messagesRef.current = next; - projectionRef.current = { ...projectionRef.current, messages: next }; + transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: next }; setRenderedMessages(next); + setHistoryState(transcriptRef.current.paging); }, []); - const [messageOwnerChatId, setMessageOwnerChatId] = useState(chatId); + const [messageScope, setMessageScope] = useState({ chatId, historyKey, client }); /** If history ends in unfinished agent activity, keep the loading spinner alive. */ const initialStreaming = useMemo(() => { if (completedTurnIds.length === 0) return hasPendingAgentActivity(initialMessages); @@ -210,11 +219,13 @@ export function useNanobotStream( const [goalState, setGoalState] = useState(undefined); const [recoveryState, setRecoveryState] = useState(null); const [streamError, setStreamError] = useState(null); + const pendingStreamEventsRef = useRef([]); const streamFrameRef = useRef(null); const streamTimerRef = useRef(null); const lastStreamFlushRef = useRef(0); + const dismissStreamError = useCallback(() => setStreamError(null), []); const clearPendingStreamWork = useCallback(() => { @@ -232,16 +243,16 @@ export function useNanobotStream( const isSideChannelEvent = useCallback((ev: InboundEvent) => { const turnId = eventTurnId(ev); - return turnId !== undefined && sideChannelTurnIdsRef.current.has(turnId); + return turnId !== undefined && transcriptRef.current.sideChannelTurnIds.has(turnId); }, []); const clearActivitySegment = useCallback(() => { - projectionRef.current = clearThreadProjectionActivity(projectionRef.current); + transcriptRef.current.projection = clearThreadProjectionActivity(transcriptRef.current.projection); }, []); const closeActiveAssistantStream = useCallback(() => { - const hadActiveAssistant = projectionRef.current.activeAssistantId !== null; - projectionRef.current = closeThreadProjectionAnswer(projectionRef.current); + const hadActiveAssistant = transcriptRef.current.projection.activeAssistantId !== null; + transcriptRef.current.projection = closeThreadProjectionAnswer(transcriptRef.current.projection); return hadActiveAssistant; }, []); @@ -258,7 +269,7 @@ export function useNanobotStream( pendingStreamEventsRef.current = pendingStreamEventsRef.current.filter( (event) => event.turn.turnId !== rejectedTurnId, ); - sideChannelTurnIdsRef.current.delete(rejectedTurnId); + transcriptRef.current.sideChannelTurnIds.delete(rejectedTurnId); setMessages((prev) => { const rejectedRows = prev.filter((message) => message.turnId === rejectedTurnId); if (rejectedRows.length === 0) return prev; @@ -268,7 +279,7 @@ export function useNanobotStream( .map((message) => message.activitySegmentId) .filter((segmentId): segmentId is string => typeof segmentId === "string"), ); - const projection = projectionRef.current; + const projection = transcriptRef.current.projection; const closedAssistantIds = new Set(projection.closedAssistantIds); for (const id of rejectedIds) closedAssistantIds.delete(id); const nextMessages = prev.flatMap((message) => { @@ -280,7 +291,7 @@ export function useNanobotStream( deliveryErrorKind: err.kind, }]; }); - projectionRef.current = { + transcriptRef.current.projection = { ...projection, messages: nextMessages, activeAssistantId: projection.activeAssistantId @@ -297,6 +308,7 @@ export function useNanobotStream( ? null : projection.fileEditSegmentId, }; + transcriptRef.current.rejectTurn(rejectedTurnId); return nextMessages; }); @@ -308,8 +320,8 @@ export function useNanobotStream( setRunStartedAt(remainingStartedAt); setIsStreaming(hasRemainingRun); if (!hasRemainingRun) { - projectionRef.current = { - ...projectionRef.current, + transcriptRef.current.projection = { + ...transcriptRef.current.projection, suppressUntilTurnEnd: false, }; } @@ -319,21 +331,23 @@ export function useNanobotStream( const applyPendingStreamEvents = useCallback( (prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => { - let projection = { ...projectionRef.current, messages: prev }; + transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: prev }; for (let index = 0; index < events.length; index++) { const event = events[index]; const chunks = [event.text]; + const members = event.turn.turnSeq === undefined ? [] : [event.turn.turnSeq]; let turn = event.turn; while (index + 1 < events.length) { const nextEvent = events[index + 1]; if (nextEvent.kind !== event.kind - || nextEvent.streamId !== event.streamId || nextEvent.turn.turnId !== event.turn.turnId || nextEvent.turn.turnPhase !== event.turn.turnPhase + || nextEvent.streamId !== event.streamId || (nextEvent.kind === "delta" && event.kind === "delta" && (nextEvent.source !== event.source || JSON.stringify(nextEvent.responseSources) !== JSON.stringify(event.responseSources)))) break; chunks.push(nextEvent.text); + if (nextEvent.turn.turnSeq !== undefined) members.push(nextEvent.turn.turnSeq); turn = { ...turn, ...nextEvent.turn }; index++; } @@ -342,7 +356,6 @@ export function useNanobotStream( ? { event: "delta", chat_id: chatId ?? "", - stream_id: event.streamId, text, turn_id: turn.turnId, turn_phase: turn.turnPhase, @@ -353,20 +366,26 @@ export function useNanobotStream( : { event: "reasoning_delta", chat_id: chatId ?? "", - stream_id: event.streamId, text, turn_id: turn.turnId, turn_phase: turn.turnPhase, turn_seq: turn.turnSeq, }; - projection = projectThreadEvent(projection, projectedEvent, { - createId: () => crypto.randomUUID(), - now: Date.now(), - startSeq: event.turn.turnSeq, + projectedEvent.stream_id = event.streamId; + if (turn.turnId && members.length) { + const ranges: Array<[number, number]> = []; + for (const seq of members) { + const last = ranges[ranges.length - 1]; + if (last && last[1] + 1 === seq) last[1] = seq; + else ranges.push([seq, seq]); + } + projectedEvent.projection_receipts = [{ turn_id: turn.turnId, ranges }]; + } + transcriptRef.current.project(projectedEvent, { + createId: () => crypto.randomUUID(), now: Date.now(), startSeq: event.turn.turnSeq, }); } - projectionRef.current = projection; - return projection.messages; + return transcriptRef.current.messages; }, [chatId], ); @@ -386,26 +405,14 @@ export function useNanobotStream( pendingStreamEventsRef.current = []; setMessages((prev) => { const nextMessages = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev; - let projection = { ...projectionRef.current, messages: nextMessages }; - if (end) { - projection = projectThreadEvent(projection, end, { - createId: () => crypto.randomUUID(), - now: Date.now(), - }); - } - projectionRef.current = projection; - return projection.messages; + transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: nextMessages }; + if (end) transcriptRef.current.project(end, { + createId: () => crypto.randomUUID(), now: Date.now(), + }); + return transcriptRef.current.messages; }); }, [applyPendingStreamEvents, setMessages]); - const getCheckpoint = useCallback(() => { - flushPendingStreamEvents(); - return copyThreadCheckpoint({ - projection: projectionRef.current, - sideChannelTurnIds: sideChannelTurnIdsRef.current, - }); - }, [flushPendingStreamEvents]); - const schedulePendingStreamFlush = useCallback(function schedule() { if (streamFrameRef.current !== null || streamTimerRef.current !== null) return; if (document.visibilityState === "hidden" || !threadVisibleRef.current) { @@ -480,8 +487,8 @@ export function useNanobotStream( const settled = prev.map((message) => ( message.isStreaming ? { ...message, isStreaming: false } : message )); - projectionRef.current = resetThreadProjectionCursor( - projectionRef.current, + transcriptRef.current.projection = resetThreadProjectionCursor( + transcriptRef.current.projection, settled, ); return settled; @@ -496,11 +503,13 @@ export function useNanobotStream( // history response after the optimistic first message has already rendered. useEffect(() => { const restoredRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null; - setMessages(initialMessages); - setMessageOwnerChatId(chatId); + transcriptRef.current = createTranscript(initialMessages, chatId ? messageCache?.get(chatId) : undefined, historyKey); + setMessages(transcriptRef.current.messages); + setMessageScope({ chatId, historyKey, client }); setIsStreaming( initialStreaming || hasPendingToolCalls + || transcriptRef.current.paging.hasPendingToolCalls || restoredRunStartedAt !== null, ); setStreamError(null); @@ -508,14 +517,9 @@ export function useNanobotStream( setRetryStatus(null); setGoalState(chatId ? client.getGoalState(chatId) : undefined); setRecoveryState(null); - const restored = initialCheckpoint - ? copyThreadCheckpoint(initialCheckpoint, initialMessages) - : createThreadCheckpoint(initialMessages); - projectionRef.current = restored.projection; - sideChannelTurnIdsRef.current = restored.sideChannelTurnIds; clearPendingStreamWork(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [chatId, client, clearActivitySegment, clearPendingStreamWork, setMessages]); + }, [chatId, client, historyKey, clearActivitySegment, clearPendingStreamWork, setMessages]); useEffect(() => { if (hasPendingToolCalls) setIsStreaming(true); @@ -526,20 +530,131 @@ export function useNanobotStream( options?: { sideChannel?: boolean }, ) => { setMessages((prev) => { - const projection = projectThreadEvent( - { ...projectionRef.current, messages: prev }, - event, - { - createId: () => crypto.randomUUID(), - now: Date.now(), - sideChannel: options?.sideChannel, - }, - ); - projectionRef.current = projection; - return projection.messages; + transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: prev }; + return transcriptRef.current.project(event, { createId: () => crypto.randomUUID(), now: Date.now(), + sideChannel: options?.sideChannel }); }); }, [setMessages]); + const olderReadRef = useRef<{ + owner: ThreadTranscript; read: ThreadRead; controller: AbortController; + } | null>(null); + const cancelOlderRead = useCallback(() => { + const pending = olderReadRef.current; + if (!pending) return; + olderReadRef.current = null; + pending.controller.abort(); + pending.owner.finishRead(pending.read); + if (transcriptRef.current === pending.owner) publishHistory(); + }, [publishHistory]); + const latestReadOwnerRef = useRef(); + const detailRequestsRef = useRef(new Map>()); + + useEffect(() => { + if (!historyKey) return; + const owner = transcriptRef.current; + const controller = new AbortController(); + const generation = chatId ? client.getRunGeneration(chatId) : 0; + const read = owner.begin(latestReadOwnerRef.current === owner ? "latest" : "initial"); + latestReadOwnerRef.current = owner; + publishHistory(); + let disposed = false; + let superseded = false; + let publishing = false; + const install = (body: Awaited>, ownRead: boolean, seed = false) => { + if (disposed || (ownRead && superseded) || transcriptRef.current !== owner) return; + flushPendingStreamEvents(); + const decision = ownRead ? read : owner.begin(seed ? "initial" : "latest"); + const canonical = body ? persistedCanonicalRunState(body) : null; + const settle = chatId && canonical && !canonical.snapshot.hasPendingToolCalls + && client.canReconcileCanonicalCompletion(chatId, generation, canonical.completedTurnIds, canonical.snapshot); + const accepted = owner.accept(body, decision); + // Commit the received owner before cache listeners/ledger callbacks can reenter. + setMessages(owner.messages); + if (accepted && chatId) messageCache?.set(chatId, owner.save()); + if (ownRead) { + publishing = true; + if (body) webuiThreadCache.set(historyKey, body); + else webuiThreadCache.delete(historyKey); + publishing = false; + } + if (ownRead && chatId && canonical) { + if (accepted && settle && client.reconcileCanonicalCompletion(chatId, generation, + canonical.completedTurnIds, canonical.snapshot)) { + setIsStreaming(false); + setRunStartedAt(null); + setRetryStatus(null); + } else client.fenceCanonicalCompletedTurns(chatId, canonical.completedTurnIds); + } + if (accepted && owner.paging.hasPendingToolCalls && chatId + && !(owner.paging.activeTurnId && client.isRunCompleted(chatId, owner.paging.activeTurnId))) { + setIsStreaming(true); + } + }; + const cached = webuiThreadCache.get(historyKey); + if (cached && owner.paging.version === 0) install(cached, false, true); + const unsubscribe = webuiThreadCache.subscribe(historyKey, (body) => { + if (publishing) return; + superseded = true; + controller.abort(); + cancelOlderRead(); + install(body, false); + }); + void fetchLatestWebuiThread(client, getToken(), historyKey, controller.signal) + .then((body) => install(body, true)) + .catch((error: unknown) => { + if (disposed || superseded || controller.signal.aborted || transcriptRef.current !== owner) return; + if (error instanceof ApiError && error.status === 404) install(null, true); + else { owner.finishRead(read, (error as Error).message); publishHistory(); } + }); + return () => { disposed = true; controller.abort(); cancelOlderRead(); unsubscribe(); }; + }, [cancelOlderRead, chatId, client, flushPendingStreamEvents, getToken, historyKey, messageCache, publishHistory, refreshSeq, setMessages]); + + const loadOlder = useCallback(async () => { + const owner = transcriptRef.current; + const before = owner.paging.beforeCursor; + if (!historyKey || !before || !owner.paging.hasMoreBefore || owner.paging.loadingOlder) return; + const read = owner.begin("older"); + const controller = new AbortController(); + const operation = { owner, read, controller }; + olderReadRef.current = operation; + publishHistory(); + try { + const body = await fetchWebuiThread(getToken(), historyKey, { before, limit: 120, signal: controller.signal }); + if (olderReadRef.current !== operation || transcriptRef.current !== owner) return; + flushPendingStreamEvents(); + owner.accept(body, read); + setMessages(owner.messages); + } catch (error) { + if (olderReadRef.current === operation && transcriptRef.current === owner) { + owner.finishRead(read, (error as Error).message); + publishHistory(); + } + } finally { + if (olderReadRef.current === operation) olderReadRef.current = null; + } + }, [flushPendingStreamEvents, getToken, historyKey, publishHistory, setMessages]); + + const loadTraceDetails = useCallback(async (refs: string[]) => { + const owner = transcriptRef.current; + if (!historyKey) return []; + const details = await Promise.all(refs.map((ref) => { + const id = `${historyKey}:${ref}`; + const existing = detailRequestsRef.current.get(id); + if (existing) return existing; + const request = fetchWebuiThreadTraceDetail(getToken(), historyKey, ref).then((detail) => { + if (transcriptRef.current !== owner) return null; + flushPendingStreamEvents(); + owner.expandDetail(ref, detail.events); + setMessages(owner.messages); + return { ref, events: detail.events }; + }).finally(() => detailRequestsRef.current.delete(id)); + detailRequestsRef.current.set(id, request); + return request; + })); + return details.filter((detail) => detail !== null); + }, [flushPendingStreamEvents, getToken, historyKey, setMessages]); + useEffect(() => { if (!chatId) return; @@ -580,16 +695,18 @@ export function useNanobotStream( closeActiveAssistantStream(); clearActivitySegment(); setIsStreaming(true); - setMessages((prev) => appendProjectedSessionInput(prev, ev)); + setMessages((prev) => { + const next = appendProjectedSessionInput(prev, ev); + if (next !== prev) transcriptRef.current.registerInput(next[next.length - 1]); + return next; + }); return; } setMessages((prev) => { if (ev.turn_id && prev.some((message) => ( message.role === "user" && message.turnId === ev.turn_id ))) return prev; - return [ - ...prev, - { + const row: UIMessage = { id: crypto.randomUUID(), role: "user", content: ev.text, @@ -607,8 +724,9 @@ export function useNanobotStream( ...(ev.session_mentions?.length ? { sessionMentions: ev.session_mentions } : {}), - }, - ]; + }; + transcriptRef.current.registerInput(row); + return [...prev, row]; }); if (ev.active_turn_id || ev.starts_turn) { setIsStreaming(true); @@ -621,31 +739,8 @@ export function useNanobotStream( flushPendingStreamEvents(); closeActiveAssistantStream(); clearActivitySegment(); - const compaction = { - id: ev.compaction_id, - phase: ev.phase, - announce: true, - }; - setMessages((prev) => { - const id = `compaction-${ev.compaction_id}`; - const existing = prev.findIndex((message) => message.id === id); - if (!acceptsCompactionPhase(prev[existing]?.compaction?.phase, ev.phase)) return prev; - const next = { - id, - role: "assistant" as const, - content: "", - kind: "compaction" as const, - createdAt: Date.now(), - compaction, - ...turnFieldsFromEvent(ev, "activity"), - }; - if (existing < 0) return [...prev, next]; - return prev.map((message, index) => ( - index === existing - ? { ...next, createdAt: message.createdAt } - : message - )); - }); + const previous = transcriptRef.current.messages.find((row) => row.id === `compaction-${ev.compaction_id}`); + if (acceptsCompactionPhase(previous?.compaction?.phase, ev.phase)) applyProjectionEvent(ev); return; } if ( @@ -656,7 +751,7 @@ export function useNanobotStream( || ev.event === "stream_end" ) setRetryStatus(null); if (ev.event === "delta") { - if (projectionRef.current.suppressUntilTurnEnd) return; + if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return; const chunk = typeof ev.text === "string" ? ev.text : ""; if (!chunk) return; setIsStreaming(true); @@ -673,7 +768,7 @@ export function useNanobotStream( } if (ev.event === "reasoning_delta") { - if (projectionRef.current.suppressUntilTurnEnd) return; + if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return; const chunk = ev.text; if (!chunk) return; setIsStreaming(true); @@ -688,8 +783,9 @@ export function useNanobotStream( } if (ev.event === "stream_end") { + if (transcriptRef.current.represented(ev)) return; flushPendingStreamEvents(ev); - if (projectionRef.current.suppressUntilTurnEnd) return; + if (transcriptRef.current.projection.suppressUntilTurnEnd) return; if (ev.resuming) { setIsStreaming(true); return; @@ -704,7 +800,7 @@ export function useNanobotStream( flushPendingStreamEvents(); if (ev.event === "reasoning_end") { - if (projectionRef.current.suppressUntilTurnEnd) return; + if (transcriptRef.current.projection.suppressUntilTurnEnd) return; applyProjectionEvent(ev); return; } @@ -757,7 +853,7 @@ export function useNanobotStream( } if (ev.event === "turn_end") { - if (typeof ev.turn_id === "string") sideChannelTurnIdsRef.current.delete(ev.turn_id); + if (typeof ev.turn_id === "string") transcriptRef.current.sideChannelTurnIds.delete(ev.turn_id); if ("goal_state" in ev && ev.goal_state != null && typeof ev.goal_state === "object") { setGoalState(ev.goal_state); } @@ -860,7 +956,7 @@ export function useNanobotStream( if (ev.event === "message") { applyProjectionEvent(ev, { sideChannel: sideChannelEvent }); if (sideChannelEvent && typeof ev.turn_id === "string") { - sideChannelTurnIdsRef.current.delete(ev.turn_id); + transcriptRef.current.sideChannelTurnIds.delete(ev.turn_id); } return; } @@ -873,13 +969,20 @@ export function useNanobotStream( const unsub = client.onTranscript(chatId, handle); return () => { unsub(); - // Capture received state, including deltas waiting for a throttled paint. - const checkpoint = getCheckpoint(); - onStreamDetach?.(checkpoint); + // Navigation may happen before the throttled paint. Snapshot the pending + // deltas synchronously while they still belong to this subscription. + const pending = pendingStreamEventsRef.current; + const snapshot = pending.length > 0 + ? applyPendingStreamEvents(messagesRef.current, pending) + : messagesRef.current; + onStreamDetach?.(snapshot); + if (pending.length > 0) setMessages(snapshot); + messageCache?.set(chatId, transcriptRef.current.save()); clearPendingStreamWork(); }; }, [ applyProjectionEvent, + applyPendingStreamEvents, applyStreamError, chatId, closeActiveAssistantStream, @@ -890,9 +993,9 @@ export function useNanobotStream( isSideChannelEvent, onTurnEnd, onStreamDetach, + messageCache, schedulePendingStreamFlush, setMessages, - getCheckpoint, ]); const send = useCallback( @@ -917,10 +1020,10 @@ export function useNanobotStream( } const turnId = crypto.randomUUID(); const userMessageId = crypto.randomUUID(); - if (sideChannel) sideChannelTurnIdsRef.current.add(turnId); + if (sideChannel) transcriptRef.current.sideChannelTurnIds.add(turnId); const previews = hasAttachments ? images!.map((i) => i.preview) : undefined; setMessages((prev) => { - let projection = { ...projectionRef.current, messages: prev }; + let projection = { ...transcriptRef.current.projection, messages: prev }; if ((!sideChannel && !continueActiveTurn) || finalizeActiveTurn) { projection = resetThreadProjectionCursor(projection, prev); } else if (continueActiveTurn) { @@ -949,7 +1052,8 @@ export function useNanobotStream( : {}), }, ]; - projectionRef.current = { ...projection, messages: next }; + transcriptRef.current.projection = { ...projection, messages: next }; + transcriptRef.current.registerInput(next[next.length - 1]); return next; }); if (!sideChannel) setIsStreaming(true); @@ -982,7 +1086,7 @@ export function useNanobotStream( setRetryStatus(null); setMessages((prev) => { const settled = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m)); - projectionRef.current = resetThreadProjectionCursor(projectionRef.current, settled); + transcriptRef.current.projection = resetThreadProjectionCursor(transcriptRef.current.projection, settled); return settled; }); setRunStartedAt(null); @@ -990,14 +1094,6 @@ export function useNanobotStream( client.sendMessage(chatId, "/stop"); }, [chatId, clearActivitySegment, client, flushPendingStreamEvents, setMessages]); - const reconcileTurnComplete = useCallback(() => { - clearPendingStreamWork(); - projectionRef.current = resetThreadProjectionCursor(projectionRef.current, messagesRef.current); - setRunStartedAt(null); - setRetryStatus(null); - setIsStreaming(false); - }, [clearActivitySegment, clearPendingStreamWork]); - const transcribeAudio = useCallback( (dataUrl: string, options?: { durationMs?: number }) => client.transcribeAudio(dataUrl, options), @@ -1023,7 +1119,7 @@ export function useNanobotStream( return { messages, - messagesReady: messageOwnerChatId === chatId, + messagesReady: messageScope.chatId === chatId && messageScope.historyKey === historyKey && messageScope.client === client, isStreaming, runStartedAt, retryStatus, @@ -1034,9 +1130,10 @@ export function useNanobotStream( send, transcribeAudio, stop, - reconcileTurnComplete, - setMessages, - getCheckpoint, + history: historyState, + refreshHistory, + loadOlder, + loadTraceDetails, streamError, dismissStreamError, }; diff --git a/webui/src/hooks/useSessions.ts b/webui/src/hooks/useSessions.ts index e0e9258d7..bf5e27231 100644 --- a/webui/src/hooks/useSessions.ts +++ b/webui/src/hooks/useSessions.ts @@ -1,211 +1,24 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useClient } from "@/providers/ClientProvider"; +import { useNanobotStream } from "@/hooks/useNanobotStream"; import { ApiError, deleteSession as apiDeleteSession, fetchSessionAutomations, - fetchWebuiThread, listSessions, } from "@/lib/api"; -import { hasPendingAgentActivity } from "@/lib/activity-timeline"; -import { projectThreadEvents } from "@/lib/thread-event-projection"; import { webuiThreadCache } from "@/lib/webui-thread-cache"; -import { fetchLatestWebuiThread } from "@/lib/latest-thread-request"; import { readReloadSessions, writeReloadCache } from "@/lib/reload-cache"; import type { ChatSummary, SessionAutomationJob, SessionDeleteResult, - UIMessage, - WebuiThreadPersistedPayload, WorkspaceScopePayload, } from "@/lib/types"; -const EMPTY_MESSAGES: UIMessage[] = []; -const OLDER_HISTORY_PAGE_LIMIT = 120; const CHAT_CREATE_TIMEOUT_MS = 60_000; -function isAbortError(error: unknown): boolean { - return ( - typeof error === "object" - && error !== null - && "name" in error - && error.name === "AbortError" - ); -} - -export type SessionHistoryContinuity = "initial" | "overlap" | "reset"; - -function projectPersistedThread(body: WebuiThreadPersistedPayload | null): { - messages: UIMessage[]; - forkBoundaryMessageCount: number | null; -} { - const events = body?.events ?? []; - const messages = projectThreadEvents(events); - const boundaryIndex = body?.fork_boundary_event_index; - const forkBoundaryMessageCount = typeof boundaryIndex === "number" - && Number.isInteger(boundaryIndex) - && boundaryIndex >= 0 - && boundaryIndex <= events.length - ? projectThreadEvents(events.slice(0, boundaryIndex)).length - : null; - return { messages, forkBoundaryMessageCount }; -} - -function sameSemanticMessage(a: UIMessage, b: UIMessage): boolean { - return ( - a.role === b.role - && (a.kind ?? "") === (b.kind ?? "") - && a.content === b.content - && (!a.turnId || !b.turnId || a.turnId === b.turnId) - ); -} - -function longestSemanticOverlap(previous: UIMessage[], latest: UIMessage[]): number { - const maxOverlap = Math.min(previous.length, latest.length); - for (let overlap = maxOverlap; overlap > 0; overlap -= 1) { - const previousStart = previous.length - overlap; - let matches = true; - for (let index = 0; index < overlap; index += 1) { - if (!sameSemanticMessage(previous[previousStart + index], latest[index])) { - matches = false; - break; - } - } - if (matches) return overlap; - } - return 0; -} - -function mergeLatestHistory( - previous: UIMessage[], - latest: UIMessage[], - initial: boolean, -): { - continuity: SessionHistoryContinuity; - messages: UIMessage[]; - retainedPrefixLength: number; -} { - if (initial) { - return { - continuity: "initial", - messages: latest, - retainedPrefixLength: 0, - }; - } - const overlapLength = longestSemanticOverlap(previous, latest); - if (overlapLength === 0) { - return { - continuity: "reset", - messages: latest, - retainedPrefixLength: 0, - }; - } - const retainedPrefixLength = previous.length - overlapLength; - return { - continuity: "overlap", - messages: [...previous.slice(0, retainedPrefixLength), ...latest], - retainedPrefixLength, - }; -} - -function hasPendingToolCallsFromThread( - body: Awaited>, - messages: UIMessage[], -): boolean { - if (typeof body?.has_pending_tool_calls === "boolean") { - return body.has_pending_tool_calls; - } - return hasPendingAgentActivity(messages); -} - -function completedTurnIdsFromThread( - body: Awaited>, -): string[] { - if (Array.isArray(body?.completed_turn_ids)) { - return Array.from(new Set(body.completed_turn_ids.filter( - (turnId) => typeof turnId === "string" && turnId.length > 0, - ))); - } - if (body?.has_pending_tool_calls !== false || body.active_turn_id) return []; - return Array.from(new Set( - body.events.flatMap((event) => ( - event.event === "turn_end" && event.turn_id ? [event.turn_id] : [] - )), - )); -} - -interface SessionHistoryState { - key: string | null; - messages: UIMessage[]; - loading: boolean; - loadingOlder: boolean; - olderError: string | null; - error: string | null; - hasPendingToolCalls: boolean; - completedTurnIds: string[]; - completionIdsProvided: boolean; - forkBoundaryMessageCount: number | null; - beforeCursor: string | null; - hasMoreBefore: boolean; - userMessageOffset: number; - version: number; - continuity: SessionHistoryContinuity; - lineage: number; - activeTurnId: string | null; -} - -function emptyHistoryState(key: string | null, loading = false): SessionHistoryState { - return { - key, - messages: [], - loading, - loadingOlder: false, - olderError: null, - error: null, - hasPendingToolCalls: false, - completedTurnIds: [], - completionIdsProvided: false, - forkBoundaryMessageCount: null, - beforeCursor: null, - hasMoreBefore: false, - userMessageOffset: 0, - version: 0, - continuity: "initial", - lineage: 0, - activeTurnId: null, - }; -} - -function cachedHistoryState( - key: string, - body: WebuiThreadPersistedPayload, - version: number, -): SessionHistoryState { - const projected = projectPersistedThread(body); - const messages = projected.messages; - return { - key, - messages, - loading: false, - loadingOlder: false, - olderError: null, - error: null, - hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages), - completedTurnIds: completedTurnIdsFromThread(body), - completionIdsProvided: Array.isArray(body.completed_turn_ids), - forkBoundaryMessageCount: projected.forkBoundaryMessageCount, - beforeCursor: body.page?.before_cursor ?? null, - hasMoreBefore: body.page?.has_more_before === true, - userMessageOffset: Math.max(0, body.page?.user_message_offset ?? 0), - version, - continuity: "initial", - lineage: version, - activeTurnId: typeof body.active_turn_id === "string" ? body.active_turn_id : null, - }; -} - /** Sidebar state: fetches the full session list and exposes create / delete actions. */ export function useSessions(): { sessions: ChatSummary[]; @@ -392,329 +205,10 @@ export function useSessions(): { }; } -/** Lazy-load a session's on-disk messages the first time the UI displays it. */ -export function useSessionHistory(key: string | null): { - messages: UIMessage[]; - loading: boolean; - loadingOlder: boolean; - olderError: string | null; - error: string | null; - refresh: () => void; - loadOlder: () => Promise; - hasMoreBefore: boolean; - userMessageOffset: number; - version: number; - forkBoundaryMessageCount: number | null; - /** ``true`` when the server reports that the turn is still in flight. */ - hasPendingToolCalls: boolean; - /** Turn identities backed by explicit persisted completion events. */ - completedTurnIds: string[]; - /** A supplied list is authoritative even when empty (unfinished transcripts). */ - completionIdsProvided: boolean; - /** Relationship between the latest canonical page and its predecessor. */ - continuity: SessionHistoryContinuity; - /** Stable across overlapping latest pages; changes on initial load or reset. */ - lineage: number; - /** Exact active turn when supplied by a current gateway. */ - activeTurnId: string | null; -} { - const { client, getToken } = useClient(); - const loadingOlderRef = useRef(false); - const olderRequestAbortRef = useRef(null); - const historyVersionRef = useRef(0); - const [refreshSeq, setRefreshSeq] = useState(0); - const refresh = useCallback(() => { - setRefreshSeq((value) => value + 1); - }, []); - const [state, setState] = useState(() => { - if (!key) return emptyHistoryState(null); - const cached = webuiThreadCache.get(key); - if (!cached) return emptyHistoryState(key, true); - historyVersionRef.current = 1; - return cachedHistoryState(key, cached, historyVersionRef.current); - }); - - useEffect(() => () => { - olderRequestAbortRef.current?.abort(); - olderRequestAbortRef.current = null; - loadingOlderRef.current = false; - }, []); - - useEffect(() => { - if (!key) { - olderRequestAbortRef.current?.abort(); - olderRequestAbortRef.current = null; - loadingOlderRef.current = false; - setState(emptyHistoryState(null)); - return; - } - let cancelled = false; - const controller = new AbortController(); - olderRequestAbortRef.current?.abort(); - olderRequestAbortRef.current = null; - loadingOlderRef.current = false; - const cachedBody = webuiThreadCache.get(key); - const cachedVersion = cachedBody ? historyVersionRef.current + 1 : 0; - if (cachedBody) historyVersionRef.current = cachedVersion; - setState((prev) => prev.key === key - ? { - ...prev, - loading: cachedBody ? false : prev.messages.length === 0 && prev.lineage === 0, - loadingOlder: false, - error: null, - } - : cachedBody - ? cachedHistoryState(key, cachedBody, cachedVersion) - : emptyHistoryState(key, true)); - const adoptBody = (body: WebuiThreadPersistedPayload | null) => { - historyVersionRef.current += 1; - const responseVersion = historyVersionRef.current; - const completedTurnIds = completedTurnIdsFromThread(body); - const projected = projectPersistedThread(body); - const ui = projected.messages; - const hasPending = hasPendingToolCallsFromThread(body, ui); - const forkBoundary = projected.forkBoundaryMessageCount; - setState((prev) => { - const merged = prev.key === key - ? mergeLatestHistory(prev.messages, ui, prev.lineage === 0) - : mergeLatestHistory([], ui, true); - const retainedPrefix = merged.retainedPrefixLength > 0; - const retainedForkBoundary = ( - retainedPrefix - && prev.forkBoundaryMessageCount !== null - && prev.forkBoundaryMessageCount <= merged.retainedPrefixLength - ) - ? prev.forkBoundaryMessageCount - : null; - return { - key, - messages: merged.messages, - loading: false, - loadingOlder: false, - olderError: merged.continuity === "overlap" - && (retainedPrefix || prev.beforeCursor === body?.page?.before_cursor) - ? prev.olderError - : null, - error: null, - hasPendingToolCalls: hasPending, - completedTurnIds, - completionIdsProvided: Array.isArray(body?.completed_turn_ids), - forkBoundaryMessageCount: forkBoundary === null - ? retainedForkBoundary - : forkBoundary + merged.retainedPrefixLength, - beforeCursor: retainedPrefix - ? prev.beforeCursor - : body?.page?.before_cursor ?? null, - hasMoreBefore: retainedPrefix - ? prev.hasMoreBefore - : body?.page?.has_more_before === true, - userMessageOffset: retainedPrefix - ? prev.userMessageOffset - : Math.max(0, body?.page?.user_message_offset ?? 0), - version: responseVersion, - continuity: merged.continuity, - lineage: merged.continuity === "overlap" - ? prev.lineage - : responseVersion, - activeTurnId: typeof body?.active_turn_id === "string" - ? body.active_turn_id - : null, - }; - }); - }; - let publishingBody = false; - const unsubscribeCache = webuiThreadCache.subscribe(key, (body) => { - if (publishingBody) return; - // A reconnect read can finish before this thread's older HTTP request. - // Adopt that published page now and prevent the older response from - // overwriting its completed content or lifecycle facts. - cancelled = true; - controller.abort(); - olderRequestAbortRef.current?.abort(); - olderRequestAbortRef.current = null; - loadingOlderRef.current = false; - adoptBody(body); - }); - (async () => { - try { - const body = await fetchLatestWebuiThread(client, getToken(), key, controller.signal); - if (cancelled) return; - publishingBody = true; - if (body) webuiThreadCache.set(key, body); - else webuiThreadCache.delete(key); - publishingBody = false; - adoptBody(body); - } catch (e) { - if (cancelled || isAbortError(e)) return; - if (e instanceof ApiError && e.status === 404) { - webuiThreadCache.delete(key); - historyVersionRef.current += 1; - const responseVersion = historyVersionRef.current; - setState((prev) => { - const continuity = prev.key === key && prev.lineage > 0 - ? "reset" - : "initial"; - return { - ...emptyHistoryState(key), - version: responseVersion, - continuity, - lineage: responseVersion, - }; - }); - } else { - setState((prev) => prev.key === key && prev.messages.length > 0 - ? { ...prev, loading: false, error: (e as Error).message } - : { ...emptyHistoryState(key), error: (e as Error).message }); - } - } - })(); - return () => { - cancelled = true; - controller.abort(); - unsubscribeCache(); - }; - }, [client, getToken, key, refreshSeq]); - - const loadOlder = useCallback(async () => { - if (!key || loadingOlderRef.current) return; - const requestKey = key; - const requestLineage = state.key === requestKey ? state.lineage : 0; - const beforeCursor = state.key === requestKey ? state.beforeCursor : null; - if (!beforeCursor || !state.hasMoreBefore || requestLineage === 0) return; - const matchesRequest = (candidate: typeof state) => ( - candidate.key === requestKey - && candidate.lineage === requestLineage - && candidate.beforeCursor === beforeCursor - ); - loadingOlderRef.current = true; - const controller = new AbortController(); - olderRequestAbortRef.current = controller; - setState((prev) => matchesRequest(prev) - ? { ...prev, loadingOlder: true, olderError: null } - : prev); - try { - const body = await fetchWebuiThread(getToken(), requestKey, { - limit: OLDER_HISTORY_PAGE_LIMIT, - before: beforeCursor, - signal: controller.signal, - }); - setState((prev) => { - if (!matchesRequest(prev)) return prev; - const projected = projectPersistedThread(body); - if (!body || !projected.messages.length) { - return { - ...prev, - loadingOlder: false, - hasMoreBefore: false, - beforeCursor: null, - }; - } - const older = projected.messages; - const olderBoundary = projected.forkBoundaryMessageCount; - const shiftedBoundary = prev.forkBoundaryMessageCount === null - ? null - : prev.forkBoundaryMessageCount + older.length; - const nextMessages = [...older, ...prev.messages]; - // An older page cannot change the authoritative latest-turn lifecycle - // state or masquerade as a completed latest-page refresh. - return { - ...prev, - messages: nextMessages, - loadingOlder: false, - olderError: null, - forkBoundaryMessageCount: olderBoundary ?? shiftedBoundary, - beforeCursor: body.page?.before_cursor ?? null, - hasMoreBefore: body.page?.has_more_before === true, - userMessageOffset: Math.max(0, body.page?.user_message_offset ?? 0), - }; - }); - } catch (e) { - if (isAbortError(e)) return; - setState((prev) => matchesRequest(prev) - ? { - ...prev, - loadingOlder: false, - olderError: (e as Error).message || "Could not load earlier messages", - } - : prev); - } finally { - if (olderRequestAbortRef.current === controller) { - olderRequestAbortRef.current = null; - loadingOlderRef.current = false; - } - } - }, [ - key, - state.beforeCursor, - state.hasMoreBefore, - state.key, - state.lineage, - getToken, - ]); - - if (!key) { - return { - messages: EMPTY_MESSAGES, - loading: false, - loadingOlder: false, - olderError: null, - error: null, - refresh, - loadOlder, - hasMoreBefore: false, - userMessageOffset: 0, - version: 0, - forkBoundaryMessageCount: null, - hasPendingToolCalls: false, - completedTurnIds: [], - completionIdsProvided: false, - continuity: "initial", - lineage: 0, - activeTurnId: null, - }; - } - - // Even before the effect above commits its loading state, never surface the - // previous session's payload for a brand-new key. - if (state.key !== key) { - return { - messages: EMPTY_MESSAGES, - loading: true, - loadingOlder: false, - olderError: null, - error: null, - refresh, - loadOlder, - hasMoreBefore: false, - userMessageOffset: 0, - version: 0, - forkBoundaryMessageCount: null, - hasPendingToolCalls: false, - completedTurnIds: [], - completionIdsProvided: false, - continuity: "initial", - lineage: 0, - activeTurnId: null, - }; - } - - return { - messages: state.messages, - loading: state.loading, - loadingOlder: state.loadingOlder, - olderError: state.olderError, - error: state.error, - refresh, - loadOlder, - hasMoreBefore: state.hasMoreBefore, - userMessageOffset: state.userMessageOffset, - version: state.version, - forkBoundaryMessageCount: state.forkBoundaryMessageCount, - hasPendingToolCalls: state.hasPendingToolCalls, - completedTurnIds: state.completedTurnIds, - completionIdsProvided: state.completionIdsProvided, - continuity: state.continuity, - lineage: state.lineage, - activeTurnId: state.activeTurnId, - }; +/** Read-only history view backed by the conversation owner. */ +export function useSessionHistory(key: string | null) { + const { messages, history, refreshHistory, loadOlder } = useNanobotStream( + null, undefined, false, undefined, undefined, undefined, { key }, + ); + return { messages, ...history, refresh: refreshHistory, loadOlder }; } diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index 91a6ea904..2a397ba4b 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -316,7 +316,17 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent { if (!isRecord(value) || typeof value.event !== "string" || typeof value.chat_id !== "string") { throw new Error("Invalid WebUI thread event"); } - if (!hasValidProjectionMetadata(value)) { + if (!hasValidProjectionMetadata(value) + || (value.stream_id !== undefined && typeof value.stream_id !== "string") + || (value.projection_receipts !== undefined && ( + !Array.isArray(value.projection_receipts) + || !value.projection_receipts.every((receipt: unknown) => isRecord(receipt) + && typeof receipt.turn_id === "string" && receipt.turn_id.length > 0 + && Array.isArray(receipt.ranges) + && receipt.ranges.every((range: unknown) => Array.isArray(range) + && range.length === 2 && Number.isSafeInteger(range[0]) && range[0] >= 0 + && Number.isSafeInteger(range[1]) && range[1] >= range[0])) + ))) { throw new Error("Invalid WebUI thread event metadata"); } switch (value.event) { diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts index 06b3e2bb7..024555c20 100644 --- a/webui/src/lib/thread-event-projection.ts +++ b/webui/src/lib/thread-event-projection.ts @@ -34,6 +34,13 @@ export interface ThreadProjectionState { turnAliases: Map; } +export interface ThreadProjectionEffects { + /** Content targets, including cleaned trace rows removed by this event. */ + bodyWrites: Set; + /** Absorbed/replaced rows; an absorbed ID can also remain a body target. */ + consumed: Set; +} + export interface ThreadProjectionOptions { createId: () => string; now: number; @@ -41,6 +48,7 @@ export interface ThreadProjectionOptions { sideChannel?: boolean; /** First sequence of a coalesced batch; event.turn_seq is its last contribution. */ startSeq?: number; + effects?: ThreadProjectionEffects; } export function turnFieldsFromEvent( @@ -278,6 +286,7 @@ function stripCoveredFileEditToolHintsFromMessages( messages: UIMessage[], edits: UIFileEdit[], turn: UIMessageTurnFields, + effects?: ThreadProjectionEffects, ): UIMessage[] { if (edits.length === 0) return messages; let next = messages; @@ -288,8 +297,10 @@ function stripCoveredFileEditToolHintsFromMessages( if (!matchesTurn(candidate, turn)) continue; const cleaned = stripCoveredFileEditToolHints(candidate, edits); if (cleaned === candidate) continue; + effects?.bodyWrites.add(candidate.id); if (next === messages) next = [...messages]; if (traceMessageIsEmpty(cleaned)) { + effects?.consumed.add(candidate.id); next.splice(i, 1); } else { next[i] = cleaned; @@ -575,6 +586,7 @@ function appendAnswerText( state.activeAssistantId = merged.id; state.mergeReasoning = false; state.messages = replaceMessageAt(state.messages, targetIndex, merged); + options.effects?.bodyWrites.add(merged.id); } function attachProjectedReasoning( @@ -598,6 +610,7 @@ function attachProjectedReasoning( reasoningStreaming: event.event === "reasoning_delta" || target.reasoningStreaming, ...(!target.content ? positionedTurnFields(target, turn, options) : {}), }); + options.effects?.bodyWrites.add(target.id); return; } const activeAssistantBeforeContinuation = state.activeAssistantId; @@ -613,6 +626,7 @@ function attachProjectedReasoning( reasoningStreaming: true, ...(event.stream_id ? { reasoningStreamId: event.stream_id } : {}), }); + options.effects?.bodyWrites.add(target.id); return; } @@ -640,16 +654,18 @@ function attachProjectedReasoning( ...positionedTurnFields(candidate, turn, options), ...(event.stream_id ? { reasoningStreamId: event.stream_id } : {}), }); + options.effects?.bodyWrites.add(candidate.id); return; } break; } const activitySegmentId = ensureProjectionActivitySegment(state); + const id = projectionMessageId(event, options); state.messages = [ ...state.messages, { - id: projectionMessageId(event, options), + id, role: "assistant", content: "", isStreaming: true, @@ -661,6 +677,7 @@ function attachProjectedReasoning( createdAt: projectionCreatedAt(event, options), }, ]; + options.effects?.bodyWrites.add(id); } function absorbProjectedAssistantMessage( @@ -681,17 +698,21 @@ function absorbProjectedAssistantMessage( reasoningStreaming: false, }, ]; + options.effects?.consumed.add(last.id); + options.effects?.bodyWrites.add(last.id); return; } + const id = projectionMessageId(event, options); state.messages = [ ...state.messages, { - id: projectionMessageId(event, options), + id, role: "assistant", createdAt: projectionCreatedAt(event, options), ...message, }, ]; + options.effects?.bodyWrites.add(id); } function projectToolActivity( @@ -753,12 +774,14 @@ function projectToolActivity( ...positionedTurnFields(last, turn, options), }, ]; + options.effects?.bodyWrites.add(last.id); return; } + const id = projectionMessageId(event, options); state.messages = [ ...state.messages, { - id: projectionMessageId(event, options), + id, role: "tool", kind: "trace", content: lines[lines.length - 1], @@ -770,6 +793,7 @@ function projectToolActivity( createdAt: projectionCreatedAt(event, options), }, ]; + options.effects?.bodyWrites.add(id); } function projectFileEdits( @@ -789,7 +813,7 @@ function projectFileEdits( segmentId = detachedProjectionActivitySegment(state); state.fileEditSegmentId = segmentId; } - const base = stripCoveredFileEditToolHintsFromMessages(state.messages, normalized, turn); + const base = stripCoveredFileEditToolHintsFromMessages(state.messages, normalized, turn, options.effects); const targetIndex = findFileEditTraceIndex(base, segmentId, normalized); if (targetIndex !== null) { const target = base[targetIndex]; @@ -801,14 +825,16 @@ function projectFileEdits( activitySegmentId: segmentId, ...positionedTurnFields(target, turn, options), }); + options.effects?.bodyWrites.add(target.id); return; } segmentId = segmentId ?? detachedProjectionActivitySegment(state); if (opensPhase) state.fileEditSegmentId = segmentId; + const id = projectionMessageId(event, options); state.messages = [ ...base, { - id: projectionMessageId(event, options), + id, role: "tool", kind: "trace", content: "", @@ -819,6 +845,7 @@ function projectFileEdits( createdAt: projectionCreatedAt(event, options), }, ]; + options.effects?.bodyWrites.add(id); } /** Canonical UI-message reducer shared by WebSocket delivery and transcript replay. */ @@ -875,6 +902,7 @@ export function projectThreadEvent( row.images = media.map(({ url, name }) => ({ url, name })); } state.messages = [...state.messages, row]; + options.effects?.bodyWrites.add(row.id); return state; } @@ -926,6 +954,7 @@ export function projectThreadEvent( ...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}), createdAt: projectionCreatedAt(event, options), }]; + options.effects?.bodyWrites.add(id); targetIndex = state.messages.length - 1; } else if (targetIndex !== null && (typeof text === "string" || event.source || event.response_sources !== undefined)) { const target = state.messages[targetIndex]; @@ -937,6 +966,7 @@ export function projectThreadEvent( ...(event.source ? { source: event.source } : {}), ...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}), }); + if (typeof text === "string") options.effects?.bodyWrites.add(target.id); } if (wasClosed || wireClosed) return state; if (targetIndex !== null) state.activeAssistantId = state.messages[targetIndex].id; @@ -986,6 +1016,7 @@ export function projectThreadEvent( ...message, createdAt: state.messages[existing].createdAt, }); + options.effects?.bodyWrites.add(id); state.activitySegmentId = null; state.fileEditSegmentId = null; return state; @@ -1037,7 +1068,13 @@ export function projectThreadEvent( } const activeId = state.activeAssistantId; Object.assign(state, closeThreadProjectionAnswer(state)); - if (activeId) state.messages = state.messages.filter((message) => message.id !== activeId); + if (activeId) { + state.messages = state.messages.filter((message) => { + if (message.id !== activeId) return true; + options.effects?.consumed.add(message.id); + return false; + }); + } absorbProjectedAssistantMessage(state, event, projected, options); state.activitySegmentId = null; state.fileEditSegmentId = null; diff --git a/webui/src/lib/thread-message-cache.ts b/webui/src/lib/thread-message-cache.ts index 84095f12c..60cec0b68 100644 --- a/webui/src/lib/thread-message-cache.ts +++ b/webui/src/lib/thread-message-cache.ts @@ -1,8 +1,8 @@ -import type { ThreadCheckpoint } from "./thread-checkpoint"; +import type { ThreadTranscriptSnapshot } from "./thread-transcript"; import { MemoryLruCache } from "./memory-lru-cache"; /** Bounded replay cache; temporary chats remain pinned because they have no disk history. */ -export class ThreadMessageCache extends MemoryLruCache { +export class ThreadMessageCache extends MemoryLruCache { constructor( isPinned: (key: string) => boolean, diff --git a/webui/src/lib/thread-transcript.ts b/webui/src/lib/thread-transcript.ts new file mode 100644 index 000000000..61dd20127 --- /dev/null +++ b/webui/src/lib/thread-transcript.ts @@ -0,0 +1,625 @@ +import { + projectThreadEvent, + type ThreadProjectionEffects, + type ThreadProjectionState, +} from "./thread-event-projection"; +import { persistedCanonicalRunState } from "./canonical-run-snapshot"; +import { copyThreadCheckpoint, createThreadCheckpoint, type ThreadCheckpoint } from "./thread-checkpoint"; +import { hasPendingAgentActivity } from "./activity-timeline"; +import type { ThreadProjectionEvent, UIMessage, WebuiThreadPersistedPayload } from "./types"; + +type Ranges = Array<[number, number]>; +type Members = Map; +interface TextSource { + turn: string; + phase: "answer" | "reasoning"; + stream: string; + after: number | null; + through: number; + end: number | null; + snapshot: boolean; + members: Ranges; +} +interface Unit { + rows: Set; + sources: Set; + members: Members; + text: TextSource[]; + introduced: number; + order: number; + received: number; +} +export interface ThreadPaging { + loading: boolean; + loadingOlder: boolean; + error: string | null; + olderError: string | null; + beforeCursor: string | null; + hasMoreBefore: boolean; + userMessageOffset: number; + forkBoundaryMessageCount: number | null; + truncated: boolean; + version: number; + lineage: number; + hasPendingToolCalls: boolean; + completedTurnIds: string[]; + completionIdsProvided: boolean; + activeTurnId: string | null; +} +export interface ThreadRead { + kind: "initial" | "latest" | "older"; + revision: number; + lineage: number; + before: string | null; + empty: boolean; +} +export interface ThreadTranscriptSnapshot extends ThreadCheckpoint { + units: Unit[]; + installed: Members; + textCoverage: TextSource[]; + boundaries: Map; + knownTurns: Set; + paging: ThreadPaging; + revision: number; +} + +function addRange(ranges: Ranges, first: number, last = first): void { + let start = first; + let end = last; + let index = 0; + while (index < ranges.length && ranges[index][1] + 1 < start) index++; + const from = index; + while (index < ranges.length && ranges[index][0] <= end + 1) { + start = Math.min(start, ranges[index][0]); + end = Math.max(end, ranges[index][1]); + index++; + } + ranges.splice(from, index - from, [start, end]); +} +function contains(ranges: Ranges | undefined, seq: number): boolean { + return ranges?.some(([first, last]) => first <= seq && seq <= last) === true; +} +function mergeMembers(target: Members, source: Members): void { + for (const [turn, ranges] of source) { + const existing = target.get(turn) ?? []; + for (const [first, last] of ranges) addRange(existing, first, last); + target.set(turn, existing); + } +} +function copyMembers(value: Members): Members { + return new Map(Array.from(value, ([key, ranges]) => [key, ranges.map(([a, b]) => [a, b])])); +} +function copyText(value: TextSource): TextSource { + return { ...value, members: value.members.map(([a, b]) => [a, b]) }; +} +function emptyPaging(): ThreadPaging { + return { loading: false, loadingOlder: false, error: null, olderError: null, + beforeCursor: null, hasMoreBefore: false, userMessageOffset: 0, + forkBoundaryMessageCount: null, truncated: false, version: 0, lineage: 0, + hasPendingToolCalls: false, completedTurnIds: [], completionIdsProvided: false, activeTurnId: null }; +} +function textKey(text: TextSource): string { + return JSON.stringify([text.turn, text.phase, text.stream, + text.phase === "answer" && text.stream ? "wire" : text.after]); +} +function sameWire(a: TextSource, b: TextSource): boolean { + return a.turn === b.turn && a.phase === b.phase && a.stream === b.stream; +} +function coversText(certificate: TextSource, text: TextSource): boolean { + return certificate.snapshot && certificate.after !== null && sameWire(certificate, text) + && text.members.every(([first, last]) => first > certificate.after! && last <= certificate.through); +} +function sourcesOverlap(candidate: Unit, retained: Unit): boolean { + if (Array.from(candidate.sources).some((key) => !key.startsWith("text:") && retained.sources.has(key))) return true; + return candidate.text.some((left) => retained.text.some((right) => sameWire(left, right) + && ((left.phase === "answer" && left.stream !== "") + // Ordered canonical ends identify reset buffers even when attachment missed a prior end. + || right.members.some(([first, last]) => last > (left.after ?? -1) && first <= (left.end ?? Infinity))))); +} +function unitPosition(unit: Unit | undefined, turn: string): number | null { + if (!unit) return null; + const positions = unit.members.get(turn)?.map(([first]) => first) ?? []; + for (const source of unit.text) if (source.turn === turn) { + positions.push(...source.members.map(([first]) => first)); + } + return positions.length ? Math.min(...positions) : null; +} + +/** One received projection and accepted history frontier. HTTP replay is scratch only. */ +export class ThreadTranscript { + projection: ThreadProjectionState; + sideChannelTurnIds = new Set(); + paging = emptyPaging(); + private units = new Set(); + private byRow = new Map(); + private bySource = new Map(); + private installed: Members = new Map(); + private textCoverage: TextSource[] = []; + private boundaries = new Map(); + private knownTurns = new Set(); + private revision = 0; + private order = 0; + + constructor(messages: UIMessage[] = [], saved?: ThreadTranscriptSnapshot) { + const checkpoint = saved ? copyThreadCheckpoint(saved) : createThreadCheckpoint(messages); + this.projection = checkpoint.projection; + this.sideChannelTurnIds = checkpoint.sideChannelTurnIds; + if (saved) { + this.installed = copyMembers(saved.installed); + this.textCoverage = saved.textCoverage.map(copyText); + this.boundaries = new Map(saved.boundaries); + this.knownTurns = new Set(saved.knownTurns); + this.paging = { ...saved.paging, loading: false, loadingOlder: false }; + this.revision = saved.revision; + for (const unit of saved.units) this.installUnit({ ...unit, rows: new Set(unit.rows), + sources: new Set(unit.sources), members: copyMembers(unit.members), text: unit.text.map(copyText) }); + } else { + for (const row of messages) this.registerInput(row, false); + } + } + + get messages(): UIMessage[] { return this.projection.messages; } + + private installUnit(unit: Unit): void { + this.order = Math.max(this.order, unit.order + 1); + this.units.add(unit); + for (const row of unit.rows) this.byRow.set(row, unit); + for (const key of unit.sources) this.bySource.set(key, unit); + } + + rejectTurn(turn: string): void { + for (const unit of this.units) if (unit.members.has(turn) || unit.sources.has(`user:${turn}`)) { + this.units.delete(unit); + for (const id of unit.rows) this.byRow.delete(id); + for (const key of unit.sources) this.bySource.delete(key); + } + for (const row of this.messages) if (row.role === "user" && row.turnId === turn) this.registerInput(row, false); + } + + registerInput(row: UIMessage, received = true): void { + if (row.role === "user" && row.turnId) this.knownTurns.add(row.turnId); + const identity = row.sessionMessage?.message_id + ? `input:${row.sessionMessage.message_id}` : row.role === "user" && row.turnId + ? `user:${row.turnId}` : row.turnId && row.turnSeq !== undefined + ? `fact:${row.turnId}:${row.turnSeq}` : `replay:${row.id}`; + if (this.bySource.has(identity)) return; + const members: Members = new Map(); + if (row.turnId && row.turnSeq !== undefined) members.set(row.turnId, [[row.turnSeq, row.turnSeq]]); + const revision = received ? ++this.revision : 0; + this.installUnit({ rows: new Set([row.id]), sources: new Set([identity]), members, text: [], + introduced: revision, order: this.order++, received: revision }); + } + + private describe(event: ThreadProjectionEvent): { source: string; members: Members; text: TextSource | null } { + const turn = event.turn_id; + const seq = event.turn_seq; + const members: Members = new Map(); + if (turn && seq !== undefined) members.set(turn, [[seq, seq]]); + for (const receipt of event.projection_receipts ?? []) { + const ranges = members.get(receipt.turn_id) ?? []; + for (const [first, last] of receipt.ranges) addRange(ranges, first, last); + members.set(receipt.turn_id, ranges); + } + if (event.event === "user_message") { + return { source: event.provenance?.session_message?.message_id + ? `input:${event.provenance.session_message.message_id}` : turn ? `user:${turn}` : `replay:${event.projection_id}`, + members, text: null }; + } + if (turn && seq !== undefined && (event.event === "delta" || event.event === "stream_end" + || event.event === "reasoning_delta" || event.event === "reasoning_end")) { + const phase = event.event.startsWith("reasoning") ? "reasoning" : "answer"; + const stream = event.stream_id ?? ""; + const boundaryKey = JSON.stringify([turn, phase, stream]); + let after = phase === "answer" && stream ? 0 + : this.boundaries.get(boundaryKey) ?? (this.knownTurns.has(turn) ? 0 : null); + if (after !== null && after >= seq) { + after = this.knownTurns.has(turn) ? 0 : null; + for (const unit of this.units) for (const prior of unit.text) { + if (prior.turn !== turn || prior.phase !== phase || prior.stream !== stream) continue; + for (const boundary of [prior.after, prior.end]) { + if (boundary !== null && boundary < seq) after = Math.max(after ?? 0, boundary); + } + } + } + const end = event.event === "reasoning_end" + || (event.event === "stream_end" && !(event.resuming && event.merge_next)) ? seq : null; + const text: TextSource = { turn, phase, stream, after, through: seq, end, + snapshot: event.event.endsWith("end") && typeof event.text === "string" + && (phase === "answer" || event.text.length > 0), + members: copyMembers(members).get(turn)! }; + return { source: `text:${textKey(text)}`, members, text }; + } + return { source: turn && seq !== undefined ? `fact:${turn}:${seq}` : `replay:${event.projection_id}`, + members, text: null }; + } + + represented(event: ThreadProjectionEvent): boolean { + if (event.turn_id && event.turn_seq !== undefined && contains(this.installed.get(event.turn_id), event.turn_seq)) return true; + const { text } = this.describe(event); + return text !== null && this.textCoverage.some((certificate) => coversText(certificate, text)); + } + + project(event: ThreadProjectionEvent, options: { + createId: () => string; now: number; persisted?: boolean; sideChannel?: boolean; startSeq?: number; + }): UIMessage[] { + if (!options.persisted && this.represented(event)) return this.messages; + if (!event.projection_id && (!event.turn_id || event.turn_seq === undefined)) { + event = { ...event, projection_id: options.createId() }; + } + const { source, members, text } = this.describe(event); + const effects: ThreadProjectionEffects = { bodyWrites: new Set(), consumed: new Set() }; + let projection = this.projection; + const historical = !options.persisted && event.event !== "turn_end" && event.event !== "user_message" + && event.turn_id && event.turn_seq !== undefined + && ((this.installed.get(event.turn_id)?.at(-1)?.[1] ?? -1) > event.turn_seq + || this.textCoverage.some((item) => item.turn === event.turn_id && item.through > event.turn_seq!)); + if (historical) { + // Replay only the identified historical destination; keep foreground pointers intact. + const callIds = new Set(event.event === "file_edit" + ? event.edits.flatMap((edit) => edit.call_id ? [edit.call_id] : []) + : event.event === "message" ? event.tool_events?.flatMap((tool) => tool.call_id ? [tool.call_id] : []) : []); + const destinations = new Set(); + const existing = this.bySource.get(source); + if (existing) destinations.add(existing); + if (callIds.size) for (const row of projection.messages) { + if (row.turnId !== event.turn_id) continue; + if (row.fileEdits?.some((edit) => edit.call_id && callIds.has(edit.call_id)) + || row.toolEvents?.some((tool) => tool.call_id && callIds.has(tool.call_id))) { + destinations.add(this.byRow.get(row.id)!); + } + } + const targets = projection.messages.filter((row) => destinations.has(this.byRow.get(row.id)!)); + const scratchState = { ...copyThreadCheckpoint(this, targets).projection, + activeAssistantId: null, mergeReasoning: false, activitySegmentId: null, fileEditSegmentId: null }; + const scratch = projectThreadEvent(scratchState, event, { ...options, effects }); + const updates = new Map(scratch.messages.map((row) => [row.id, row])); + const targetIds = new Set(targets.map((row) => row.id)); + const additions = scratch.messages.filter((row) => !targetIds.has(row.id)).map((row) => ({ ...row, + ...(row.activitySegmentId ? { activitySegmentId: `history:${event.turn_id}:${event.turn_seq}` } : {}) })); + const messages = projection.messages.flatMap((row) => targetIds.has(row.id) + ? updates.has(row.id) ? [updates.get(row.id)!] : [] : [row]); + const index = messages.findIndex((row) => { + const position = unitPosition(this.byRow.get(row.id), event.turn_id!); + return position !== null && position > event.turn_seq!; + }); + let lastInTurn = messages.length - 1; + while (lastInTurn >= 0 && unitPosition(this.byRow.get(messages[lastInTurn].id), event.turn_id!) === null) lastInTurn--; + if (index < 0 && lastInTurn < 0) { + this.paging = { ...this.paging, error: "Could not place earlier transcript event" }; + return this.messages; + } + const before = index < 0 ? lastInTurn + 1 : index; + projection = { ...projection, messages: [...messages.slice(0, before), ...additions, ...messages.slice(before)], + closedAssistantIds: scratch.closedAssistantIds, closedAnswerStreamIds: scratch.closedAnswerStreamIds, + closedTurnIds: scratch.closedTurnIds }; + } else { + projection = projectThreadEvent(projection, event, { ...options, effects }); + } + this.projection = projection; + const connected = new Set(); + const existing = this.bySource.get(source); + if (existing) connected.add(existing); + for (const id of [...effects.bodyWrites, ...effects.consumed]) { + const unit = this.byRow.get(id); + if (unit) connected.add(unit); + } + const revision = options.persisted ? 0 : ++this.revision; + const unit: Unit = { rows: new Set(), sources: new Set([source]), members, + text: text ? [text] : [], introduced: revision, order: this.order++, received: revision }; + for (const previous of connected) { + this.units.delete(previous); + for (const id of previous.rows) if (!effects.consumed.has(id)) unit.rows.add(id); + for (const key of previous.sources) unit.sources.add(key); + mergeMembers(unit.members, previous.members); + for (const prior of previous.text) { + const matching = unit.text.find((item) => textKey(item) === textKey(prior)); + if (matching) { + if (prior.end !== null) matching.end = Math.max(matching.end ?? 0, prior.end); + for (const [first, last] of prior.members) addRange(matching.members, first, last); + if (prior.snapshot) { + matching.through = matching.snapshot ? Math.max(matching.through, prior.through) : prior.through; + matching.snapshot = true; + } else if (!matching.snapshot) matching.through = Math.max(matching.through, prior.through); + } else unit.text.push(copyText(prior)); + } + unit.introduced = Math.min(unit.introduced, previous.introduced); + unit.order = Math.min(unit.order, previous.order); + unit.received = Math.max(unit.received, previous.received); + } + for (const id of effects.consumed) this.byRow.delete(id); + for (const id of effects.bodyWrites) { + if (!effects.consumed.has(id) || projection.messages.some((row) => row.id === id)) unit.rows.add(id); + } + this.installUnit(unit); + if (event.event === "user_message" && event.turn_id) this.knownTurns.add(event.turn_id); + if (text?.end !== null && text?.end !== undefined) { + const key = JSON.stringify([text.turn, text.phase, text.stream]); + this.boundaries.set(key, Math.max(text.end, this.boundaries.get(key) ?? 0)); + } + return this.messages; + } + + begin(kind: ThreadRead["kind"]): ThreadRead { + this.paging = { ...this.paging, + [kind === "older" ? "loadingOlder" : "loading"]: kind === "older" || this.paging.version === 0, + [kind === "older" ? "olderError" : "error"]: null }; + return { kind, revision: this.revision, lineage: this.paging.lineage, + before: this.paging.beforeCursor, empty: this.messages.length === 0 }; + } + + private unitCovered(unit: Unit, candidate: ThreadTranscript): boolean { + if (unit.text.length === 0 && Array.from(unit.sources).every((source) => candidate.bySource.has(source))) return true; + if (unit.members.size === 0) return false; + const represented = copyMembers(candidate.installed); + for (const text of unit.text) { + if (Array.from(candidate.units).some((other) => other.text.some((certificate) => coversText(certificate, text)))) { + mergeMembers(represented, new Map([[text.turn, text.members]])); + } + } + return Array.from(unit.members).every(([turn, ranges]) => ranges.every(([first, last]) => + represented.get(turn)?.some(([a, b]) => a <= first && b >= last))); + + } + + accept(body: WebuiThreadPersistedPayload | null, read: ThreadRead): boolean { + if (read.kind === "older" && (read.lineage !== this.paging.lineage || read.before !== this.paging.beforeCursor)) return false; + if (read.kind === "older" && !body?.page) { + this.finishRead(read, "Earlier history did not include a page cursor"); + return false; + } + const candidate = new ThreadTranscript(); + for (const [index, event] of (body?.events ?? []).entries()) candidate.project(event, + { createId: () => `history-${index}`, now: 0, persisted: true }); + for (const unit of candidate.units) mergeMembers(candidate.installed, unit.members); + const overlaps = new Set(Array.from(this.units).filter((old) => + Array.from(candidate.units).some((unit) => sourcesOverlap(unit, old)))); + const firstOverlap = this.messages.findIndex((row) => overlaps.has(this.byRow.get(row.id)!)); + const windowRows = new Set(this.messages.slice(Math.max(0, firstOverlap)).map((row) => row.id)); + const received = Array.from(this.units).filter((unit) => unit.received > 0 + && Array.from(unit.rows).some((id) => windowRows.has(id))); + const canonical = body ? persistedCanonicalRunState(body) : null; + const completed = new Set(canonical?.completedTurnIds); + const protectedUnits = received.filter((unit) => !this.unitCovered(unit, candidate) + || (unit.text.length > 0 && (body?.page?.truncated_oversized_turn + || unit.text.some((text) => !completed.has(text.turn))))); + const newTail = read.empty && protectedUnits.length > 0 + && protectedUnits.every((unit) => unit.received > read.revision); + const appendedInputs = this.messages.filter((row) => row.role === "user" && row.turnId + && this.byRow.get(row.id)!.introduced > read.revision); + const appendedTurns = new Set(appendedInputs.map((row) => row.turnId!)); + const appendedInputUnits = new Set(appendedInputs.map((row) => this.byRow.get(row.id)!)); + const reset = read.kind === "latest" && overlaps.size === 0 + && !body?.page?.truncated_oversized_turn + && protectedUnits.every((unit) => unit.introduced > read.revision + && (appendedInputUnits.has(unit) || (unit.members.size > 0 + && Array.from(unit.members.keys()).every((turn) => appendedTurns.has(turn))))); + if (read.kind !== "older" && this.messages.length > 0 && overlaps.size === 0 && !newTail && !reset) { + this.finishRead(read); + return false; + } + const held = new Set(); + for (const unit of candidate.units) { + if (protectedUnits.some((old) => sourcesOverlap(unit, old))) held.add(unit); + for (const old of protectedUnits) for (const turn of old.members.keys()) { + const at = unitPosition(unit, turn); + const start = unitPosition(old, turn); + if (at !== null && start !== null && at >= start) held.add(unit); + } + } + const rows = candidate.messages; + let cut = rows.findIndex((row) => held.has(candidate.byRow.get(row.id)!)); + if (cut < 0) cut = rows.length; + // A whole source can straddle several rows: never install only part of it. + for (let changed = true; changed;) { + changed = false; + for (let index = 0; index < cut; index++) { + const unit = candidate.byRow.get(rows[index].id)!; + if (rows.slice(cut).some((row) => unit.rows.has(row.id))) { cut = index; changed = true; break; } + } + } + const admittedRows = rows.slice(0, cut); + const admitted = new Set(admittedRows.map((row) => candidate.byRow.get(row.id)!)); + const cutOrder = cut < rows.length ? candidate.byRow.get(rows[cut].id)!.order : Infinity; + for (const unit of candidate.units) { + if (unit.rows.size === 0 && unit.order < cutOrder && !held.has(unit)) admitted.add(unit); + } + if (read.kind === "older" && Array.from(candidate.units).some((unit) => !admitted.has(unit) + && !Array.from(this.units).some((old) => sourcesOverlap(unit, old)))) { + this.finishRead(read, "Could not place earlier history"); + return false; + } + if (read.kind === "older" && body?.page?.has_more_before === true + && (!body.page.before_cursor || body.page.before_cursor === read.before)) { + this.finishRead(read, "Earlier history cursor did not advance"); + return false; + } + const fullyAdopt = protectedUnits.length === 0 && cut === rows.length + && !body?.page?.truncated_oversized_turn + && (this.messages.length === 0 || reset || overlaps.size > 0); + const replaced = new Set(); + for (const old of this.units) if ((reset && !protectedUnits.includes(old)) || Array.from(admitted) + .some((unit) => sourcesOverlap(unit, old) && (old.received === 0 || this.unitCovered(old, candidate)))) replaced.add(old); + const previousCount = this.messages.length; + const firstReplaced = this.messages.findIndex((row) => replaced.has(this.byRow.get(row.id)!)); + const prefix = read.kind !== "older" && !reset && firstReplaced > 0 + ? this.messages.slice(0, firstReplaced) : []; + const keepSuffix = !fullyAdopt || read.kind === "older"; + const anchors = new Map(); + if (keepSuffix) for (const [index, row] of this.messages.entries()) { + const old = this.byRow.get(row.id)!; + if (!replaced.has(old)) continue; + for (const unit of admitted) { + if (!anchors.has(unit) && sourcesOverlap(unit, old)) anchors.set(unit, index); + } + } + const segments = new Map(); + const mappedRows = admittedRows.map((row) => { + if (!row.activitySegmentId) return row; + let segment = segments.get(row.activitySegmentId); + if (!segment) { + segment = `history:${Array.from(candidate.byRow.get(row.id)!.sources)[0]}`; + segments.set(row.activitySegmentId, segment); + } + return { ...row, activitySegmentId: segment }; + }); + const nextMessages = [...prefix]; + let previous = prefix.length; + for (const row of mappedRows) { + const anchor = anchors.get(candidate.byRow.get(row.id)!); + while (anchor !== undefined && previous < anchor) { + const retained = this.messages[previous++]; + if (!replaced.has(this.byRow.get(retained.id)!)) nextMessages.push(retained); + } + nextMessages.push(row); + } + if (keepSuffix) nextMessages.push(...this.messages.slice(previous) + .filter((row) => !replaced.has(this.byRow.get(row.id)!))); + this.projection = fullyAdopt && read.kind !== "older" + ? { ...candidate.projection, messages: nextMessages, + activitySegmentId: candidate.projection.activitySegmentId + ? segments.get(candidate.projection.activitySegmentId) ?? null : null, + fileEditSegmentId: candidate.projection.fileEditSegmentId + ? segments.get(candidate.projection.fileEditSegmentId) ?? null : null, + closedTurnIds: new Set([...this.projection.closedTurnIds, ...candidate.projection.closedTurnIds]), + closedAnswerStreamIds: new Set([...this.projection.closedAnswerStreamIds, ...candidate.projection.closedAnswerStreamIds]) } + : { ...this.projection, messages: nextMessages }; + if (fullyAdopt && read.kind !== "older") { + const retained = new Set(prefix.map((row) => row.id)); + for (const unit of this.units) if (!Array.from(unit.rows).some((id) => retained.has(id))) replaced.add(unit); + } + for (const unit of replaced) { + this.units.delete(unit); + for (const id of unit.rows) this.byRow.delete(id); + for (const key of unit.sources) this.bySource.delete(key); + } + for (const unit of admitted) this.installUnit(unit); + const retainedMembers: Members = new Map(); + for (const unit of this.units) mergeMembers(retainedMembers, unit.members); + const installed: Members = new Map(); + for (const [turn, ranges] of this.installed) { + const kept: Ranges = []; + for (const [first, last] of ranges) for (const [a, b] of retainedMembers.get(turn) ?? []) { + if (first <= b && a <= last) addRange(kept, Math.max(first, a), Math.min(last, b)); + } + if (kept.length) installed.set(turn, kept); + } + const certificates = new Map(this.textCoverage + .filter((text) => this.bySource.has(`text:${textKey(text)}`)) + .map((text) => [textKey(text), text])); + for (const unit of admitted) { + mergeMembers(installed, unit.members); + for (const text of unit.text) if (text.snapshot && text.after !== null) { + const previous = certificates.get(textKey(text)); + if (!previous || text.through > previous.through) certificates.set(textKey(text), copyText(text)); + } + } + this.installed = installed; + this.textCoverage = Array.from(certificates.values()); + if (fullyAdopt && read.kind !== "older") { + this.boundaries = new Map(candidate.boundaries); + this.knownTurns = new Set(candidate.knownTurns); + } + for (const row of nextMessages) if (row.role === "user" && row.turnId) this.knownTurns.add(row.turnId); + for (const unit of admitted) for (const text of unit.text) { + const key = JSON.stringify([text.turn, text.phase, text.stream]); + const end = candidate.boundaries.get(key); + if (end !== undefined && contains(unit.members.get(text.turn), end)) { + this.boundaries.set(key, Math.max(end, this.boundaries.get(key) ?? 0)); + } + } + for (const event of body?.events ?? []) { + if (event.event === "turn_end" && event.turn_id && event.turn_seq !== undefined + && contains(this.installed.get(event.turn_id), event.turn_seq)) this.projection.closedTurnIds.add(event.turn_id); + } + for (const id of candidate.projection.closedAssistantIds) { + if (admittedRows.some((row) => row.id === id)) this.projection.closedAssistantIds.add(id); + } + const admittedStreams = new Set(admittedRows.filter((row) => row.streamId) + .map((row) => JSON.stringify([row.turnId ?? "", row.streamId]))); + for (const unit of admitted) for (const text of unit.text) { + if (text.phase === "answer" && text.stream && text.end !== null) { + admittedStreams.add(JSON.stringify([text.turn, text.stream])); + } + } + for (const key of candidate.projection.closedAnswerStreamIds) { + if (admittedStreams.has(key)) this.projection.closedAnswerStreamIds.add(key); + } + const retainedStreams = new Set(nextMessages.filter((row) => row.streamId) + .map((row) => JSON.stringify([row.turnId ?? "", row.streamId]))); + for (const unit of this.units) for (const text of unit.text) { + if (text.phase === "answer" && text.stream && text.end !== null) { + retainedStreams.add(JSON.stringify([text.turn, text.stream])); + } + } + this.projection.closedAnswerStreamIds = new Set(Array.from(this.projection.closedAnswerStreamIds) + .filter((key) => retainedStreams.has(key))); + const retainedTurns = new Set(Array.from(this.units).flatMap((unit) => Array.from(unit.members.keys()))); + for (const row of nextMessages) if (row.turnId) retainedTurns.add(row.turnId); + const retainedRows = new Set(nextMessages.map((row) => row.id)); + const retainedBoundaries = new Set(Array.from(this.units).flatMap((unit) => unit.text + .map((text) => JSON.stringify([text.turn, text.phase, text.stream])))); + this.knownTurns = new Set(Array.from(this.knownTurns).filter((turn) => retainedTurns.has(turn))); + this.boundaries = new Map(Array.from(this.boundaries).filter(([key]) => retainedBoundaries.has(key))); + this.sideChannelTurnIds = new Set(Array.from(this.sideChannelTurnIds).filter((turn) => retainedTurns.has(turn))); + this.projection.closedTurnIds = new Set(Array.from(this.projection.closedTurnIds).filter((turn) => retainedTurns.has(turn))); + this.projection.closedAssistantIds = new Set(Array.from(this.projection.closedAssistantIds).filter((id) => retainedRows.has(id))); + this.projection.turnAliases = new Map(Array.from(this.projection.turnAliases).filter(([turn, alias]) => + retainedTurns.has(turn) && retainedTurns.has(alias))); + const page = body?.page; + const preserveFrontier = read.kind !== "older" && prefix.length > 0; + const boundary = body?.fork_boundary_event_index; + const forkRows = boundary === undefined ? null : new ThreadTranscript(); + if (forkRows && boundary !== undefined) for (const [index, event] of (body?.events ?? []).slice(0, boundary).entries()) { + forkRows.project(event, { createId: () => `boundary-${index}`, now: 0, persisted: true }); + } + this.paging = { ...this.paging, loading: false, loadingOlder: false, error: null, + olderError: read.kind !== "older" && !reset + && (preserveFrontier || this.paging.beforeCursor === page?.before_cursor) ? this.paging.olderError : null, + beforeCursor: preserveFrontier ? this.paging.beforeCursor : page?.before_cursor ?? null, + hasMoreBefore: preserveFrontier ? this.paging.hasMoreBefore : page?.has_more_before === true, + userMessageOffset: preserveFrontier ? this.paging.userMessageOffset : Math.max(0, page?.user_message_offset ?? 0), + forkBoundaryMessageCount: forkRows ? prefix.length + forkRows.messages.length + : read.kind === "older" && this.paging.forkBoundaryMessageCount !== null + ? this.paging.forkBoundaryMessageCount + nextMessages.length - previousCount + : this.paging.forkBoundaryMessageCount, + truncated: page?.truncated_oversized_turn === true, + version: this.paging.version + (read.kind === "older" ? 0 : 1), + lineage: this.paging.lineage + (reset || this.paging.lineage === 0 ? 1 : 0), + ...(read.kind === "older" ? {} : { + hasPendingToolCalls: body?.has_pending_tool_calls ?? hasPendingAgentActivity(nextMessages), + completedTurnIds: canonical?.completedTurnIds ?? [], + completionIdsProvided: Array.isArray(body?.completed_turn_ids), + activeTurnId: body?.active_turn_id ?? null, + }), + }; + return true; + } + + finishRead(read: ThreadRead, error: string | null = null): void { + this.paging = { ...this.paging, [read.kind === "older" ? "loadingOlder" : "loading"]: false, + [read.kind === "older" ? "olderError" : "error"]: error }; + } + + expandDetail(ref: string, events: ThreadProjectionEvent[]): void { + const target = this.messages.find((row) => row.traceDetail?.ref === ref); + if (!target) return; + const scratch = new ThreadTranscript(); + events.forEach((event, index) => scratch.project(event, + { createId: () => `detail:${ref}:${index}`, now: 0, persisted: true })); + const unit = this.byRow.get(target.id)!; + unit.rows.delete(target.id); + this.byRow.delete(target.id); + const replacements = scratch.messages.map((row) => ({ ...row, activitySegmentId: target.activitySegmentId })); + for (const row of replacements) { unit.rows.add(row.id); this.byRow.set(row.id, unit); } + this.projection = { ...this.projection, messages: this.messages.flatMap((row) => row === target ? replacements : [row]) }; + } + + save(): ThreadTranscriptSnapshot { + return { ...copyThreadCheckpoint(this), + units: Array.from(this.units, (unit) => ({ ...unit, rows: new Set(unit.rows), sources: new Set(unit.sources), + members: copyMembers(unit.members), text: unit.text.map(copyText) })), + installed: copyMembers(this.installed), textCoverage: this.textCoverage.map(copyText), + boundaries: new Map(this.boundaries), knownTurns: new Set(this.knownTurns), + paging: { ...this.paging }, revision: this.revision }; + } +} diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index a8faafbe3..2be186534 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -1661,6 +1661,9 @@ export type ThreadProjectionEvent = Extract< > & { projection_id?: string; created_at_ms?: number; + turn_seq?: number; + /** Actual facts represented by a compacted HTTP projection event. */ + projection_receipts?: Array<{ turn_id: string; ranges: Array<[number, number]> }>; }; /** Local draft/preview data, converted to HTTP binary before sending a message. @@ -1703,6 +1706,7 @@ interface WebuiThreadPagePayload { has_more_after?: boolean; user_message_offset?: number; loaded_event_count?: number; + truncated_oversized_turn?: boolean; } export interface PromptSummary { diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.ts index fb18d1904..26d86fafa 100644 --- a/webui/src/tests/api.test.ts +++ b/webui/src/tests/api.test.ts @@ -190,6 +190,40 @@ describe("webui API helpers", () => { ); }); + it.each([ + {}, + { stream_id: "answer-1" }, + { projection_receipts: [] }, + { stream_id: "answer-1", projection_receipts: [{ turn_id: "turn-1", ranges: [[1, 3], [5, 5]] }] }, + ])("accepts optional stream identity and projection receipts: %j", async (metadata) => { + const event = { event: "stream_end", chat_id: "chat-1", text: "Reply", turn_id: "turn-1", turn_seq: 6, ...metadata }; + vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ + schemaVersion: 3, projection: "events", events: [event], + }))); + + await expect(fetchWebuiThread("tok", "websocket:chat-1")).resolves.toMatchObject({ events: [event] }); + }); + + it.each([ + { stream_id: 123 }, + { projection_receipts: null }, + { projection_receipts: [{ turn_id: "", ranges: [[1, 2]] }] }, + { projection_receipts: [{ turn_id: "turn-1", ranges: [[2, 1]] }] }, + { projection_receipts: [{ turn_id: "turn-1", ranges: [[1]] }] }, + { projection_receipts: [{ turn_id: "turn-1", ranges: [[-1, 2]] }] }, + { projection_receipts: [{ turn_id: "turn-1", ranges: [[1, 2.5]] }] }, + ])("rejects malformed stream identity or projection receipts at the HTTP boundary: %j", async (metadata) => { + vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ + schemaVersion: 3, + projection: "events", + events: [{ event: "stream_end", chat_id: "chat-1", text: "Reply", ...metadata }], + }))); + + await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow( + "Invalid WebUI thread event metadata", + ); + }); + it.each([ null, "backup", diff --git a/webui/src/tests/memory-lru-cache.test.ts b/webui/src/tests/memory-lru-cache.test.ts new file mode 100644 index 000000000..10b8c27b6 --- /dev/null +++ b/webui/src/tests/memory-lru-cache.test.ts @@ -0,0 +1,20 @@ +import { expect, it } from "vitest"; + +import { MemoryLruCache } from "@/lib/memory-lru-cache"; + +it.each([ + { collection: "Map keys", small: new Map([["turn", "source"]]), large: new Map([["x".repeat(64), "source"]]) }, + { collection: "Map values", small: new Map([["turn", "source"]]), large: new Map([["turn", "x".repeat(64)]]) }, + { collection: "Set members", small: new Set(["turn"]), large: new Set(["x".repeat(64)]) }, +])("counts nested $collection toward the byte budget", ({ small, large }) => { + const cache = new MemoryLruCache<{ members: typeof large }>(160, 2); + const snapshot = { members: small }; + cache.set("small", snapshot); + expect(cache.get("small")).toBe(snapshot); + + cache.set("large", { members: large }); + expect(cache.get("large")).toBeUndefined(); + + cache.set("small", snapshot); + expect(cache.get("small")).toBe(snapshot); +}); diff --git a/webui/src/tests/thread-message-cache.test.ts b/webui/src/tests/thread-message-cache.test.ts index 74a54c224..de03952c6 100644 --- a/webui/src/tests/thread-message-cache.test.ts +++ b/webui/src/tests/thread-message-cache.test.ts @@ -1,26 +1,27 @@ import { expect, it } from "vitest"; import { ThreadMessageCache } from "@/lib/thread-message-cache"; +import { ThreadTranscript } from "@/lib/thread-transcript"; import type { UIMessage } from "@/lib/types"; -import { createThreadCheckpoint } from "@/lib/thread-checkpoint"; -const messages: UIMessage[] = [{ id: "u", role: "user", content: "hello", createdAt: 1 }]; -const rows = createThreadCheckpoint(messages); +const rows: UIMessage[] = [{ id: "u", role: "user", content: "hello", createdAt: 1 }]; +const snapshot = new ThreadTranscript(rows).save(); it("keeps recently visited chats within the entry budget", () => { const cache = new ThreadMessageCache(() => false, 10000, 2); - cache.set("a", rows); cache.set("b", rows); - expect(cache.get("a")).toBe(rows); - cache.set("c", rows); - expect([cache.get("a"), cache.get("b"), cache.get("c")]).toEqual([rows, undefined, rows]); + cache.set("a", snapshot); cache.set("b", snapshot); + expect(cache.get("a")?.projection.messages).toBe(rows); + cache.set("c", snapshot); + expect([cache.get("a")?.projection.messages, cache.get("b"), cache.get("c")?.projection.messages]) + .toEqual([rows, undefined, rows]); }); it("bounds large replay snapshots while retaining temporary chats", () => { - const cache = new ThreadMessageCache((key) => key === "temporary", 1000, 2); - cache.set("temporary", rows); - cache.set("large", createThreadCheckpoint([{ ...messages[0], content: "x".repeat(1000) }])); + const cache = new ThreadMessageCache((key) => key === "temporary", 4096, 2); + cache.set("temporary", snapshot); + cache.set("large", new ThreadTranscript([{ ...rows[0], content: "x".repeat(4096) }]).save()); expect(cache.get("large")).toBeUndefined(); - expect(cache.get("temporary")).toBe(rows); + expect(cache.get("temporary")?.projection.messages).toBe(rows); cache.delete("temporary"); - cache.set("small", rows); - expect(cache.get("small")).toBe(rows); + cache.set("small", snapshot); + expect(cache.get("small")?.projection.messages).toBe(rows); }); diff --git a/webui/src/tests/thread-projection-effects.test.ts b/webui/src/tests/thread-projection-effects.test.ts new file mode 100644 index 000000000..82fabf3e3 --- /dev/null +++ b/webui/src/tests/thread-projection-effects.test.ts @@ -0,0 +1,314 @@ +import { describe, expect, it } from "vitest"; + +import { copyThreadCheckpoint } from "@/lib/thread-checkpoint"; +import { + createThreadProjectionState, + projectThreadEvent, + type ThreadProjectionEffects, + type ThreadProjectionOptions, +} from "@/lib/thread-event-projection"; +import type { ThreadProjectionEvent, UIFileEdit } from "@/lib/types"; + +function createProjector(state = createThreadProjectionState()) { + let nextId = 0; + return ( + event: ThreadProjectionEvent, + options: Pick = {}, + ) => { + const effects: ThreadProjectionEffects = { + bodyWrites: new Set(), + consumed: new Set(), + }; + state = projectThreadEvent(state, event, { + createId: () => `row-${++nextId}`, + now: 1_800_000_000_000, + ...options, + effects, + }); + return { state, effects }; + }; +} + +const turn = { chat_id: "chat", turn_id: "turn" }; + +function fileEdit(overrides: Partial = {}): UIFileEdit { + return { + call_id: "write-1", + tool: "write_file", + path: "notes.md", + added: 1, + deleted: 0, + status: "editing", + phase: "start", + ...overrides, + }; +} + +describe("thread projection content effects", () => { + it("reports reasoning and answer contributions to their shared body row", () => { + const project = createProjector(); + const reasoning = project({ + ...turn, event: "reasoning_delta", text: "First thought", projection_id: "shared", + }); + expect(reasoning.effects.bodyWrites).toEqual(new Set(["shared"])); + + const reasoningEnd = project({ ...turn, event: "reasoning_end", text: "." }); + expect(reasoningEnd.effects.bodyWrites).toEqual(new Set(["shared"])); + expect(reasoningEnd.state.messages[0].reasoning).toBe("First thought."); + + const answer = project({ ...turn, event: "delta", text: "Answer" }); + expect(answer.effects.bodyWrites).toEqual(new Set(["shared"])); + const end = project({ + ...turn, event: "stream_end", text: "Final answer", resuming: true, merge_next: true, + }); + expect(end.effects.bodyWrites).toEqual(new Set(["shared"])); + + const continuation = project({ ...turn, event: "reasoning_delta", text: "More thought" }); + expect(continuation.effects.bodyWrites).toEqual(new Set(["shared"])); + expect(continuation.effects.consumed.size).toBe(0); + expect(continuation.state.messages[0]).toMatchObject({ + id: "shared", content: "Final answer", reasoning: "First thought.\n\nMore thought", + }); + const closure = project({ ...turn, event: "reasoning_end" }); + expect(closure.effects.bodyWrites.size).toBe(0); + expect(closure.effects.consumed.size).toBe(0); + }); + + it("reports identified reasoning snapshots without claiming another open reasoning row", () => { + const project = createProjector(); + project({ ...turn, event: "reasoning_delta", stream_id: "first", text: "Thought", projection_id: "thought" }); + project({ ...turn, event: "reasoning_end", stream_id: "first" }); + project({ ...turn, event: "delta", stream_id: "first", text: "Answer" }); + project({ ...turn, event: "stream_end", stream_id: "first" }); + project({ ...turn, event: "reasoning_delta", stream_id: "second", text: "Next thought", projection_id: "next" }); + + const snapshot = project({ ...turn, event: "reasoning_end", stream_id: "first", text: "Revised thought" }); + expect(snapshot.effects.bodyWrites).toEqual(new Set(["thought"])); + expect(snapshot.effects.consumed.size).toBe(0); + expect(snapshot.state.messages[0].reasoning).toBe("Revised thought"); + expect(snapshot.state.messages[1]).toMatchObject({ id: "next", reasoningStreaming: true }); + + const ignored = project({ ...turn, event: "reasoning_delta", stream_id: "first", text: "Late" }); + expect(ignored.effects.bodyWrites.size).toBe(0); + expect(ignored.effects.consumed.size).toBe(0); + }); + + it("reports late answer snapshot targets but not textless metadata or closure patches", () => { + const project = createProjector(); + project({ ...turn, event: "delta", stream_id: "first", text: "Draft", projection_id: "first" }); + project({ ...turn, event: "stream_end", stream_id: "first" }); + project({ ...turn, event: "message", kind: "tool_hint", text: "Tool", projection_id: "tool" }); + project({ ...turn, event: "delta", stream_id: "second", text: "Current", projection_id: "second" }); + + const snapshot = project({ ...turn, event: "stream_end", stream_id: "first", text: "Final" }); + expect(snapshot.effects.bodyWrites).toEqual(new Set(["first"])); + expect(snapshot.effects.consumed.size).toBe(0); + expect(snapshot.state.activeAssistantId).toBe("second"); + for (const streamId of ["first", "empty"]) { + const metadata = project({ ...turn, event: "stream_end", stream_id: streamId, response_sources: [] }); + expect(metadata.effects.bodyWrites.size).toBe(0); + expect(metadata.effects.consumed.size).toBe(0); + expect(metadata.state.activeAssistantId).toBe("second"); + expect(metadata.state.messages).toHaveLength(3); + } + const cleared = project({ ...turn, event: "stream_end", stream_id: "first", text: "" }); + expect(cleared.effects.bodyWrites).toEqual(new Set(["first"])); + expect(cleared.state.messages[0].content).toBe(""); + expect(cleared.state.activeAssistantId).toBe("second"); + }); + + it("reports only the destination slice of legacy cumulative HTTP answer snapshots", () => { + const project = createProjector(); + project({ + ...turn, event: "stream_end", stream_id: "answer", turn_seq: 2, text: "Before ", + resuming: true, merge_next: true, projection_id: "before", + }, { persisted: true }); + project({ + ...turn, event: "message", kind: "tool_hint", turn_seq: 3, text: "Tool", projection_id: "tool", + }, { persisted: true }); + const after = project({ + ...turn, event: "stream_end", stream_id: "answer", turn_seq: 5, + text: "Before after", projection_id: "after", + }, { persisted: true }); + expect(after.effects.bodyWrites).toEqual(new Set(["after"])); + expect(after.effects.consumed.size).toBe(0); + expect(after.state.messages.map((message) => message.content)).toEqual(["Before ", "Tool", "after"]); + + const revised = project({ + ...turn, event: "stream_end", stream_id: "answer", turn_seq: 6, text: "Before revised", + }, { persisted: true }); + expect(revised.effects.bodyWrites).toEqual(new Set(["after"])); + expect(revised.state.messages[2]).toMatchObject({ content: "revised", projectionStartSeq: 5, turnSeq: 6 }); + }); + + it("reports continuation effects after copying a merge_next checkpoint with closed wire fences", () => { + const project = createProjector(); + project({ ...turn, event: "delta", stream_id: "first", text: "First", turn_seq: 2, projection_id: "first" }, { startSeq: 1 }); + project({ ...turn, event: "stream_end", stream_id: "first", turn_seq: 3 }); + project({ ...turn, event: "message", kind: "tool_hint", text: "Tool", turn_seq: 4, projection_id: "tool" }); + project({ ...turn, event: "delta", stream_id: "second", text: "Next ", turn_seq: 6, projection_id: "second" }, { startSeq: 5 }); + project({ ...turn, event: "stream_end", stream_id: "second", text: "Next ", turn_seq: 7, resuming: true, merge_next: true }); + const queued = project({ ...turn, event: "reasoning_delta", stream_id: "second", text: "Queued ", turn_seq: 8 }); + const checkpoint = copyThreadCheckpoint({ projection: queued.state, sideChannelTurnIds: new Set(["command"]) }); + const restored = createProjector(copyThreadCheckpoint(checkpoint).projection); + + const ignored = restored({ ...turn, event: "delta", stream_id: "first", text: "Late", turn_seq: 9 }); + expect(ignored.effects.bodyWrites.size).toBe(0); + const reasoning = restored({ ...turn, event: "reasoning_delta", stream_id: "second", text: "continued", turn_seq: 10 }); + expect(reasoning.effects.bodyWrites).toEqual(new Set(["second"])); + const closure = restored({ ...turn, event: "reasoning_end", stream_id: "second", turn_seq: 11 }); + expect(closure.effects.bodyWrites.size).toBe(0); + restored({ ...turn, event: "delta", stream_id: "second", text: "last", turn_seq: 12 }); + const completed = restored({ ...turn, event: "stream_end", stream_id: "second", text: "Next last", turn_seq: 13 }); + expect(completed.effects.bodyWrites).toEqual(new Set(["second"])); + expect(completed.effects.consumed.size).toBe(0); + expect(completed.state.messages[0]).toMatchObject({ content: "First", projectionStartSeq: 1 }); + expect(completed.state.messages[2]).toMatchObject({ + content: "Next last", reasoning: "Queued continued", projectionStartSeq: 5, turnSeq: 13, + }); + expect(checkpoint.projection.messages[2]).toMatchObject({ content: "Next ", reasoning: "Queued " }); + expect(checkpoint.projection.closedAnswerStreamIds.size).toBe(1); + expect(completed.state.closedAnswerStreamIds.size).toBe(2); + }); + + it("reports only the tool body target when activity closes an answer, including trace merges", () => { + const project = createProjector(); + project({ ...turn, event: "delta", text: "Working", projection_id: "answer" }); + const activity = project({ + ...turn, + event: "message", + kind: "tool_hint", + text: "Running command", + projection_id: "tool", + tool_events: [{ call_id: "exec-1", name: "exec", phase: "start" }], + }); + expect(activity.state.closedAssistantIds.has("answer")).toBe(true); + expect(activity.effects.bodyWrites).toEqual(new Set(["tool"])); + expect(activity.effects.consumed.size).toBe(0); + + const merged = project({ + ...turn, + event: "message", + kind: "progress", + text: "Command finished", + tool_events: [{ call_id: "exec-1", name: "exec", phase: "end", result: "done" }], + }); + expect(merged.effects.bodyWrites).toEqual(new Set(["tool"])); + expect(merged.state.messages.find((message) => message.id === "tool")?.toolEvents) + .toEqual([{ call_id: "exec-1", name: "exec", phase: "end", result: "done" }]); + }); + + it("reports every stripped hint and edit target, consuming only the removed trace row", () => { + const project = createProjector(); + const write = { call_id: "write-1", name: "write_file", arguments: { path: "notes.md" } }; + project({ + ...turn, event: "message", kind: "tool_hint", text: "Writing", projection_id: "removed-hint", + tool_events: [{ ...write, phase: "start" }], + }); + project({ ...turn, event: "delta", text: "Saving notes", projection_id: "answer" }); + project({ + ...turn, event: "message", kind: "progress", text: "Written", projection_id: "kept-hint", + tool_events: [ + { ...write, phase: "end" }, + { call_id: "exec-1", name: "exec", phase: "end" }, + ], + }); + + const edit = project({ + ...turn, event: "file_edit", edits: [fileEdit()], projection_id: "edits", + }); + expect(edit.effects.bodyWrites).toEqual(new Set(["removed-hint", "kept-hint", "edits"])); + expect(edit.effects.consumed).toEqual(new Set(["removed-hint"])); + expect(edit.state.messages.find((message) => message.id === "removed-hint")).toBeUndefined(); + expect(edit.state.messages.find((message) => message.id === "kept-hint")?.toolEvents) + .toEqual([{ call_id: "exec-1", name: "exec", phase: "end" }]); + expect(edit.state.messages.find((message) => message.id === "edits")?.fileEdits) + .toEqual([fileEdit()]); + + const completed = project({ + ...turn, event: "file_edit", edits: [fileEdit({ status: "done", phase: "end", added: 2 })], + }); + expect(completed.effects.bodyWrites).toEqual(new Set(["edits"])); + expect(completed.effects.consumed.size).toBe(0); + }); + + it("transfers the consumed active row to the plain assistant replacement", () => { + const project = createProjector(); + project({ ...turn, event: "delta", text: "Draft", projection_id: "draft" }); + const replacement = project({ + ...turn, event: "message", text: "Final reply", projection_id: "final", + }); + expect(replacement.effects.bodyWrites).toEqual(new Set(["final"])); + expect(replacement.effects.consumed).toEqual(new Set(["draft"])); + expect(replacement.state.messages.find((message) => message.id === "final")?.content) + .toBe("Final reply"); + }); + + it.each([false, true])("reports reasoning-placeholder absorption (sideChannel=%s)", (sideChannel) => { + const project = createProjector(); + project({ + ...turn, event: "message", kind: "reasoning", text: "Thinking", projection_id: "reasoning", + }); + const absorbed = project({ + ...turn, event: "message", text: "Explained", projection_id: "unused-reply-id", + }, { sideChannel }); + expect(absorbed.effects.bodyWrites).toEqual(new Set(["reasoning"])); + expect(absorbed.effects.consumed).toEqual(new Set(["reasoning"])); + expect(absorbed.state.messages[0]).toMatchObject({ + id: "reasoning", content: "Explained", reasoning: "Thinking", + }); + }); + + it("reports input, stream-end insertion and compaction bodies without owning lifecycle flags", () => { + const project = createProjector(); + const input = project({ + ...turn, event: "user_message", text: "Prompt", starts_turn: true, projection_id: "input", + }); + expect(input.effects.bodyWrites).toEqual(new Set(["input"])); + const answer = project({ ...turn, event: "stream_end", text: "Reply", projection_id: "answer" }); + expect(answer.effects.bodyWrites).toEqual(new Set(["answer"])); + const started = project({ + ...turn, event: "context_compaction", compaction_id: "compact", phase: "started", + }); + expect(started.effects.bodyWrites).toEqual(new Set(["compaction-compact"])); + const finished = project({ + ...turn, event: "context_compaction", compaction_id: "compact", phase: "succeeded", + }); + expect(finished.effects.bodyWrites).toEqual(new Set(["compaction-compact"])); + + for (const event of [ + { ...turn, event: "reasoning_end" }, + { ...turn, event: "stream_end" }, + { ...turn, event: "turn_end", latency_ms: 120, context_window_tokens: 4096 }, + ] satisfies ThreadProjectionEvent[]) { + const closure = project(event); + expect(closure.effects.bodyWrites.size).toBe(0); + expect(closure.effects.consumed.size).toBe(0); + } + }); + + it("leaves projection state unchanged when reporting is optional", () => { + const events: ThreadProjectionEvent[] = [ + { ...turn, event: "user_message", text: "Prompt", starts_turn: true }, + { ...turn, event: "reasoning_delta", text: "Thinking" }, + { ...turn, event: "reasoning_end" }, + { ...turn, event: "delta", text: "Draft" }, + { ...turn, event: "message", kind: "tool_hint", text: "Writing", + tool_events: [{ call_id: "write-1", name: "write_file", phase: "start" }] }, + { ...turn, event: "file_edit", edits: [fileEdit()] }, + { ...turn, event: "stream_end", text: "Final reply" }, + { ...turn, event: "message", text: "Replacement" }, + { ...turn, event: "context_compaction", compaction_id: "compact", phase: "succeeded" }, + { ...turn, event: "turn_end", latency_ms: 100 }, + ]; + let reported = createThreadProjectionState(); + let unreported = createThreadProjectionState(); + events.forEach((event, index) => { + const options = { createId: () => `row-${index}`, now: 1_800_000_000_000 }; + const effects: ThreadProjectionEffects = { bodyWrites: new Set(), consumed: new Set() }; + reported = projectThreadEvent(reported, event, { ...options, effects }); + unreported = projectThreadEvent(unreported, event, options); + expect(reported).toEqual(unreported); + }); + }); +}); diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index aa2c2f267..bf071f69a 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -11,12 +11,14 @@ import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events"; import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client"; import { webuiThreadCache } from "@/lib/webui-thread-cache"; import { ThreadMessageCache } from "@/lib/thread-message-cache"; -import { createThreadCheckpoint } from "@/lib/thread-checkpoint"; +import { ThreadTranscript } from "@/lib/thread-transcript"; +import { persistedCanonicalRunState } from "@/lib/canonical-run-snapshot"; import { ClientProvider } from "@/providers/ClientProvider"; import type { CliAppsPayload, ConnectionStatus, SettingsPayload, + ThreadProjectionEvent, UIMessage, WebuiThreadPersistedPayload, } from "@/lib/types"; @@ -79,11 +81,14 @@ function makeClient() { || ( snapshot?.completionIdsProvided !== true && snapshot?.hasPendingToolCalls === false + && snapshot?.activeTurnId !== turnId && observedTurnIds.has(turnId) ) ); const currentGeneration = runGenerationByChatId.get(chatId) ?? 0; const latestTurnId = latestRunTurnIdByChatId.get(chatId); + if (latestTurnId && !closedRunTurnIdsByChatId.get(chatId)?.has(latestTurnId) + && !isRepresented(latestTurnId)) return false; return ( currentGeneration === expectedRunGeneration || (typeof latestTurnId === "string" && isRepresented(latestTurnId)) @@ -106,7 +111,8 @@ function makeClient() { const fences = completedTurnIdsByChatId.get(chatId) ?? new Set(); for (const turnId of completedTurnIds) fences.add(turnId); completedTurnIdsByChatId.set(chatId, fences); - runStartedAtByChatId.delete(chatId); + const hadClock = runStartedAtByChatId.delete(chatId); + if (hadClock) for (const h of runStatusHandlers) h(chatId, null); return true; }); return { @@ -187,6 +193,13 @@ function makeClient() { }; }, _emitError(err: StreamError) { + if (err.kind !== "model_request_failed" && err.chatId && err.turnId) { + if (latestRunTurnIdByChatId.get(err.chatId) === err.turnId) { + latestRunTurnIdByChatId.delete(err.chatId); + const hadClock = runStartedAtByChatId.delete(err.chatId); + if (hadClock) for (const h of runStatusHandlers) h(err.chatId, null); + } + } for (const h of errorHandlers) h(err); }, _emitStatus(nextStatus: ConnectionStatus) { @@ -285,12 +298,12 @@ function session(chatId: string, modelPreset?: string | null) { } function transcriptFromSimpleMessages( - rows: Array<{ role: "user" | "assistant"; content: string; turnId?: string }>, + rows: Array<{ id?: string; role: "user" | "assistant"; content: string; turnId?: string }>, ): WebuiThreadPersistedPayload { return canonicalThreadPayload({ schemaVersion: 3, messages: rows.map((m, i) => ({ - id: `m-${i}`, + id: m.id ?? `m-${i}`, role: m.role, content: m.content, ...(m.turnId ? { turnId: m.turnId } : {}), @@ -299,6 +312,80 @@ function transcriptFromSimpleMessages( })!; } +type StreamedFixtureRow = + | ({ + role: "user"; + content: string; + startsTurn?: boolean; + activeTurnId?: string; + } & ( + | { turnId: string; sessionMessage?: never } + | { turnId?: never; sessionMessage: NonNullable } + )) + | { + role: "assistant"; + content: string; + turnId: string; + streamId: string; + textSeq?: number; + endSeq?: number; + mergeNext?: boolean; + }; + +// Stream replacement requires the actual input and wire sources, not display IDs. +function streamedThreadPayload( + chatId: string, + rows: StreamedFixtureRow[], + completedTurnIds: string[] = [], +): WebuiThreadPersistedPayload { + const events: ThreadProjectionEvent[] = []; + rows.forEach((row, index) => { + if (row.role === "user") { + events.push({ + event: "user_message", chat_id: chatId, + projection_id: `input:${row.turnId ?? row.sessionMessage.message_id}`, + text: row.content, starts_turn: row.startsTurn ?? true, + ...(row.turnId ? { turn_id: row.turnId, turn_seq: 1 } : {}), + ...(row.activeTurnId ? { active_turn_id: row.activeTurnId } : {}), + ...(row.sessionMessage ? { provenance: { session_message: row.sessionMessage } } : {}), + }); + } else { + const textSeq = row.textSeq ?? 2; + const endSeq = row.endSeq ?? 3; + events.push({ + event: "stream_end", chat_id: chatId, + projection_id: `answer:${row.turnId}:${row.streamId}:${endSeq}`, + turn_id: row.turnId, turn_phase: "answer", turn_seq: endSeq, + stream_id: row.streamId, text: row.content, + projection_receipts: [{ turn_id: row.turnId, ranges: [[textSeq, endSeq]] }], + ...(row.mergeNext ? { resuming: true, merge_next: true } : {}), + }); + } + if (row.turnId && completedTurnIds.includes(row.turnId) + && !rows.slice(index + 1).some((later) => later.turnId === row.turnId)) { + events.push({ + event: "turn_end", chat_id: chatId, turn_id: row.turnId, + projection_id: `complete:${row.turnId}`, + turn_seq: row.role === "assistant" ? (row.endSeq ?? 3) + 1 : 2, + }); + } + }); + return { schemaVersion: 3, projection: "events", events, completed_turn_ids: completedTurnIds }; +} + +function publishReconnectCompletion( + client: ReturnType, + chatId: string, + body: WebuiThreadPersistedPayload, +) { + const generation = client.getRunGeneration(chatId); + const { completedTurnIds, snapshot } = persistedCanonicalRunState(body); + expect(client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)).toBe(true); + // useReconnectRuns publishes synchronously before settling/fencing the ledger. + webuiThreadCache.set(`websocket:${chatId}`, body); + expect(client.reconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)).toBe(true); +} + function httpJson(body: unknown) { const normalized = body && typeof body === "object" && "schemaVersion" in body @@ -2609,7 +2696,7 @@ describe("ThreadShell", () => { await act(async () => { client._emitChat("chat-a", { event: "goal_status", - chat_id: "chat-a", + chat_id: "chat-a", turn_id: "running-chat-a-turn", status: "running", started_at: Date.now() / 1000, }); @@ -2630,6 +2717,7 @@ describe("ThreadShell", () => { it("keeps live fork replies when a canonical refresh is missing an earlier assistant answer", async () => { const client = makeClient(); let historyCalls = 0; + let secondTurnId = ""; vi.stubGlobal( "fetch", vi.fn(async (input: RequestInfo | URL) => { @@ -2637,12 +2725,12 @@ describe("ThreadShell", () => { if (url.includes("websocket%3Achat-fork/webui-thread")) { historyCalls += 1; return httpJson( - transcriptFromSimpleMessages( + streamedThreadPayload("chat-fork", historyCalls === 1 - ? [{ role: "user", content: "first fork question" }] + ? [{ role: "user", content: "first fork question", turnId: "first-fork-turn" }] : [ - { role: "user", content: "first fork question" }, - { role: "user", content: "second fork question" }, + { role: "user", content: "first fork question", turnId: "first-fork-turn" }, + { role: "user", content: "second fork question", turnId: secondTurnId }, ], ), ); @@ -2672,7 +2760,7 @@ describe("ThreadShell", () => { client._emitChat("chat-fork", { event: "message", chat_id: "chat-fork", - text: "first fork answer", + text: "first fork answer", turn_id: "first-fork-turn", turn_seq: 2, }); }); expect(screen.getByText("first fork answer")).toBeInTheDocument(); @@ -2684,6 +2772,8 @@ describe("ThreadShell", () => { await waitFor(() => expectSendMessageWithTurn(client, "chat-fork", "second fork question"), ); + secondTurnId = client.sendMessage.mock.calls[0]?.[3]?.turnId ?? ""; + expect(secondTurnId).not.toBe(""); expect(screen.getByText("second fork question")).toBeInTheDocument(); await act(async () => { @@ -2691,13 +2781,17 @@ describe("ThreadShell", () => { }); await waitFor(() => expect(historyCalls).toBe(2)); - expect(screen.getByText("first fork question")).toBeInTheDocument(); - expect(screen.getByText("first fork answer")).toBeInTheDocument(); - expect(screen.getByText("second fork question")).toBeInTheDocument(); + const firstQuestion = screen.getByText("first fork question"); + const firstAnswer = screen.getByText("first fork answer"); + const secondQuestion = screen.getByText("second fork question"); + expect(firstQuestion.compareDocumentPosition(firstAnswer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(firstAnswer.compareDocumentPosition(secondQuestion) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); }); it("recovers a truncated streamed answer after reconnecting", async () => { const client = makeClient(); + const turnId = "resume-turn"; + const streamId = "resume-answer"; let historyCalls = 0; vi.stubGlobal( "fetch", @@ -2705,16 +2799,18 @@ describe("ThreadShell", () => { const url = String(input); if (url.includes("websocket%3Aresume-chat/webui-thread")) { historyCalls += 1; - return httpJson( - transcriptFromSimpleMessages( + return httpJson({ + ...streamedThreadPayload("resume-chat", historyCalls === 1 - ? [{ role: "user", content: "question" }] + ? [{ role: "user", content: "question", turnId }] : [ - { role: "user", content: "question" }, - { role: "assistant", content: "partial answer completed while away" }, + { role: "user", content: "question", turnId }, + { role: "assistant", content: "partial answer completed while away", turnId, streamId }, ], + historyCalls === 1 ? [] : [turnId], ), - ); + has_pending_tool_calls: historyCalls === 1, + }); } return { ok: false, @@ -2740,13 +2836,13 @@ describe("ThreadShell", () => { act(() => { client._emitChat("resume-chat", { event: "goal_status", - chat_id: "resume-chat", + chat_id: "resume-chat", turn_id: turnId, status: "running", started_at: 1_700, }); client._emitChat("resume-chat", { event: "delta", - chat_id: "resume-chat", + chat_id: "resume-chat", turn_id: turnId, turn_seq: 2, stream_id: streamId, text: "partial answer", }); }); @@ -2778,7 +2874,7 @@ describe("ThreadShell", () => { historyCalls += 1; if (historyCalls > 1) return { ok: false, status: 304 }; return httpJson({ - ...transcriptFromSimpleMessages([{ role: "user", content: "question", turnId }]), + ...streamedThreadPayload(chatId, [{ role: "user", content: "question", turnId }]), has_pending_tool_calls: true, }); })); @@ -2793,23 +2889,23 @@ describe("ThreadShell", () => { status: "running", started_at: 1_700, }); client._emitChat(chatId, { - event: "delta", chat_id: chatId, turn_id: turnId, text: "cached prefix", + event: "delta", chat_id: chatId, turn_id: turnId, turn_seq: 2, + stream_id: "cached-answer", text: "cached prefix", }); }); await screen.findByText("cached prefix"); act(() => client._emitStatus("reconnecting")); // The reconnect coordinator can cache this response before the mounted // thread's conditional request returns the same body through HTTP 304. - act(() => webuiThreadCache.set(`websocket:${chatId}`, canonicalThreadPayload({ - schemaVersion: 3, + act(() => publishReconnectCompletion(client, chatId, { + ...streamedThreadPayload(chatId, [ + { role: "user", content: "question", turnId }, + { role: "assistant", content: "full cached answer", turnId, streamId: "cached-answer" }, + ], [turnId]), revision: "completed-revision", has_pending_tool_calls: false, - completed_turn_ids: [turnId], - messages: [ - { id: "canonical-user", role: "user", content: "question", turnId, createdAt: 1_000 }, - { id: "canonical-answer", role: "assistant", content: "full cached answer", turnId, createdAt: 2_000 }, - ], - })!)); + })); + expect(client.reconcileCanonicalCompletion).toHaveBeenCalledTimes(1); act(() => client._emitStatus("open")); await screen.findByText("full cached answer"); expect(historyCalls).toBe(2); @@ -2829,7 +2925,7 @@ describe("ThreadShell", () => { } historyCalls += 1; if (historyCalls === 1) return Promise.resolve(httpJson({ - ...transcriptFromSimpleMessages([{ role: "user", content: "question", turnId }]), + ...streamedThreadPayload(chatId, [{ role: "user", content: "question", turnId }]), has_pending_tool_calls: true, })); return new Promise>((resolve) => { finishOlderRead = resolve; }); @@ -2845,27 +2941,28 @@ describe("ThreadShell", () => { status: "running", started_at: 1_700, }); client._emitChat(chatId, { - event: "delta", chat_id: chatId, turn_id: turnId, text: "old active prefix", + event: "delta", chat_id: chatId, turn_id: turnId, turn_seq: 2, + stream_id: "published-answer", text: "old active prefix", }); }); await screen.findByText("old active prefix"); act(() => client._emitStatus("reconnecting")); act(() => client._emitStatus("open")); await waitFor(() => expect(historyCalls).toBe(2)); - const completed = canonicalThreadPayload({ - ...transcriptFromSimpleMessages([ + const completed = { + ...streamedThreadPayload(chatId, [ { role: "user", content: "question", turnId }, - { role: "assistant", content: "externally published final answer", turnId }, - ]), + { role: "assistant", content: "externally published final answer", turnId, streamId: "published-answer" }, + ], [turnId]), revision: "completed-revision", has_pending_tool_calls: false, - completed_turn_ids: [turnId], - })!; - act(() => webuiThreadCache.set(`websocket:${chatId}`, completed)); + }; + act(() => publishReconnectCompletion(client, chatId, completed)); + expect(client.reconcileCanonicalCompletion).toHaveBeenCalledTimes(1); await screen.findByText("externally published final answer"); expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument(); await act(async () => finishOlderRead(httpJson({ - ...transcriptFromSimpleMessages([{ role: "user", content: "question", turnId }]), + ...streamedThreadPayload(chatId, [{ role: "user", content: "question", turnId }]), revision: "older-active-revision", has_pending_tool_calls: true, active_turn_id: turnId, @@ -2875,6 +2972,7 @@ describe("ThreadShell", () => { expect(screen.queryByText("old active prefix")).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument(); expect(webuiThreadCache.get(`websocket:${chatId}`)).toBe(completed); + expect(client.reconcileCanonicalCompletion).toHaveBeenCalledTimes(1); }); it("refreshes after opening when mounted while the socket is reconnecting", async () => { @@ -2940,7 +3038,7 @@ describe("ThreadShell", () => { historyCalls === 1 ? [ { - role: "assistant", + id: "expired-window-replay", role: "assistant", content: "row from the expired latest window", turnId: "turn-old-window", }, @@ -2952,7 +3050,7 @@ describe("ThreadShell", () => { turnId: canonicalTurnId, }, { - role: "assistant", + id: "new-window-replay", role: "assistant", content: "answer in the new latest window", turnId: canonicalTurnId, }, @@ -3016,8 +3114,8 @@ describe("ThreadShell", () => { return httpJson({ ...transcriptFromSimpleMessages( chatACalls === 1 - ? [{ role: "assistant", content: "committed old lineage" }] - : [{ role: "assistant", content: "disjoint new lineage" }], + ? [{ id: "old-lineage-replay", role: "assistant", content: "committed old lineage" }] + : [{ id: "new-lineage-replay", role: "assistant", content: "disjoint new lineage" }], ), has_pending_tool_calls: false, }); @@ -3080,7 +3178,7 @@ describe("ThreadShell", () => { historyCalls += 1; if (historyCalls === 1) { return Promise.resolve(httpJson(transcriptFromSimpleMessages([ - { role: "assistant", content: "old canonical row" }, + { id: "old-canonical-replay", role: "assistant", content: "old canonical row" }, ]))); } return new Promise((resolve) => { @@ -3109,7 +3207,7 @@ describe("ThreadShell", () => { client._emitChat("reset-tail-race", { event: "message", chat_id: "reset-tail-race", - text: "local durable row after request", + text: "local durable row after request", turn_id: "durable-post-request-turn", turn_seq: 2, }); }); await waitFor(() => @@ -3119,7 +3217,7 @@ describe("ThreadShell", () => { await act(async () => { resolveRefresh?.(httpJson({ ...transcriptFromSimpleMessages([ - { role: "assistant", content: "disjoint canonical reset row" }, + { id: "disjoint-canonical-replay", role: "assistant", content: "disjoint canonical reset row" }, ]), has_pending_tool_calls: false, })); @@ -3139,6 +3237,9 @@ describe("ThreadShell", () => { vi.fn(async (input: RequestInfo | URL) => { if (String(input).includes("websocket%3Aempty-reset-chat/webui-thread")) { historyCalls += 1; + if (historyCalls > 1) return httpJson({ + schemaVersion: 3, projection: "events", events: [], has_pending_tool_calls: false, + }); } return { ok: false, @@ -3165,6 +3266,12 @@ describe("ThreadShell", () => { fireEvent.change(input, { target: { value: "rejected local turn" } }); fireEvent.click(screen.getByRole("button", { name: "Send message" })); await waitFor(() => expect(screen.getByText("rejected local turn")).toBeInTheDocument()); + const rejectedTurnId = client.sendMessage.mock.calls[0]?.[3]?.turnId; + expect(rejectedTurnId).toBeTruthy(); + act(() => client._emitError({ + kind: "turn_rejected", chatId: "empty-reset-chat", turnId: rejectedTurnId!, + detail: "message_rejected", + })); act(() => client._emitSessionUpdate("empty-reset-chat", "thread")); @@ -3194,13 +3301,14 @@ describe("ThreadShell", () => { vi.fn(async (input: RequestInfo | URL) => { if (String(input).includes("websocket%3Astrict-canonical/webui-thread")) { return httpJson({ - ...transcriptFromSimpleMessages( + ...streamedThreadPayload("strict-canonical", canonicalComplete ? [ { role: "user", content: "strict question", turnId }, - { role: "assistant", content: "strict canonical answer", turnId }, + { role: "assistant", content: "strict canonical answer", turnId, streamId: "strict-answer" }, ] : [{ role: "user", content: "strict question", turnId }], + canonicalComplete ? [turnId] : [], ), has_pending_tool_calls: !canonicalComplete, }); @@ -3240,7 +3348,7 @@ describe("ThreadShell", () => { event: "delta", chat_id: "strict-canonical", text: "strict partial", - turn_id: turnId, + turn_id: turnId, turn_seq: 2, stream_id: "strict-answer", }); }); await waitFor(() => expect(screen.getByText("strict partial")).toBeInTheDocument()); @@ -3254,88 +3362,86 @@ describe("ThreadShell", () => { expect(client.canReconcileCanonicalCompletion).toHaveBeenCalled(); }); - it("keeps completed content while deferring a rejected final lifecycle reconciliation", async () => { + it("keeps completed content while a newer run blocks lifecycle reconciliation", async () => { const client = makeClient(); + const chatId = "layout-recheck"; const turnId = "turn-layout-recheck"; + const newerTurnId = "newer-layout-turn"; let historyCalls = 0; - vi.stubGlobal( - "fetch", - vi.fn(async (input: RequestInfo | URL) => { - if (String(input).includes("websocket%3Alayout-recheck/webui-thread")) { - historyCalls += 1; - return httpJson({ - ...transcriptFromSimpleMessages( - historyCalls === 1 - ? [{ role: "user", content: "layout question", turnId }] - : [ - { role: "user", content: "layout question", turnId }, - { role: "assistant", content: "layout canonical answer", turnId }, - ], - ), - has_pending_tool_calls: historyCalls === 1, - }); - } - return { - ok: false, - status: 404, - json: async () => ({}), - }; - }), - ); - - render( - wrap( - client, - {}} - onNewChat={() => {}} - />, - ), - ); - - await waitFor(() => expect(screen.getByText("layout question")).toBeInTheDocument()); + let finishRefresh!: (response: Response) => void; + const completedBody = (includeNewer: boolean) => { + const rows: StreamedFixtureRow[] = [ + { role: "user", content: "layout question", turnId }, + { role: "assistant", content: "layout canonical answer", turnId, streamId: "layout-answer" }, + ]; + if (includeNewer) rows.push( + { role: "user", content: "newer layout question", turnId: newerTurnId }, + { role: "assistant", content: "newer layout complete", turnId: newerTurnId, streamId: "newer-layout-answer" }, + ); + return { + ...streamedThreadPayload(chatId, rows, includeNewer ? [turnId, newerTurnId] : [turnId]), + has_pending_tool_calls: false, + }; + }; + vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => { + if (!String(input).includes(`websocket%3A${chatId}/webui-thread`)) { + return Promise.resolve({ ok: false, status: 404, json: async () => ({}) }); + } + historyCalls += 1; + if (historyCalls === 1) return Promise.resolve(httpJson({ + ...streamedThreadPayload(chatId, [{ role: "user", content: "layout question", turnId }]), + has_pending_tool_calls: true, + })); + if (historyCalls === 2) return new Promise((resolve) => { finishRefresh = resolve; }); + return Promise.resolve(httpJson(completedBody(true))); + })); + render(wrap(client, {}} onNewChat={() => {}} />)); + await screen.findByText("layout question"); act(() => { - client._emitChat("layout-recheck", { - event: "goal_status", - chat_id: "layout-recheck", - status: "running", - started_at: 2_200, - turn_id: turnId, + client._emitChat(chatId, { + event: "goal_status", chat_id: chatId, status: "running", started_at: 2_200, turn_id: turnId, }); - client._emitChat("layout-recheck", { - event: "delta", - chat_id: "layout-recheck", - text: "layout partial", - turn_id: turnId, + client._emitChat(chatId, { + event: "delta", chat_id: chatId, text: "layout partial", turn_id: turnId, + turn_seq: 2, stream_id: "layout-answer", }); }); - await waitFor(() => expect(screen.getByText("layout partial")).toBeInTheDocument()); + await screen.findByText("layout partial"); + act(() => client._emitSessionUpdate(chatId, "thread")); + await waitFor(() => expect(historyCalls).toBe(2)); - const reconcileAfterReject = client.reconcileCanonicalCompletion.getMockImplementation(); - client.reconcileCanonicalCompletion - .mockImplementationOnce(() => false) - .mockImplementation((...args) => reconcileAfterReject?.(...args) ?? false); - - act(() => client._emitSessionUpdate("layout-recheck", "thread")); - - await waitFor(() => { - expect(historyCalls).toBe(2); - expect(client.reconcileCanonicalCompletion).toHaveBeenCalledTimes(1); - expect(screen.queryByText("layout partial")).not.toBeInTheDocument(); - expect(screen.getByText("layout canonical answer")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument(); + // Another tab starts a newer turn while this read is pending. Its running + // status invalidates settlement before the pure preflight runs. + act(() => { + for (const event of streamedThreadPayload(chatId, [ + { role: "user", content: "newer layout question", turnId: newerTurnId }, + ]).events) client._emitChat(chatId, event); + client._emitChat(chatId, { + event: "goal_status", chat_id: chatId, status: "running", started_at: 2_300, turn_id: newerTurnId, + }); + client._emitChat(chatId, { + event: "delta", chat_id: chatId, text: "newer layout partial", turn_id: newerTurnId, + turn_seq: 2, stream_id: "newer-layout-answer", + }); }); + await screen.findByText("newer layout partial"); + await act(async () => finishRefresh(httpJson(completedBody(false)))); + await screen.findByText("layout canonical answer"); + expect(screen.queryByText("layout partial")).not.toBeInTheDocument(); + expect(screen.getByText("newer layout partial")).toBeInTheDocument(); + expect(client.reconcileCanonicalCompletion).not.toHaveBeenCalled(); + expect(client.isRunCompleted(chatId, turnId)).toBe(true); + expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument(); - act(() => client._emitSessionUpdate("layout-recheck", "thread")); - - await waitFor(() => { - expect(historyCalls).toBe(3); - expect(screen.getByText("layout canonical answer")).toBeInTheDocument(); - expect(screen.queryByText("layout partial")).not.toBeInTheDocument(); - expect(client.reconcileCanonicalCompletion).toHaveBeenCalledTimes(2); - }); + act(() => client._emitSessionUpdate(chatId, "thread")); + await screen.findByText("newer layout complete"); + expect(historyCalls).toBe(3); + expect(screen.getByText("layout canonical answer")).toBeInTheDocument(); + expect(screen.queryByText("layout partial")).not.toBeInTheDocument(); + expect(screen.queryByText("newer layout partial")).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument(); + expect(client.reconcileCanonicalCompletion).toHaveBeenCalledTimes(1); }); it("adopts a completed equal-length history when returning after an inactive outage", async () => { @@ -3349,23 +3455,16 @@ describe("ThreadShell", () => { const url = String(input); if (url.includes("websocket%3Achat-version-a/webui-thread")) { chatACalls += 1; - const rows = chatACalls <= 2 - ? [ - { role: "user" as const, content: "old question", turnId: oldTurnId }, - { role: "assistant" as const, content: "old answer", turnId: oldTurnId }, - ] - : [ - { role: "user" as const, content: "old question", turnId: oldTurnId }, - { role: "assistant" as const, content: "old answer", turnId: oldTurnId }, - { role: "user" as const, content: "new question", turnId: newTurnId }, - { - role: "assistant" as const, - content: "partial answer completed", - turnId: newTurnId, - }, - ]; + const rows: StreamedFixtureRow[] = [ + { role: "user", content: "old question", turnId: oldTurnId }, + { role: "assistant", content: "old answer", turnId: oldTurnId, streamId: "old-answer" }, + ]; + if (chatACalls > 2) rows.push( + { role: "user", content: "new question", turnId: newTurnId }, + { role: "assistant", content: "partial answer completed", turnId: newTurnId, streamId: "new-answer" }, + ); return httpJson({ - ...transcriptFromSimpleMessages(rows), + ...streamedThreadPayload("chat-version-a", rows, chatACalls <= 2 ? [oldTurnId] : [oldTurnId, newTurnId]), has_pending_tool_calls: false, }); } @@ -3417,7 +3516,7 @@ describe("ThreadShell", () => { event: "delta", chat_id: "chat-version-a", text: "partial answer", - turn_id: newTurnId, + turn_id: newTurnId, turn_seq: 2, stream_id: "new-answer", }); }); await waitFor(() => expect(screen.getByText("partial answer")).toBeInTheDocument()); @@ -3512,12 +3611,16 @@ describe("ThreadShell", () => { expect(client.sendMessage).not.toHaveBeenCalled(); }); - it.each(["both", "current", "canonical"] as const)("keeps repeated guidance order and newer live output with %s turn ids", async (guidanceTurnIds) => { + it.each(["raw-turn", "session-message"] as const)("keeps repeated guidance order and newer live output with stable %s sources", async (guidanceIdentity) => { const client = makeClient(); const chatId = "completed-guidance-new-tail"; const turnId = "completed-guided-turn"; - const guidanceTurnId = "guidance-input"; - const repeatedGuidanceTurnId = "repeated-guidance-input"; + const guidanceRows = ["guidance-input", "repeated-guidance-input"].map((id): StreamedFixtureRow => ({ + role: "user", content: "supplemental guidance", startsTurn: false, activeTurnId: turnId, + ...(guidanceIdentity === "raw-turn" + ? { turnId: id } + : { sessionMessage: { message_id: id, session: { id: "guidance-session", name: "Guidance" } } }), + })); let historyCalls = 0; let resolveRefresh!: (response: ReturnType) => void; vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => { @@ -3526,7 +3629,7 @@ describe("ThreadShell", () => { } historyCalls += 1; if (historyCalls === 1) return Promise.resolve(httpJson({ - ...transcriptFromSimpleMessages([{ role: "user", content: "guided question", turnId }]), + ...streamedThreadPayload(chatId, [{ role: "user", content: "guided question", turnId }]), has_pending_tool_calls: true, })); return new Promise>((resolve) => { resolveRefresh = resolve; }); @@ -3543,32 +3646,26 @@ describe("ThreadShell", () => { }); client._emitChat(chatId, { event: "delta", chat_id: chatId, text: "first partial segment", turn_id: turnId, + turn_seq: 2, stream_id: "guided-first-answer", }); }); await screen.findByText("first partial segment"); act(() => { client._emitChat(chatId, { event: "stream_end", chat_id: chatId, turn_id: turnId, resuming: true, + turn_seq: 3, stream_id: "guided-first-answer", text: "first partial segment", }); - client._emitChat(chatId, { - event: "user_message", chat_id: chatId, - turn_id: guidanceTurnIds === "canonical" ? undefined : guidanceTurnId, - text: "supplemental guidance", starts_turn: false, active_turn_id: turnId, - }); - client._emitChat(chatId, { - event: "user_message", chat_id: chatId, - turn_id: guidanceTurnIds === "canonical" ? undefined : repeatedGuidanceTurnId, - text: "supplemental guidance", starts_turn: false, active_turn_id: turnId, - }); + for (const event of streamedThreadPayload(chatId, guidanceRows).events) client._emitChat(chatId, event); client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: turnId, text: "last partial segment", + turn_seq: 4, stream_id: "guided-last-answer", }); }); await screen.findByText("last partial segment"); act(() => client._emitSessionUpdate(chatId, "thread")); await waitFor(() => expect(historyCalls).toBe(2)); act(() => client._emitChat(chatId, { - event: "turn_end", chat_id: chatId, turn_id: turnId, + event: "turn_end", chat_id: chatId, turn_id: turnId, turn_seq: 6, })); fireEvent.change(screen.getByRole("textbox", { name: "Message input" }), { target: { value: "new local question" }, @@ -3583,21 +3680,18 @@ describe("ThreadShell", () => { }); client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: newerTurnId, text: "newer live reply", + turn_seq: 2, stream_id: "newer-guidance-answer", }); }); await screen.findByText("newer live reply"); await act(async () => resolveRefresh(httpJson({ - ...transcriptFromSimpleMessages([ + ...streamedThreadPayload(chatId, [ { role: "user", content: "guided question", turnId }, - { role: "assistant", content: "canonical first segment", turnId }, - { role: "user", content: "supplemental guidance", - turnId: guidanceTurnIds === "current" ? undefined : guidanceTurnId }, - { role: "user", content: "supplemental guidance", - turnId: guidanceTurnIds === "current" ? undefined : repeatedGuidanceTurnId }, - { role: "assistant", content: "canonical final segment", turnId }, - ]), + { role: "assistant", content: "canonical first segment", turnId, streamId: "guided-first-answer" }, + ...guidanceRows, + { role: "assistant", content: "canonical final segment", turnId, streamId: "guided-last-answer", textSeq: 4, endSeq: 5 }, + ], [turnId]), has_pending_tool_calls: false, - completed_turn_ids: [turnId], }))); const first = await screen.findByText("canonical first segment"); const guidance = screen.getAllByText("supplemental guidance"); @@ -3614,9 +3708,11 @@ describe("ThreadShell", () => { act(() => { client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: turnId, text: "obsolete delayed delta", + turn_seq: 7, stream_id: "guided-last-answer", }); client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: newerTurnId, text: " continued", + turn_seq: 3, stream_id: "newer-guidance-answer", }); }); await screen.findByText("newer live reply continued"); @@ -3631,13 +3727,23 @@ describe("ThreadShell", () => { const unseenTurnId = "other-tab-completed-turn"; const newerTurnId = "new-local-turn"; const messageCache = new ThreadMessageCache(() => false); - messageCache.set(chatId, createThreadCheckpoint([ + const owner = new ThreadTranscript([ { id: "older-page", role: "assistant", content: "older paginated answer", createdAt: 1 }, - { id: "cached-user", role: "user", content: "completed question", turnId: completedTurnId, createdAt: 2 }, - { id: "cached-prefix", role: "assistant", content: "outdated prefix", turnId: completedTurnId, createdAt: 3 }, - { id: "new-user", role: "user", content: "new local question", turnId: newerTurnId, createdAt: 7 }, - { id: "new-answer", role: "assistant", content: "new local stream", turnId: newerTurnId, isStreaming: true, createdAt: 8 }, - ])); + ]); + const cachedEvents = [ + { event: "user_message", chat_id: chatId, turn_id: completedTurnId, turn_seq: 1, + text: "completed question", starts_turn: true }, + { event: "delta", chat_id: chatId, turn_id: completedTurnId, turn_seq: 2, + stream_id: "completed-cached-answer", text: "outdated prefix" }, + { event: "user_message", chat_id: chatId, turn_id: newerTurnId, turn_seq: 1, + text: "new local question", starts_turn: true }, + { event: "delta", chat_id: chatId, turn_id: newerTurnId, turn_seq: 2, + stream_id: "new-local-answer", text: "new local stream" }, + ] satisfies ThreadProjectionEvent[]; + cachedEvents.forEach((event, index) => owner.project(event, { + createId: () => `cached-${index}`, now: index + 2, + })); + messageCache.set(chatId, owner.save()); client._emitChat(chatId, { event: "goal_status", chat_id: chatId, turn_id: newerTurnId, status: "running", started_at: 2_000, }); @@ -3646,12 +3752,12 @@ describe("ThreadShell", () => { return { ok: false, status: 404, json: async () => ({}) }; } return httpJson({ - ...transcriptFromSimpleMessages([ + ...streamedThreadPayload(chatId, [ { role: "user", content: "completed question", turnId: completedTurnId }, - { role: "assistant", content: "completed reply", turnId: completedTurnId }, + { role: "assistant", content: "completed reply", turnId: completedTurnId, streamId: "completed-cached-answer" }, { role: "user", content: "other tab question", turnId: unseenTurnId }, - { role: "assistant", content: "other tab completed reply", turnId: unseenTurnId }, - ]), + { role: "assistant", content: "other tab completed reply", turnId: unseenTurnId, streamId: "other-tab-answer" }, + ], [completedTurnId, unseenTurnId]), has_pending_tool_calls: false, completed_turn_ids: [completedTurnId, unseenTurnId], page: { before_cursor: "older-page", has_more_before: true, user_message_offset: 25 }, @@ -3672,21 +3778,37 @@ describe("ThreadShell", () => { expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument(); }); - it.each(["identified", "anonymous"] as const)("keeps completed guidance after a paginated prefix with %s live identity", async (guidanceIdentity) => { + it.each(["raw-turn", "session-message"] as const)("keeps completed guidance after a paginated prefix with stable %s sources", async (guidanceIdentity) => { const client = makeClient(); const chatId = "completed-guidance-paged-prefix"; + const guidanceRow: StreamedFixtureRow = { + role: "user", content: "continue", startsTurn: false, activeTurnId: "main", + ...(guidanceIdentity === "raw-turn" + ? { turnId: "guidance" } + : { sessionMessage: { message_id: "cached-guidance", session: { id: "guidance-session", name: "Guidance" } } }), + }; const messageCache = new ThreadMessageCache(() => false); - messageCache.set(chatId, createThreadCheckpoint([ + const owner = new ThreadTranscript([ { id: "old-user", role: "user", content: "continue", createdAt: 1 }, { id: "old-answer", role: "assistant", content: "older answer", createdAt: 2 }, - { id: "question", role: "user", content: "current question", turnId: "main", createdAt: 3 }, - { id: "first", role: "assistant", content: "first partial", turnId: "main", createdAt: 4 }, - { id: "guidance", role: "user", content: "continue", - ...(guidanceIdentity === "identified" ? { turnId: "guidance" } : {}), createdAt: 5 }, - { id: "last", role: "assistant", content: "last partial", turnId: "main", createdAt: 6 }, - { id: "new-user", role: "user", content: "new question", turnId: "new", createdAt: 7 }, - { id: "new-answer", role: "assistant", content: "new live answer", turnId: "new", isStreaming: true, createdAt: 8 }, - ])); + ]); + const cachedEvents = [ + { event: "user_message", chat_id: chatId, turn_id: "main", turn_seq: 1, + text: "current question", starts_turn: true }, + { event: "delta", chat_id: chatId, turn_id: "main", turn_seq: 2, + stream_id: "main-first-answer", text: "first partial" }, + ...streamedThreadPayload(chatId, [guidanceRow]).events, + { event: "delta", chat_id: chatId, turn_id: "main", turn_seq: 4, + stream_id: "main-last-answer", text: "last partial" }, + { event: "user_message", chat_id: chatId, turn_id: "new", turn_seq: 1, + text: "new question", starts_turn: true }, + { event: "delta", chat_id: chatId, turn_id: "new", turn_seq: 2, + stream_id: "new-live-answer", text: "new live answer" }, + ] satisfies ThreadProjectionEvent[]; + cachedEvents.forEach((event, index) => owner.project(event, { + createId: () => `cached-${index}`, now: index + 3, + })); + messageCache.set(chatId, owner.save()); client._emitChat(chatId, { event: "goal_status", chat_id: chatId, turn_id: "new", status: "running", started_at: 2_000, }); @@ -3695,12 +3817,12 @@ describe("ThreadShell", () => { return { ok: false, status: 404, json: async () => ({}) }; } return httpJson({ - ...transcriptFromSimpleMessages([ + ...streamedThreadPayload(chatId, [ { role: "user", content: "current question", turnId: "main" }, - { role: "assistant", content: "completed first", turnId: "main" }, - { role: "user", content: "continue", turnId: "guidance" }, - { role: "assistant", content: "completed last", turnId: "main" }, - ]), + { role: "assistant", content: "completed first", turnId: "main", streamId: "main-first-answer" }, + guidanceRow, + { role: "assistant", content: "completed last", turnId: "main", streamId: "main-last-answer", textSeq: 4, endSeq: 5 }, + ], ["main"]), has_pending_tool_calls: false, completed_turn_ids: ["main"], page: { before_cursor: "older-page", has_more_before: true, user_message_offset: 25 }, @@ -3726,6 +3848,7 @@ describe("ThreadShell", () => { expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument(); act(() => client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: "new", text: " continued", + turn_seq: 3, stream_id: "new-live-answer", })); await screen.findByText("new live answer continued"); }); @@ -3775,13 +3898,14 @@ describe("ThreadShell", () => { if (url.includes("websocket%3Alate-frame-chat/webui-thread")) { historyCalls += 1; return httpJson({ - ...transcriptFromSimpleMessages( + ...streamedThreadPayload("late-frame-chat", historyCalls === 1 ? [{ role: "user", content: "question", turnId }] : [ { role: "user", content: "question", turnId }, - { role: "assistant", content: "canonical complete answer", turnId }, + { role: "assistant", content: "canonical complete answer", turnId, streamId: "http-won-answer" }, ], + historyCalls === 1 ? [] : [turnId], ), has_pending_tool_calls: false, }); @@ -3819,7 +3943,7 @@ describe("ThreadShell", () => { event: "delta", chat_id: "late-frame-chat", text: "partial", - turn_id: turnId, + turn_id: turnId, turn_seq: 2, stream_id: "http-won-answer", }); }); await waitFor(() => expect(screen.getByText("partial")).toBeInTheDocument()); @@ -3834,18 +3958,19 @@ describe("ThreadShell", () => { event: "delta", chat_id: "late-frame-chat", text: " delayed duplicate", - turn_id: turnId, + turn_id: turnId, turn_seq: 2, stream_id: "http-won-answer", }); client._emitChat("late-frame-chat", { event: "turn_end", chat_id: "late-frame-chat", - turn_id: turnId, + turn_id: turnId, turn_seq: 4, }); client._emitSessionUpdate("late-frame-chat"); }); await waitFor(() => expect(historyCalls).toBe(3)); expect(screen.getAllByText("canonical complete answer")).toHaveLength(1); + expect(screen.queryByText("partial")).not.toBeInTheDocument(); expect(screen.queryByText(" delayed duplicate")).not.toBeInTheDocument(); expect(screen.queryByText("canonical complete answer delayed duplicate")).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument(); @@ -3995,12 +4120,12 @@ describe("ThreadShell", () => { vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => { if (String(input).includes(`websocket%3A${chatId}/webui-thread`)) { return httpJson({ - ...transcriptFromSimpleMessages([ + ...streamedThreadPayload(chatId, [ { role: "user", content: "previous question", turnId: "finished-turn" }, - { role: "assistant", content: "previous answer", turnId: "finished-turn" }, + { role: "assistant", content: "previous answer", turnId: "finished-turn", streamId: "finished-answer" }, { role: "user", content: "current question", turnId: "persisted-turn" }, - { role: "assistant", content: "saved answer prefix", turnId: "persisted-turn" }, - ]), + { role: "assistant", content: "saved answer prefix", turnId: "persisted-turn", streamId: "saved-answer" }, + ], ["finished-turn"]), completed_turn_ids: ["finished-turn"], has_pending_tool_calls: true, active_turn_id: turnId, @@ -4028,10 +4153,12 @@ describe("ThreadShell", () => { act(() => client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: turnId, text: "continued", + turn_seq: 4, stream_id: "continued-answer", })); await screen.findByText("continued"); act(() => client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: turnId, text: " answer", + turn_seq: 5, stream_id: "continued-answer", })); await screen.findByText("continued answer"); expect(screen.getByText("saved answer prefix")).toBeInTheDocument(); @@ -4052,7 +4179,7 @@ describe("ThreadShell", () => { ], expectVisible: false }, { name: "an empty successful page", rows: [], expectVisible: false }, { name: "a failed page", rows: [], expectVisible: false, error: true }, - ])("releases older-page loading after ThreadShell handles $name", async ({ rows, expectVisible, error = false }) => { + ])("atomically publishes older-page rows and loading completion for $name", async ({ rows, expectVisible, error = false }) => { const client = makeClient(); const chatId = `older-projection-${expectVisible ? "visible" : "hidden"}`; let resolveOlder!: (response: Response) => void; @@ -4099,6 +4226,7 @@ describe("ThreadShell", () => { if (expectVisible) { act(() => client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: "current-turn", text: "live during pagination", + turn_seq: 2, stream_id: "pagination-answer", })); await screen.findByText("live during pagination"); } @@ -4113,7 +4241,12 @@ describe("ThreadShell", () => { }); if (expectVisible) await screen.findByText("older answer"); await waitFor(() => expect(container.querySelector('.thread-history-status[data-state="loading"]')).toBeNull()); - expect(commits.some((commit) => commit.loading && !commit.olderVisible)).toBe(expectVisible); + expect(commits.length).toBeGreaterThan(0); + expect(commits.at(-1)?.loading).toBe(false); + if (expectVisible) { + expect(commits.some((commit) => !commit.loading && !commit.olderVisible)).toBe(false); + expect(commits.at(-1)?.olderVisible).toBe(true); + } if (error) { expect(container.querySelector('.thread-history-status[data-state="error"]')).toBeInTheDocument(); expect(container.querySelector(".thread-history-slot")).toBeInTheDocument(); @@ -4190,23 +4323,24 @@ describe("ThreadShell", () => { const url = String(input); if (url.includes("websocket%3Abefore-delta-chat/webui-thread")) { historyCalls += 1; - const transcript = transcriptFromSimpleMessages( + const transcript = streamedThreadPayload("before-delta-chat", historyCalls === 1 ? [{ role: "user", content: "question", turnId }] : [ { role: "user", content: "question", turnId }, { - role: "assistant", - content: historyCalls === 2 - ? "missed prefix" - : "missed prefix resumed suffix", - turnId, + role: "assistant", turnId, streamId: "before-delta-answer", + content: historyCalls === 2 ? "missed prefix" : "missed prefix resumed suffix", + endSeq: historyCalls === 2 ? 3 : 5, + mergeNext: historyCalls === 2, }, ], + historyCalls < 3 ? [] : [turnId], ); return httpJson({ ...transcript, - has_pending_tool_calls: historyCalls === 2, + has_pending_tool_calls: historyCalls < 3, + active_turn_id: historyCalls < 3 ? turnId : null, }); } return { @@ -4248,7 +4382,7 @@ describe("ThreadShell", () => { act(() => client._emitStatus("reconnecting")); act(() => client._emitStatus("open")); await waitFor(() => expect(historyCalls).toBe(2)); - expect(screen.queryByText("missed prefix")).not.toBeInTheDocument(); + await screen.findByText("missed prefix"); expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument(); expect(client.sendMessage).not.toHaveBeenCalled(); @@ -4256,11 +4390,14 @@ describe("ThreadShell", () => { client._emitChat("before-delta-chat", { event: "delta", chat_id: "before-delta-chat", - text: "resumed suffix", - turn_id: turnId, + text: " resumed suffix", + turn_id: turnId, turn_seq: 4, stream_id: "before-delta-answer", }); }); - await waitFor(() => expect(screen.getByText("resumed suffix")).toBeInTheDocument()); + await screen.findByText("missed prefix resumed suffix"); + expect(screen.queryByText("missed prefix")).not.toBeInTheDocument(); + expect(screen.queryByText("resumed suffix")).not.toBeInTheDocument(); + expect(client.sendMessage).not.toHaveBeenCalled(); act(() => client._emitStatus("reconnecting")); act(() => client._emitStatus("open")); @@ -4286,25 +4423,25 @@ describe("ThreadShell", () => { const url = String(input); if (url.includes("websocket%3Aactive-resume-chat/webui-thread")) { historyCalls += 1; - const transcript = transcriptFromSimpleMessages( + const transcript = streamedThreadPayload("active-resume-chat", historyCalls === 1 ? [{ role: "user", content: "question", turnId }] : [ { role: "user", content: "question", turnId }, { - role: "assistant", - content: historyCalls === 2 - ? "partial answer missed" - : "partial answer missed resumed", - turnId, + role: "assistant", turnId, streamId: "active-resume-answer", + content: historyCalls === 2 ? "partial answer missed" : "partial answer missed resumed", + endSeq: historyCalls === 2 ? 4 : 6, + mergeNext: historyCalls === 2, }, ], + historyCalls < 3 ? [] : [turnId], ); - return httpJson( - historyCalls === 1 - ? transcript - : { ...transcript, has_pending_tool_calls: historyCalls === 2 }, - ); + return httpJson({ + ...transcript, + has_pending_tool_calls: historyCalls < 3, + active_turn_id: historyCalls < 3 ? turnId : null, + }); } return { ok: false, @@ -4339,7 +4476,7 @@ describe("ThreadShell", () => { event: "delta", chat_id: "active-resume-chat", text: "partial answer", - turn_id: turnId, + turn_id: turnId, turn_seq: 2, stream_id: "active-resume-answer", }); }); await waitFor(() => expect(screen.getByText("partial answer")).toBeInTheDocument()); @@ -4360,7 +4497,7 @@ describe("ThreadShell", () => { event: "delta", chat_id: "active-resume-chat", text: " resumed", - turn_id: turnId, + turn_id: turnId, turn_seq: 5, stream_id: "active-resume-answer", }); }); diff --git a/webui/src/tests/thread-transcript.test.ts b/webui/src/tests/thread-transcript.test.ts new file mode 100644 index 000000000..b7dc9bf3f --- /dev/null +++ b/webui/src/tests/thread-transcript.test.ts @@ -0,0 +1,629 @@ +import { beforeEach, describe, expect, it } from "vitest"; + +import { ThreadTranscript } from "@/lib/thread-transcript"; +import type { ThreadProjectionEvent, WebuiThreadPersistedPayload } from "@/lib/types"; + +const NOW = 1_800_000_000_000; +let nextId = 0; + +beforeEach(() => { nextId = 0; }); + +function at(turn_id: string, turn_seq: number) { + return { chat_id: "hydration-chat", turn_id, turn_seq }; +} + +function input(turnId: string, text: string): ThreadProjectionEvent { + return { ...at(turnId, 1), event: "user_message", text, starts_turn: true }; +} + +function history( + events: ThreadProjectionEvent[], + options: Partial> = {}, +): WebuiThreadPersistedPayload { + return { + schemaVersion: 3, + projection: "events", + events: events.map((event, index) => ({ + ...event, + projection_id: event.projection_id + ?? `canonical:${event.turn_id}:${"turn_seq" in event ? event.turn_seq : index}`, + })), + page: { before_cursor: null, has_more_before: false, user_message_offset: 0 }, + ...options, + }; +} + +function receive(thread: ThreadTranscript, ...events: ThreadProjectionEvent[]): void { + for (const event of events) thread.project(event, { + createId: () => `received-${++nextId}`, + now: NOW, + }); +} + +describe("ThreadTranscript admission", () => { + it("installs an older safe prefix without replacing or redirecting the received foreground", () => { + const thread = new ThreadTranscript(); + const read = thread.begin("initial"); + receive(thread, + input("turn-now", "Current question"), + { ...at("turn-now", 2), event: "delta", stream_id: "answer-now", text: "Live " }, + ); + const foregroundId = thread.messages.at(-1)?.id; + + expect(thread.accept(history([ + input("turn-before", "Earlier question"), + { ...at("turn-before", 2), event: "message", text: "Earlier answer" }, + { ...at("turn-before", 3), event: "turn_end" }, + input("turn-now", "Current question"), + ], { page: { before_cursor: "before-earlier", has_more_before: true, user_message_offset: 7 } }), read)).toBe(true); + + expect(thread.messages.map((row) => row.content)).toEqual([ + "Earlier question", "Earlier answer", "Current question", "Live ", + ]); + expect(thread.paging).toMatchObject({ beforeCursor: "before-earlier", hasMoreBefore: true, userMessageOffset: 7 }); + receive(thread, { ...at("turn-now", 3), event: "delta", stream_id: "answer-now", text: "continues" }); + expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Live continues" }); + }); + + it("admits independent same-text segments in the active turn using their distinct source identities", () => { + const thread = new ThreadTranscript(); + const read = thread.begin("initial"); + // Attach during C; A and B ended before this WebSocket attachment. + receive(thread, + input("turn-active", "Continue"), + { ...at("turn-active", 6), event: "delta", stream_id: "wire-C", text: "Current" }, + { ...at("turn-active", 7), event: "stream_end", stream_id: "wire-C", text: "Current", resuming: true, merge_next: true }, + { ...at("turn-active", 8), event: "delta", stream_id: "wire-C", text: " tail" }, + ); + const foregroundId = thread.messages.at(-1)?.id; + + expect(thread.accept(history([ + input("turn-active", "Continue"), + { ...at("turn-active", 3), event: "stream_end", stream_id: "wire-A", text: "same" }, + { ...at("turn-active", 5), event: "stream_end", stream_id: "wire-B", text: "same" }, + { ...at("turn-active", 7), event: "stream_end", stream_id: "wire-C", text: "Current", resuming: true, merge_next: true }, + ]), read)).toBe(true); + + const answers = thread.messages.filter((row) => row.role === "assistant"); + expect(answers.map((row) => row.content)).toEqual(["same", "same", "Current tail"]); + expect(answers[0].id).not.toBe(answers[1].id); + expect(answers[2].id).toBe(foregroundId); + receive(thread, { ...at("turn-active", 9), event: "delta", stream_id: "wire-C", text: " next" }); + expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Current tail next" }); + }); + + it("holds every live slice of one cumulative wire and does not move its hosted tool before the first slice", () => { + const thread = new ThreadTranscript(); + const read = thread.begin("initial"); + receive(thread, + input("turn-hosted", "Inspect"), + { ...at("turn-hosted", 4), event: "delta", stream_id: "wire-hosted", text: "L1 " }, + { ...at("turn-hosted", 5), event: "message", kind: "progress", text: "Hosted search" }, + { ...at("turn-hosted", 6), event: "delta", stream_id: "wire-hosted", text: "L2" }, + ); + const leftId = thread.messages[1].id; + const rightId = thread.messages[3].id; + const aggregate: ThreadProjectionEvent = { + ...at("turn-hosted", 7), event: "stream_end", stream_id: "wire-hosted", + text: "L1 L2", resuming: true, merge_next: true, + }; + + // HTTP has compacted S's deltas into its later cumulative end, after the tool. + expect(thread.accept(history([ + input("turn-hosted", "Inspect"), + { ...at("turn-hosted", 3), event: "stream_end", stream_id: "wire-earlier", text: "Earlier independent segment" }, + { ...at("turn-hosted", 5), event: "message", kind: "progress", text: "Hosted search" }, + aggregate, + ]), read)).toBe(true); + + expect(thread.messages.map((row) => row.content)).toEqual([ + "Inspect", "Earlier independent segment", "L1 ", "Hosted search", "L2", + ]); + expect(thread.messages[2].id).toBe(leftId); + expect(thread.messages[4].id).toBe(rightId); + // A held aggregate grants no text certificate: the real end must still project. + receive(thread, aggregate, + { ...at("turn-hosted", 8), event: "delta", stream_id: "wire-hosted", text: " continued" }, + ); + expect(thread.messages.at(-1)).toMatchObject({ id: rightId, content: "L1 L2 continued" }); + expect(thread.messages[2]).toMatchObject({ id: leftId, content: "L1 " }); + expect(thread.messages[3].content).toBe("Hosted search"); + }); + + it("holds a mixed reasoning-and-answer row as a whole while its answer has a newer continuation", () => { + const thread = new ThreadTranscript(); + const read = thread.begin("initial"); + receive(thread, + input("turn-mixed", "Explain"), + { ...at("turn-mixed", 2), event: "reasoning_delta", stream_id: "reasoning-mixed", text: "Think." }, + { ...at("turn-mixed", 3), event: "reasoning_end", stream_id: "reasoning-mixed" }, + { ...at("turn-mixed", 4), event: "delta", stream_id: "answer-mixed", text: "Draft" }, + { ...at("turn-mixed", 5), event: "stream_end", stream_id: "answer-mixed", text: "Draft", resuming: true, merge_next: true }, + { ...at("turn-mixed", 6), event: "delta", stream_id: "answer-mixed", text: " live" }, + ); + const sharedId = thread.messages[1].id; + + expect(thread.accept(history([ + input("turn-mixed", "Explain"), + { ...at("turn-mixed", 3), event: "reasoning_end", stream_id: "reasoning-mixed", text: "Think." }, + { ...at("turn-mixed", 5), event: "stream_end", stream_id: "answer-mixed", text: "Draft", resuming: true, merge_next: true }, + ]), read)).toBe(true); + + expect(thread.messages.filter((row) => row.role === "assistant")).toMatchObject([ + { id: sharedId, reasoning: "Think.", content: "Draft live" }, + ]); + receive(thread, { ...at("turn-mixed", 7), event: "delta", stream_id: "answer-mixed", text: " more" }); + expect(thread.messages.at(-1)).toMatchObject({ id: sharedId, reasoning: "Think.", content: "Draft live more" }); + }); + + it("suppresses history-covered late text but continues the installed cursor and respects its next real end", () => { + const thread = new ThreadTranscript(); + const installed: ThreadProjectionEvent = { + ...at("turn-history-first", 4), event: "stream_end", stream_id: "answer-first", + text: "Installed ", resuming: true, merge_next: true, + }; + expect(thread.accept(history([input("turn-history-first", "Continue"), installed]), thread.begin("initial"))).toBe(true); + const answerId = thread.messages[1].id; + + receive(thread, + { ...at("turn-history-first", 2), event: "delta", stream_id: "answer-first", text: "Installed " }, + installed, + { ...at("turn-history-first", 5), event: "delta", stream_id: "answer-first", text: "continuation" }, + ); + expect(thread.messages).toHaveLength(2); + expect(thread.messages[1]).toMatchObject({ id: answerId, content: "Installed continuation" }); + + receive(thread, + { ...at("turn-history-first", 6), event: "stream_end", stream_id: "answer-first", text: "Installed continuation" }, + { ...at("turn-history-first", 7), event: "delta", stream_id: "answer-next", text: "Next segment" }, + ); + expect(thread.messages.filter((row) => row.role === "assistant").map((row) => row.content)) + .toEqual(["Installed continuation", "Next segment"]); + expect(thread.messages[2].id).not.toBe(answerId); + }); + + it.each([false, true])("retains a closed wire through a truncated page and historical delivery (visible slice: %s)", (visibleSlice) => { + const thread = new ThreadTranscript(); + // A capped active-turn window can start after an earlier chunk. A textless + // end is a wire fence even when this window has no body for that wire. + expect(thread.accept(history([ + ...(visibleSlice ? [{ ...at("turn-capped", 3), event: "delta" as const, stream_id: "closed-wire", text: "Retained slice" }] : []), + { ...at("turn-capped", 4), event: "stream_end", stream_id: "closed-wire", resuming: true }, + { ...at("turn-capped", 7), event: "stream_end", stream_id: "current-wire", text: "Current", resuming: true, merge_next: true }, + ], { page: { before_cursor: "earlier", has_more_before: true, user_message_offset: 0, + truncated_oversized_turn: true } }), thread.begin("initial"))).toBe(true); + const restored = new ThreadTranscript([], thread.save()); + const contents = restored.messages.map((row) => row.content); + receive(restored, { ...at("turn-capped", 2), event: "delta", stream_id: "closed-wire", text: "Late older chunk" }); + expect(restored.messages.map((row) => row.content)).toEqual(contents); + receive(restored, { ...at("turn-capped", 8), event: "delta", stream_id: "current-wire", text: " continues" }); + expect(restored.messages.at(-1)?.content).toBe("Current continues"); + }); + + it("keeps missing-ID reasoning segments separate at their actual ends and does not swallow a fresh segment", () => { + const thread = new ThreadTranscript(); + expect(thread.accept(history([ + input("turn-no-id", "Think in stages"), + { ...at("turn-no-id", 3), event: "reasoning_end", text: "First thought" }, + { ...at("turn-no-id", 4), event: "message", kind: "progress", text: "Read a file" }, + { ...at("turn-no-id", 7), event: "reasoning_end", text: "Second thought" }, + ]), thread.begin("initial"))).toBe(true); + + receive(thread, + { ...at("turn-no-id", 2), event: "reasoning_delta", text: "First thought" }, + { ...at("turn-no-id", 6), event: "reasoning_delta", text: "Second thought" }, + { ...at("turn-no-id", 3), event: "reasoning_end", text: "First thought" }, + { ...at("turn-no-id", 8), event: "reasoning_delta", text: "Third thought" }, + { ...at("turn-no-id", 9), event: "reasoning_end" }, + { ...at("turn-no-id", 10), event: "delta", stream_id: "answer-after-thoughts", text: "Fresh answer" }, + ); + + expect(thread.messages.filter((row) => row.reasoning).map((row) => row.reasoning)) + .toEqual(["First thought", "Second thought", "Third thought"]); + expect(thread.messages).toHaveLength(5); + expect(thread.messages.at(-1)).toMatchObject({ reasoning: "Third thought", content: "Fresh answer" }); + }); + + it("admits earlier missing-ID reasoning segments before an already received later segment", () => { + const thread = new ThreadTranscript(); + const read = thread.begin("initial"); + // Attach after the first reasoning end; the received delta belongs to the second buffer. + receive(thread, + input("turn-reasoning-attach", "Think in stages"), + { ...at("turn-reasoning-attach", 6), event: "reasoning_delta", text: "Second live" }, + ); + const foregroundId = thread.messages.at(-1)?.id; + + expect(thread.accept(history([ + input("turn-reasoning-attach", "Think in stages"), + { ...at("turn-reasoning-attach", 3), event: "reasoning_end", text: "First thought" }, + { ...at("turn-reasoning-attach", 4), event: "message", kind: "progress", text: "Read a file" }, + { ...at("turn-reasoning-attach", 7), event: "reasoning_end", text: "Second snapshot" }, + ]), read)).toBe(true); + + expect(thread.messages.map((row) => row.reasoning || row.content)).toEqual([ + "Think in stages", "First thought", "Read a file", "Second live", + ]); + receive(thread, { ...at("turn-reasoning-attach", 8), event: "reasoning_delta", text: " continues" }); + expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, reasoning: "Second live continues" }); + }); + + it("honors exact summary receipts while inserting a late hole without closing the foreground answer", () => { + const thread = new ThreadTranscript(); + const detail = { ref: "2.history-summary", bytes: 40_000, traceCount: 3 }; + expect(thread.accept(history([ + input("turn-unrelated", "Earlier question"), + { ...at("turn-unrelated", 2), event: "message", text: "Earlier answer" }, + { ...at("turn-unrelated", 3), event: "turn_end" }, + input("turn-summary", "Run tools"), + { + ...at("turn-summary", 3), event: "message", kind: "progress", text: "Tools summary", + trace_detail: detail, + projection_receipts: [{ turn_id: "turn-summary", ranges: [[3, 4], [8, 8]] }], + }, + { ...at("turn-summary", 10), event: "stream_end", stream_id: "answer-summary", text: "Foreground ", resuming: true, merge_next: true }, + ]), thread.begin("initial"))).toBe(true); + const foregroundId = thread.messages.at(-1)?.id; + + receive(thread, + { ...at("turn-summary", 4), event: "message", kind: "progress", text: "Already summarized member 4" }, + { ...at("turn-summary", 8), event: "message", kind: "progress", text: "Already summarized member 8" }, + { ...at("turn-summary", 11), event: "delta", stream_id: "answer-summary", text: "live" }, + { ...at("turn-summary", 6), event: "message", kind: "progress", text: "Delayed independent tool" }, + { ...at("turn-summary", 12), event: "delta", stream_id: "answer-summary", text: " continues" }, + ); + + expect(thread.messages.map((row) => row.content)).toEqual([ + "Earlier question", "Earlier answer", "Run tools", "Tools summary", "Delayed independent tool", "Foreground live continues", + ]); + expect(thread.messages[3].traceDetail).toEqual(detail); + expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, isStreaming: true }); + }); + + it("does not install a later turn's completion receipt behind a held canonical source", () => { + const thread = new ThreadTranscript(); + const read = thread.begin("initial"); + receive(thread, + input("turn-held", "Current question"), + { ...at("turn-held", 2), event: "delta", stream_id: "answer-held", text: "Current live" }, + ); + expect(thread.accept(history([ + input("turn-held", "Current question"), + { ...at("turn-held", 3), event: "stream_end", stream_id: "answer-held", text: "Current snapshot", resuming: true, merge_next: true }, + input("turn-later", "Later question"), + { ...at("turn-later", 2), event: "message", text: "Later canonical answer" }, + { ...at("turn-later", 3), event: "turn_end", latency_ms: 250 }, + ]), read)).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["Current question", "Current live"]); + + receive(thread, + input("turn-later", "Later question"), + { ...at("turn-later", 2), event: "delta", stream_id: "answer-later", text: "Later received answer" }, + { ...at("turn-later", 3), event: "turn_end", latency_ms: 250 }, + ); + expect(thread.messages.at(-1)).toMatchObject({ content: "Later received answer", isStreaming: false, latencyMs: 250 }); + }); + + it("advances the accepted cursor and user offset across an older hidden-only page", () => { + const thread = new ThreadTranscript(); + expect(thread.accept(history([ + input("turn-visible", "Visible question"), + { ...at("turn-visible", 3), event: "stream_end", stream_id: "answer-visible", text: "Visible answer" }, + { ...at("turn-visible", 4), event: "turn_end" }, + ], { page: { before_cursor: "before-visible", has_more_before: true, user_message_offset: 6 } }), thread.begin("initial"))).toBe(true); + const visible = thread.messages; + const version = thread.paging.version; + + expect(thread.accept(history([], { + page: { before_cursor: "before-hidden", has_more_before: true, user_message_offset: 4, loaded_event_count: 20 }, + }), thread.begin("older"))).toBe(true); + + expect(thread.messages).toEqual(visible); + expect(thread.paging).toMatchObject({ + beforeCursor: "before-hidden", hasMoreBefore: true, userMessageOffset: 4, + loadingOlder: false, olderError: null, + }); + expect(thread.paging.version).toBe(version); + }); + + it("restores a cached full cursor and coverage before reasoning and answer continuation", () => { + const original = new ThreadTranscript(); + expect(original.accept(history([ + input("turn-cached", "Continue after returning"), + { ...at("turn-cached", 3), event: "reasoning_end", text: "Plan." }, + { ...at("turn-cached", 5), event: "stream_end", stream_id: "answer-cached", text: "First", resuming: true, merge_next: true }, + ]), original.begin("initial"))).toBe(true); + const sharedId = original.messages[1].id; + expect(original.accept(history([ + input("turn-cached-older", "Earlier cached question"), + { ...at("turn-cached-older", 2), event: "message", text: "Earlier cached answer" }, + { ...at("turn-cached-older", 3), event: "turn_end" }, + ], { page: { before_cursor: "before-cached-older", has_more_before: true, user_message_offset: 3 } }), original.begin("older"))).toBe(true); + const saved = original.save(); + receive(original, input("turn-other", "Another visit")); + const restored = new ThreadTranscript([], saved); + + receive(restored, + { ...at("turn-cached", 4), event: "delta", stream_id: "answer-cached", text: "First" }, + { ...at("turn-cached", 6), event: "reasoning_delta", text: "Continue." }, + { ...at("turn-cached", 7), event: "reasoning_end" }, + { ...at("turn-cached", 8), event: "delta", stream_id: "answer-cached", text: " second" }, + ); + + expect(restored.messages).toHaveLength(4); + expect(restored.messages.slice(0, 2).map((row) => row.content)).toEqual(["Earlier cached question", "Earlier cached answer"]); + expect(restored.paging).toMatchObject({ beforeCursor: "before-cached-older", hasMoreBefore: true, userMessageOffset: 3 }); + expect(restored.messages.at(-1)).toMatchObject({ + id: sharedId, content: "First second", reasoning: "Plan.\n\nContinue.", + }); + expect(restored.messages.some((row) => row.turnId === "turn-other")).toBe(false); + }); + + it("preserves the loaded older prefix and its frontier when a latest window overlaps the suffix", () => { + const thread = new ThreadTranscript(); + const latest = [ + input("turn-second", "Second question"), + { ...at("turn-second", 2), event: "message", text: "Second answer" }, + { ...at("turn-second", 3), event: "turn_end" }, + ] satisfies ThreadProjectionEvent[]; + expect(thread.accept(history(latest, { + page: { before_cursor: "before-second", has_more_before: true, user_message_offset: 1 }, + }), thread.begin("initial"))).toBe(true); + expect(thread.accept(history([ + input("turn-first", "First question"), + { ...at("turn-first", 2), event: "message", text: "First answer" }, + { ...at("turn-first", 3), event: "turn_end" }, + ], { page: { before_cursor: "before-first", has_more_before: false, user_message_offset: 0 } }), thread.begin("older"))).toBe(true); + + expect(thread.accept(history(latest, { + page: { before_cursor: "before-second", has_more_before: true, user_message_offset: 1 }, + }), thread.begin("latest"))).toBe(true); + + expect(thread.messages.map((row) => row.content)).toEqual([ + "First question", "First answer", "Second question", "Second answer", + ]); + expect(thread.paging).toMatchObject({ beforeCursor: "before-first", hasMoreBefore: false, userMessageOffset: 0 }); + }); + + it("rejects an older ticket from before an authorized latest-window reset without moving the frontier", () => { + const thread = new ThreadTranscript(); + expect(thread.accept(history([ + input("turn-canonical-old", "Old window"), + { ...at("turn-canonical-old", 2), event: "message", text: "Old answer" }, + { ...at("turn-canonical-old", 3), event: "turn_end" }, + ], { page: { before_cursor: "before-old", has_more_before: true, user_message_offset: 4 } }), thread.begin("initial"))).toBe(true); + const older = thread.begin("older"); + const refresh = thread.begin("latest"); + expect(thread.accept(history([ + input("turn-canonical-new", "New window"), + { ...at("turn-canonical-new", 2), event: "message", text: "New answer" }, + { ...at("turn-canonical-new", 3), event: "turn_end" }, + ], { page: { before_cursor: "before-reset", has_more_before: true, user_message_offset: 9 } }), refresh)).toBe(true); + const accepted = thread.messages; + + expect(thread.accept(history([ + input("turn-too-old", "Stale older question"), + { ...at("turn-too-old", 2), event: "message", text: "Stale older answer" }, + ], { page: { before_cursor: "before-stale", has_more_before: false, user_message_offset: 0 } }), older)).toBe(false); + + expect(thread.messages).toEqual(accepted); + expect(thread.paging).toMatchObject({ beforeCursor: "before-reset", hasMoreBefore: true, userMessageOffset: 9 }); + }); + + it("reports a stalled older cursor as retryable without installing rows or claiming exhaustion", () => { + const thread = new ThreadTranscript(); + const events = [ + input("turn-stalled", "Question"), + { ...at("turn-stalled", 2), event: "message", text: "Answer" }, + { ...at("turn-stalled", 3), event: "turn_end" }, + ] satisfies ThreadProjectionEvent[]; + expect(thread.accept(history(events, { + page: { before_cursor: "same-cursor", has_more_before: true, user_message_offset: 6 }, + }), thread.begin("initial"))).toBe(true); + const accepted = thread.messages; + + expect(thread.accept(history(events, { + page: { before_cursor: "same-cursor", has_more_before: true, user_message_offset: 4 }, + }), thread.begin("older"))).toBe(false); + + expect(thread.messages).toEqual(accepted); + expect(thread.paging).toMatchObject({ + beforeCursor: "same-cursor", hasMoreBefore: true, userMessageOffset: 6, loadingOlder: false, + }); + expect(thread.paging.olderError).toEqual(expect.any(String)); + expect(thread.paging.olderError).not.toBe(""); + }); + + it("retains a post-request input and its received tail when an older latest snapshot returns", () => { + const thread = new ThreadTranscript(); + const old = history([ + input("turn-settled", "Settled question"), + { ...at("turn-settled", 2), event: "message", text: "Settled answer" }, + { ...at("turn-settled", 3), event: "turn_end" }, + ]); + expect(thread.accept(old, thread.begin("initial"))).toBe(true); + const refresh = thread.begin("latest"); + receive(thread, + input("turn-new-input", "New question"), + { ...at("turn-new-input", 2), event: "delta", stream_id: "answer-new-input", text: "New live" }, + ); + const foregroundId = thread.messages.at(-1)?.id; + + expect(thread.accept(old, refresh)).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual([ + "Settled question", "Settled answer", "New question", "New live", + ]); + receive(thread, { ...at("turn-new-input", 3), event: "delta", stream_id: "answer-new-input", text: " tail" }); + expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "New live tail" }); + }); + + it("keeps a received answer between its two canonical input anchors when a refresh omits that answer", () => { + const thread = new ThreadTranscript(); + expect(thread.accept(history([input("turn-fork-first", "First question")]), thread.begin("initial"))).toBe(true); + receive(thread, + { ...at("turn-fork-first", 2), event: "message", text: "First live answer" }, + input("turn-fork-second", "Second question"), + ); + + expect(thread.accept(history([ + input("turn-fork-first", "First question"), + input("turn-fork-second", "Second question"), + ]), thread.begin("latest"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual([ + "First question", "First live answer", "Second question", + ]); + }); + + it("does not treat an unanchored durable reply received after the request as proof of a new append turn", () => { + const thread = new ThreadTranscript(); + expect(thread.accept(history([ + { chat_id: "hydration-chat", event: "message", projection_id: "old-canonical", text: "Old canonical row" }, + ]), thread.begin("initial"))).toBe(true); + const refresh = thread.begin("latest"); + receive(thread, { ...at("turn-unanchored-tail", 2), event: "message", text: "Received durable tail" }); + + expect(thread.accept(history([ + { chat_id: "hydration-chat", event: "message", projection_id: "disjoint-canonical", text: "Disjoint canonical row" }, + ]), refresh)).toBe(false); + expect(thread.messages.map((row) => row.content)).toEqual(["Old canonical row", "Received durable tail"]); + }); + + it("retires a disjoint canonical window on refresh while keeping a post-request received tail", () => { + const thread = new ThreadTranscript(); + expect(thread.accept(history([ + input("turn-retired", "Old cached window"), + { ...at("turn-retired", 2), event: "stream_end", stream_id: "answer-retired", text: "Old answer" }, + { ...at("turn-retired", 3), event: "turn_end" }, + ], { page: { before_cursor: "before-retired", has_more_before: true, user_message_offset: 4 } }), thread.begin("initial"))).toBe(true); + const older = thread.begin("older"); + const refresh = thread.begin("latest"); + receive(thread, + input("turn-post-request", "New input"), + { ...at("turn-post-request", 2), event: "delta", stream_id: "answer-post-request", text: "Live" }, + ); + const foregroundId = thread.messages.at(-1)?.id; + + expect(thread.accept(history([ + input("turn-revalidated", "New canonical window"), + { ...at("turn-revalidated", 2), event: "message", text: "Canonical answer" }, + { ...at("turn-revalidated", 3), event: "turn_end" }, + ], { page: { before_cursor: "before-revalidated", has_more_before: true, user_message_offset: 9 } }), refresh)).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual([ + "New canonical window", "Canonical answer", "New input", "Live", + ]); + expect(thread.paging).toMatchObject({ beforeCursor: "before-revalidated", hasMoreBefore: true, userMessageOffset: 9 }); + receive(thread, { ...at("turn-post-request", 3), event: "delta", stream_id: "answer-post-request", text: " tail" }); + expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Live tail" }); + expect(thread.accept(history([], { page: { before_cursor: null, has_more_before: false } }), older)).toBe(false); + + const saved = thread.save(); + expect(Array.from(saved.boundaries.keys())).not.toContain(JSON.stringify(["turn-retired", "answer", "answer-retired"])); + expect(Array.from(saved.knownTurns).sort()).toEqual(["turn-post-request", "turn-revalidated"]); + expect(Array.from(saved.installed.keys())).toEqual(["turn-revalidated"]); + expect(saved.units.every((unit) => !unit.members.has("turn-retired"))).toBe(true); + const restored = new ThreadTranscript([], saved); + receive(restored, { ...at("turn-post-request", 4), event: "delta", stream_id: "answer-post-request", text: " restored" }); + expect(restored.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Live tail restored" }); + }); + + it("does not authorize a disjoint reset from a continuation of a source already retained before the request", () => { + const thread = new ThreadTranscript(); + expect(thread.accept(history([ + input("turn-before-request", "Question"), + { ...at("turn-before-request", 3), event: "stream_end", stream_id: "answer-before-request", text: "Installed", resuming: true, merge_next: true }, + ]), thread.begin("initial"))).toBe(true); + const foregroundId = thread.messages.at(-1)?.id; + const refresh = thread.begin("latest"); + receive(thread, { ...at("turn-before-request", 4), event: "delta", stream_id: "answer-before-request", text: " live" }); + + expect(thread.accept(history([ + input("turn-disjoint", "Disjoint question"), + { ...at("turn-disjoint", 2), event: "message", text: "Disjoint answer" }, + ]), refresh)).toBe(false); + expect(thread.messages.map((row) => row.content)).toEqual(["Question", "Installed live"]); + receive(thread, { ...at("turn-before-request", 5), event: "delta", stream_id: "answer-before-request", text: " continues" }); + expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Installed live continues" }); + }); + + it("keeps retired-window metadata out of the resumable cache snapshot", () => { + const thread = new ThreadTranscript(); + for (let index = 0; index < 4; index++) { + const turn = `turn-window-${index}`; + expect(thread.accept(history([ + input(turn, "Question"), + { ...at(turn, 2), event: "stream_end", stream_id: `answer-${index}`, text: "Answer" }, + { ...at(turn, 3), event: "turn_end" }, + ], { completed_turn_ids: [turn] }), thread.begin(index === 0 ? "initial" : "latest"))).toBe(true); + } + + expect(thread.messages).toHaveLength(2); + const saved = thread.save(); + expect(Array.from(saved.projection.closedTurnIds)).toEqual(["turn-window-3"]); + expect(Array.from(saved.knownTurns)).toEqual(["turn-window-3"]); + expect(Array.from(saved.installed.keys())).toEqual(["turn-window-3"]); + expect(saved.units.every((unit) => Array.from(unit.members.keys()).every((turn) => turn === "turn-window-3"))).toBe(true); + }); + + it("does not certify earlier reasoning from a truncated snapshot with an unknown left boundary", () => { + const thread = new ThreadTranscript(); + expect(thread.accept(history([ + { ...at("turn-unknown-left", 5), event: "reasoning_end", text: "Truncated thought" }, + ], { page: { before_cursor: "before-unknown", has_more_before: true, truncated_oversized_turn: true } }), thread.begin("initial"))).toBe(true); + + receive(thread, + { ...at("turn-unknown-left", 3), event: "reasoning_delta", text: "Earlier uncovered thought" }, + { ...at("turn-unknown-left", 6), event: "reasoning_delta", text: "Fresh thought" }, + { ...at("turn-unknown-left", 7), event: "reasoning_end" }, + { ...at("turn-unknown-left", 8), event: "delta", stream_id: "answer-unknown-left", text: "Fresh answer" }, + ); + expect(thread.messages.map((row) => row.reasoning)).toEqual([ + "Earlier uncovered thought", "Truncated thought", "Fresh thought", + ]); + expect(thread.messages.at(-1)).toMatchObject({ reasoning: "Fresh thought", content: "Fresh answer" }); + }); + + it("does not replace a received source merely because a truncated page reports its turn completed", () => { + const thread = new ThreadTranscript(); + const read = thread.begin("initial"); + receive(thread, + input("turn-truncated", "Long question"), + { ...at("turn-truncated", 2), event: "delta", stream_id: "answer-truncated", text: "Received" }, + ); + const receivedId = thread.messages[1].id; + + expect(thread.accept(history([ + input("turn-truncated", "Long question"), + { ...at("turn-truncated", 4), event: "stream_end", stream_id: "answer-truncated", text: "Received full answer" }, + { ...at("turn-truncated", 5), event: "turn_end" }, + ], { + completed_turn_ids: ["turn-truncated"], + page: { before_cursor: "before-oversized", has_more_before: true, truncated_oversized_turn: true }, + }), read)).toBe(true); + + expect(thread.messages.filter((row) => row.role === "assistant")).toMatchObject([ + { id: receivedId, content: "Received" }, + ]); + expect(thread.paging.truncated).toBe(true); + }); + + it("can replace a fully represented received turn with a nontruncated explicit canonical completion", () => { + const thread = new ThreadTranscript(); + const read = thread.begin("initial"); + receive(thread, + input("turn-complete", "Question"), + { ...at("turn-complete", 2), event: "delta", stream_id: "answer-complete", text: "Received" }, + ); + const receivedId = thread.messages[1].id; + + expect(thread.accept(history([ + input("turn-complete", "Question"), + { ...at("turn-complete", 4), event: "stream_end", stream_id: "answer-complete", text: "Received full answer" }, + { ...at("turn-complete", 5), event: "turn_end" }, + ], { completed_turn_ids: ["turn-complete"] }), read)).toBe(true); + + expect(thread.messages.filter((row) => row.role === "assistant")).toMatchObject([ + { content: "Received full answer", isStreaming: false }, + ]); + expect(thread.messages[1].id).not.toBe(receivedId); + }); +}); diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index 217bada72..7a545717e 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -5,7 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { useNanobotStream } from "@/hooks/useNanobotStream"; import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility"; import { normalizeActivityTimeline } from "@/lib/activity-timeline"; -import type { ThreadCheckpoint } from "@/lib/thread-checkpoint"; +import { ThreadMessageCache } from "@/lib/thread-message-cache"; import type { StreamError } from "@/lib/nanobot-client"; import type { ConnectionStatus, @@ -205,20 +205,21 @@ async function flushStreamFrame() { } describe("useNanobotStream", () => { - it("resumes a merge_next checkpoint including reasoning queued before detach", () => { + it("resumes a merge_next cached snapshot including reasoning queued before detach", () => { const fake = fakeClient(); - let checkpoint: ThreadCheckpoint | undefined; - const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, undefined, - (value) => { checkpoint = value; }), { wrapper: wrap(fake.client) }); + const cache = new ThreadMessageCache(() => false); + const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, + undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) }); act(() => { fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 1, text: "First " }); fake.emit("checkpoint", { event: "stream_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 2, text: "First ", resuming: true, merge_next: true }); fake.emit("checkpoint", { event: "reasoning_delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 3, text: "Queued " }); }); first.unmount(); - expect(checkpoint?.projection.messages[0].reasoning).toBe("Queued "); - const restored = renderHook(() => useNanobotStream("checkpoint", checkpoint!.projection.messages, false, - undefined, undefined, [], checkpoint), { wrapper: wrap(fake.client) }); + const snapshot = cache.get("checkpoint")!; + expect(snapshot.projection.messages[0].reasoning).toBe("Queued "); + const restored = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, + undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) }); act(() => { fake.emit("checkpoint", { event: "reasoning_delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 4, text: "Continue reasoning" }); fake.emit("checkpoint", { event: "reasoning_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 5 }); @@ -230,8 +231,8 @@ describe("useNanobotStream", () => { content: "First last", reasoning: "Queued Continue reasoning", streamId: "answer", reasoningStreamId: "answer", projectionStartSeq: 1, turnSeq: 7, }); - expect(checkpoint?.projection.messages[0].content).toBe("First "); - expect(checkpoint?.projection.messages[0].reasoning).toBe("Queued "); + expect(snapshot.projection.messages[0].content).toBe("First "); + expect(snapshot.projection.messages[0].reasoning).toBe("Queued "); }); it.each([true, false])("keeps answer segments across a provider-tool boundary (snapshot: %s)", (snapshot) => { @@ -256,41 +257,50 @@ describe("useNanobotStream", () => { it("captures the first sequence of coalesced chunks before a paint", () => { const fake = fakeClient(); - const { result } = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES), { wrapper: wrap(fake.client) }); + const cache = new ThreadMessageCache(() => false); + const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, + undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) }); act(() => { fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 1, text: "First " }); fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 2, text: "last" }); }); - let checkpoint!: ThreadCheckpoint; - act(() => { checkpoint = result.current.getCheckpoint(); }); - expect(checkpoint.projection.messages).toHaveLength(1); - expect(checkpoint.projection.messages[0]).toMatchObject({ + expect(first.result.current.messages).toHaveLength(0); + first.unmount(); + const snapshot = cache.get("checkpoint")!; + expect(snapshot.projection.messages).toHaveLength(1); + expect(snapshot.projection.messages[0]).toMatchObject({ content: "First last", streamId: "answer", projectionStartSeq: 1, turnSeq: 2, }); + const restored = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, + undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) }); act(() => { fake.emit("checkpoint", { event: "stream_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 3, response_sources: [] }); }); - expect(result.current.messages[0]).toMatchObject({ projectionStartSeq: 1, turnSeq: 3 }); - expect(checkpoint.projection.closedAssistantIds.size).toBe(0); - expect(checkpoint.projection.closedAnswerStreamIds.size).toBe(0); - const closed = result.current.getCheckpoint().projection; + expect(restored.result.current.messages[0]).toMatchObject({ projectionStartSeq: 1, turnSeq: 3 }); + expect(snapshot.projection.closedAssistantIds.size).toBe(0); + expect(snapshot.projection.closedAnswerStreamIds.size).toBe(0); + restored.unmount(); + const closed = cache.get("checkpoint")!.projection; expect(closed.closedAssistantIds.size).toBe(1); expect(closed.closedAnswerStreamIds.size).toBe(1); }); - it("retains side-channel ownership when restoring an active answer checkpoint", async () => { + it("retains side-channel ownership when restoring an active answer from cache", async () => { const fake = fakeClient(); - const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES), { wrapper: wrap(fake.client) }); + const cache = new ThreadMessageCache(() => false); + const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, + undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) }); act(() => { fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", text: "Active answer" }); }); await flushStreamFrame(); act(() => { first.result.current.send("/model", undefined, { sideChannel: true }); }); const commandTurn = fake.client.sendMessage.mock.calls.at(-1)![3]?.turnId; - const checkpoint = first.result.current.getCheckpoint(); first.unmount(); - const restored = renderHook(() => useNanobotStream("checkpoint", checkpoint.projection.messages, false, - undefined, undefined, [], checkpoint), { wrapper: wrap(fake.client) }); + const snapshot = cache.get("checkpoint")!; + expect(snapshot.sideChannelTurnIds.has(commandTurn)).toBe(true); + const restored = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, + undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) }); act(() => { fake.emit("checkpoint", { event: "message", chat_id: "checkpoint", turn_id: commandTurn, text: "Current model" }); fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", text: " continued" }); @@ -298,6 +308,9 @@ describe("useNanobotStream", () => { }); expect(restored.result.current.messages.filter((message) => message.role === "assistant").map((message) => message.content)) .toEqual(["Active answer continued", "Current model"]); + expect(snapshot.sideChannelTurnIds.has(commandTurn)).toBe(true); + restored.unmount(); + expect(cache.get("checkpoint")!.sideChannelTurnIds.has(commandTurn)).toBe(false); }); it("keeps invocation snapshots across streaming, recovery segments, completion and reload", async () => { diff --git a/webui/src/tests/useSessions.test.tsx b/webui/src/tests/useSessions.test.tsx index 2a8dc2753..a8ba68e38 100644 --- a/webui/src/tests/useSessions.test.tsx +++ b/webui/src/tests/useSessions.test.tsx @@ -925,6 +925,44 @@ describe("useSessions", () => { expect(result.current.hasPendingToolCalls).toBe(false); }); + it("clears the body and paging metadata when no session is selected", async () => { + vi.mocked(api.fetchWebuiThread).mockResolvedValue(canonicalThreadPayload({ + schemaVersion: 3, + has_pending_tool_calls: true, + active_turn_id: "selected-turn", + messages: [{ id: "selected-user", role: "user", content: "selected question", turnId: "selected-turn", createdAt: 1 }], + fork_boundary_message_count: 1, + page: { + before_cursor: "selected-cursor", has_more_before: true, + loaded_event_count: 1, user_message_offset: 4, + }, + })); + const { result, rerender } = renderHook(({ sessionKey }) => useSessionHistory(sessionKey), { + initialProps: { sessionKey: "websocket:selected" as string | null }, + wrapper: wrap(fakeClient()), + }); + await waitFor(() => expect(result.current.loading).toBe(false)); + expect(result.current.messages[0]?.id).toBe("selected-user"); + expect(result.current.hasMoreBefore).toBe(true); + expect(result.current.userMessageOffset).toBe(4); + expect(result.current.hasPendingToolCalls).toBe(true); + expect(result.current.activeTurnId).toBe("selected-turn"); + expect(result.current.forkBoundaryMessageCount).toBe(1); + + rerender({ sessionKey: null }); + + expect(result.current.messages).toEqual([]); + expect(result.current.loading).toBe(false); + expect(result.current.hasMoreBefore).toBe(false); + expect(result.current.userMessageOffset).toBe(0); + expect(result.current.hasPendingToolCalls).toBe(false); + expect(result.current.activeTurnId).toBeNull(); + expect(result.current.forkBoundaryMessageCount).toBeNull(); + act(() => result.current.refresh()); + await act(async () => { await result.current.loadOlder(); }); + expect(api.fetchWebuiThread).toHaveBeenCalledTimes(1); + }); + it("does not reload history when only the auth token rotates", async () => { const tokenSource = { current: "tok-old" }; vi.mocked(api.fetchWebuiThread).mockResolvedValue(canonicalThreadPayload({ @@ -961,6 +999,45 @@ describe("useSessions", () => { ); }); + it("ignores an old client's pending response after the provider switches clients", async () => { + let oldSignal: AbortSignal | undefined; + let finishOld!: (body: Awaited>) => void; + const currentBody = canonicalThreadPayload({ + schemaVersion: 3, + messages: [{ id: "current-host-answer", role: "assistant", content: "current host", createdAt: 2 }], + }); + vi.mocked(api.fetchWebuiThread) + .mockImplementationOnce((_token, _key, optionsOrBase) => new Promise((resolve) => { + if (typeof optionsOrBase !== "string") oldSignal = optionsOrBase?.signal; + finishOld = resolve; + })) + .mockResolvedValueOnce(currentBody); + let client = fakeClient(); + const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + + ); + const { result, rerender } = renderHook(() => useSessionHistory("websocket:host-switch"), { wrapper }); + await waitFor(() => expect(oldSignal).toBeDefined()); + + client = fakeClient(); + rerender(); + + expect(oldSignal?.aborted).toBe(true); + await waitFor(() => expect(result.current.messages[0]?.id).toBe("current-host-answer")); + await act(async () => { + finishOld(canonicalThreadPayload({ + schemaVersion: 3, + messages: [{ id: "old-host-answer", role: "assistant", content: "old host", createdAt: 1 }], + })); + }); + expect(api.fetchWebuiThread).toHaveBeenCalledTimes(2); + expect(result.current.messages.map((message) => message.id)).toEqual(["current-host-answer"]); + expect(result.current.error).toBeNull(); + expect(webuiThreadCache.get("websocket:host-switch")).toBe(currentBody); + }); + it("aborts a superseded latest-history request without surfacing an error", async () => { let firstSignal: AbortSignal | undefined; vi.mocked(api.fetchWebuiThread) @@ -1039,7 +1116,6 @@ describe("useSessions", () => { expect(result.current.userMessageOffset).toBe(1); const latestVersion = result.current.version; const latestLineage = result.current.lineage; - expect(result.current.continuity).toBe("initial"); await act(async () => { await result.current.loadOlder(); @@ -1064,7 +1140,6 @@ describe("useSessions", () => { expect(result.current.userMessageOffset).toBe(0); expect(result.current.version).toBe(latestVersion); expect(result.current.lineage).toBe(latestLineage); - expect(result.current.continuity).toBe("initial"); }); it("keeps older-history failures separate and retries them explicitly", async () => { @@ -1144,11 +1219,52 @@ describe("useSessions", () => { expect(result.current.error).toBeNull(); rerender({ sessionKey: "websocket:other-history" }); + expect(result.current.messages).toEqual([]); expect(result.current.olderError).toBeNull(); await waitFor(() => expect(result.current.loading).toBe(false)); expect(result.current.messages).toEqual([]); }); + it("releases a superseded older read when the replacement latest read fails", async () => { + const latest = canonicalThreadPayload({ + schemaVersion: 3, + messages: [{ id: "current", role: "assistant", content: "current answer", createdAt: 2 }], + page: { before_cursor: "previous-page", has_more_before: true, user_message_offset: 1 }, + }); + const older = canonicalThreadPayload({ + schemaVersion: 3, + messages: [{ id: "previous", role: "assistant", content: "previous answer", createdAt: 1 }], + page: { before_cursor: null, has_more_before: false, user_message_offset: 0 }, + }); + let olderSignal: AbortSignal | undefined; + vi.mocked(api.fetchWebuiThread) + .mockResolvedValueOnce(latest) + .mockImplementationOnce((_token, _key, options) => new Promise((_resolve, reject) => { + if (typeof options !== "string") olderSignal = options?.signal; + olderSignal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError"))); + })) + .mockRejectedValueOnce(new Error("latest unavailable")) + .mockResolvedValueOnce(older); + const { result } = renderHook(() => useSessionHistory("websocket:superseded-older"), { + wrapper: wrap(fakeClient()), + }); + await waitFor(() => expect(result.current.messages[0]?.content).toBe("current answer")); + let pending!: Promise; + act(() => { pending = result.current.loadOlder(); }); + expect(result.current.loadingOlder).toBe(true); + act(() => result.current.refresh()); + await waitFor(() => expect(result.current.error).toBe("latest unavailable")); + await act(async () => { await pending; }); + expect(olderSignal?.aborted).toBe(true); + expect(result.current.loadingOlder).toBe(false); + expect(result.current.hasMoreBefore).toBe(true); + expect(result.current.messages.map((row) => row.content)).toEqual(["current answer"]); + await act(async () => { await result.current.loadOlder(); }); + expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("tok", "websocket:superseded-older", + expect.objectContaining({ before: "previous-page" })); + expect(result.current.messages.map((row) => row.content)).toEqual(["previous answer", "current answer"]); + }); + it("aborts an older-history request when the consumer unmounts", async () => { let olderSignal: AbortSignal | undefined; vi.mocked(api.fetchWebuiThread) @@ -1195,8 +1311,8 @@ describe("useSessions", () => { schemaVersion: 3, has_pending_tool_calls: true, messages: [ - { id: "u2", role: "user", content: "middle question", createdAt: 2 }, - { id: "a2", role: "assistant", content: "middle answer", createdAt: 3 }, + { id: "u2", role: "user", content: "middle question", turnId: "turn-2", turnSeq: 1, createdAt: 2 }, + { id: "a2", role: "assistant", content: "middle answer", turnId: "turn-2", turnSeq: 2, createdAt: 3 }, ], page: { before_cursor: "cursor-middle", @@ -1223,7 +1339,7 @@ describe("useSessions", () => { has_pending_tool_calls: false, completed_turn_ids: ["turn-3"], messages: [ - { id: "a2-replayed", role: "assistant", content: "middle answer", createdAt: 3 }, + { id: "a2-replayed", role: "assistant", content: "middle answer", turnId: "turn-2", turnSeq: 2, createdAt: 3 }, { id: "u3", role: "user", @@ -1273,23 +1389,24 @@ describe("useSessions", () => { expect(result.current.userMessageOffset).toBe(0); expect(result.current.hasPendingToolCalls).toBe(false); expect(result.current.completedTurnIds).toEqual(["turn-3"]); - expect(result.current.continuity).toBe("overlap"); expect(result.current.lineage).toBe(loadedLineage); }); - it("starts a new lineage when more than 160 new rows remove all latest-page overlap", async () => { + it("starts a new lineage for a disjoint latest window even when row text repeats", async () => { const oldWindow = Array.from({ length: 160 }, (_, index) => ({ id: `old-${index}`, role: index % 2 === 0 ? "user" as const : "assistant" as const, - content: `old window row ${index}`, + content: `window row ${index}`, turnId: `old-turn-${Math.floor(index / 2)}`, + turnSeq: index % 2 + 1, createdAt: index, })); const newWindow = Array.from({ length: 160 }, (_, index) => ({ id: `new-${index}`, role: index % 2 === 0 ? "user" as const : "assistant" as const, - content: `new window row ${index}`, + content: `window row ${index}`, turnId: `new-turn-${Math.floor(index / 2)}`, + turnSeq: index % 2 + 1, createdAt: 1_000 + index, })); vi.mocked(api.fetchWebuiThread) @@ -1323,23 +1440,22 @@ describe("useSessions", () => { expect(result.current.messages).toHaveLength(160); expect(result.current.messages.at(-1)?.id).toBe("new-159"); - expect(result.current.continuity).toBe("reset"); expect(result.current.lineage).toBeGreaterThan(initialLineage); expect(result.current.hasMoreBefore).toBe(true); }); - it("uses the longest consecutive semantic overlap for legacy unstable replay metadata", async () => { + it("preserves repeated prompts by stable turn sources when replay IDs change", async () => { vi.mocked(api.fetchWebuiThread) .mockResolvedValueOnce(canonicalThreadPayload({ schemaVersion: 3, messages: [ - { id: "repeat-1-old", role: "user", content: "repeat", createdAt: 10 }, - { id: "answer-1-old", role: "assistant", content: "first answer", createdAt: 11 }, - { id: "repeat-2-old", role: "user", content: "repeat", createdAt: 12 }, - { id: "answer-2-old", role: "assistant", content: "second answer", createdAt: 13 }, + { id: "repeat-1-old", role: "user", content: "repeat", turnId: "repeat-turn-1", turnSeq: 1, createdAt: 10 }, + { id: "answer-1-old", role: "assistant", content: "first answer", turnId: "repeat-turn-1", turnSeq: 2, createdAt: 11 }, + { id: "repeat-2-old", role: "user", content: "repeat", turnId: "repeat-turn-2", turnSeq: 1, createdAt: 12 }, + { id: "answer-2-old", role: "assistant", content: "second answer", turnId: "repeat-turn-2", turnSeq: 2, createdAt: 13 }, ], page: { - before_cursor: "legacy-cursor", + before_cursor: "source-cursor", has_more_before: true, }, })) @@ -1356,17 +1472,17 @@ describe("useSessions", () => { .mockResolvedValueOnce(canonicalThreadPayload({ schemaVersion: 3, messages: [ - { id: "repeat-2-new", role: "user", content: "repeat", createdAt: 9_012 }, - { id: "answer-2-new", role: "assistant", content: "second answer", createdAt: 9_013 }, + { id: "repeat-2-new", role: "user", content: "repeat", turnId: "repeat-turn-2", turnSeq: 1, createdAt: 9_012 }, + { id: "answer-2-new", role: "assistant", content: "second answer", turnId: "repeat-turn-2", turnSeq: 2, createdAt: 9_013 }, { id: "new-tail", role: "assistant", content: "new tail", createdAt: 9_014 }, ], page: { - before_cursor: "shifted-legacy-cursor", + before_cursor: "shifted-source-cursor", has_more_before: true, }, })); - const { result } = renderHook(() => useSessionHistory("websocket:legacy-overlap"), { + const { result } = renderHook(() => useSessionHistory("websocket:source-overlap"), { wrapper: wrap(fakeClient()), }); @@ -1387,7 +1503,6 @@ describe("useSessions", () => { "answer-2-new", "new-tail", ]); - expect(result.current.continuity).toBe("overlap"); expect(result.current.lineage).toBe(lineage); }); @@ -1434,7 +1549,6 @@ describe("useSessions", () => { act(() => result.current.refresh()); await waitFor(() => expect(result.current.messages[0]?.id).toBe("new-latest")); - expect(result.current.continuity).toBe("reset"); expect(result.current.lineage).toBeGreaterThan(oldLineage); await act(async () => {