fix(webui): admit history without dropping live output (NAN-311)

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-22 01:22:49 +08:00
1 parent df63526ddf
commit b37a23698d
21 files changed
+3026 -1607

No files matched your search

+34
View File
@@ -190,6 +190,40 @@ describe("webui API helpers", () => {
);
});
it.each([
{},
{ stream_id: "answer-1" },
{ projection_receipts: [] },
{ stream_id: "answer-1", projection_receipts: [{ turn_id: "turn-1", ranges: [[1, 3], [5, 5]] }] },
])("accepts optional stream identity and projection receipts: %j", async (metadata) => {
const event = { event: "stream_end", chat_id: "chat-1", text: "Reply", turn_id: "turn-1", turn_seq: 6, ...metadata };
vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({
schemaVersion: 3, projection: "events", events: [event],
})));
await expect(fetchWebuiThread("tok", "websocket:chat-1")).resolves.toMatchObject({ events: [event] });
});
it.each([
{ stream_id: 123 },
{ projection_receipts: null },
{ projection_receipts: [{ turn_id: "", ranges: [[1, 2]] }] },
{ projection_receipts: [{ turn_id: "turn-1", ranges: [[2, 1]] }] },
{ projection_receipts: [{ turn_id: "turn-1", ranges: [[1]] }] },
{ projection_receipts: [{ turn_id: "turn-1", ranges: [[-1, 2]] }] },
{ projection_receipts: [{ turn_id: "turn-1", ranges: [[1, 2.5]] }] },
])("rejects malformed stream identity or projection receipts at the HTTP boundary: %j", async (metadata) => {
vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({
schemaVersion: 3,
projection: "events",
events: [{ event: "stream_end", chat_id: "chat-1", text: "Reply", ...metadata }],
})));
await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow(
"Invalid WebUI thread event metadata",
);
});
it.each([
null,
"backup",
+20
View File
@@ -0,0 +1,20 @@
import { expect, it } from "vitest";
import { MemoryLruCache } from "@/lib/memory-lru-cache";
it.each([
{ collection: "Map keys", small: new Map([["turn", "source"]]), large: new Map([["x".repeat(64), "source"]]) },
{ collection: "Map values", small: new Map([["turn", "source"]]), large: new Map([["turn", "x".repeat(64)]]) },
{ collection: "Set members", small: new Set(["turn"]), large: new Set(["x".repeat(64)]) },
])("counts nested $collection toward the byte budget", ({ small, large }) => {
const cache = new MemoryLruCache<{ members: typeof large }>(160, 2);
const snapshot = { members: small };
cache.set("small", snapshot);
expect(cache.get("small")).toBe(snapshot);
cache.set("large", { members: large });
expect(cache.get("large")).toBeUndefined();
cache.set("small", snapshot);
expect(cache.get("small")).toBe(snapshot);
});
+14 -13
View File
@@ -1,26 +1,27 @@
import { expect, it } from "vitest";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { ThreadTranscript } from "@/lib/thread-transcript";
import type { UIMessage } from "@/lib/types";
import { createThreadCheckpoint } from "@/lib/thread-checkpoint";
const messages: UIMessage[] = [{ id: "u", role: "user", content: "hello", createdAt: 1 }];
const rows = createThreadCheckpoint(messages);
const rows: UIMessage[] = [{ id: "u", role: "user", content: "hello", createdAt: 1 }];
const snapshot = new ThreadTranscript(rows).save();
it("keeps recently visited chats within the entry budget", () => {
const cache = new ThreadMessageCache(() => false, 10000, 2);
cache.set("a", rows); cache.set("b", rows);
expect(cache.get("a")).toBe(rows);
cache.set("c", rows);
expect([cache.get("a"), cache.get("b"), cache.get("c")]).toEqual([rows, undefined, rows]);
cache.set("a", snapshot); cache.set("b", snapshot);
expect(cache.get("a")?.projection.messages).toBe(rows);
cache.set("c", snapshot);
expect([cache.get("a")?.projection.messages, cache.get("b"), cache.get("c")?.projection.messages])
.toEqual([rows, undefined, rows]);
});
it("bounds large replay snapshots while retaining temporary chats", () => {
const cache = new ThreadMessageCache((key) => key === "temporary", 1000, 2);
cache.set("temporary", rows);
cache.set("large", createThreadCheckpoint([{ ...messages[0], content: "x".repeat(1000) }]));
const cache = new ThreadMessageCache((key) => key === "temporary", 4096, 2);
cache.set("temporary", snapshot);
cache.set("large", new ThreadTranscript([{ ...rows[0], content: "x".repeat(4096) }]).save());
expect(cache.get("large")).toBeUndefined();
expect(cache.get("temporary")).toBe(rows);
expect(cache.get("temporary")?.projection.messages).toBe(rows);
cache.delete("temporary");
cache.set("small", rows);
expect(cache.get("small")).toBe(rows);
cache.set("small", snapshot);
expect(cache.get("small")?.projection.messages).toBe(rows);
});
@@ -0,0 +1,314 @@
import { describe, expect, it } from "vitest";
import { copyThreadCheckpoint } from "@/lib/thread-checkpoint";
import {
createThreadProjectionState,
projectThreadEvent,
type ThreadProjectionEffects,
type ThreadProjectionOptions,
} from "@/lib/thread-event-projection";
import type { ThreadProjectionEvent, UIFileEdit } from "@/lib/types";
function createProjector(state = createThreadProjectionState()) {
let nextId = 0;
return (
event: ThreadProjectionEvent,
options: Pick<ThreadProjectionOptions, "sideChannel" | "persisted" | "startSeq"> = {},
) => {
const effects: ThreadProjectionEffects = {
bodyWrites: new Set(),
consumed: new Set(),
};
state = projectThreadEvent(state, event, {
createId: () => `row-${++nextId}`,
now: 1_800_000_000_000,
...options,
effects,
});
return { state, effects };
};
}
const turn = { chat_id: "chat", turn_id: "turn" };
function fileEdit(overrides: Partial<UIFileEdit> = {}): UIFileEdit {
return {
call_id: "write-1",
tool: "write_file",
path: "notes.md",
added: 1,
deleted: 0,
status: "editing",
phase: "start",
...overrides,
};
}
describe("thread projection content effects", () => {
it("reports reasoning and answer contributions to their shared body row", () => {
const project = createProjector();
const reasoning = project({
...turn, event: "reasoning_delta", text: "First thought", projection_id: "shared",
});
expect(reasoning.effects.bodyWrites).toEqual(new Set(["shared"]));
const reasoningEnd = project({ ...turn, event: "reasoning_end", text: "." });
expect(reasoningEnd.effects.bodyWrites).toEqual(new Set(["shared"]));
expect(reasoningEnd.state.messages[0].reasoning).toBe("First thought.");
const answer = project({ ...turn, event: "delta", text: "Answer" });
expect(answer.effects.bodyWrites).toEqual(new Set(["shared"]));
const end = project({
...turn, event: "stream_end", text: "Final answer", resuming: true, merge_next: true,
});
expect(end.effects.bodyWrites).toEqual(new Set(["shared"]));
const continuation = project({ ...turn, event: "reasoning_delta", text: "More thought" });
expect(continuation.effects.bodyWrites).toEqual(new Set(["shared"]));
expect(continuation.effects.consumed.size).toBe(0);
expect(continuation.state.messages[0]).toMatchObject({
id: "shared", content: "Final answer", reasoning: "First thought.\n\nMore thought",
});
const closure = project({ ...turn, event: "reasoning_end" });
expect(closure.effects.bodyWrites.size).toBe(0);
expect(closure.effects.consumed.size).toBe(0);
});
it("reports identified reasoning snapshots without claiming another open reasoning row", () => {
const project = createProjector();
project({ ...turn, event: "reasoning_delta", stream_id: "first", text: "Thought", projection_id: "thought" });
project({ ...turn, event: "reasoning_end", stream_id: "first" });
project({ ...turn, event: "delta", stream_id: "first", text: "Answer" });
project({ ...turn, event: "stream_end", stream_id: "first" });
project({ ...turn, event: "reasoning_delta", stream_id: "second", text: "Next thought", projection_id: "next" });
const snapshot = project({ ...turn, event: "reasoning_end", stream_id: "first", text: "Revised thought" });
expect(snapshot.effects.bodyWrites).toEqual(new Set(["thought"]));
expect(snapshot.effects.consumed.size).toBe(0);
expect(snapshot.state.messages[0].reasoning).toBe("Revised thought");
expect(snapshot.state.messages[1]).toMatchObject({ id: "next", reasoningStreaming: true });
const ignored = project({ ...turn, event: "reasoning_delta", stream_id: "first", text: "Late" });
expect(ignored.effects.bodyWrites.size).toBe(0);
expect(ignored.effects.consumed.size).toBe(0);
});
it("reports late answer snapshot targets but not textless metadata or closure patches", () => {
const project = createProjector();
project({ ...turn, event: "delta", stream_id: "first", text: "Draft", projection_id: "first" });
project({ ...turn, event: "stream_end", stream_id: "first" });
project({ ...turn, event: "message", kind: "tool_hint", text: "Tool", projection_id: "tool" });
project({ ...turn, event: "delta", stream_id: "second", text: "Current", projection_id: "second" });
const snapshot = project({ ...turn, event: "stream_end", stream_id: "first", text: "Final" });
expect(snapshot.effects.bodyWrites).toEqual(new Set(["first"]));
expect(snapshot.effects.consumed.size).toBe(0);
expect(snapshot.state.activeAssistantId).toBe("second");
for (const streamId of ["first", "empty"]) {
const metadata = project({ ...turn, event: "stream_end", stream_id: streamId, response_sources: [] });
expect(metadata.effects.bodyWrites.size).toBe(0);
expect(metadata.effects.consumed.size).toBe(0);
expect(metadata.state.activeAssistantId).toBe("second");
expect(metadata.state.messages).toHaveLength(3);
}
const cleared = project({ ...turn, event: "stream_end", stream_id: "first", text: "" });
expect(cleared.effects.bodyWrites).toEqual(new Set(["first"]));
expect(cleared.state.messages[0].content).toBe("");
expect(cleared.state.activeAssistantId).toBe("second");
});
it("reports only the destination slice of legacy cumulative HTTP answer snapshots", () => {
const project = createProjector();
project({
...turn, event: "stream_end", stream_id: "answer", turn_seq: 2, text: "Before ",
resuming: true, merge_next: true, projection_id: "before",
}, { persisted: true });
project({
...turn, event: "message", kind: "tool_hint", turn_seq: 3, text: "Tool", projection_id: "tool",
}, { persisted: true });
const after = project({
...turn, event: "stream_end", stream_id: "answer", turn_seq: 5,
text: "Before after", projection_id: "after",
}, { persisted: true });
expect(after.effects.bodyWrites).toEqual(new Set(["after"]));
expect(after.effects.consumed.size).toBe(0);
expect(after.state.messages.map((message) => message.content)).toEqual(["Before ", "Tool", "after"]);
const revised = project({
...turn, event: "stream_end", stream_id: "answer", turn_seq: 6, text: "Before revised",
}, { persisted: true });
expect(revised.effects.bodyWrites).toEqual(new Set(["after"]));
expect(revised.state.messages[2]).toMatchObject({ content: "revised", projectionStartSeq: 5, turnSeq: 6 });
});
it("reports continuation effects after copying a merge_next checkpoint with closed wire fences", () => {
const project = createProjector();
project({ ...turn, event: "delta", stream_id: "first", text: "First", turn_seq: 2, projection_id: "first" }, { startSeq: 1 });
project({ ...turn, event: "stream_end", stream_id: "first", turn_seq: 3 });
project({ ...turn, event: "message", kind: "tool_hint", text: "Tool", turn_seq: 4, projection_id: "tool" });
project({ ...turn, event: "delta", stream_id: "second", text: "Next ", turn_seq: 6, projection_id: "second" }, { startSeq: 5 });
project({ ...turn, event: "stream_end", stream_id: "second", text: "Next ", turn_seq: 7, resuming: true, merge_next: true });
const queued = project({ ...turn, event: "reasoning_delta", stream_id: "second", text: "Queued ", turn_seq: 8 });
const checkpoint = copyThreadCheckpoint({ projection: queued.state, sideChannelTurnIds: new Set(["command"]) });
const restored = createProjector(copyThreadCheckpoint(checkpoint).projection);
const ignored = restored({ ...turn, event: "delta", stream_id: "first", text: "Late", turn_seq: 9 });
expect(ignored.effects.bodyWrites.size).toBe(0);
const reasoning = restored({ ...turn, event: "reasoning_delta", stream_id: "second", text: "continued", turn_seq: 10 });
expect(reasoning.effects.bodyWrites).toEqual(new Set(["second"]));
const closure = restored({ ...turn, event: "reasoning_end", stream_id: "second", turn_seq: 11 });
expect(closure.effects.bodyWrites.size).toBe(0);
restored({ ...turn, event: "delta", stream_id: "second", text: "last", turn_seq: 12 });
const completed = restored({ ...turn, event: "stream_end", stream_id: "second", text: "Next last", turn_seq: 13 });
expect(completed.effects.bodyWrites).toEqual(new Set(["second"]));
expect(completed.effects.consumed.size).toBe(0);
expect(completed.state.messages[0]).toMatchObject({ content: "First", projectionStartSeq: 1 });
expect(completed.state.messages[2]).toMatchObject({
content: "Next last", reasoning: "Queued continued", projectionStartSeq: 5, turnSeq: 13,
});
expect(checkpoint.projection.messages[2]).toMatchObject({ content: "Next ", reasoning: "Queued " });
expect(checkpoint.projection.closedAnswerStreamIds.size).toBe(1);
expect(completed.state.closedAnswerStreamIds.size).toBe(2);
});
it("reports only the tool body target when activity closes an answer, including trace merges", () => {
const project = createProjector();
project({ ...turn, event: "delta", text: "Working", projection_id: "answer" });
const activity = project({
...turn,
event: "message",
kind: "tool_hint",
text: "Running command",
projection_id: "tool",
tool_events: [{ call_id: "exec-1", name: "exec", phase: "start" }],
});
expect(activity.state.closedAssistantIds.has("answer")).toBe(true);
expect(activity.effects.bodyWrites).toEqual(new Set(["tool"]));
expect(activity.effects.consumed.size).toBe(0);
const merged = project({
...turn,
event: "message",
kind: "progress",
text: "Command finished",
tool_events: [{ call_id: "exec-1", name: "exec", phase: "end", result: "done" }],
});
expect(merged.effects.bodyWrites).toEqual(new Set(["tool"]));
expect(merged.state.messages.find((message) => message.id === "tool")?.toolEvents)
.toEqual([{ call_id: "exec-1", name: "exec", phase: "end", result: "done" }]);
});
it("reports every stripped hint and edit target, consuming only the removed trace row", () => {
const project = createProjector();
const write = { call_id: "write-1", name: "write_file", arguments: { path: "notes.md" } };
project({
...turn, event: "message", kind: "tool_hint", text: "Writing", projection_id: "removed-hint",
tool_events: [{ ...write, phase: "start" }],
});
project({ ...turn, event: "delta", text: "Saving notes", projection_id: "answer" });
project({
...turn, event: "message", kind: "progress", text: "Written", projection_id: "kept-hint",
tool_events: [
{ ...write, phase: "end" },
{ call_id: "exec-1", name: "exec", phase: "end" },
],
});
const edit = project({
...turn, event: "file_edit", edits: [fileEdit()], projection_id: "edits",
});
expect(edit.effects.bodyWrites).toEqual(new Set(["removed-hint", "kept-hint", "edits"]));
expect(edit.effects.consumed).toEqual(new Set(["removed-hint"]));
expect(edit.state.messages.find((message) => message.id === "removed-hint")).toBeUndefined();
expect(edit.state.messages.find((message) => message.id === "kept-hint")?.toolEvents)
.toEqual([{ call_id: "exec-1", name: "exec", phase: "end" }]);
expect(edit.state.messages.find((message) => message.id === "edits")?.fileEdits)
.toEqual([fileEdit()]);
const completed = project({
...turn, event: "file_edit", edits: [fileEdit({ status: "done", phase: "end", added: 2 })],
});
expect(completed.effects.bodyWrites).toEqual(new Set(["edits"]));
expect(completed.effects.consumed.size).toBe(0);
});
it("transfers the consumed active row to the plain assistant replacement", () => {
const project = createProjector();
project({ ...turn, event: "delta", text: "Draft", projection_id: "draft" });
const replacement = project({
...turn, event: "message", text: "Final reply", projection_id: "final",
});
expect(replacement.effects.bodyWrites).toEqual(new Set(["final"]));
expect(replacement.effects.consumed).toEqual(new Set(["draft"]));
expect(replacement.state.messages.find((message) => message.id === "final")?.content)
.toBe("Final reply");
});
it.each([false, true])("reports reasoning-placeholder absorption (sideChannel=%s)", (sideChannel) => {
const project = createProjector();
project({
...turn, event: "message", kind: "reasoning", text: "Thinking", projection_id: "reasoning",
});
const absorbed = project({
...turn, event: "message", text: "Explained", projection_id: "unused-reply-id",
}, { sideChannel });
expect(absorbed.effects.bodyWrites).toEqual(new Set(["reasoning"]));
expect(absorbed.effects.consumed).toEqual(new Set(["reasoning"]));
expect(absorbed.state.messages[0]).toMatchObject({
id: "reasoning", content: "Explained", reasoning: "Thinking",
});
});
it("reports input, stream-end insertion and compaction bodies without owning lifecycle flags", () => {
const project = createProjector();
const input = project({
...turn, event: "user_message", text: "Prompt", starts_turn: true, projection_id: "input",
});
expect(input.effects.bodyWrites).toEqual(new Set(["input"]));
const answer = project({ ...turn, event: "stream_end", text: "Reply", projection_id: "answer" });
expect(answer.effects.bodyWrites).toEqual(new Set(["answer"]));
const started = project({
...turn, event: "context_compaction", compaction_id: "compact", phase: "started",
});
expect(started.effects.bodyWrites).toEqual(new Set(["compaction-compact"]));
const finished = project({
...turn, event: "context_compaction", compaction_id: "compact", phase: "succeeded",
});
expect(finished.effects.bodyWrites).toEqual(new Set(["compaction-compact"]));
for (const event of [
{ ...turn, event: "reasoning_end" },
{ ...turn, event: "stream_end" },
{ ...turn, event: "turn_end", latency_ms: 120, context_window_tokens: 4096 },
] satisfies ThreadProjectionEvent[]) {
const closure = project(event);
expect(closure.effects.bodyWrites.size).toBe(0);
expect(closure.effects.consumed.size).toBe(0);
}
});
it("leaves projection state unchanged when reporting is optional", () => {
const events: ThreadProjectionEvent[] = [
{ ...turn, event: "user_message", text: "Prompt", starts_turn: true },
{ ...turn, event: "reasoning_delta", text: "Thinking" },
{ ...turn, event: "reasoning_end" },
{ ...turn, event: "delta", text: "Draft" },
{ ...turn, event: "message", kind: "tool_hint", text: "Writing",
tool_events: [{ call_id: "write-1", name: "write_file", phase: "start" }] },
{ ...turn, event: "file_edit", edits: [fileEdit()] },
{ ...turn, event: "stream_end", text: "Final reply" },
{ ...turn, event: "message", text: "Replacement" },
{ ...turn, event: "context_compaction", compaction_id: "compact", phase: "succeeded" },
{ ...turn, event: "turn_end", latency_ms: 100 },
];
let reported = createThreadProjectionState();
let unreported = createThreadProjectionState();
events.forEach((event, index) => {
const options = { createId: () => `row-${index}`, now: 1_800_000_000_000 };
const effects: ThreadProjectionEffects = { bodyWrites: new Set(), consumed: new Set() };
reported = projectThreadEvent(reported, event, { ...options, effects });
unreported = projectThreadEvent(unreported, event, options);
expect(reported).toEqual(unreported);
});
});
});
File diff suppressed because it is too large. Load diff
+629
View File
@@ -0,0 +1,629 @@
import { beforeEach, describe, expect, it } from "vitest";
import { ThreadTranscript } from "@/lib/thread-transcript";
import type { ThreadProjectionEvent, WebuiThreadPersistedPayload } from "@/lib/types";
const NOW = 1_800_000_000_000;
let nextId = 0;
beforeEach(() => { nextId = 0; });
function at(turn_id: string, turn_seq: number) {
return { chat_id: "hydration-chat", turn_id, turn_seq };
}
function input(turnId: string, text: string): ThreadProjectionEvent {
return { ...at(turnId, 1), event: "user_message", text, starts_turn: true };
}
function history(
events: ThreadProjectionEvent[],
options: Partial<Omit<WebuiThreadPersistedPayload, "schemaVersion" | "projection" | "events">> = {},
): WebuiThreadPersistedPayload {
return {
schemaVersion: 3,
projection: "events",
events: events.map((event, index) => ({
...event,
projection_id: event.projection_id
?? `canonical:${event.turn_id}:${"turn_seq" in event ? event.turn_seq : index}`,
})),
page: { before_cursor: null, has_more_before: false, user_message_offset: 0 },
...options,
};
}
function receive(thread: ThreadTranscript, ...events: ThreadProjectionEvent[]): void {
for (const event of events) thread.project(event, {
createId: () => `received-${++nextId}`,
now: NOW,
});
}
describe("ThreadTranscript admission", () => {
it("installs an older safe prefix without replacing or redirecting the received foreground", () => {
const thread = new ThreadTranscript();
const read = thread.begin("initial");
receive(thread,
input("turn-now", "Current question"),
{ ...at("turn-now", 2), event: "delta", stream_id: "answer-now", text: "Live " },
);
const foregroundId = thread.messages.at(-1)?.id;
expect(thread.accept(history([
input("turn-before", "Earlier question"),
{ ...at("turn-before", 2), event: "message", text: "Earlier answer" },
{ ...at("turn-before", 3), event: "turn_end" },
input("turn-now", "Current question"),
], { page: { before_cursor: "before-earlier", has_more_before: true, user_message_offset: 7 } }), read)).toBe(true);
expect(thread.messages.map((row) => row.content)).toEqual([
"Earlier question", "Earlier answer", "Current question", "Live ",
]);
expect(thread.paging).toMatchObject({ beforeCursor: "before-earlier", hasMoreBefore: true, userMessageOffset: 7 });
receive(thread, { ...at("turn-now", 3), event: "delta", stream_id: "answer-now", text: "continues" });
expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Live continues" });
});
it("admits independent same-text segments in the active turn using their distinct source identities", () => {
const thread = new ThreadTranscript();
const read = thread.begin("initial");
// Attach during C; A and B ended before this WebSocket attachment.
receive(thread,
input("turn-active", "Continue"),
{ ...at("turn-active", 6), event: "delta", stream_id: "wire-C", text: "Current" },
{ ...at("turn-active", 7), event: "stream_end", stream_id: "wire-C", text: "Current", resuming: true, merge_next: true },
{ ...at("turn-active", 8), event: "delta", stream_id: "wire-C", text: " tail" },
);
const foregroundId = thread.messages.at(-1)?.id;
expect(thread.accept(history([
input("turn-active", "Continue"),
{ ...at("turn-active", 3), event: "stream_end", stream_id: "wire-A", text: "same" },
{ ...at("turn-active", 5), event: "stream_end", stream_id: "wire-B", text: "same" },
{ ...at("turn-active", 7), event: "stream_end", stream_id: "wire-C", text: "Current", resuming: true, merge_next: true },
]), read)).toBe(true);
const answers = thread.messages.filter((row) => row.role === "assistant");
expect(answers.map((row) => row.content)).toEqual(["same", "same", "Current tail"]);
expect(answers[0].id).not.toBe(answers[1].id);
expect(answers[2].id).toBe(foregroundId);
receive(thread, { ...at("turn-active", 9), event: "delta", stream_id: "wire-C", text: " next" });
expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Current tail next" });
});
it("holds every live slice of one cumulative wire and does not move its hosted tool before the first slice", () => {
const thread = new ThreadTranscript();
const read = thread.begin("initial");
receive(thread,
input("turn-hosted", "Inspect"),
{ ...at("turn-hosted", 4), event: "delta", stream_id: "wire-hosted", text: "L1 " },
{ ...at("turn-hosted", 5), event: "message", kind: "progress", text: "Hosted search" },
{ ...at("turn-hosted", 6), event: "delta", stream_id: "wire-hosted", text: "L2" },
);
const leftId = thread.messages[1].id;
const rightId = thread.messages[3].id;
const aggregate: ThreadProjectionEvent = {
...at("turn-hosted", 7), event: "stream_end", stream_id: "wire-hosted",
text: "L1 L2", resuming: true, merge_next: true,
};
// HTTP has compacted S's deltas into its later cumulative end, after the tool.
expect(thread.accept(history([
input("turn-hosted", "Inspect"),
{ ...at("turn-hosted", 3), event: "stream_end", stream_id: "wire-earlier", text: "Earlier independent segment" },
{ ...at("turn-hosted", 5), event: "message", kind: "progress", text: "Hosted search" },
aggregate,
]), read)).toBe(true);
expect(thread.messages.map((row) => row.content)).toEqual([
"Inspect", "Earlier independent segment", "L1 ", "Hosted search", "L2",
]);
expect(thread.messages[2].id).toBe(leftId);
expect(thread.messages[4].id).toBe(rightId);
// A held aggregate grants no text certificate: the real end must still project.
receive(thread, aggregate,
{ ...at("turn-hosted", 8), event: "delta", stream_id: "wire-hosted", text: " continued" },
);
expect(thread.messages.at(-1)).toMatchObject({ id: rightId, content: "L1 L2 continued" });
expect(thread.messages[2]).toMatchObject({ id: leftId, content: "L1 " });
expect(thread.messages[3].content).toBe("Hosted search");
});
it("holds a mixed reasoning-and-answer row as a whole while its answer has a newer continuation", () => {
const thread = new ThreadTranscript();
const read = thread.begin("initial");
receive(thread,
input("turn-mixed", "Explain"),
{ ...at("turn-mixed", 2), event: "reasoning_delta", stream_id: "reasoning-mixed", text: "Think." },
{ ...at("turn-mixed", 3), event: "reasoning_end", stream_id: "reasoning-mixed" },
{ ...at("turn-mixed", 4), event: "delta", stream_id: "answer-mixed", text: "Draft" },
{ ...at("turn-mixed", 5), event: "stream_end", stream_id: "answer-mixed", text: "Draft", resuming: true, merge_next: true },
{ ...at("turn-mixed", 6), event: "delta", stream_id: "answer-mixed", text: " live" },
);
const sharedId = thread.messages[1].id;
expect(thread.accept(history([
input("turn-mixed", "Explain"),
{ ...at("turn-mixed", 3), event: "reasoning_end", stream_id: "reasoning-mixed", text: "Think." },
{ ...at("turn-mixed", 5), event: "stream_end", stream_id: "answer-mixed", text: "Draft", resuming: true, merge_next: true },
]), read)).toBe(true);
expect(thread.messages.filter((row) => row.role === "assistant")).toMatchObject([
{ id: sharedId, reasoning: "Think.", content: "Draft live" },
]);
receive(thread, { ...at("turn-mixed", 7), event: "delta", stream_id: "answer-mixed", text: " more" });
expect(thread.messages.at(-1)).toMatchObject({ id: sharedId, reasoning: "Think.", content: "Draft live more" });
});
it("suppresses history-covered late text but continues the installed cursor and respects its next real end", () => {
const thread = new ThreadTranscript();
const installed: ThreadProjectionEvent = {
...at("turn-history-first", 4), event: "stream_end", stream_id: "answer-first",
text: "Installed ", resuming: true, merge_next: true,
};
expect(thread.accept(history([input("turn-history-first", "Continue"), installed]), thread.begin("initial"))).toBe(true);
const answerId = thread.messages[1].id;
receive(thread,
{ ...at("turn-history-first", 2), event: "delta", stream_id: "answer-first", text: "Installed " },
installed,
{ ...at("turn-history-first", 5), event: "delta", stream_id: "answer-first", text: "continuation" },
);
expect(thread.messages).toHaveLength(2);
expect(thread.messages[1]).toMatchObject({ id: answerId, content: "Installed continuation" });
receive(thread,
{ ...at("turn-history-first", 6), event: "stream_end", stream_id: "answer-first", text: "Installed continuation" },
{ ...at("turn-history-first", 7), event: "delta", stream_id: "answer-next", text: "Next segment" },
);
expect(thread.messages.filter((row) => row.role === "assistant").map((row) => row.content))
.toEqual(["Installed continuation", "Next segment"]);
expect(thread.messages[2].id).not.toBe(answerId);
});
it.each([false, true])("retains a closed wire through a truncated page and historical delivery (visible slice: %s)", (visibleSlice) => {
const thread = new ThreadTranscript();
// A capped active-turn window can start after an earlier chunk. A textless
// end is a wire fence even when this window has no body for that wire.
expect(thread.accept(history([
...(visibleSlice ? [{ ...at("turn-capped", 3), event: "delta" as const, stream_id: "closed-wire", text: "Retained slice" }] : []),
{ ...at("turn-capped", 4), event: "stream_end", stream_id: "closed-wire", resuming: true },
{ ...at("turn-capped", 7), event: "stream_end", stream_id: "current-wire", text: "Current", resuming: true, merge_next: true },
], { page: { before_cursor: "earlier", has_more_before: true, user_message_offset: 0,
truncated_oversized_turn: true } }), thread.begin("initial"))).toBe(true);
const restored = new ThreadTranscript([], thread.save());
const contents = restored.messages.map((row) => row.content);
receive(restored, { ...at("turn-capped", 2), event: "delta", stream_id: "closed-wire", text: "Late older chunk" });
expect(restored.messages.map((row) => row.content)).toEqual(contents);
receive(restored, { ...at("turn-capped", 8), event: "delta", stream_id: "current-wire", text: " continues" });
expect(restored.messages.at(-1)?.content).toBe("Current continues");
});
it("keeps missing-ID reasoning segments separate at their actual ends and does not swallow a fresh segment", () => {
const thread = new ThreadTranscript();
expect(thread.accept(history([
input("turn-no-id", "Think in stages"),
{ ...at("turn-no-id", 3), event: "reasoning_end", text: "First thought" },
{ ...at("turn-no-id", 4), event: "message", kind: "progress", text: "Read a file" },
{ ...at("turn-no-id", 7), event: "reasoning_end", text: "Second thought" },
]), thread.begin("initial"))).toBe(true);
receive(thread,
{ ...at("turn-no-id", 2), event: "reasoning_delta", text: "First thought" },
{ ...at("turn-no-id", 6), event: "reasoning_delta", text: "Second thought" },
{ ...at("turn-no-id", 3), event: "reasoning_end", text: "First thought" },
{ ...at("turn-no-id", 8), event: "reasoning_delta", text: "Third thought" },
{ ...at("turn-no-id", 9), event: "reasoning_end" },
{ ...at("turn-no-id", 10), event: "delta", stream_id: "answer-after-thoughts", text: "Fresh answer" },
);
expect(thread.messages.filter((row) => row.reasoning).map((row) => row.reasoning))
.toEqual(["First thought", "Second thought", "Third thought"]);
expect(thread.messages).toHaveLength(5);
expect(thread.messages.at(-1)).toMatchObject({ reasoning: "Third thought", content: "Fresh answer" });
});
it("admits earlier missing-ID reasoning segments before an already received later segment", () => {
const thread = new ThreadTranscript();
const read = thread.begin("initial");
// Attach after the first reasoning end; the received delta belongs to the second buffer.
receive(thread,
input("turn-reasoning-attach", "Think in stages"),
{ ...at("turn-reasoning-attach", 6), event: "reasoning_delta", text: "Second live" },
);
const foregroundId = thread.messages.at(-1)?.id;
expect(thread.accept(history([
input("turn-reasoning-attach", "Think in stages"),
{ ...at("turn-reasoning-attach", 3), event: "reasoning_end", text: "First thought" },
{ ...at("turn-reasoning-attach", 4), event: "message", kind: "progress", text: "Read a file" },
{ ...at("turn-reasoning-attach", 7), event: "reasoning_end", text: "Second snapshot" },
]), read)).toBe(true);
expect(thread.messages.map((row) => row.reasoning || row.content)).toEqual([
"Think in stages", "First thought", "Read a file", "Second live",
]);
receive(thread, { ...at("turn-reasoning-attach", 8), event: "reasoning_delta", text: " continues" });
expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, reasoning: "Second live continues" });
});
it("honors exact summary receipts while inserting a late hole without closing the foreground answer", () => {
const thread = new ThreadTranscript();
const detail = { ref: "2.history-summary", bytes: 40_000, traceCount: 3 };
expect(thread.accept(history([
input("turn-unrelated", "Earlier question"),
{ ...at("turn-unrelated", 2), event: "message", text: "Earlier answer" },
{ ...at("turn-unrelated", 3), event: "turn_end" },
input("turn-summary", "Run tools"),
{
...at("turn-summary", 3), event: "message", kind: "progress", text: "Tools summary",
trace_detail: detail,
projection_receipts: [{ turn_id: "turn-summary", ranges: [[3, 4], [8, 8]] }],
},
{ ...at("turn-summary", 10), event: "stream_end", stream_id: "answer-summary", text: "Foreground ", resuming: true, merge_next: true },
]), thread.begin("initial"))).toBe(true);
const foregroundId = thread.messages.at(-1)?.id;
receive(thread,
{ ...at("turn-summary", 4), event: "message", kind: "progress", text: "Already summarized member 4" },
{ ...at("turn-summary", 8), event: "message", kind: "progress", text: "Already summarized member 8" },
{ ...at("turn-summary", 11), event: "delta", stream_id: "answer-summary", text: "live" },
{ ...at("turn-summary", 6), event: "message", kind: "progress", text: "Delayed independent tool" },
{ ...at("turn-summary", 12), event: "delta", stream_id: "answer-summary", text: " continues" },
);
expect(thread.messages.map((row) => row.content)).toEqual([
"Earlier question", "Earlier answer", "Run tools", "Tools summary", "Delayed independent tool", "Foreground live continues",
]);
expect(thread.messages[3].traceDetail).toEqual(detail);
expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, isStreaming: true });
});
it("does not install a later turn's completion receipt behind a held canonical source", () => {
const thread = new ThreadTranscript();
const read = thread.begin("initial");
receive(thread,
input("turn-held", "Current question"),
{ ...at("turn-held", 2), event: "delta", stream_id: "answer-held", text: "Current live" },
);
expect(thread.accept(history([
input("turn-held", "Current question"),
{ ...at("turn-held", 3), event: "stream_end", stream_id: "answer-held", text: "Current snapshot", resuming: true, merge_next: true },
input("turn-later", "Later question"),
{ ...at("turn-later", 2), event: "message", text: "Later canonical answer" },
{ ...at("turn-later", 3), event: "turn_end", latency_ms: 250 },
]), read)).toBe(true);
expect(thread.messages.map((row) => row.content)).toEqual(["Current question", "Current live"]);
receive(thread,
input("turn-later", "Later question"),
{ ...at("turn-later", 2), event: "delta", stream_id: "answer-later", text: "Later received answer" },
{ ...at("turn-later", 3), event: "turn_end", latency_ms: 250 },
);
expect(thread.messages.at(-1)).toMatchObject({ content: "Later received answer", isStreaming: false, latencyMs: 250 });
});
it("advances the accepted cursor and user offset across an older hidden-only page", () => {
const thread = new ThreadTranscript();
expect(thread.accept(history([
input("turn-visible", "Visible question"),
{ ...at("turn-visible", 3), event: "stream_end", stream_id: "answer-visible", text: "Visible answer" },
{ ...at("turn-visible", 4), event: "turn_end" },
], { page: { before_cursor: "before-visible", has_more_before: true, user_message_offset: 6 } }), thread.begin("initial"))).toBe(true);
const visible = thread.messages;
const version = thread.paging.version;
expect(thread.accept(history([], {
page: { before_cursor: "before-hidden", has_more_before: true, user_message_offset: 4, loaded_event_count: 20 },
}), thread.begin("older"))).toBe(true);
expect(thread.messages).toEqual(visible);
expect(thread.paging).toMatchObject({
beforeCursor: "before-hidden", hasMoreBefore: true, userMessageOffset: 4,
loadingOlder: false, olderError: null,
});
expect(thread.paging.version).toBe(version);
});
it("restores a cached full cursor and coverage before reasoning and answer continuation", () => {
const original = new ThreadTranscript();
expect(original.accept(history([
input("turn-cached", "Continue after returning"),
{ ...at("turn-cached", 3), event: "reasoning_end", text: "Plan." },
{ ...at("turn-cached", 5), event: "stream_end", stream_id: "answer-cached", text: "First", resuming: true, merge_next: true },
]), original.begin("initial"))).toBe(true);
const sharedId = original.messages[1].id;
expect(original.accept(history([
input("turn-cached-older", "Earlier cached question"),
{ ...at("turn-cached-older", 2), event: "message", text: "Earlier cached answer" },
{ ...at("turn-cached-older", 3), event: "turn_end" },
], { page: { before_cursor: "before-cached-older", has_more_before: true, user_message_offset: 3 } }), original.begin("older"))).toBe(true);
const saved = original.save();
receive(original, input("turn-other", "Another visit"));
const restored = new ThreadTranscript([], saved);
receive(restored,
{ ...at("turn-cached", 4), event: "delta", stream_id: "answer-cached", text: "First" },
{ ...at("turn-cached", 6), event: "reasoning_delta", text: "Continue." },
{ ...at("turn-cached", 7), event: "reasoning_end" },
{ ...at("turn-cached", 8), event: "delta", stream_id: "answer-cached", text: " second" },
);
expect(restored.messages).toHaveLength(4);
expect(restored.messages.slice(0, 2).map((row) => row.content)).toEqual(["Earlier cached question", "Earlier cached answer"]);
expect(restored.paging).toMatchObject({ beforeCursor: "before-cached-older", hasMoreBefore: true, userMessageOffset: 3 });
expect(restored.messages.at(-1)).toMatchObject({
id: sharedId, content: "First second", reasoning: "Plan.\n\nContinue.",
});
expect(restored.messages.some((row) => row.turnId === "turn-other")).toBe(false);
});
it("preserves the loaded older prefix and its frontier when a latest window overlaps the suffix", () => {
const thread = new ThreadTranscript();
const latest = [
input("turn-second", "Second question"),
{ ...at("turn-second", 2), event: "message", text: "Second answer" },
{ ...at("turn-second", 3), event: "turn_end" },
] satisfies ThreadProjectionEvent[];
expect(thread.accept(history(latest, {
page: { before_cursor: "before-second", has_more_before: true, user_message_offset: 1 },
}), thread.begin("initial"))).toBe(true);
expect(thread.accept(history([
input("turn-first", "First question"),
{ ...at("turn-first", 2), event: "message", text: "First answer" },
{ ...at("turn-first", 3), event: "turn_end" },
], { page: { before_cursor: "before-first", has_more_before: false, user_message_offset: 0 } }), thread.begin("older"))).toBe(true);
expect(thread.accept(history(latest, {
page: { before_cursor: "before-second", has_more_before: true, user_message_offset: 1 },
}), thread.begin("latest"))).toBe(true);
expect(thread.messages.map((row) => row.content)).toEqual([
"First question", "First answer", "Second question", "Second answer",
]);
expect(thread.paging).toMatchObject({ beforeCursor: "before-first", hasMoreBefore: false, userMessageOffset: 0 });
});
it("rejects an older ticket from before an authorized latest-window reset without moving the frontier", () => {
const thread = new ThreadTranscript();
expect(thread.accept(history([
input("turn-canonical-old", "Old window"),
{ ...at("turn-canonical-old", 2), event: "message", text: "Old answer" },
{ ...at("turn-canonical-old", 3), event: "turn_end" },
], { page: { before_cursor: "before-old", has_more_before: true, user_message_offset: 4 } }), thread.begin("initial"))).toBe(true);
const older = thread.begin("older");
const refresh = thread.begin("latest");
expect(thread.accept(history([
input("turn-canonical-new", "New window"),
{ ...at("turn-canonical-new", 2), event: "message", text: "New answer" },
{ ...at("turn-canonical-new", 3), event: "turn_end" },
], { page: { before_cursor: "before-reset", has_more_before: true, user_message_offset: 9 } }), refresh)).toBe(true);
const accepted = thread.messages;
expect(thread.accept(history([
input("turn-too-old", "Stale older question"),
{ ...at("turn-too-old", 2), event: "message", text: "Stale older answer" },
], { page: { before_cursor: "before-stale", has_more_before: false, user_message_offset: 0 } }), older)).toBe(false);
expect(thread.messages).toEqual(accepted);
expect(thread.paging).toMatchObject({ beforeCursor: "before-reset", hasMoreBefore: true, userMessageOffset: 9 });
});
it("reports a stalled older cursor as retryable without installing rows or claiming exhaustion", () => {
const thread = new ThreadTranscript();
const events = [
input("turn-stalled", "Question"),
{ ...at("turn-stalled", 2), event: "message", text: "Answer" },
{ ...at("turn-stalled", 3), event: "turn_end" },
] satisfies ThreadProjectionEvent[];
expect(thread.accept(history(events, {
page: { before_cursor: "same-cursor", has_more_before: true, user_message_offset: 6 },
}), thread.begin("initial"))).toBe(true);
const accepted = thread.messages;
expect(thread.accept(history(events, {
page: { before_cursor: "same-cursor", has_more_before: true, user_message_offset: 4 },
}), thread.begin("older"))).toBe(false);
expect(thread.messages).toEqual(accepted);
expect(thread.paging).toMatchObject({
beforeCursor: "same-cursor", hasMoreBefore: true, userMessageOffset: 6, loadingOlder: false,
});
expect(thread.paging.olderError).toEqual(expect.any(String));
expect(thread.paging.olderError).not.toBe("");
});
it("retains a post-request input and its received tail when an older latest snapshot returns", () => {
const thread = new ThreadTranscript();
const old = history([
input("turn-settled", "Settled question"),
{ ...at("turn-settled", 2), event: "message", text: "Settled answer" },
{ ...at("turn-settled", 3), event: "turn_end" },
]);
expect(thread.accept(old, thread.begin("initial"))).toBe(true);
const refresh = thread.begin("latest");
receive(thread,
input("turn-new-input", "New question"),
{ ...at("turn-new-input", 2), event: "delta", stream_id: "answer-new-input", text: "New live" },
);
const foregroundId = thread.messages.at(-1)?.id;
expect(thread.accept(old, refresh)).toBe(true);
expect(thread.messages.map((row) => row.content)).toEqual([
"Settled question", "Settled answer", "New question", "New live",
]);
receive(thread, { ...at("turn-new-input", 3), event: "delta", stream_id: "answer-new-input", text: " tail" });
expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "New live tail" });
});
it("keeps a received answer between its two canonical input anchors when a refresh omits that answer", () => {
const thread = new ThreadTranscript();
expect(thread.accept(history([input("turn-fork-first", "First question")]), thread.begin("initial"))).toBe(true);
receive(thread,
{ ...at("turn-fork-first", 2), event: "message", text: "First live answer" },
input("turn-fork-second", "Second question"),
);
expect(thread.accept(history([
input("turn-fork-first", "First question"),
input("turn-fork-second", "Second question"),
]), thread.begin("latest"))).toBe(true);
expect(thread.messages.map((row) => row.content)).toEqual([
"First question", "First live answer", "Second question",
]);
});
it("does not treat an unanchored durable reply received after the request as proof of a new append turn", () => {
const thread = new ThreadTranscript();
expect(thread.accept(history([
{ chat_id: "hydration-chat", event: "message", projection_id: "old-canonical", text: "Old canonical row" },
]), thread.begin("initial"))).toBe(true);
const refresh = thread.begin("latest");
receive(thread, { ...at("turn-unanchored-tail", 2), event: "message", text: "Received durable tail" });
expect(thread.accept(history([
{ chat_id: "hydration-chat", event: "message", projection_id: "disjoint-canonical", text: "Disjoint canonical row" },
]), refresh)).toBe(false);
expect(thread.messages.map((row) => row.content)).toEqual(["Old canonical row", "Received durable tail"]);
});
it("retires a disjoint canonical window on refresh while keeping a post-request received tail", () => {
const thread = new ThreadTranscript();
expect(thread.accept(history([
input("turn-retired", "Old cached window"),
{ ...at("turn-retired", 2), event: "stream_end", stream_id: "answer-retired", text: "Old answer" },
{ ...at("turn-retired", 3), event: "turn_end" },
], { page: { before_cursor: "before-retired", has_more_before: true, user_message_offset: 4 } }), thread.begin("initial"))).toBe(true);
const older = thread.begin("older");
const refresh = thread.begin("latest");
receive(thread,
input("turn-post-request", "New input"),
{ ...at("turn-post-request", 2), event: "delta", stream_id: "answer-post-request", text: "Live" },
);
const foregroundId = thread.messages.at(-1)?.id;
expect(thread.accept(history([
input("turn-revalidated", "New canonical window"),
{ ...at("turn-revalidated", 2), event: "message", text: "Canonical answer" },
{ ...at("turn-revalidated", 3), event: "turn_end" },
], { page: { before_cursor: "before-revalidated", has_more_before: true, user_message_offset: 9 } }), refresh)).toBe(true);
expect(thread.messages.map((row) => row.content)).toEqual([
"New canonical window", "Canonical answer", "New input", "Live",
]);
expect(thread.paging).toMatchObject({ beforeCursor: "before-revalidated", hasMoreBefore: true, userMessageOffset: 9 });
receive(thread, { ...at("turn-post-request", 3), event: "delta", stream_id: "answer-post-request", text: " tail" });
expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Live tail" });
expect(thread.accept(history([], { page: { before_cursor: null, has_more_before: false } }), older)).toBe(false);
const saved = thread.save();
expect(Array.from(saved.boundaries.keys())).not.toContain(JSON.stringify(["turn-retired", "answer", "answer-retired"]));
expect(Array.from(saved.knownTurns).sort()).toEqual(["turn-post-request", "turn-revalidated"]);
expect(Array.from(saved.installed.keys())).toEqual(["turn-revalidated"]);
expect(saved.units.every((unit) => !unit.members.has("turn-retired"))).toBe(true);
const restored = new ThreadTranscript([], saved);
receive(restored, { ...at("turn-post-request", 4), event: "delta", stream_id: "answer-post-request", text: " restored" });
expect(restored.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Live tail restored" });
});
it("does not authorize a disjoint reset from a continuation of a source already retained before the request", () => {
const thread = new ThreadTranscript();
expect(thread.accept(history([
input("turn-before-request", "Question"),
{ ...at("turn-before-request", 3), event: "stream_end", stream_id: "answer-before-request", text: "Installed", resuming: true, merge_next: true },
]), thread.begin("initial"))).toBe(true);
const foregroundId = thread.messages.at(-1)?.id;
const refresh = thread.begin("latest");
receive(thread, { ...at("turn-before-request", 4), event: "delta", stream_id: "answer-before-request", text: " live" });
expect(thread.accept(history([
input("turn-disjoint", "Disjoint question"),
{ ...at("turn-disjoint", 2), event: "message", text: "Disjoint answer" },
]), refresh)).toBe(false);
expect(thread.messages.map((row) => row.content)).toEqual(["Question", "Installed live"]);
receive(thread, { ...at("turn-before-request", 5), event: "delta", stream_id: "answer-before-request", text: " continues" });
expect(thread.messages.at(-1)).toMatchObject({ id: foregroundId, content: "Installed live continues" });
});
it("keeps retired-window metadata out of the resumable cache snapshot", () => {
const thread = new ThreadTranscript();
for (let index = 0; index < 4; index++) {
const turn = `turn-window-${index}`;
expect(thread.accept(history([
input(turn, "Question"),
{ ...at(turn, 2), event: "stream_end", stream_id: `answer-${index}`, text: "Answer" },
{ ...at(turn, 3), event: "turn_end" },
], { completed_turn_ids: [turn] }), thread.begin(index === 0 ? "initial" : "latest"))).toBe(true);
}
expect(thread.messages).toHaveLength(2);
const saved = thread.save();
expect(Array.from(saved.projection.closedTurnIds)).toEqual(["turn-window-3"]);
expect(Array.from(saved.knownTurns)).toEqual(["turn-window-3"]);
expect(Array.from(saved.installed.keys())).toEqual(["turn-window-3"]);
expect(saved.units.every((unit) => Array.from(unit.members.keys()).every((turn) => turn === "turn-window-3"))).toBe(true);
});
it("does not certify earlier reasoning from a truncated snapshot with an unknown left boundary", () => {
const thread = new ThreadTranscript();
expect(thread.accept(history([
{ ...at("turn-unknown-left", 5), event: "reasoning_end", text: "Truncated thought" },
], { page: { before_cursor: "before-unknown", has_more_before: true, truncated_oversized_turn: true } }), thread.begin("initial"))).toBe(true);
receive(thread,
{ ...at("turn-unknown-left", 3), event: "reasoning_delta", text: "Earlier uncovered thought" },
{ ...at("turn-unknown-left", 6), event: "reasoning_delta", text: "Fresh thought" },
{ ...at("turn-unknown-left", 7), event: "reasoning_end" },
{ ...at("turn-unknown-left", 8), event: "delta", stream_id: "answer-unknown-left", text: "Fresh answer" },
);
expect(thread.messages.map((row) => row.reasoning)).toEqual([
"Earlier uncovered thought", "Truncated thought", "Fresh thought",
]);
expect(thread.messages.at(-1)).toMatchObject({ reasoning: "Fresh thought", content: "Fresh answer" });
});
it("does not replace a received source merely because a truncated page reports its turn completed", () => {
const thread = new ThreadTranscript();
const read = thread.begin("initial");
receive(thread,
input("turn-truncated", "Long question"),
{ ...at("turn-truncated", 2), event: "delta", stream_id: "answer-truncated", text: "Received" },
);
const receivedId = thread.messages[1].id;
expect(thread.accept(history([
input("turn-truncated", "Long question"),
{ ...at("turn-truncated", 4), event: "stream_end", stream_id: "answer-truncated", text: "Received full answer" },
{ ...at("turn-truncated", 5), event: "turn_end" },
], {
completed_turn_ids: ["turn-truncated"],
page: { before_cursor: "before-oversized", has_more_before: true, truncated_oversized_turn: true },
}), read)).toBe(true);
expect(thread.messages.filter((row) => row.role === "assistant")).toMatchObject([
{ id: receivedId, content: "Received" },
]);
expect(thread.paging.truncated).toBe(true);
});
it("can replace a fully represented received turn with a nontruncated explicit canonical completion", () => {
const thread = new ThreadTranscript();
const read = thread.begin("initial");
receive(thread,
input("turn-complete", "Question"),
{ ...at("turn-complete", 2), event: "delta", stream_id: "answer-complete", text: "Received" },
);
const receivedId = thread.messages[1].id;
expect(thread.accept(history([
input("turn-complete", "Question"),
{ ...at("turn-complete", 4), event: "stream_end", stream_id: "answer-complete", text: "Received full answer" },
{ ...at("turn-complete", 5), event: "turn_end" },
], { completed_turn_ids: ["turn-complete"] }), read)).toBe(true);
expect(thread.messages.filter((row) => row.role === "assistant")).toMatchObject([
{ content: "Received full answer", isStreaming: false },
]);
expect(thread.messages[1].id).not.toBe(receivedId);
});
});
+37 -24
View File
@@ -5,7 +5,7 @@ import { describe, expect, it, vi } from "vitest";
import { useNanobotStream } from "@/hooks/useNanobotStream";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
import type { ThreadCheckpoint } from "@/lib/thread-checkpoint";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import type { StreamError } from "@/lib/nanobot-client";
import type {
ConnectionStatus,
@@ -205,20 +205,21 @@ async function flushStreamFrame() {
}
describe("useNanobotStream", () => {
it("resumes a merge_next checkpoint including reasoning queued before detach", () => {
it("resumes a merge_next cached snapshot including reasoning queued before detach", () => {
const fake = fakeClient();
let checkpoint: ThreadCheckpoint | undefined;
const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, undefined,
(value) => { checkpoint = value; }), { wrapper: wrap(fake.client) });
const cache = new ThreadMessageCache(() => false);
const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false,
undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) });
act(() => {
fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 1, text: "First " });
fake.emit("checkpoint", { event: "stream_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 2, text: "First ", resuming: true, merge_next: true });
fake.emit("checkpoint", { event: "reasoning_delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 3, text: "Queued " });
});
first.unmount();
expect(checkpoint?.projection.messages[0].reasoning).toBe("Queued ");
const restored = renderHook(() => useNanobotStream("checkpoint", checkpoint!.projection.messages, false,
undefined, undefined, [], checkpoint), { wrapper: wrap(fake.client) });
const snapshot = cache.get("checkpoint")!;
expect(snapshot.projection.messages[0].reasoning).toBe("Queued ");
const restored = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false,
undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) });
act(() => {
fake.emit("checkpoint", { event: "reasoning_delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 4, text: "Continue reasoning" });
fake.emit("checkpoint", { event: "reasoning_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 5 });
@@ -230,8 +231,8 @@ describe("useNanobotStream", () => {
content: "First last", reasoning: "Queued Continue reasoning", streamId: "answer", reasoningStreamId: "answer",
projectionStartSeq: 1, turnSeq: 7,
});
expect(checkpoint?.projection.messages[0].content).toBe("First ");
expect(checkpoint?.projection.messages[0].reasoning).toBe("Queued ");
expect(snapshot.projection.messages[0].content).toBe("First ");
expect(snapshot.projection.messages[0].reasoning).toBe("Queued ");
});
it.each([true, false])("keeps answer segments across a provider-tool boundary (snapshot: %s)", (snapshot) => {
@@ -256,41 +257,50 @@ describe("useNanobotStream", () => {
it("captures the first sequence of coalesced chunks before a paint", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES), { wrapper: wrap(fake.client) });
const cache = new ThreadMessageCache(() => false);
const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false,
undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) });
act(() => {
fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 1, text: "First " });
fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 2, text: "last" });
});
let checkpoint!: ThreadCheckpoint;
act(() => { checkpoint = result.current.getCheckpoint(); });
expect(checkpoint.projection.messages).toHaveLength(1);
expect(checkpoint.projection.messages[0]).toMatchObject({
expect(first.result.current.messages).toHaveLength(0);
first.unmount();
const snapshot = cache.get("checkpoint")!;
expect(snapshot.projection.messages).toHaveLength(1);
expect(snapshot.projection.messages[0]).toMatchObject({
content: "First last", streamId: "answer", projectionStartSeq: 1, turnSeq: 2,
});
const restored = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false,
undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) });
act(() => {
fake.emit("checkpoint", { event: "stream_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 3, response_sources: [] });
});
expect(result.current.messages[0]).toMatchObject({ projectionStartSeq: 1, turnSeq: 3 });
expect(checkpoint.projection.closedAssistantIds.size).toBe(0);
expect(checkpoint.projection.closedAnswerStreamIds.size).toBe(0);
const closed = result.current.getCheckpoint().projection;
expect(restored.result.current.messages[0]).toMatchObject({ projectionStartSeq: 1, turnSeq: 3 });
expect(snapshot.projection.closedAssistantIds.size).toBe(0);
expect(snapshot.projection.closedAnswerStreamIds.size).toBe(0);
restored.unmount();
const closed = cache.get("checkpoint")!.projection;
expect(closed.closedAssistantIds.size).toBe(1);
expect(closed.closedAnswerStreamIds.size).toBe(1);
});
it("retains side-channel ownership when restoring an active answer checkpoint", async () => {
it("retains side-channel ownership when restoring an active answer from cache", async () => {
const fake = fakeClient();
const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES), { wrapper: wrap(fake.client) });
const cache = new ThreadMessageCache(() => false);
const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false,
undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) });
act(() => {
fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", text: "Active answer" });
});
await flushStreamFrame();
act(() => { first.result.current.send("/model", undefined, { sideChannel: true }); });
const commandTurn = fake.client.sendMessage.mock.calls.at(-1)![3]?.turnId;
const checkpoint = first.result.current.getCheckpoint();
first.unmount();
const restored = renderHook(() => useNanobotStream("checkpoint", checkpoint.projection.messages, false,
undefined, undefined, [], checkpoint), { wrapper: wrap(fake.client) });
const snapshot = cache.get("checkpoint")!;
expect(snapshot.sideChannelTurnIds.has(commandTurn)).toBe(true);
const restored = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false,
undefined, undefined, [], { key: null, cache }), { wrapper: wrap(fake.client) });
act(() => {
fake.emit("checkpoint", { event: "message", chat_id: "checkpoint", turn_id: commandTurn, text: "Current model" });
fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", text: " continued" });
@@ -298,6 +308,9 @@ describe("useNanobotStream", () => {
});
expect(restored.result.current.messages.filter((message) => message.role === "assistant").map((message) => message.content))
.toEqual(["Active answer continued", "Current model"]);
expect(snapshot.sideChannelTurnIds.has(commandTurn)).toBe(true);
restored.unmount();
expect(cache.get("checkpoint")!.sideChannelTurnIds.has(commandTurn)).toBe(false);
});
it("keeps invocation snapshots across streaming, recovery segments, completion and reload", async () => {
+136 -22
View File
@@ -925,6 +925,44 @@ describe("useSessions", () => {
expect(result.current.hasPendingToolCalls).toBe(false);
});
it("clears the body and paging metadata when no session is selected", async () => {
vi.mocked(api.fetchWebuiThread).mockResolvedValue(canonicalThreadPayload({
schemaVersion: 3,
has_pending_tool_calls: true,
active_turn_id: "selected-turn",
messages: [{ id: "selected-user", role: "user", content: "selected question", turnId: "selected-turn", createdAt: 1 }],
fork_boundary_message_count: 1,
page: {
before_cursor: "selected-cursor", has_more_before: true,
loaded_event_count: 1, user_message_offset: 4,
},
}));
const { result, rerender } = renderHook(({ sessionKey }) => useSessionHistory(sessionKey), {
initialProps: { sessionKey: "websocket:selected" as string | null },
wrapper: wrap(fakeClient()),
});
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.messages[0]?.id).toBe("selected-user");
expect(result.current.hasMoreBefore).toBe(true);
expect(result.current.userMessageOffset).toBe(4);
expect(result.current.hasPendingToolCalls).toBe(true);
expect(result.current.activeTurnId).toBe("selected-turn");
expect(result.current.forkBoundaryMessageCount).toBe(1);
rerender({ sessionKey: null });
expect(result.current.messages).toEqual([]);
expect(result.current.loading).toBe(false);
expect(result.current.hasMoreBefore).toBe(false);
expect(result.current.userMessageOffset).toBe(0);
expect(result.current.hasPendingToolCalls).toBe(false);
expect(result.current.activeTurnId).toBeNull();
expect(result.current.forkBoundaryMessageCount).toBeNull();
act(() => result.current.refresh());
await act(async () => { await result.current.loadOlder(); });
expect(api.fetchWebuiThread).toHaveBeenCalledTimes(1);
});
it("does not reload history when only the auth token rotates", async () => {
const tokenSource = { current: "tok-old" };
vi.mocked(api.fetchWebuiThread).mockResolvedValue(canonicalThreadPayload({
@@ -961,6 +999,45 @@ describe("useSessions", () => {
);
});
it("ignores an old client's pending response after the provider switches clients", async () => {
let oldSignal: AbortSignal | undefined;
let finishOld!: (body: Awaited<ReturnType<typeof api.fetchWebuiThread>>) => void;
const currentBody = canonicalThreadPayload({
schemaVersion: 3,
messages: [{ id: "current-host-answer", role: "assistant", content: "current host", createdAt: 2 }],
});
vi.mocked(api.fetchWebuiThread)
.mockImplementationOnce((_token, _key, optionsOrBase) => new Promise((resolve) => {
if (typeof optionsOrBase !== "string") oldSignal = optionsOrBase?.signal;
finishOld = resolve;
}))
.mockResolvedValueOnce(currentBody);
let client = fakeClient();
const wrapper = ({ children }: { children: ReactNode }) => (
<ClientProvider client={client as unknown as import("@/lib/nanobot-client").NanobotClient} token="tok">
{children}
</ClientProvider>
);
const { result, rerender } = renderHook(() => useSessionHistory("websocket:host-switch"), { wrapper });
await waitFor(() => expect(oldSignal).toBeDefined());
client = fakeClient();
rerender();
expect(oldSignal?.aborted).toBe(true);
await waitFor(() => expect(result.current.messages[0]?.id).toBe("current-host-answer"));
await act(async () => {
finishOld(canonicalThreadPayload({
schemaVersion: 3,
messages: [{ id: "old-host-answer", role: "assistant", content: "old host", createdAt: 1 }],
}));
});
expect(api.fetchWebuiThread).toHaveBeenCalledTimes(2);
expect(result.current.messages.map((message) => message.id)).toEqual(["current-host-answer"]);
expect(result.current.error).toBeNull();
expect(webuiThreadCache.get("websocket:host-switch")).toBe(currentBody);
});
it("aborts a superseded latest-history request without surfacing an error", async () => {
let firstSignal: AbortSignal | undefined;
vi.mocked(api.fetchWebuiThread)
@@ -1039,7 +1116,6 @@ describe("useSessions", () => {
expect(result.current.userMessageOffset).toBe(1);
const latestVersion = result.current.version;
const latestLineage = result.current.lineage;
expect(result.current.continuity).toBe("initial");
await act(async () => {
await result.current.loadOlder();
@@ -1064,7 +1140,6 @@ describe("useSessions", () => {
expect(result.current.userMessageOffset).toBe(0);
expect(result.current.version).toBe(latestVersion);
expect(result.current.lineage).toBe(latestLineage);
expect(result.current.continuity).toBe("initial");
});
it("keeps older-history failures separate and retries them explicitly", async () => {
@@ -1144,11 +1219,52 @@ describe("useSessions", () => {
expect(result.current.error).toBeNull();
rerender({ sessionKey: "websocket:other-history" });
expect(result.current.messages).toEqual([]);
expect(result.current.olderError).toBeNull();
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.messages).toEqual([]);
});
it("releases a superseded older read when the replacement latest read fails", async () => {
const latest = canonicalThreadPayload({
schemaVersion: 3,
messages: [{ id: "current", role: "assistant", content: "current answer", createdAt: 2 }],
page: { before_cursor: "previous-page", has_more_before: true, user_message_offset: 1 },
});
const older = canonicalThreadPayload({
schemaVersion: 3,
messages: [{ id: "previous", role: "assistant", content: "previous answer", createdAt: 1 }],
page: { before_cursor: null, has_more_before: false, user_message_offset: 0 },
});
let olderSignal: AbortSignal | undefined;
vi.mocked(api.fetchWebuiThread)
.mockResolvedValueOnce(latest)
.mockImplementationOnce((_token, _key, options) => new Promise((_resolve, reject) => {
if (typeof options !== "string") olderSignal = options?.signal;
olderSignal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));
}))
.mockRejectedValueOnce(new Error("latest unavailable"))
.mockResolvedValueOnce(older);
const { result } = renderHook(() => useSessionHistory("websocket:superseded-older"), {
wrapper: wrap(fakeClient()),
});
await waitFor(() => expect(result.current.messages[0]?.content).toBe("current answer"));
let pending!: Promise<void>;
act(() => { pending = result.current.loadOlder(); });
expect(result.current.loadingOlder).toBe(true);
act(() => result.current.refresh());
await waitFor(() => expect(result.current.error).toBe("latest unavailable"));
await act(async () => { await pending; });
expect(olderSignal?.aborted).toBe(true);
expect(result.current.loadingOlder).toBe(false);
expect(result.current.hasMoreBefore).toBe(true);
expect(result.current.messages.map((row) => row.content)).toEqual(["current answer"]);
await act(async () => { await result.current.loadOlder(); });
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("tok", "websocket:superseded-older",
expect.objectContaining({ before: "previous-page" }));
expect(result.current.messages.map((row) => row.content)).toEqual(["previous answer", "current answer"]);
});
it("aborts an older-history request when the consumer unmounts", async () => {
let olderSignal: AbortSignal | undefined;
vi.mocked(api.fetchWebuiThread)
@@ -1195,8 +1311,8 @@ describe("useSessions", () => {
schemaVersion: 3,
has_pending_tool_calls: true,
messages: [
{ id: "u2", role: "user", content: "middle question", createdAt: 2 },
{ id: "a2", role: "assistant", content: "middle answer", createdAt: 3 },
{ id: "u2", role: "user", content: "middle question", turnId: "turn-2", turnSeq: 1, createdAt: 2 },
{ id: "a2", role: "assistant", content: "middle answer", turnId: "turn-2", turnSeq: 2, createdAt: 3 },
],
page: {
before_cursor: "cursor-middle",
@@ -1223,7 +1339,7 @@ describe("useSessions", () => {
has_pending_tool_calls: false,
completed_turn_ids: ["turn-3"],
messages: [
{ id: "a2-replayed", role: "assistant", content: "middle answer", createdAt: 3 },
{ id: "a2-replayed", role: "assistant", content: "middle answer", turnId: "turn-2", turnSeq: 2, createdAt: 3 },
{
id: "u3",
role: "user",
@@ -1273,23 +1389,24 @@ describe("useSessions", () => {
expect(result.current.userMessageOffset).toBe(0);
expect(result.current.hasPendingToolCalls).toBe(false);
expect(result.current.completedTurnIds).toEqual(["turn-3"]);
expect(result.current.continuity).toBe("overlap");
expect(result.current.lineage).toBe(loadedLineage);
});
it("starts a new lineage when more than 160 new rows remove all latest-page overlap", async () => {
it("starts a new lineage for a disjoint latest window even when row text repeats", async () => {
const oldWindow = Array.from({ length: 160 }, (_, index) => ({
id: `old-${index}`,
role: index % 2 === 0 ? "user" as const : "assistant" as const,
content: `old window row ${index}`,
content: `window row ${index}`,
turnId: `old-turn-${Math.floor(index / 2)}`,
turnSeq: index % 2 + 1,
createdAt: index,
}));
const newWindow = Array.from({ length: 160 }, (_, index) => ({
id: `new-${index}`,
role: index % 2 === 0 ? "user" as const : "assistant" as const,
content: `new window row ${index}`,
content: `window row ${index}`,
turnId: `new-turn-${Math.floor(index / 2)}`,
turnSeq: index % 2 + 1,
createdAt: 1_000 + index,
}));
vi.mocked(api.fetchWebuiThread)
@@ -1323,23 +1440,22 @@ describe("useSessions", () => {
expect(result.current.messages).toHaveLength(160);
expect(result.current.messages.at(-1)?.id).toBe("new-159");
expect(result.current.continuity).toBe("reset");
expect(result.current.lineage).toBeGreaterThan(initialLineage);
expect(result.current.hasMoreBefore).toBe(true);
});
it("uses the longest consecutive semantic overlap for legacy unstable replay metadata", async () => {
it("preserves repeated prompts by stable turn sources when replay IDs change", async () => {
vi.mocked(api.fetchWebuiThread)
.mockResolvedValueOnce(canonicalThreadPayload({
schemaVersion: 3,
messages: [
{ id: "repeat-1-old", role: "user", content: "repeat", createdAt: 10 },
{ id: "answer-1-old", role: "assistant", content: "first answer", createdAt: 11 },
{ id: "repeat-2-old", role: "user", content: "repeat", createdAt: 12 },
{ id: "answer-2-old", role: "assistant", content: "second answer", createdAt: 13 },
{ id: "repeat-1-old", role: "user", content: "repeat", turnId: "repeat-turn-1", turnSeq: 1, createdAt: 10 },
{ id: "answer-1-old", role: "assistant", content: "first answer", turnId: "repeat-turn-1", turnSeq: 2, createdAt: 11 },
{ id: "repeat-2-old", role: "user", content: "repeat", turnId: "repeat-turn-2", turnSeq: 1, createdAt: 12 },
{ id: "answer-2-old", role: "assistant", content: "second answer", turnId: "repeat-turn-2", turnSeq: 2, createdAt: 13 },
],
page: {
before_cursor: "legacy-cursor",
before_cursor: "source-cursor",
has_more_before: true,
},
}))
@@ -1356,17 +1472,17 @@ describe("useSessions", () => {
.mockResolvedValueOnce(canonicalThreadPayload({
schemaVersion: 3,
messages: [
{ id: "repeat-2-new", role: "user", content: "repeat", createdAt: 9_012 },
{ id: "answer-2-new", role: "assistant", content: "second answer", createdAt: 9_013 },
{ id: "repeat-2-new", role: "user", content: "repeat", turnId: "repeat-turn-2", turnSeq: 1, createdAt: 9_012 },
{ id: "answer-2-new", role: "assistant", content: "second answer", turnId: "repeat-turn-2", turnSeq: 2, createdAt: 9_013 },
{ id: "new-tail", role: "assistant", content: "new tail", createdAt: 9_014 },
],
page: {
before_cursor: "shifted-legacy-cursor",
before_cursor: "shifted-source-cursor",
has_more_before: true,
},
}));
const { result } = renderHook(() => useSessionHistory("websocket:legacy-overlap"), {
const { result } = renderHook(() => useSessionHistory("websocket:source-overlap"), {
wrapper: wrap(fakeClient()),
});
@@ -1387,7 +1503,6 @@ describe("useSessions", () => {
"answer-2-new",
"new-tail",
]);
expect(result.current.continuity).toBe("overlap");
expect(result.current.lineage).toBe(lineage);
});
@@ -1434,7 +1549,6 @@ describe("useSessions", () => {
act(() => result.current.refresh());
await waitFor(() => expect(result.current.messages[0]?.id).toBe("new-latest"));
expect(result.current.continuity).toBe("reset");
expect(result.current.lineage).toBeGreaterThan(oldLineage);
await act(async () => {