Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 单页验证对照、交互检查与发布目标
Chris1259615c921e
diff --git a/apps/desktop/scripts/ui-page/README.md b/apps/desktop/scripts/ui-page/README.mdindex da25548f07..11dbbc32f2 100644--- a/apps/desktop/scripts/ui-page/README.md+++ b/apps/desktop/scripts/ui-page/README.md@@ -46,7 +46,7 @@ FAIL group-chat.no-sidebar.dark.zh-CN.1280x800- 证据目录只保留最近 20 次运行;`summary.json` 有每个变体的截图、错误、警告、耗时、宿主缺失接口和 Electron/Chromium 版本,`--json` 直接输出它。-每个变体都会自动检查,出现以下情况判为失败:+每次截图(`initial`、`check` 里的 `ui.capture`、`final`)时都会自动检查,出现以下情况判为失败:- 页面报错、控制台 error、尝试访问测试源以外的网络;- 横向溢出;@@ -60,7 +60,7 @@ FAIL group-chat.no-sidebar.dark.zh-CN.1280x800`--changed` 读取相对上游主干的改动(含未提交和未跟踪文件),选出真实加载了这些文件的页面,默认跑全部场景:-- `loaded` 文件被某页面加载。加载不等于被渲染到,具体分支是否出现取决于场景。+- `loaded` 文件被某页面加载;全局样式及其引入的样式文件、Tailwind 配置算作每个页面都加载。加载不等于被渲染到,具体分支是否出现取决于场景。- `STUBBED` 文件在该页面里被替换,等于没验证。- `UNCOVERED` 是 renderer 里没有任何页面加载的界面文件,**未被验证**:补一个场景、用`--entry` 临时挂载,或在完整 Desktop 里验收。@@ -120,15 +120,20 @@ export default {import { AppFrame, ctx, forbid, mountPage, subscription } from '../../ui-page/harness';mountPage({- route: '/bots/group/fixture-group', // 可选:MemoryRouter 初始地址- host: (ctx) => ({ // window.electronAPI 的场景数据+ route: '/bots/group/fixture-group', // 可选:MemoryRouter 初始地址+ host: (ctx) => ({+ // window.electronAPI 的场景数据maker: {getBotGroup: async () => groupFrom(ctx.data),onBotGroupChanged: subscription('botGroupChanged'),sendBotGroupMessage: forbid('maker.sendBotGroupMessage'),},}),- render: (ctx) => <AppFrame><BotGroupChatView /></AppFrame>,+ render: (ctx) => (+ <AppFrame>+ <BotGroupChatView />+ </AppFrame>+ ),});```@@ -142,7 +147,7 @@ mountPage({3. **模块替换(`stubs`)**,只在 store 或 hook 无法经宿主接口喂数据时使用。键是相对`apps/desktop` 的模块路径(不带扩展名):- 字符串:整个模块换成这段代码;- - `{ file: './x.ts' }`:换成场景目录下的文件;+ - 以 `./` 或 `../` 开头的字符串(如 `'./x.ts'`):换成场景目录下的这个文件;- `{ partial: '…' }`:保留真实模块,只覆盖其中几个导出。被替换的模块会列在报告的 `replaced` 里,不算被验证。@@ -175,8 +180,9 @@ mountPage({ cases: ['off', 'on'], render: (ctx) => <Switch checked={ctx.case ===## 改前/改后对照-`--compare [<ref>]` 把本页面加载的产品源码(`apps/desktop/src`、`packages`)换回 `<ref>` 的-版本再渲染一次;不写 `<ref>` 时用本分支与上游主干的分叉点,也就是“本分支改动之前”。场景与+`--compare [<ref>]` 把本页面加载的产品源码、样式与翻译(`apps/desktop/src`、`packages` 下的+脚本、CSS、JSON,含全局样式)换回 `<ref>` 的版本再渲染一次,此后移动或删除的文件也按 `<ref>`+补回;不写 `<ref>` 时用本分支与上游主干的分叉点,也就是“本分支改动之前”。场景与harness 始终用当前版本,所以两边执行同样的步骤、截同样的图。没有文件不同时不重复渲染。改前一侧的断言失败不影响结果,在报告里以 `before <ref>:` 开头逐条列出;`<ref>` 之后才新增的文件按当前版本使用并列出。diff --git a/apps/desktop/scripts/ui-page/build.mjs b/apps/desktop/scripts/ui-page/build.mjsindex ac85b6f14d..f569ece219 100644--- a/apps/desktop/scripts/ui-page/build.mjs+++ b/apps/desktop/scripts/ui-page/build.mjs@@ -22,6 +22,10 @@ const assetLoaders = Object.fromEntries(]),);const SOURCE = /\.[cm]?[jt]sx?$/;+// Inputs `--compare` can take from another revision: source, styles and translations.+const OVERLAY = /\.(?:[cm]?[jt]sx?|css|json)$/;+const loaderFor = (file) =>+ file.endsWith('.css') ? 'css' : file.endsWith('.json') ? 'json' : /x$/.test(file) ? 'tsx' : 'ts';const CONTENT_TYPES = {'.js': 'text/javascript','.css': 'text/css',@@ -92,7 +96,11 @@ function boundaries(stubs, replaced, overlay) {candidate = path.resolve(args.resolveDir, args.path);if (!candidate) return undefined;const stub = stubs.get(withoutExtension(candidate));- if (!stub) return undefined;+ if (!stub) {+ // --compare: a file the old revision imports but the worktree no longer has.+ const old = overlay?.resolve(candidate);+ return old ? { path: old } : undefined;+ }const importers = (replaced[stub.key] ??= { kind: stub.kind, importers: [] }).importers;const importer = path.relative(desktop, args.importer);if (!importers.includes(importer)) importers.push(importer);@@ -109,15 +117,13 @@ function boundaries(stubs, replaced, overlay) {}: { contents: stub.code, loader: 'tsx', resolveDir: desktop };});- if (overlay?.size)- build.onLoad({ filter: SOURCE }, (args) =>- overlay.has(args.path)- ? {- contents: overlay.get(args.path),- loader: /x$/.test(args.path) ? 'tsx' : 'ts',- }- : undefined,- );+ if (overlay)+ build.onLoad({ filter: OVERLAY }, (args) => {+ const contents = overlay.get(args.path);+ return contents === undefined+ ? undefined+ : { contents, loader: loaderFor(args.path), resolveDir: path.dirname(args.path) };+ });},};}@@ -157,7 +163,38 @@ const common = (definition, plugins) => ({plugins,});-/** Source inputs only (no CSS); used to decide which pages load a changed file. */+const globalsPath = path.join(renderer, 'styles/globals.css');+const configPath = path.join(desktop, 'tailwind.config.ts');++/** Stylesheets every page is built with (globals.css and its imports) and the Tailwind config. */+let sharedStyles;+async function sharedStyleInputs() {+ sharedStyles ??= esbuild+ .build({+ absWorkingDir: root,+ bundle: true,+ write: false,+ metafile: true,+ outdir,+ loader: assetLoaders,+ logLevel: 'silent',+ stdin: {+ contents: await readFile(globalsPath, 'utf8'),+ loader: 'css',+ resolveDir: path.dirname(globalsPath),+ },+ })+ .then((result) => [+ globalsPath,+ configPath,+ ...Object.keys(result.metafile.inputs)+ .filter((file) => file !== '<stdin>')+ .map(sourcePath),+ ]);+ return sharedStyles;+}++/** Everything a page is built from; used to decide which pages a changed file affects. */export async function scanPage(definition) {const replaced = {};const { contents } = entryContents(definition);@@ -167,16 +204,20 @@ export async function scanPage(definition) {entryNames: 'page',});return {- inputs: Object.keys(result.metafile.inputs)- .filter((file) => !file.startsWith('ui-stub:') && file !== 'ui-page-entry.ts')- .map(sourcePath),+ inputs: [+ ...Object.keys(result.metafile.inputs)+ .filter((file) => !file.startsWith('ui-stub:') && file !== 'ui-page-entry.ts')+ .map(sourcePath),+ ...(await sharedStyleInputs()),+ ],replaced,};}/*** Builds the selected page from current source every time (no cached bundle).- * `overlay` maps absolute source paths to replacement contents (used by --compare).+ * `overlay` (--compare) supplies another revision's contents: `has(file)`, `get(file)` and+ * `resolve(path)` for files that revision imports but the worktree no longer has.*/export async function buildPage(definition, overlay) {const replaced = {};@@ -190,7 +231,6 @@ export async function buildPage(definition, overlay) {.filter((file) => !file.startsWith('ui-stub:') && file !== 'ui-page-entry.ts').map(sourcePath);// Tailwind scans exactly the imported source (and overlay text in compare mode).- const configPath = path.join(desktop, 'tailwind.config.ts');const config = loadConfig(configPath);const scanned = inputs.filter((file) => !file.includes(`${path.sep}node_modules${path.sep}`) && SOURCE.test(file),@@ -201,12 +241,12 @@ export async function buildPage(definition, overlay) {.filter((file) => overlay?.has(file)).map((file) => ({ raw: overlay.get(file), extension: path.extname(file).slice(1) })),];- const globalsPath = path.join(renderer, 'styles/globals.css');- const globals = await postcss([tailwind(config)]).process(await readFile(globalsPath, 'utf8'), {- from: globalsPath,- });+ const globals = await postcss([tailwind(config)]).process(+ overlay?.get(globalsPath) ?? (await readFile(globalsPath, 'utf8')),+ { from: globalsPath },+ );const styles = await esbuild.build({- ...common(definition, []),+ ...common(definition, overlay ? [boundaries(new Map(), {}, overlay)] : []),stdin: { contents: globals.css, loader: 'css', resolveDir: path.dirname(globalsPath) },entryNames: 'styles',});@@ -218,13 +258,14 @@ export async function buildPage(definition, overlay) {body: Buffer.from(output.contents),});}+ const styleInputs = Object.keys(styles.metafile.inputs)+ .filter((file) => file !== '<stdin>')+ .map(sourcePath);const watched = [...new Set([...inputs,- ...Object.keys(styles.metafile.inputs)- .filter((file) => file !== '<stdin>')- .map(sourcePath),+ ...styleInputs,...Object.values(definition.stubs ?? {}).filter((value) => typeof value === 'string' && /^\.\.?\//.test(value)).map((value) => path.resolve(definition.dir, value)),@@ -250,6 +291,7 @@ export async function buildPage(definition, overlay) {files,styles: ['/styles.css', ...(files.has('/page.css') ? ['/page.css'] : [])],inputs,+ styleInputs: [globalsPath, ...styleInputs],replaced,fingerprints,sourceDigest: digest.digest('hex'),diff --git a/apps/desktop/scripts/ui-page/publish.mjs b/apps/desktop/scripts/ui-page/publish.mjsindex a4a7769757..db675f2662 100644--- a/apps/desktop/scripts/ui-page/publish.mjs+++ b/apps/desktop/scripts/ui-page/publish.mjs@@ -59,19 +59,29 @@ async function main() {const images = summary.overviews ?? (summary.overview ? [summary.overview] : []);if (!images.length) throw new Error(`${run} has no overview images`);- // Images go to the author's fork, never to the repository the PR targets.+ // Images go to the author's fork, never to the repository PRs target: the project's own+ // repository (package.json) and an `upstream` remote, if any. Checked against the URL git+ // actually pushes to, which is also where the links point.const remotes = git(['remote']).split('\n').filter(Boolean);- const canonical = githubRepo(- git(['remote', 'get-url', remotes.includes('upstream') ? 'upstream' : 'origin']),+ const pushRepo = (name) => githubRepo(git(['remote', 'get-url', '--push', name]));+ const project = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));+ const targets = new Set(+ [+ githubRepo(project.repository?.url ?? ''),+ remotes.includes('upstream') && githubRepo(git(['remote', 'get-url', 'upstream'])),+ ].filter(Boolean),);const remote =options.remote ??- remotes.find((name) => githubRepo(git(['remote', 'get-url', name])) !== canonical);- const repo = remote && githubRepo(git(['remote', 'get-url', remote]));+ remotes.find((name) => {+ const repo = pushRepo(name);+ return repo && !targets.has(repo);+ });+ const repo = remote && pushRepo(remote);if (!repo)throw new Error('Need a GitHub fork remote for screenshots (e.g. origin = <you>/cindy)');- if (repo === canonical)- throw new Error(`${remote} is ${canonical}, the PR's target; publish to your fork instead`);+ if (targets.has(repo))+ throw new Error(`${remote} pushes to ${repo}, the PR's target; publish to your fork instead`);const current = git(['rev-parse', '--abbrev-ref', 'HEAD']);const branch = options.branch ?? `pr-assets/${current === 'HEAD' ? 'detached' : current}`;diff --git a/apps/desktop/scripts/ui-page/registry.mjs b/apps/desktop/scripts/ui-page/registry.mjsindex 4006c9c0be..8d3f112bfd 100644--- a/apps/desktop/scripts/ui-page/registry.mjs+++ b/apps/desktop/scripts/ui-page/registry.mjs@@ -34,6 +34,14 @@ export async function loadPages() {return pages;}+/** Re-imports a page definition after its file changed (preview). */+export async function reloadPage(definition) {+ if (definition.adhoc) return definition;+ const fresh = (await import(`${pathToFileURL(definition.file).href}?v=${Date.now()}`)).default;+ validate(fresh, definition.file);+ return { ...fresh, dir: definition.dir, file: definition.file };+}+/** Throwaway entry written by an agent: generic checks only, cases come from mountPage(). */export function adhocPage(entry) {if (!existsSync(entry)) throw new Error(`--entry not found: ${entry}`);diff --git a/apps/desktop/scripts/ui-page/run.mjs b/apps/desktop/scripts/ui-page/run.mjsindex edb262e343..b96b2c39d9 100644--- a/apps/desktop/scripts/ui-page/run.mjs+++ b/apps/desktop/scripts/ui-page/run.mjs@@ -1,5 +1,5 @@import assert from 'node:assert/strict';-import { existsSync } from 'node:fs';+import { existsSync, statSync } from 'node:fs';import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';@@ -11,6 +11,7 @@ import { chromium, _electron } from 'playwright-core';import { buildPage, inputsChanged, root } from './build.mjs';import { auditOutcome, pageAudit } from './audit.mjs';import { variantsFor } from './options.mjs';+import { reloadPage } from './registry.mjs';const require = createRequire(import.meta.url);export const origin = 'http://cindy-ui.test';@@ -18,7 +19,12 @@ const csp ="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'";const git = (args) =>- execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ execFileSync('git', args, {+ cwd: root,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ maxBuffer: 64 * 1024 * 1024,+ });const bundlePrefix = (bundle) => `/b/${bundle.bundleDigest.slice(0, 16)}`;@@ -80,32 +86,57 @@ function browserPath(explicit) {return found;}-/** Contents of each bundle input as of `ref`, for files that differ from the worktree. */-function compareOverlay(ref, inputs) {- const changed = new Set(- git(['diff', '--name-only', ref, '--', 'apps', 'packages'])- .split('\n')- .filter(Boolean)- .map((file) => path.join(root, file)),+const COMPARE_SCOPE = ['apps/desktop/src', 'packages'];+const MODULE_SUFFIXES = [+ '',+ '.ts',+ '.tsx',+ '.js',+ '.jsx',+ '.mjs',+ '/index.ts',+ '/index.tsx',+ '/index.js',+];++/**+ * Product source (apps/desktop/src, packages) as of `ref`, read lazily from git: files that+ * differ from the worktree, including ones the worktree has since moved or deleted. The+ * scenario (fixtures, harness) stays current so before/after render the same data.+ */+function compareOverlay(ref) {+ const absolute = (list) =>+ new Set(+ list+ .split('\n')+ .filter(Boolean)+ .map((file) => path.join(root, file)),+ );+ const atRef = absolute(git(['ls-tree', '-r', '--name-only', ref, '--', ...COMPARE_SCOPE]));+ const changed = absolute(+ git(['diff', '--no-renames', '--name-only', ref, '--', ...COMPARE_SCOPE]),);- const overlay = new Map();- const newSinceRef = [];- // Only product source goes back to `ref`; the scenario (fixtures, harness) stays current so- // before/after render the same data.- const scenario = path.join(root, 'apps/desktop/scripts') + path.sep;- for (const file of inputs) {- if (!changed.has(file) || file.startsWith(scenario)) continue;- const relative = path.relative(root, file).split(path.sep).join('/');- try {- overlay.set(file, git(['show', `${ref}:${relative}`]));- } catch {- newSinceRef.push(relative);- }- }+ const contents = new Map();+ const isFile = (file) => existsSync(file) && statSync(file).isFile();return {- overlay,- newSinceRef,- files: [...overlay.keys()].map((file) => path.relative(root, file)),+ changed,+ atRef,+ used: new Set(),+ has: (file) => changed.has(file) && atRef.has(file),+ get(file) {+ if (!this.has(file)) return undefined;+ this.used.add(file);+ if (!contents.has(file))+ contents.set(+ file,+ git(['show', `${ref}:${path.relative(root, file).split(path.sep).join('/')}`]),+ );+ return contents.get(file);+ },+ resolve(candidate) {+ if (MODULE_SUFFIXES.some((suffix) => isFile(candidate + suffix))) return null;+ return MODULE_SUFFIXES.map((suffix) => candidate + suffix).find((file) => atRef.has(file));+ },};}@@ -187,22 +218,25 @@ export async function runPlan(plan, options, externalSignal) {}const controller = new AbortController();let browser, app, electronPage, stopping;+ // Nothing to close yet (still launching): the finally block stops whatever launch returns.const stopRuntime = () =>- (stopping ??= (async () => {- if (app) {- const child = app.process();- const force = setTimeout(() => {- if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');- }, 4000);- try {- await app.close();- } finally {- clearTimeout(force);- }- assert(child.exitCode !== null || child.signalCode !== null, 'Electron still running');- } else if (browser) await browser.close();- summary.cleanup.runtimeClosed = true;- })());+ !app && !browser+ ? Promise.resolve()+ : (stopping ??= (async () => {+ if (app) {+ const child = app.process();+ const force = setTimeout(() => {+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');+ }, 4000);+ try {+ await app.close();+ } finally {+ clearTimeout(force);+ }+ assert(child.exitCode !== null || child.signalCode !== null, 'Electron still running');+ } else if (browser) await browser.close();+ summary.cleanup.runtimeClosed = true;+ })());const abort = () => controller.abort(externalSignal?.reason ?? new Error('Interrupted'));externalSignal?.addEventListener('abort', abort, { once: true });if (externalSignal?.aborted) abort();@@ -263,11 +297,19 @@ export async function runPlan(plan, options, externalSignal) {bundleDigest: after.bundleDigest,};if (options.compare) {- const { overlay, newSinceRef, files } = compareOverlay(options.compare, after.inputs);+ const overlay = compareOverlay(options.compare);+ const loaded = [...after.inputs, ...after.styleInputs];// Nothing this page loads differs from the ref: a second render would be identical.- if (overlay.size)+ if (loaded.some((file) => overlay.has(file)))item.bundles.before = await measure('buildMs', () => buildPage(item.definition, overlay));- page.compare = { ref: options.compare, replacedFromRef: files, newSinceRef };+ const relative = (file) => path.relative(root, file);+ page.compare = {+ ref: options.compare,+ replacedFromRef: [...overlay.used].map(relative).sort(),+ newSinceRef: loaded+ .filter((file) => overlay.changed.has(file) && !overlay.atRef.has(file))+ .map(relative),+ };}summary.pages.push(page);}@@ -327,7 +369,9 @@ export async function runPlan(plan, options, externalSignal) {}});- const openVariant = async (variant, bundle, definition) => {+ // Resources go into `opened` as soon as they exist, so a variant that fails to start is+ // still screenshotted, its listeners removed and its context closed by the caller.+ const openVariant = async (variant, bundle, definition, opened = {}) => {let page, context;if (app) {page = electronPage;@@ -355,6 +399,15 @@ export async function runPlan(plan, options, externalSignal) {};page.on('pageerror', onError);page.on('console', onConsole);+ Object.assign(opened, {+ page,+ context,+ errors,+ detach: () => {+ page.off('pageerror', onError);+ page.off('console', onConsole);+ },+ });if (app) await writeBundle(path.join(scratch, 'bundle'), bundle);current.bundle = bundle;current.blocked = [];@@ -397,11 +450,7 @@ export async function runPlan(plan, options, externalSignal) {const actual = await page.evaluate(() => ({ width: innerWidth, height: innerHeight }));assert.deepEqual(actual, variant.viewport, 'Electron window matches the variant viewport');}- const detach = () => {- page.off('pageerror', onError);- page.off('console', onConsole);- };- return { page, context, errors, detach };+ return opened;};const runVariant = async (item, variant, role) => {@@ -429,12 +478,28 @@ export async function runPlan(plan, options, externalSignal) {let opened;let timer;const started = performance.now();- const capture = async (name, captureOptions = {}) => {+ // Generic checks run at every capture, so states reached in check() (open menus, new+ // messages) are checked too. Host mutations are checked once after check().+ const audited = { errors: new Set(), warnings: new Set(), hostMissing: new Set() };+ const auditPage = async () => {+ const audit = await opened.page.evaluate(pageAudit);+ const outcome = auditOutcome({ ...audit, mutations: [] });+ for (const error of outcome.errors) audited.errors.add(error);+ for (const warning of outcome.warnings) audited.warnings.add(warning);+ for (const name of audit.hostMissing) audited.hostMissing.add(name);+ };+ const mergeAudits = () => {+ result.warnings.push(...audited.warnings);+ result.hostMissing = [...audited.hostMissing];+ if (role === 'after' && options.mode === 'check') result.errors.push(...audited.errors);+ };+ const capture = async (name, captureOptions = {}, { audit = true } = {}) => {const file = path.join(dir, `${name}.png`);const target = captureOptions.locator ?? opened.page;await target.screenshot({ path: path.join(evidence, file), timeout: 5000, scale: 'css' });result.screenshots.push(file.split(path.sep).join('/'));if (options.focus && !captureOptions.locator) await captureFocus(name);+ if (audit) await auditPage();};// `--focus`: a 2x crop around one element plus its measured box, so small spacing and// truncation changes are readable without opening the full screenshot.@@ -486,7 +551,8 @@ export async function runPlan(plan, options, externalSignal) {};try {const work = (async () => {- opened = await openVariant(variant, item.bundles[role], definition);+ opened = {};+ await openVariant(variant, item.bundles[role], definition, opened);result.timings.readyMs = Math.round(performance.now() - started);const { page } = opened;if (definition.adhoc && options.cases === 'all' && !item.expanded) {@@ -502,14 +568,9 @@ export async function runPlan(plan, options, externalSignal) {}}await capture('initial');- const audit = await page.evaluate(pageAudit);- const outcome = auditOutcome(audit);- result.warnings.push(...outcome.warnings);- result.hostMissing = audit.hostMissing;// The pre-change side replays the same steps so every capture has a counterpart;// its assertions only describe the old code and never fail the run.if (options.mode === 'check') {- if (role === 'after') result.errors.push(...outcome.errors);const checkStarted = performance.now();const ui = {...variant,@@ -562,7 +623,8 @@ export async function runPlan(plan, options, externalSignal) {});}),]);- if (opened) result.errors.push(...opened.errors);+ mergeAudits();+ if (opened?.errors) result.errors.push(...opened.errors);if (options.focus && !result.focus.length)result.warnings.push(`focus ${options.focus} was not visible at any capture`);if (current.blocked.length)@@ -571,16 +633,18 @@ export async function runPlan(plan, options, externalSignal) {else result.status = result.errors.length ? 'failed' : 'passed';} catch (error) {result.errors.unshift(String(error?.stack ?? error));- if (opened) result.errors.push(...opened.errors);+ mergeAudits();+ if (opened?.errors) result.errors.push(...opened.errors);if (result.hostMissing.length === 0 && opened?.page && !opened.page.isClosed())result.hostMissing = await opened.page.evaluate(() => window.__uiPage?.hostMissing ?? []).catch(() => []);- if (opened?.page && !opened.page.isClosed()) await capture('failure').catch(() => {});+ if (opened?.page && !opened.page.isClosed())+ await capture('failure', {}, { audit: false }).catch(() => {});result.status = role === 'before' ? 'before-failed' : 'failed';} finally {clearTimeout(timer);- opened?.detach();+ opened?.detach?.();if (opened?.context) await opened.context.close().catch(() => {});result.timings.totalMs = Math.round(performance.now() - started);}@@ -591,7 +655,7 @@ export async function runPlan(plan, options, externalSignal) {if (options.mode === 'preview') {const item = plan.pages[0];const variant = item.variants[0];- const definition = item.definition;+ let definition = item.definition;const opened = await openVariant(variant, item.bundles.after, definition);summary.status = 'preview-open';console.log(@@ -603,8 +667,24 @@ export async function runPlan(plan, options, externalSignal) {if (controller.signal.aborted || opened.page.isClosed()) break;if (!(await inputsChanged(item.bundles.after.fingerprints))) continue;try {+ // The scenario file may have changed too: reload its data, stubs and viewport.+ definition = item.definition = await reloadPage(definition);+ const scenario = definition.cases[variant.case];+ if (!scenario) throw new Error(`case ${variant.case} no longer exists`);item.bundles.after = await buildPage(definition);current.bundle = item.bundles.after;+ const viewport = options.viewports?.[0] ?? scenario.viewport ?? definition.viewport;+ current.context = {+ ...current.context,+ data: scenario.data ?? {},+ storage: scenario.storage,+ viewport,+ };+ if (app)+ await app.evaluate(({ BrowserWindow }, size) => {+ BrowserWindow.getAllWindows()[0].setContentSize(size.width, size.height);+ }, viewport);+ else await opened.page.setViewportSize(viewport);if (app) {await writeBundle(path.join(scratch, 'bundle'), current.bundle);await writeFile(