fix(webui): preserve answer checkpoints and stream order (#6368)
* fix(webui): preserve answer checkpoints and stream order * fix(stream): close hosted-tool answer segments at the producer
This commit is contained in:
1 parent
d2ab462b42
commit
76da55994b
19 files changed
+745
-195
No files matched your search
@@ -117,7 +117,7 @@ class AgentProgressHook(AgentHook):
|
||||
"embeds": [],
|
||||
}
|
||||
if phase == "start":
|
||||
await self.emit_reasoning_end()
|
||||
await self.on_stream_end(context, resuming=True)
|
||||
tool_call = ToolCallRequest(id=str(call_id), name=name, arguments=arguments)
|
||||
tool_hint = self._strip_think(self._tool_hint([tool_call])) or name
|
||||
await self._publish(ProgressEvent(
|
||||
|
||||
@@ -1378,6 +1378,9 @@ def _client_projection_event(
|
||||
|
||||
if event in {"delta", "stream_end", "reasoning_delta", "reasoning_end"}:
|
||||
projected = {"event": event, **common}
|
||||
stream_id = record.get("stream_id")
|
||||
if isinstance(stream_id, str) and stream_id:
|
||||
projected["stream_id"] = stream_id
|
||||
text = record.get("text")
|
||||
if isinstance(text, str):
|
||||
if event == "stream_end" and augment_assistant_text is not None:
|
||||
|
||||
@@ -29,6 +29,7 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():
|
||||
"name": "read_file",
|
||||
"arguments_delta": "",
|
||||
})
|
||||
await on_content_delta("Before search.")
|
||||
await on_tool_call_delta({
|
||||
"kind": "hosted_tool",
|
||||
"phase": "start",
|
||||
@@ -46,7 +47,7 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():
|
||||
"result": {"name": "x_semantic_search"},
|
||||
})
|
||||
await on_content_delta("done")
|
||||
return LLMResponse(content="done", tool_calls=[], usage=None)
|
||||
return LLMResponse(content="Before search.done", tool_calls=[], usage=None)
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
provider.chat_with_retry = AsyncMock()
|
||||
@@ -54,17 +55,23 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():
|
||||
tools.get_definitions.return_value = []
|
||||
progress_events: list[dict] = []
|
||||
progress_text: list[str] = []
|
||||
streamed_text: list[str] = []
|
||||
timeline: list[str] = []
|
||||
|
||||
async def progress_cb(content, *, tool_events=None, **kwargs):
|
||||
progress_text.append(content)
|
||||
if tool_events:
|
||||
progress_events.extend(tool_events)
|
||||
timeline.extend(f"tool:{event['phase']}" for event in tool_events)
|
||||
|
||||
async def stream_cb(content: str) -> None:
|
||||
streamed_text.append(content)
|
||||
timeline.append(f"delta:{content}")
|
||||
|
||||
hook = AgentProgressHook(output_events(on_progress=progress_cb, on_stream=stream_cb), streaming=True)
|
||||
async def end_cb(*, resuming: bool) -> None:
|
||||
timeline.append(f"end:{resuming}")
|
||||
|
||||
hook = AgentProgressHook(output_events(
|
||||
on_progress=progress_cb, on_stream=stream_cb, on_stream_end=end_cb,
|
||||
), streaming=True)
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[{"role": "user", "content": "search X"}],
|
||||
@@ -75,7 +82,7 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():
|
||||
hook=hook,
|
||||
))
|
||||
|
||||
assert result.final_content == "done"
|
||||
assert result.final_content == "Before search.done"
|
||||
assert result.tools_used == []
|
||||
assert result.tool_events == []
|
||||
assert progress_events == [
|
||||
@@ -103,7 +110,9 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():
|
||||
},
|
||||
]
|
||||
assert progress_text == ['search X "nanobot oauth"', ""]
|
||||
assert streamed_text == ["done"]
|
||||
assert timeline == [
|
||||
"delta:Before search.", "end:True", "tool:start", "tool:end", "delta:done", "end:False",
|
||||
]
|
||||
provider.chat_with_retry.assert_not_awaited()
|
||||
|
||||
|
||||
|
||||
@@ -21,6 +21,21 @@ def test_append_and_read_roundtrip(history, tmp_path, monkeypatch) -> None:
|
||||
assert lines[0]["text"] == "hello"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event", ["stream_end", "reasoning_end"])
|
||||
def test_history_preserves_phase_qualified_stream_identity(history, event) -> None:
|
||||
key = "websocket:stream-identity"
|
||||
history.append(key, {"event": "user", "chat_id": "stream-identity", "text": "question"})
|
||||
history.append(key, {
|
||||
"event": event, "chat_id": "stream-identity", "text": "completed segment",
|
||||
"stream_id": "stream-one", "turn_id": "turn-one", "turn_seq": 2,
|
||||
})
|
||||
response = history.build(key)
|
||||
assert response is not None
|
||||
segment = next(record for record in response["events"] if record["event"] == event)
|
||||
assert segment["stream_id"] == "stream-one"
|
||||
assert segment["turn_seq"] == 2
|
||||
|
||||
|
||||
def test_append_stamps_created_at_ms(history, tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
monkeypatch.setattr("nanobot.webui.transcript.time.time", lambda: 1_700_000_000.0)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { ThreadShell } from "@/components/thread/ThreadShell";
|
||||
import { settings } from "@/dev/gallery/settings";
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
|
||||
// The browser spec controls HTTP and WebSocket frames; all projection and caching
|
||||
// run through the real client and thread, without model calls or saved user data.
|
||||
export function AnswerOrderFixture() {
|
||||
const [client] = useState(() => new NanobotClient({
|
||||
url: `ws://${location.host}/answer-order-socket`, reconnect: false,
|
||||
}));
|
||||
const [cache] = useState(() => new ThreadMessageCache(() => false));
|
||||
const [chatId, setChatId] = useState("answer-order");
|
||||
const [revision, setRevision] = useState(0);
|
||||
const [, setCompletedRevision] = useState(0);
|
||||
const onTurnEnd = useCallback(() => setCompletedRevision(revision), [revision]);
|
||||
useEffect(() => {
|
||||
client.connect();
|
||||
return () => client.close();
|
||||
}, [client]);
|
||||
return <ClientProvider client={client} token="fixture">
|
||||
<main className="thread-workspace flex min-w-0 flex-col overflow-hidden bg-background" style={{ height: "100dvh" }}>
|
||||
<nav className="flex gap-4 p-2" aria-label="Fixture controls">
|
||||
<button onClick={() => setChatId(chatId === "answer-order" ? "other-chat" : "answer-order")}>Switch topic</button>
|
||||
<button onClick={() => setRevision((value) => value + 1)}>Rebuild subscription</button>
|
||||
</nav>
|
||||
<ThreadShell
|
||||
session={{ key: `websocket:${chatId}`, channel: "websocket", chatId, createdAt: null, updatedAt: null, preview: "" }}
|
||||
title={chatId} onToggleSidebar={() => {}} onTurnEnd={onTurnEnd}
|
||||
settingsSnapshot={settings} messageCache={cache}
|
||||
/>
|
||||
</main>
|
||||
</ClientProvider>;
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { expect, test, type Page, type WebSocketRoute } from "@playwright/test";
|
||||
import type { InboundEvent, ThreadProjectionEvent } from "../src/lib/types";
|
||||
|
||||
const chatId = "answer-order";
|
||||
const turnId = "answer-order-turn";
|
||||
const source = { provider: "fixture", model: "fixture", preset: "fixture" };
|
||||
const base = { chat_id: chatId, turn_id: turnId };
|
||||
|
||||
async function openThread(page: Page, events: ThreadProjectionEvent[] = []) {
|
||||
const errors: string[] = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
await page.addInitScript(() => { localStorage.setItem("nanobot.locale", "en"); });
|
||||
await page.route("**/api/**", (route) => route.fulfill({ status: 404, json: {} }));
|
||||
await page.route("**/api/commands", (route) => route.fulfill({ json: { commands: [] } }));
|
||||
await page.route("**/api/sessions/*/webui-thread?*", (route) => {
|
||||
const requestedPath = decodeURIComponent(new URL(route.request().url()).pathname);
|
||||
const history = requestedPath.includes(`/sessions/websocket:${chatId}/`) ? events : [];
|
||||
return route.fulfill({ json: {
|
||||
schemaVersion: 3, projection: "events", events: history, has_more: false,
|
||||
has_pending_tool_calls: history.length > 0,
|
||||
} });
|
||||
});
|
||||
let socket!: WebSocketRoute;
|
||||
const attached = new Set<string>();
|
||||
await page.routeWebSocket("**/answer-order-socket", (route) => {
|
||||
socket = route;
|
||||
route.onMessage((raw) => {
|
||||
const frame = JSON.parse(String(raw));
|
||||
if (frame.type === "attach") {
|
||||
attached.add(frame.chat_id);
|
||||
route.send(JSON.stringify({ event: "attached", chat_id: frame.chat_id }));
|
||||
}
|
||||
});
|
||||
});
|
||||
await page.goto("/browser/fixture.html?case=answer-order");
|
||||
await expect.poll(() => attached.has(chatId)).toBe(true);
|
||||
await expect(page.getByRole("status", { name: "Loading conversation…" })).toHaveCount(0);
|
||||
return { emit: (...frames: InboundEvent[]) => frames.forEach((frame) => socket.send(JSON.stringify(frame))), errors };
|
||||
}
|
||||
|
||||
async function expectAnswerOrder(page: Page) {
|
||||
await expect(page.getByText("Earlier answer", { exact: true })).toHaveCount(1);
|
||||
await expect(page.getByText("Later answer", { exact: true })).toHaveCount(1);
|
||||
const texts = await page.locator("[data-thread-display-unit]").allTextContents();
|
||||
expect(texts.findIndex((text) => text.includes("Earlier answer")))
|
||||
.toBeLessThan(texts.findIndex((text) => text.includes("Later answer")));
|
||||
}
|
||||
|
||||
for (const width of [1440, 390]) {
|
||||
for (const path of ["callback", "cached return"] as const) {
|
||||
test(`keeps closed answer order through ${path} and textless streams at ${width}px`, async ({ page }, info) => {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
const { emit, errors } = await openThread(page);
|
||||
emit(
|
||||
{ event: "goal_status", ...base, status: "running", started_at: 100 },
|
||||
{ event: "delta", ...base, stream_id: "first", turn_seq: 1, text: "Earlier answer" },
|
||||
{ event: "stream_end", ...base, stream_id: "first", turn_seq: 2, resuming: true, response_sources: [source] },
|
||||
{ event: "message", ...base, turn_seq: 3, kind: "tool_hint", text: "read_file(earlier)" },
|
||||
{ event: "delta", ...base, stream_id: "second", turn_seq: 4, text: "Later answer" },
|
||||
{ event: "stream_end", ...base, stream_id: "second", turn_seq: 5, resuming: true, response_sources: [source] },
|
||||
{ event: "message", ...base, turn_seq: 6, kind: "tool_hint", text: "read_file(later)" },
|
||||
);
|
||||
await expectAnswerOrder(page);
|
||||
if (path === "callback") {
|
||||
await page.getByRole("button", { name: "Rebuild subscription" }).click();
|
||||
} else {
|
||||
await page.getByRole("button", { name: "Switch topic" }).click();
|
||||
await expect(page.getByText("Earlier answer", { exact: true })).toHaveCount(0);
|
||||
}
|
||||
emit(
|
||||
{ event: "stream_end", ...base, stream_id: "empty-one", turn_seq: 7, resuming: true, response_sources: [source] },
|
||||
{ event: "stream_end", ...base, stream_id: "empty-two", turn_seq: 8, resuming: true, response_sources: [source] },
|
||||
);
|
||||
if (path === "cached return") await page.getByRole("button", { name: "Switch topic" }).click();
|
||||
// The late final snapshot belongs to the first row, not the latest row.
|
||||
emit({ event: "stream_end", ...base, stream_id: "first", turn_seq: 9, text: "Earlier answer", response_sources: [] });
|
||||
await expectAnswerOrder(page);
|
||||
await expect(page.getByRole("button", { name: "Stop response" })).toBeVisible();
|
||||
await page.screenshot({ path: info.outputPath("answer-order.png") });
|
||||
emit({ event: "turn_end", ...base, turn_seq: 10 });
|
||||
await expect(page.getByRole("button", { name: "Stop response" })).toHaveCount(0);
|
||||
emit({ event: "delta", ...base, stream_id: "late", turn_seq: 11, text: "Obsolete answer" });
|
||||
// Ordered WebSocket processing: a subsequent new-turn frame is the barrier.
|
||||
emit({ event: "message", chat_id: chatId, turn_id: "new-turn", text: "Next turn" });
|
||||
await expect(page.getByText("Next turn", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Obsolete answer", { exact: true })).toHaveCount(0);
|
||||
await expectAnswerOrder(page);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test(`keeps hosted-tool answer segments after a cached return at ${width}px`, async ({ page }) => {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
const { emit, errors } = await openThread(page);
|
||||
emit(
|
||||
{ event: "goal_status", ...base, status: "running", started_at: 100 },
|
||||
{ event: "delta", ...base, stream_id: "hosted", turn_seq: 1, text: "First " },
|
||||
{ event: "stream_end", ...base, stream_id: "hosted", turn_seq: 2, resuming: true },
|
||||
{ event: "message", ...base, turn_seq: 3, kind: "tool_hint", text: "web_search(query)" },
|
||||
{ event: "delta", ...base, stream_id: "after-tool", turn_seq: 4, text: "second" },
|
||||
{ event: "stream_end", ...base, stream_id: "after-tool", turn_seq: 5, text: "second", resuming: true, merge_next: true },
|
||||
);
|
||||
await expect(page.getByText("First", { exact: true })).toHaveCount(1);
|
||||
await expect(page.getByText("second", { exact: true })).toHaveCount(1);
|
||||
await page.getByRole("button", { name: "Switch topic" }).click();
|
||||
await expect(page.getByText("second", { exact: true })).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "Switch topic" }).click();
|
||||
await expect(page.getByText("second", { exact: true })).toHaveCount(1);
|
||||
emit(
|
||||
{ event: "delta", ...base, stream_id: "after-tool", turn_seq: 6, text: " last" },
|
||||
{ event: "stream_end", ...base, stream_id: "after-tool", turn_seq: 7, text: "second last", response_sources: [source] },
|
||||
);
|
||||
await expect(page.getByText("First", { exact: true })).toHaveCount(1);
|
||||
await expect(page.getByText("second last", { exact: true })).toHaveCount(1);
|
||||
const texts = await page.locator("[data-thread-display-unit]").allTextContents();
|
||||
expect(texts.findIndex((text) => text.includes("First"))).toBeLessThan(texts.findIndex((text) => text.includes("second last")));
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test(`replays legacy cumulative answers on both sides of a hosted tool at ${width}px`, async ({ page }) => {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
const { errors } = await openThread(page, [
|
||||
{ event: "stream_end", ...base, stream_id: "legacy", turn_seq: 2, text: "First ", resuming: true, merge_next: true },
|
||||
{ event: "message", ...base, turn_seq: 3, kind: "tool_hint", text: "web_search(query)" },
|
||||
{ event: "stream_end", ...base, stream_id: "legacy", turn_seq: 5, text: "First last" },
|
||||
{ event: "turn_end", ...base, turn_seq: 6 },
|
||||
]);
|
||||
await expect(page.getByText("First", { exact: true })).toHaveCount(1);
|
||||
await expect(page.getByText("last", { exact: true })).toHaveCount(1);
|
||||
const texts = await page.locator("[data-thread-display-unit]").allTextContents();
|
||||
expect(texts.findIndex((text) => text.includes("First"))).toBeLessThan(texts.findIndex((text) => text.includes("Searching the web")));
|
||||
expect(texts.findIndex((text) => text.includes("Searching the web"))).toBeLessThan(texts.findIndex((text) => text.includes("last")));
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test(`keeps a rewritten image intact before a hosted tool at ${width}px`, async ({ page }, info) => {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
const { emit, errors } = await openThread(page);
|
||||
await page.route("**/api/media/**", (route) => route.fulfill({ contentType: "image/png", body: Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j5hUAAAAASUVORK5CYII=", "base64",
|
||||
) }));
|
||||
emit(
|
||||
{ event: "delta", ...base, stream_id: "image", turn_seq: 1, text: "" },
|
||||
{ event: "stream_end", ...base, stream_id: "image", turn_seq: 2, text: "", resuming: true },
|
||||
{ event: "message", ...base, turn_seq: 3, kind: "tool_hint", text: "web_search(query)" },
|
||||
{ event: "delta", ...base, stream_id: "after-tool", turn_seq: 4, text: "After tool." },
|
||||
{ event: "stream_end", ...base, stream_id: "after-tool", turn_seq: 5 },
|
||||
);
|
||||
const image = page.getByRole("img", { name: "plot", exact: true });
|
||||
await expect(image).toHaveCount(1);
|
||||
await expect(image).toHaveAttribute("src", /\/api\/media\/signature\/plot.png/);
|
||||
await expect.poll(() => image.evaluate((element: HTMLImageElement) => element.naturalWidth)).toBe(1);
|
||||
await expect(page.getByText("After tool.", { exact: true })).toHaveCount(1);
|
||||
const units = page.locator("[data-thread-display-unit]");
|
||||
const imageIndex = await units.evaluateAll((elements) => elements.findIndex((element) => element.querySelector('img[alt="plot"]')));
|
||||
const texts = await units.allTextContents();
|
||||
const toolIndex = texts.findIndex((text) => text.includes("Searching the web"));
|
||||
expect(imageIndex).toBeLessThan(toolIndex);
|
||||
expect(toolIndex).toBeLessThan(texts.findIndex((text) => text.includes("After tool.")));
|
||||
await page.screenshot({ path: info.outputPath("hosted-tool-image.png") });
|
||||
emit({ event: "turn_end", ...base, turn_seq: 6 });
|
||||
await expect(page.getByRole("button", { name: "Stop response" })).toHaveCount(0);
|
||||
await expect(image).toHaveCount(1);
|
||||
await expect(page.getByText("After tool.", { exact: true })).toHaveCount(1);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test(`resumes merge_next with cumulative HTTP snapshots at ${width}px`, async ({ page }) => {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
const events: ThreadProjectionEvent[] = [
|
||||
{ event: "stream_end", ...base, stream_id: "answer", turn_seq: 2, text: "First ", resuming: true, merge_next: true, projection_id: "http-first" },
|
||||
{ event: "reasoning_end", ...base, stream_id: "answer", turn_seq: 3, text: "More reasoning", projection_id: "http-reasoning" },
|
||||
{ event: "stream_end", ...base, stream_id: "answer", turn_seq: 5, text: "First last", resuming: true, merge_next: true, projection_id: "http-last" },
|
||||
];
|
||||
const { emit, errors } = await openThread(page, events);
|
||||
await expect(page.getByText("First last", { exact: true })).toHaveCount(1);
|
||||
await page.getByRole("button", { name: "Switch topic" }).click();
|
||||
await expect(page.getByText("First last", { exact: true })).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "Switch topic" }).click();
|
||||
await expect(page.getByText("First last", { exact: true })).toHaveCount(1);
|
||||
emit(
|
||||
{ event: "goal_status", ...base, status: "running", started_at: 100 },
|
||||
{ event: "delta", ...base, stream_id: "answer", turn_seq: 6, text: " continued" },
|
||||
{ event: "stream_end", ...base, stream_id: "answer", turn_seq: 7, text: "First last continued", response_sources: [source] },
|
||||
);
|
||||
await expect(page.getByText("First last continued", { exact: true })).toHaveCount(1);
|
||||
await expect(page.getByText("First last", { exact: true })).toHaveCount(0);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import { TypographyFixture } from "./typography-fixture";
|
||||
import { HistoryBoundaryFixture } from "./history-boundary-fixture";
|
||||
import { ChatFailureFixture } from "./chat-failure-fixture";
|
||||
import { ThreadLoadingFixture } from "./thread-loading-fixture";
|
||||
import { AnswerOrderFixture } from "./answer-order-fixture";
|
||||
|
||||
const history: UIMessage[] = [
|
||||
{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },
|
||||
@@ -166,7 +167,9 @@ function AppsFixture() {
|
||||
if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();
|
||||
await initializeI18n();
|
||||
createRoot(document.getElementById("root")!).render(<TooltipProvider>
|
||||
{parameters.get("case") === "chat-failure"
|
||||
{parameters.get("case") === "answer-order"
|
||||
? <AnswerOrderFixture />
|
||||
: parameters.get("case") === "chat-failure"
|
||||
? <ChatFailureFixture parameters={parameters} />
|
||||
: parameters.get("case") === "typography"
|
||||
? <ClientProvider client={railClient} token="fixture"><TypographyFixture /></ClientProvider>
|
||||
|
||||
@@ -75,6 +75,7 @@ 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";
|
||||
@@ -883,10 +884,6 @@ export function ThreadShell({
|
||||
));
|
||||
const messageCacheRef = useRef(messageCache ?? localMessageCacheRef.current);
|
||||
messageCacheRef.current = messageCache ?? localMessageCacheRef.current;
|
||||
/** Last chatId we associated with the in-memory thread (for cache-on-switch). */
|
||||
const prevChatIdForCacheRef = useRef<string | null>(null);
|
||||
/** Skip one message-cache write right after chatId changes (messages may not match yet). */
|
||||
const skipLayoutCacheRef = useRef(false);
|
||||
const pendingCanonicalHydrateRef = useRef<Map<string, PendingCanonicalHydrate>>(new Map());
|
||||
const pendingCanonicalCommitRef = useRef<Map<string, PendingCanonicalCommit>>(new Map());
|
||||
const pendingHistoryLineageCommitRef = useRef<Map<string, PendingHistoryLineageCommit>>(
|
||||
@@ -905,19 +902,18 @@ export function ThreadShell({
|
||||
!hideHeader && !session && !loading && !!onTemporaryChatEnabledChange;
|
||||
|
||||
const initial = useMemo(() => {
|
||||
if (!chatId) return historical;
|
||||
const cached = messageCacheRef.current.get(chatId);
|
||||
const cached = chatId ? messageCacheRef.current.get(chatId) : undefined;
|
||||
return cached
|
||||
? replaceCanonicalCompletedTurns(cached, historical, completedTurnIds)
|
||||
: historical;
|
||||
? 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((snapshot: UIMessage[]) => {
|
||||
if (chatId) messageCacheRef.current.set(chatId, projectWebuiThreadMessages(snapshot));
|
||||
const handleStreamDetach = useCallback((checkpoint: ThreadCheckpoint) => {
|
||||
if (chatId) messageCacheRef.current.set(chatId, checkpoint);
|
||||
}, [chatId]);
|
||||
const {
|
||||
messages,
|
||||
@@ -934,10 +930,11 @@ export function ThreadShell({
|
||||
stop,
|
||||
reconcileTurnComplete,
|
||||
setMessages,
|
||||
getCheckpoint,
|
||||
streamError,
|
||||
dismissStreamError,
|
||||
} = useNanobotStream(
|
||||
chatId, initial, hasPendingToolCalls, handleTurnEnd, handleStreamDetach, completedTurnIds,
|
||||
chatId, initial.projection.messages, hasPendingToolCalls, handleTurnEnd, handleStreamDetach, completedTurnIds, initial,
|
||||
);
|
||||
const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]);
|
||||
const normalizedHistory = useMemo(() => projectWebuiThreadMessages(historical), [historical]);
|
||||
@@ -1292,7 +1289,7 @@ export function ThreadShell({
|
||||
historyLineage,
|
||||
historyVersion,
|
||||
runGeneration: client.getRunGeneration(chatId),
|
||||
uiBaseline: durableMessageShapes(initial),
|
||||
uiBaseline: durableMessageShapes(initial.projection.messages),
|
||||
uiLineage: committedHistoryLineageRef.current.get(chatId) ?? null,
|
||||
uiRevision: uiRevisionRef.current,
|
||||
});
|
||||
@@ -1476,11 +1473,11 @@ export function ThreadShell({
|
||||
) {
|
||||
pendingCanonicalCommitRef.current.delete(chatId);
|
||||
const fallback = replaceCanonicalCompletedTurns(
|
||||
messageCacheRef.current.get(chatId) ?? commit.previousMessages,
|
||||
messageCacheRef.current.get(chatId)?.projection.messages ?? commit.previousMessages,
|
||||
commit.messages,
|
||||
commit.completedTurnIds,
|
||||
);
|
||||
messageCacheRef.current.set(chatId, fallback);
|
||||
messageCacheRef.current.set(chatId, copyThreadCheckpoint(getCheckpoint(), fallback));
|
||||
setMessages((current) => current === commit.messages ? fallback : current);
|
||||
return;
|
||||
}
|
||||
@@ -1488,7 +1485,7 @@ export function ThreadShell({
|
||||
pendingCanonicalCommitRef.current.delete(chatId);
|
||||
committedHistoryLineageRef.current.set(chatId, historyLineage);
|
||||
completedCanonicalHydrateVersionRef.current.set(chatId, historyVersion);
|
||||
}, [chatId, client, historyKey, historyLineage, historyVersion, messages, setMessages]);
|
||||
}, [chatId, client, getCheckpoint, historyKey, historyLineage, historyVersion, messages, setMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!historyKey || !chatId || hasPendingToolCalls) return;
|
||||
@@ -1573,42 +1570,10 @@ export function ThreadShell({
|
||||
setMessages(projectWebuiThreadMessages(historical));
|
||||
}, [chatId, historical, setMessages]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (chatId) {
|
||||
const prev = prevChatIdForCacheRef.current;
|
||||
if (prev && prev !== chatId) {
|
||||
messageCacheRef.current.set(prev, displayMessages);
|
||||
skipLayoutCacheRef.current = true;
|
||||
}
|
||||
prevChatIdForCacheRef.current = chatId;
|
||||
} else {
|
||||
if (prevChatIdForCacheRef.current) {
|
||||
messageCacheRef.current.set(
|
||||
prevChatIdForCacheRef.current,
|
||||
displayMessages,
|
||||
);
|
||||
skipLayoutCacheRef.current = true;
|
||||
}
|
||||
prevChatIdForCacheRef.current = null;
|
||||
}
|
||||
}, [chatId, displayMessages]);
|
||||
|
||||
// Persist thread to in-memory cache after paint so ``useNanobotStream``'s chat switch
|
||||
// ``useEffect`` reset has flushed; ``skipLayoutCacheRef`` drops the first run that still
|
||||
// sees the *previous* chat's ``messages`` (avoids stale rows leaking across sessions).
|
||||
useEffect(() => {
|
||||
if (!chatId) {
|
||||
return;
|
||||
}
|
||||
if (skipLayoutCacheRef.current) {
|
||||
skipLayoutCacheRef.current = false;
|
||||
return;
|
||||
}
|
||||
if (loading) {
|
||||
return;
|
||||
}
|
||||
messageCacheRef.current.set(chatId, displayMessages);
|
||||
}, [chatId, displayMessages, loading]);
|
||||
if (!chatId || !messagesReady || loading) return;
|
||||
messageCacheRef.current.set(chatId, getCheckpoint());
|
||||
}, [chatId, getCheckpoint, loading, messages, messagesReady]);
|
||||
|
||||
// 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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { copyThreadCheckpoint, createThreadCheckpoint, type ThreadCheckpoint } from "@/lib/thread-checkpoint";
|
||||
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
||||
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
@@ -9,7 +9,6 @@ import type { StreamError } from "@/lib/nanobot-client";
|
||||
import {
|
||||
clearThreadProjectionActivity,
|
||||
closeThreadProjectionAnswer,
|
||||
createThreadProjectionState,
|
||||
finalizeStreamedTurn,
|
||||
projectThreadEvent,
|
||||
resetThreadProjectionCursor,
|
||||
@@ -38,8 +37,8 @@ import type {
|
||||
} from "@/lib/types";
|
||||
|
||||
type PendingStreamEvent =
|
||||
| { kind: "delta"; text: string; turn: UIMessageTurnFields; source?: UIMessage["source"]; responseSources?: UIMessage["responseSources"] }
|
||||
| { kind: "reasoning"; text: string; turn: UIMessageTurnFields };
|
||||
| { kind: "delta"; text: string; turn: UIMessageTurnFields; streamId?: string; source?: UIMessage["source"]; responseSources?: UIMessage["responseSources"] }
|
||||
| { kind: "reasoning"; text: string; turn: UIMessageTurnFields; streamId?: string };
|
||||
|
||||
const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000;
|
||||
// Markdown and layout work must leave room for input between visible updates.
|
||||
@@ -137,8 +136,9 @@ export function useNanobotStream(
|
||||
initialMessages: UIMessage[] = EMPTY_INITIAL_MESSAGES,
|
||||
hasPendingToolCalls = false,
|
||||
onTurnEnd?: () => void,
|
||||
onStreamDetach?: (messages: UIMessage[]) => void,
|
||||
onStreamDetach?: (checkpoint: ThreadCheckpoint) => void,
|
||||
completedTurnIds: readonly string[] = EMPTY_COMPLETED_TURN_IDS,
|
||||
initialCheckpoint?: ThreadCheckpoint,
|
||||
): {
|
||||
messages: UIMessage[];
|
||||
/** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */
|
||||
@@ -163,6 +163,8 @@ export function useNanobotStream(
|
||||
/** Mark an accepted canonical snapshot as the definitive end of the active turn. */
|
||||
reconcileTurnComplete: () => void;
|
||||
setMessages: React.Dispatch<React.SetStateAction<UIMessage[]>>;
|
||||
/** Flush received chunks and capture a resumable copy, independently of paint. */
|
||||
getCheckpoint: () => ThreadCheckpoint;
|
||||
/** Latest transport-level fault raised since the last ``dismissStreamError``.
|
||||
* ``null`` when there is nothing to show. */
|
||||
streamError: StreamError | null;
|
||||
@@ -174,7 +176,11 @@ export function useNanobotStream(
|
||||
const threadVisible = useThreadVisibility();
|
||||
const threadVisibleRef = useRef(threadVisible);
|
||||
threadVisibleRef.current = threadVisible;
|
||||
const { t } = useTranslation();
|
||||
const [initialState] = useState(() => initialCheckpoint
|
||||
? copyThreadCheckpoint(initialCheckpoint, initialMessages)
|
||||
: createThreadCheckpoint(initialMessages));
|
||||
const projectionRef = useRef<ThreadProjectionState>(initialState.projection);
|
||||
const sideChannelTurnIdsRef = useRef(initialState.sideChannelTurnIds);
|
||||
const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
|
||||
const [messages, setRenderedMessages] = useState<UIMessage[]>(initialMessages);
|
||||
const messagesRef = useRef(messages);
|
||||
@@ -183,6 +189,7 @@ export function useNanobotStream(
|
||||
const setMessages = useCallback<React.Dispatch<React.SetStateAction<UIMessage[]>>>((update) => {
|
||||
const next = typeof update === "function" ? update(messagesRef.current) : update;
|
||||
messagesRef.current = next;
|
||||
projectionRef.current = { ...projectionRef.current, messages: next };
|
||||
setRenderedMessages(next);
|
||||
}, []);
|
||||
const [messageOwnerChatId, setMessageOwnerChatId] = useState(chatId);
|
||||
@@ -203,14 +210,10 @@ export function useNanobotStream(
|
||||
const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined);
|
||||
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
|
||||
const [streamError, setStreamError] = useState<StreamError | null>(null);
|
||||
const projectionRef = useRef<ThreadProjectionState>(
|
||||
createThreadProjectionState(initialMessages),
|
||||
);
|
||||
const pendingStreamEventsRef = useRef<PendingStreamEvent[]>([]);
|
||||
const streamFrameRef = useRef<number | null>(null);
|
||||
const streamTimerRef = useRef<number | null>(null);
|
||||
const lastStreamFlushRef = useRef(0);
|
||||
const sideChannelTurnIdsRef = useRef<Set<string>>(new Set());
|
||||
|
||||
const dismissStreamError = useCallback(() => setStreamError(null), []);
|
||||
|
||||
@@ -324,6 +327,7 @@ export function useNanobotStream(
|
||||
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.kind === "delta" && event.kind === "delta"
|
||||
@@ -338,6 +342,7 @@ export function useNanobotStream(
|
||||
? {
|
||||
event: "delta",
|
||||
chat_id: chatId ?? "",
|
||||
stream_id: event.streamId,
|
||||
text,
|
||||
turn_id: turn.turnId,
|
||||
turn_phase: turn.turnPhase,
|
||||
@@ -348,6 +353,7 @@ export function useNanobotStream(
|
||||
: {
|
||||
event: "reasoning_delta",
|
||||
chat_id: chatId ?? "",
|
||||
stream_id: event.streamId,
|
||||
text,
|
||||
turn_id: turn.turnId,
|
||||
turn_phase: turn.turnPhase,
|
||||
@@ -356,6 +362,7 @@ export function useNanobotStream(
|
||||
projection = projectThreadEvent(projection, projectedEvent, {
|
||||
createId: () => crypto.randomUUID(),
|
||||
now: Date.now(),
|
||||
startSeq: event.turn.turnSeq,
|
||||
});
|
||||
}
|
||||
projectionRef.current = projection;
|
||||
@@ -364,14 +371,7 @@ export function useNanobotStream(
|
||||
[chatId],
|
||||
);
|
||||
|
||||
const flushPendingStreamEvents = useCallback((options?: {
|
||||
closeAnswerSegment?: boolean;
|
||||
mergeReasoning?: boolean;
|
||||
finalAnswerText?: string;
|
||||
turn?: UIMessageTurnFields;
|
||||
source?: UIMessage["source"];
|
||||
responseSources?: UIMessage["responseSources"];
|
||||
}) => {
|
||||
const flushPendingStreamEvents = useCallback((end?: Extract<ThreadProjectionEvent, { event: "stream_end" }>) => {
|
||||
lastStreamFlushRef.current = 0;
|
||||
if (streamFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(streamFrameRef.current);
|
||||
@@ -382,37 +382,13 @@ export function useNanobotStream(
|
||||
streamTimerRef.current = null;
|
||||
}
|
||||
const events = pendingStreamEventsRef.current;
|
||||
const finalAnswerText = options?.finalAnswerText;
|
||||
const turn = options?.turn ?? {};
|
||||
const source = options?.source;
|
||||
const responseSources = options?.responseSources;
|
||||
if (events.length === 0 && finalAnswerText === undefined && source === undefined && responseSources === undefined
|
||||
&& !options?.mergeReasoning) {
|
||||
if (options?.closeAnswerSegment) closeActiveAssistantStream();
|
||||
return;
|
||||
}
|
||||
if (events.length === 0 && !end) return;
|
||||
pendingStreamEventsRef.current = [];
|
||||
setMessages((prev) => {
|
||||
const nextMessages = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev;
|
||||
let projection = { ...projectionRef.current, messages: nextMessages };
|
||||
if (
|
||||
finalAnswerText !== undefined
|
||||
|| source !== undefined
|
||||
|| responseSources !== undefined
|
||||
|| options?.mergeReasoning
|
||||
|| options?.closeAnswerSegment
|
||||
) {
|
||||
projection = projectThreadEvent(projection, {
|
||||
event: "stream_end",
|
||||
chat_id: chatId ?? "",
|
||||
...(finalAnswerText !== undefined ? { text: finalAnswerText } : {}),
|
||||
...(source ? { source } : {}),
|
||||
...(responseSources !== undefined ? { response_sources: responseSources } : {}),
|
||||
...(options?.mergeReasoning ? { resuming: true, merge_next: true } : {}),
|
||||
turn_id: turn.turnId,
|
||||
turn_phase: turn.turnPhase,
|
||||
turn_seq: turn.turnSeq,
|
||||
}, {
|
||||
if (end) {
|
||||
projection = projectThreadEvent(projection, end, {
|
||||
createId: () => crypto.randomUUID(),
|
||||
now: Date.now(),
|
||||
});
|
||||
@@ -420,7 +396,15 @@ export function useNanobotStream(
|
||||
projectionRef.current = projection;
|
||||
return projection.messages;
|
||||
});
|
||||
}, [applyPendingStreamEvents, chatId, closeActiveAssistantStream, setMessages]);
|
||||
}, [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;
|
||||
@@ -524,9 +508,12 @@ export function useNanobotStream(
|
||||
setRetryStatus(null);
|
||||
setGoalState(chatId ? client.getGoalState(chatId) : undefined);
|
||||
setRecoveryState(null);
|
||||
projectionRef.current = createThreadProjectionState(initialMessages);
|
||||
const restored = initialCheckpoint
|
||||
? copyThreadCheckpoint(initialCheckpoint, initialMessages)
|
||||
: createThreadCheckpoint(initialMessages);
|
||||
projectionRef.current = restored.projection;
|
||||
sideChannelTurnIdsRef.current = restored.sideChannelTurnIds;
|
||||
clearPendingStreamWork();
|
||||
sideChannelTurnIdsRef.current.clear();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [chatId, client, clearActivitySegment, clearPendingStreamWork, setMessages]);
|
||||
|
||||
@@ -589,7 +576,8 @@ export function useNanobotStream(
|
||||
if (ev.event === "message_accepted") return;
|
||||
if (ev.event === "user_message") {
|
||||
if (ev.provenance?.session_message) {
|
||||
flushPendingStreamEvents({ closeAnswerSegment: true });
|
||||
flushPendingStreamEvents();
|
||||
closeActiveAssistantStream();
|
||||
clearActivitySegment();
|
||||
setIsStreaming(true);
|
||||
setMessages((prev) => appendProjectedSessionInput(prev, ev));
|
||||
@@ -630,7 +618,8 @@ export function useNanobotStream(
|
||||
}
|
||||
const sideChannelEvent = isSideChannelEvent(ev);
|
||||
if (ev.event === "context_compaction") {
|
||||
flushPendingStreamEvents({ closeAnswerSegment: true });
|
||||
flushPendingStreamEvents();
|
||||
closeActiveAssistantStream();
|
||||
clearActivitySegment();
|
||||
const compaction = {
|
||||
id: ev.compaction_id,
|
||||
@@ -675,6 +664,7 @@ export function useNanobotStream(
|
||||
kind: "delta",
|
||||
text: chunk,
|
||||
turn: turnFieldsFromEvent(ev, "answer"),
|
||||
streamId: ev.stream_id,
|
||||
source: ev.source,
|
||||
responseSources: ev.response_sources,
|
||||
});
|
||||
@@ -691,22 +681,14 @@ export function useNanobotStream(
|
||||
kind: "reasoning",
|
||||
text: chunk,
|
||||
turn: turnFieldsFromEvent(ev, "reasoning"),
|
||||
streamId: ev.stream_id,
|
||||
});
|
||||
schedulePendingStreamFlush();
|
||||
return;
|
||||
}
|
||||
|
||||
if (ev.event === "stream_end") {
|
||||
const turn = turnFieldsFromEvent(ev, "answer");
|
||||
const mergeNext = ev.resuming === true && ev.merge_next === true;
|
||||
flushPendingStreamEvents({
|
||||
closeAnswerSegment: !mergeNext,
|
||||
mergeReasoning: mergeNext,
|
||||
...(typeof ev.text === "string" ? { finalAnswerText: ev.text } : {}),
|
||||
turn,
|
||||
source: ev.source,
|
||||
responseSources: ev.response_sources,
|
||||
});
|
||||
flushPendingStreamEvents(ev);
|
||||
if (projectionRef.current.suppressUntilTurnEnd) return;
|
||||
if (ev.resuming) {
|
||||
setIsStreaming(true);
|
||||
@@ -891,20 +873,13 @@ export function useNanobotStream(
|
||||
const unsub = client.onTranscript(chatId, handle);
|
||||
return () => {
|
||||
unsub();
|
||||
// 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);
|
||||
projectionRef.current = resetThreadProjectionCursor(projectionRef.current);
|
||||
// Capture received state, including deltas waiting for a throttled paint.
|
||||
const checkpoint = getCheckpoint();
|
||||
onStreamDetach?.(checkpoint);
|
||||
clearPendingStreamWork();
|
||||
};
|
||||
}, [
|
||||
applyProjectionEvent,
|
||||
applyPendingStreamEvents,
|
||||
applyStreamError,
|
||||
chatId,
|
||||
closeActiveAssistantStream,
|
||||
@@ -917,7 +892,7 @@ export function useNanobotStream(
|
||||
onStreamDetach,
|
||||
schedulePendingStreamFlush,
|
||||
setMessages,
|
||||
t,
|
||||
getCheckpoint,
|
||||
]);
|
||||
|
||||
const send = useCallback(
|
||||
@@ -1061,6 +1036,7 @@ export function useNanobotStream(
|
||||
stop,
|
||||
reconcileTurnComplete,
|
||||
setMessages,
|
||||
getCheckpoint,
|
||||
streamError,
|
||||
dismissStreamError,
|
||||
};
|
||||
|
||||
@@ -50,8 +50,8 @@ export function hasPendingAgentActivity(messages: UIMessage[]): boolean {
|
||||
|
||||
/** Project gateway rows without changing their causal order.
|
||||
*
|
||||
* Messages use ``turnSeq`` when every row in the turn provides it and fall
|
||||
* back to stable arrival order otherwise. Only contiguous rows of the same
|
||||
* Messages use their first contributing sequence (legacy rows use ``turnSeq``)
|
||||
* when every row provides one, and stable arrival order otherwise. Only contiguous rows of the same
|
||||
* display class are combined: activity rows share a collapsible surface, and
|
||||
* adjacent answer slices share an answer bubble. A visible answer is always a
|
||||
* hard boundary between activity surfaces; completed empty transport frames
|
||||
@@ -267,12 +267,14 @@ function isAssistantAnswer(message: UIMessage): boolean {
|
||||
}
|
||||
|
||||
function orderMessagesByTurnSeq(messages: UIMessage[]): UIMessage[] {
|
||||
if (messages.length < 2 || !messages.every((message) => Number.isFinite(message.turnSeq))) {
|
||||
if (messages.length < 2 || !messages.every((message) => Number.isFinite(message.projectionStartSeq ?? message.turnSeq))) {
|
||||
return messages;
|
||||
}
|
||||
return messages
|
||||
.map((message, index) => ({ message, index }))
|
||||
.sort((left, right) => (left.message.turnSeq! - right.message.turnSeq!) || (left.index - right.index))
|
||||
.sort((left, right) => (
|
||||
(left.message.projectionStartSeq ?? left.message.turnSeq!) - (right.message.projectionStartSeq ?? right.message.turnSeq!)
|
||||
) || (left.index - right.index))
|
||||
.map(({ message }) => message);
|
||||
}
|
||||
|
||||
@@ -310,6 +312,7 @@ function reasoningOnlyMessageFromAnswer(message: UIMessage): UIMessage {
|
||||
turnId: message.turnId,
|
||||
turnPhase: "reasoning",
|
||||
turnSeq: message.turnSeq,
|
||||
projectionStartSeq: message.projectionStartSeq,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Byte- and entry-bounded in-memory LRU for JSON-shaped WebUI state. */
|
||||
/** Byte- and entry-bounded in-memory LRU for WebUI state. */
|
||||
export class MemoryLruCache<T> {
|
||||
private entries = new Map<string, { value: T; bytes: number }>();
|
||||
private sizes = new WeakMap<object, number>();
|
||||
@@ -46,7 +46,9 @@ export class MemoryLruCache<T> {
|
||||
if (!value || typeof value !== "object") return 8;
|
||||
const cached = this.sizes.get(value);
|
||||
if (cached !== undefined) return cached;
|
||||
const size = 32 + Object.values(value).reduce<number>(
|
||||
const values = value instanceof Map ? Array.from(value.entries())
|
||||
: value instanceof Set ? Array.from(value) : Object.values(value);
|
||||
const size = 32 + values.reduce<number>(
|
||||
(total, item) => total + this.estimate(item),
|
||||
0,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createThreadProjectionState, type ThreadProjectionState } from "./thread-event-projection";
|
||||
import type { UIMessage } from "./types";
|
||||
|
||||
/** Resumable, memory-only state. Visible rows alone are not a projection cursor. */
|
||||
export interface ThreadCheckpoint {
|
||||
projection: ThreadProjectionState;
|
||||
sideChannelTurnIds: Set<string>;
|
||||
}
|
||||
|
||||
export function createThreadCheckpoint(messages: UIMessage[] = []): ThreadCheckpoint {
|
||||
return { projection: createThreadProjectionState(messages), sideChannelTurnIds: new Set() };
|
||||
}
|
||||
|
||||
export function copyThreadCheckpoint(
|
||||
checkpoint: ThreadCheckpoint,
|
||||
messages = checkpoint.projection.messages,
|
||||
): ThreadCheckpoint {
|
||||
return {
|
||||
projection: {
|
||||
...checkpoint.projection,
|
||||
messages,
|
||||
closedAssistantIds: new Set(checkpoint.projection.closedAssistantIds),
|
||||
closedAnswerStreamIds: new Set(checkpoint.projection.closedAnswerStreamIds),
|
||||
closedTurnIds: new Set(checkpoint.projection.closedTurnIds),
|
||||
turnAliases: new Map(checkpoint.projection.turnAliases),
|
||||
},
|
||||
sideChannelTurnIds: new Set(checkpoint.sideChannelTurnIds),
|
||||
};
|
||||
}
|
||||
@@ -23,6 +23,8 @@ export interface ThreadProjectionState {
|
||||
messages: UIMessage[];
|
||||
activeAssistantId: string | null;
|
||||
closedAssistantIds: Set<string>;
|
||||
/** Completed wire identities also fence late deltas for textless ends. */
|
||||
closedAnswerStreamIds: Set<string>;
|
||||
mergeReasoning: boolean;
|
||||
activitySegmentId: string | null;
|
||||
fileEditSegmentId: string | null;
|
||||
@@ -37,6 +39,8 @@ export interface ThreadProjectionOptions {
|
||||
now: number;
|
||||
persisted?: boolean;
|
||||
sideChannel?: boolean;
|
||||
/** First sequence of a coalesced batch; event.turn_seq is its last contribution. */
|
||||
startSeq?: number;
|
||||
}
|
||||
|
||||
export function turnFieldsFromEvent(
|
||||
@@ -59,6 +63,15 @@ function matchesTurn(message: UIMessage, turn: UIMessageTurnFields): boolean {
|
||||
return !turn.turnId || !message.turnId || message.turnId === turn.turnId;
|
||||
}
|
||||
|
||||
function positionedTurnFields(
|
||||
target: UIMessage | undefined,
|
||||
turn: UIMessageTurnFields,
|
||||
options: ThreadProjectionOptions,
|
||||
): UIMessageTurnFields & Pick<UIMessage, "projectionStartSeq"> {
|
||||
const start = target?.projectionStartSeq ?? target?.turnSeq ?? options.startSeq ?? turn.turnSeq;
|
||||
return { ...turn, ...(start !== undefined ? { projectionStartSeq: start } : {}) };
|
||||
}
|
||||
|
||||
/** Find a still-open streamed assistant turn. Closed stream segments stay visible
|
||||
* as streaming until ``turn_end`` for visual continuity, but they must not
|
||||
* receive later delta segments. */
|
||||
@@ -66,6 +79,7 @@ function findStreamingAssistantIndex(
|
||||
prev: UIMessage[],
|
||||
closedStreamIds: ReadonlySet<string>,
|
||||
turn: UIMessageTurnFields = {},
|
||||
streamId?: string,
|
||||
): number | null {
|
||||
for (let i = prev.length - 1; i >= 0; i -= 1) {
|
||||
const m = prev[i];
|
||||
@@ -74,6 +88,7 @@ function findStreamingAssistantIndex(
|
||||
m.role === "assistant"
|
||||
&& m.isStreaming
|
||||
&& !closedStreamIds.has(m.id)
|
||||
&& (!streamId || !m.streamId || m.streamId === streamId)
|
||||
&& matchesTurn(m, turn)
|
||||
) return i;
|
||||
if (m.role === "user") break;
|
||||
@@ -110,10 +125,15 @@ function replaceMessageAt(
|
||||
|
||||
/** Close the active reasoning stream segment. ``now`` is supplied by the caller
|
||||
* so the projection remains deterministic for replay and fixture tests. */
|
||||
function closeReasoningStream(prev: UIMessage[], now?: number): UIMessage[] {
|
||||
function closeReasoningStream(prev: UIMessage[], now?: number, turn: UIMessageTurnFields = {}, streamId?: string): UIMessage[] {
|
||||
const identifiedIndex = streamId ? prev.findIndex((message) => (
|
||||
message.reasoningStreamId === streamId && matchesTurn(message, turn)
|
||||
)) : -1;
|
||||
for (let i = prev.length - 1; i >= 0; i -= 1) {
|
||||
if (identifiedIndex >= 0 && i !== identifiedIndex) continue;
|
||||
const candidate = prev[i];
|
||||
if (!candidate.reasoningStreaming) continue;
|
||||
if (!candidate.reasoningStreaming || !matchesTurn(candidate, turn)
|
||||
|| (streamId && candidate.reasoningStreamId && streamId !== candidate.reasoningStreamId)) continue;
|
||||
const latencyMs =
|
||||
now !== undefined
|
||||
&& candidate.latencyMs === undefined
|
||||
@@ -374,6 +394,7 @@ export function createThreadProjectionState(
|
||||
messages,
|
||||
activeAssistantId: null,
|
||||
closedAssistantIds: new Set(),
|
||||
closedAnswerStreamIds: new Set(),
|
||||
mergeReasoning: false,
|
||||
activitySegmentId: null,
|
||||
fileEditSegmentId: null,
|
||||
@@ -489,18 +510,44 @@ function activeAssistantIndex(
|
||||
return index;
|
||||
}
|
||||
|
||||
function answerStreamKey(turn: UIMessageTurnFields, streamId?: string): string | undefined {
|
||||
return streamId ? JSON.stringify([turn.turnId ?? "", streamId]) : undefined;
|
||||
}
|
||||
|
||||
function answerStreamIndex(
|
||||
state: ThreadProjectionState,
|
||||
turn: UIMessageTurnFields,
|
||||
streamId?: string,
|
||||
): number | null {
|
||||
if (streamId) {
|
||||
for (let index = state.messages.length - 1; index >= 0; index--) {
|
||||
const message = state.messages[index];
|
||||
if (message.role === "assistant" && message.streamId === streamId && matchesTurn(message, turn)) return index;
|
||||
}
|
||||
}
|
||||
const active = activeAssistantIndex(state, turn);
|
||||
if (active !== null && (!streamId || !state.messages[active].streamId || state.messages[active].streamId === streamId)) {
|
||||
return active;
|
||||
}
|
||||
const placeholder = findActiveAssistantPlaceholderIndex(state.messages, turn);
|
||||
if (placeholder !== null && (!streamId || !state.messages[placeholder].streamId || state.messages[placeholder].streamId === streamId)) {
|
||||
return placeholder;
|
||||
}
|
||||
return findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn, streamId);
|
||||
}
|
||||
|
||||
function appendAnswerText(
|
||||
state: ThreadProjectionState,
|
||||
event: Extract<ThreadProjectionEvent, { event: "delta" }>,
|
||||
options: ThreadProjectionOptions,
|
||||
): void {
|
||||
const turn = turnFieldsForProjection(state, event, "answer");
|
||||
let targetIndex = activeAssistantIndex(state, turn);
|
||||
if (targetIndex === null) targetIndex = findActiveAssistantPlaceholderIndex(state.messages, turn);
|
||||
if (targetIndex === null) {
|
||||
targetIndex = findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn);
|
||||
}
|
||||
const streamKey = answerStreamKey(turn, event.stream_id);
|
||||
if (streamKey && state.closedAnswerStreamIds.has(streamKey)) return;
|
||||
let targetIndex = answerStreamIndex(state, turn, event.stream_id);
|
||||
if (targetIndex !== null && state.closedAssistantIds.has(state.messages[targetIndex].id)) targetIndex = null;
|
||||
if (targetIndex === null) {
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
const id = projectionMessageId(event, options);
|
||||
state.messages = [
|
||||
...state.messages,
|
||||
@@ -519,7 +566,8 @@ function appendAnswerText(
|
||||
...target,
|
||||
content: target.content + event.text,
|
||||
isStreaming: true,
|
||||
...turn,
|
||||
...positionedTurnFields(target, turn, options),
|
||||
...(event.stream_id ? { streamId: event.stream_id } : {}),
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
|
||||
};
|
||||
@@ -536,6 +584,22 @@ function attachProjectedReasoning(
|
||||
options: ThreadProjectionOptions,
|
||||
): void {
|
||||
const turn = turnFieldsForProjection(state, event, "reasoning");
|
||||
const streamIndex = event.stream_id ? state.messages.findIndex((message) => (
|
||||
message.reasoningStreamId === event.stream_id && matchesTurn(message, turn)
|
||||
)) : -1;
|
||||
if (streamIndex >= 0) {
|
||||
const target = state.messages[streamIndex];
|
||||
const continues = state.mergeReasoning && state.activeAssistantId === target.id;
|
||||
if (event.event === "reasoning_delta" && !target.reasoningStreaming && !continues) return;
|
||||
const separator = target.reasoning && !target.reasoningStreaming ? "\n\n" : "";
|
||||
state.messages = replaceMessageAt(state.messages, streamIndex, {
|
||||
...target,
|
||||
reasoning: event.event === "reasoning_end" ? text : (target.reasoning ?? "") + separator + text,
|
||||
reasoningStreaming: event.event === "reasoning_delta" || target.reasoningStreaming,
|
||||
...(!target.content ? positionedTurnFields(target, turn, options) : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const activeAssistantBeforeContinuation = state.activeAssistantId;
|
||||
const continuationIndex = state.mergeReasoning
|
||||
? activeAssistantIndex(state, turn)
|
||||
@@ -547,6 +611,7 @@ function attachProjectedReasoning(
|
||||
...target,
|
||||
reasoning: (target.reasoning ?? "") + separator + text,
|
||||
reasoningStreaming: true,
|
||||
...(event.stream_id ? { reasoningStreamId: event.stream_id } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -562,7 +627,8 @@ function attachProjectedReasoning(
|
||||
const candidate = state.messages[index];
|
||||
if (candidate.role === "user" || candidate.kind === "trace") break;
|
||||
if (candidate.role !== "assistant") continue;
|
||||
if (!matchesTurn(candidate, turn) || candidate.content.length > 0) break;
|
||||
if (!matchesTurn(candidate, turn) || candidate.content.length > 0
|
||||
|| (event.stream_id && candidate.reasoningStreamId && event.stream_id !== candidate.reasoningStreamId)) break;
|
||||
if (candidate.reasoningStreaming || (candidate.isStreaming && candidate.reasoning === undefined)) {
|
||||
const activitySegmentId = candidate.activitySegmentId
|
||||
?? ensureProjectionActivitySegment(state);
|
||||
@@ -571,7 +637,8 @@ function attachProjectedReasoning(
|
||||
reasoning: (candidate.reasoning ?? "") + text,
|
||||
reasoningStreaming: true,
|
||||
activitySegmentId,
|
||||
...turn,
|
||||
...positionedTurnFields(candidate, turn, options),
|
||||
...(event.stream_id ? { reasoningStreamId: event.stream_id } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -589,7 +656,8 @@ function attachProjectedReasoning(
|
||||
reasoning: text,
|
||||
reasoningStreaming: true,
|
||||
activitySegmentId,
|
||||
...turn,
|
||||
...positionedTurnFields(undefined, turn, options),
|
||||
...(event.stream_id ? { reasoningStreamId: event.stream_id } : {}),
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
},
|
||||
];
|
||||
@@ -608,6 +676,7 @@ function absorbProjectedAssistantMessage(
|
||||
{
|
||||
...last,
|
||||
...message,
|
||||
projectionStartSeq: last.projectionStartSeq ?? last.turnSeq ?? message.projectionStartSeq,
|
||||
isStreaming: false,
|
||||
reasoningStreaming: false,
|
||||
},
|
||||
@@ -681,7 +750,7 @@ function projectToolActivity(
|
||||
: lines[lines.length - 1],
|
||||
toolEvents: mergedEvents,
|
||||
activitySegmentId: last.activitySegmentId ?? segmentId,
|
||||
...turn,
|
||||
...positionedTurnFields(last, turn, options),
|
||||
},
|
||||
];
|
||||
return;
|
||||
@@ -697,7 +766,7 @@ function projectToolActivity(
|
||||
...(visibleEvents.length ? { toolEvents: visibleEvents } : {}),
|
||||
...(deferredDetail ? { traceDetail: deferredDetail } : {}),
|
||||
activitySegmentId: segmentId,
|
||||
...turn,
|
||||
...positionedTurnFields(undefined, turn, options),
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
},
|
||||
];
|
||||
@@ -730,7 +799,7 @@ function projectFileEdits(
|
||||
...target,
|
||||
fileEdits: mergeFileEdits(target.fileEdits, normalized),
|
||||
activitySegmentId: segmentId,
|
||||
...turn,
|
||||
...positionedTurnFields(target, turn, options),
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -746,7 +815,7 @@ function projectFileEdits(
|
||||
traces: [],
|
||||
fileEdits: normalized,
|
||||
activitySegmentId: segmentId,
|
||||
...turn,
|
||||
...positionedTurnFields(undefined, turn, options),
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
},
|
||||
];
|
||||
@@ -761,6 +830,7 @@ export function projectThreadEvent(
|
||||
const state: ThreadProjectionState = {
|
||||
...previous,
|
||||
closedAssistantIds: new Set(previous.closedAssistantIds),
|
||||
closedAnswerStreamIds: new Set(previous.closedAnswerStreamIds),
|
||||
closedTurnIds: new Set(previous.closedTurnIds),
|
||||
turnAliases: new Map(previous.turnAliases),
|
||||
};
|
||||
@@ -821,46 +891,54 @@ export function projectThreadEvent(
|
||||
if (state.suppressUntilTurnEnd) return state;
|
||||
const turn = turnFieldsForProjection(state, event, "answer");
|
||||
const mergeNext = event.resuming === true && event.merge_next === true;
|
||||
let targetIndex = activeAssistantIndex(state, turn);
|
||||
if (targetIndex === null) {
|
||||
targetIndex = findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn);
|
||||
}
|
||||
if (typeof event.text === "string") {
|
||||
if (targetIndex === null) {
|
||||
const id = projectionMessageId(event, options);
|
||||
state.messages = [
|
||||
...state.messages,
|
||||
{
|
||||
id,
|
||||
role: "assistant",
|
||||
content: event.text,
|
||||
isStreaming: true,
|
||||
...turn,
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
},
|
||||
];
|
||||
targetIndex = state.messages.length - 1;
|
||||
} else {
|
||||
const target = state.messages[targetIndex];
|
||||
state.messages = replaceMessageAt(state.messages, targetIndex, {
|
||||
...target,
|
||||
content: event.text,
|
||||
isStreaming: true,
|
||||
...turn,
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
|
||||
});
|
||||
const streamKey = answerStreamKey(turn, event.stream_id);
|
||||
const wireClosed = streamKey !== undefined && state.closedAnswerStreamIds.has(streamKey);
|
||||
if (streamKey && !mergeNext) state.closedAnswerStreamIds.add(streamKey);
|
||||
let targetIndex = answerStreamIndex(state, turn, event.stream_id);
|
||||
let text = event.text;
|
||||
// Older completed records can span a hosted tool. Their snapshots already
|
||||
// use rewritten text; live streams now end before the tool starts.
|
||||
if (options.persisted && event.stream_id && typeof text === "string") {
|
||||
let offset = 0;
|
||||
for (let index = 0; index < (targetIndex ?? state.messages.length); index++) {
|
||||
const row = state.messages[index];
|
||||
if (row.streamId === event.stream_id && matchesTurn(row, turn)) offset += row.content.length;
|
||||
}
|
||||
} else if ((event.source || event.response_sources !== undefined) && targetIndex !== null) {
|
||||
if (targetIndex !== null && state.closedAssistantIds.has(state.messages[targetIndex].id)
|
||||
&& !wireClosed && text.length > offset + state.messages[targetIndex].content.length) {
|
||||
offset += state.messages[targetIndex].content.length;
|
||||
targetIndex = null;
|
||||
}
|
||||
text = text.slice(offset);
|
||||
}
|
||||
if (targetIndex === null && typeof text !== "string") return state;
|
||||
const wasClosed = targetIndex !== null && state.closedAssistantIds.has(state.messages[targetIndex].id);
|
||||
if (targetIndex === null && typeof text === "string") {
|
||||
const id = projectionMessageId(event, options);
|
||||
state.messages = [...state.messages, {
|
||||
id,
|
||||
role: "assistant",
|
||||
content: text,
|
||||
isStreaming: true,
|
||||
...positionedTurnFields(undefined, turn, options),
|
||||
...(event.stream_id ? { streamId: event.stream_id } : {}),
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
}];
|
||||
targetIndex = state.messages.length - 1;
|
||||
} else if (targetIndex !== null && (typeof text === "string" || event.source || event.response_sources !== undefined)) {
|
||||
const target = state.messages[targetIndex];
|
||||
state.messages = replaceMessageAt(state.messages, targetIndex, {
|
||||
...state.messages[targetIndex],
|
||||
...turn,
|
||||
...target,
|
||||
...(typeof text === "string" ? { content: text } : {}),
|
||||
...positionedTurnFields(target, turn, options),
|
||||
...(event.stream_id ? { streamId: event.stream_id } : {}),
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
|
||||
});
|
||||
}
|
||||
if (wasClosed || wireClosed) return state;
|
||||
if (targetIndex !== null) state.activeAssistantId = state.messages[targetIndex].id;
|
||||
state.mergeReasoning = mergeNext && state.activeAssistantId !== null;
|
||||
if (!mergeNext) Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
@@ -880,6 +958,8 @@ export function projectThreadEvent(
|
||||
state.messages = closeReasoningStream(
|
||||
state.messages,
|
||||
options.persisted ? undefined : options.now,
|
||||
turnFieldsForProjection(state, event, "reasoning"),
|
||||
event.stream_id,
|
||||
);
|
||||
return state;
|
||||
}
|
||||
@@ -899,7 +979,7 @@ export function projectThreadEvent(
|
||||
phase: event.phase,
|
||||
...(!options.persisted ? { announce: true } : {}),
|
||||
},
|
||||
...turnFieldsForProjection(state, event, "activity"),
|
||||
...positionedTurnFields(state.messages[existing], turnFieldsForProjection(state, event, "activity"), options),
|
||||
};
|
||||
if (existing < 0) state.messages = [...state.messages, message];
|
||||
else state.messages = replaceMessageAt(state.messages, existing, {
|
||||
@@ -945,7 +1025,11 @@ export function projectThreadEvent(
|
||||
...(latencyMs !== undefined ? { latencyMs } : {}),
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
|
||||
...turnFieldsForProjection(state, event, "answer"),
|
||||
...positionedTurnFields(
|
||||
options.sideChannel ? undefined : state.messages.find((message) => message.id === state.activeAssistantId),
|
||||
turnFieldsForProjection(state, event, "answer"),
|
||||
options,
|
||||
),
|
||||
};
|
||||
if (options.sideChannel) {
|
||||
absorbProjectedAssistantMessage(state, event, projected, options);
|
||||
@@ -989,6 +1073,7 @@ export function projectThreadEvent(
|
||||
);
|
||||
state.activeAssistantId = null;
|
||||
state.closedAssistantIds.clear();
|
||||
state.closedAnswerStreamIds.clear();
|
||||
state.mergeReasoning = false;
|
||||
if (event.turn_id) {
|
||||
if (state.turnAliases.has(event.turn_id)) state.turnAliases.delete(event.turn_id);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { UIMessage } from "./types";
|
||||
import type { ThreadCheckpoint } from "./thread-checkpoint";
|
||||
import { MemoryLruCache } from "./memory-lru-cache";
|
||||
|
||||
/** Bounded replay cache; temporary chats remain pinned because they have no disk history. */
|
||||
export class ThreadMessageCache extends MemoryLruCache<UIMessage[]> {
|
||||
export class ThreadMessageCache<T extends ThreadCheckpoint = ThreadCheckpoint> extends MemoryLruCache<T> {
|
||||
|
||||
constructor(
|
||||
isPinned: (key: string) => boolean,
|
||||
|
||||
@@ -172,6 +172,11 @@ export interface UIMessage {
|
||||
turnId?: string;
|
||||
turnPhase?: UITurnPhase;
|
||||
turnSeq?: number;
|
||||
/** First contributing sequence; later content/source updates do not move this row. */
|
||||
projectionStartSeq?: number;
|
||||
/** Phase-qualified stream ownership survives memory-cache restoration. */
|
||||
streamId?: string;
|
||||
reasoningStreamId?: string;
|
||||
/** Ephemeral delivery lifecycle for optimistic user messages. */
|
||||
deliveryStatus?: MessageDeliveryStatus;
|
||||
/** Structured rejection reason shown with a failed optimistic message. */
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import { createThreadProjectionState, projectThreadEvent, projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
|
||||
import type { ThreadProjectionEvent, UIMessage } from "@/lib/types";
|
||||
import projectionFixture from "./fixtures/live-replay-event-projection.json";
|
||||
|
||||
@@ -74,6 +75,98 @@ function normalizeProjection(messages: UIMessage[]): Array<Record<string, unknow
|
||||
}
|
||||
|
||||
describe("canonical thread event projection", () => {
|
||||
it("routes late snapshots by stream without moving same-text answers or stealing the active cursor", () => {
|
||||
let state = createThreadProjectionState();
|
||||
const emit = (event: ThreadProjectionEvent) => {
|
||||
state = projectThreadEvent(state, event, { createId: () => `live-${state.messages.length}`, now: 100 });
|
||||
};
|
||||
emit({ event: "delta", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 1, text: "Same answer" });
|
||||
emit({ event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 2, resuming: true });
|
||||
emit({ event: "message", chat_id: "chat", turn_id: "turn", turn_seq: 3, kind: "tool_hint", text: "read_file(first)" });
|
||||
emit({ event: "delta", chat_id: "chat", turn_id: "turn", stream_id: "second", turn_seq: 4, text: "Same answer" });
|
||||
const source = { provider: "fixture", model: "fixture", preset: "fixture" };
|
||||
emit({ event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 5, text: "Same answer", response_sources: [source] });
|
||||
expect(state.activeAssistantId).toBe("live-2");
|
||||
emit({ event: "delta", chat_id: "chat", turn_id: "turn", stream_id: "second", turn_seq: 6, text: " continued" });
|
||||
emit({ event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "empty", turn_seq: 7, response_sources: [] });
|
||||
expect(state.activeAssistantId).toBe("live-2");
|
||||
expect(normalizeActivityTimeline(state.messages).map((unit) => unit.type === "message"
|
||||
? unit.message.content : unit.messages.map((message) => message.content).join("")))
|
||||
.toEqual(["Same answer", "read_file(first)", "Same answer continued"]);
|
||||
expect(state.messages[0]).toMatchObject({ projectionStartSeq: 1, turnSeq: 5, responseSources: [source] });
|
||||
expect(state.messages[2]).toMatchObject({ projectionStartSeq: 4, turnSeq: 6, streamId: "second" });
|
||||
});
|
||||
|
||||
it("updates an identified reasoning snapshot without duplicating it or closing another phase", () => {
|
||||
const messages = projectThreadEvents([
|
||||
{ event: "reasoning_delta", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 1, text: "First thought" },
|
||||
{ event: "reasoning_end", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 2, text: "First thought" },
|
||||
{ event: "delta", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 3, text: "Answer" },
|
||||
{ event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 4, resuming: true },
|
||||
{ event: "reasoning_delta", chat_id: "chat", turn_id: "turn", turn_seq: 5, text: "Second thought" },
|
||||
{ event: "reasoning_end", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 6, text: "First thought revised" },
|
||||
{ event: "reasoning_delta", chat_id: "chat", turn_id: "turn", turn_seq: 7, text: " continued" },
|
||||
]);
|
||||
expect(messages).toHaveLength(2);
|
||||
expect(messages[0]).toMatchObject({
|
||||
content: "Answer", reasoning: "First thought revised", streamId: "first", reasoningStreamId: "first", projectionStartSeq: 1,
|
||||
});
|
||||
expect(messages[1]).toMatchObject({ reasoning: "Second thought continued", projectionStartSeq: 5 });
|
||||
expect(normalizeActivityTimeline(messages).some((unit) => unit.type === "message" && unit.message.content === "Answer")).toBe(true);
|
||||
});
|
||||
|
||||
it("retains completion latency for a live identified reasoning snapshot", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
let state = projectThreadEvent(createThreadProjectionState(), {
|
||||
event: "reasoning_delta", chat_id: "chat", stream_id: "reasoning", text: "Thought",
|
||||
}, { createId: () => "live", now });
|
||||
state = projectThreadEvent(state, {
|
||||
event: "reasoning_end", chat_id: "chat", stream_id: "reasoning", text: "Thought",
|
||||
}, { createId: () => "end", now: now + 75 });
|
||||
expect(state.messages).toHaveLength(1);
|
||||
expect(state.messages[0]).toMatchObject({ reasoning: "Thought", reasoningStreaming: false, latencyMs: 75 });
|
||||
});
|
||||
|
||||
it("keeps one cumulative merge_next answer through completed HTTP replay", () => {
|
||||
const messages = projectThreadEvents([
|
||||
{ event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "answer", turn_seq: 2, text: "First ", resuming: true, merge_next: true, projection_id: "replay-one" },
|
||||
{ event: "reasoning_end", chat_id: "chat", turn_id: "turn", stream_id: "answer", turn_seq: 3, text: "More reasoning", projection_id: "replay-reasoning" },
|
||||
{ event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "answer", turn_seq: 5, text: "First last", projection_id: "replay-two" },
|
||||
{ event: "turn_end", chat_id: "chat", turn_id: "turn", turn_seq: 6 },
|
||||
]);
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0]).toMatchObject({
|
||||
id: "replay-one", content: "First last", reasoning: "More reasoning",
|
||||
streamId: "answer", reasoningStreamId: "answer", projectionStartSeq: 2, turnSeq: 5,
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["First ", "\n\n"])(
|
||||
"keeps legacy cumulative replay contributions around tools: %s", (prefix) => {
|
||||
const messages = projectThreadEvents([
|
||||
{ event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "answer", turn_seq: 2, text: prefix, resuming: true, merge_next: true },
|
||||
{ event: "message", chat_id: "chat", turn_id: "turn", turn_seq: 3, kind: "tool_hint", text: "web_search(query)" },
|
||||
{ event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "answer", turn_seq: 5, text: prefix + "After tool." },
|
||||
{ event: "turn_end", chat_id: "chat", turn_id: "turn", turn_seq: 6 },
|
||||
]);
|
||||
expect(normalizeActivityTimeline(messages).map((unit) => unit.type === "message"
|
||||
? unit.message.content : unit.messages.map((message) => message.content).join("")))
|
||||
.toEqual([prefix.trim(), "web_search(query)", "After tool."]);
|
||||
expect(messages[0]).toMatchObject({ content: prefix, projectionStartSeq: 2 });
|
||||
expect(messages[2]).toMatchObject({ content: "After tool.", projectionStartSeq: 5 });
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves the stream's position when a complete message replaces its active row", () => {
|
||||
const messages = projectThreadEvents([
|
||||
{ event: "delta", chat_id: "chat", turn_id: "turn", stream_id: "answer", turn_seq: 1, text: "Partial" },
|
||||
{ event: "message", chat_id: "chat", turn_id: "turn", turn_seq: 3, text: "Complete answer" },
|
||||
{ event: "turn_end", chat_id: "chat", turn_id: "turn", turn_seq: 4 },
|
||||
]);
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0]).toMatchObject({ content: "Complete answer", projectionStartSeq: 1, turnSeq: 3 });
|
||||
});
|
||||
|
||||
it.each(["message", "stream_end"] as const)("preserves recorded sources in %s replay", (event) => {
|
||||
const source = { provider: "xai", model: "grok", preset: "saved backup", fallback: true };
|
||||
const messages = projectThreadEvents([
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import type { UIMessage } from "@/lib/types";
|
||||
import { createThreadCheckpoint } from "@/lib/thread-checkpoint";
|
||||
|
||||
const rows: UIMessage[] = [{ id: "u", role: "user", content: "hello", createdAt: 1 }];
|
||||
const messages: UIMessage[] = [{ id: "u", role: "user", content: "hello", createdAt: 1 }];
|
||||
const rows = createThreadCheckpoint(messages);
|
||||
|
||||
it("keeps recently visited chats within the entry budget", () => {
|
||||
const cache = new ThreadMessageCache(() => false, 10000, 2);
|
||||
@@ -15,7 +17,7 @@ it("keeps recently visited chats within the entry budget", () => {
|
||||
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", [{ ...rows[0], content: "x".repeat(1000) }]);
|
||||
cache.set("large", createThreadCheckpoint([{ ...messages[0], content: "x".repeat(1000) }]));
|
||||
expect(cache.get("large")).toBeUndefined();
|
||||
expect(cache.get("temporary")).toBe(rows);
|
||||
cache.delete("temporary");
|
||||
|
||||
@@ -11,6 +11,7 @@ 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 { ClientProvider } from "@/providers/ClientProvider";
|
||||
import type {
|
||||
CliAppsPayload,
|
||||
@@ -508,6 +509,42 @@ describe("ThreadShell", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["callback", "cached return"] as const)("keeps closed answer segments in order after %s", async (path) => {
|
||||
const client = makeClient();
|
||||
const messageCache = new ThreadMessageCache(() => false);
|
||||
const chatId = "answer-order";
|
||||
const turnId = "answer-order-turn";
|
||||
const source = { provider: "fixture", model: "fixture", preset: "fixture" };
|
||||
const shell = (id: string, onTurnEnd = () => {}) => wrap(client, <ThreadShell
|
||||
session={session(id)} title="Answer order" messageCache={messageCache}
|
||||
onToggleSidebar={() => {}} onTurnEnd={onTurnEnd} />);
|
||||
const view = render(shell(chatId));
|
||||
act(() => {
|
||||
client._emitChat(chatId, { event: "goal_status", chat_id: chatId, turn_id: turnId, status: "running", started_at: 100 });
|
||||
client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: turnId, stream_id: "first", turn_seq: 1, text: "Earlier answer" });
|
||||
client._emitChat(chatId, { event: "stream_end", chat_id: chatId, turn_id: turnId, stream_id: "first", turn_seq: 2, resuming: true, response_sources: [source] });
|
||||
client._emitChat(chatId, { event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 3, kind: "tool_hint", text: "read_file(earlier)" });
|
||||
client._emitChat(chatId, { event: "delta", chat_id: chatId, turn_id: turnId, stream_id: "second", turn_seq: 4, text: "Later answer" });
|
||||
client._emitChat(chatId, { event: "stream_end", chat_id: chatId, turn_id: turnId, stream_id: "second", turn_seq: 5, resuming: true, response_sources: [source] });
|
||||
client._emitChat(chatId, { event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 6, kind: "tool_hint", text: "read_file(later)" });
|
||||
});
|
||||
await screen.findByText("Later answer");
|
||||
if (path === "cached return") {
|
||||
view.rerender(shell("other-chat"));
|
||||
expect(screen.queryByText("Earlier answer")).not.toBeInTheDocument();
|
||||
}
|
||||
view.rerender(shell(chatId));
|
||||
await screen.findByText("Earlier answer");
|
||||
act(() => {
|
||||
client._emitChat(chatId, { event: "stream_end", chat_id: chatId, turn_id: turnId, stream_id: "empty-one", turn_seq: 7, resuming: true, response_sources: [source] });
|
||||
client._emitChat(chatId, { event: "stream_end", chat_id: chatId, turn_id: turnId, stream_id: "empty-two", turn_seq: 8, resuming: true, response_sources: [source] });
|
||||
});
|
||||
const earlier = screen.getByText("Earlier answer");
|
||||
const later = screen.getByText("Later answer");
|
||||
expect(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders one persisted task entry at the initiating prompt through the full shell", async () => {
|
||||
const client = makeClient();
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
@@ -3594,13 +3631,13 @@ describe("ThreadShell", () => {
|
||||
const unseenTurnId = "other-tab-completed-turn";
|
||||
const newerTurnId = "new-local-turn";
|
||||
const messageCache = new ThreadMessageCache(() => false);
|
||||
messageCache.set(chatId, [
|
||||
messageCache.set(chatId, createThreadCheckpoint([
|
||||
{ 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 },
|
||||
]);
|
||||
]));
|
||||
client._emitChat(chatId, {
|
||||
event: "goal_status", chat_id: chatId, turn_id: newerTurnId, status: "running", started_at: 2_000,
|
||||
});
|
||||
@@ -3639,7 +3676,7 @@ describe("ThreadShell", () => {
|
||||
const client = makeClient();
|
||||
const chatId = "completed-guidance-paged-prefix";
|
||||
const messageCache = new ThreadMessageCache(() => false);
|
||||
messageCache.set(chatId, [
|
||||
messageCache.set(chatId, createThreadCheckpoint([
|
||||
{ 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 },
|
||||
@@ -3649,7 +3686,7 @@ describe("ThreadShell", () => {
|
||||
{ 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 },
|
||||
]);
|
||||
]));
|
||||
client._emitChat(chatId, {
|
||||
event: "goal_status", chat_id: chatId, turn_id: "new", status: "running", started_at: 2_000,
|
||||
});
|
||||
|
||||
@@ -5,6 +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 type { StreamError } from "@/lib/nanobot-client";
|
||||
import type {
|
||||
ConnectionStatus,
|
||||
@@ -204,6 +205,101 @@ async function flushStreamFrame() {
|
||||
}
|
||||
|
||||
describe("useNanobotStream", () => {
|
||||
it("resumes a merge_next checkpoint 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) });
|
||||
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) });
|
||||
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 });
|
||||
fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 6, text: "last" });
|
||||
fake.emit("checkpoint", { event: "stream_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 7, text: "First last" });
|
||||
});
|
||||
expect(restored.result.current.messages).toHaveLength(1);
|
||||
expect(restored.result.current.messages[0]).toMatchObject({
|
||||
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 ");
|
||||
});
|
||||
|
||||
it.each([true, false])("keeps answer segments across a provider-tool boundary (snapshot: %s)", (snapshot) => {
|
||||
const fake = fakeClient();
|
||||
const { result } = renderHook(() => useNanobotStream("hosted-tool", EMPTY_MESSAGES), { wrapper: wrap(fake.client) });
|
||||
act(() => {
|
||||
fake.emit("hosted-tool", { event: "delta", chat_id: "hosted-tool", turn_id: "turn", stream_id: "answer", turn_seq: 1, text: "First " });
|
||||
fake.emit("hosted-tool", { event: "stream_end", chat_id: "hosted-tool", turn_id: "turn", stream_id: "answer", turn_seq: 2, ...(snapshot ? { text: "First " } : {}), resuming: true });
|
||||
fake.emit("hosted-tool", { event: "message", chat_id: "hosted-tool", turn_id: "turn", turn_seq: 3, kind: "tool_hint", text: "web_search(query)" });
|
||||
fake.emit("hosted-tool", { event: "delta", chat_id: "hosted-tool", turn_id: "turn", stream_id: "after-tool", turn_seq: 4, text: "second" });
|
||||
fake.emit("hosted-tool", { event: "stream_end", chat_id: "hosted-tool", turn_id: "turn", stream_id: "after-tool", turn_seq: 5, ...(snapshot ? { text: "second" } : {}), resuming: true, merge_next: true });
|
||||
});
|
||||
expect(result.current.messages.map((message) => message.content)).toEqual(["First ", "web_search(query)", "second"]);
|
||||
act(() => {
|
||||
fake.emit("hosted-tool", { event: "delta", chat_id: "hosted-tool", turn_id: "turn", stream_id: "after-tool", turn_seq: 6, text: " last" });
|
||||
fake.emit("hosted-tool", { event: "stream_end", chat_id: "hosted-tool", turn_id: "turn", stream_id: "after-tool", turn_seq: 7, ...(snapshot ? { text: "second last" } : {}), response_sources: [] });
|
||||
});
|
||||
expect(result.current.messages.map((message) => message.content)).toEqual(["First ", "web_search(query)", "second last"]);
|
||||
expect(result.current.messages[0].projectionStartSeq).toBe(1);
|
||||
expect(result.current.messages[2].projectionStartSeq).toBe(4);
|
||||
});
|
||||
|
||||
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) });
|
||||
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({
|
||||
content: "First last", streamId: "answer", projectionStartSeq: 1, turnSeq: 2,
|
||||
});
|
||||
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(closed.closedAssistantIds.size).toBe(1);
|
||||
expect(closed.closedAnswerStreamIds.size).toBe(1);
|
||||
});
|
||||
|
||||
it("retains side-channel ownership when restoring an active answer checkpoint", async () => {
|
||||
const fake = fakeClient();
|
||||
const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES), { 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) });
|
||||
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" });
|
||||
fake.emit("checkpoint", { event: "stream_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer" });
|
||||
});
|
||||
expect(restored.result.current.messages.filter((message) => message.role === "assistant").map((message) => message.content))
|
||||
.toEqual(["Active answer continued", "Current model"]);
|
||||
});
|
||||
|
||||
it("keeps invocation snapshots across streaming, recovery segments, completion and reload", async () => {
|
||||
const fake = fakeClient();
|
||||
const a = { provider: "openai_codex", model: "gpt", preset: "writer", fallback: false };
|
||||
|
||||
Reference in new issue
Block a user