Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 单页验证超时后停住场景、平台跟随本机、仓库名大小写与图片覆盖
Chris1e1ea9693e90
diff --git a/apps/desktop/scripts/ui-page/README.md b/apps/desktop/scripts/ui-page/README.mdindex e8cd776c76..ade2ea8a6e 100644--- a/apps/desktop/scripts/ui-page/README.md+++ b/apps/desktop/scripts/ui-page/README.md@@ -185,6 +185,7 @@ mountPage({ cases: ['off', 'on'], render: (ctx) => <Switch checked={ctx.case ===补回;不写 `<ref>` 时用本分支与上游主干的分叉点,也就是“本分支改动之前”。场景与harness 始终用当前版本,所以两边执行同样的步骤、截同样的图。没有文件不同时不重复渲染。改前一侧的断言失败不影响结果,在报告里以 `before <ref>:` 开头逐条列出;`<ref>` 之后才新增的文件按当前版本使用并列出。+Tailwind 配置由 Tailwind 直接从磁盘加载,两侧都用当前版本;它在 `<ref>` 之后有改动时报告会写明。## 运行方式@@ -192,7 +193,11 @@ harness 始终用当前版本,所以两边执行同样的步骤、截同样的临时 profile、拒绝权限与下载、只允许访问测试源,运行完删除临时数据;后台检查不显示窗口、不占 Dock。- `--engine chromium`:Playwright Chromium 或本机 Chrome(`--browser <路径>` 指定)。-- `--timeout` 是每个变体的超时(默认 20 秒);Ctrl+C 会写完 `summary.json` 并关闭窗口。+- `--timeout` 是每个变体的超时(默认 20 秒);超时后场景不能再截图。Electron 各变体共用一个+ 窗口,超时的场景仍在运行时本次检查直接停止,避免它操作后面的变体。Ctrl+C 会写完+ `summary.json` 并关闭窗口。+- `--platform` 默认是当前电脑的平台;指定其它平台只改变页面读到的 `electronAPI.platform`,+ 报告会写明模拟的平台。- `ui:preview` 只用于人工验收:显示一个窗口,依赖的源码、样式、翻译或场景变化后自动重载,关窗或 Ctrl+C 结束。自动检查不要用它保持窗口。修改运行器、依赖或 Tailwind 配置后重启命令。diff --git a/apps/desktop/scripts/ui-page/cli.mjs b/apps/desktop/scripts/ui-page/cli.mjsindex 36f11a762b..6935cbce17 100644--- a/apps/desktop/scripts/ui-page/cli.mjs+++ b/apps/desktop/scripts/ui-page/cli.mjs@@ -17,7 +17,7 @@ matrix (comma lists; every combination runs in one browser):--theme light,dark|all default: light--locale <list>|all ${LOCALES.join(', ')} (default: zh-CN)--viewport 1280x800,… default: the page/case viewport- --platform darwin|win32|linux value of electronAPI.platform (default: darwin)+ --platform darwin|win32|linux value of electronAPI.platform (default: this machine)runtime:--compare [<ref>] also render the source at <ref> (default: upstream merge-base); overview pairs before/after--focus <css selector> 2x crop + measured box/padding/font of one element at every capture@@ -66,6 +66,9 @@ function report(summary) {: 'no loaded product file differs from ref; before = now, not rendered') +(page.compare.newSinceRef.length? `; new since ref (used as-is): ${page.compare.newSinceRef.join(', ')}`+ : '') ++ (page.compare.currentOnBothSides?.length+ ? `; current on both sides: ${page.compare.currentOnBothSides.join(', ')}`: ''),);}@@ -193,6 +196,8 @@ async function main() {}console.log(options.json ? JSON.stringify(summary, null, 2) : report(summary));if (!['passed', 'preview-closed'].includes(summary.status)) process.exitCode = 1;+ // A scenario still running after its timeout keeps this process alive; end once output is out.+ if (summary.strandedScenarios?.length) process.stdout.write('', () => process.exit());} finally {process.removeListener('SIGINT', interrupt);process.removeListener('SIGTERM', interrupt);diff --git a/apps/desktop/scripts/ui-page/coverage.mjs b/apps/desktop/scripts/ui-page/coverage.mjsindex fa3816f40b..23e143e2a6 100644--- a/apps/desktop/scripts/ui-page/coverage.mjs+++ b/apps/desktop/scripts/ui-page/coverage.mjs@@ -7,7 +7,7 @@ const git = (args) =>execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });const renderer = path.join(desktop, 'src/renderer');// Files whose change is visible in the UI; anything else is ignored for coverage.-const UI_FILE = /\.(?:tsx|ts|css|json)$/;+const UI_FILE = /\.(?:tsx|ts|css|json|png|jpe?g|gif|webp|avif|svg|woff2?|ttf|otf)$/;/** Merge-base with `requested`, or with the conventional upstream branch. */export function baseRef(requested) {diff --git a/apps/desktop/scripts/ui-page/options.mjs b/apps/desktop/scripts/ui-page/options.mjsindex ef5a11eafb..295eec62f7 100644--- a/apps/desktop/scripts/ui-page/options.mjs+++ b/apps/desktop/scripts/ui-page/options.mjs@@ -87,7 +87,9 @@ export function parseOptions(argv) {options.cases = raw.case ?? 'default';options.themes = list(raw.theme ?? 'light', THEMES, 'theme');options.locales = list(raw.locale ?? 'zh-CN', LOCALES, 'locale');- options.platform = list(raw.platform ?? 'darwin', PLATFORMS, 'platform')[0];+ // Same platform as the machine taking the screenshots unless one is simulated explicitly.+ const host = PLATFORMS.includes(process.platform) ? process.platform : 'linux';+ options.platform = list(raw.platform ?? host, PLATFORMS, 'platform')[0];if (raw.viewport && (raw.width || raw.height))throw new Error('Use either --viewport or --width/--height');options.viewports = raw.viewportdiff --git a/apps/desktop/scripts/ui-page/pr.mjs b/apps/desktop/scripts/ui-page/pr.mjsindex 59f534ad6d..0c5753f637 100644--- a/apps/desktop/scripts/ui-page/pr.mjs+++ b/apps/desktop/scripts/ui-page/pr.mjs@@ -29,6 +29,13 @@ export function prSnippet(summary, argv) {`- 版本:\`${summary.commit?.slice(0, 12) ?? '未知'}\`${summary.worktreeDirty ? '(含未提交改动)' : ''}`,`- 结果:${passed}/${variants.length} 个场景通过${warnings ? `,${warnings} 条警告` : ''}`,];+ const simulated = [...new Set(variants.map((variant) => variant.platform))].filter(+ (platform) => platform !== process.platform,+ );+ if (simulated.length)+ lines.push(+ `- 模拟平台:页面按 ${simulated.map((platform) => PLATFORM[platform] ?? platform).join(' / ')} 渲染`,+ );for (const page of summary.pages) {const own = variants.filter((variant) => variant.page === page.name);const cases = [...new Map(own.map((variant) => [variant.case, variant.about])).entries()];@@ -46,6 +53,10 @@ export function prSnippet(summary, argv) {? ` - 改前/改后对照:\`${page.compare.ref}\`,同一步骤左右并排`: ` - 改前/改后对照:\`${page.compare.ref}\` 之后没有改动本页面加载的产品文件`,);+ if (page.compare?.currentOnBothSides?.length)+ lines.push(+ ` - 对照两侧都用当前版本:${page.compare.currentOnBothSides.map((file) => `\`${file}\``).join('、')}`,+ );}// `--focus` measurements: the last capture where the element was visible, before → now.for (const variant of variants) {diff --git a/apps/desktop/scripts/ui-page/publish.mjs b/apps/desktop/scripts/ui-page/publish.mjsindex db675f2662..ff23e8ec70 100644--- a/apps/desktop/scripts/ui-page/publish.mjs+++ b/apps/desktop/scripts/ui-page/publish.mjs@@ -65,22 +65,26 @@ async function main() {const remotes = git(['remote']).split('\n').filter(Boolean);const pushRepo = (name) => githubRepo(git(['remote', 'get-url', '--push', name]));const project = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));+ // GitHub owner and repository names are case-insensitive.const targets = new Set([githubRepo(project.repository?.url ?? ''),remotes.includes('upstream') && githubRepo(git(['remote', 'get-url', 'upstream'])),- ].filter(Boolean),+ ]+ .filter(Boolean)+ .map((name) => name.toLowerCase()),);+ const isTarget = (name) => targets.has(name.toLowerCase());const remote =options.remote ??remotes.find((name) => {const repo = pushRepo(name);- return repo && !targets.has(repo);+ return repo && !isTarget(repo);});const repo = remote && pushRepo(remote);if (!repo)throw new Error('Need a GitHub fork remote for screenshots (e.g. origin = <you>/cindy)');- if (targets.has(repo))+ if (isTarget(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']);diff --git a/apps/desktop/scripts/ui-page/run.mjs b/apps/desktop/scripts/ui-page/run.mjsindex adafd58502..dce51c7a4e 100644--- a/apps/desktop/scripts/ui-page/run.mjs+++ b/apps/desktop/scripts/ui-page/run.mjs@@ -87,6 +87,7 @@ function browserPath(explicit) {}const COMPARE_SCOPE = ['apps/desktop/src', 'apps/desktop/resources', 'packages'];+const TAILWIND_CONFIG = 'apps/desktop/tailwind.config.ts';const BINARY = /\.(?:png|jpe?g|gif|webp|avif|woff2?|ttf|otf)$/;const MODULE_SUFFIXES = ['',@@ -315,6 +316,10 @@ export async function runPlan(plan, options, externalSignal) {newSinceRef: loaded.filter((file) => overlay.changed.has(file) && !overlay.atRef.has(file)).map(relative),+ // Loaded as a module by Tailwind from disk, so both sides use the current version.+ currentOnBothSides: git(['diff', '--name-only', options.compare, '--', TAILWIND_CONFIG])+ .split('\n')+ .filter(Boolean),};}summary.pages.push(page);@@ -485,6 +490,9 @@ export async function runPlan(plan, options, externalSignal) {};let opened;let timer;+ let work;+ // After a timeout the scenario may still be running; it must not capture or act anymore.+ let timedOut = false;const started = performance.now();// 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().@@ -501,7 +509,8 @@ export async function runPlan(plan, options, externalSignal) {result.hostMissing = [...audited.hostMissing];if (role === 'after' && options.mode === 'check') result.errors.push(...audited.errors);};- const capture = async (name, captureOptions = {}, { audit = true } = {}) => {+ const capture = async (name, captureOptions = {}, { audit = true, failure = false } = {}) => {+ if (timedOut && !failure) throw new Error(`variant timed out before capture ${name}`);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' });@@ -558,7 +567,7 @@ export async function runPlan(plan, options, externalSignal) {});};try {- const work = (async () => {+ work = (async () => {opened = {};await openVariant(variant, item.bundles[role], definition, opened);result.timings.readyMs = Math.round(performance.now() - started);@@ -613,6 +622,7 @@ export async function runPlan(plan, options, externalSignal) {work,new Promise((_, reject) => {timer = setTimeout(() => {+ timedOut = true;reject(new Error(`variant timed out after ${options.timeout}ms`));// Unblock pending Playwright calls. Chromium: close this variant's context.// Electron: leave the page; only a hung renderer costs the shared window.@@ -648,10 +658,31 @@ export async function runPlan(plan, options, externalSignal) {.evaluate(() => window.__uiPage?.hostMissing ?? []).catch(() => []);if (opened?.page && !opened.page.isClosed())- await capture('failure', {}, { audit: false }).catch(() => {});+ await capture('failure', {}, { audit: false, failure: true }).catch(() => {});result.status = role === 'before' ? 'before-failed' : 'failed';} finally {clearTimeout(timer);+ if (timedOut) {+ // Pending Playwright calls fail within the page default timeout once the page is gone.+ const settled = await Promise.race([+ work.then(+ () => true,+ () => true,+ ),+ delay(Math.min(options.timeout, 10000) + 2000).then(() => false),+ ]);+ if (!settled)+ summary.strandedScenarios = [...(summary.strandedScenarios ?? []), variant.id];+ // Electron shares one window between variants: a scenario that keeps running would act+ // on the next variant's page, so stop the run instead of recording polluted results.+ if (!settled && app) {+ const error = new Error(+ `${variant.id} was still running after its timeout; stopped the run so it cannot affect later variants`,+ );+ result.errors.push(error.message);+ controller.abort(error);+ }+ }opened?.detach?.();if (opened?.context) await opened.context.close().catch(() => {});result.timings.totalMs = Math.round(performance.now() - started);diff --git a/apps/desktop/scripts/ui-page/runner.selftest.mjs b/apps/desktop/scripts/ui-page/runner.selftest.mjsindex f0b98b3390..61c5df2b5e 100644--- a/apps/desktop/scripts/ui-page/runner.selftest.mjs+++ b/apps/desktop/scripts/ui-page/runner.selftest.mjs@@ -130,16 +130,24 @@ test('a page that never mounts fails at the timeout and leaves no runtime behindassert.equal(leftoverRunners(), '');});-test('an interrupt still writes the summary and stops the runtime', async () => {- // Never mounts, so the run is still waiting when the interrupt arrives.- const file = await entry('waiting', `export {};\n`);- const { code, stdout } = await run(['--entry', file, '--timeout', '60000'], {- interruptWhenRunning: true,- });- assert.equal(code, 1);- const summaryFile = /summary:\s+(\S+)/.exec(stdout)?.[1];- assert.ok(summaryFile, stdout);- const summary = JSON.parse(await readFile(summaryFile, 'utf8'));- assert.match(summary.errors.join('\n'), /用户中断/);- assert.equal(leftoverRunners(), '');-});+// Windows has no POSIX signals: a child killed with 'SIGINT' is terminated outright, so the+// CLI's own interrupt handling cannot be observed from here.+test(+ 'an interrupt still writes the summary and stops the runtime',+ {+ skip: process.platform === 'win32' && 'Windows cannot deliver SIGINT to the child',+ },+ async () => {+ // Never mounts, so the run is still waiting when the interrupt arrives.+ const file = await entry('waiting', `export {};\n`);+ const { code, stdout } = await run(['--entry', file, '--timeout', '60000'], {+ interruptWhenRunning: true,+ });+ assert.equal(code, 1);+ const summaryFile = /summary:\s+(\S+)/.exec(stdout)?.[1];+ assert.ok(summaryFile, stdout);+ const summary = JSON.parse(await readFile(summaryFile, 'utf8'));+ assert.match(summary.errors.join('\n'), /用户中断/);+ assert.equal(leftoverRunners(), '');+ },+);