fix(webui): show skeleton while conversation history loads

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-20 22:01:40 +08:00
1 parent 85bee83247
commit 14d9e6ed0d
7 files changed
+176 -16

No files matched your search

+3
View File
@@ -24,6 +24,7 @@ import "../src/globals.css";
import { DiagramFixture } from "./diagram-fixture";
import { TypographyFixture } from "./typography-fixture";
import { HistoryBoundaryFixture } from "./history-boundary-fixture";
import { ThreadLoadingFixture } from "./thread-loading-fixture";
const history: UIMessage[] = [
{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },
@@ -151,6 +152,8 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>
? <ClientProvider client={railClient} token="fixture" webuiCapabilities={["webui.prompt-navigation.v1"]}><HistoryBoundaryFixture local={parameters.has("local")} navigate={parameters.has("navigate")} /></ClientProvider>
: parameters.get("case") === "diagrams"
? <DiagramFixture parameters={parameters} />
: parameters.get("case") === "thread-loading"
? <ClientProvider client={railClient} token="fixture"><ThreadLoadingFixture /></ClientProvider>
: parameters.get("case") === "new-chat-skeleton"
? <ClientProvider client={railClient} token="fixture"><NewChatSkeletonFixture /></ClientProvider>
: parameters.get("case") === "skeleton-additions"
+14
View File
@@ -0,0 +1,14 @@
import { ThreadShell } from "@/components/thread/ThreadShell";
import { settings } from "@/dev/gallery/settings";
export function ThreadLoadingFixture() {
const dark = new URLSearchParams(location.search).has("dark");
document.documentElement.classList.toggle("dark", dark);
return <main className="thread-workspace flex min-w-0 flex-col overflow-hidden bg-background" style={{ height: "100dvh" }}>
<ThreadShell
session={{ key: "websocket:loading-preview", channel: "websocket", chatId: "loading-preview", createdAt: null, updatedAt: null, preview: "" }}
title="Loading preview" onToggleSidebar={() => {}} theme={dark ? "dark" : "light"}
settingsSnapshot={settings}
/>
</main>;
}
+68
View File
@@ -0,0 +1,68 @@
import { expect, test } from "@playwright/test";
import { canonicalThreadPayload } from "../src/tests/thread-test-payload";
const history = canonicalThreadPayload({
schemaVersion: 3,
messages: [
{ id: "question", role: "user", content: "Preview question", createdAt: 1_700_000_000_000 },
{ id: "answer", role: "assistant", content: "Preview answer", createdAt: 1_700_000_001_000 },
],
});
for (const width of [314, 390, 1440]) for (const dark of [false, true]) {
test(`history skeleton keeps live controls in place at ${width}px ${dark ? "dark" : "light"}`, async ({ page }) => {
await page.setViewportSize({ width, height: width === 314 ? 647 : 844 });
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.addInitScript(() => { localStorage.setItem("nanobot.locale", "en"); });
await page.route("**/api/commands", (route) => route.fulfill({ json: { commands: [] } }));
let releaseHistory!: () => void;
const historyGate = new Promise<void>((resolve) => { releaseHistory = resolve; });
await page.route("**/api/sessions/*/webui-thread?*", async (route) => {
await historyGate;
await route.fulfill({ json: history });
});
await page.goto(`/browser/fixture.html?case=thread-loading${dark ? "&dark" : ""}`);
const loading = page.getByRole("status", { name: "Loading conversation…" });
await expect(loading).toBeVisible();
await expect(loading).toHaveAttribute("aria-busy", "true");
await expect(page.getByRole("textbox", { name: "Message input" })).toBeEnabled();
await expect(page.locator(".startup-shell")).toHaveCount(0);
await expect(loading.locator("[aria-hidden] > div")).toHaveCount(3);
await page.evaluate(async () => { await document.fonts.ready; });
const header = await page.getByTestId("thread-header").boundingBox();
const composer = page.locator(".thread-composer-surface");
const before = (await composer.boundingBox())!;
const loadingBox = (await loading.boundingBox())!;
expect(loadingBox.width).toBeGreaterThan(0);
expect(loadingBox.y + loadingBox.height).toBeLessThanOrEqual(before.y);
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
const pulse = loading.locator("[aria-hidden]");
await expect(pulse).toHaveCSS("animation-name", "pulse");
await page.emulateMedia({ reducedMotion: "reduce" });
await expect(pulse).toHaveCSS("animation-name", "none");
await page.emulateMedia({ reducedMotion: "no-preference" });
await page.evaluate(() => {
const layout = document.querySelector(".thread-layout")!;
const transitions: (string | null)[] = [];
Object.defineProperty(window, "loadingLayoutTransitions", { value: transitions });
new MutationObserver((records) => {
for (const record of records) transitions.push(record.oldValue);
}).observe(layout, { attributes: true, attributeFilter: ["data-layout"], attributeOldValue: true });
});
await page.getByRole("textbox", { name: "Message input" }).fill("Draft survives loading");
releaseHistory();
await expect(page.getByText("Preview answer", { exact: true })).toBeVisible();
await expect(loading).toHaveCount(0);
expect(await page.evaluate(() => (window as Window & { loadingLayoutTransitions?: (string | null)[] }).loadingLayoutTransitions)).not.toContain("hero");
await expect(page.getByRole("textbox", { name: "Message input" })).toHaveValue("Draft survives loading");
const after = (await composer.boundingBox())!;
for (const dimension of ["x", "y", "width", "height"] as const) {
expect(Math.abs(before[dimension] - after[dimension]), dimension).toBeLessThanOrEqual(1);
}
expect(await page.getByTestId("thread-header").boundingBox()).toEqual(header);
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
expect(errors).toEqual([]);
});
}
@@ -0,0 +1,23 @@
import { useTranslation } from "react-i18next";
import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus";
export function ThreadLoadingSkeleton() {
const { t } = useTranslation();
return (
<SkeletonStatus label={t("thread.loadingConversation")} className="space-y-8 pt-12">
<div className="thread-message-row">
<div className="ml-auto h-10 w-2/5 rounded-floating bg-muted/60" />
</div>
<div className="thread-message-row space-y-3">
<div className="h-3 w-4/5 rounded bg-muted/60" />
<div className="h-3 w-full rounded bg-muted/60" />
<div className="h-3 w-3/5 rounded bg-muted/60" />
</div>
<div className="thread-message-row space-y-3">
<div className="h-3 w-3/4 rounded bg-muted/60" />
<div className="h-3 w-1/2 rounded bg-muted/60" />
</div>
</SkeletonStatus>
);
}
+11 -8
View File
@@ -29,6 +29,7 @@ import {
toModelBadgeInfo,
} from "@/components/thread/model-preset";
import { ThreadHeader } from "@/components/thread/ThreadHeader";
import { ThreadLoadingSkeleton } from "@/components/thread/ThreadLoadingSkeleton";
import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
import { useNanobotStream, type SendAttachment, type SendOptions } from "@/hooks/useNanobotStream";
@@ -938,6 +939,9 @@ export function ThreadShell({
chatId, initial, hasPendingToolCalls, handleTurnEnd, handleStreamDetach, completedTurnIds,
);
const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]);
const normalizedHistory = useMemo(() => projectWebuiThreadMessages(historical), [historical]);
// The response can arrive one commit before its messages reach the viewport.
const initialHistoryLoading = loading || (normalizedHistory.length > 0 && displayMessages.length === 0);
const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages);
const updateNavigationMessages = promptNavigation.updateMessages;
@@ -1139,7 +1143,7 @@ export function ThreadShell({
chatId,
]);
const showHeroComposer = displayMessages.length === 0 && !loading;
const showHeroComposer = displayMessages.length === 0 && !initialHistoryLoading;
const composerVariant = showHeroComposer ? emptyComposerVariant : "thread";
const wasShowingHeroComposerRef = useRef(showHeroComposer);
const sessionModelPreset = session?.modelPreset?.trim() || null;
@@ -1269,9 +1273,9 @@ export function ThreadShell({
const canonicalCompletedTurnIds = useMemo(() => Array.from(new Set([
...completedTurnIds,
...(!completionIdsProvided && !hasPendingToolCalls && historyActiveTurnId === null
? completedAssistantTurnIds(projectWebuiThreadMessages(historical))
? completedAssistantTurnIds(normalizedHistory)
: []),
])), [completedTurnIds, completionIdsProvided, hasPendingToolCalls, historical, historyActiveTurnId]);
])), [completedTurnIds, completionIdsProvided, hasPendingToolCalls, normalizedHistory, historyActiveTurnId]);
const lastRunTurnId = chatId ? client.getRunTurnId(chatId) : null;
const completedRunTurnId = chatId && lastRunTurnId && client.isRunCompleted(chatId, lastRunTurnId)
@@ -1298,7 +1302,6 @@ export function ThreadShell({
)
)
);
const normalizedHistory = projectWebuiThreadMessages(historical);
// Completion is a fact about a turn, even when a newer local turn prevents
// this snapshot from settling the conversation's current run.
client.fenceCanonicalCompletedTurns(chatId, canonicalCompletedTurnIds);
@@ -1407,6 +1410,7 @@ export function ThreadShell({
canonicalCompletedTurnIds,
completionIdsProvided,
historical,
normalizedHistory,
historyVersion,
historyContinuity,
historyLineage,
@@ -2000,10 +2004,8 @@ export function ThreadShell({
</>
);
const emptyState = loading ? (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
{t("thread.loadingConversation")}
</div>
const emptyState = initialHistoryLoading ? (
<ThreadLoadingSkeleton />
) : (
<div className="flex w-full flex-col items-center text-center animate-in fade-in-0 slide-in-from-bottom-2 [animation-duration:220ms] motion-reduce:animate-none">
<HeroGreeting text={t(heroGreetingKey)} />
@@ -2085,6 +2087,7 @@ export function ThreadShell({
runStartedAt={currentRunStartedAt}
retryStatus={retryStatus}
emptyState={emptyState}
initialLoading={initialHistoryLoading}
composer={composerPortalTarget === undefined ? composer : null}
activeTurnId={viewportTurnId}
activeTurnStartedHere={activeTurnStartedHere}
+12 -7
View File
@@ -48,6 +48,7 @@ interface ThreadViewportProps {
composer?: ReactNode;
navigationFrame?: HTMLElement | null;
emptyState?: ReactNode;
initialLoading?: boolean;
scrollToBottomSignal?: number;
activeTurnId?: string | null;
activeTurnStartedHere?: boolean;
@@ -249,6 +250,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
composer,
navigationFrame,
emptyState,
initialLoading = false,
scrollToBottomSignal = 0,
activeTurnId: liveTurnId = null,
activeTurnStartedHere = false,
@@ -384,6 +386,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}
const hasTaskContent = useHasSubagentContent();
const hasMessages = messages.length > 0 || (hasTaskContent && conversationReady);
const hasThreadLayout = hasMessages || initialLoading;
useLayoutEffect(() => {
scrollRef.current = hasMessages
? messageRegionRef.current
@@ -1045,11 +1048,11 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
>
<div
ref={contentRef}
data-testid={!hasMessages ? "thread-welcome-layout" : undefined}
data-layout={hasComposer ? (hasMessages ? "thread" : "hero") : "external"}
data-testid={!hasThreadLayout ? "thread-welcome-layout" : undefined}
data-layout={hasComposer ? (hasThreadLayout ? "thread" : "hero") : "external"}
className={cn(
"thread-layout mx-auto grid min-h-full w-full",
hasMessages
hasThreadLayout
? "h-full"
: "max-w-[72rem] px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-6 sm:px-4 sm:py-12",
)}
@@ -1097,8 +1100,10 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
ref={emptyStateRef}
data-testid="thread-empty-region"
className={cn(
"row-start-1 flex min-h-0 min-w-0 w-full items-center justify-center",
hasComposer && "sm:items-end sm:pb-8",
"row-start-1 min-h-0 min-w-0 w-full",
initialLoading
? "overflow-hidden"
: cn("flex items-center justify-center", hasComposer && "sm:items-end sm:pb-8"),
)}
>
{emptyState}
@@ -1130,12 +1135,12 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}}
className={cn(
"row-start-2 z-10 w-full",
hasMessages ? "thread-composer-dock relative" : "relative self-center",
hasThreadLayout ? "thread-composer-dock relative" : "relative self-center",
)}
>
<div
className={cn(
hasMessages
hasThreadLayout
? "px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] sm:px-4"
: "",
)}
+45 -1
View File
@@ -5232,7 +5232,13 @@ describe("ThreadShell", () => {
});
expect(screen.queryByText("from chat a")).not.toBeInTheDocument();
expect(screen.getByText("Loading conversation…")).toBeInTheDocument();
const loading = screen.getByRole("status", { name: "Loading conversation…" });
expect(loading).toHaveAttribute("aria-busy", "true");
expect(loading.querySelector("[aria-hidden]")).not.toBeEmptyDOMElement();
expect(screen.getByRole("textbox", { name: "Message input" })).toBeEnabled();
const header = screen.getByTestId("thread-header");
const composer = screen.getByTestId("thread-composer-motion");
expect(composer.closest("[data-layout]")).toHaveAttribute("data-layout", "thread");
await act(async () => {
resolveChatB?.(
@@ -5242,6 +5248,44 @@ describe("ThreadShell", () => {
await waitFor(() => expect(screen.getByText("from chat b")).toBeInTheDocument());
expect(screen.queryByText("from chat a")).not.toBeInTheDocument();
expect(screen.queryByRole("status", { name: "Loading conversation…" })).not.toBeInTheDocument();
expect(screen.getByTestId("thread-header")).toBe(header);
expect(screen.getByTestId("thread-composer-motion")).toBe(composer);
});
it.each([false, true])("replaces the initial history skeleton with welcome when no visible history remains (systemOnly=%s)", async (systemOnly) => {
let resolveHistory!: (response: Response) => void;
vi.mocked(fetch).mockImplementation((input) => String(input).includes("/webui-thread")
? new Promise<Response>((resolve) => { resolveHistory = resolve; })
: Promise.resolve(new Response(null, { status: 404 })));
render(wrap(makeClient(), <ThreadShell session={session("empty-topic")} title="Empty topic"
onToggleSidebar={() => {}} />));
expect(screen.getByRole("status", { name: "Loading conversation…" })).toHaveAttribute("aria-busy", "true");
await act(async () => {
resolveHistory(httpJson(transcriptFromSimpleMessages(systemOnly
? [{ role: "assistant", content: "Model selected", turnId: "webui-system:model-preset" }]
: [])));
});
expect(await screen.findByText(HERO_GREETING_PATTERN)).toBeVisible();
expect(screen.queryByRole("status", { name: "Loading conversation…" })).not.toBeInTheDocument();
expect(screen.getByTestId("thread-welcome-layout")).toHaveAttribute("data-layout", "hero");
});
it("keeps cached messages visible while the first history revalidation is pending", async () => {
webuiThreadCache.set("websocket:cached-topic", transcriptFromSimpleMessages([
{ role: "assistant", content: "Cached answer" },
]));
vi.mocked(fetch).mockImplementation((input) => String(input).includes("/webui-thread")
? new Promise<Response>(() => {})
: Promise.resolve(new Response(null, { status: 404 })));
render(wrap(makeClient(), <ThreadShell session={session("cached-topic")} title="Cached topic"
onToggleSidebar={() => {}} />));
expect(await screen.findByText("Cached answer")).toBeVisible();
expect(screen.queryByRole("status", { name: "Loading conversation…" })).not.toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "Message input" })).toBeEnabled();
});
it("loads mention catalogs only on demand and ignores window focus", async () => {