import { expect, type Page, type TestInfo } from "@playwright/test"; import fs from "node:fs"; import path from "node:path"; /** * Shared helpers for the deployed-site functional suite. * * Everything here asserts through the DOM and the engine's public status * elements, so the specs run against the built bundle (no `import("/src/...")`, * which only exists on a Vite dev server). */ export const REPO_ROOT = path.resolve(import.meta.dirname, "../../../.."); export function reportDir(): string { const explicit = process.env.DEPLOYED_REPORT_DIR; if (explicit) return explicit; const day = new Date().toISOString().slice(0, 10).replaceAll("-", ""); return path.join(REPO_ROOT, `tests/golden/DEPLOYED-FUNCTIONAL-${day}`); } /** `[ch07] ...` in the test title is the manual chapter a case walks. */ export function caseId(testInfo: TestInfo): string { const tag = /\[([a-z0-9][a-z0-9-]*)\]/.exec(testInfo.title); return tag?.[1] ?? testInfo.title.replace(/[^\w.-]+/g, "-").replace(/^-|-$/g, "").slice(0, 72); } export async function gotoApp(page: Page, mode: "web" | "native" = "web"): Promise { /* The shared page already holds the compiled engine. Re-navigating restarts * it (and left the engine status empty while it came back), so only navigate * when the entry actually changes. */ const current = new URL(page.url()); const origin = new URL(process.env.WEB_ORIGIN ?? "https://49.232.250.35:58014").origin; const modeMatches = mode === "web" ? current.searchParams.get("ui") === "web" : !current.searchParams.has("ui"); const hasApp = await page.locator("main.blender-app").count() > 0; if (current.origin === origin && modeMatches && hasApp) return; await page.goto(mode === "web" ? "/?ui=web" : "/", { waitUntil: "domcontentloaded", timeout: 20_000 }); await page.locator("main.blender-app").waitFor({ timeout: 20_000 }); } /** * The first load of the deployed bundle pulls a ~300 MB wasm module; the * repository's own deployed checks wait up to 300 s for the same state. * * Boot and scene are two different states: at startup the engine opens the * built-in General template and reports `new General project`; `SceneIR rN` * appears once a project is actually opened. Waiting for SceneIR right after * boot blocks forever. */ export async function waitEngineBoot(page: Page, timeout = 30_000): Promise { await page.waitForFunction(() => document.body.innerText.includes("WASM ABI: ready"), undefined, { timeout }); await expect(page.getByTestId("engine-status")).not.toHaveText(/starting/i, { timeout }); return (await page.getByTestId("engine-status").innerText()).trim(); } export async function waitEngineReady(page: Page, timeout = 30_000): Promise { await expect(page.getByTestId("engine-status")).toContainText(/SceneIR r\d+/, { timeout }); return (await page.getByTestId("engine-status").innerText()).trim(); } /** * The deployed app opens a built-in "General" template on startup, and that * open can land AFTER the file the user picked, silently replacing it with the * 3-object template. Waiting for an object count alone is therefore a race; a * project is considered open only once its active object and object count stay * put for a couple of polls. */ export async function waitSceneStable( page: Page, expected: { objects: number; active?: RegExp }, timeout = 30_000, ): Promise { let last = ""; let streak = 0; const deadline = Date.now() + timeout; while (Date.now() < deadline) { const text = await page.getByTestId("scene-stats").innerText().catch(() => ""); const objects = Number(text.match(/Objects (\d+)/)?.[1] ?? -1); const active = /Active ([^·]+?) ·/.exec(text)?.[1]?.trim() ?? ""; const matches = objects === expected.objects && (!expected.active || expected.active.test(active)); streak = matches && text === last ? streak + 1 : matches ? 1 : 0; last = text; if (streak >= 4) return text.trim(); await page.waitForTimeout(500); } throw new Error(`scene did not settle at Objects ${expected.objects}${expected.active ? ` / ${expected.active}` : ""}; last was "${last}"`); } /** The 保存当前工程的修改? prompt blocks scripted opens; open it discarded. */ export async function dismissReplacementPrompt(page: Page): Promise { const discard = page.getByRole("button", { name: "不保存,继续", exact: true }); const save = page.getByRole("button", { name: "保存后继续", exact: true }); for (let attempt = 0; attempt < 20; attempt += 1) { if (await discard.isVisible().catch(() => false)) { await discard.click(); return; } if (await save.isVisible().catch(() => false)) { await save.click(); return; } await page.waitForTimeout(250); } } /** Boot, then open a project and wait until its scene has settled. */ export async function openProject( page: Page, absolutePath: string, expected?: { objects: number; active?: RegExp }, timeout = 30_000, ): Promise { await waitEngineBoot(page, timeout); await openBlend(page, absolutePath); await dismissReplacementPrompt(page).catch(() => undefined); /* engine-status also carries transient mode/error text ("模式:Object", * "Command failed"), so `SceneIR rN` there is not a stable proof that the * project opened. When the caller states the expected scene, the settled * scene-stats line is the stronger evidence; keep SceneIR only as the * fallback for callers that do not. */ if (expected) await waitSceneStable(page, expected, timeout); else await waitEngineReady(page, timeout); await recoverOutlinerRows(page); return (await page.getByTestId("engine-status").innerText()).trim(); } /** * Opening a project right after an edit-mode session can leave the native * Outliner with an empty row list although the scene has objects (diagnosed * with ch11 -> ch12; the scene-stats line shows the fresh project while the * tree only carries the collection row). The product ships a 「刷新大纲树」 * entry for exactly this context; use it once, and record whether it recovered * the rows instead of silently waiting on a tree that will never fill. */ export async function recoverOutlinerRows(page: Page, timeout = 8_000): Promise { /* The product-side fix (an OUTLINER_REFRESH after a successful open) was * proven with ch11 -> ch12 on release …-uifix2, so the workaround is off by * default: a missing row list must fail loudly. Opt in only when pinning an * older release that predates the fix. */ if (process.env.DEPLOYED_OUTLINER_RECOVERY !== "1") return 0; const rows = page.locator('.outliner-area [role="tree"][aria-label="场景层级"] [role="treeitem"]'); const count = await rows.count().catch(() => 0); if (count > 1) return count; const refresh = page.locator('.outliner-area [aria-label="刷新大纲树"]'); if (await refresh.count() === 0) return count; await refresh.first().dispatchEvent("click").catch(() => undefined); const deadline = Date.now() + timeout; while (Date.now() < deadline) { const next = await rows.count().catch(() => 0); if (next > 1) return next; await page.waitForTimeout(250); } return await rows.count().catch(() => 0); } export async function openBlend(page: Page, absolutePath: string): Promise { await page.getByTestId("blend-file-input").setInputFiles(absolutePath); } /** Object count must also hold still, so a late template open cannot satisfy it. */ export async function waitForObjects(page: Page, count: number, timeout = 20_000): Promise { await waitSceneStable(page, { objects: count }, timeout); } export async function sceneStats(page: Page): Promise { return (await page.getByTestId("scene-stats").innerText()).trim(); } /** Named evidence image, kept beside the report it belongs to. */ export async function shot(page: Page, testInfo: TestInfo, name: string): Promise { const dir = path.join(reportDir(), "screenshots"); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${caseId(testInfo)}-${name}.png`); await page.screenshot({ path: file, fullPage: false }); return path.relative(REPO_ROOT, file); } /** One JSON receipt per case: what was walked, what was seen, where the images are. */ export function receipt(testInfo: TestInfo, data: Record): void { const dir = path.join(reportDir(), "receipts"); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${caseId(testInfo)}.json`); fs.writeFileSync(file, JSON.stringify({ schemaVersion: 1, browser: "chromium-headed", storage: "OPFS", caseId: caseId(testInfo), title: testInfo.title, origin: process.env.WEB_ORIGIN ?? "https://49.232.250.35:58014", acceptance: "NOT_CLAIMED", ...data, }, null, 2)); } /** * Browser-mode saves go to OPFS and nowhere else. Returns the project ids the * origin currently stores, so a case can prove a save happened without * downloading anything. */ export async function opfsProjectIds(page: Page): Promise { return page.evaluate(async () => { try { const root = await navigator.storage.getDirectory(); const projects = await root.getDirectoryHandle("projects"); const ids: string[] = []; for await (const [name] of (projects as unknown as AsyncIterable<[string, FileSystemHandle]>)) ids.push(name); return ids.sort(); } catch { return []; } }); } export async function clearOPFS(page: Page): Promise { await page.evaluate(async () => { try { const root = await navigator.storage.getDirectory(); for await (const [name] of (root as unknown as AsyncIterable<[string, FileSystemHandle]>)) { await root.removeEntry(name, { recursive: true }); } } catch { /* a fresh context has nothing to clear */ } }); } /** * Bring the app back to a neutral state before a case runs. * * The suite shares one persistent browser profile, so layout and preference * changes survive between cases (that is what makes it fast). A case that walks * area splitting must therefore start from the built-in layout, and any dialog * left open by a previous, interrupted case must not swallow its clicks. */ export async function normalizeApp(page: Page): Promise { const app = page.locator("main.blender-app"); if (await app.count() === 0) return; await page.keyboard.press("Escape").catch(() => undefined); const preferences = page.getByTestId("preferences-window"); if (await preferences.isVisible().catch(() => false)) { await page.getByRole("button", { name: "关闭偏好设置", exact: true }).click().catch(() => undefined); } /* Test-scoped: keep it well inside the one-minute case budget. */ await ensureDefaultLayout(page, 10_000).catch(() => undefined); } /** * The saved layout is restored from OPFS a moment after boot, so a check that * runs immediately can still see `default` and then watch it turn `custom`. * Wait for the built-in four-area grid, resetting a custom layout if one is * actually applied. */ export async function ensureDefaultLayout(page: Page, timeout = 20_000): Promise { const app = page.locator("main.blender-app"); const grid = page.locator(".workspace-grid"); const deadline = Date.now() + timeout; let custom = false; let frames = 0; while (Date.now() < deadline) { custom = (await app.getAttribute("data-area-layout")) === "custom"; frames = await grid.locator(":scope > .area-frame").count(); if (!custom && frames === 4) return; if (custom) await resetAreaLayout(page).catch(() => undefined); await page.waitForTimeout(400); } throw new Error(`layout did not settle to the built-in four areas (custom=${custom}, frames=${frames})`); } /** * 区域 ⋮ → 重置工作区布局. * * In the deployed build some area switchers are overlapped by neighbouring * chrome, and a split can place a frame partly off-screen, so the trigger is * activated through the DOM (the same handler the button runs) instead of * relying on hit-testing. Recorded as a UI gap in the status doc. */ export async function resetAreaLayout(page: Page, timeout = 15_000): Promise { const triggers = page.locator(".workspace-grid .area-type-switch .area-menu button"); const count = await triggers.count(); for (let index = 0; index < count; index += 1) { await triggers.nth(index).dispatchEvent("click").catch(() => undefined); const reset = page.getByRole("menuitem", { name: "重置工作区布局", exact: true }); if (await reset.count()) { await reset.click({ force: true, timeout }); return; } await page.keyboard.press("Escape").catch(() => undefined); } throw new Error("no area menu exposed 重置工作区布局"); } export const FIXTURES = { studio: path.join(REPO_ROOT, "web/app/public/tutorial/pbr/studio.blend"), basic: path.join(REPO_ROOT, "tests/files/web/basic_scene.blend"), monkey: path.join(REPO_ROOT, "re/猴头.glb"), empty: path.join(REPO_ROOT, "tests/files/web/empty.blend"), nla: path.join(REPO_ROOT, "tests/files/web/nla_time_mapping_scene.blend"), };