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:
chengyongru authored and GitHub committed 2026-10-21 18:30:52 +08:00
1 parent d2ab462b42
commit 76da55994b
19 files changed
+745 -195

No files matched your search

@@ -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 ", "![plot](/api/media/signature/immutable-plot.png)\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([
+4 -2
View File
@@ -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");
+41 -4
View File
@@ -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,
});
+96
View File
@@ -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 };