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:
1 parent
40e4e8a3fd
commit
efec4a608d
14 files changed
+751
-103
No files matched your search
+2
-2
@@ -52,9 +52,9 @@ Supporting hooks and display-model helpers stay near the feature that owns them.
|
||||
|
||||
## History-boundary motion
|
||||
|
||||
History request hooks own loading, pagination and errors. `usePromptHistory.operation` keeps jump/newer feedback separate from an older-page slot, including failed reads and retry; index errors have no page operation. `ThreadHistorySpring` owns input resistance, gesture thresholds and transient/rest/held targets; Motion owns spring integration, frame scheduling and interruption velocity. The reduced-motion preference removes transient travel while preserving request and committed-slot behavior. The spring never writes `scrollTop`. `ThreadViewport` hands a triggered reveal to a fixed-height slot before the original boundary display unit through `ThreadMessages.beforeUnit`, subtracting that slot from the remaining transform. `ThreadMessages.topInset` remains the single normal gutter at the start of the currently rendered list and does not travel into the middle of the timeline with a loading slot; the header paints inside its own slot, not above it over earlier text. The leading content (including unlinked tasks) has its own stable keyed prelude alongside the display units, preserving identity and disclosure state across remote and local cached prepends. The scroller's `scroll-padding-top` remains the prompt-navigation inset. The preceding message margin belongs before the slot, and reading-anchor measurements exclude the slot only for following units. This keeps the handoff and later prepends continuous without a second scroll writer. The temporary loading slot stays in the message flow while a request is pending and on failure, so native scrolling carries feedback out of view; successful completion, including an exhausted result, removes the slot and its old-boundary gutter, restoring normal message spacing. `ThreadViewport` measures and compensates the active reading anchor through the existing camera when scroll bounds permit; explicit navigation and conversation changes take priority, and at a scroll bound the camera clamps rather than preserving space artificially. The leading top inset remains a single normal gutter when the historical boundary is no longer first. Explicit navigation and conversation changes reset the reveal. Boundary feedback without a real request remains transient.
|
||||
History hooks own content preparation, pagination and errors. One older/newer operation may consume several cursor pages: bookkeeping-only pages and unadmitted fragments keep it pending until display content changes, the boundary is exhausted, or a read fails. Content comparison surrounds history admission so live updates, replay identities and usage metadata cannot complete an unrelated pull. Completion publishes the prepared messages and status together; deferred Markdown, images and highlighting remain layout work, not extra loading gates. `usePromptHistory.operation` keeps jump/newer feedback separate from an older-page slot, including failed reads and retry; index errors have no page operation. `ThreadHistorySpring` owns input resistance, gesture thresholds and transient/rest/held targets; Motion owns spring integration, frame scheduling and interruption velocity. The reduced-motion preference removes transient travel while preserving request and committed-slot behavior. The spring never writes `scrollTop`. `ThreadViewport` hands a triggered reveal to a fixed-height slot before the original boundary display unit through `ThreadMessages.beforeUnit`, subtracting that slot from the remaining transform. `ThreadMessages.topInset` remains the single normal gutter at the start of the currently rendered list and does not travel into the middle of the timeline with a loading slot; the header paints inside its own slot, not above it over earlier text. The leading content (including unlinked tasks) has its own stable keyed prelude alongside the display units, preserving identity and disclosure state across remote and local cached prepends. The scroller's `scroll-padding-top` remains the prompt-navigation inset. The preceding message margin belongs before the slot, and reading-anchor measurements exclude the slot only for following units. This keeps the handoff and later prepends continuous without a second scroll writer. The temporary loading slot stays in the message flow while content preparation is pending and on failure, so native scrolling carries feedback out of view; successful content admission, including an exhausted result, removes the slot and its old-boundary gutter, restoring normal message spacing. `ThreadViewport` measures and compensates the active reading anchor through the existing camera when scroll bounds permit; explicit navigation and conversation changes take priority, and at a scroll bound the camera clamps and rebases the reading offset rather than preserving space artificially or restoring an obsolete offset on the next prepend. The leading top inset remains a single normal gutter when the historical boundary is no longer first. Explicit navigation and conversation changes reset the reveal. Boundary feedback without a real request remains transient.
|
||||
|
||||
Prompt navigation retains at most three server pages. Static ready Blocks appear only during an uncommitted boundary pull; a completed header is hidden and offers no second pagination entry point. Loading continues at the new boundary, where the header binds to the current first display unit for wheel, touch and keyboard alike; page eviction therefore does not remove the header or the message being read. A failure animates the same Blocks in red without visible error text; hovering shows details, and selecting the red Blocks or a fresh boundary gesture starts another request. Failed reads suppress scroll-triggered automatic requests, not explicit user input.
|
||||
Prompt navigation keeps a three-page raw window. Fragmented turns also retain their single terminal record so the event projector can preserve completion metadata when bookkeeping pages or the terminal page leave that window; skipped raw pages are not accumulated. Accepted metadata survives exhaustion and failed continuation without counting as new display content. Crossed fork boundaries survive skipped pages too; a marker before all visible rows keeps the pull pending until earlier content arrives or history is exhausted. Static ready Blocks appear only during an uncommitted boundary pull; a completed header is hidden and offers no second pagination entry point. Loading continues at the new boundary, where the header binds to the current first display unit for wheel, touch and keyboard alike; page eviction therefore does not remove the header or the message being read. A failure animates the same Blocks in red without visible error text; hovering shows details, and selecting the red Blocks or a fresh boundary gesture retries the failed cursor rather than rereading successful intermediate pages. Failed reads suppress scroll-triggered automatic requests, not explicit user input.
|
||||
|
||||
## Theme artwork and surface motion
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ import { TypographyFixture } from "./typography-fixture";
|
||||
import { CodeWrappingFixture } from "./code-wrapping-fixture";
|
||||
import { InlineReferencesFixture } from "./inline-references-fixture";
|
||||
import { HistoryBoundaryFixture } from "./history-boundary-fixture";
|
||||
import { installHistoryBoundaryPreviewApi } from "./history-boundary-preview";
|
||||
import { ChatFailureFixture } from "./chat-failure-fixture";
|
||||
import { ThreadLoadingFixture } from "./thread-loading-fixture";
|
||||
import { AnswerOrderFixture } from "./answer-order-fixture";
|
||||
@@ -111,6 +112,11 @@ function SessionMessagesFixture() {
|
||||
}
|
||||
|
||||
const parameters = new URLSearchParams(location.search);
|
||||
const historyPreview = parameters.get("preview");
|
||||
if (parameters.get("case") === "history-boundary"
|
||||
&& (historyPreview === "slow" || historyPreview === "fast" || historyPreview === "pages" || historyPreview === "error")) {
|
||||
installHistoryBoundaryPreviewApi(historyPreview);
|
||||
}
|
||||
const railClient = new NanobotClient({ url: "ws://127.0.0.1:8765", reconnect: false });
|
||||
const railHistory: UIMessage[] = Array.from({ length: 5 }, (_, index) => [
|
||||
{ id: `u${1995 + index}`, role: "user" as const, content: `Question ${1995 + index}`, createdAt: index + 1 },
|
||||
@@ -232,7 +238,7 @@ if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();
|
||||
if (parameters.get("case") === "subagent-dock") installSubagentDockApi();
|
||||
await initializeI18n();
|
||||
if (parameters.get("case") === "activity-wheel") await setAppLanguage("zh-CN");
|
||||
if (parameters.get("case") === "appearance" && parameters.has("lang")) {
|
||||
if ((parameters.get("case") === "appearance" || historyPreview) && parameters.has("lang")) {
|
||||
await setAppLanguage(normalizeLocale(parameters.get("lang")));
|
||||
}
|
||||
createRoot(document.getElementById("root")!).render(<TooltipProvider>
|
||||
|
||||
@@ -13,6 +13,7 @@ const localMessages: UIMessage[] = Array.from({ length: 280 }, (_, index) => ({
|
||||
|
||||
export function HistoryBoundaryFixture({ local = false, navigate = false, tasks = false }: { local?: boolean; navigate?: boolean; tasks?: boolean }) {
|
||||
const { client, token } = useClient();
|
||||
const preview = new URLSearchParams(location.search).get("preview");
|
||||
const [key, setKey] = useState("websocket:boundary-a");
|
||||
const history = useSessionHistory(local ? null : key);
|
||||
const messages = local ? localMessages : history.messages;
|
||||
@@ -24,8 +25,13 @@ export function HistoryBoundaryFixture({ local = false, navigate = false, tasks
|
||||
&& current.turnIds.every((turnId, index) => turnId === turnIds[index]) ? current : { key, turnIds });
|
||||
}, [key]);
|
||||
return <main className="bg-background text-foreground" style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
|
||||
<div className="flex h-10 shrink-0 items-center gap-4 px-4 text-sm">
|
||||
<button onClick={() => setKey((current) => current.endsWith("-a") ? "websocket:boundary-b" : "websocket:boundary-a")}>Switch conversation</button>
|
||||
<div className="flex min-h-10 shrink-0 flex-wrap items-center gap-4 px-4 py-2 text-sm">
|
||||
{preview ? <>
|
||||
<span className="text-muted-foreground">历史加载预览</span>
|
||||
{([["slow", "慢加载"], ["pages", "连续分页"], ["fast", "快速完成"], ["error", "失败重试"]] as const).map(([mode, label]) =>
|
||||
<a key={mode} href={`?case=history-boundary&preview=${mode}&lang=zh-CN`}
|
||||
className={preview === mode ? "font-medium underline underline-offset-4" : "text-muted-foreground"}>{label}</a>)}
|
||||
</> : <button onClick={() => setKey((current) => current.endsWith("-a") ? "websocket:boundary-b" : "websocket:boundary-a")}>Switch conversation</button>}
|
||||
</div>
|
||||
<Profiler id="history-boundary" onRender={(_, phase, actualDuration) => {
|
||||
window.dispatchEvent(new CustomEvent("history-boundary-render", { detail: { phase, actualDuration } }));
|
||||
@@ -40,7 +46,9 @@ export function HistoryBoundaryFixture({ local = false, navigate = false, tasks
|
||||
initialLoading={history.loading} initialError={history.error} onRetryInitial={history.refresh}
|
||||
loadingOlder={history.loadingOlder} olderError={history.olderError} onLoadOlder={history.loadOlder}
|
||||
navigation={navigate ? navigation : undefined} userMessageOffset={history.userMessageOffset}
|
||||
composer={<div className="border-t px-4 py-6" style={{ height: 96 }}>History boundary fixture</div>} />
|
||||
composer={<div className="border-t px-4 py-6 text-sm text-muted-foreground" style={{ height: 96 }}>
|
||||
{preview ? "滚到顶部后继续向上滚;触屏在顶部向下拉。仅使用示例消息,不连接真实会话。" : "History boundary fixture"}
|
||||
</div>} />
|
||||
</SubagentTasksProvider>
|
||||
</Profiler>
|
||||
</main>;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { WebuiThreadPersistedPayload } from "@/lib/types";
|
||||
|
||||
export type HistoryPreviewMode = "slow" | "fast" | "pages" | "error";
|
||||
|
||||
export function historyPreviewPage(start: number): WebuiThreadPersistedPayload {
|
||||
return {
|
||||
schemaVersion: 3, projection: "events",
|
||||
events: Array.from({ length: 6 }, (_, offset) => {
|
||||
const index = start + offset;
|
||||
return [
|
||||
{ event: "user_message" as const, chat_id: "boundary-a", projection_id: `u${index}`,
|
||||
text: `历史消息 ${index + 1}`, starts_turn: true },
|
||||
{ event: "message" as const, chat_id: "boundary-a", projection_id: `a${index}`,
|
||||
text: "这是一段用于体验历史加载的示例内容。\n\n加载完成后,这条消息应保持在原来的阅读位置;九宫格不应提前收起。" },
|
||||
];
|
||||
}).flat(),
|
||||
page: { before_cursor: start ? String(start) : null, has_more_before: start > 0,
|
||||
user_message_offset: start, has_more_after: false },
|
||||
};
|
||||
}
|
||||
|
||||
// Only the opt-in browser fixture uses simulated data; production requests are untouched.
|
||||
export function installHistoryBoundaryPreviewApi(mode: HistoryPreviewMode) {
|
||||
const originalFetch = window.fetch.bind(window);
|
||||
let failed = false;
|
||||
window.fetch = async (input, init) => {
|
||||
const url = new URL(input instanceof Request ? input.url : String(input), location.href);
|
||||
if (url.origin !== location.origin || !url.pathname.startsWith("/api/")) return originalFetch(input, init);
|
||||
if (url.pathname.endsWith("/prompts")) return Response.json({ prompts: [] });
|
||||
if (!url.pathname.endsWith("/webui-thread")) return Response.json({});
|
||||
const cursor = url.searchParams.get("before");
|
||||
if (!cursor) return Response.json(historyPreviewPage(12));
|
||||
const continuation = cursor.startsWith("content-");
|
||||
const start = Number(cursor.replace("content-", ""));
|
||||
await new Promise((resolve) => setTimeout(resolve, mode === "fast" ? 30 : 1500));
|
||||
if (mode === "error" && !failed) {
|
||||
failed = true;
|
||||
return new Response("Preview: history unavailable", { status: 503 });
|
||||
}
|
||||
if (mode === "pages" && !continuation) {
|
||||
return Response.json({ schemaVersion: 3, projection: "events", events: [],
|
||||
page: { before_cursor: `content-${start}`, has_more_before: true, user_message_offset: start } });
|
||||
}
|
||||
return Response.json(historyPreviewPage(Math.max(0, start - 6)));
|
||||
};
|
||||
}
|
||||
@@ -304,6 +304,116 @@ test("wheel loading hands off to a retained 48px slot; prepend and delayed layou
|
||||
expect(history.reads).toHaveLength(1);
|
||||
});
|
||||
|
||||
for (const navigate of [false, true]) {
|
||||
test(`one pull holds its header across non-display pages until content is ready (${navigate ? "navigation" : "latest"})`, async ({ page }) => {
|
||||
const history = await installHistory(page, 40, 12, (start, count, more) => {
|
||||
const payload = historyPage(start, count, more);
|
||||
// Record-level history can return only bookkeeping, with an advancing cursor.
|
||||
return start === (navigate ? 26 : 28) ? { ...payload, events: [] } : payload;
|
||||
});
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
const { body, header } = await openSettledHistory(page, navigate ? "&navigate=1" : "");
|
||||
if (navigate) {
|
||||
const rail = page.getByTestId("prompt-rail-scroll");
|
||||
await rail.getByRole("button").first().focus();
|
||||
await page.keyboard.press("Home");
|
||||
await page.getByRole("button", { name: "Jump to message: Question 38", exact: true }).click();
|
||||
await expect.poll(() => history.reads.length).toBe(1);
|
||||
history.complete();
|
||||
await expect(body.getByText("Question 38", { exact: true })).toBeInViewport();
|
||||
await stableLayout(body);
|
||||
await body.hover();
|
||||
await page.mouse.wheel(0, 10000);
|
||||
await expect.poll(() => history.reads.length).toBe(2);
|
||||
history.complete();
|
||||
await expect(body.getByText("Question 51", { exact: true })).toBeAttached();
|
||||
await stableLayout(body);
|
||||
}
|
||||
const anchor = navigate ? "Question 38" : "Question 40";
|
||||
await positionAtTop(body);
|
||||
await requestOlderWithWheel(body, history, navigate ? 3 : 1);
|
||||
const held = await expectHeld(body, anchor);
|
||||
history.complete();
|
||||
await expect.poll(() => history.reads.length).toBe(navigate ? 4 : 2);
|
||||
await expect(header).toHaveAttribute("data-state", "loading");
|
||||
await stableLayout(body);
|
||||
await expectCoordinates(body, anchor, held);
|
||||
history.complete();
|
||||
await expect(body.getByText(navigate ? "Question 14" : "Question 16", { exact: true })).toBeAttached();
|
||||
await expect(body.locator(".thread-history-slot")).toHaveCount(0);
|
||||
await stableLayout(body);
|
||||
await expectAnchorCoordinate(body, anchor, held.anchorTop);
|
||||
});
|
||||
}
|
||||
|
||||
for (const retryWith of ["Blocks button", "boundary wheel"] as const) {
|
||||
test(`navigation older retries the failed cursor after a non-display page (${retryWith})`, async ({ page }) => {
|
||||
const history = await installHistory(page, 40, 12, (start, count, more) => {
|
||||
const payload = historyPage(start, count, more);
|
||||
return start === 26 ? { ...payload, events: [] } : payload;
|
||||
});
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
const { body, header, slot } = await openSettledHistory(page, "&navigate=1");
|
||||
// Keep the jump away from latest's bottom so setup cannot prefetch newer.
|
||||
await positionAtTop(body);
|
||||
await jumpViaRail(page, 38);
|
||||
await expect.poll(() => history.reads.length).toBe(1);
|
||||
history.complete();
|
||||
await expect(body.getByText("Question 38", { exact: true })).toBeInViewport();
|
||||
await stableLayout(body);
|
||||
await positionAtTop(body);
|
||||
await requestOlderWithWheel(body, history, 2);
|
||||
await expectHeld(body, "Question 38");
|
||||
|
||||
history.complete();
|
||||
await expect.poll(() => history.reads.length).toBe(3);
|
||||
await expect(header).toHaveAttribute("data-state", "loading");
|
||||
await expect(slot).toHaveCSS("height", "48px");
|
||||
history.complete("error");
|
||||
await expect(header).toHaveAttribute("data-state", "error");
|
||||
const retry = page.getByRole("button", { name: "Loading failed. Retry", exact: true });
|
||||
const blocks = retry.locator(".thread-history-blocks");
|
||||
await expect(blocks).toBeInViewport();
|
||||
await expect(blocks).toHaveCSS("color", "rgb(185, 28, 28)");
|
||||
if (retryWith === "Blocks button") await blocks.click();
|
||||
else await requestOlderWithWheel(body, history, 4);
|
||||
await expect.poll(() => history.reads.length).toBe(4);
|
||||
await expect(header).toHaveAttribute("data-state", "loading");
|
||||
expect(history.reads).toEqual([
|
||||
"?limit=24&after=38&include_model_requests=1&context_graph_encoding=references-v1",
|
||||
"?limit=24&before=38&include_model_requests=1&context_graph_encoding=references-v1",
|
||||
"?limit=24&before=26&include_model_requests=1&context_graph_encoding=references-v1",
|
||||
"?limit=24&before=26&include_model_requests=1&context_graph_encoding=references-v1",
|
||||
]);
|
||||
history.complete();
|
||||
await expect(body.getByText("Question 14", { exact: true })).toBeAttached();
|
||||
await expect(header).toHaveCount(0);
|
||||
await expect(slot).toHaveCount(0);
|
||||
await stableLayout(body);
|
||||
expect(history.reads).toHaveLength(4);
|
||||
});
|
||||
}
|
||||
|
||||
test("content settling at the top during preparation does not restore an obsolete reading offset", async ({ page }) => {
|
||||
const history = await installHistory(page);
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
const { body } = await openSettledHistory(page);
|
||||
const first = body.locator("[data-thread-display-unit]").first();
|
||||
// A plain Markdown fallback can be taller than its final layout above the reading anchor.
|
||||
await first.evaluate((node) => { (node as HTMLElement).style.paddingBottom = "160px"; });
|
||||
await positionAtTop(body);
|
||||
await requestOlderWithWheel(body, history, 1);
|
||||
await expectHeld(body, "Question 40");
|
||||
await first.evaluate((node) => { (node as HTMLElement).style.paddingBottom = ""; });
|
||||
await stableLayout(body);
|
||||
const top = await anchorTop(body, "Question 40");
|
||||
await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBe(0);
|
||||
history.complete();
|
||||
await expect(body.getByText("Question 28", { exact: true })).toBeAttached();
|
||||
await stableLayout(body);
|
||||
await expectAnchorCoordinate(body, "Question 40", top);
|
||||
});
|
||||
|
||||
test("task results stay with their prompts and retain the reading boundary when earlier messages load", async ({ page }) => {
|
||||
const history = await installHistory(page, 40, 12, (start, count, more) => {
|
||||
const payload = historyPage(start, count, more);
|
||||
|
||||
@@ -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]);
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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" } });
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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({
|
||||
|
||||
Reference in new issue
Block a user