fix(webui): keep history loading until content is ready (#6659)

* fix(webui): keep history loading until content is ready

* fix(webui): preserve history content and retry state

Share final activity filtering with history readiness and retain completion and fork metadata across bookkeeping pages. Route boundary retries to the failed cursor and publish navigation pages synchronously so concurrent trace details are preserved. Cover real retry gestures, metadata traversal, batched details, and fork boundaries in both directions.

* fix(webui): reduce history admission work and release retry pages
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-14 22:52:44 +08:00
1 parent 40e4e8a3fd
commit efec4a608d
14 files changed
+751 -103

No files matched your search

@@ -16,6 +16,7 @@ import { useMediaQuery } from "@/hooks/useMediaQuery";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
import { fmtDateTime, formatMessageHoverTime } from "@/lib/format-time";
import { leadingDisplayNoopCount, projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
import { filterThreadDisplayUnits } from "@/lib/thread-display-projection";
import { withoutSubagentCreateActivity } from "@/lib/subagent-create-activity";
import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
@@ -109,11 +110,7 @@ export function ThreadMessages({
const messageListRef = useRef<HTMLDivElement>(null);
const mobileActions = useMediaQuery("(max-width: 767px)");
const rawUnits = useMemo(() => buildDisplayUnits(messages), [messages]);
const units = useMemo(() => rawUnits.map((unit) => unit.type === "activity"
? { ...unit, messages: unit.messages.flatMap((message) => {
const visible = withoutSubagentCreateActivity(message);
return visible ? [visible] : [];
}) } : unit), [rawUnits]);
const units = useMemo(() => filterThreadDisplayUnits(rawUnits), [rawUnits]);
const forkBoundaryAfterUnitIndex = useMemo(() => {
if (forkBoundaryMessageCount != null && forkBoundaryMessageCount > 0
&& forkBoundaryMessageCount <= leadingDisplayNoopCount(messages)) return -1;
@@ -577,9 +577,12 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
- (historySlotRef.current ? HISTORY_HOLD_PX : 0);
const delta = nextOffset - anchor.offsetTop;
if (Math.abs(delta) < 0.5) return true;
const nextTop = Math.min(maxScrollTop, Math.max(0, scroller.scrollTop + delta));
const requestedTop = scroller.scrollTop + delta;
const nextTop = Math.min(maxScrollTop, Math.max(0, requestedTop));
threadMotionRef.current?.jumpTo(nextTop);
anchor.scrollTop = scroller.scrollTop;
// A clamped layout is the new reading position, not space owed by a later prepend.
anchor.offsetTop += requestedTop - nextTop;
return true;
}, [captureHistoryScrollAnchor]);
+23 -10
View File
@@ -7,6 +7,7 @@ import { hasPendingAgentActivity } from "@/lib/activity-timeline";
import { ApiError, fetchWebuiThread, fetchWebuiThreadTraceDetail } from "@/lib/api";
import { fetchLatestWebuiThread } from "@/lib/latest-thread-request";
import { persistedCanonicalRunState } from "@/lib/canonical-run-snapshot";
import { historyContentSnapshot, sameHistoryContent } from "@/lib/thread-display-projection";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { ThreadTranscript, type ThreadPaging, type ThreadRead, type ThreadTranscriptSnapshot } from "@/lib/thread-transcript";
import type { ThreadMessageCache } from "@/lib/thread-message-cache";
@@ -612,19 +613,31 @@ export function useNanobotStream(
olderReadRef.current = operation;
publishHistory();
try {
const body = await fetchWebuiThread(getToken(), historyKey, { before, limit: 120, signal: controller.signal });
if (olderReadRef.current !== operation || transcriptRef.current !== owner) return;
flushPendingStreamEvents();
const accepted = owner.accept(body, read);
setMessages(owner.messages);
setExecSourceMessages(owner.messages);
if (accepted) {
if (chatId) messageCache?.set(chatId, owner.save());
settleFragment(owner);
while (true) {
const body = await fetchWebuiThread(getToken(), historyKey, {
before: operation.read.before!, limit: 120, signal: controller.signal,
});
if (olderReadRef.current !== operation || transcriptRef.current !== owner) return;
flushPendingStreamEvents();
const previousContent = historyContentSnapshot(owner.messages, owner.paging.forkBoundaryMessageCount);
const accepted = owner.accept(body, operation.read);
const needsContent = accepted && owner.paging.hasMoreBefore
&& (owner.hasPendingFragmentGap
|| sameHistoryContent(previousContent, historyContentSnapshot(owner.messages, owner.paging.forkBoundaryMessageCount)));
// Keep one pull pending across bookkeeping pages and staged fragments.
// Begin the continuation before publishing accept()'s intermediate state.
if (needsContent) operation.read = owner.begin("older");
setMessages(owner.messages);
setExecSourceMessages(owner.messages);
if (accepted) {
if (chatId) messageCache?.set(chatId, owner.save());
settleFragment(owner);
}
if (!needsContent) break;
}
} catch (error) {
if (olderReadRef.current === operation && transcriptRef.current === owner) {
owner.finishRead(read, (error as Error).message);
owner.finishRead(operation.read, (error as Error).message);
publishHistory();
}
} finally {
+161 -75
View File
@@ -2,17 +2,33 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import { fetchPromptIndex, fetchWebuiThread } from "@/lib/api";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { historyContentSnapshot, projectWebuiThreadMessages, sameHistoryContent } from "@/lib/thread-display-projection";
import { joinThreadFragments } from "@/lib/thread-page-fragments";
import { isModelCommandText } from "@/lib/format";
import { isSystemCommandTurnId } from "@/lib/nanobot-client";
import type { PromptIndex, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
import type { PromptIndex, ThreadProjectionEvent, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
import { type PromptAnchor, userPromptAnchors } from "@/components/thread/promptNavigation";
interface HistoryPage {
messages: UIMessage[];
body: WebuiThreadPersistedPayload;
details: Map<string, UIMessage[]>;
/** One terminal record per raw turn, retained when its page leaves the bounded cache. */
completion?: Extract<ThreadProjectionEvent, { event: "turn_end" }>;
/** A crossed marker can precede all visible rows until an older page arrives. */
forkBoundaryBefore?: boolean;
}
function projectionBody(page: HistoryPage): WebuiThreadPersistedPayload {
return page.forkBoundaryBefore ? { ...page.body, fork_boundary_event_index: 0 } : page.body;
}
function retainFragmentCompletion(pages: HistoryPage[], page: HistoryPage): HistoryPage[] {
const turn = page.body.page?.record_range?.turn;
if (turn === undefined || !page.completion
|| !pages.some((saved) => saved.body.page?.record_range?.turn === turn && saved.completion !== page.completion)) return pages;
return pages.map((saved) => saved.body.page?.record_range?.turn === turn && saved.completion !== page.completion
? { ...saved, completion: page.completion } : saved);
}
function expandDetails(messages: UIMessage[], details: ReadonlyMap<string, UIMessage[]>): UIMessage[] {
@@ -47,6 +63,49 @@ export interface PromptHistoryNavigation {
expandTraceDetail: (ref: string, rows: UIMessage[]) => void;
}
// Pages and detail maps are replaced, never mutated. Cache by the immutable raw window,
// so admission and the rendered window share one projection without retaining evicted pages.
const projectedWindows = new WeakMap<HistoryPage[], NonNullable<PromptHistoryNavigation["window"]>>();
function projectHistoryWindow(pages: HistoryPage[]): NonNullable<PromptHistoryNavigation["window"]> {
const cached = projectedWindows.get(pages);
if (cached) return cached;
const messages: UIMessage[] = [];
let boundary: number | null = null;
for (let index = 0; index < pages.length; index++) {
const page = pages[index];
let body = projectionBody(page);
let rows = page.messages;
const range = body.page?.record_range;
if (range) {
let joined = joinThreadFragments([], body);
const details = new Map(page.details);
let completion = page.completion;
while (pages[index + 1]?.body.page?.record_range?.turn === range.turn) {
const next = pages[++index];
joined = joinThreadFragments(joined.pages, projectionBody(next));
completion = next.completion ?? completion;
for (const [ref, detail] of next.details) details.set(ref, detail);
}
body = joined.body;
// Completion is data, not a content-ready signal. Replay it through the same
// reducer even when intervening telemetry or the terminal page was evicted.
const events = completion && !body.events.some((event) => event.event === "turn_end")
? [...body.events, completion] : body.events;
rows = expandDetails(projectWebuiThreadMessages(projectThreadEvents(events)), details);
}
const eventIndex = body.fork_boundary_event_index;
if (eventIndex !== undefined) boundary = messages.length + projectWebuiThreadMessages(projectThreadEvents(body.events.slice(0, eventIndex))).length;
messages.push(...rows);
}
const window = { messages, userMessageOffset: pages[0]?.body.page?.user_message_offset ?? 0,
hasMoreBefore: pages[0]?.body.page?.has_more_before === true,
hasMoreAfter: pages.at(-1)?.body.page?.has_more_after === true,
forkBoundaryMessageCount: boundary };
projectedWindows.set(pages, window);
return window;
}
/** Browsing pages never replace the canonical latest page or live turn state. */
export function usePromptHistory(key: string | null, version: number, messages: UIMessage[]): PromptHistoryNavigation {
const { client, getToken, webuiCapabilities } = useClient();
@@ -55,7 +114,11 @@ export function usePromptHistory(key: string | null, version: number, messages:
const indexSnapshot = useRef<PromptIndex>();
const [pages, setPages] = useState<HistoryPage[]>([]);
const pagesRef = useRef(pages);
pagesRef.current = pages;
const publishPages = useCallback((next: HistoryPage[]) => {
// Reads and detail expansion share the latest window even within one React batch.
pagesRef.current = next;
setPages(next);
}, []);
const [target, setTarget] = useState<PromptHistoryNavigation["target"]>(null);
const [operation, setOperation] = useState<PromptHistoryNavigation["operation"]>(null);
const [loading, setLoading] = useState(false);
@@ -64,14 +127,14 @@ export function usePromptHistory(key: string | null, version: number, messages:
const [refresh, setRefresh] = useState(0);
const request = useRef<AbortController | null>(null);
const sequence = useRef(0);
const retry = useRef<() => void>(() => setRefresh((value) => value + 1));
const emptyScan = useRef<{ direction: "before" | "after"; reversed: boolean }>({ direction: "after", reversed: false });
const retry = useRef<(() => void) | null>(null);
const scope = useRef({ key, client });
const currentScope = scope.current.key === key && scope.current.client === client;
const cancel = useCallback(() => {
request.current?.abort();
request.current = null;
retry.current = null;
setTarget(null);
setLoading(false);
setError(null);
@@ -79,8 +142,8 @@ export function usePromptHistory(key: string | null, version: number, messages:
const latest = useCallback(() => {
cancel();
setPages([]);
}, [cancel]);
publishPages([]);
}, [cancel, publishPages]);
useEffect(() => {
scope.current = { key, client };
@@ -149,107 +212,130 @@ export function usePromptHistory(key: string | null, version: number, messages:
}, [currentScope, enabled, index, indexed, key, messages]);
const expandTraceDetail = useCallback((ref: string, rows: UIMessage[]) => {
setPages((current) => current.map((page) => {
publishPages(pagesRef.current.map((page) => {
if (!page.messages.some((message) => message.traceDetail?.ref === ref)) return page;
const details = new Map(page.details).set(ref, rows);
return { ...page, messages: expandDetails(page.messages, details), details };
}));
}, []);
}, [publishPages]);
const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string, automatic = false) => {
const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string, resume?: HistoryPage[]) => {
// Boundary inputs can arrive before loading renders; only a new jump supersedes a read.
if (!key || (!id && request.current)) return;
if (!automatic) emptyScan.current = { direction, reversed: false };
request.current?.abort();
const controller = new AbortController();
request.current = controller;
setOperation(id ? "jump" : direction === "before" ? "older" : "newer");
setLoading(true);
setError(null);
retry.current = () => { void read(cursor, direction, id); };
retry.current = null;
let staged = resume ?? pagesRef.current;
let retryRead: (() => void) | null = null;
try {
const body = await fetchWebuiThread(getToken(), key, {
[direction]: cursor, limit: 24, signal: controller.signal,
});
if (controller.signal.aborted) return;
if (!body) throw new Error("History is no longer available");
const generation = body.page?.history_generation;
const previousGeneration = pagesRef.current[0]?.body.page?.history_generation;
if (!id && generation && previousGeneration && generation !== previousGeneration) {
throw new Error("History changed; select the message again");
while (true) {
const requestedCursor = cursor;
const retryPages = staged;
retryRead = () => { void read(requestedCursor, direction, id, retryPages); };
const body = await fetchWebuiThread(getToken(), key, {
[direction]: cursor, limit: 24, signal: controller.signal,
});
if (controller.signal.aborted) return;
if (!body) throw new Error("History is no longer available");
const generation = body.page?.history_generation;
const previousGeneration = staged[0]?.body.page?.history_generation;
if (!id && generation && previousGeneration && generation !== previousGeneration) {
throw new Error("History changed; select the message again");
}
const turn = body.page?.record_range?.turn;
const page: HistoryPage = { body, messages: projectWebuiThreadMessages(projectThreadEvents(body.events)), details: new Map(),
completion: body.events.find((event) => event.event === "turn_end")
?? (!id && turn !== undefined ? staged.find((saved) => saved.body.page?.record_range?.turn === turn)?.completion : undefined) };
if (id && !page.messages.some((message) => message.id === id)) {
setRefresh((value) => value + 1);
throw new Error("History changed; select the message again");
}
// Trace details can finish while this read is pending; preserve those visible updates.
const updated = staged.map((saved) => pagesRef.current.find((current) => current.body === saved.body) ?? saved);
if (updated.some((saved, index) => saved !== staged[index])) staged = updated;
if (!id && page.completion) {
staged = retainFragmentCompletion(staged, page);
const retained = retainFragmentCompletion(pagesRef.current, page);
if (retained.some((saved, index) => saved !== pagesRef.current[index])) {
publishPages(retained);
}
}
// Only fragments need the staged raw context. Self-contained pages extend
// the readable window, not the bookkeeping pages traversed on the way here.
const source = body.page?.record_range ? staged : pagesRef.current;
const expanded = id ? [page] : direction === "before" ? [page, ...source] : [...source, page];
// Compare before eviction: a full window can gain content without growing.
const previous = projectHistoryWindow(source);
const prepared = projectHistoryWindow(expanded);
const ready = id || !sameHistoryContent(
historyContentSnapshot(previous.messages, previous.forkBoundaryMessageCount),
historyContentSnapshot(prepared.messages, prepared.forkBoundaryMessageCount),
);
const nextCursor = direction === "before" ? body.page?.before_cursor : body.page?.after_cursor;
const more = direction === "before" ? body.page?.has_more_before : body.page?.has_more_after;
if (!id && more && (!nextCursor || nextCursor === cursor)) throw new Error("History cursor did not advance");
if (!ready && direction === "before" && body.fork_boundary_event_index !== undefined) {
// Admit the crossed boundary without ending a pull that still has no
// visible content before it. It must survive discarded staging pages.
publishPages(pagesRef.current.map((saved, index) => index === 0 ? { ...saved, forkBoundaryBefore: true } : saved));
}
// At most three bounded server pages; intermediate pages do not complete the operation.
staged = expanded.length <= HISTORY_PAGE_LIMIT ? expanded
: direction === "before" ? expanded.slice(0, HISTORY_PAGE_LIMIT) : expanded.slice(-HISTORY_PAGE_LIMIT);
if (ready || !more) {
// Reaching the end through bookkeeping must not evict the readable window.
if (!ready) staged = pagesRef.current.map((saved, index, current) => {
if (index !== (direction === "before" ? 0 : current.length - 1)) return saved;
const boundary = direction === "before"
? { before_cursor: nextCursor ?? null, has_more_before: false }
: { after_cursor: nextCursor ?? null, has_more_after: false };
return { ...saved, body: { ...saved.body, page: { ...saved.body.page, ...boundary } } };
});
publishPages(staged);
if (id) setTarget({ id, sequence: ++sequence.current });
break;
}
cursor = nextCursor!;
}
const page = { body, messages: projectWebuiThreadMessages(projectThreadEvents(body.events)), details: new Map<string, UIMessage[]>() };
if (id && !page.messages.some((message) => message.id === id)) {
setRefresh((value) => value + 1);
throw new Error("History changed; select the message again");
}
// At most three bounded server pages, even after many navigations.
setPages((previous) => id ? [page] : direction === "before"
? [page, ...previous].slice(0, HISTORY_PAGE_LIMIT) : [...previous, page].slice(-HISTORY_PAGE_LIMIT));
if (id) setTarget({ id, sequence: ++sequence.current });
} catch (cause) {
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : String(cause));
if (!controller.signal.aborted) {
retry.current = retryRead;
setError(cause instanceof Error ? cause.message : String(cause));
}
} finally {
if (request.current === controller) {
request.current = null;
setLoading(false);
}
}
}, [getToken, key]);
}, [getToken, key, publishPages]);
const first = pages[0]?.body.page;
const last = pages[pages.length - 1]?.body.page;
const window = useMemo(() => {
if (!currentScope || !pages.length) return null;
const messages: UIMessage[] = [];
let boundary: number | null = null;
for (let index = 0; index < pages.length; index++) {
const page = pages[index];
let body = page.body;
let rows = page.messages;
const range = body.page?.record_range;
if (range) {
let joined = joinThreadFragments([], body);
const details = new Map(page.details);
while (pages[index + 1]?.body.page?.record_range?.turn === range.turn) {
const next = pages[++index];
joined = joinThreadFragments(joined.pages, next.body);
for (const [ref, detail] of next.details) details.set(ref, detail);
}
body = joined.body;
rows = expandDetails(projectWebuiThreadMessages(projectThreadEvents(body.events)), details);
}
const eventIndex = body.fork_boundary_event_index;
if (eventIndex !== undefined) boundary = messages.length + projectWebuiThreadMessages(projectThreadEvents(body.events.slice(0, eventIndex))).length;
messages.push(...rows);
const window = useMemo(() => currentScope && pages.length ? projectHistoryWindow(pages) : null,
[currentScope, pages]);
const readBoundary = (direction: "before" | "after") => {
if (error && operation === (direction === "before" ? "older" : "newer")) {
retry.current?.();
return;
}
return { messages,
userMessageOffset: first?.user_message_offset ?? 0,
hasMoreBefore: first?.has_more_before === true, hasMoreAfter: last?.has_more_after === true,
forkBoundaryMessageCount: boundary };
}, [currentScope, pages, first, last]);
useEffect(() => {
if (!window || window.messages.length || loading || error) return;
let direction = emptyScan.current.direction;
let cursor = direction === "after" ? last?.after_cursor : first?.before_cursor;
if (!cursor && !emptyScan.current.reversed) {
direction = direction === "after" ? "before" : "after";
emptyScan.current = { direction, reversed: true };
cursor = direction === "after" ? last?.after_cursor : first?.before_cursor;
}
if (cursor) void read(cursor, direction, undefined, true);
}, [error, first?.before_cursor, last?.after_cursor, loading, read, window]);
const cursor = direction === "before" ? first?.before_cursor : last?.after_cursor;
if (cursor) void read(cursor, direction);
};
return { prompts, window, target: currentScope ? target : null, loading: currentScope && loading,
operation: currentScope && (loading || error) ? operation : null,
error: currentScope ? error ?? indexError : null, cancel, latest, expandTraceDetail,
retry: () => error ? retry.current() : setRefresh((value) => value + 1),
retry: () => error ? retry.current?.() : setRefresh((value) => value + 1),
jump: (id) => {
const prompt = prompts.find((item) => item.id === id);
if (enabled && prompt?.cursor) void read(prompt.cursor, "after", id);
},
older: () => { if (first?.before_cursor) void read(first.before_cursor, "before"); },
newer: () => { if (last?.after_cursor) void read(last.after_cursor, "after"); },
older: () => readBoundary("before"),
newer: () => readBoundary("after"),
};
}
@@ -1,4 +1,6 @@
import { isModelCommandResponseText, isModelCommandText } from "@/lib/format";
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
import { withoutSubagentCreateActivity } from "@/lib/subagent-create-activity";
import { isSystemCommandTurnId } from "@/lib/nanobot-client";
import { scrubSubagentUiMessages } from "@/lib/subagent-channel-display";
import type { UIMessage } from "@/lib/types";
@@ -74,3 +76,48 @@ export function projectWebuiThreadMessages(messages: UIMessage[]): UIMessage[] {
}
return visible;
}
/** Keep empty activity units as source anchors, but remove their redundant task content. */
export function filterThreadDisplayUnits(units: TurnUnit[]): TurnUnit[] {
return units.map((unit) => unit.type === "activity"
? { ...unit, messages: unit.messages.flatMap((message) => {
const visible = withoutSubagentCreateActivity(message);
return visible ? [visible] : [];
}) } : unit);
}
/** Compare history admission, not replay identities, completion times or usage telemetry. */
export function historyContentSnapshot(messages: UIMessage[], forkBoundaryMessageCount: number | null) {
return { forkBoundary: forkBoundaryMessageCount !== null && forkBoundaryMessageCount > 0,
messages: filterThreadDisplayUnits(projectActivityTimeline(projectWebuiThreadMessages(messages)))
.flatMap((unit) => unit.type === "message" ? [unit.message] : unit.messages)
.map(({ role, kind, renderAs, activityKind, content, reasoning, images, media, traces,
toolEvents, fileEdits, traceDetail, compaction, compactReply, cliApps, mcpPresets, sessionMentions, sessionMessage }) =>
({ role, kind, renderAs, activityKind, content, reasoning, images, media, traces,
toolEvents, fileEdits, traceDetail, compaction, compactReply, cliApps, mcpPresets, sessionMentions, sessionMessage })) };
}
// Display payloads are JSON values. Shared tool results and media need no byte-by-byte serialization.
function sameContentValue(left: unknown, right: unknown): boolean {
if (left === right) return true;
if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;
if (Array.isArray(left)) {
return Array.isArray(right) && left.length === right.length
&& left.every((value, index) => sameContentValue(value, right[index]));
}
if (Array.isArray(right)) return false;
const previous = left as Record<string, unknown>;
const next = right as Record<string, unknown>;
const keys = Object.keys(previous).filter((key) => previous[key] !== undefined);
return keys.length === Object.keys(next).filter((key) => next[key] !== undefined).length
&& keys.every((key) => Object.hasOwn(next, key) && sameContentValue(previous[key], next[key]));
}
export function sameHistoryContent(
previous: ReturnType<typeof historyContentSnapshot>,
next: ReturnType<typeof historyContentSnapshot>,
): boolean {
return previous.forkBoundary === next.forkBoundary
&& previous.messages.length === next.messages.length
&& previous.messages.every((message, index) => sameContentValue(message, next.messages[index]));
}
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { deriveTitle, isModelCommandText, visibleSessionPreview } from "@/lib/format";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { historyContentSnapshot, projectWebuiThreadMessages, sameHistoryContent } from "@/lib/thread-display-projection";
import type { UIMessage } from "@/lib/types";
const STARTED_AT = Date.UTC(2026, 6, 25, 12, 34, 0);
@@ -147,3 +147,66 @@ describe("projectWebuiThreadMessages", () => {
expect(visible[1]?.completedAt).toBeUndefined();
});
});
describe("history content admission", () => {
it("compares displayed answers independently of replay identities and completion telemetry", () => {
const before = historyContentSnapshot([message("assistant", { content: "First\n\nSecond" })], null);
const after = historyContentSnapshot([
message("assistant", { id: "slice-1", content: "First", turnId: "turn-1", turnSeq: 1 }),
message("assistant", { id: "slice-2", content: "Second", turnId: "turn-1", turnSeq: 2,
completedAt: STARTED_AT + 1000, latencyMs: 1000, usage: { total_tokens: 42 } }),
], null);
expect(sameHistoryContent(before, after)).toBe(true);
expect(sameHistoryContent(after, historyContentSnapshot([
message("assistant", { content: "First\n\nSecond\n\nThird" }),
], null))).toBe(false);
});
it("ignores hidden task creation and transport placeholders", () => {
const prompt = message("user");
const before = historyContentSnapshot([prompt], null);
const after = historyContentSnapshot([prompt,
message("assistant", { content: 'subagent({"action":"create"})', kind: "trace",
toolEvents: [{ name: "subagent", phase: "end", arguments: { action: "create" } }] }),
message("assistant", { content: "", completedAt: STARTED_AT + 1000 }),
], null);
expect(sameHistoryContent(before, after)).toBe(true);
});
it("recognizes a visible fork boundary without treating a leading marker as content", () => {
const rows = [message("user"), message("assistant")];
const before = historyContentSnapshot(rows, null);
expect(sameHistoryContent(before, historyContentSnapshot(rows, 0))).toBe(true);
expect(sameHistoryContent(before, historyContentSnapshot(rows, 1))).toBe(false);
});
it("compares nested tool payloads by content, including results and attachments", () => {
const tool = { name: "read_file", phase: "end", arguments: { path: "test.txt" },
result: { lines: ["first", "second"], truncated: false } };
const trace = message("assistant", { content: "read_file(test.txt)", kind: "trace", toolEvents: [tool] });
const before = historyContentSnapshot([trace], null);
const replay = { ...trace, id: "replayed", toolEvents: [{ ...tool,
arguments: { path: "test.txt" }, result: { truncated: false, lines: ["first", "second"] } }] };
expect(sameHistoryContent(before, historyContentSnapshot([replay], null))).toBe(true);
for (const changed of [
{ ...tool, result: { lines: ["first", "changed"], truncated: false } },
{ ...tool, result: { lines: ["first"], truncated: false } },
{ ...tool, result: null, error: "Not found" },
{ ...tool, files: [{ name: "test.txt", url: "/files/test.txt" }] },
]) {
expect(sameHistoryContent(before, historyContentSnapshot([{ ...trace, toolEvents: [changed] }], null))).toBe(false);
}
});
it("detects newly available media without relying on new message identities", () => {
const original = message("user", { images: [{ name: "picture.png" }] });
const before = historyContentSnapshot([original], null);
expect(sameHistoryContent(before, historyContentSnapshot([
{ ...original, images: [{ name: "picture.png", url: undefined }] },
], null))).toBe(true);
expect(sameHistoryContent(before, historyContentSnapshot([
{ ...original, images: [{ name: "picture.png", url: "/files/picture.png" }] },
], null))).toBe(false);
});
});
+219 -2
View File
@@ -7,6 +7,7 @@ import { NanobotClient } from "@/lib/nanobot-client";
import { ClientProvider } from "@/providers/ClientProvider";
import type { UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
@@ -105,12 +106,228 @@ it("continues through telemetry-only fragments until another message is visible"
await waitFor(() => expect(result.current.prompts[0]?.id).toBe("u10"));
await act(async () => result.current.jump("u10"));
await act(async () => result.current.newer());
await act(async () => result.current.newer());
await act(async () => result.current.newer());
await waitFor(() => expect(result.current.window?.messages.map((row) => row.content)).toContain("Visible answer"));
expect(api.fetchWebuiThread).toHaveBeenCalledTimes(5);
});
it("keeps loading through task-create fragments hidden by the message list", async () => {
const initial = page(10);
initial.events = [{ event: "user_message", chat_id: "a", projection_id: "u10", turn_id: "long",
turn_seq: 1, text: "question", starts_turn: true }];
initial.page = { ...initial.page, record_range: { turn: 0, start: 0, end: 1 } };
const hidden: WebuiThreadPersistedPayload = { ...page(11), events: [
{ event: "message", chat_id: "a", projection_id: "create", turn_id: "long", turn_seq: 2,
kind: "progress", text: 'subagent({"action":"create"})',
tool_events: [{ call_id: "create", name: "subagent", phase: "end", arguments: { action: "create" } }] },
], page: { ...page(11).page, record_range: { turn: 0, start: 1, end: 2 } } };
let finish!: (body: WebuiThreadPersistedPayload) => void;
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial).mockResolvedValueOnce(hidden)
.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
const list = render(<ThreadMessages messages={result.current.window!.messages} />);
const text = list.container.textContent;
await act(async () => result.current.newer());
list.rerender(<ThreadMessages messages={result.current.window!.messages} />);
expect(list.container.textContent).toBe(text);
expect(result.current.loading).toBe(true);
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ after: "12" }));
await act(async () => finish({ ...page(12), events: [
{ event: "message", chat_id: "a", projection_id: "answer", turn_id: "long", turn_seq: 3, text: "Visible answer" },
], page: { has_more_after: false, record_range: { turn: 0, start: 2, end: 3 } } }));
list.rerender(<ThreadMessages messages={result.current.window!.messages} />);
expect(list.getByText("Visible answer")).toBeVisible();
expect(result.current.loading).toBe(false);
});
it.each([[0, "exhausted"], [4, "exhausted"], [4, "error"]] as const)("retains completion metadata after %s bookkeeping fragments end in %s", async (count, outcome) => {
const initial = page(10);
initial.events = [
{ event: "user_message", chat_id: "a", projection_id: "u10", turn_id: "long", turn_seq: 1, text: "question", starts_turn: true },
{ event: "message", chat_id: "a", projection_id: "a10", turn_id: "long", turn_seq: 2, text: "answer" },
];
initial.page = { ...initial.page, record_range: { turn: 0, start: 0, end: 2 } };
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial);
for (let part = 0; part < count; part++) {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(11 + part), events: [
{ event: "model_request", chat_id: "a", request_id: `r${part}`, run_id: "run", sequence: part,
phase: "completed", turn_id: "long", turn_seq: part + 3 },
], page: { ...page(11 + part).page, record_range: { turn: 0, start: part + 2, end: part + 3 } } });
}
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(11 + count), events: [
{ event: "turn_end", chat_id: "a", projection_id: "end", turn_id: "long", turn_seq: count + 3,
latency_ms: 1234, usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } },
], page: { has_more_after: outcome === "error", after_cursor: outcome === "error" ? "continue" : null,
record_range: { turn: 0, start: count + 2, end: count + 3 } } });
if (outcome === "error") vi.mocked(api.fetchWebuiThread).mockRejectedValueOnce(new Error("offline"));
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
await act(async () => result.current.newer());
expect(result.current.loading).toBe(false);
expect(result.current.window?.hasMoreAfter).toBe(outcome === "error");
expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question", "answer"]);
expect(result.current.window?.messages.find((message) => message.id === "a10")).toMatchObject({
latencyMs: 1234, completedAt: 1234, usage: { total_tokens: 15 },
});
if (outcome === "error") {
expect(result.current.error).toBe("offline");
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(page(20));
await act(async () => result.current.newer());
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ after: "continue" }));
expect(result.current.window?.messages.map((message) => message.content)).toContain("question 20");
}
});
it.each([0, 4])("admits a fork-marker-only page after %s bookkeeping fragments without losing the readable window", async (count) => {
const initial = page(10);
initial.events = [
{ event: "user_message", chat_id: "a", projection_id: "u10", turn_id: "forked", text: "Forked prompt", starts_turn: true },
...Array.from({ length: 24 }, (_, i) => ({ event: "message" as const, chat_id: "a", projection_id: `a${i}`,
turn_id: "forked", text: `answer ${i}` })),
];
const completion = { event: "turn_end" as const, chat_id: "a", turn_id: "forked", latency_ms: 1234 };
if (count) initial.page = { ...initial.page, record_range: { turn: 0, start: 0, end: 25 } };
else {
initial.events.push(completion);
initial.page = { ...initial.page, after_cursor: "fork" };
}
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial);
for (let part = 0; part < count; part++) {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(11 + part), events: [
{ event: "model_request", chat_id: "a", turn_id: "forked", request_id: `r${part}`, run_id: "run",
sequence: part, phase: "completed" },
], page: { ...page(11 + part).page, record_range: { turn: 0, start: 25 + part, end: 26 + part } } });
}
if (count) vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(15), events: [completion],
page: { ...page(15).page, after_cursor: "fork", record_range: { turn: 0, start: 29, end: 30 } } });
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(16), events: [], fork_boundary_event_index: 0,
page: { before_cursor: "fork", has_more_before: true, after_cursor: null, has_more_after: false } });
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
await act(async () => result.current.newer());
expect(result.current.loading).toBe(false);
expect(result.current.window?.hasMoreAfter).toBe(false);
expect(result.current.window?.messages).toHaveLength(25);
expect(result.current.window?.forkBoundaryMessageCount).toBe(25);
const list = render(<ThreadMessages messages={result.current.window!.messages}
forkBoundaryMessageCount={result.current.window!.forkBoundaryMessageCount} />);
expect(list.getByText("Forked from history")).toBeVisible();
});
it("keeps a crossed fork boundary while reading from the first child prompt into its parent history", async () => {
const child = page(10);
child.page = { ...child.page, record_range: { turn: 1, start: 1, end: 4 } };
child.events.push({ event: "turn_end", chat_id: "a" });
const marker: WebuiThreadPersistedPayload = { ...page(9), events: [], fork_boundary_event_index: 0,
page: { ...page(9).page, record_range: { turn: 1, start: 0, end: 1 } } };
let finish!: (body: WebuiThreadPersistedPayload) => void;
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(child).mockResolvedValueOnce(marker)
.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
await act(async () => result.current.older());
expect(result.current.loading).toBe(true);
expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question 10", "answer"]);
await act(async () => finish(page(8)));
expect(result.current.loading).toBe(false);
expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question 8", "answer", "question 10", "answer"]);
expect(result.current.window?.forkBoundaryMessageCount).toBe(2);
const list = render(<ThreadMessages messages={result.current.window!.messages}
forkBoundaryMessageCount={result.current.window!.forkBoundaryMessageCount} />);
expect(list.getByText("Forked from history")).toBeVisible();
});
it("retains a terminal record until its answer arrives while scanning backward", async () => {
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u20"));
for (let part = 6; part >= 2; part--) {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(10 + part), events: part === 6
? [{ event: "turn_end", chat_id: "a", turn_id: "long", latency_ms: 1234, usage: { total_tokens: 15 } }]
: [{ event: "model_request", chat_id: "a", turn_id: "long", request_id: `r${part}`, run_id: "run",
sequence: part, phase: "completed" }],
page: { ...page(10 + part).page, record_range: { turn: 0, start: part, end: part + 1 } } });
}
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(10), events: [
{ event: "user_message", chat_id: "a", projection_id: "u10", turn_id: "long", text: "question", starts_turn: true },
{ event: "message", chat_id: "a", projection_id: "a10", turn_id: "long", text: "answer" },
], page: { ...page(10).page, record_range: { turn: 0, start: 0, end: 2 } } });
await act(async () => result.current.older());
expect(api.fetchWebuiThread).toHaveBeenCalledTimes(7);
expect(result.current.loading).toBe(false);
expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question", "answer"]);
expect(result.current.window?.messages.find((message) => message.id === "a10")).toMatchObject({
latencyMs: 1234, completedAt: 1234, usage: { total_tokens: 15 },
});
});
it.each([false, true])("preserves trace details arriving during a multi-page read (fragment=%s)", async (fragment) => {
const ref = "1.history-aaaaaaaaaaaaaaaaaaaa";
const initial = page(10);
initial.events.splice(1, 0, { event: "message", chat_id: "a", projection_id: "trace", kind: "progress",
text: "exec(…)", trace_detail: { ref, bytes: 40_000, traceCount: 1 } });
const bookkeeping: WebuiThreadPersistedPayload = { ...page(11), events: [{ event: "model_request", chat_id: "a",
request_id: "r1", run_id: "run", sequence: 1, phase: "started" }] };
const ready: WebuiThreadPersistedPayload = { ...page(12), events: [
{ event: "message", chat_id: "a", projection_id: "continuation", text: "continued answer" },
] };
if (fragment) {
initial.page = { ...initial.page, record_range: { turn: 0, start: 0, end: 3 } };
bookkeeping.page = { ...bookkeeping.page, record_range: { turn: 0, start: 3, end: 4 } };
ready.page = { ...ready.page, record_range: { turn: 0, start: 4, end: 5 } };
}
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial);
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
let finishBookkeeping!: (body: WebuiThreadPersistedPayload) => void;
let finishContent!: (body: WebuiThreadPersistedPayload) => void;
vi.mocked(api.fetchWebuiThread)
.mockImplementationOnce(() => new Promise((resolve) => { finishBookkeeping = resolve; }))
.mockImplementationOnce(() => new Promise((resolve) => { finishContent = resolve; }));
act(() => result.current.newer());
const details = projectThreadEvents([{ event: "message", chat_id: "a", projection_id: "trace", kind: "progress",
text: 'exec({"command":"echo historical"})' }]);
await act(async () => finishBookkeeping(bookkeeping));
expect(result.current.loading).toBe(true);
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ after: "12" }));
// Both HTTP completions can land in one React batch.
await act(async () => {
result.current.expandTraceDetail(ref, details);
finishContent(ready);
});
expect(result.current.loading).toBe(false);
const contents = result.current.window!.messages.map((message) => message.content);
expect(contents).toContain("continued answer");
expect(contents).toContain('exec({"command":"echo historical"})');
});
it.each(["exhausted", "error"] as const)("preserves readable navigation after several bookkeeping pages end in %s", async (outcome) => {
const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() });
await waitFor(() => expect(result.current.prompts).toHaveLength(2000));
await act(async () => result.current.jump("u10"));
const original = result.current.window!.messages;
for (let cursor = 9; cursor >= 6; cursor--) {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(cursor), events: [] });
}
if (outcome === "error") vi.mocked(api.fetchWebuiThread).mockRejectedValueOnce(new Error("offline"));
else vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(0), events: [] });
await act(async () => result.current.older());
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.window!.messages).toEqual(original);
if (outcome === "error") {
expect(result.current.error).toBe("offline");
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(page(5));
await act(async () => result.current.retry());
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ before: "6" }));
expect(result.current.window!.messages.map((row) => row.content)).toContain("question 5");
} else expect(result.current.window?.hasMoreBefore).toBe(false);
});
it("does not mix navigation pages from a replaced session", async () => {
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(10),
page: { ...page(10).page, history_generation: "old" } });
+11 -3
View File
@@ -343,11 +343,14 @@ describe("durable run recovery", () => {
const initial = page(1, 3, [chunk(2, "B"), chunk(3, "C")]);
const latest = page(6, 9, [chunk(8, "H"), chunk(9, "I"),
{ event: "turn_end", chat_id: chatId, turn_id: turnId, turn_seq: 10, projection_id: "history-end" }], true);
const missing = page(3, 6, [chunk(5, "E"), chunk(6, "F"), chunk(7, "G")]);
const middle = page(5, 6, [chunk(7, "G")]);
const missing = page(3, 5, [chunk(5, "E"), chunk(6, "F")]);
let finishLatest!: (value: Response) => void;
let finishMiddle!: (value: Response) => void;
let finishMissing!: (value: Response) => void;
let latestReads = 0;
vi.stubGlobal("fetch", vi.fn((url: string) => {
if (url.includes("before=before-6")) return new Promise<Response>((resolve) => { finishMiddle = resolve; });
if (url.includes("before=")) return new Promise<Response>((resolve) => { finishMissing = resolve; });
const read = latestReads++;
if (read === 0) return Promise.resolve(response(initial));
@@ -382,7 +385,7 @@ describe("durable run recovery", () => {
expect(webuiThreadCache.get(`websocket:${chatId}`)).toEqual(latest);
expect(mounted.result.current.history.error).toBeNull();
expect(mounted.result.current.history.loadingOlder).toBe(true);
expect(finishMissing).toBeTypeOf("function");
expect(finishMiddle).toBeTypeOf("function");
expect(reconcile).not.toHaveBeenCalled();
expect(fence).not.toHaveBeenCalled();
expect(client.getRunState(chatId).active).toBe(true);
@@ -391,8 +394,13 @@ describe("durable run recovery", () => {
turn_seq: 5, stream_id: "wire", text: "E" }));
await act(async () => { await vi.advanceTimersByTimeAsync(100); });
expect(mounted.result.current.messages.at(-1)?.content).toBe("BCDE");
await act(async () => { finishMiddle(response(middle)); });
expect(mounted.result.current.history.loadingOlder).toBe(true);
expect(mounted.result.current.messages.map((row) => row.content)).toEqual(["BCDE"]);
expect(finishMissing).toBeTypeOf("function");
await act(async () => { finishMissing(response(missing)); });
expect(mounted.result.current.messages.at(-1)?.content).toBe("BCDEFGHI");
expect(mounted.result.current.messages.map((row) => row.content)).toEqual(["BCDEFGHI"]);
expect(mounted.result.current.history.loadingOlder).toBe(false);
expect(client.getRunState(chatId).active).toBe(false);
expect(mounted.result.current.isStreaming).toBe(false);
const late = { event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 11,
+44
View File
@@ -8,6 +8,7 @@ import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
import { ClientProvider } from "@/providers/ClientProvider";
import { canonicalThreadPayload } from "./thread-test-payload";
import type { WebuiThreadPersistedPayload } from "@/lib/types";
vi.mock("@/lib/api", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/api")>();
@@ -1168,6 +1169,49 @@ describe("useSessions", () => {
expect(result.current.hasMoreBefore).toBe(false);
});
it("keeps one pull pending through telemetry pages and retries from its failed continuation", async () => {
const initial: WebuiThreadPersistedPayload = {
schemaVersion: 3, projection: "events",
events: [{ event: "message", chat_id: "ready", projection_id: "answer", turn_id: "turn", turn_seq: 1, text: "Visible answer" }],
page: { before_cursor: "telemetry", has_more_before: true },
};
let fail!: (error: Error) => void;
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(initial).mockResolvedValueOnce({
...initial, events: [
{ event: "model_request", chat_id: "ready", projection_id: "request", turn_id: "turn", turn_seq: 2,
request_id: "request", run_id: "run", sequence: 1, phase: "completed" },
{ event: "turn_end", chat_id: "ready", projection_id: "end", turn_id: "turn", turn_seq: 3, latency_ms: 1000 },
], page: { before_cursor: "content", has_more_before: true },
}).mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject; }));
const loading: boolean[] = [];
const { result } = renderHook(() => {
const history = useSessionHistory("websocket:ready");
loading.push(history.loadingOlder);
return history;
}, { wrapper: wrap(fakeClient()) });
await waitFor(() => expect(result.current.messages[0]?.content).toBe("Visible answer"));
loading.length = 0;
let finished = false;
act(() => { void result.current.loadOlder().then(() => { finished = true; }); });
await waitFor(() => expect(api.fetchWebuiThread).toHaveBeenCalledTimes(3));
expect(finished).toBe(false);
expect(result.current.loadingOlder).toBe(true);
expect(loading).not.toContain(false);
expect(result.current.messages.map((row) => row.content)).toEqual(["Visible answer"]);
await act(async () => { fail(new Error("offline")); });
expect(finished).toBe(true);
expect(result.current.olderError).toBe("offline");
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...initial,
events: [{ event: "user_message", chat_id: "ready", projection_id: "old", text: "Earlier question", starts_turn: true }],
page: { before_cursor: null, has_more_before: false },
});
await act(async () => { await result.current.loadOlder(); });
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("tok", "websocket:ready", expect.objectContaining({ before: "content" }));
expect(result.current.messages.map((row) => row.content)).toEqual(["Earlier question", "Visible answer"]);
expect(result.current.loadingOlder).toBe(false);
expect(result.current.olderError).toBeNull();
});
it("keeps older-history failures separate and retries them explicitly", async () => {
vi.mocked(api.fetchWebuiThread)
.mockResolvedValueOnce(canonicalThreadPayload({