From 14d9e6ed0d07d293ce4360d3019d30021e790bc0 Mon Sep 17 00:00:00 2001 From: chengyongru <2755839590@qq.com> Date: Tue, 20 Oct 2026 21:41:30 +0800 Subject: [PATCH] fix(webui): show skeleton while conversation history loads --- webui/browser/fixture.tsx | 3 + webui/browser/thread-loading-fixture.tsx | 14 ++++ webui/browser/thread-loading.spec.ts | 68 +++++++++++++++++++ .../thread/ThreadLoadingSkeleton.tsx | 23 +++++++ webui/src/components/thread/ThreadShell.tsx | 19 +++--- .../src/components/thread/ThreadViewport.tsx | 19 ++++-- webui/src/tests/thread-shell.test.tsx | 46 ++++++++++++- 7 files changed, 176 insertions(+), 16 deletions(-) create mode 100644 webui/browser/thread-loading-fixture.tsx create mode 100644 webui/browser/thread-loading.spec.ts create mode 100644 webui/src/components/thread/ThreadLoadingSkeleton.tsx diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index 1e5797eb6..45d4b0f5c 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -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( ? : parameters.get("case") === "diagrams" ? + : parameters.get("case") === "thread-loading" + ? : parameters.get("case") === "new-chat-skeleton" ? : parameters.get("case") === "skeleton-additions" diff --git a/webui/browser/thread-loading-fixture.tsx b/webui/browser/thread-loading-fixture.tsx new file mode 100644 index 000000000..34d2a4e47 --- /dev/null +++ b/webui/browser/thread-loading-fixture.tsx @@ -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
+ {}} theme={dark ? "dark" : "light"} + settingsSnapshot={settings} + /> +
; +} diff --git a/webui/browser/thread-loading.spec.ts b/webui/browser/thread-loading.spec.ts new file mode 100644 index 000000000..8210b7af8 --- /dev/null +++ b/webui/browser/thread-loading.spec.ts @@ -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((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([]); + }); +} diff --git a/webui/src/components/thread/ThreadLoadingSkeleton.tsx b/webui/src/components/thread/ThreadLoadingSkeleton.tsx new file mode 100644 index 000000000..64b32915e --- /dev/null +++ b/webui/src/components/thread/ThreadLoadingSkeleton.tsx @@ -0,0 +1,23 @@ +import { useTranslation } from "react-i18next"; + +import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus"; + +export function ThreadLoadingSkeleton() { + const { t } = useTranslation(); + return ( + +
+
+
+
+
+
+
+
+
+
+
+
+ + ); +} diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index 9448f0684..ed5ac6795 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -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 ? ( -
- {t("thread.loadingConversation")} -
+ const emptyState = initialHistoryLoading ? ( + ) : (
@@ -2085,6 +2087,7 @@ export function ThreadShell({ runStartedAt={currentRunStartedAt} retryStatus={retryStatus} emptyState={emptyState} + initialLoading={initialHistoryLoading} composer={composerPortalTarget === undefined ? composer : null} activeTurnId={viewportTurnId} activeTurnStartedHere={activeTurnStartedHere} diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx index e9a5fe6b3..9d678742a 100644 --- a/webui/src/components/thread/ThreadViewport.tsx +++ b/webui/src/components/thread/ThreadViewport.tsx @@ -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 0 || (hasTaskContent && conversationReady); + const hasThreadLayout = hasMessages || initialLoading; useLayoutEffect(() => { scrollRef.current = hasMessages ? messageRegionRef.current @@ -1045,11 +1048,11 @@ export const ThreadViewport = forwardRef
{emptyState} @@ -1130,12 +1135,12 @@ export const ThreadViewport = forwardRef
{ }); 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((resolve) => { resolveHistory = resolve; }) + : Promise.resolve(new Response(null, { status: 404 }))); + render(wrap(makeClient(), {}} />)); + + 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(() => {}) + : Promise.resolve(new Response(null, { status: 404 }))); + render(wrap(makeClient(), {}} />)); + + 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 () => {