fix(webui): show route-aligned skeletons from first paint (#6303)
This commit is contained in:
1 parent
af68da3280
commit
5d886fbb20
43 files changed
+1592
-213
No files matched your search
@@ -17,6 +17,9 @@ import { Button } from "@/components/ui/button";
|
||||
import { SettingsIcon } from "@/components/icons/product-icons";
|
||||
import { initializeI18n } from "@/i18n";
|
||||
import type { McpPresetInfo, UIMessage } from "@/lib/types";
|
||||
import { SkeletonFixture } from "./skeleton-fixture";
|
||||
import { installSkeletonPreviewApi, SkeletonAdditionsFixture } from "./skeleton-additions-fixture";
|
||||
import { NewChatSkeletonFixture } from "./new-chat-skeleton-fixture";
|
||||
import "../src/globals.css";
|
||||
|
||||
const history: UIMessage[] = [
|
||||
@@ -136,9 +139,16 @@ function AppsFixture() {
|
||||
onMcpToolsChange={noop}
|
||||
/></main>;
|
||||
}
|
||||
if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();
|
||||
await initializeI18n();
|
||||
createRoot(document.getElementById("root")!).render(<TooltipProvider>
|
||||
{parameters.get("case") === "apps"
|
||||
{parameters.get("case") === "new-chat-skeleton"
|
||||
? <ClientProvider client={railClient} token="fixture"><NewChatSkeletonFixture /></ClientProvider>
|
||||
: parameters.get("case") === "skeleton-additions"
|
||||
? <ClientProvider client={railClient} token="fixture"><SkeletonAdditionsFixture /></ClientProvider>
|
||||
: parameters.get("case") === "skeleton"
|
||||
? <ClientProvider client={railClient} token="fixture"><SkeletonFixture surface={parameters.get("surface") ?? "skills"} loading={parameters.has("loading")} /></ClientProvider>
|
||||
: parameters.get("case") === "apps"
|
||||
? <ClientProvider client={railClient} token="fixture"><AppsFixture /></ClientProvider>
|
||||
: parameters.get("case") === "rail"
|
||||
? <ClientProvider client={railClient} token="fixture" webuiCapabilities={["webui.prompt-navigation.v1"]}><RailFixture /></ClientProvider>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { ThreadShell } from "@/components/thread/ThreadShell";
|
||||
import { StartupSkeleton } from "@/components/StartupSkeleton";
|
||||
import { settings } from "@/dev/gallery/settings";
|
||||
import "@/components/startup-skeleton.css";
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
export function NewChatSkeletonFixture() {
|
||||
const params = new URLSearchParams(location.search);
|
||||
const sidebarExpanded = !params.has("collapsed");
|
||||
const sidebarWidth = Number(params.get("sidebarWidth") ?? 272);
|
||||
const dark = params.has("dark");
|
||||
document.documentElement.classList.toggle("dark", dark);
|
||||
return <div className="flex overflow-hidden bg-background" style={{ height: "100dvh" }}>
|
||||
{params.has("loading") ? <StartupSkeleton sidebarExpanded={sidebarExpanded} sidebarWidth={sidebarWidth} /> : <>
|
||||
<aside className="hidden shrink-0 bg-sidebar lg:block" style={{ width: sidebarExpanded ? sidebarWidth : 56 }} />
|
||||
<main className="thread-workspace relative flex min-w-0 flex-1 flex-col overflow-hidden">
|
||||
<ThreadShell session={null} title="nanobot" onToggleSidebar={noop} theme={dark ? "dark" : "light"}
|
||||
hideSidebarToggleForHostChrome onTemporaryChatEnabledChange={noop} settingsSnapshot={settings}
|
||||
workspaceScope={{ project_path: "/workspace", access_mode: "full" }}
|
||||
workspaceDefaultScope={{ project_path: "/workspace", access_mode: "full" }}
|
||||
workspaceControls={{ can_change_project: true, can_browse_directories: true }} onWorkspaceScopeChange={noop} />
|
||||
</main>
|
||||
</>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { expect, test, type Locator } from "@playwright/test";
|
||||
|
||||
const cases = [
|
||||
{ name: "phone", width: 390, height: 844, touch: true, extra: "" },
|
||||
{ name: "reported viewport", width: 946, height: 936, touch: false, extra: "" },
|
||||
{ name: "desktop", width: 1440, height: 936, touch: false, extra: "" },
|
||||
{ name: "sidebar rail", width: 1440, height: 936, touch: false, extra: "&collapsed" },
|
||||
{ name: "custom sidebar", width: 1440, height: 936, touch: false, extra: "&sidebarWidth=384" },
|
||||
{ name: "compact desktop composer", width: 1024, height: 936, touch: false, extra: "&sidebarWidth=480" },
|
||||
{ name: "wide desktop", width: 1920, height: 1080, touch: false, extra: "" },
|
||||
];
|
||||
|
||||
async function box(locator: Locator) {
|
||||
await expect(locator).toBeVisible();
|
||||
return (await locator.boundingBox())!;
|
||||
}
|
||||
|
||||
function sameBox(actual: Awaited<ReturnType<typeof box>>, expected: typeof actual) {
|
||||
for (const key of ["x", "y", "width", "height"] as const) {
|
||||
// The live thread camera can retain its 1px scroll anchor after initial focus.
|
||||
expect(Math.abs(actual[key] - expected[key]), key).toBeLessThanOrEqual(1);
|
||||
}
|
||||
}
|
||||
|
||||
for (const c of cases) for (const locale of ["en", "zh-CN"]) {
|
||||
test.describe(`${c.name} ${locale} new chat`, () => {
|
||||
test.use({ viewport: { width: c.width, height: c.height }, hasTouch: c.touch, reducedMotion: "reduce" });
|
||||
test("aligns the document skeleton with the real welcome, composer and header", async ({ page }) => {
|
||||
await page.addInitScript((language) => {
|
||||
Math.random = () => 0;
|
||||
localStorage.setItem("nanobot.locale", language);
|
||||
}, locale);
|
||||
await page.route("**/api/commands", (route) => route.fulfill({ json: { commands: [] } }));
|
||||
const url = `/browser/fixture.html?case=new-chat-skeleton${c.extra}${locale === "zh-CN" ? "&dark" : ""}`;
|
||||
await page.goto(url);
|
||||
await expect(page.locator(".thread-composer-surface")).toBeVisible();
|
||||
await page.evaluate(async () => { await document.fonts.ready; });
|
||||
const loaded = {
|
||||
header: await box(page.getByTestId("thread-header")),
|
||||
controls: await page.getByTestId("thread-header").locator("button:visible").evaluateAll((elements) => elements.map((e) => {
|
||||
const { x, y, width, height } = e.getBoundingClientRect();
|
||||
return { x, y, width, height };
|
||||
})),
|
||||
composer: await box(page.locator(".thread-composer-surface")),
|
||||
input: await box(page.locator(".thread-composer-input")),
|
||||
footer: await box(page.locator(".thread-composer-footer")),
|
||||
greeting: await box(page.getByTestId("hero-greeting")),
|
||||
workspaceRow: await page.locator(".thread-composer-workspace-row").isVisible()
|
||||
? await box(page.locator(".thread-composer-workspace-row")) : null,
|
||||
};
|
||||
await page.goto(`${url}&loading`);
|
||||
sameBox(await box(page.locator(".startup-chat-header")), loaded.header);
|
||||
sameBox(await box(page.locator(".startup-composer-surface")), loaded.composer);
|
||||
sameBox(await box(page.locator(".startup-composer-input")), loaded.input);
|
||||
sameBox(await box(page.locator(".startup-composer-footer")), loaded.footer);
|
||||
if (loaded.workspaceRow) sameBox(await box(page.locator(".startup-workspace-row")), loaded.workspaceRow);
|
||||
const controls = page.locator(".startup-header-menu:visible, .startup-header-actions > div");
|
||||
await expect(controls).toHaveCount(loaded.controls.length);
|
||||
for (let i = 0; i < loaded.controls.length; i++) sameBox(await box(controls.nth(i)), loaded.controls[i]);
|
||||
const greeting = await box(page.locator(".startup-welcome-line"));
|
||||
if (c.width < 640) expect(Math.abs(greeting.y + greeting.height / 2 - loaded.greeting.y - loaded.greeting.height / 2)).toBeLessThanOrEqual(1);
|
||||
else expect(Math.abs(greeting.y + greeting.height - loaded.greeting.y - loaded.greeting.height)).toBeLessThanOrEqual(1);
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
|
||||
await expect(page.getByRole("status")).toHaveText("Loading nanobot…");
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useLayoutEffect, useState } from "react";
|
||||
|
||||
import { LinearMemberAccessView } from "../../nanobot/channels/linear/webui/LinearMemberAccessView";
|
||||
import type { LinearMembersPayload } from "../../nanobot/channels/linear/webui/types";
|
||||
import { ChatList } from "@/components/ChatList";
|
||||
import { SettingsPage } from "@/components/settings/SettingsPage";
|
||||
import type { SettingsSectionKey } from "@/components/settings/contracts";
|
||||
import { SkillsCatalogSettings } from "@/components/settings/SkillsCatalogSettings";
|
||||
import { AutomationsSettings } from "@/components/settings/system/AutomationsSettings";
|
||||
import { RUNTIME_CONFIG_FIELDS } from "@/components/settings/system/runtime-config-fields";
|
||||
import { useSettingsController } from "@/components/settings/useSettingsController";
|
||||
import { SessionInfoPopoverView } from "@/components/thread/SessionInfoPopoverView";
|
||||
import { settings } from "@/dev/gallery/settings";
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import type { ChatSummary, SessionAutomationJob, SettingsPayload, SkillDetail } from "@/lib/types";
|
||||
|
||||
const noop = () => {};
|
||||
const now = Date.now();
|
||||
const names = ["Project summary", "Review changes", "Release checklist", "Documentation"];
|
||||
const jobs: SessionAutomationJob[] = names.slice(0, 3).map((name, index) => ({
|
||||
id: `preview-${index}`, name, enabled: true, schedule: { kind: "every", every_ms: 3_600_000 },
|
||||
payload: { message: "Summarize the project." }, state: { next_run_at_ms: now + index * 86_400_000 + 3_600_000 },
|
||||
}));
|
||||
const sessions: ChatSummary[] = names.map((title, index) => ({
|
||||
key: `websocket:preview-${index}`, chatId: `preview-${index}`, channel: "websocket", title, preview: "",
|
||||
handle: { id: `preview-${index}`, name: `topic${index}` },
|
||||
createdAt: new Date(now).toISOString(), updatedAt: new Date(now).toISOString(),
|
||||
}));
|
||||
const skill: SkillDetail = {
|
||||
name: "project-review", description: "Review the repository and summarize actionable changes.", source: "builtin", available: true, enabled: true,
|
||||
requirements: { bins: [], env: [], missing_bins: [], missing_env: [] }, raw_markdown: "# Project review\n\nRead the repository instructions before reviewing changes.",
|
||||
};
|
||||
const members: LinearMembersPayload = {
|
||||
session_id: "", status: "members", organization_id: "preview", legacy_allow_all: false,
|
||||
members: names.slice(0, 3).map((_, index) => ({ id: `member-${index}`, name: ["Alex Chen", "Morgan Lee", "Sam Rivera"][index], teams: [], allowed: index === 0 })),
|
||||
};
|
||||
const previewSettings: SettingsPayload = {
|
||||
...settings,
|
||||
advanced: { ...settings.advanced, exec_max_runtime_limit: 86400 },
|
||||
model_presets: [{ name: "default", model: "gpt-5.4", provider: "openai", resolved_provider: "openai", active: true, is_default: true,
|
||||
max_tokens: 8192, context_window_tokens: 200_000, temperature: 0.1, reasoning_effort: null }],
|
||||
model_call_order: ["default"],
|
||||
runtime_config: Object.fromEntries(RUNTIME_CONFIG_FIELDS.map((field) => [field.path,
|
||||
field.kind === "boolean" ? true : field.kind === "toggle" ? field.options?.[1] ?? "" : field.kind === "list" ? [] : field.kind === "number" ? 20 : field.kind === "duration" ? 3600 : "",
|
||||
])),
|
||||
};
|
||||
let detailState = "loaded";
|
||||
|
||||
export function installSkeletonPreviewApi() {
|
||||
const fetch = window.fetch.bind(window);
|
||||
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 fetch(input, init);
|
||||
if ((init?.method ?? "GET") !== "GET") return Response.json({ error: "Read-only preview" }, { status: 403 });
|
||||
if (url.pathname.startsWith("/api/webui/skills/")) {
|
||||
if (detailState === "loading") await new Promise<void>(() => {});
|
||||
return detailState === "error" ? Response.json({ error: "Preview read failed" }, { status: 503 }) : Response.json(skill);
|
||||
}
|
||||
const bodies: Record<string, unknown> = {
|
||||
"/api/settings": previewSettings, "/api/settings/usage": { usage: null },
|
||||
"/api/webui/automations": { jobs }, "/api/settings/nanobot-features": { features: [], enabled_count: 0, requires_restart: false },
|
||||
"/api/settings/cli-apps": { apps: [], installed_count: 0 }, "/api/settings/mcp-presets": { presets: [], installed_count: 0 },
|
||||
"/api/settings/api-service": { installed: false, running: false, managed: false, host: "127.0.0.1", port: 8900, timeout: 120, endpoint: "http://127.0.0.1:8900/v1", command: "nanobot serve" },
|
||||
};
|
||||
return Response.json(bodies[url.pathname] ?? {});
|
||||
};
|
||||
}
|
||||
|
||||
export function SkeletonAdditionsFixture() {
|
||||
return new URLSearchParams(location.search).has("preview") ? <SkeletonPreview /> : <SkeletonSurface />;
|
||||
}
|
||||
|
||||
function SkeletonPreview() {
|
||||
const params = new URLSearchParams(location.search);
|
||||
const [surface, setSurface] = useState(params.get("surface") ?? "chats");
|
||||
const [state, setState] = useState(params.get("state") ?? "loaded");
|
||||
const [section, setSection] = useState<SettingsSectionKey>((params.get("section") ?? "appearance") as SettingsSectionKey);
|
||||
const [density, setDensity] = useState<"compact" | "comfortable">(params.has("compact") ? "compact" : "comfortable");
|
||||
const [dark, setDark] = useState(false);
|
||||
const [language, setLanguage] = useState(document.documentElement.lang);
|
||||
const source = new URLSearchParams({ case: "skeleton-additions", surface, state, section });
|
||||
if (density === "compact") source.set("compact", "");
|
||||
if (dark) source.set("dark", "");
|
||||
const changeLanguage = (next: Parameters<typeof setAppLanguage>[0]) => { void setAppLanguage(next).then(() => setLanguage(next)); };
|
||||
return <div style={{ height: "100dvh", display: "flex", flexDirection: "column" }}>
|
||||
<nav style={{ position: "sticky", top: 0, zIndex: 100, display: "flex", flexWrap: "wrap", alignItems: "center", gap: 12, padding: "12px 16px" }} className="border-b bg-background text-sm" aria-label="Skeleton preview controls">
|
||||
<span className="font-medium">首载骨架验收</span>
|
||||
<select aria-label="Surface" value={surface} onChange={(event) => setSurface(event.target.value)} className="rounded border bg-background p-1">
|
||||
{["chats", "settings", "automations", "skill-detail", "session-jobs", "linear-members"].map((name) => <option key={name}>{name}</option>)}
|
||||
</select>
|
||||
<select aria-label="State" value={state} onChange={(event) => setState(event.target.value)} className="rounded border bg-background p-1">
|
||||
{["loading", "loaded", "refresh", "error"].map((name) => <option key={name}>{name}</option>)}
|
||||
</select>
|
||||
{surface === "settings" ? <select aria-label="Section" value={section} onChange={(event) => setSection(event.target.value as SettingsSectionKey)} className="rounded border bg-background p-1">
|
||||
{["overview", "appearance", "models", "capabilities", "runtime", "advanced", "about", "channels", "apps", "skills", "automations"].map((name) => <option key={name}>{name}</option>)}
|
||||
</select> : null}
|
||||
{surface === "chats" ? <button onClick={() => setDensity(density === "compact" ? "comfortable" : "compact")}>{density}</button> : null}
|
||||
<button onClick={() => { document.documentElement.classList.toggle("dark", !dark); setDark(!dark); }}>{dark ? "浅色" : "深色"}</button>
|
||||
<button onClick={() => changeLanguage("zh-CN")}>中文</button><button onClick={() => changeLanguage("en")}>English</button>
|
||||
<span className="text-xs text-muted-foreground">固定展示状态;仅示例数据,无模型调用</span>
|
||||
</nav>
|
||||
<iframe key={language} title="首载骨架预览" src={`/browser/fixture.html?${source}`} style={{ width: "100%", minHeight: 0, flex: 1, border: 0 }} />
|
||||
</div>;
|
||||
}
|
||||
|
||||
function SkeletonSurface() {
|
||||
const params = new URLSearchParams(location.search);
|
||||
const surface = params.get("surface") ?? "chats";
|
||||
const state = params.get("state") ?? "loaded";
|
||||
const section = (params.get("section") ?? "appearance") as SettingsSectionKey;
|
||||
const density = params.has("compact") ? "compact" : "comfortable";
|
||||
const dark = params.has("dark");
|
||||
useLayoutEffect(() => { document.documentElement.classList.toggle("dark", dark); }, [dark]);
|
||||
const controller = useSettingsController({ initialSection: section, initialSettings: previewSettings, onModelNameChange: noop });
|
||||
detailState = state;
|
||||
const loading = state === "loading" || state === "refresh";
|
||||
const empty = state === "loading" || state === "error";
|
||||
return <div data-testid="skeleton-additions" className="min-h-[85vh] bg-settings-canvas">
|
||||
{surface === "settings" ? <div style={{ minHeight: "85vh" }} className="flex flex-col"><SettingsPage controller={{ ...controller, loading, settings: empty ? null : previewSettings, error: state === "error" ? "Preview read failed" : null,
|
||||
systemState: { ...controller.systemState,
|
||||
cliApps: empty ? null : { apps: [], installed_count: 0 }, cliAppsLoading: loading,
|
||||
mcpPresets: empty ? null : { presets: [], installed_count: 0 }, mcpPresetsLoading: loading,
|
||||
nanobotFeatures: empty ? null : { features: [], enabled_count: 0, requires_restart: false }, nanobotFeaturesLoading: loading,
|
||||
automations: empty ? null : { jobs }, automationsLoading: loading,
|
||||
automationsError: state === "error" ? "Preview read failed" : null,
|
||||
},
|
||||
}}
|
||||
theme={dark ? "dark" : "light"} showSidebar mainNavigationExpanded={false} onToggleTheme={noop} onBackToChat={noop}
|
||||
skills={empty ? [] : [skill]} skillsLoading={loading && empty} skillsError={state === "error"} isRestarting={false} hostChromeInset={false} /></div>
|
||||
: <main className="settings-grid mx-auto w-full p-4" style={surface === "automations" ? { maxWidth: 960 } : undefined}>
|
||||
{surface === "chats" ? <div style={{ height: 440, width: 280, maxWidth: "100%" }} className="bg-sidebar"><ChatList sessions={empty ? [] : sessions} activeKey={null} loading={loading} density={density}
|
||||
onSelect={noop} onRequestDelete={noop} onTogglePin={noop} onToggleArchive={noop} onRequestRename={async () => {}} /></div>
|
||||
: surface === "automations" ? <AutomationsSettings payload={empty ? null : { jobs }} loading={loading} filter="all" actionKey={null} error={state === "error" ? "Preview read failed" : null}
|
||||
onFilterChange={noop} onAction={noop} onRequestEdit={noop} onRequestDelete={noop} />
|
||||
: surface === "skill-detail" ? <SkillsCatalogSettings skills={[skill]} />
|
||||
: surface === "session-jobs" ? <SessionInfoPopoverView title="Project review" jobs={empty ? [] : jobs} loading={loading} loadFailed={state === "error"} now={now}
|
||||
onAction={async () => jobs} onEdit={async () => jobs} />
|
||||
: surface === "linear-members" ? <LinearMemberAccessView snapshot={{ payload: empty ? null : members, loading, error: state === "error" ? "Preview read failed" : null, saves: {} }} onLoad={noop} onSetAllowed={noop} /> : null}
|
||||
</main>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { expect, test, type Locator, type Page } from "@playwright/test";
|
||||
|
||||
const fixture = (surface: string, state = "loaded", extra = "") => `/browser/fixture.html?case=skeleton-additions&surface=${surface}&state=${state}${extra}`;
|
||||
const status = (page: Page) => page.locator('[role="status"][aria-busy="true"]');
|
||||
|
||||
async function settle(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
await document.fonts.ready;
|
||||
await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getTiming().iterations !== Infinity)
|
||||
.map((animation) => animation.finished.catch(() => {})));
|
||||
});
|
||||
}
|
||||
|
||||
async function boxes(locator: Locator) {
|
||||
await expect(locator.first()).toBeVisible();
|
||||
return locator.evaluateAll((elements) => elements.map((element) => {
|
||||
const { x, y, width, height } = element.getBoundingClientRect();
|
||||
return { x, y, width, height };
|
||||
}));
|
||||
}
|
||||
|
||||
function sameBoxes(actual: Awaited<ReturnType<typeof boxes>>, expected: typeof actual) {
|
||||
expect(actual).toHaveLength(expected.length);
|
||||
for (let index = 0; index < actual.length; index++) for (const key of ["x", "y", "width", "height"] as const) {
|
||||
expect(Math.abs(actual[index][key] - expected[index][key]), `row ${index} ${key}`).toBeLessThan(0.5);
|
||||
}
|
||||
}
|
||||
|
||||
async function accessibleSkeleton(page: Page) {
|
||||
await expect(status(page).first()).toBeVisible();
|
||||
expect(await status(page).first().getAttribute("aria-label")).toBeTruthy();
|
||||
await expect(status(page).first().locator(".animate-pulse")).toHaveAttribute("aria-hidden", "true");
|
||||
expect(await status(page).first().locator(".animate-pulse").evaluate((element) => getComputedStyle(element).animationName)).toBe("none");
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
|
||||
}
|
||||
|
||||
for (const width of [390, 1440]) for (const locale of ["en", "zh-CN"]) {
|
||||
test.describe(`${width}px ${locale} new first-load skeletons`, () => {
|
||||
test.use({ viewport: { width, height: 1000 }, reducedMotion: "reduce", hasTouch: width === 390 });
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.addInitScript((language) => localStorage.setItem("nanobot.locale", language), locale);
|
||||
await page.clock.setFixedTime(new Date("2026-10-19T12:00:00Z"));
|
||||
});
|
||||
|
||||
test("sidebar rows preserve comfortable, compact and touch density", async ({ page }) => {
|
||||
for (const extra of ["", "&compact"]) {
|
||||
await page.goto(fixture("chats", "loaded", extra));
|
||||
await settle(page);
|
||||
const loaded = await boxes(page.locator("[data-chat-row]"));
|
||||
await page.goto(fixture("chats", "loading", extra));
|
||||
await settle(page);
|
||||
sameBoxes((await boxes(page.locator("[data-chat-skeleton-row]"))).slice(0, loaded.length), loaded);
|
||||
await accessibleSkeleton(page);
|
||||
}
|
||||
});
|
||||
|
||||
test("settings sections preserve their loaded row layout", async ({ page }) => {
|
||||
for (const section of ["appearance", "capabilities", "runtime", "advanced", "overview", "models", "about"]) {
|
||||
await page.goto(fixture("settings", "loaded", `§ion=${section}`));
|
||||
if (section === "runtime") await expect(page.locator('[data-settings-section] button').filter({ hasText: locale === "en" ? "Start API server" : "启动 API 服务" })).toBeVisible();
|
||||
await settle(page);
|
||||
const target = page.locator("[data-settings-section]");
|
||||
const selector = section === "overview" ? "section button.group" : section === "models" ? '[data-testid^="model-call-order-row"], .settings-footer' : section === "about" ? ".settings-list-row" : ".settings-row";
|
||||
const loaded = await boxes(target.locator(selector));
|
||||
await page.goto(fixture("settings", "loading", `§ion=${section}`));
|
||||
await settle(page);
|
||||
const skeletonSelector = section === "overview" ? "[data-overview-skeleton-row]" : section === "models" ? "[data-model-preset-skeleton], .settings-footer" : section === "about" ? ".settings-list-row" : "[data-settings-skeleton-row]";
|
||||
sameBoxes(await boxes(target.locator(skeletonSelector)), loaded);
|
||||
await accessibleSkeleton(page);
|
||||
}
|
||||
});
|
||||
|
||||
test("calendar and task skeletons retain their toolbar and real date grid", async ({ page }) => {
|
||||
for (const nextMonth of [false, true]) {
|
||||
const open = async (state: string) => {
|
||||
await page.goto(fixture("automations", state));
|
||||
if (nextMonth) await page.getByRole("button", { name: locale === "en" ? "Next month" : "下个月" }).click();
|
||||
await settle(page);
|
||||
};
|
||||
await open("loaded");
|
||||
const toolbar = await boxes(page.locator(".automation-panel-toolbar"));
|
||||
const nav = await boxes(page.locator(".automation-calendar-navigation"));
|
||||
const grid = width === 1440 ? await boxes(page.locator(".automation-calendar-day")) : null;
|
||||
if (grid) expect(grid).toHaveLength(nextMonth ? 42 : 35);
|
||||
const agenda = !nextMonth && width === 390 ? await boxes(page.locator(".automation-calendar-agenda li")) : null;
|
||||
await open("loading");
|
||||
sameBoxes(await boxes(page.locator(".automation-panel-toolbar")), toolbar);
|
||||
sameBoxes(await boxes(page.locator(".automation-calendar-navigation")), nav);
|
||||
if (grid) sameBoxes(await boxes(page.locator(".automation-calendar-day")), grid);
|
||||
if (agenda) sameBoxes(await boxes(page.locator("[data-agenda-skeleton-row]")), agenda);
|
||||
await accessibleSkeleton(page);
|
||||
}
|
||||
await page.goto(fixture("automations"));
|
||||
await page.locator(".automation-view-switch button").first().click();
|
||||
await settle(page);
|
||||
const rows = await boxes(page.locator('section[aria-label] button[aria-haspopup="dialog"]'));
|
||||
await page.goto(fixture("automations", "loading"));
|
||||
await page.locator(".automation-view-switch button").first().click();
|
||||
await settle(page);
|
||||
sameBoxes(await boxes(page.locator("[data-automation-task-skeleton]")), rows);
|
||||
});
|
||||
|
||||
test("skill detail keeps the known summary and matches the toggle and instructions disclosure", async ({ page }) => {
|
||||
const open = async (state: string) => {
|
||||
await page.goto(fixture("skill-detail", state));
|
||||
await page.getByRole("button", { name: locale === "en" ? "Open details for project-review" : "查看 project-review 详情" }).click();
|
||||
await settle(page);
|
||||
};
|
||||
await open("loaded");
|
||||
await expect(page.getByRole("dialog").getByRole("switch")).toBeEnabled();
|
||||
const toggle = await boxes(page.getByRole("dialog").getByRole("switch").locator(".."));
|
||||
const instructions = await boxes(page.getByRole("dialog").getByRole("button", { name: /SKILL.md/ }).locator(".."));
|
||||
const title = await boxes(page.getByRole("dialog").getByRole("heading", { name: "project-review" }));
|
||||
await open("loading");
|
||||
await expect(page.getByRole("dialog").getByText("Review the repository and summarize actionable changes.")).toBeVisible();
|
||||
sameBoxes(await boxes(page.locator("[data-skill-toggle-skeleton]")), toggle);
|
||||
sameBoxes(await boxes(page.locator("[data-skill-instructions-skeleton]")), instructions);
|
||||
sameBoxes(await boxes(page.getByRole("dialog").getByRole("heading", { name: "project-review" })), title);
|
||||
await accessibleSkeleton(page);
|
||||
});
|
||||
|
||||
test("session automation and Linear members keep row and action alignment", async ({ page }) => {
|
||||
for (const surface of ["session-jobs", "linear-members"]) {
|
||||
const open = async (state: string) => {
|
||||
await page.goto(fixture(surface, state));
|
||||
if (surface === "session-jobs") await page.getByRole("button", { name: locale === "en" ? "Session details" : "会话详情" }).click();
|
||||
else await page.locator("button[aria-expanded]").first().click();
|
||||
await settle(page);
|
||||
};
|
||||
await open("loaded");
|
||||
const rows = await boxes(surface === "session-jobs" ? page.getByRole("dialog").locator('button[aria-haspopup="dialog"]') : page.locator(".settings-row"));
|
||||
await open("loading");
|
||||
sameBoxes(await boxes(page.locator(surface === "session-jobs" ? "[data-session-job-skeleton]" : "[data-member-skeleton-row]")), rows);
|
||||
await accessibleSkeleton(page);
|
||||
}
|
||||
});
|
||||
|
||||
test("cached settings and lists stay visible during background refresh", async ({ page }) => {
|
||||
for (const surface of ["settings", "chats", "automations", "session-jobs", "linear-members"]) {
|
||||
await page.goto(fixture(surface, "refresh"));
|
||||
if (surface === "session-jobs") await page.getByRole("button", { name: locale === "en" ? "Session details" : "会话详情" }).click();
|
||||
if (surface === "linear-members") await page.locator("button[aria-expanded]").first().click();
|
||||
await settle(page);
|
||||
await expect(status(page)).toHaveCount(0);
|
||||
await expect(surface === "settings" || surface === "linear-members" ? page.getByRole("switch").first() : page.getByText("Project summary", { exact: true }).first()).toBeVisible();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { FilePreviewPanelView } from "@/components/FilePreviewPanelView";
|
||||
import { SkillsCatalogSettings } from "@/components/settings/SkillsCatalogSettings";
|
||||
import { SkillsMarketplace } from "@/components/settings/SkillsMarketplace";
|
||||
import { ModelIdPicker } from "@/components/settings/shared/ModelControls";
|
||||
import { AppsCatalogSettings, DEFAULT_CUSTOM_MCP_FORM } from "@/components/settings/system/AppsSettings";
|
||||
import { ChannelsSettings } from "@/components/settings/system/ChannelsSettings";
|
||||
import { McpManagementDialog } from "@/components/settings/system/McpManagementDialog";
|
||||
import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";
|
||||
import { settings } from "@/dev/gallery/settings";
|
||||
import { fetchWorkspaceDirectories } from "@/lib/api";
|
||||
import type { McpPresetInfo, NanobotFeatureInfo } from "@/lib/types";
|
||||
|
||||
const noop = () => {};
|
||||
const names = ["Search documentation", "Read repository", "List projects", "Inspect changes", "Review results", "Write notes"];
|
||||
const preset: McpPresetInfo = {
|
||||
name: "docs", display_name: "Docs MCP", category: "Workflow", description: "Search the team knowledge base.",
|
||||
docs_url: "", requires: "", note: "", connection_summary: "https://example.com/mcp",
|
||||
transport: "streamableHttp", install_supported: true, installed: true, configured: true,
|
||||
available: true, status: "configured", required_fields: [], source: "custom",
|
||||
};
|
||||
|
||||
export function SkeletonFixture({ surface, loading }: { surface: string; loading: boolean }) {
|
||||
const [model, setModel] = useState("");
|
||||
const [previewLoading, setPreviewLoading] = useState(loading);
|
||||
const feature: NanobotFeatureInfo = {
|
||||
name: "telegram", display_name: "Telegram", type: "channel", enabled: true, installed: true,
|
||||
configured: true, ready: true, install_supported: true, status: "enabled", requires_restart: false,
|
||||
};
|
||||
return <main className="settings-grid mx-auto w-full max-w-4xl p-4" data-testid="skeleton-fixture">
|
||||
{surface === "workspace" ? <WorkspaceProjectPicker isHero scope={{ project_path: "/srv/workspace", access_mode: "restricted" }}
|
||||
defaultScope={{ project_path: "/srv/workspace", access_mode: "restricted" }}
|
||||
controls={{ can_change_project: true, can_browse_directories: true }}
|
||||
onBrowseDirectories={(path, query, showHidden, allowPartial) => fetchWorkspaceDirectories("fixture", path, query, showHidden, allowPartial)}
|
||||
onChange={noop} /> : surface === "apps" || surface === "cli" ? <AppsCatalogSettings
|
||||
cliApps={{ apps: surface === "cli" && !loading ? names.map((name, index) => ({
|
||||
name: `app-${index}`, display_name: name, category: "Tools", description: "Search and inspect the project.",
|
||||
requires: "", source: "builtin", entry_point: `app-${index}`, install_supported: true, installed: false,
|
||||
available: false, status: "not_installed", skill_installed: false,
|
||||
})) : [], installed_count: 0 }}
|
||||
mcpPresets={loading ? null : { presets: names.map((name, index) => ({ ...preset, name: `docs-${index}`, display_name: name })), installed_count: 6 }}
|
||||
cliAppsLoading={loading} mcpPresetsLoading={loading} query="" filter={surface === "cli" ? "cli" : "mcp"}
|
||||
cliActionKey={null} mcpActionKey={null} mcpOAuthFlow={null} mcpOAuthPopupBlocked={false}
|
||||
mcpOAuthCallbackUrl="" mcpOAuthCompleting={false} mcpOAuthCallbackError={null}
|
||||
cliMessage={null} cliError={null} cliFocusName={null} mcpMessage={null} mcpError={null}
|
||||
mcpFieldValues={{}} customMcpForm={DEFAULT_CUSTOM_MCP_FORM} mcpConfigImport=""
|
||||
showBrandLogos={false} requiresRestartPending={false}
|
||||
onQueryChange={noop} onFilterChange={noop} onCliAction={noop} onMcpAction={noop}
|
||||
onMcpOAuthConnect={noop} onMcpOAuthCancel={noop} onMcpOAuthOpen={noop}
|
||||
onMcpOAuthCallbackUrlChange={noop} onMcpOAuthComplete={noop} onDismissStatus={noop}
|
||||
onBackToChat={noop} onMcpFieldChange={noop} onCustomMcpFormChange={noop}
|
||||
onMcpConfigImportChange={noop} onSaveCustomMcp={noop} onImportMcpConfig={noop} onMcpToolsChange={noop}
|
||||
/> : surface === "channels" ? <ChannelsSettings
|
||||
token="fixture" nanobotFeatures={loading ? null : { features: names.map((name, index) => ({ ...feature, name: `channel-${index}`, display_name: name })), enabled_count: 6, requires_restart: false }}
|
||||
loading={loading} actionKey={null} showBrandLogos={false} error={null} requiresRestartPending={false}
|
||||
onAction={noop} onFeaturesUpdate={noop} onDismissStatus={noop}
|
||||
/> : surface === "skills" ? <SkillsCatalogSettings loading={loading} skills={loading ? [] : names.map((name) => ({
|
||||
name, description: "Search, inspect and maintain the project.", source: "builtin", available: true, enabled: true,
|
||||
}))} /> : surface === "marketplace" ? <SkillsMarketplace installedSkills={[]} installing="" onInstallingChange={noop} />
|
||||
: surface === "models" || surface === "models-compact" ? <ModelIdPicker token="fixture"
|
||||
settings={{ ...settings, providers: settings.providers.map((provider) => provider.name === "openai" ? { ...provider, model_catalog: "official" } : provider) }}
|
||||
provider={surface === "models-compact" ? "openai" : "anthropic"}
|
||||
value={model} showProviderLogos={false} onChange={setModel} />
|
||||
: surface === "tools" ? <McpManagementDialog
|
||||
preset={{ ...preset, tool_names: loading ? [] : names.map((_, index) => `read_project_${index}`), tool_count: loading ? 0 : 6 }}
|
||||
values={{}} actionKey={loading ? "test:docs" : null} statusLabel="Connected" statusTone="success" tab="tools"
|
||||
icon={<span aria-hidden>DM</span>} onTabChange={noop} onOpenChange={noop} onFieldChange={noop}
|
||||
onAction={noop} onOAuthConnect={noop} onToolsChange={noop}
|
||||
/> : surface === "file" || surface === "markdown" ? <div className="flex flex-col" style={{ height: 560 }}><FilePreviewPanelView path={surface === "markdown" ? "/project/README.md" : "/project/main.py"}
|
||||
state={previewLoading ? { status: "loading" } : { status: "ready", payload: {
|
||||
kind: "text", path: surface === "markdown" ? "/project/README.md" : "/project/main.py", display_path: "project file", project_path: "/project", size: 400,
|
||||
language: surface === "markdown" ? "markdown" : "python", truncated: false,
|
||||
content: surface === "markdown" ? "# Project overview\n\nSearch, inspect and maintain the project.\n\nReview the results before making changes." : names.map((name, index) => `value_${index} = ${JSON.stringify(name)}`).join("\n"),
|
||||
} }} imageOpen={false} onImageOpenChange={noop} onImageError={noop} /></div> : null}
|
||||
{surface === "file" || surface === "markdown" ? <button data-testid="reload-preview" style={{ position: "fixed", bottom: 8, left: 8 }} onClick={() => setPreviewLoading(true)}>Reload preview</button> : null}
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { expect, test, type Locator, type Page } from "@playwright/test";
|
||||
|
||||
const fixture = (surface: string, loading = false) => `/browser/fixture.html?case=skeleton&surface=${surface}${loading ? "&loading" : ""}`;
|
||||
const status = (page: Page) => page.locator('[role="status"][aria-busy="true"]');
|
||||
const catalogRows = {
|
||||
channels: [".settings-list-row", ".settings-list-row"],
|
||||
apps: ["article > .group", ".px-3.py-3"],
|
||||
cli: [".apps-catalog-row", ".px-3.py-3"],
|
||||
skills: ["button:has(h3)", ".px-2.py-3"],
|
||||
};
|
||||
|
||||
async function settle(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
await document.fonts.ready;
|
||||
await Promise.all(document.getAnimations()
|
||||
.filter((animation) => animation.effect?.getTiming().iterations !== Infinity)
|
||||
.map((animation) => animation.finished.catch(() => {})));
|
||||
});
|
||||
}
|
||||
|
||||
async function box(locator: Locator) {
|
||||
await expect(locator).toBeVisible();
|
||||
return (await locator.boundingBox())!;
|
||||
}
|
||||
|
||||
function sameBox(actual: { x: number; y: number; width: number; height: number }, expected: typeof actual) {
|
||||
for (const key of ["x", "y", "width", "height"] as const) {
|
||||
expect(Math.abs(actual[key] - expected[key]), key).toBeLessThan(0.5);
|
||||
}
|
||||
}
|
||||
|
||||
async function noOverflow(page: Page) {
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
|
||||
}
|
||||
|
||||
const marketplaceSkills = ["skills_sh", "skillhub"].flatMap((provider) => Array.from({ length: 5 }, (_, index) => ({
|
||||
id: `${provider}:project-${index}`, skill_id: `project-${index}`, name: `Project Skill ${index + 1}`,
|
||||
source: "team/project-skills", provider, installs: 200, url: "https://example.com/skill",
|
||||
installed: false, install_supported: true, metric: "installs_total", rank: index + 1,
|
||||
})));
|
||||
|
||||
for (const width of [390, 1440]) {
|
||||
for (const locale of ["en", "zh-CN"]) {
|
||||
test.describe(`${width}px ${locale}`, () => {
|
||||
test.use({ viewport: { width, height: 900 }, reducedMotion: "reduce", hasTouch: width === 390 });
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.addInitScript((language) => localStorage.setItem("nanobot.locale", language), locale);
|
||||
});
|
||||
|
||||
test("catalog skeletons preserve loaded row, icon, title and action geometry", async ({ page }) => {
|
||||
for (const [surface, [loadedSelector, loadingSelector]] of Object.entries(catalogRows)) {
|
||||
await page.goto(fixture(surface));
|
||||
const loaded = page.locator(loadedSelector).first();
|
||||
const row = await box(loaded);
|
||||
const icon = await box(surface === "channels" ? loaded.locator('[data-testid^="channel-logo"]') : loaded.locator(":scope > :first-child"));
|
||||
const title = await box(loaded.locator("h3"));
|
||||
const action = width === 1440 || surface !== "skills" ? await box(loaded.locator(":scope > :last-child")) : null;
|
||||
await page.goto(fixture(surface, true));
|
||||
const skeleton = status(page).locator(loadingSelector).first();
|
||||
sameBox(await box(skeleton), row);
|
||||
sameBox(await box(skeleton.locator(":scope > :first-child")), icon);
|
||||
const placeholder = await box(skeleton.locator(":scope > :nth-child(2) [class*='bg-muted-foreground']").first());
|
||||
expect(placeholder.x).toBe(title.x);
|
||||
expect(placeholder.y + placeholder.height / 2).toBe(title.y + title.height / 2);
|
||||
if (action) sameBox(await box(skeleton.locator(":scope > :last-child")), action);
|
||||
await noOverflow(page);
|
||||
}
|
||||
});
|
||||
|
||||
test("marketplace skeletons preserve groups, ranks and provider-specific trend columns", async ({ page }) => {
|
||||
let release = () => {};
|
||||
let pending: Promise<void> | undefined;
|
||||
await page.route("**/api/webui/skills/trending?**", async (route) => {
|
||||
await pending;
|
||||
await route.fulfill({ json: { period: "mixed", provider: "all", install_supported: true, skills: marketplaceSkills } });
|
||||
});
|
||||
await page.route("**/api/webui/skills/search?**", async (route) => {
|
||||
await pending;
|
||||
await route.fulfill({ json: { query: "project", provider: "all", install_supported: true,
|
||||
skills: marketplaceSkills.map((skill) => ({ ...skill, rank: undefined })) } });
|
||||
});
|
||||
await page.route("**/api/webui/skills/trends?**", (route) => route.fulfill({ json: { trends: {} } }));
|
||||
for (const view of ["grouped", "single", "search"]) {
|
||||
const open = async () => {
|
||||
await page.goto(fixture("marketplace"));
|
||||
if (view === "single") await page.getByRole("tab", { name: "skills.sh", exact: true }).click();
|
||||
if (view === "search") await page.locator("input").fill("project");
|
||||
};
|
||||
await open();
|
||||
const loaded = page.locator(".group.py-3\\.5");
|
||||
await expect(loaded).toHaveCount(view === "single" ? 5 : 10);
|
||||
const rows = await loaded.evaluateAll((elements) => elements.map((element) => {
|
||||
const r = element.getBoundingClientRect();
|
||||
const text = element.querySelector("h3")!.parentElement!.parentElement!.getBoundingClientRect();
|
||||
return { row: { x: r.x, y: r.y, width: r.width, height: r.height }, text: { x: text.x, width: text.width } };
|
||||
}));
|
||||
pending = new Promise<void>((resolve) => { release = resolve; });
|
||||
try {
|
||||
await open();
|
||||
const skeletons = status(page).locator(".py-3\\.5");
|
||||
await expect(skeletons).toHaveCount(rows.length);
|
||||
for (let index = 0; index < rows.length; index++) {
|
||||
sameBox(await box(skeletons.nth(index)), rows[index].row);
|
||||
const text = await box(skeletons.nth(index).locator(".flex-1"));
|
||||
expect(text.x).toBe(rows[index].text.x);
|
||||
expect(text.width).toBe(rows[index].text.width);
|
||||
}
|
||||
await noOverflow(page);
|
||||
} finally { release(); pending = undefined; }
|
||||
await page.goto("about:blank");
|
||||
}
|
||||
});
|
||||
|
||||
test("model catalog skeletons follow single-line official and two-line managed options", async ({ page }) => {
|
||||
let release = () => {};
|
||||
let pending: Promise<void> | undefined;
|
||||
await page.route("**/api/settings/provider-models?**", async (route) => {
|
||||
await pending;
|
||||
const provider = new URL(route.request().url()).searchParams.get("provider");
|
||||
await route.fulfill({ json: { provider, status: "available", source: "api", catalog_kind: "live",
|
||||
models: [0, 1, 2].map((index) => ({ id: `project-${index}`,
|
||||
...(provider === "anthropic" ? { label: `Project ${index}`, description: "Code assistance" } : {}) })) } });
|
||||
});
|
||||
for (const surface of ["models", "models-compact"]) {
|
||||
await page.goto(fixture(surface));
|
||||
await page.getByRole("combobox").click();
|
||||
const loaded = page.getByRole("option").first();
|
||||
await expect(loaded).toBeVisible();
|
||||
await settle(page);
|
||||
const row = await box(loaded);
|
||||
const icon = await box(loaded.locator(":scope > :first-child > :first-child"));
|
||||
pending = new Promise<void>((resolve) => { release = resolve; });
|
||||
try {
|
||||
await page.goto(fixture(surface));
|
||||
await page.getByRole("combobox").click();
|
||||
await expect(status(page)).toBeVisible();
|
||||
await settle(page);
|
||||
const skeleton = status(page).locator(".px-2.py-1\\.5").first();
|
||||
sameBox(await box(skeleton), row);
|
||||
sameBox(await box(skeleton.locator(":scope > :first-child")), icon);
|
||||
await noOverflow(page);
|
||||
} finally { release(); pending = undefined; }
|
||||
await page.goto("about:blank");
|
||||
}
|
||||
});
|
||||
|
||||
test("MCP tools preserve the localized toolbar and checkbox rows", async ({ page }) => {
|
||||
await page.goto(fixture("tools"));
|
||||
const loaded = page.getByRole("tabpanel");
|
||||
await expect(loaded.getByRole("checkbox")).toHaveCount(6);
|
||||
await settle(page);
|
||||
const row = await box(loaded.locator("label:has(input[type=checkbox])").first());
|
||||
const search = await box(loaded.locator("input:not([type=checkbox])"));
|
||||
await page.goto(fixture("tools", true));
|
||||
await expect(status(page)).toBeVisible();
|
||||
await settle(page);
|
||||
sameBox(await box(status(page).locator(".min-h-11").first()), row);
|
||||
sameBox(await box(status(page).locator("[aria-hidden] > .flex > :first-child")), search);
|
||||
await noOverflow(page);
|
||||
});
|
||||
|
||||
test("directory loading preserves the centered whole-row viewport and scrollbar gutter", async ({ page }) => {
|
||||
let release = () => {};
|
||||
let blocked = false;
|
||||
const pending = new Promise<void>((resolve) => { release = resolve; });
|
||||
await page.route("**/api/workspaces/directories?**", async (route) => {
|
||||
if (blocked) await pending;
|
||||
const directory = new URL(route.request().url()).searchParams.get("path")!;
|
||||
await route.fulfill({ json: { path: directory, parent: "/srv", host: "dev-server", platform: "Linux", truncated: false,
|
||||
entries: Array.from({ length: 30 }, (_, index) => ({ name: `project-${index}`, path: `${directory}/project-${index}` })) } });
|
||||
});
|
||||
const open = async () => {
|
||||
await page.goto(fixture("workspace"));
|
||||
await page.getByTestId("skeleton-fixture").getByRole("button").first().click();
|
||||
};
|
||||
await open();
|
||||
await expect(page.getByRole("option").first()).toBeVisible();
|
||||
await settle(page);
|
||||
const row = await box(page.getByRole("option").first());
|
||||
blocked = true;
|
||||
try {
|
||||
await open();
|
||||
await expect(page.locator(".workspace-directory-loading")).toBeVisible();
|
||||
await settle(page);
|
||||
sameBox(await box(page.locator(".workspace-directory-loading [aria-hidden] > div").first()), row);
|
||||
await noOverflow(page);
|
||||
} finally { release(); }
|
||||
});
|
||||
|
||||
test("file preview skeletons follow code gutters and Markdown controls", async ({ page }) => {
|
||||
await page.goto(fixture("file"));
|
||||
await expect(page.getByTestId("viewport-code-rows")).toBeVisible();
|
||||
const source = await box(page.locator("pre"));
|
||||
const code = await box(page.locator("[data-highlighted]"));
|
||||
await page.goto(fixture("file", true));
|
||||
sameBox(await box(status(page).locator(".font-mono")), source);
|
||||
const line = await box(status(page).locator(".font-mono > div > :last-child").first());
|
||||
expect(line.x).toBe(code.x);
|
||||
await noOverflow(page);
|
||||
await page.goto(fixture("markdown"));
|
||||
const heading = await box(page.getByRole("heading", { name: "Project overview" }));
|
||||
const controls = await box(page.getByTestId("file-preview-panel").locator(":scope > div").first());
|
||||
await page.goto(fixture("markdown", true));
|
||||
sameBox(await box(status(page).locator("[aria-hidden] > .flex").first()), controls);
|
||||
const title = await box(status(page).locator(".h-7 > div"));
|
||||
expect(title.x).toBe(heading.x);
|
||||
expect(title.y + title.height / 2).toBe(heading.y + heading.height / 2);
|
||||
await noOverflow(page);
|
||||
await page.goto(fixture("markdown"));
|
||||
await expect(page.getByRole("heading", { name: "Project overview" })).toBeVisible();
|
||||
await page.getByTestId("file-preview-panel").locator(".segmented-control button").nth(1).click();
|
||||
await expect(page.getByTestId("viewport-code-rows")).toBeVisible();
|
||||
const markdownSource = await box(page.locator("pre"));
|
||||
await page.getByTestId("reload-preview").click();
|
||||
const markdownLoading = await box(status(page).locator(".font-mono"));
|
||||
for (const key of ["x", "y", "width"] as const) expect(markdownLoading[key]).toBe(markdownSource[key]);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
for (const width of [412, 1440]) {
|
||||
test.describe(`${width}px document startup skeleton`, () => {
|
||||
test.use({ viewport: { width, height: 922 }, reducedMotion: "reduce" });
|
||||
for (const surface of ["skills", "apps", "channels", "automations", "settings", "chat"]) {
|
||||
test(`${surface} paints before the application and stylesheet download`, async ({ page }) => {
|
||||
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
|
||||
// Neither React nor the app stylesheet may supply this first paint.
|
||||
await page.route(/\/(?:src\/main\.tsx|assets\/index-[^/]+\.(?:js|css))$/, (route) => route.abort());
|
||||
await page.goto(`/#/${surface === "chat" ? "chat/websocket%3Aexample" : surface}`, { waitUntil: "domcontentloaded" });
|
||||
const shell = page.locator(".startup-shell");
|
||||
await expect(shell).toHaveAttribute("data-startup-surface", surface);
|
||||
await expect(shell).toHaveAttribute("aria-busy", "true");
|
||||
await expect(shell.locator(surface === "chat" ? ".startup-composer" : ".startup-page")).toBeVisible();
|
||||
const blocks = shell.locator(".startup-block:visible");
|
||||
expect(await blocks.count()).toBeGreaterThan(5);
|
||||
const box = await blocks.first().boundingBox();
|
||||
expect(box!.width).toBeGreaterThan(0);
|
||||
expect(box!.height).toBeGreaterThan(0);
|
||||
expect(await blocks.first().evaluate((element) => getComputedStyle(element).backgroundColor)).not.toBe("rgba(0, 0, 0, 0)");
|
||||
expect(await shell.getByRole("button").count()).toBe(0);
|
||||
expect(await shell.getByRole("textbox").count()).toBe(0);
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
|
||||
const status = shell.getByRole("status");
|
||||
await expect(status).toHaveText("Loading nanobot…");
|
||||
expect(await status.evaluate((element) => element.getBoundingClientRect().width)).toBe(1);
|
||||
});
|
||||
}
|
||||
|
||||
test("restores a collapsed sidebar and the settings-section alias before React", async ({ page }) => {
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem("nanobot-webui.sidebar", "0");
|
||||
localStorage.setItem("nanobot-webui.theme", "dark");
|
||||
localStorage.setItem("nanobot.locale", "zh-CN");
|
||||
});
|
||||
await page.route("**/src/main.tsx", (route) => route.abort());
|
||||
await page.goto("/#/settings?section=skills");
|
||||
const shell = page.locator(".startup-shell");
|
||||
await expect(shell).toHaveAttribute("data-startup-surface", "skills");
|
||||
await expect(shell).toHaveAttribute("data-sidebar-expanded", "false");
|
||||
await expect(shell.getByRole("status")).toHaveText("正在加载 nanobot…");
|
||||
await expect(page.locator("html")).toHaveClass(/dark/);
|
||||
if (width === 1440) expect((await shell.locator(".startup-navigation").boundingBox())!.width).toBe(56);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user