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

+7 -1
View File
@@ -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>
+11 -3
View File
@@ -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>;
+46
View File
@@ -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)));
};
}
+110
View File
@@ -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);