Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 单页 UI 快速验证 pnpm ui:check

Chris31b49781dbe1
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 4cf7507e82..49966b3918 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -30,7 +30,12 @@ type:feat / fix / refactor / perf / chore / docs / test / revert / build / ci
### UI 变化
-<!-- 涉及 UI 时附截图或录屏,并注明平台;不涉及则写“不涉及”。 -->
+<!-- 涉及 UI 时附截图或录屏,并注明平台;不涉及则写“不涉及”。
+普通 Desktop 界面改动用单页验证截图即可:`pnpm ui:check --changed --theme all`(修旧问题加
+`--compare` 出改前/改后对照),再运行 `pnpm ui:check:publish`,它把截图发到作者 fork 的
+`pr-assets/<分支>`,输出带图片链接的本段内容,原样贴到这里。涉及登录、发送、跨设备等单页验证
+覆盖不到的变化,仍附完整 Cindy 截图;设计系统 PR 的证据要求见
+docs/design-rules/design-governance.md §6。 -->
- 引用的设计规范:
diff --git a/AGENTS.md b/AGENTS.md
index 325ab305b3..b64cd2bb8e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -92,6 +92,11 @@
- 新增或修改任何界面、组件、布局、样式、动效或 UI 文案前,必须先读权威设计规范
`docs/design-rules/DESIGN.md`;设计文档索引见
`docs/design-rules/cindy-design-system.md`。
+- 改完 Desktop renderer 界面(组件、样式、布局、文案、深浅色、多语言)后自检,先运行
+ `pnpm ui:check --changed --theme all` 并查看输出的 `overview.png`,无需为此启动完整
+ Desktop;输出中 `UNCOVERED` 的文件未被验证。发 PR 时运行 `pnpm ui:check:publish`,把输出的
+ 带图内容写进「UI 变化」。按改动类型选择验证方式见
+ `docs/dev-rules/desktop-development.md`「按改动选择验证方式」。
- 新增或修改 Mobile(`apps/mobile`)界面上的文字前,必须先查
`apps/mobile/docs/mobile-design-guide.md` §3「文字规范速查」:先定角色,再整行照抄字号、
行高、字重、字色;五档中性字色、浅色字不配粗字重、11 档字号、必须配行高四条由
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index b460e187a4..ac1614ec68 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -217,9 +217,11 @@
"cross-env": "^7.0.3",
"drizzle-kit": "^0.31.10",
"electron": "42.11.12",
+ "esbuild": "0.28.1",
"eslint": "^9.0.0",
"eslint-config-prettier": "^9.1.0",
"jsdom": "^29.1.1",
+ "playwright-core": "1.60.0",
"postcss": "^8.4.49",
"prettier": "^3.4.2",
"remark-parse": "11.0.0",
diff --git a/apps/desktop/scripts/check-group-control-layout.mjs b/apps/desktop/scripts/check-group-control-layout.mjs
deleted file mode 100644
index db14bbcee2..0000000000
--- a/apps/desktop/scripts/check-group-control-layout.mjs
+++ /dev/null
@@ -1,319 +0,0 @@
-#!/usr/bin/env node
-// Isolated production-component layout regression; no Electron or device connections.
-// Run: node apps/desktop/scripts/check-group-control-layout.mjs [Chromium executable] [screenshot directory]
-import assert from 'node:assert/strict';
-import { readFileSync, mkdtempSync, mkdirSync, rmSync } from 'node:fs';
-import os from 'node:os';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import esbuild from 'esbuild';
-import postcss from 'postcss';
-import tailwind from 'tailwindcss';
-import loadConfig from 'tailwindcss/loadConfig.js';
-import { chromium } from 'playwright-core';
-
-const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-const renderer = path.join(desktop, 'src/renderer');
-const temp = mkdtempSync(path.join(os.tmpdir(), 'cindy-group-control-'));
-const screenshots = process.argv[3];
-if (screenshots) mkdirSync(screenshots, { recursive: true });
-// Stub only host-facing/unrendered dependencies. The page, composer, banner,
-// theme tokens and CSS are production implementations.
-const stubs = {
- '@/components/chat/MarkdownRenderer': 'export const MarkdownRenderer=({content})=>content;',
- '@/contexts/dataOwnerGeneration':
- 'export const getDataOwnerGeneration=()=>1;export const isDataOwnerGenerationCurrent=()=>true;export const isDataOwnerPushCurrent=()=>true;',
- '@/state/agentIslandActivity': 'export const useAgentIslandActivity=()=>null;',
- '@/lib/logger': 'export const createLogger=()=>({debug(){},info(){},warn(){},error(){}});',
- '@/lib/toast': 'export const toast={error(){},success(){}};',
- './BotGroupPendingInteraction': 'export const BotGroupPendingInteraction=()=>null;',
-};
-let browser;
-try {
- const config = loadConfig(path.join(desktop, 'tailwind.config.ts'));
- config.content = [
- path.join(renderer, 'features/bots/*.tsx'),
- path.join(renderer, 'features/remote-device/ControlledBanner.tsx'),
- path.join(renderer, 'components/ui/*.tsx'),
- path.join(renderer, 'components/new-chat/SendButton.tsx'),
- ];
- const css = (
- await postcss([tailwind(config)]).process(
- readFileSync(path.join(renderer, 'styles/generated/tokens.css'), 'utf8') +
- '\n' +
- readFileSync(path.join(renderer, 'styles/globals.css'), 'utf8').replace(
- /^@import.*$/gm,
- '',
- ),
- { from: undefined },
- )
- ).css;
- const bundle = await esbuild.build({
- entryPoints: [path.join(desktop, 'scripts/fixtures/group-control/group-control-fixture.tsx')],
- write: false,
- outfile: path.join(temp, 'group-control.js'),
- bundle: true,
- format: 'esm',
- platform: 'browser',
- jsx: 'automatic',
- tsconfig: path.join(desktop, 'tsconfig.json'),
- loader: { '.svg': 'dataurl', '.png': 'dataurl' },
- define: { 'import.meta.env.PROD': 'true', 'import.meta.env.DEV': 'false' },
- plugins: [
- {
- name: 'fixture-stubs',
- setup(build) {
- build.onResolve({ filter: /.*/ }, (args) =>
- stubs[args.path] ? { path: args.path, namespace: 'fixture-stub' } : undefined,
- );
- build.onLoad({ filter: /.*/, namespace: 'fixture-stub' }, (args) => ({
- contents: stubs[args.path],
- loader: 'tsx',
- }));
- },
- },
- ],
- });
- const shellCss = `
- body{margin:0;color:var(--text-primary);background:var(--surface);font-family:Inter,-apple-system,sans-serif}
- .fixture-caption{height:36px;padding:8px 16px;font-size:12px;border-bottom:1px solid var(--border-default)}
- .fixture-shell{display:flex;height:calc(100vh - 36px)}
- aside{flex-shrink:0;padding:20px;overflow:hidden;border-right:1px solid var(--border-default)}
- aside[style="width: 0px;"]{padding:0;border:0}
- .fixture-content{flex:1;min-width:0;display:flex;flex-direction:column}
- header{height:52px;flex-shrink:0;display:flex;align-items:center;justify-content:space-between;padding:0 20px;border-bottom:1px solid var(--border-default)}
- .fixture-view{flex:1;min-height:0}`;
- const script = bundle.outputFiles.find((file) => file.path.endsWith('.js')).text;
- const componentCss = bundle.outputFiles
- .filter((file) => file.path.endsWith('.css'))
- .map((file) => file.text)
- .join('');
- browser = await chromium.launch({
- headless: true,
- ...(process.argv[2] ? { executablePath: process.argv[2] } : {}),
- });
- const page = await browser.newPage();
- const errors = [];
- page.on('pageerror', (error) => errors.push(error.message));
- await page.route('**/*', (route) =>
- route.request().url().startsWith('http://fixture.local/')
- ? route.fulfill({
- contentType: 'text/html',
- body: `<!doctype html><meta charset="utf-8"><style>${css}${componentCss}${shellCss}</style><div id="root"></div><script type="module">${script.replace(/<\/script/gi, '<\\/script')}</script>`,
- })
- : route.abort(),
- );
- const connect = async (connected = true, long = false) => {
- await page.evaluate(
- ({ connected, long }) =>
- window.fixturePush({
- controllers: connected
- ? [
- {
- deviceId: 'fixture',
- name: long
- ? 'Mac Studio · A very long device name for layout verification'
- : 'Mac Studio',
- },
- ]
- : [],
- }),
- { connected, long },
- );
- await page
- .locator('main [data-controlled-banner-chip]')
- .waitFor({ state: connected ? 'visible' : 'detached' });
- };
- const bottomGap = () =>
- page
- .locator('main > div')
- .first()
- .evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop);
- const collapse = async () => {
- await page.locator('[data-controlled-banner-collapse]').click();
- await page.locator('[data-controlled-banner="collapsed"]').waitFor();
- assert.equal(await page.locator('[data-controlled-banner-chip]').count(), 0);
- };
- const expand = async () => {
- await page.locator('[data-controlled-banner="collapsed"]').click();
- await page.locator('[data-controlled-banner-chip]').waitFor();
- };
- const activateWithKeyboard = async (selector, key) => {
- // Reach the notice through normal tab order, not locator.focus().
- await page.locator('textarea').focus();
- await page.keyboard.press('Shift+Tab');
- const target = page.locator(selector);
- assert(
- await target.evaluate((element) => element === document.activeElement),
- `Keyboard cannot reach ${selector}`,
- );
- assert(
- await target.evaluate(
- (element) =>
- Boolean(element.getAttribute('aria-label')) &&
- element.matches(':focus-visible') &&
- getComputedStyle(element).boxShadow !== 'none',
- ),
- `Missing accessible focus: ${selector}`,
- );
- await page.keyboard.press(key);
- };
- let layouts = 0;
- for (const theme of ['light', 'dark']) {
- for (const width of [720, 800, 1280])
- for (const sidebar of [0, 280])
- for (const lines of [1, 8]) {
- const scenario = JSON.stringify({ theme, width, sidebar, lines });
- await page.setViewportSize({ width, height: width === 800 ? 600 : 800 });
- await page.goto(
- `http://fixture.local/?theme=${theme}&sidebar=${sidebar}&stage=regression`,
- );
- await page.locator('textarea').waitFor();
- await connect(true, width === 800);
- await page
- .locator('textarea')
- .fill(Array(lines).fill('只检查布局,不发送消息。').join('\n'));
- const result = await page.evaluate(() => {
- const chip = document.querySelector('[data-controlled-banner-chip]');
- const input = document.querySelector('textarea');
- const send = input.parentElement.querySelector('button[aria-label="发送消息"]');
- const revoke = chip.querySelector('button');
- const cr = chip.getBoundingClientRect(),
- card = input.parentElement.getBoundingClientRect();
- const accessible = (element) => {
- const r = element.getBoundingClientRect();
- return element.contains(
- document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2),
- );
- };
- return {
- centerDelta: Math.abs(cr.x + cr.width / 2 - card.x - card.width / 2),
- noticeAbove: cr.bottom <= card.y,
- actionsAccessible: [
- input,
- send,
- revoke,
- chip.querySelector('[data-controlled-banner-collapse]'),
- ].every(accessible),
- overflow: document.documentElement.scrollWidth > innerWidth,
- };
- });
- assert(result.centerDelta < 1, `Notice is not centered: ${scenario}`);
- assert(
- result.noticeAbove && result.actionsAccessible && !result.overflow,
- `Overlap/overflow: ${scenario}`,
- );
- const capture =
- screenshots &&
- sidebar === 280 &&
- ((theme === 'light' && width === 1280 && lines === 1) ||
- (theme === 'dark' && width === 720 && lines === 8));
- const imageName = `group-control-${theme}-${width === 1280 ? 'wide' : 'narrow'}`;
- if (capture) await page.screenshot({ path: path.join(screenshots, `${imageName}.png`) });
- await collapse();
- const collapsed = await page.evaluate(() => {
- const dot = document.querySelector('[data-controlled-banner="collapsed"]');
- const r = dot.getBoundingClientRect();
- const card = document.querySelector('textarea').parentElement.getBoundingClientRect();
- return {
- centerDelta: Math.abs(r.x + r.width / 2 - card.x - card.width / 2),
- above: r.bottom <= card.y,
- accessible: dot.contains(
- document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2),
- ),
- };
- });
- assert(
- collapsed.centerDelta < 1 && collapsed.above && collapsed.accessible,
- `Collapsed indicator misplaced or blocked: ${scenario}`,
- );
- if (capture)
- await page.screenshot({ path: path.join(screenshots, `${imageName}-collapsed.png`) });
- await expand();
- // Both native button activation keys must preserve the full UI-only cycle.
- for (const key of ['Enter', 'Space']) {
- await activateWithKeyboard('[data-controlled-banner-collapse]', key);
- await page.locator('[data-controlled-banner="collapsed"]').waitFor();
- assert.equal(await page.locator('[data-controlled-banner-chip]').count(), 0);
- await activateWithKeyboard('[data-controlled-banner="collapsed"]', key);
- await page.locator('[data-controlled-banner-chip]').waitFor();
- assert.equal(await page.locator('[data-controlled-banner="collapsed"]').count(), 0);
- }
- // Revocation remains a separate button before X in the tab order.
- await page.locator('textarea').focus();
- await page.keyboard.press('Shift+Tab');
- await page.keyboard.press('Shift+Tab');
- assert(
- await page
- .locator('[data-controlled-banner-chip] button')
- .first()
- .evaluate((element) => element === document.activeElement),
- 'Revoke is not separately reachable',
- );
- assert.deepEqual(
- await page.evaluate(() => window.fixtureMutations),
- [],
- `Folding/restoring invoked a host mutation: ${scenario}`,
- );
- assert.equal(await page.getByRole('dialog').count(), 0);
- layouts++;
- }
- // A real long thread: connecting changes only the scroller viewport, not content.
- await page.setViewportSize({ width: 800, height: 600 });
- await page.goto(`http://fixture.local/?theme=${theme}&sidebar=280&thread=long`);
- await page.locator('textarea').waitFor();
- await page.waitForFunction(() => {
- const el = document.querySelector('main > div');
- return (
- el &&
- el.scrollHeight > el.clientHeight &&
- el.scrollHeight - el.clientHeight - el.scrollTop < 1
- );
- });
- await connect();
- assert((await bottomGap()) < 1, `Connection lost bottom pin (${theme})`);
- await collapse();
- assert((await bottomGap()) < 1, `Collapse lost bottom pin (${theme})`);
- await expand();
- assert((await bottomGap()) < 1, `Expand lost bottom pin (${theme})`);
- await connect(false);
- assert((await bottomGap()) < 1, `Disconnection lost bottom pin (${theme})`);
- const scroller = page.locator('main > div').first();
- const before = await scroller.evaluate((element) => {
- element.scrollTop = 180;
- element.dispatchEvent(new Event('scroll', { bubbles: true }));
- return element.scrollTop;
- });
- await connect();
- assert.equal(
- await scroller.evaluate((element) => element.scrollTop),
- before,
- `Connection jumped away from history (${theme})`,
- );
- await collapse();
- assert.equal(
- await scroller.evaluate((element) => element.scrollTop),
- before,
- `Collapse jumped away from history (${theme})`,
- );
- await expand();
- assert.equal(
- await scroller.evaluate((element) => element.scrollTop),
- before,
- `Expand jumped away from history (${theme})`,
- );
- await connect(false);
- assert.equal(
- await scroller.evaluate((element) => element.scrollTop),
- before,
- `Disconnection jumped away from history (${theme})`,
- );
- }
- assert.deepEqual(errors, []);
- console.log(
- `PASS: ${layouts} expanded/collapsed layouts with click, Tab, Enter and Space; no host mutations; bottom pin and history position survive connection and collapse changes in both themes.`,
- );
-} finally {
- await browser?.close();
- rmSync(temp, { recursive: true, force: true });
-}
diff --git a/apps/desktop/scripts/fixtures/cindy-device-picker/device-picker-fixture.tsx b/apps/desktop/scripts/fixtures/cindy-device-picker/device-picker-fixture.tsx
index f18f59ba4b..f0cbf0fd0f 100644
--- a/apps/desktop/scripts/fixtures/cindy-device-picker/device-picker-fixture.tsx
+++ b/apps/desktop/scripts/fixtures/cindy-device-picker/device-picker-fixture.tsx
@@ -1,47 +1,47 @@
import { useState } from 'react';
-import { createRoot } from 'react-dom/client';
-import i18next from 'i18next';
-import { initReactI18next } from 'react-i18next';
-import { MemoryRouter, useLocation } from 'react-router-dom';
-import zh from '../../../src/renderer/i18n/locales/zh-CN/common.json';
-import '../../../src/renderer/themes/colors';
-import { ThemeService } from '../../../src/renderer/themes/theme-service';
-import { defaultLight } from '../../../src/renderer/themes/builtin/default-light';
-import { defaultDark } from '../../../src/renderer/themes/builtin/default-dark';
+import { useLocation } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
+import { AppFrame, mountPage } from '../../ui-page/harness';
import { CindyDeviceRow } from '../../../src/renderer/features/bots/CindyDeviceRow';
-import { BotSessionContentHeader } from '../../../src/renderer/features/bots/BotSessionContentHeader';
+import { BotSessionContentHeaderRegistration } from '../../../src/renderer/features/bots/BotSessionContentHeader';
import { cindyDeviceOptions } from '../../../src/renderer/features/bots/cindyDeviceRoster';
import { Select } from '../../../src/renderer/components/ui/select';
-const query = new URLSearchParams(location.search);
-const dark = query.get('theme') === 'dark';
-new ThemeService().applyTheme(dark ? defaultDark : defaultLight);
-document.documentElement.classList.toggle('dark', dark);
-await i18next.use(initReactI18next).init({
- lng: 'zh-CN',
- resources: { 'zh-CN': { translation: zh } },
-});
+// Roster hooks are replaced at build time (ui-page.mjs `stubs`); the row, picker, header,
+// Radix select, routing, theme and fonts are the production implementations.
+type Roster = Parameters<typeof cindyDeviceOptions>;
-// Only roster hooks are stubbed by the runner; geometry, Radix and routing are real.
-const data = (window as any).devicePickerFixture;
-const options = cindyDeviceOptions(data.bots, data.remoteBots, data.devices, data.unread, '本机');
-function App() {
- const [current, setCurrent] = useState(options[query.has('long') ? 1 : 0]);
+function DevicePickerPage({ data }: { data: Record<string, unknown> }) {
+ const { t } = useTranslation();
+ const roster = data as unknown as {
+ bots: Roster[0];
+ remoteBots: Roster[1];
+ devices: Roster[2];
+ unread: Roster[3];
+ currentIndex: number;
+ selected: boolean;
+ };
+ const options = cindyDeviceOptions(
+ roster.bots,
+ roster.remoteBots,
+ roster.devices,
+ roster.unread,
+ t('bots.devicePicker.local'),
+ );
+ const [current, setCurrent] = useState(options[roster.currentIndex]);
const [opens, setOpens] = useState(0);
const [selections, setSelections] = useState(0);
const route = useLocation();
- return (
- <>
- <p className="fixture-caption">
- {query.get('stage')} · {dark ? 'Dark' : 'Light'} · 生产组件浏览器验证(非实机)
- </p>
- <div className="fixture-layout">
- <aside>
+ // Sidebar list containers mirror TeammatesSection (section > list > rows).
+ const sidebar = (
+ <div className="flex w-full flex-col gap-0.5 pt-3" data-sidebar-section="teammates">
+ <div className="flex flex-col pt-1 pr-0 pl-3">
+ <div className="flex flex-col gap-1" data-ui-page-subject>
<CindyDeviceRow
current={current}
options={options}
- selected={!query.has('unselected')}
- subtitle="已整理好今天的安排。"
+ selected={roster.selected}
+ subtitle={t('bots.list.startChat')}
timestamp="13:56"
onOpen={() => setOpens((count) => count + 1)}
onSelect={(option) => {
@@ -49,32 +49,39 @@ function App() {
setSelections((count) => count + 1);
}}
/>
- </aside>
- <main>
- <header>
- <BotSessionContentHeader bot={options[query.has('long') ? 1 : 0].bot} />
- </header>
- <section className="fixture-results">
- <output data-testid="opens">{opens}</output>
- <output data-testid="selections">{selections}</output>
- <output data-testid="route">{route.pathname}</output>
- <div data-testid="ordinary-select" style={{ width: 180 }}>
- <Select
- label="普通选择器"
- value="one"
- options={[{ value: 'one', label: '普通选项' }]}
- onValueChange={() => {}}
- className="w-full"
- />
- </div>
- </section>
- </main>
+ </div>
</div>
- </>
+ </div>
+ );
+ return (
+ <AppFrame sidebar={sidebar}>
+ <BotSessionContentHeaderRegistration bot={options[roster.currentIndex].bot} />
+ <div className="min-h-0 flex-1 p-6">
+ <output hidden data-testid="opens">
+ {opens}
+ </output>
+ <output hidden data-testid="selections">
+ {selections}
+ </output>
+ <output hidden data-testid="route">
+ {route.pathname}
+ </output>
+ {/* Control sample: the shared Select must keep its trigger-width menu. */}
+ <div data-testid="ordinary-select" style={{ width: 180 }}>
+ <Select
+ label="Select"
+ value="one"
+ options={[{ value: 'one', label: 'Option' }]}
+ onValueChange={() => {}}
+ className="w-full"
+ />
+ </div>
+ </div>
+ </AppFrame>
);
}
-createRoot(document.getElementById('root')!).render(
- <MemoryRouter>
- <App />
- </MemoryRouter>,
-);
+
+void mountPage({
+ route: '/bots/cindy-default',
+ render: (ctx) => <DevicePickerPage data={ctx.data} />,
+});
diff --git a/apps/desktop/scripts/fixtures/cindy-device-picker/ui-page.mjs b/apps/desktop/scripts/fixtures/cindy-device-picker/ui-page.mjs
new file mode 100644
index 0000000000..5818741493
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/cindy-device-picker/ui-page.mjs
@@ -0,0 +1,183 @@
+import assert from 'node:assert/strict';
+
+const longName = 'Studio workstation with a very long device name 工作电脑';
+const roster = {
+ bots: [
+ { id: 'cindy-default', name: 'Cindy', status: 'active', avatar: '', sessionId: 'fixture-chat' },
+ ],
+ remoteBots: [
+ {
+ id: 'cindy-default',
+ deviceId: 'fixture-remote',
+ deviceName: longName,
+ name: 'Cindy',
+ online: false,
+ lastReplyAt: 20,
+ readAt: 10,
+ status: 'active',
+ avatar: '',
+ },
+ ],
+ devices: [{ deviceId: 'self', name: 'Local workstation', isSelf: true }],
+ unread: { 'cindy-default': 3 },
+};
+const data = 'window.__uiPage.ctx.data';
+
+/** DESIGN.md compact Cindy device navigation (replaces the former verify-device-picker.cjs). */
+export default {
+ name: 'device-picker',
+ entry: './device-picker-fixture.tsx',
+ viewport: { width: 1040, height: 520 },
+ real: 'CindyDeviceRow, CindyDevicePicker, BotSessionContentHeader in the ContentHeader shell, shared Select/Radix menu, routing, theme, fonts and translations',
+ notCovered:
+ 'Roster loading and unread state sources, device connections, workbench opening, row context menu',
+ stubs: {
+ 'src/renderer/features/bots/botStore': {
+ partial: `export const useBotProfiles=()=>${data}.bots;export const useBotUnreadCounts=()=>${data}.unread;`,
+ },
+ 'src/renderer/features/bots/useRemoteBots': `export const useRemoteBots=()=>${data}.remoteBots;`,
+ 'src/renderer/features/device-link/useDeviceLinkDeviceList': `export const useDeviceLinkDeviceList=()=>${data}.devices;`,
+ 'src/renderer/features/right-sidebar/lib/openBotWorkbenchTab':
+ 'export const openBotWorkbenchTab=async()=>{};',
+ },
+ cases: {
+ default: {
+ about: 'This device is current and the row is selected; trigger stays compact',
+ data: { ...roster, currentIndex: 0, selected: true },
+ },
+ 'long-name': {
+ about: 'Offline remote device with a long name is current; row not selected',
+ data: { ...roster, currentIndex: 1, selected: false },
+ },
+ },
+ async ready(page) {
+ await page.getByTestId('cindy-device-row').getByRole('combobox').waitFor();
+ await page.locator('header').getByRole('combobox').waitFor();
+ },
+ async check(page, ui) {
+ const long = ui.case === 'long-name';
+ const local = await ui.t('bots.devicePicker.local');
+ const row = page.getByTestId('cindy-device-row');
+ const trigger = row.getByRole('combobox');
+ const header = page.locator('header');
+ const headerTrigger = header.getByRole('combobox');
+ const box = await trigger.boundingBox();
+ const rowBox = await row.boundingBox();
+ const headerBox = await headerTrigger.boundingBox();
+ assert.equal(box.height, 24, 'trigger keeps 24px height');
+ assert.ok(box.x + box.width <= rowBox.x + rowBox.width - 10, 'picker stays inside the row');
+ if (!long)
+ for (const [picker, name] of [
+ [trigger, 'sidebar'],
+ [headerTrigger, 'header'],
+ ]) {
+ // Compact = exactly its label, unread dot and chevron, in every locale.
+ const { actual, natural } = await picker.evaluate((el) => {
+ const actual = el.getBoundingClientRect().width;
+ const previous = el.style.width;
+ el.style.width = 'max-content';
+ const natural = el.getBoundingClientRect().width;
+ el.style.width = previous;
+ return { actual, natural };
+ });
+ assert.ok(
+ Math.abs(actual - natural) < 1,
+ `${name} trigger fits its label (${actual} vs ${natural})`,
+ );
+ }
+ assert.ok(headerBox.width <= 176, 'header trigger maximum 176px');
+ if (long)
+ for (const picker of [trigger, headerTrigger]) {
+ assert.ok(
+ await picker
+ .locator('span')
+ .first()
+ .evaluate((el) => el.scrollWidth > el.clientWidth),
+ 'long device name truncates',
+ );
+ assert.equal(
+ await picker.getAttribute('title'),
+ longName,
+ 'truncated name keeps its title',
+ );
+ }
+ // Blank row area opens the chat once and never the menu.
+ await page.mouse.click(
+ long ? rowBox.x + rowBox.width - 4 : box.x + box.width + 12,
+ box.y + box.height / 2,
+ );
+ assert.equal(await page.getByTestId('opens').textContent(), '1', 'blank area opens chat once');
+ assert.equal(await page.getByRole('listbox').count(), 0, 'blank area does not open the menu');
+ await page.mouse.click(rowBox.x + 20, rowBox.y + 20);
+ assert.equal(await page.getByTestId('opens').textContent(), '2', 'avatar opens chat');
+ await trigger.hover();
+ await ui.capture('hover');
+ await trigger.click();
+ const menu = page.getByRole('listbox');
+ await menu.waitFor();
+ const menuBox = await menu.boundingBox();
+ assert.ok(
+ menuBox.width >= 250 && menuBox.x >= 0 && menuBox.x + menuBox.width <= ui.viewport.width,
+ 'menu is readable and inside the window',
+ );
+ assert.equal(
+ await page.getByTestId('opens').textContent(),
+ '2',
+ 'menu does not also open chat',
+ );
+ const menuText = await menu.innerText();
+ assert.ok(menuText.includes(await ui.t('bots.remote.offline')), 'offline state shown');
+ assert.ok(menuText.includes('3'), 'unread count shown');
+ assert.equal(
+ await menu.getByRole('option', { name: new RegExp(longName) }).getAttribute('title'),
+ longName,
+ );
+ await ui.capture('menu');
+ await page.keyboard.press('Escape');
+ await menu.waitFor({ state: 'detached' });
+ await page.waitForFunction(() =>
+ document.activeElement?.matches('[data-testid="cindy-device-row"] [role="combobox"]'),
+ );
+ await page.keyboard.press('Tab');
+ assert.ok(
+ await header
+ .getByRole('button')
+ .first()
+ .evaluate((el) => el === document.activeElement),
+ 'Tab leaves the picker',
+ );
+ await trigger.focus();
+ await page.keyboard.press('Enter');
+ await menu.waitFor();
+ await page.keyboard.press(long ? 'Home' : 'End');
+ await page.waitForFunction(
+ (label) => document.activeElement?.textContent?.includes(label),
+ long ? local : longName,
+ );
+ await page.keyboard.press('Enter');
+ await menu.waitFor({ state: 'detached' });
+ assert.equal(await page.getByTestId('selections').textContent(), '1', 'keyboard selects once');
+ assert.equal(await page.getByTestId('opens').textContent(), '2', 'selection never opens chat');
+ await trigger.focus();
+ await page.keyboard.press('Space');
+ await menu.waitFor();
+ await page.keyboard.press('Escape');
+ await menu.waitFor({ state: 'detached' });
+ await headerTrigger.click();
+ await menu.getByRole('option', { name: long ? local : new RegExp(longName) }).click();
+ const target = long ? '/bots/cindy-default' : '/bots/remote/fixture-remote/cindy-default';
+ await page.waitForFunction(
+ (route) => document.querySelector('[data-testid="route"]')?.textContent === route,
+ target,
+ );
+ const ordinary = page.getByTestId('ordinary-select').getByRole('combobox');
+ const ordinaryWidth = (await ordinary.boundingBox()).width;
+ await ordinary.click();
+ assert.equal(
+ Math.round((await menu.boundingBox()).width),
+ Math.round(ordinaryWidth),
+ 'ordinary Select keeps trigger-width menu',
+ );
+ await page.keyboard.press('Escape');
+ },
+};
diff --git a/apps/desktop/scripts/fixtures/cindy-device-picker/verify-device-picker.cjs b/apps/desktop/scripts/fixtures/cindy-device-picker/verify-device-picker.cjs
deleted file mode 100644
index a23f2bfa3f..0000000000
--- a/apps/desktop/scripts/fixtures/cindy-device-picker/verify-device-picker.cjs
+++ /dev/null
@@ -1,345 +0,0 @@
-// Run from the repository root. Optional --baseline=<git-ref> captures the old hit target.
-// Uses one headless Chromium, synthetic data, and production components/styles; no Cindy process.
-// Prepare once: pnpm exec playwright-core install chromium
-// Or set DEVICE_PICKER_CHROMIUM_PATH to an existing Chrome/Chromium executable.
-const fs = require('node:fs');
-const path = require('node:path');
-const os = require('node:os');
-const cp = require('node:child_process');
-const assert = require('node:assert/strict');
-const esbuild = require('esbuild');
-const postcss = require('postcss');
-const tailwind = require('tailwindcss');
-const { chromium } = require('playwright-core');
-const root = process.cwd();
-const renderer = path.join(root, 'apps/desktop/src/renderer');
-const evidence = path.resolve(process.env.DEVICE_PICKER_EVIDENCE_DIR || 'artifacts/device-picker');
-const baseline = process.argv.find((arg) => arg.startsWith('--baseline='))?.slice(11);
-const sourceFiles = [
- 'features/bots/CindyDeviceRow.tsx',
- 'features/bots/CindyDevicePicker.tsx',
- 'components/ui/select.tsx',
-];
-const longName = 'Studio workstation with a very long device name 工作电脑';
-const data = {
- bots: [
- {
- id: 'cindy-default',
- name: 'Cindy',
- status: 'active',
- avatar: 'cindy://avatar/preset/cindy',
- sessionId: 'fixture-chat',
- },
- ],
- remoteBots: [
- {
- id: 'cindy-default',
- deviceId: 'fixture-remote',
- deviceName: longName,
- name: 'Cindy',
- online: false,
- lastReplyAt: 20,
- readAt: 10,
- },
- ],
- devices: [{ deviceId: 'self', name: 'Local workstation', isSelf: true }],
- unread: { 'cindy-default': 3 },
-};
-const stubs = {
- botStore:
- 'export const useBotProfiles=()=>window.devicePickerFixture.bots; export const useBotUnreadCounts=()=>window.devicePickerFixture.unread;',
- useRemoteBots: 'export const useRemoteBots=()=>window.devicePickerFixture.remoteBots;',
- useDeviceLinkDeviceList:
- 'export const useDeviceLinkDeviceList=()=>window.devicePickerFixture.devices;',
- openBotWorkbenchTab: 'export const openBotWorkbenchTab=async()=>{};',
-};
-const extraCss = `body{margin:0;background:var(--surface);color:var(--text-primary)}
- .fixture-caption{margin:0;padding:16px;font-size:12px}.fixture-layout{display:flex;min-height:320px}
- aside{width:290px;flex-shrink:0;padding:12px;background:var(--sidebar);border-right:1px solid var(--border-default)}
- main{flex:1;min-width:0}header{height:56px;padding:10px;border-bottom:1px solid var(--border-default)}
- .fixture-results{padding:24px;display:grid;gap:12px}output{display:none}
- @media(max-width:700px){aside{width:220px}}`;
-
-(async () => {
- fs.mkdirSync(evidence, { recursive: true });
- const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-device-picker-'));
- let browser;
- const results = [];
- try {
- browser = await chromium.launch({
- headless: true,
- executablePath: process.env.DEVICE_PICKER_CHROMIUM_PATH || undefined,
- });
- for (const stage of baseline ? ['before', 'after'] : ['after']) {
- const old = stage === 'before';
- const historical = Object.fromEntries(
- old
- ? sourceFiles.map((file) => [
- path.join(renderer, file),
- cp.execFileSync('git', ['show', `${baseline}:apps/desktop/src/renderer/${file}`], {
- encoding: 'utf8',
- }),
- ])
- : [],
- );
- const cfg = require('tailwindcss/loadConfig')(
- path.join(root, 'apps/desktop/tailwind.config.ts'),
- );
- cfg.content = [
- path.join(
- renderer,
- 'features/bots/{CindyDevicePicker,CindyDeviceRow,BotAvatar,BotConnectionStatus,BotSessionContentHeader}.tsx',
- ),
- path.join(renderer, 'components/ui/{select,button,spinner}.tsx'),
- ...Object.values(historical).map((raw) => ({ raw, extension: 'tsx' })),
- ];
- const css = (
- await postcss([tailwind(cfg)]).process(
- fs.readFileSync(path.join(renderer, 'styles/generated/tokens.css'), 'utf8') +
- '\n' +
- fs
- .readFileSync(path.join(renderer, 'styles/globals.css'), 'utf8')
- .replace(/^@import.*$/gm, ''),
- { from: undefined },
- )
- ).css;
- const bundle = path.join(temp, `${stage}.js`);
- await esbuild.build({
- entryPoints: [path.join(__dirname, 'device-picker-fixture.tsx')],
- outfile: bundle,
- bundle: true,
- format: 'esm',
- platform: 'browser',
- jsx: 'automatic',
- loader: { '.png': 'dataurl', '.svg': 'dataurl', '.woff2': 'dataurl' },
- define: { 'import.meta.env.PROD': 'true', 'import.meta.env.DEV': 'false' },
- plugins: [
- {
- name: 'fixture-roster',
- setup(build) {
- build.onResolve(
- {
- filter: /botStore$|useRemoteBots$|useDeviceLinkDeviceList$|openBotWorkbenchTab$/,
- },
- (args) => ({ path: path.basename(args.path), namespace: 'stub' }),
- );
- build.onLoad({ filter: /.*/, namespace: 'stub' }, (args) => ({
- contents: stubs[args.path],
- loader: 'js',
- }));
- build.onResolve({ filter: /^@\// }, (args) => {
- const base = path.join(renderer, args.path.slice(2));
- const resolved = ['', '.tsx', '.ts', '.js', '/index.tsx', '/index.ts']
- .map((suffix) => base + suffix)
- .find((file) => fs.existsSync(file) && fs.statSync(file).isFile());
- return { path: resolved };
- });
- build.onLoad({ filter: /\.(tsx?|js)$/ }, (args) =>
- historical[args.path]
- ? {
- contents: historical[args.path],
- loader: args.path.endsWith('tsx') ? 'tsx' : 'ts',
- }
- : undefined,
- );
- },
- },
- ],
- logLevel: 'warning',
- });
- const buttonCss = fs.readFileSync(bundle.replace(/\.js$/, '.css'), 'utf8');
- for (const theme of ['light', 'dark'])
- for (const width of [1040, 560])
- for (const long of [false, true]) {
- const page = await browser.newPage({ viewport: { width, height: 400 } });
- page.setDefaultTimeout(8000);
- console.log('Checking', stage, theme, width, long);
- const errors = [];
- page.on('pageerror', (error) => errors.push(error.message));
- await page.route('http://fixture.local/**', (route) =>
- route.fulfill({
- contentType: 'text/html',
- body: `<!doctype html><html><head><meta charset="utf-8"><style>${css}${buttonCss}${extraCss}</style></head><body><div id="root"></div><script>window.devicePickerFixture=${JSON.stringify(data)}</script><script type="module">${fs.readFileSync(bundle, 'utf8').replace(/<\/script/gi, '<\\/script')}</script></body></html>`,
- }),
- );
- await page.goto(
- `http://fixture.local/?stage=${stage}&theme=${theme}${long ? '&long&unselected' : ''}`,
- );
- const row = page.getByTestId('cindy-device-row');
- const trigger = row.getByRole('combobox');
- const header = page.locator('header');
- await trigger.waitFor();
- const box = await trigger.boundingBox();
- const rowBox = await row.boundingBox();
- const headerBox = await header.getByRole('combobox').boundingBox();
- assert.equal(box.height, 24);
- if (!old) {
- assert.ok(box.x + box.width <= rowBox.x + rowBox.width - 10, 'sidebar bounds');
- if (!long) {
- assert.ok(box.width < 100, 'compact sidebar');
- assert.ok(headerBox.width < 100, 'compact header');
- }
- assert.ok(headerBox.width <= 176, 'header maximum');
- assert.equal(
- await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
- false,
- 'no horizontal overflow',
- );
- if (long) {
- for (const picker of [trigger, header.getByRole('combobox')]) {
- assert.equal(
- await picker
- .locator('span')
- .first()
- .evaluate((el) => el.scrollWidth > el.clientWidth),
- true,
- 'long device name is truncated',
- );
- assert.equal(await picker.getAttribute('title'), longName);
- }
- }
- const point = { x: rowBox.x + rowBox.width - 4, y: box.y + box.height / 2 };
- if (!long) point.x = box.x + box.width + 12;
- await page.mouse.click(point.x, point.y);
- assert.equal(
- await page.getByTestId('opens').textContent(),
- '1',
- 'blank area opens chat exactly once',
- );
- assert.equal(
- await page.getByRole('listbox').count(),
- 0,
- 'blank area does not open menu',
- );
- await page.mouse.click(rowBox.x + 20, rowBox.y + 20);
- assert.equal(await page.getByTestId('opens').textContent(), '2', 'avatar opens chat');
- }
- await trigger.hover();
- const name = `${stage}-${theme}-${width}-${long ? 'long-name' : 'local'}`;
- await page.screenshot({ path: path.join(evidence, `${name}.png`) });
- if (old && !long) {
- await page.mouse.click(box.x + 110, box.y + box.height / 2);
- } else await trigger.click();
- const menu = page.getByRole('listbox');
- await menu.waitFor();
- if (old && !long)
- assert.equal(
- await page.getByTestId('opens').textContent(),
- '0',
- 'baseline blank area opens menu instead of chat',
- );
- if (!old) {
- const menuBox = await menu.boundingBox();
- assert.ok(
- menuBox.width >= 250 && menuBox.x >= 0 && menuBox.x + menuBox.width <= width,
- 'readable bounded menu',
- );
- assert.equal(
- await page.getByTestId('opens').textContent(),
- '2',
- 'menu does not also open chat',
- );
- assert.ok((await menu.innerText()).includes('离线'));
- assert.ok((await menu.innerText()).includes('3'));
- const option = menu.getByRole('option', { name: new RegExp(longName) });
- assert.equal(await option.getAttribute('title'), longName);
- }
- await page.screenshot({ path: path.join(evidence, `${name}-menu.png`) });
- await page.keyboard.press('Escape');
- await menu.waitFor({ state: 'detached' });
- if (!old) {
- await page.waitForFunction(() =>
- document.activeElement?.matches(
- '[data-testid="cindy-device-row"] [role="combobox"]',
- ),
- );
- assert.equal(
- await trigger.evaluate((el) => el === document.activeElement),
- true,
- 'Escape restores focus',
- );
- await page.keyboard.press('Tab');
- assert.equal(
- await header
- .getByRole('button')
- .first()
- .evaluate((el) => el === document.activeElement),
- true,
- 'Tab leaves picker',
- );
- await trigger.focus();
- await page.keyboard.press('Enter');
- await menu.waitFor();
- await page.keyboard.press(long ? 'Home' : 'End');
- await page.waitForFunction(
- (label) => document.activeElement?.textContent?.includes(label),
- long ? '本机' : longName,
- );
- await page.keyboard.press('Enter');
- await menu.waitFor({ state: 'detached' });
- assert.equal(
- await page.getByTestId('selections').textContent(),
- '1',
- 'keyboard selection once',
- );
- assert.equal(
- await page.getByTestId('opens').textContent(),
- '2',
- 'selection never opens chat',
- );
- await trigger.focus();
- await page.keyboard.press('Space');
- await menu.waitFor();
- await page.keyboard.press('Escape');
- await menu.waitFor({ state: 'detached' });
- await header.getByRole('combobox').click();
- await menu
- .getByRole('option', { name: long ? '本机' : new RegExp(longName) })
- .click();
- await page.waitForFunction(
- (route) => document.querySelector('[data-testid="route"]')?.textContent === route,
- long ? '/bots/cindy-default' : '/bots/remote/fixture-remote/cindy-default',
- );
- assert.equal(
- await page.getByTestId('route').textContent(),
- long ? '/bots/cindy-default' : '/bots/remote/fixture-remote/cindy-default',
- 'header routes to selected device',
- );
- const ordinary = page.getByTestId('ordinary-select').getByRole('combobox');
- const ordinaryWidth = (await ordinary.boundingBox()).width;
- await ordinary.click();
- assert.equal(
- Math.round((await menu.boundingBox()).width),
- Math.round(ordinaryWidth),
- 'ordinary Select remains equal width',
- );
- await page.keyboard.press('Escape');
- }
- assert.deepEqual(errors, []);
- results.push({
- stage,
- theme,
- width,
- long,
- sidebarWidth: box.width,
- headerWidth: headerBox.width,
- height: box.height,
- });
- await page.close();
- }
- }
- fs.writeFileSync(
- path.join(evidence, 'device-picker-measurements.json'),
- JSON.stringify(results, null, 2),
- );
- console.log(
- JSON.stringify({ passed: true, scenarios: results.length, evidence, results }, null, 2),
- );
- } finally {
- await browser?.close();
- fs.rmSync(temp, { recursive: true, force: true });
- }
-})().catch((error) => {
- console.error(error);
- process.exitCode = 1;
-});
diff --git a/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx
index ff7e5d9822..24b8a05a70 100644
--- a/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx
+++ b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx
@@ -1,133 +1,88 @@
-import React from 'react';
-import { createRoot } from 'react-dom/client';
-import i18next from 'i18next';
-import { initReactI18next } from 'react-i18next';
-import { MemoryRouter, Routes, Route } from 'react-router-dom';
-import zh from '../../../src/renderer/i18n/locales/zh-CN/common.json';
-import '../../../src/renderer/themes/colors';
-import { ThemeService } from '../../../src/renderer/themes/theme-service';
-import { defaultLight } from '../../../src/renderer/themes/builtin/default-light';
-import { defaultDark } from '../../../src/renderer/themes/builtin/default-dark';
-import {
- FeatureSidebarSlotProvider,
- useFeatureContentHeader,
-} from '../../../src/renderer/features/feature-context';
+import { Route, Routes } from 'react-router-dom';
+import { AppFrame, forbid, mountPage, subscription } from '../../ui-page/harness';
import { BotGroupChatView } from '../../../src/renderer/features/bots/BotGroupChatView';
import { ControlledBanner } from '../../../src/renderer/features/remote-device/ControlledBanner';
-import { ConfirmDialogProvider } from '../../../src/renderer/components/ui/confirm-dialog-provider';
-const q = new URLSearchParams(location.search);
-const dark = q.get('theme') === 'dark';
-new ThemeService().applyTheme(dark ? defaultDark : defaultLight);
-document.documentElement.classList.toggle('dark', dark);
-await i18next
- .use(initReactI18next)
- .init({
- lng: 'zh-CN',
- resources: { 'zh-CN': { translation: zh } },
- interpolation: { escapeValue: false },
- });
-const member = (botId: string, name: string) => ({
- botId,
- name,
- avatar: '',
- avatarColor: 'gray',
- status: 'active',
-});
-const group = {
- id: 'fixture-group',
- name: '设计讨论',
- replyMode: 'all',
- speakingMode: 'auto',
- members: [member('a', 'Aster'), member('b', 'Nova')],
- organizerBotId: 'a',
- projectDir: null,
- lastMessage: null,
- speakingBotIds: [],
- planningBotId: null,
- openPlan: null,
- createdAt: 1,
- updatedAt: 1,
- plans: [],
- messages: q.has('thread')
- ? Array.from({ length: 40 }, (_, i) => ({
- id: `m${i}`,
- sequence: i + 1,
- kind: 'message',
- authorKind: 'user',
- authorBotId: null,
- authorName: '',
- content: `布局回归消息 ${i + 1}`,
- mentions: { all: false, botIds: [] },
- noticeCode: null,
- planId: null,
- files: [],
- createdAt: 1700000000000 + i,
- }))
- : [],
- hasMoreBefore: false,
- round: { status: 'idle', speakers: [], canContinue: false },
-};
-(window as any).fixtureMutations = [];
-const blocked = () => {
- (window as any).fixtureMutations.push('forbidden mutation');
- throw Error('Fixture forbids mutations');
-};
-window.electronAPI = {
- maker: {
- listBotGroups: async () => ({ ok: true, groups: [] }),
- getBotGroup: async () => ({ ok: true, group }),
- onBotGroupChanged: () => () => {},
- sendBotGroupMessage: blocked,
- stopBotGroupRound: blocked,
- },
- deviceLink: {
- getState: async () => ({ controlledBy: [] }),
- onControlledState: (
- cb: (payload: { controllers: Array<{ deviceId: string; name: string }> }) => void,
- ) => {
- (window as any).fixturePush = cb;
- return () => {};
- },
- revoke: blocked,
- },
-} as any;
-function Header() {
- return <header>{useFeatureContentHeader()}</header>;
+
+interface GroupData {
+ name: string;
+ members: Array<{ botId: string; name: string }>;
+ messages: number;
+ sidebar: boolean;
+}
+
+function groupFrom(data: GroupData) {
+ return {
+ id: 'fixture-group',
+ name: data.name,
+ replyMode: 'all',
+ speakingMode: 'auto',
+ members: data.members.map((member) => ({
+ ...member,
+ avatar: '',
+ avatarColor: 'gray',
+ status: 'active',
+ })),
+ organizerBotId: data.members[0]?.botId ?? null,
+ projectDir: null,
+ lastMessage: null,
+ speakingBotIds: [],
+ planningBotId: null,
+ openPlan: null,
+ createdAt: 1,
+ updatedAt: 1,
+ plans: [],
+ messages: Array.from({ length: data.messages }, (_, i) => ({
+ id: `m${i}`,
+ sequence: i + 1,
+ kind: 'message',
+ authorKind: 'user',
+ authorBotId: null,
+ authorName: '',
+ content: `Layout message ${i + 1}`,
+ mentions: { all: false, botIds: [] },
+ noticeCode: null,
+ planId: null,
+ attachments: [],
+ createdAt: 1700000000000 + i,
+ })),
+ hasMoreBefore: false,
+ round: { status: 'idle', speakers: [], canContinue: false },
+ };
}
-createRoot(document.getElementById('root')!).render(
- <MemoryRouter initialEntries={['/bots/groups/fixture-group']}>
- <ConfirmDialogProvider>
- <FeatureSidebarSlotProvider isCollapsed={false}>
- <div className="fixture-caption">
- {q.get('stage')} · {dark ? '深色' : '浅色'} · 生产群聊组件 Fixture,非实机
- </div>
- <div className="fixture-shell">
- <aside style={{ width: Number(q.get('sidebar')) }}>
- 伙伴
- <br />
- <br />
- Aster
- <br />
- <br />
- Nova
- <br />
- <br />
- 群聊
- <br />
- <br />
- 设计讨论
- </aside>
- <section className="fixture-content">
- <Header />
- <div className="fixture-view">
- <Routes>
- <Route path="/bots/groups/:groupId" element={<BotGroupChatView />} />
- </Routes>
- </div>
- </section>
- </div>
+
+void mountPage({
+ route: '/bots/groups/fixture-group',
+ host: (ctx) => {
+ const group = groupFrom(ctx.data as unknown as GroupData);
+ return {
+ maker: {
+ listBotGroups: async () => ({ ok: true, groups: [] }),
+ getBotGroup: async () => ({ ok: true, group }),
+ onBotGroupChanged: subscription('botGroupChanged'),
+ sendBotGroupMessage: forbid('maker.sendBotGroupMessage'),
+ stopBotGroupRound: forbid('maker.stopBotGroupRound'),
+ },
+ deviceLink: {
+ getState: async () => ({ controlledBy: [] }),
+ onControlledState: subscription('controlledState'),
+ revoke: forbid('deviceLink.revoke'),
+ },
+ };
+ },
+ render: (ctx) => {
+ const data = ctx.data as unknown as GroupData;
+ const sidebar = data.sidebar ? <div className="p-5" /> : undefined;
+ return (
+ <>
+ <AppFrame sidebar={sidebar}>
+ <div className="min-h-0 flex-1" data-ui-page-subject>
+ <Routes>
+ <Route path="/bots/groups/:groupId" element={<BotGroupChatView />} />
+ </Routes>
+ </div>
+ </AppFrame>
<ControlledBanner />
- </FeatureSidebarSlotProvider>
- </ConfirmDialogProvider>
- </MemoryRouter>,
-);
+ </>
+ );
+ },
+});
diff --git a/apps/desktop/scripts/fixtures/group-control/ui-page.mjs b/apps/desktop/scripts/fixtures/group-control/ui-page.mjs
new file mode 100644
index 0000000000..eadc742018
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/group-control/ui-page.mjs
@@ -0,0 +1,194 @@
+import assert from 'node:assert/strict';
+
+const members = [
+ { botId: 'a', name: 'Aster' },
+ { botId: 'b', name: 'Nova' },
+];
+const base = { name: 'Design review', members, messages: 0, sidebar: true };
+const LONG_DEVICE = 'Mac Studio · A very long device name for layout verification';
+
+/** Migrated from check-group-control-layout.mjs (remote-control notice above the composer). */
+export default {
+ name: 'group-chat',
+ entry: './group-control-fixture.tsx',
+ viewport: { width: 1280, height: 800 },
+ real: 'BotGroupChatView (timeline, composer, send button, header registration), ControlledBanner, ContentHeader shell, Markdown, theme, fonts and translations',
+ notCovered:
+ 'Sending, round control, real device-link control and revocation, pending interactions, plans and attachments; the sidebar is an empty frame',
+ cases: {
+ default: { about: 'Empty group, short controller name, expanded sidebar', data: base },
+ 'long-thread': {
+ about: '40 messages: bottom pin and history position survive notice changes',
+ viewport: { width: 800, height: 600 },
+ data: { ...base, messages: 40 },
+ },
+ 'long-device': {
+ about: 'Long controller device name in the notice',
+ data: base,
+ controller: LONG_DEVICE,
+ },
+ multiline: { about: 'Eight-line draft pushes the composer up', data: base, lines: 8 },
+ 'no-sidebar': { about: 'Collapsed sidebar layout', data: { ...base, sidebar: false } },
+ },
+ async ready(page) {
+ await page.locator('textarea').waitFor();
+ },
+ async check(page, ui) {
+ const definition = this.cases[ui.case];
+ const input = page.locator('textarea');
+ const chip = page.locator('[data-controlled-banner-chip]');
+ const collapsedDot = page.locator('[data-controlled-banner="collapsed"]');
+ const scroller = page.getByTestId('bot-group-timeline');
+ const connect = async (connected = true) => {
+ const name = definition.controller ?? 'Mac Studio';
+ assert.ok(
+ await ui.emit('controlledState', {
+ controllers: connected ? [{ deviceId: 'fixture', name }] : [],
+ }),
+ 'banner subscribed to controlled state',
+ );
+ await chip.waitFor({ state: connected ? 'visible' : 'detached' });
+ };
+ const collapse = async () => {
+ await page.locator('[data-controlled-banner-collapse]').click();
+ await collapsedDot.waitFor();
+ assert.equal(await chip.count(), 0);
+ };
+ const expand = async () => {
+ await collapsedDot.click();
+ await chip.waitFor();
+ };
+
+ if (ui.case === 'long-thread') {
+ const bottomGap = () =>
+ scroller.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop);
+ await page.waitForFunction(() => {
+ const el = document.querySelector('[data-testid="bot-group-timeline"]');
+ return (
+ el &&
+ el.scrollHeight > el.clientHeight &&
+ el.scrollHeight - el.clientHeight - el.scrollTop < 1
+ );
+ });
+ for (const [step, action] of [
+ ['connection', () => connect()],
+ ['collapse', collapse],
+ ['expand', expand],
+ ['disconnection', () => connect(false)],
+ ]) {
+ await action();
+ assert.ok((await bottomGap()) < 1, `${step} keeps the thread pinned to the bottom`);
+ }
+ const before = await scroller.evaluate((el) => {
+ el.scrollTop = 180;
+ el.dispatchEvent(new Event('scroll', { bubbles: true }));
+ return el.scrollTop;
+ });
+ for (const [step, action] of [
+ ['connection', () => connect()],
+ ['collapse', collapse],
+ ['expand', expand],
+ ['disconnection', () => connect(false)],
+ ]) {
+ await action();
+ assert.equal(
+ await scroller.evaluate((el) => el.scrollTop),
+ before,
+ `${step} keeps history position`,
+ );
+ }
+ await connect();
+ await ui.capture('history');
+ return;
+ }
+
+ await connect();
+ await input.fill(
+ Array(definition.lines ?? 1)
+ .fill('Layout check only; never sent.')
+ .join('\n'),
+ );
+ // BotGroupComposer labels its send button with bots.send (not the shared SendButton default).
+ const sendLabel = await ui.t('bots.send');
+ const layout = await page.evaluate((sendLabel) => {
+ const notice = document.querySelector('[data-controlled-banner-chip]');
+ const textarea = document.querySelector('textarea');
+ const card = textarea.parentElement.getBoundingClientRect();
+ const send = textarea.parentElement.querySelector(`button[aria-label="${sendLabel}"]`);
+ const reachable = (el) => {
+ if (!el) return false;
+ const r = el.getBoundingClientRect();
+ return el.contains(document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2));
+ };
+ const n = notice.getBoundingClientRect();
+ return {
+ centerDelta: Math.abs(n.x + n.width / 2 - card.x - card.width / 2),
+ above: n.bottom <= card.y,
+ reachable: [
+ textarea,
+ send,
+ notice.querySelector('button'),
+ notice.querySelector('[data-controlled-banner-collapse]'),
+ ].map(reachable),
+ };
+ }, sendLabel);
+ assert.ok(layout.centerDelta < 1, 'notice is centered on the composer');
+ assert.ok(layout.above, 'notice sits above the composer');
+ assert.deepEqual(
+ Object.fromEntries(
+ ['input', 'send', 'revoke', 'collapse'].map((name, i) => [name, layout.reachable[i]]),
+ ),
+ { input: true, send: true, revoke: true, collapse: true },
+ `input, send ("${sendLabel}"), revoke and collapse are clickable`,
+ );
+ await ui.capture('connected');
+ await collapse();
+ const dot = await page.evaluate(() => {
+ const el = document.querySelector('[data-controlled-banner="collapsed"]');
+ const r = el.getBoundingClientRect();
+ const card = document.querySelector('textarea').parentElement.getBoundingClientRect();
+ return {
+ centerDelta: Math.abs(r.x + r.width / 2 - card.x - card.width / 2),
+ above: r.bottom <= card.y,
+ reachable: el.contains(document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2)),
+ };
+ });
+ assert.ok(dot.centerDelta < 1 && dot.above && dot.reachable, 'collapsed indicator placement');
+ await ui.capture('collapsed');
+ await expand();
+ // Reach the notice through normal tab order; both activation keys toggle it.
+ const viaKeyboard = async (selector, key) => {
+ await input.focus();
+ await page.keyboard.press('Shift+Tab');
+ const target = page.locator(selector);
+ assert.ok(
+ await target.evaluate(
+ (el) =>
+ el === document.activeElement &&
+ Boolean(el.getAttribute('aria-label')) &&
+ el.matches(':focus-visible') &&
+ getComputedStyle(el).boxShadow !== 'none',
+ ),
+ `${selector} is keyboard reachable with visible focus`,
+ );
+ await page.keyboard.press(key);
+ };
+ for (const key of ['Enter', 'Space']) {
+ await viaKeyboard('[data-controlled-banner-collapse]', key);
+ await collapsedDot.waitFor();
+ await viaKeyboard('[data-controlled-banner="collapsed"]', key);
+ await chip.waitFor();
+ }
+ await input.focus();
+ await page.keyboard.press('Shift+Tab');
+ await page.keyboard.press('Shift+Tab');
+ assert.ok(
+ await chip
+ .locator('button')
+ .first()
+ .evaluate((el) => el === document.activeElement),
+ 'revoke is a separate tab stop',
+ );
+ assert.equal(await page.getByRole('dialog').count(), 0, 'folding never opens a dialog');
+ },
+};
diff --git a/apps/desktop/scripts/ui-page/README.md b/apps/desktop/scripts/ui-page/README.md
new file mode 100644
index 0000000000..da25548f07
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/README.md
@@ -0,0 +1,197 @@
+# 单页 UI 快速验证
+
+只编译要看的真实 renderer 组件,在隔离窗口里按场景渲染、检查、截图后退出。不启动 Forge、
+Vite、main、登录、数据库、模型或插件,也不碰正式 Cindy 的数据。适合 Agent 在改完界面后
+自检,以及人工快速看一个页面。何时用它、何时必须回到完整 Desktop,见
+[`desktop-development.md`「按改动选择验证方式」](../../../../docs/dev-rules/desktop-development.md)。
+
+```sh
+pnpm ui:check --changed --theme all # 本分支改动涉及的页面,全部场景
+pnpm ui:check --page device-picker --locale all # 五种语言
+pnpm ui:check --page group-chat --case all --theme all --viewport 720x600,1280x800
+pnpm ui:check --page group-chat --case long-device --compare # 改前/改后对照
+pnpm ui:check --page group-chat --case long-device --focus '[data-controlled-banner-chip]' # 放大看一个元素并量尺寸
+pnpm ui:check --entry tmp/my-card.tsx --case all # 还没注册的组件
+pnpm ui:check --list # 已注册页面与场景
+pnpm ui:preview --page group-chat --case long-thread # 人工验收:保持窗口,改文件自动重载
+```
+
+## 读结果
+
+```
+UI_CHECK failed 9/10 variants · 6.1s (build 2246ms, launch 232ms)
+overview: artifacts/ui-check/group-chat-xxxx/overview.png
+page group-chat: real — BotGroupChatView, ControlledBanner, …
+ not covered — Sending, round control, …
+ replaced — none
+FAIL group-chat.no-sidebar.dark.zh-CN.1280x800
+ error: …
+ host APIs read but not provided: maker.listBotGroupPlans
+```
+
+- 每个变体 id 是 `页面.场景.主题.语言.宽x高`。退出码:0 通过,1 有变体失败,2 参数错误。
+- **先看 `overview.png`**:截图按变体排列,每张最多 6 个变体,更多的写到 `overview-2.png`
+ 等并在首行列出;`--compare` 时同一步骤的改前/改后并排。命令通过只代表断言和通用检查
+ 通过,视觉是否合理仍要看图。
+- 改动集中在一个元素(间距、截断、对齐)时加 `--focus <CSS 选择器>`:每次截图另存该元素
+ 周围的 2 倍放大图(`*.focus.png`),overview 只放这些放大图,报告逐行给出元素尺寸、
+ padding、gap、字号/行高/字重和被裁切的子元素数;与 `--compare` 一起用时改前数值同时
+ 列出,可以直接比对。元素在某次截图时不存在会跳过,全程都不存在才给警告。
+- 截图按 2 倍像素密度渲染(与 Retina Mac 一致,不随外接显示器变化),整页截图按 CSS
+ 尺寸保存。
+- 报告写到 stdout。环境里设置了 `NODE_DEBUG` 时 Node 会往 stderr 刷调试日志,用
+ `env -u NODE_DEBUG pnpm ui:check …` 或丢弃 stderr。
+- `real` 是本页面真实加载的产品代码,`not covered` 是这些场景没有验证的行为,`replaced`
+ 是被场景替换掉的模块(替换的模块本身没有被验证)。
+- 证据目录只保留最近 20 次运行;`summary.json` 有每个变体的截图、错误、警告、耗时、宿主缺失
+ 接口和 Electron/Chromium 版本,`--json` 直接输出它。
+
+每个变体都会自动检查,出现以下情况判为失败:
+
+- 页面报错、控制台 error、尝试访问测试源以外的网络;
+- 横向溢出;
+- 界面上出现原样的翻译 key;
+- 调用了场景用 `forbid()` 声明为禁止的宿主写接口。
+
+以下只给警告:文字被裁切、截断文本没有 `title`、当前语言缺少翻译而回退到其他语言。
+
+## `--changed` 的覆盖含义
+
+`--changed` 读取相对上游主干的改动(含未提交和未跟踪文件),选出真实加载了这些文件的页面,
+默认跑全部场景:
+
+- `loaded` 文件被某页面加载。加载不等于被渲染到,具体分支是否出现取决于场景。
+- `STUBBED` 文件在该页面里被替换,等于没验证。
+- `UNCOVERED` 是 renderer 里没有任何页面加载的界面文件,**未被验证**:补一个场景、用
+ `--entry` 临时挂载,或在完整 Desktop 里验收。
+
+## 发 PR 时带图
+
+每次检查都会在输出目录写 `pr.md`,报告里有一行 `pr:` 给出路径。内容对应 PR 模板「UI 变化」:
+截图来源(命令、平台、Electron/Chromium 版本,注明是场景数据)、版本与是否含未提交改动、
+通过情况、每个页面的场景与未覆盖行为、被替换的模块、改前/改后对照、`--focus` 实测数值
+(改前 → 改后)、未通过的场景和 `--changed` 没覆盖到的文件。
+
+发 PR 前运行 `pnpm ui:check:publish`(默认取最近一次运行,也可以传运行目录):
+
+- 把该次运行的 `overview*.png` 作为一个提交推到作者 fork 的 `pr-assets/<当前分支>`。提交只含
+ 截图、不与产品历史相连;同一分支多次发布时依次追加,旧链接继续有效。不改工作区、索引和
+ 当前分支,截图不会进入上游仓库;目标远端就是 PR 的目标仓库时直接拒绝。
+- 输出 `pr.published.md`:`pr.md` 加上按提交 SHA 固定的图片链接,原样写进 PR 正文「UI 变化」。
+- 默认推到第一个不是上游仓库的 GitHub 远端(通常是 `origin`),可用 `--remote`/`--branch`
+ 指定;`--dry-run` 只生成内容不推送。
+
+普通界面改动用这些截图即可。登录、发送、跨设备等单页验证覆盖不到的变化,仍附完整 Cindy
+截图;设计系统 PR 的证据要求见
+[`design-governance.md` §6](../../../../docs/design-rules/design-governance.md)。
+
+## 多语言、主题与尺寸
+
+`--locale` 取自 `src/shared/locale.ts` 的 `SUPPORTED_LOCALES`,`--theme` 为 `light`/`dark`,
+都可以写逗号列表或 `all`;`--viewport` 可以写多个尺寸。所有组合在同一个窗口里依次运行。
+语言和主题按产品启动时的同一套偏好写入(`localStorage` 的 `theme` 与语言偏好),字体使用产品
+自带的 Inter、JetBrains Mono 与鸿蒙黑体子集。断言里不要写死某种语言的文字,用 `ui.t(key)`
+取当前语言的翻译。
+
+## 场景与数据模拟
+
+注册页面放在 `apps/desktop/scripts/fixtures/<名>/ui-page.mjs`,会被自动发现:
+
+```js
+export default {
+ name: 'device-picker',
+ entry: './device-picker-fixture.tsx', // 调用 mountPage() 的入口
+ viewport: { width: 1040, height: 520 },
+ real: '真实加载的组件',
+ notCovered: '这些场景不验证的行为',
+ stubs: { /* 见下 */ },
+ cases: {
+ default: { about: '一句话说明场景', data: { /* 传给页面的 JSON */ } },
+ 'long-name': { about: '…', data: { … }, viewport: { width: 800, height: 600 } },
+ },
+ async ready(page) {}, // 可选:截图前等待
+ async check(page, ui) {}, // 可选:交互与断言
+};
+```
+
+入口里用 harness 挂载真实组件:
+
+```tsx
+import { AppFrame, ctx, forbid, mountPage, subscription } from '../../ui-page/harness';
+
+mountPage({
+ 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>,
+});
+```
+
+数据按从轻到重三种方式提供,优先用前一种:
+
+1. **宿主接口(`host`)**。页面代码通过 `window.electronAPI` 读取数据时,直接在场景里给出。
+ 没给出的接口读取为 `undefined` 并记录到 `host APIs read but not provided`,页面失败时据此
+ 补数据。会改动用户数据的接口用 `forbid(name)` 声明:调用即失败。推送事件用
+ `subscription(name)`,在 `check` 里用 `await ui.emit(name, payload)` 触发。
+2. **`ctx.data`**。场景的 `data` 原样传给入口,用于组件 props 或宿主数据。
+3. **模块替换(`stubs`)**,只在 store 或 hook 无法经宿主接口喂数据时使用。键是相对
+ `apps/desktop` 的模块路径(不带扩展名):
+ - 字符串:整个模块换成这段代码;
+ - `{ file: './x.ts' }`:换成场景目录下的文件;
+ - `{ partial: '…' }`:保留真实模块,只覆盖其中几个导出。
+
+ 被替换的模块会列在报告的 `replaced` 里,不算被验证。
+
+`AppFrame` 复刻主界面的侧栏(默认 260px)与内容区结构,并挂载真实的 `ContentHeaderSlot`,
+让页面在真实宽度和标题栏里排版;不需要外框时直接渲染组件。
+
+`check(page, ui)` 里的 `page` 是 Playwright Page。`ui` 包含当前变体
+(`case`、`theme`、`locale`、`viewport`、`data`)以及:
+
+- `ui.capture(name, { locator })`:额外截图;
+- `ui.t(key, values)`:当前语言的翻译;
+- `ui.emit(name, payload)`:推送事件。
+
+每个变体都自动截 `initial`;有 `check` 时结束再截 `final`。
+
+### 临时入口
+
+还没注册的组件,写一个调用 `mountPage()` 的文件即可,放在 Git 忽略的 `tmp/` 下:
+
+```tsx
+import { mountPage } from '../apps/desktop/scripts/ui-page/harness';
+import { Switch } from '../apps/desktop/src/renderer/components/ui/switch';
+
+mountPage({ cases: ['off', 'on'], render: (ctx) => <Switch checked={ctx.case === 'on'} /> });
+```
+
+`pnpm ui:check --entry tmp/switch.tsx --case all --theme all` 运行声明的全部场景,只做通用检查和
+截图。组件会反复回归时,再注册成页面并写 `check`。
+
+## 改前/改后对照
+
+`--compare [<ref>]` 把本页面加载的产品源码(`apps/desktop/src`、`packages`)换回 `<ref>` 的
+版本再渲染一次;不写 `<ref>` 时用本分支与上游主干的分叉点,也就是“本分支改动之前”。场景与
+harness 始终用当前版本,所以两边执行同样的步骤、截同样的图。没有文件不同时不重复渲染。
+改前一侧的断言失败不影响结果,在报告里以 `before <ref>:` 开头逐条列出;`<ref>` 之后才新增的文件按当前版本使用并列出。
+
+## 运行方式
+
+- 默认 `--engine electron`:仓库里的 Electron,与 Cindy 同一个 Chromium。每次运行使用新的
+ 临时 profile、拒绝权限与下载、只允许访问测试源,运行完删除临时数据;后台检查不显示窗口、
+ 不占 Dock。
+- `--engine chromium`:Playwright Chromium 或本机 Chrome(`--browser <路径>` 指定)。
+- `--timeout` 是每个变体的超时(默认 20 秒);Ctrl+C 会写完 `summary.json` 并关闭窗口。
+- `ui:preview` 只用于人工验收:显示一个窗口,依赖的源码、样式、翻译或场景变化后自动重载,
+ 关窗或 Ctrl+C 结束。自动检查不要用它保持窗口。修改运行器、依赖或 Tailwind 配置后重启命令。
+
+## 维护
+
+运行器自身的回归:`pnpm ui:check:selftest`(node:test,会打开 Electron,不属于 `test:unit`)。
+覆盖页面报错、外网请求、禁止写入、宿主缺失记录、原样翻译 key、超时与中断后的清理。改动
+`ui-page/` 后运行它,并跑一遍已注册页面。
diff --git a/apps/desktop/scripts/ui-page/audit.mjs b/apps/desktop/scripts/ui-page/audit.mjs
new file mode 100644
index 0000000000..77b944c138
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/audit.mjs
@@ -0,0 +1,66 @@
+/**
+ * Generic checks every variant receives, evaluated inside the page. Errors fail the
+ * variant; warnings are reported for the agent to judge against the screenshots.
+ */
+export function pageAudit() {
+ const describe = (el) => {
+ const testId = el.getAttribute('data-testid');
+ const classes =
+ typeof el.className === 'string'
+ ? el.className.trim().split(/\s+/).slice(0, 3).join('.')
+ : '';
+ return `${el.tagName.toLowerCase()}${testId ? `[data-testid="${testId}"]` : ''}${classes ? `.${classes}` : ''}`;
+ };
+ const text = (el) =>
+ (el.innerText || el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 80);
+ const clipped = [];
+ const truncatedWithoutTitle = [];
+ for (const el of document.body.querySelectorAll('*')) {
+ if (clipped.length + truncatedWithoutTitle.length >= 40) break;
+ if (!el.getClientRects().length) continue;
+ if (![...el.childNodes].some((node) => node.nodeType === 3 && node.textContent.trim()))
+ continue;
+ const style = getComputedStyle(el);
+ if (style.visibility === 'hidden' || style.opacity === '0') continue;
+ const overflowX = el.scrollWidth > el.clientWidth + 1 && /hidden|clip/.test(style.overflowX);
+ const clamped = style.webkitLineClamp && style.webkitLineClamp !== 'none';
+ const overflowY =
+ !clamped && el.scrollHeight > el.clientHeight + 2 && /hidden|clip/.test(style.overflowY);
+ const item = { element: describe(el), text: text(el) };
+ if (overflowX && style.textOverflow === 'ellipsis') {
+ if (!el.closest('[title]')) truncatedWithoutTitle.push(item);
+ } else if (overflowX || overflowY) clipped.push({ ...item, axis: overflowX ? 'x' : 'y' });
+ }
+ const rawKeys = [];
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ while (walker.nextNode() && rawKeys.length < 20) {
+ const value = walker.currentNode.textContent.trim();
+ if (/^[a-z][a-zA-Z0-9_-]*(\.[a-zA-Z0-9_-]+){2,}$/.test(value)) rawKeys.push(value);
+ }
+ const runtime = window.__uiPage;
+ return {
+ horizontalOverflow: document.documentElement.scrollWidth > innerWidth,
+ rawKeys,
+ clipped,
+ truncatedWithoutTitle,
+ missingTranslations: runtime.missingTranslations.slice(0, 50),
+ mutations: runtime.mutations.slice(),
+ hostMissing: runtime.hostMissing.slice(),
+ };
+}
+
+export function auditOutcome(audit) {
+ const errors = [];
+ if (audit.horizontalOverflow) errors.push('page overflows horizontally');
+ if (audit.rawKeys.length) errors.push(`untranslated keys rendered: ${audit.rawKeys.join(', ')}`);
+ if (audit.mutations.length)
+ errors.push(`host mutations attempted: ${audit.mutations.join(', ')}`);
+ const warnings = [
+ ...audit.clipped.map((item) => `clipped text (${item.axis}) ${item.element}: "${item.text}"`),
+ ...audit.truncatedWithoutTitle.map(
+ (item) => `truncated without title ${item.element}: "${item.text}"`,
+ ),
+ ...audit.missingTranslations.map((entry) => `missing translation ${entry}`),
+ ];
+ return { errors, warnings };
+}
diff --git a/apps/desktop/scripts/ui-page/build.mjs b/apps/desktop/scripts/ui-page/build.mjs
new file mode 100644
index 0000000000..ac85b6f14d
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/build.mjs
@@ -0,0 +1,275 @@
+import { readFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createHash } from 'node:crypto';
+import esbuild from 'esbuild';
+import postcss from 'postcss';
+import tailwind from 'tailwindcss';
+import loadConfig from 'tailwindcss/loadConfig.js';
+
+export const desktop = path.resolve(fileURLToPath(new URL('../..', import.meta.url)));
+export const root = path.resolve(desktop, '../..');
+const renderer = path.join(desktop, 'src/renderer');
+const harness = fileURLToPath(new URL('./harness/', import.meta.url));
+// Never written: esbuild needs an output directory to name assets; files are served from memory.
+const outdir = path.join(root, 'artifacts/ui-check/.bundle');
+// Assets stay separate files (like Vite) so unicode-range font subsets load on demand.
+const assetLoaders = Object.fromEntries(
+ ['png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'svg', 'woff', 'woff2', 'ttf', 'otf'].map((ext) => [
+ `.${ext}`,
+ 'file',
+ ]),
+);
+const SOURCE = /\.[cm]?[jt]sx?$/;
+const CONTENT_TYPES = {
+ '.js': 'text/javascript',
+ '.css': 'text/css',
+ '.svg': 'image/svg+xml',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.avif': 'image/avif',
+ '.woff': 'font/woff',
+ '.woff2': 'font/woff2',
+ '.ttf': 'font/ttf',
+ '.otf': 'font/otf',
+};
+
+const withoutExtension = (file) =>
+ file.replace(/\.(?:[cm]?[jt]sx?)$/, '').replace(/[\\/]index$/, '');
+
+function sourceFile(base) {
+ const file = ['.ts', '.tsx', '.js', '/index.ts', '/index.tsx']
+ .map((suffix) => base + suffix)
+ .find((candidate) => existsSync(candidate));
+ if (!file) throw new Error(`Stub target not found: ${path.relative(desktop, base)}`);
+ return file;
+}
+
+/**
+ * Stub keys are paths relative to apps/desktop (`src/renderer/x/y`), matched after resolution.
+ * Values: `'code'` replaces the module, `'./file.ts'` replaces it with a file next to the page,
+ * `{ partial: 'code' }` keeps every real export and overrides only the names declared in code.
+ */
+function stubTable(definition) {
+ return new Map(
+ Object.entries(definition.stubs ?? {}).map(([key, value]) => {
+ const target = path.join(desktop, key);
+ const real = sourceFile(target);
+ if (typeof value === 'object') {
+ if (typeof value?.partial !== 'string') throw new Error(`Stub ${key}: { partial: 'code' }`);
+ return [
+ withoutExtension(real),
+ {
+ key,
+ kind: 'partial',
+ code: `export * from ${JSON.stringify(real)};\n${value.partial}`,
+ },
+ ];
+ }
+ const file = /^\.\.?\//.test(value) ? path.resolve(definition.dir, value) : null;
+ if (file && !existsSync(file)) throw new Error(`Stub file not found: ${file}`);
+ return [
+ withoutExtension(real),
+ { key, kind: file ? 'file' : 'replace', file, code: file ? null : value },
+ ];
+ }),
+ );
+}
+
+function boundaries(stubs, replaced, overlay) {
+ return {
+ name: 'ui-page-boundaries',
+ setup(build) {
+ build.onResolve({ filter: /.*/ }, (args) => {
+ if (args.namespace === 'ui-stub') return undefined;
+ let candidate;
+ if (args.path.startsWith('@/')) candidate = path.join(renderer, args.path.slice(2));
+ else if (/^\.\.?\//.test(args.path) && args.resolveDir)
+ candidate = path.resolve(args.resolveDir, args.path);
+ if (!candidate) return undefined;
+ const stub = stubs.get(withoutExtension(candidate));
+ if (!stub) return 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);
+ return { path: stub.key, namespace: 'ui-stub', pluginData: stub };
+ });
+ build.onLoad({ filter: /.*/, namespace: 'ui-stub' }, async (args) => {
+ const stub = args.pluginData;
+ return stub.file
+ ? {
+ contents: await readFile(stub.file, 'utf8'),
+ loader: 'tsx',
+ resolveDir: path.dirname(stub.file),
+ watchFiles: [stub.file],
+ }
+ : { 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,
+ );
+ },
+ };
+}
+
+const sourcePath = (file) => path.resolve(root, file.replace(/ with \{[^}]*\}$/, ''));
+
+function entryContents(definition) {
+ const entry = path.resolve(definition.dir, definition.entry);
+ return {
+ entry,
+ contents: `import ${JSON.stringify(path.join(harness, 'preamble.ts'))};\nimport ${JSON.stringify(entry)};\n`,
+ };
+}
+
+const common = (definition, plugins) => ({
+ absWorkingDir: root,
+ bundle: true,
+ write: false,
+ metafile: true,
+ outdir,
+ format: 'esm',
+ platform: 'browser',
+ jsx: 'automatic',
+ tsconfig: path.join(desktop, 'tsconfig.json'),
+ // Lets entries outside the repository (agent scratch files) resolve desktop dependencies.
+ nodePaths: [path.join(desktop, 'node_modules'), path.join(root, 'node_modules')],
+ loader: assetLoaders,
+ assetNames: 'assets/[name]-[hash]',
+ publicPath: '/',
+ define: {
+ 'import.meta.env.PROD': 'true',
+ 'import.meta.env.DEV': 'false',
+ 'import.meta.env.MODE': '"production"',
+ 'process.env.NODE_ENV': '"production"',
+ },
+ logLevel: 'silent',
+ plugins,
+});
+
+/** Source inputs only (no CSS); used to decide which pages load a changed file. */
+export async function scanPage(definition) {
+ const replaced = {};
+ const { contents } = entryContents(definition);
+ const result = await esbuild.build({
+ ...common(definition, [boundaries(stubTable(definition), replaced)]),
+ stdin: { contents, resolveDir: root, sourcefile: 'ui-page-entry.ts', loader: 'ts' },
+ entryNames: 'page',
+ });
+ return {
+ inputs: Object.keys(result.metafile.inputs)
+ .filter((file) => !file.startsWith('ui-stub:') && file !== 'ui-page-entry.ts')
+ .map(sourcePath),
+ replaced,
+ };
+}
+
+/**
+ * Builds the selected page from current source every time (no cached bundle).
+ * `overlay` maps absolute source paths to replacement contents (used by --compare).
+ */
+export async function buildPage(definition, overlay) {
+ const replaced = {};
+ const { contents, entry } = entryContents(definition);
+ const result = await esbuild.build({
+ ...common(definition, [boundaries(stubTable(definition), replaced, overlay)]),
+ stdin: { contents, resolveDir: root, sourcefile: 'ui-page-entry.ts', loader: 'ts' },
+ entryNames: 'page',
+ });
+ const inputs = Object.keys(result.metafile.inputs)
+ .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),
+ );
+ config.content = [
+ ...scanned.filter((file) => !overlay?.has(file)),
+ ...scanned
+ .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 styles = await esbuild.build({
+ ...common(definition, []),
+ stdin: { contents: globals.css, loader: 'css', resolveDir: path.dirname(globalsPath) },
+ entryNames: 'styles',
+ });
+ const files = new Map();
+ for (const output of [...result.outputFiles, ...styles.outputFiles]) {
+ const url = `/${path.relative(outdir, output.path).split(path.sep).join('/')}`;
+ files.set(url, {
+ contentType: CONTENT_TYPES[path.extname(output.path)] ?? 'application/octet-stream',
+ body: Buffer.from(output.contents),
+ });
+ }
+ const watched = [
+ ...new Set(
+ [
+ ...inputs,
+ ...Object.keys(styles.metafile.inputs)
+ .filter((file) => file !== '<stdin>')
+ .map(sourcePath),
+ ...Object.values(definition.stubs ?? {})
+ .filter((value) => typeof value === 'string' && /^\.\.?\//.test(value))
+ .map((value) => path.resolve(definition.dir, value)),
+ globalsPath,
+ configPath,
+ definition.file,
+ path.join(root, 'pnpm-lock.yaml'),
+ ].filter(Boolean),
+ ),
+ ].sort();
+ const digest = createHash('sha256');
+ const fingerprints = new Map();
+ for (const file of watched) {
+ const content = overlay?.get(file) ?? (await readFile(file));
+ const hash = createHash('sha256').update(content).digest('hex');
+ fingerprints.set(file, hash);
+ digest.update(path.relative(root, file)).update('\0').update(hash);
+ }
+ const bundle = createHash('sha256');
+ for (const [url, file] of [...files].sort()) bundle.update(url).update(file.body);
+ return {
+ entry,
+ files,
+ styles: ['/styles.css', ...(files.has('/page.css') ? ['/page.css'] : [])],
+ inputs,
+ replaced,
+ fingerprints,
+ sourceDigest: digest.digest('hex'),
+ bundleDigest: bundle.digest('hex'),
+ inputCount: watched.length,
+ };
+}
+
+export async function inputsChanged(fingerprints) {
+ for (const [file, previous] of fingerprints) {
+ try {
+ if (
+ createHash('sha256')
+ .update(await readFile(file))
+ .digest('hex') !== previous
+ )
+ return true;
+ } catch {
+ return true;
+ }
+ }
+ return false;
+}
diff --git a/apps/desktop/scripts/ui-page/cli.mjs b/apps/desktop/scripts/ui-page/cli.mjs
new file mode 100644
index 0000000000..36f11a762b
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/cli.mjs
@@ -0,0 +1,205 @@
+#!/usr/bin/env node
+import { writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { parseOptions, variantsFor, LOCALES } from './options.mjs';
+import { adhocPage, loadPages } from './registry.mjs';
+import { root } from './build.mjs';
+import { prSnippet } from './pr.mjs';
+
+const HELP = `pnpm ui:check [selection] [matrix] [runtime]
+
+selection (one of):
+ --page <name> registered page (pnpm ui:check --list)
+ --entry <file.tsx> ad-hoc entry calling mountPage(); generic checks + screenshots
+ --changed[=<ref>] pages that load files changed since the upstream merge-base
+matrix (comma lists; every combination runs in one browser):
+ --case <name,…|all> default: default
+ --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)
+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
+ --engine chromium|electron --browser <path> --timeout <ms per variant> --output <dir>
+ --json print summary.json instead of the text report
+pnpm ui:preview <page and single variant> keep one window open; rebuilds on source edits`;
+
+function report(summary) {
+ const after = summary.variants.filter((variant) => variant.role === 'after');
+ const passed = after.filter((variant) => variant.status === 'passed').length;
+ const lines = [
+ summary.mode === 'preview'
+ ? `UI_PREVIEW ${summary.status} · ${summary.reloads ?? 0} reloads · ${(summary.timings.totalMs / 1000).toFixed(1)}s`
+ : `UI_CHECK ${summary.status} ${passed}/${after.length} variants · ${(summary.timings.totalMs / 1000).toFixed(1)}s (build ${summary.timings.buildMs ?? 0}ms, launch ${summary.timings.launchMs ?? 0}ms)`,
+ ];
+ const overviews = summary.overviews ?? (summary.overview ? [summary.overview] : []);
+ if (overviews.length)
+ lines.push(
+ `overview: ${overviews[0]}` +
+ (overviews.length > 1
+ ? ` (+${overviews.length - 1}: ${overviews
+ .slice(1)
+ .map((file) => path.basename(file))
+ .join(', ')})`
+ : ''),
+ );
+ lines.push(`summary: ${path.join(summary.evidence, 'summary.json')}`);
+ if (summary.pr)
+ lines.push(
+ `pr: ${summary.pr} — 发 PR 前运行 pnpm ui:check:publish,把截图发到你的 fork 并生成带图的「UI 变化」`,
+ );
+ for (const page of summary.pages) {
+ const replaced = Object.entries(page.replaced);
+ lines.push(
+ `page ${page.name}: real — ${page.real}`,
+ ` not covered — ${page.notCovered}`,
+ replaced.length
+ ? ` replaced — ${replaced.map(([key, info]) => `${key} (${info.kind})`).join(', ')}`
+ : ' replaced — none',
+ );
+ if (page.compare)
+ lines.push(
+ ` compare ${page.compare.ref}: ` +
+ (page.compare.replacedFromRef.length
+ ? `${page.compare.replacedFromRef.length} files from ref`
+ : '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(', ')}`
+ : ''),
+ );
+ }
+ for (const variant of after) {
+ const mark = variant.status === 'passed' ? 'ok ' : 'FAIL';
+ lines.push(
+ `${mark} ${variant.id}${variant.warnings.length ? ` · ${variant.warnings.length} warnings` : ''}`,
+ );
+ for (const error of variant.errors.slice(0, 3))
+ lines.push(` error: ${error.split('\n')[0]}`);
+ if (variant.status !== 'passed' && variant.hostMissing.length)
+ lines.push(
+ ` host APIs read but not provided: ${variant.hostMissing.slice(0, 8).join(', ')}`,
+ );
+ for (const warning of variant.warnings.slice(0, 4)) lines.push(` warn: ${warning}`);
+ for (const item of variant.focus ?? [])
+ lines.push(
+ ` focus ${item.capture}: ${item.box.width}×${item.box.height} · padding ${item.padding} · gap ${item.gap} · ${item.font}` +
+ (item.clippedChildren ? ` · ${item.clippedChildren} clipped` : ''),
+ );
+ // The pre-change side never fails the run; show what differed there so it can be compared.
+ const before = summary.variants.find(
+ (other) => other.role === 'before' && other.id === variant.id,
+ );
+ if (before) {
+ for (const note of [...before.errors, ...before.warnings].slice(0, 3))
+ lines.push(` before ${summary.compare?.ref}: ${note.split('\n')[0]}`);
+ for (const item of before.focus ?? [])
+ lines.push(
+ ` before focus ${item.capture}: ${item.box.width}×${item.box.height} · padding ${item.padding} · gap ${item.gap} · ${item.font}`,
+ );
+ }
+ }
+ for (const error of summary.errors) lines.push(`error: ${error.split('\n')[0]}`);
+ const coverage = summary.coverage;
+ if (coverage) {
+ lines.push(`changed since ${coverage.base.slice(0, 10)}: ${coverage.changedCount} files`);
+ for (const [file, pages] of Object.entries(coverage.covered))
+ lines.push(` loaded ${file} → ${pages.join(', ')}`);
+ for (const [file, pages] of Object.entries(coverage.replacedOnly))
+ lines.push(` STUBBED ${file} → replaced in ${pages.join(', ')}; not verified there`);
+ for (const file of coverage.uncovered) lines.push(` UNCOVERED ${file}`);
+ if (coverage.uncovered.length)
+ lines.push(
+ ' Uncovered files are NOT verified: add a case/page, use --entry, or verify in the full app.',
+ );
+ }
+ return lines.join('\n');
+}
+
+async function main() {
+ const options = parseOptions(process.argv.slice(2));
+ if (options.help) return console.log(HELP);
+ if (options.compare === true)
+ options.compare = (await import('./coverage.mjs')).baseRef(true).slice(0, 12);
+ const pages = await loadPages();
+ if (options.list) {
+ for (const page of Object.values(pages)) {
+ console.log(`${page.name} (${path.relative(root, page.file)})`);
+ console.log(` real: ${page.real}\n not covered: ${page.notCovered}`);
+ for (const [name, item] of Object.entries(page.cases))
+ console.log(` --case ${name}: ${item.about}`);
+ }
+ return;
+ }
+ const plan = { pages: [] };
+ if (options.changed) {
+ const { changedFiles, coverageFor } = await import('./coverage.mjs');
+ const { base, files } = changedFiles(options.changed);
+ const coverage = await coverageFor(pages, files);
+ plan.coverage = { base, changedCount: files.length, ...coverage };
+ plan.label = 'changed';
+ // Changed pages run every case unless a case list was given explicitly.
+ if (!process.argv.includes('--case') && !process.argv.some((arg) => arg.startsWith('--case=')))
+ options.cases = 'all';
+ for (const name of coverage.selected) plan.pages.push({ definition: pages[name] });
+ if (!plan.pages.length) {
+ const text = report({
+ status: 'nothing-to-run',
+ variants: [],
+ pages: [],
+ errors: [],
+ timings: { totalMs: 0 },
+ evidence: '-',
+ coverage: plan.coverage,
+ });
+ console.log(options.json ? JSON.stringify(plan.coverage, null, 2) : text);
+ process.exitCode = 0;
+ return;
+ }
+ } else if (options.entry) {
+ plan.pages.push({ definition: adhocPage(options.entry) });
+ } else {
+ if (!options.page) throw new Error('Choose --page, --entry or --changed (see --list)');
+ if (!pages[options.page]) throw new Error(`Unknown page: ${options.page}; use --list`);
+ plan.pages.push({ definition: pages[options.page] });
+ }
+ if (options.changed && options.cases !== 'all') {
+ // A case list with --changed applies to the pages that declare those cases.
+ const wanted = options.cases.split(',').map((name) => name.trim());
+ const matching = plan.pages.filter((item) =>
+ wanted.some((name) => item.definition.cases[name]),
+ );
+ if (!matching.length) throw new Error(`No changed page declares --case ${options.cases}`);
+ plan.pages = matching.map((item) => ({
+ ...item,
+ cases: wanted.filter((name) => item.definition.cases[name]).join(','),
+ }));
+ }
+ for (const item of plan.pages)
+ item.variants = variantsFor(
+ item.definition,
+ item.cases ? { ...options, cases: item.cases } : options,
+ );
+ const { runPlan } = await import('./run.mjs');
+ const stop = new AbortController();
+ const interrupt = () => stop.abort(new Error('用户中断单页验证'));
+ process.once('SIGINT', interrupt);
+ process.once('SIGTERM', interrupt);
+ try {
+ const summary = await runPlan(plan, options, stop.signal);
+ if (summary.mode === 'check' && summary.variants.length) {
+ summary.pr = path.join(summary.evidence, 'pr.md');
+ await writeFile(summary.pr, prSnippet(summary, process.argv.slice(2)));
+ }
+ console.log(options.json ? JSON.stringify(summary, null, 2) : report(summary));
+ if (!['passed', 'preview-closed'].includes(summary.status)) process.exitCode = 1;
+ } finally {
+ process.removeListener('SIGINT', interrupt);
+ process.removeListener('SIGTERM', interrupt);
+ }
+}
+
+main().catch((error) => {
+ console.error(`单页验证未能运行:${error.message}\n运行 pnpm ui:check --help 查看参数。`);
+ process.exitCode = 2;
+});
diff --git a/apps/desktop/scripts/ui-page/coverage.mjs b/apps/desktop/scripts/ui-page/coverage.mjs
new file mode 100644
index 0000000000..fa3816f40b
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/coverage.mjs
@@ -0,0 +1,67 @@
+import { execFileSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { desktop, root, scanPage } from './build.mjs';
+
+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)$/;
+
+/** Merge-base with `requested`, or with the conventional upstream branch. */
+export function baseRef(requested) {
+ if (typeof requested === 'string') return git(['merge-base', 'HEAD', requested]).trim();
+ for (const candidate of ['upstream/main', 'origin/main', 'main']) {
+ try {
+ return git(['merge-base', 'HEAD', candidate]).trim();
+ } catch {
+ // Try the next conventional base.
+ }
+ }
+ throw new Error('No base for --changed; pass --changed=<ref>');
+}
+
+/** Worktree changes (committed since the base, staged, unstaged and untracked). */
+export function changedFiles(requested) {
+ const base = baseRef(requested);
+ const tracked = git(['diff', '--name-only', base, '--']).split('\n');
+ const untracked = git(['ls-files', '--others', '--exclude-standard']).split('\n');
+ return {
+ base,
+ files: [...new Set([...tracked, ...untracked])]
+ .filter(Boolean)
+ .map((file) => path.join(root, file))
+ .filter((file) => existsSync(file)),
+ };
+}
+
+/**
+ * Which pages load each changed file for real. A file a page replaces with a stub is not
+ * covered by that page. Renderer UI files no page loads are reported as uncovered.
+ */
+export async function coverageFor(pages, changed) {
+ const covered = {};
+ const replacedOnly = {};
+ const selected = [];
+ for (const definition of Object.values(pages)) {
+ const { inputs, replaced } = await scanPage(definition);
+ const loaded = new Set(inputs);
+ const stubbed = new Set(Object.keys(replaced).map((key) => path.join(desktop, key)));
+ const hits = changed.filter((file) => loaded.has(file));
+ for (const file of changed) {
+ const base = file.replace(/\.(?:[cm]?[jt]sx?)$/, '');
+ if (stubbed.has(base)) (replacedOnly[path.relative(root, file)] ??= []).push(definition.name);
+ }
+ for (const file of hits) (covered[path.relative(root, file)] ??= []).push(definition.name);
+ // Fixture-only edits also select the page (its own scenario changed).
+ const own = changed.some((file) => file.startsWith(definition.dir + path.sep));
+ if (hits.length || own) selected.push(definition.name);
+ }
+ const uncovered = changed
+ .filter((file) => file.startsWith(renderer + path.sep) && UI_FILE.test(file))
+ .filter((file) => !file.includes(`${path.sep}__tests__${path.sep}`))
+ .map((file) => path.relative(root, file))
+ .filter((file) => !covered[file]);
+ return { covered, replacedOnly, uncovered, selected };
+}
diff --git a/apps/desktop/scripts/ui-page/electron.cjs b/apps/desktop/scripts/ui-page/electron.cjs
new file mode 100644
index 0000000000..0375c2069a
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/electron.cjs
@@ -0,0 +1,98 @@
+// Test-only single-page host. Never imports Cindy bootstrap, auth, stores or agent runtimes.
+const { app, BrowserWindow, session } = require('electron');
+const fs = require('node:fs');
+const path = require('node:path');
+const profile = process.env.CINDY_UI_PROFILE;
+const bundleDir = process.env.CINDY_UI_BUNDLE_DIR;
+const evidenceDir = process.env.CINDY_UI_EVIDENCE_DIR;
+if (![profile, bundleDir, evidenceDir].every((dir) => dir && path.isAbsolute(dir)))
+ throw new Error('Missing isolated UI profile, bundle or evidence directory');
+// Same policy the runner sends with the page document in Chromium mode.
+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'";
+fs.mkdirSync(profile, { recursive: true });
+app.setPath('userData', profile);
+app.setPath('sessionData', profile);
+app.setName('Cindy UI Check');
+// Fixed 2x density regardless of the attached display, matching a Retina Mac.
+app.commandLine.appendSwitch('force-device-scale-factor', '2');
+const origin = 'http://cindy-ui.test';
+const types = {
+ '.html': 'text/html',
+ '.js': 'text/javascript',
+ '.css': 'text/css',
+ '.svg': 'image/svg+xml',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.avif': 'image/avif',
+ '.woff': 'font/woff',
+ '.woff2': 'font/woff2',
+ '.ttf': 'font/ttf',
+ '.otf': 'font/otf',
+};
+// Background checks must not take focus or add a Dock icon to the user's desktop.
+if (process.env.CINDY_UI_PREVIEW !== '1') app.dock?.hide();
+app.whenReady().then(() => {
+ const ownSession = session.fromPartition('ui-check');
+ ownSession.setPermissionRequestHandler((_wc, _permission, callback) => callback(false));
+ ownSession.setPermissionCheckHandler(() => false);
+ ownSession.on('will-download', (event) => event.preventDefault());
+ ownSession.webRequest.onBeforeRequest((details, callback) => {
+ const url = new URL(details.url);
+ callback({
+ cancel: !['about:', 'data:', 'blob:'].includes(url.protocol) && url.origin !== origin,
+ });
+ });
+ // Everything on the test origin is a file the runner wrote for this run: variant documents,
+ // bundle files, and (for the overview) evidence screenshots. Other http requests are refused.
+ ownSession.protocol.handle('http', async (request) => {
+ const url = new URL(request.url);
+ const pathname = decodeURIComponent(url.pathname);
+ const [base, relative] = pathname.startsWith('/__evidence/')
+ ? [evidenceDir, pathname.slice('/__evidence/'.length)]
+ : [bundleDir, pathname];
+ const file = path.join(base, relative);
+ if (url.origin !== origin || !file.startsWith(base + path.sep))
+ return new Response(null, { status: 403 });
+ try {
+ const type = types[path.extname(file)] ?? 'application/octet-stream';
+ return new Response(await fs.promises.readFile(file), {
+ headers: {
+ 'content-type': type,
+ ...(type === 'text/html' && base === bundleDir ? { 'content-security-policy': csp } : {}),
+ },
+ });
+ } catch {
+ return new Response(null, { status: 404 });
+ }
+ });
+ const win = new BrowserWindow({
+ width: Number(process.env.CINDY_UI_WIDTH),
+ height: Number(process.env.CINDY_UI_HEIGHT),
+ useContentSize: true,
+ show: process.env.CINDY_UI_PREVIEW === '1',
+ title: 'Cindy UI Check',
+ webPreferences: {
+ session: ownSession,
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ },
+ });
+ win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ win.webContents.on('will-navigate', (event, url) => {
+ if (new URL(url).origin !== origin) event.preventDefault();
+ });
+ void win.loadURL('about:blank');
+});
+app.on('window-all-closed', () => app.quit());
diff --git a/apps/desktop/scripts/ui-page/harness/host.ts b/apps/desktop/scripts/ui-page/harness/host.ts
new file mode 100644
index 0000000000..d5732153a8
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/harness/host.ts
@@ -0,0 +1,73 @@
+// Scenario-backed replacement for the preload bridge (`window.electronAPI`).
+// Unknown paths resolve to undefined, like a host without that capability, so optional
+// product calls stay inert; every such read is recorded so a failing page reports which
+// host data to add. Writes must be declared explicitly, normally with `forbid()`.
+import type { UiPageRuntime } from './types';
+
+type HostTree = Record<string, unknown>;
+
+const IGNORED = new Set(['then', 'toJSON', 'constructor', '$$typeof', 'prototype', 'valueOf']);
+const backing: HostTree = {};
+const registry: Record<string, Set<(payload: unknown) => void>> = {};
+let runtime: UiPageRuntime;
+
+function isTree(value: unknown): value is HostTree {
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+}
+
+function view(target: HostTree, path: string): HostTree {
+ return new Proxy(target, {
+ get(tree, key) {
+ if (typeof key === 'symbol') return Reflect.get(tree, key);
+ const name = path ? `${path}.${key}` : key;
+ if (!Object.hasOwn(tree, key)) {
+ if (!IGNORED.has(key) && !runtime.hostMissing.includes(name))
+ runtime.hostMissing.push(name);
+ return undefined;
+ }
+ const value = tree[key];
+ return isTree(value) ? view(value, name) : value;
+ },
+ has: (tree, key) => Reflect.has(tree, key),
+ });
+}
+
+function merge(target: HostTree, source: HostTree): void {
+ for (const [key, value] of Object.entries(source)) {
+ const existing = target[key];
+ if (isTree(value) && isTree(existing)) merge(existing, value);
+ else target[key] = value;
+ }
+}
+
+export function installHost(owner: UiPageRuntime, base: HostTree): void {
+ runtime = owner;
+ runtime.emit = (name, payload) => {
+ const listeners = [...(registry[name] ?? [])];
+ for (const listener of listeners) listener(payload);
+ return listeners.length;
+ };
+ merge(backing, base);
+ (window as unknown as { electronAPI: unknown }).electronAPI = view(backing, '');
+}
+
+/** Add scenario host APIs; nested namespaces merge with earlier registrations. */
+export function registerHost(api: HostTree): void {
+ merge(backing, api);
+}
+
+/** A host write the scenario must never perform: recorded and rejected. */
+export function forbid(name: string) {
+ return (..._args: unknown[]): never => {
+ runtime.mutations.push(name);
+ throw new Error(`UI page forbids host mutation: ${name}`);
+ };
+}
+
+/** `onX(listener)` host subscription; a check pushes events with `ctx.emit(name, payload)`. */
+export function subscription(name: string) {
+ return (listener: (payload: unknown) => void) => {
+ (registry[name] ??= new Set()).add(listener);
+ return () => registry[name]?.delete(listener);
+ };
+}
diff --git a/apps/desktop/scripts/ui-page/harness/index.tsx b/apps/desktop/scripts/ui-page/harness/index.tsx
new file mode 100644
index 0000000000..70a77dd9c3
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/harness/index.tsx
@@ -0,0 +1,157 @@
+// Browser side of `pnpm ui:check`. A page fixture calls `mountPage()` once; the harness
+// applies the product's own appearance bootstrap (main-entry.tsx), mounts the product
+// providers and reports readiness. It never imports auth, stores, agent runtimes or IPC.
+import '@fontsource-variable/inter';
+import '@fontsource-variable/jetbrains-mono';
+import 'harmonyos-sans-sc-webfont-splitted';
+import '../../../src/renderer/themes/colors';
+import '../../../src/renderer/styles/sortable.css';
+import type { ReactNode } from 'react';
+import { createRoot } from 'react-dom/client';
+import { MemoryRouter } from 'react-router-dom';
+import i18n from '../../../src/renderer/i18n';
+import { themeService } from '../../../src/renderer/themes/theme-service';
+import { getInitialThemeVariant, ThemeProvider } from '../../../src/renderer/hooks/useTheme';
+import {
+ applyFontSettings,
+ FontSettingsProvider,
+ getInitialFontSettings,
+} from '../../../src/renderer/hooks/useFontSettings';
+import { LocaleProvider } from '../../../src/renderer/hooks/useLocale';
+import { ConfirmDialogProvider } from '../../../src/renderer/components/ui/confirm-dialog-provider';
+import { Tooltip } from '../../../src/renderer/components/ui/tooltip';
+import { FeatureSidebarSlotProvider } from '../../../src/renderer/features/feature-context';
+import { ContentHeaderSlot } from '../../../src/renderer/components/layout/ContentHeader';
+import { registerHost } from './host';
+import type { UiPageContext, UiPageRuntime } from './types';
+
+export { forbid, registerHost, subscription } from './host';
+export type { UiPageContext } from './types';
+
+const runtime = (window as unknown as { __uiPage: UiPageRuntime }).__uiPage;
+export const ctx: UiPageContext = runtime.ctx;
+
+export interface PageDefinition {
+ /** Host APIs for this scenario. Missing paths resolve to undefined and are reported. */
+ host?: Record<string, unknown> | ((ctx: UiPageContext) => Record<string, unknown>);
+ /** Extra JSON-safe cases for ad-hoc entries (`--entry`); registered pages declare cases in ui-page.mjs. */
+ cases?: string[];
+ /** Initial MemoryRouter entries; omit for components that do not use routing. */
+ route?: string;
+ render: (ctx: UiPageContext) => ReactNode;
+}
+
+/** Report keys that only resolve through the fallback language for the active locale. */
+function trackMissingTranslations(): void {
+ const translator = (i18n as unknown as { translator?: { translate: Function } }).translator;
+ if (!translator) return;
+ const original = translator.translate.bind(translator);
+ translator.translate = (
+ keys: string | string[],
+ options?: Record<string, unknown>,
+ ...rest: unknown[]
+ ) => {
+ const list = (Array.isArray(keys) ? keys : [keys]).filter((key) => typeof key === 'string');
+ const lng = (options?.lng as string | undefined) ?? i18n.language;
+ if (
+ list.length &&
+ !list.some((key) => i18n.exists(key, { ...options, lng, fallbackLng: false }))
+ ) {
+ const entry = `${lng}:${list[0]}`;
+ if (!runtime.missingTranslations.includes(entry)) runtime.missingTranslations.push(entry);
+ }
+ return original(keys, options, ...rest);
+ };
+}
+
+export async function mountPage(definition: PageDefinition): Promise<void> {
+ if (definition.cases?.length && !definition.cases.includes(ctx.case)) {
+ // Ad-hoc entries: the runner's `default` case means the first declared case.
+ if (ctx.case !== 'default')
+ throw new Error(`Unknown case "${ctx.case}"; declared: ${definition.cases.join(', ')}`);
+ ctx.case = definition.cases[0];
+ }
+ runtime.cases = definition.cases;
+ if (definition.host)
+ registerHost(typeof definition.host === 'function' ? definition.host(ctx) : definition.host);
+ // Same order as main-entry.tsx: theme and fonts before the first React render.
+ themeService.applyTheme(getInitialThemeVariant().theme);
+ applyFontSettings(getInitialFontSettings());
+ await i18n.changeLanguage(ctx.locale);
+ trackMissingTranslations();
+ runtime.t = (key, options) => i18n.t(key, options) as string;
+ const content = definition.render(ctx);
+ createRoot(document.getElementById('root')!).render(
+ <ThemeProvider syncWindowVibrancy={false}>
+ <FontSettingsProvider>
+ <LocaleProvider>
+ <ConfirmDialogProvider>
+ <Tooltip.Provider>
+ {definition.route ? (
+ <MemoryRouter initialEntries={[definition.route]}>{content}</MemoryRouter>
+ ) : (
+ content
+ )}
+ </Tooltip.Provider>
+ </ConfirmDialogProvider>
+ </LocaleProvider>
+ </FontSettingsProvider>
+ </ThemeProvider>,
+ );
+ await document.fonts.ready;
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ runtime.ready = true;
+ document.documentElement.dataset.uiPageReady = '1';
+}
+
+interface AppFrameProps {
+ /** Sidebar content; omit to render the collapsed-sidebar layout. */
+ sidebar?: ReactNode;
+ sidebarWidth?: number;
+ /** Render the product ContentHeader shell (feature header content is injected by the page). */
+ header?: boolean;
+ children?: ReactNode;
+}
+
+/**
+ * Window layout mirror. Classes are copied from MainLayout (root row and chat main) and
+ * Sidebar (expanded aside); 260px is useSidebarResize's default width. Only the page
+ * subject inside is under test — keep these in sync when those files change.
+ */
+export function AppFrame({ sidebar, sidebarWidth = 260, header = true, children }: AppFrameProps) {
+ return (
+ <FeatureSidebarSlotProvider isCollapsed={!sidebar}>
+ <div
+ data-ui-frame="window"
+ className="relative flex h-screen bg-content-area text-foreground"
+ >
+ {sidebar ? (
+ <aside
+ data-ui-frame="sidebar"
+ style={{ width: sidebarWidth }}
+ className="relative flex shrink-0 flex-col overflow-hidden border-r border-sidebar-border bg-sidebar"
+ >
+ {sidebar}
+ </aside>
+ ) : null}
+ <main
+ data-ui-frame="content"
+ className="relative flex min-w-[400px] flex-1 flex-col overflow-hidden bg-content-area"
+ >
+ {header ? (
+ <ContentHeaderSlot
+ sidebarVisible={Boolean(sidebar)}
+ showCollapsedActions={!sidebar}
+ isSidebarRail={false}
+ rightSidebarAvailable={false}
+ >
+ {children}
+ </ContentHeaderSlot>
+ ) : (
+ children
+ )}
+ </main>
+ </div>
+ </FeatureSidebarSlotProvider>
+ );
+}
diff --git a/apps/desktop/scripts/ui-page/harness/preamble.ts b/apps/desktop/scripts/ui-page/harness/preamble.ts
new file mode 100644
index 0000000000..ac70c61562
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/harness/preamble.ts
@@ -0,0 +1,39 @@
+// First module of every UI page bundle: runs before any product module is evaluated, so
+// product code that reads storage, platform or window.electronAPI at import time sees the
+// scenario environment instead of a missing host.
+import { writeStoredLocale } from '../../../src/renderer/lib/localePreference';
+import { installHost } from './host';
+import type { UiPageContext, UiPageRuntime } from './types';
+
+// Startup failures end the wait for readiness immediately instead of at the variant timeout.
+const fail = (message: string) => {
+ if (!(window as unknown as { __uiPage?: UiPageRuntime }).__uiPage?.ready)
+ document.documentElement.dataset.uiPageError ||= message;
+};
+addEventListener('error', (event) => fail(event.message));
+addEventListener('unhandledrejection', (event) =>
+ fail(String(event.reason?.stack ?? event.reason)),
+);
+
+const ctx = JSON.parse(document.getElementById('ui-page-context')!.textContent!) as UiPageContext;
+
+const runtime: UiPageRuntime = {
+ ctx,
+ hostMissing: [],
+ mutations: [],
+ missingTranslations: [],
+ ready: false,
+};
+(window as unknown as { __uiPage: UiPageRuntime }).__uiPage = runtime;
+
+localStorage.clear();
+// Same preference keys the product reads on startup (useTheme STORAGE_KEY, localePreference),
+// plus the first-launch marker so the login light-mode gate does not override the theme.
+localStorage.setItem('theme', ctx.theme);
+localStorage.setItem('login.firstLaunchLightShown', '1');
+writeStoredLocale(ctx.locale);
+for (const [key, value] of Object.entries(ctx.storage ?? {})) localStorage.setItem(key, value);
+document.documentElement.lang = ctx.locale;
+document.documentElement.dataset.platform = ctx.platform;
+document.documentElement.dataset.windowBackdropMaterial = 'none';
+installHost(runtime, { platform: ctx.platform, windowBackdropMaterial: 'none' });
diff --git a/apps/desktop/scripts/ui-page/harness/types.ts b/apps/desktop/scripts/ui-page/harness/types.ts
new file mode 100644
index 0000000000..bc50d179e7
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/harness/types.ts
@@ -0,0 +1,29 @@
+export type UiPageTheme = 'light' | 'dark';
+
+/** Serialized by the runner into the page; identical shape for every engine. */
+export interface UiPageContext {
+ page: string;
+ case: string;
+ theme: UiPageTheme;
+ locale: 'zh-CN' | 'zh-TW' | 'en' | 'ja' | 'ko';
+ platform: 'darwin' | 'win32' | 'linux';
+ viewport: { width: number; height: number };
+ /** JSON data declared by the page case; the fixture and the Playwright checks read the same values. */
+ data: Record<string, unknown>;
+ storage?: Record<string, string>;
+}
+
+export interface UiPageRuntime {
+ ctx: UiPageContext;
+ /** Host API paths the product read but the scenario did not provide (resolved as undefined). */
+ hostMissing: string[];
+ /** Host writes attempted through `forbid()` handlers; a check fails if any exist. */
+ mutations: string[];
+ /** `${locale}:${key}` entries i18next could not resolve in the active locale. */
+ missingTranslations: string[];
+ ready: boolean;
+ /** Deliver a host event to listeners registered through `subscription(name)`; returns listener count. */
+ emit?: (name: string, payload: unknown) => number;
+ t?: (key: string, options?: Record<string, unknown>) => string;
+ cases?: string[];
+}
diff --git a/apps/desktop/scripts/ui-page/options.mjs b/apps/desktop/scripts/ui-page/options.mjs
new file mode 100644
index 0000000000..ef5a11eafb
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/options.mjs
@@ -0,0 +1,149 @@
+import path from 'node:path';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const localeSource = readFileSync(
+ fileURLToPath(new URL('../../src/shared/locale.ts', import.meta.url)),
+ 'utf8',
+);
+/** The product's own locale list; the runner never keeps a second copy. */
+export const LOCALES = [
+ ...localeSource.match(/SUPPORTED_LOCALES\s*=\s*\[([^\]]*)\]/)[1].matchAll(/'([^']+)'/g),
+].map((match) => match[1]);
+export const THEMES = ['light', 'dark'];
+export const PLATFORMS = ['darwin', 'win32', 'linux'];
+
+const VALUE_OPTIONS = new Set([
+ 'page',
+ 'case',
+ 'theme',
+ 'locale',
+ 'viewport',
+ 'width',
+ 'height',
+ 'platform',
+ 'engine',
+ 'timeout',
+ 'browser',
+ 'output',
+ 'entry',
+ 'compare',
+ 'focus',
+]);
+const FLAGS = new Set(['preview', 'list', 'help', 'json']);
+
+function list(value, all, name) {
+ const items = value === 'all' ? all : value.split(',').map((item) => item.trim());
+ for (const item of items)
+ if (!all.includes(item)) throw new Error(`--${name}: ${all.join(' | ')} | all`);
+ return [...new Set(items)];
+}
+
+function viewports(value) {
+ return value.split(',').map((item) => {
+ const match = /^(\d+)x(\d+)$/.exec(item.trim());
+ if (!match) throw new Error('--viewport: <width>x<height>[,<width>x<height>]');
+ const [width, height] = [Number(match[1]), Number(match[2])];
+ if (width < 360 || width > 3840 || height < 320 || height > 2160)
+ throw new Error('--viewport: width 360–3840, height 320–2160');
+ return { width, height };
+ });
+}
+
+export function parseOptions(argv) {
+ const raw = {};
+ const options = { mode: 'check' };
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === '--') continue;
+ const match = /^--([a-z]+)(?:=(.*))?$/.exec(arg);
+ if (!match) throw new Error(`Unknown argument: ${arg}`);
+ const [, name, inline] = match;
+ if (name === 'changed') {
+ // `--changed` alone compares with the upstream merge-base; `--changed=<ref>` picks a ref.
+ options.changed = inline ?? true;
+ continue;
+ }
+ if (
+ name === 'compare' &&
+ inline === undefined &&
+ (!argv[i + 1] || argv[i + 1].startsWith('--'))
+ ) {
+ // `--compare` alone renders the branch's merge-base as "before".
+ raw.compare = true;
+ continue;
+ }
+ if (FLAGS.has(name)) {
+ if (name === 'preview') options.mode = 'preview';
+ else options[name] = true;
+ continue;
+ }
+ if (!VALUE_OPTIONS.has(name)) throw new Error(`Unknown option: ${arg}`);
+ const value = inline ?? argv[++i];
+ if (!value || value.startsWith('--')) throw new Error(`Missing value: --${name}`);
+ raw[name] = value;
+ }
+ options.page = raw.page;
+ 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];
+ if (raw.viewport && (raw.width || raw.height))
+ throw new Error('Use either --viewport or --width/--height');
+ options.viewports = raw.viewport
+ ? viewports(raw.viewport)
+ : raw.width || raw.height
+ ? viewports(`${raw.width ?? 1040}x${raw.height ?? 760}`)
+ : undefined;
+ // Electron is the default: same Chromium build as Cindy, no browser install, fastest locally.
+ options.engine = raw.engine ?? 'electron';
+ if (!['chromium', 'electron'].includes(options.engine))
+ throw new Error('--engine: chromium | electron');
+ options.timeout = Number(raw.timeout ?? 20000);
+ if (!Number.isInteger(options.timeout) || options.timeout < 1000 || options.timeout > 120000)
+ throw new Error('--timeout: 1000–120000 (per variant, ms)');
+ options.browser = raw.browser;
+ options.output = raw.output && path.resolve(raw.output);
+ options.entry = raw.entry && path.resolve(raw.entry);
+ options.compare = raw.compare;
+ options.focus = raw.focus;
+ const selectors = [options.page, options.entry, options.changed].filter(Boolean).length;
+ if (selectors > 1) throw new Error('Choose one of --page, --entry or --changed');
+ if (options.mode === 'preview' && (options.changed || options.compare))
+ throw new Error(
+ '--preview runs one explicit page; it cannot be combined with --changed/--compare',
+ );
+ return options;
+}
+
+/** Expand the requested matrix for one page definition. */
+export function variantsFor(definition, options) {
+ const names = Object.keys(definition.cases);
+ const cases =
+ options.cases === 'all' ? names : options.cases.split(',').map((name) => name.trim());
+ for (const name of cases) {
+ // Ad-hoc entries declare their cases in mountPage(); the page itself rejects unknown names.
+ if (definition.adhoc) definition.cases[name] ??= { about: name };
+ if (!definition.cases[name])
+ throw new Error(`--case for ${definition.name}: ${names.join(' | ')} | all`);
+ }
+ const variants = [];
+ for (const name of cases)
+ for (const viewport of options.viewports ?? [
+ definition.cases[name].viewport ?? definition.viewport,
+ ])
+ for (const theme of options.themes)
+ for (const locale of options.locales)
+ variants.push({
+ page: definition.name,
+ case: name,
+ theme,
+ locale,
+ platform: options.platform,
+ viewport,
+ id: `${definition.name}.${name}.${theme}.${locale}.${viewport.width}x${viewport.height}`,
+ });
+ if (options.mode === 'preview' && variants.length > 1)
+ throw new Error('--preview keeps one window: pick a single case, theme, locale and viewport');
+ return variants;
+}
diff --git a/apps/desktop/scripts/ui-page/pr.mjs b/apps/desktop/scripts/ui-page/pr.mjs
new file mode 100644
index 0000000000..59f534ad6d
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/pr.mjs
@@ -0,0 +1,76 @@
+// `pr.md`: the run described for the PR template's「UI 变化」section. The last line is a
+// placeholder that `pnpm ui:check:publish` replaces with links to the published screenshots.
+import path from 'node:path';
+
+const PLATFORM = { darwin: 'macOS', win32: 'Windows', linux: 'Linux' };
+
+// Arguments are pasted back into a shell, so quote anything a shell would expand.
+const shellArg = (arg) =>
+ /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", `'\\''`)}'`;
+
+const measured = (item) =>
+ `${item.box.width}×${item.box.height},padding ${item.padding},gap ${item.gap},${item.font}`;
+
+function list(values) {
+ return [...new Set(values)].join(' / ');
+}
+
+export function prSnippet(summary, argv) {
+ const variants = summary.variants.filter((variant) => variant.role === 'after');
+ const passed = variants.filter((variant) => variant.status === 'passed').length;
+ const warnings = variants.reduce((count, variant) => count + variant.warnings.length, 0);
+ const runtime = summary.versions?.electron
+ ? `Electron ${summary.versions.electron}(Chromium ${summary.versions.chrome},与 Cindy 同一渲染内核)`
+ : `Chromium ${summary.versions?.chrome ?? '?'}`;
+ const lines = [
+ '<!-- 由 pnpm ui:check 生成;pnpm ui:check:publish 把截图发到作者 fork 并换上图片链接 -->',
+ `- 截图来源:单页验证 \`pnpm ui:check ${argv.map(shellArg).join(' ')}\`,${PLATFORM[process.platform] ?? process.platform} · ${runtime};` +
+ '真实组件与主题,场景数据,不是登录账号下的完整 Cindy',
+ `- 版本:\`${summary.commit?.slice(0, 12) ?? '未知'}\`${summary.worktreeDirty ? '(含未提交改动)' : ''}`,
+ `- 结果:${passed}/${variants.length} 个场景通过${warnings ? `,${warnings} 条警告` : ''}`,
+ ];
+ 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()];
+ lines.push(
+ `- 页面 \`${page.name}\`:${list(own.map((variant) => variant.theme))} · ${list(own.map((variant) => variant.locale))} · ${list(own.map((variant) => `${variant.viewport.width}×${variant.viewport.height}`))}`,
+ ...cases.map(([name, about]) => ` - \`${name}\`:${about ?? name}`),
+ ` - 未覆盖:${page.notCovered}`,
+ );
+ const replaced = Object.keys(page.replaced);
+ if (replaced.length)
+ lines.push(` - 场景替换的模块(未验证):${replaced.map((key) => `\`${key}\``).join('、')}`);
+ if (page.compare)
+ lines.push(
+ page.compare.replacedFromRef.length
+ ? ` - 改前/改后对照:\`${page.compare.ref}\`,同一步骤左右并排`
+ : ` - 改前/改后对照:\`${page.compare.ref}\` 之后没有改动本页面加载的产品文件`,
+ );
+ }
+ // `--focus` measurements: the last capture where the element was visible, before → now.
+ for (const variant of variants) {
+ const now = variant.focus?.at(-1);
+ if (!now) continue;
+ const before = summary.variants
+ .find((other) => other.role === 'before' && other.id === variant.id)
+ ?.focus?.find((item) => item.capture === now.capture);
+ lines.push(
+ `- 实测 \`${variant.case}\` ${variant.theme} ${variant.locale}(${now.capture}):` +
+ (before ? `${measured(before)} → ${measured(now)}` : measured(now)),
+ );
+ }
+ const failed = variants.filter((variant) => variant.status !== 'passed');
+ for (const variant of failed)
+ lines.push(`- 未通过:\`${variant.id}\` — ${variant.errors[0]?.split('\n')[0] ?? ''}`);
+ if (summary.coverage?.uncovered.length)
+ lines.push(
+ `- 本分支改动中没有被单页验证覆盖的界面文件:${summary.coverage.uncovered.map((file) => `\`${file}\``).join('、')}`,
+ );
+ const images = summary.overviews ?? (summary.overview ? [summary.overview] : []);
+ lines.push(
+ '',
+ `<!-- 截图:${images.map((file) => path.basename(file)).join('、') || '(本次没有生成总览图)'} -->`,
+ '',
+ );
+ return lines.join('\n');
+}
diff --git a/apps/desktop/scripts/ui-page/publish.mjs b/apps/desktop/scripts/ui-page/publish.mjs
new file mode 100644
index 0000000000..a4a7769757
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/publish.mjs
@@ -0,0 +1,116 @@
+#!/usr/bin/env node
+// `pnpm ui:check:publish [<run dir>] [--remote <name>] [--branch <name>] [--dry-run]`
+// Publishes a run's screenshots for a PR description, the way this repo's PRs carry images:
+// an orphan-history `pr-assets/…` branch on the author's fork (never the upstream repo), linked
+// by commit SHA. The worktree, index and current branch are not touched. Prints the PR text.
+import { execFileSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { root } from './build.mjs';
+
+const git = (args, input) =>
+ execFileSync('git', args, {
+ cwd: root,
+ encoding: 'utf8',
+ input,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ }).trim();
+
+function parse(argv) {
+ const options = {};
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === '--') continue;
+ if (arg === '--remote' || arg === '--branch') options[arg.slice(2)] = argv[++i];
+ else if (arg === '--dry-run') options.dryRun = true;
+ else if (arg.startsWith('--')) throw new Error(`Unknown option: ${arg}`);
+ else options.run = path.resolve(arg);
+ }
+ return options;
+}
+
+/** owner/repo of a GitHub remote URL, or null. */
+function githubRepo(url) {
+ return /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(url)?.[1] ?? null;
+}
+
+async function latestRun() {
+ const base = path.join(root, 'artifacts/ui-check');
+ const runs = await Promise.all(
+ (await readdir(base, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
+ .map(async (entry) => {
+ const dir = path.join(base, entry.name);
+ return { dir, time: (await stat(dir)).mtimeMs };
+ }),
+ );
+ const run = runs
+ .filter((item) => existsSync(path.join(item.dir, 'pr.md')))
+ .sort((a, b) => b.time - a.time)[0];
+ if (!run) throw new Error('No ui:check run with pr.md; run pnpm ui:check first');
+ return run.dir;
+}
+
+async function main() {
+ const options = parse(process.argv.slice(2));
+ const run = options.run ?? (await latestRun());
+ const summary = JSON.parse(await readFile(path.join(run, 'summary.json'), 'utf8'));
+ 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.
+ const remotes = git(['remote']).split('\n').filter(Boolean);
+ const canonical = githubRepo(
+ git(['remote', 'get-url', remotes.includes('upstream') ? 'upstream' : 'origin']),
+ );
+ const remote =
+ options.remote ??
+ remotes.find((name) => githubRepo(git(['remote', 'get-url', name])) !== canonical);
+ const repo = remote && githubRepo(git(['remote', 'get-url', 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`);
+
+ const current = git(['rev-parse', '--abbrev-ref', 'HEAD']);
+ const branch = options.branch ?? `pr-assets/${current === 'HEAD' ? 'detached' : current}`;
+ const folder = path.basename(run);
+
+ // One commit per run under its own folder; earlier runs stay reachable through the parent.
+ const entries = [];
+ for (const file of images) {
+ const blob = git(['hash-object', '-w', file]);
+ entries.push(`100644 blob ${blob}\t${path.basename(file)}`);
+ }
+ const runTree = git(['mktree'], `${entries.join('\n')}\n`);
+ const tree = git(['mktree'], `040000 tree ${runTree}\t${folder}\n`);
+ let parent = '';
+ try {
+ parent = git(['ls-remote', remote, `refs/heads/${branch}`]).split('\t')[0];
+ if (parent) git(['fetch', '--quiet', remote, `refs/heads/${branch}`]);
+ } catch {
+ parent = '';
+ }
+ const message = `ui:check screenshots ${folder}\n\nNot for merging; referenced by PR descriptions.`;
+ const commit = git(['commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', message]);
+ if (!options.dryRun) git(['push', '--quiet', remote, `${commit}:refs/heads/${branch}`]);
+
+ const url = (file) =>
+ `https://raw.githubusercontent.com/${repo}/${commit}/${folder}/${path.basename(file)}`;
+ const text = (await readFile(path.join(run, 'pr.md'), 'utf8')).replace(
+ /\n<!-- 截图:[^\n]*-->\n?$/,
+ `\n${images.map((file, i) => `![单页验证截图 ${i + 1}/${images.length}](${url(file)})`).join('\n')}\n`,
+ );
+ const out = path.join(run, 'pr.published.md');
+ await writeFile(out, text);
+ console.log(
+ `UI_PUBLISH${options.dryRun ? ' (dry run, not pushed)' : ''} ${repo}@${branch} ${commit.slice(0, 12)} · ${images.length} images\npr: ${out}\n`,
+ );
+ console.log(text);
+}
+
+main().catch((error) => {
+ console.error(`单页验证截图未能发布:${error.message.split('\n')[0]}`);
+ process.exitCode = 1;
+});
diff --git a/apps/desktop/scripts/ui-page/registry.mjs b/apps/desktop/scripts/ui-page/registry.mjs
new file mode 100644
index 0000000000..4006c9c0be
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/registry.mjs
@@ -0,0 +1,51 @@
+import { readdir } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { desktop, root } from './build.mjs';
+
+export const fixturesDir = path.join(desktop, 'scripts/fixtures');
+
+function validate(definition, file) {
+ const fail = (message) => {
+ throw new Error(`${path.relative(desktop, file)}: ${message}`);
+ };
+ if (!/^[a-z0-9-]+$/.test(definition.name ?? '')) fail('name must be kebab-case');
+ if (!definition.entry) fail('entry is required');
+ if (!definition.cases?.default) fail('cases.default is required');
+ if (!definition.viewport?.width || !definition.viewport?.height) fail('viewport is required');
+ if (!definition.real || !definition.notCovered) fail('real and notCovered describe the scope');
+ for (const [name, item] of Object.entries(definition.cases))
+ if (!/^[a-z0-9-]+$/.test(name) || !item.about)
+ fail(`case ${name} needs a kebab name and about`);
+}
+
+/** Every `scripts/fixtures/<dir>/ui-page.mjs`; adding a page never edits a central list. */
+export async function loadPages() {
+ const pages = {};
+ for (const entry of await readdir(fixturesDir, { withFileTypes: true })) {
+ const file = path.join(fixturesDir, entry.name, 'ui-page.mjs');
+ if (!entry.isDirectory() || !existsSync(file)) continue;
+ const definition = (await import(pathToFileURL(file).href)).default;
+ validate(definition, file);
+ if (pages[definition.name]) throw new Error(`Duplicate UI page: ${definition.name}`);
+ pages[definition.name] = { ...definition, dir: path.dirname(file), file };
+ }
+ return pages;
+}
+
+/** 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}`);
+ return {
+ name: 'entry',
+ entry,
+ dir: path.dirname(entry),
+ adhoc: true,
+ viewport: { width: 1040, height: 760 },
+ cases: { default: { about: 'Ad-hoc entry' } },
+ real: `Everything imported by ${entry.startsWith(root + path.sep) ? path.relative(root, entry) : entry}`,
+ notCovered: 'No page-specific assertions; only generic checks and screenshots',
+ stubs: {},
+ };
+}
diff --git a/apps/desktop/scripts/ui-page/run.mjs b/apps/desktop/scripts/ui-page/run.mjs
new file mode 100644
index 0000000000..edb262e343
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/run.mjs
@@ -0,0 +1,720 @@
+import assert from 'node:assert/strict';
+import { existsSync } 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';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+import { execFileSync } from 'node:child_process';
+import { setTimeout as delay } from 'node:timers/promises';
+import { chromium, _electron } from 'playwright-core';
+import { buildPage, inputsChanged, root } from './build.mjs';
+import { auditOutcome, pageAudit } from './audit.mjs';
+import { variantsFor } from './options.mjs';
+
+const require = createRequire(import.meta.url);
+export const origin = 'http://cindy-ui.test';
+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'] });
+
+const bundlePrefix = (bundle) => `/b/${bundle.bundleDigest.slice(0, 16)}`;
+
+/** HTML shell + in-memory bundle; anything else is not served (and fails the check). */
+export function pageResponse(url, bundle, context) {
+ const parsed = new URL(url);
+ if (parsed.origin !== origin) return null;
+ const prefix = bundlePrefix(bundle);
+ if (parsed.pathname === '/') {
+ const json = JSON.stringify(context).replace(/</g, '\\u003c');
+ const links = bundle.styles
+ .map((href) => `<link rel="stylesheet" href="${prefix}${href}">`)
+ .join('');
+ return {
+ contentType: 'text/html',
+ headers: { 'Content-Security-Policy': csp },
+ body: `<!doctype html><html lang="${context.locale}"><head><meta charset="utf-8"><title>Cindy UI Check</title>${links}<script type="application/json" id="ui-page-context">${json}</script></head><body><div id="root"></div><script type="module" src="${prefix}/page.js"></script></body></html>`,
+ };
+ }
+ if (parsed.pathname === '/favicon.ico') return { status: 204, body: '' };
+ // Entry files are versioned by bundle; content-hashed assets are shared.
+ const key = parsed.pathname.startsWith(`${prefix}/`)
+ ? parsed.pathname.slice(prefix.length)
+ : parsed.pathname.startsWith('/assets/')
+ ? parsed.pathname
+ : null;
+ const file = key && bundle.files.get(key);
+ return file ? { contentType: file.contentType, body: file.body } : null;
+}
+
+/** Electron reads bundle files from disk through its own protocol handler (see electron.cjs). */
+async function writeBundle(dir, bundle) {
+ const prefix = bundlePrefix(bundle);
+ for (const [key, file] of bundle.files) {
+ const target = path.join(dir, key.startsWith('/assets/') ? key : `${prefix}${key}`);
+ if (existsSync(target)) continue;
+ await mkdir(path.dirname(target), { recursive: true });
+ await writeFile(target, file.body);
+ }
+}
+
+function browserPath(explicit) {
+ if (explicit) return explicit;
+ const installed = chromium.executablePath();
+ if (existsSync(installed)) return installed;
+ const candidates =
+ process.platform === 'darwin'
+ ? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome']
+ : process.platform === 'win32'
+ ? [process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA]
+ .filter(Boolean)
+ .map((base) => path.join(base, 'Google/Chrome/Application/chrome.exe'))
+ : ['/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome'];
+ const found = candidates.find((p) => existsSync(p));
+ if (!found)
+ throw new Error(
+ '未找到浏览器。运行 pnpm --filter desktop exec playwright-core install chromium,或传 --browser <可执行文件路径>。',
+ );
+ 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 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);
+ }
+ }
+ return {
+ overlay,
+ newSinceRef,
+ files: [...overlay.keys()].map((file) => path.relative(root, file)),
+ };
+}
+
+function overviewHtml(rows) {
+ const esc = (value) => String(value).replace(/[&<>"]/g, (char) => `&#${char.charCodeAt(0)};`);
+ return `<!doctype html><meta charset="utf-8"><style>
+ body{margin:0;padding:16px;font:12px -apple-system,system-ui,sans-serif;background:#f4f4f5;color:#18181b}
+ .row{display:flex;flex-wrap:wrap;gap:12px;align-items:flex-start;margin-bottom:20px}
+ .label{width:180px;flex-shrink:0;line-height:1.5}.failed{color:#b91c1c;font-weight:600}
+ figure{margin:0;background:#fff;border:1px solid #d4d4d8;border-radius:6px;padding:6px}
+ figcaption{margin-bottom:4px;color:#52525b}img{display:block;max-width:640px;max-height:440px}
+ </style>${rows
+ .map(
+ (row) =>
+ `<div class="row"><div class="label"><b>${esc(row.title)}</b><br>${esc(row.subtitle)}<br><span class="${row.status === 'failed' ? 'failed' : ''}">${esc(row.status)}${row.warnings ? ` · ${row.warnings} warnings` : ''}</span></div>${row.images
+ .map(
+ (image) =>
+ `<figure><figcaption>${esc(image.label)}</figcaption><img src="/__evidence/${image.src}"></figure>`,
+ )
+ .join('')}</div>`,
+ )
+ .join('')}`;
+}
+
+const KEEP_RUNS = 20;
+const OVERVIEW_ROWS = 6;
+
+/** The default evidence folder keeps the most recent runs only. */
+async function pruneEvidence(outputRoot, current) {
+ const runs = await Promise.all(
+ (await readdir(outputRoot, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
+ .map(async (entry) => {
+ const dir = path.join(outputRoot, entry.name);
+ return { dir, time: (await stat(dir)).mtimeMs };
+ }),
+ );
+ const stale = runs
+ .filter((run) => run.dir !== current)
+ .sort((a, b) => b.time - a.time)
+ .slice(KEEP_RUNS - 1);
+ await Promise.all(stale.map((run) => rm(run.dir, { recursive: true, force: true })));
+}
+
+/**
+ * Runs every variant of every selected page in one owned runtime, then exits.
+ * Preview mode keeps the single variant open and rebuilds on source changes.
+ */
+export async function runPlan(plan, options, externalSignal) {
+ const startedAt = performance.now();
+ const outputRoot = options.output ?? path.join(root, 'artifacts/ui-check');
+ await mkdir(outputRoot, { recursive: true });
+ const label = plan.label ?? plan.pages.map((item) => item.definition.name).join('+');
+ const evidence = await mkdtemp(path.join(outputRoot, `${label}-`));
+ if (!options.output) await pruneEvidence(outputRoot, evidence);
+ const scratch = await mkdtemp(path.join(os.tmpdir(), 'cindy-ui-check-'));
+ const summary = {
+ status: 'failed',
+ mode: options.mode,
+ engine: options.engine,
+ startedAt: new Date().toISOString(),
+ evidence,
+ overview: null,
+ commit: null,
+ worktreeDirty: null,
+ timings: {},
+ pages: [],
+ variants: [],
+ coverage: plan.coverage,
+ compare: null,
+ errors: [],
+ cleanup: { runtimeClosed: false, scratchRemoved: false },
+ };
+ try {
+ summary.commit = git(['rev-parse', 'HEAD']).trim();
+ summary.worktreeDirty = git(['status', '--porcelain']).trim().length > 0;
+ } catch {
+ // Not a git checkout; evidence still records digests.
+ }
+ const controller = new AbortController();
+ let browser, app, electronPage, stopping;
+ 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;
+ })());
+ const abort = () => controller.abort(externalSignal?.reason ?? new Error('Interrupted'));
+ externalSignal?.addEventListener('abort', abort, { once: true });
+ if (externalSignal?.aborted) abort();
+ controller.signal.addEventListener(
+ 'abort',
+ () => void stopRuntime().catch((error) => summary.errors.push(`shutdown: ${error.message}`)),
+ { once: true },
+ );
+ const measure = async (name, fn) => {
+ controller.signal.throwIfAborted();
+ const start = performance.now();
+ try {
+ return await fn();
+ } finally {
+ summary.timings[name] = (summary.timings[name] ?? 0) + Math.round(performance.now() - start);
+ }
+ };
+
+ // The route handler serves whatever variant is current (Electron reuses one window).
+ const current = { bundle: null, context: null, blocked: [], overview: '' };
+ const routePage = async (context) => {
+ await context.route('**/*', (route) => {
+ const url = route.request().url();
+ if (url.startsWith(`${origin}/__overview`))
+ return route.fulfill({ contentType: 'text/html', body: current.overview });
+ if (url.startsWith(`${origin}/__evidence/`)) {
+ const file = path.join(evidence, decodeURIComponent(new URL(url).pathname.slice(12)));
+ if (!file.startsWith(evidence + path.sep)) return route.abort();
+ return readFile(file).then(
+ (body) => route.fulfill({ contentType: 'image/png', body }),
+ () => route.abort(),
+ );
+ }
+ const response = current.bundle && pageResponse(url, current.bundle, current.context);
+ if (response) return route.fulfill(response);
+ current.blocked.push(url);
+ return route.abort();
+ });
+ await context.routeWebSocket('**/*', (socket) => {
+ current.blocked.push(socket.url());
+ socket.close();
+ });
+ };
+
+ const rows = [];
+ let documents = 0;
+ try {
+ for (const item of plan.pages) {
+ const after = await measure('buildMs', () => buildPage(item.definition));
+ item.bundles = { after };
+ const page = {
+ name: item.definition.name,
+ real: item.definition.real,
+ notCovered: item.definition.notCovered,
+ replaced: after.replaced,
+ inputCount: after.inputCount,
+ sourceDigest: after.sourceDigest,
+ bundleDigest: after.bundleDigest,
+ };
+ if (options.compare) {
+ const { overlay, newSinceRef, files } = compareOverlay(options.compare, after.inputs);
+ // Nothing this page loads differs from the ref: a second render would be identical.
+ if (overlay.size)
+ item.bundles.before = await measure('buildMs', () => buildPage(item.definition, overlay));
+ page.compare = { ref: options.compare, replacedFromRef: files, newSinceRef };
+ }
+ summary.pages.push(page);
+ }
+ if (options.compare) summary.compare = { ref: options.compare };
+
+ await measure('launchMs', async () => {
+ if (options.engine === 'electron') {
+ const env = Object.fromEntries(
+ Object.entries(process.env).filter(([key]) =>
+ /^(PATH|SYSTEMROOT|WINDIR|TEMP|TMP|TMPDIR|DISPLAY|WAYLAND_DISPLAY|XDG_RUNTIME_DIR|DBUS_SESSION_BUS_ADDRESS|LANG|LC_ALL)$/i.test(
+ key,
+ ),
+ ),
+ );
+ const first = plan.pages[0].variants[0].viewport;
+ // Playwright's Electron launcher always installs signal handlers that exit(130) before
+ // the CLI can write the summary and remove scratch data; the CLI owns interrupts instead.
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
+ const ownListeners = new Map(signals.map((name) => [name, process.listeners(name)]));
+ app = await _electron.launch({
+ executablePath: require('electron'),
+ args: [fileURLToPath(new URL('./electron.cjs', import.meta.url))],
+ timeout: options.timeout,
+ env: {
+ ...env,
+ CINDY_UI_PROFILE: path.join(scratch, 'profile'),
+ CINDY_UI_BUNDLE_DIR: path.join(scratch, 'bundle'),
+ CINDY_UI_EVIDENCE_DIR: evidence,
+ CINDY_UI_WIDTH: String(first.width),
+ CINDY_UI_HEIGHT: String(first.height),
+ CINDY_UI_PREVIEW: options.mode === 'preview' ? '1' : '0',
+ },
+ });
+ for (const name of signals)
+ for (const listener of process.listeners(name))
+ if (!ownListeners.get(name).includes(listener)) process.off(name, listener);
+ electronPage = await app.firstWindow({ timeout: options.timeout });
+ // Electron serves the test origin itself (electron.cjs) and cancels any other request.
+ electronPage.on('requestfailed', (request) => {
+ if (new URL(request.url()).origin !== origin) current.blocked.push(request.url());
+ });
+ summary.versions = await app.evaluate(() => ({
+ electron: process.versions.electron,
+ chrome: process.versions.chrome,
+ }));
+ } else {
+ const executablePath = browserPath(options.browser);
+ browser = await chromium.launch({
+ executablePath,
+ headless: options.mode !== 'preview',
+ timeout: options.timeout,
+ handleSIGINT: false,
+ handleSIGTERM: false,
+ handleSIGHUP: false,
+ });
+ summary.versions = { chrome: browser.version(), executablePath };
+ }
+ });
+
+ const openVariant = async (variant, bundle, definition) => {
+ let page, context;
+ if (app) {
+ page = electronPage;
+ await app.evaluate(({ BrowserWindow }, size) => {
+ BrowserWindow.getAllWindows()[0].setContentSize(size.width, size.height);
+ }, variant.viewport);
+ } else {
+ context = await browser.newContext({
+ viewport: variant.viewport,
+ // Same density as a Retina Mac and as the Electron runner, so crops are comparable.
+ deviceScaleFactor: 2,
+ serviceWorkers: 'block',
+ reducedMotion: 'reduce',
+ colorScheme: variant.theme,
+ locale: variant.locale,
+ });
+ await routePage(context);
+ page = await context.newPage();
+ }
+ await page.emulateMedia({ colorScheme: variant.theme, reducedMotion: 'reduce' });
+ const errors = [];
+ const onError = (error) => errors.push(error.message);
+ const onConsole = (message) => {
+ if (message.type() === 'error') errors.push(message.text());
+ };
+ page.on('pageerror', onError);
+ page.on('console', onConsole);
+ if (app) await writeBundle(path.join(scratch, 'bundle'), bundle);
+ current.bundle = bundle;
+ current.blocked = [];
+ current.context = {
+ page: variant.page,
+ case: variant.case,
+ theme: variant.theme,
+ locale: variant.locale,
+ platform: variant.platform,
+ viewport: variant.viewport,
+ data: definition.cases[variant.case]?.data ?? {},
+ storage: definition.cases[variant.case]?.storage,
+ };
+ page.setDefaultTimeout(Math.min(options.timeout, 10000));
+ if (app) {
+ const document = `/variant-${++documents}.html`;
+ current.document = path.join(scratch, 'bundle', document);
+ await writeFile(current.document, pageResponse(`${origin}/`, bundle, current.context).body);
+ await page.goto(`${origin}${document}`);
+ } else await page.goto(`${origin}/?variant=${encodeURIComponent(variant.id)}`);
+ await page
+ .waitForFunction(
+ () => window.__uiPage?.ready || document.documentElement.dataset.uiPageError,
+ undefined,
+ { timeout: options.timeout },
+ )
+ .catch((error) => {
+ throw new Error(
+ `mountPage() never finished${errors.length ? `: ${errors[0]}` : ''} (${error.message.split('\n')[0]})`,
+ );
+ });
+ const startupError = await page.evaluate(() => document.documentElement.dataset.uiPageError);
+ if (startupError) throw new Error(`page failed to start: ${startupError}`);
+ await definition.ready?.(page);
+ await page.evaluate(async () => {
+ await document.fonts.ready;
+ await Promise.all(Array.from(document.images).map((img) => img.decode().catch(() => {})));
+ });
+ if (app) {
+ 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 };
+ };
+
+ const runVariant = async (item, variant, role) => {
+ const definition = item.definition;
+ const dir = path.join(variant.id, role === 'before' ? 'before' : '');
+ await mkdir(path.join(evidence, dir), { recursive: true });
+ const result = {
+ id: variant.id,
+ role,
+ page: variant.page,
+ case: variant.case,
+ about: definition.cases[variant.case]?.about,
+ theme: variant.theme,
+ locale: variant.locale,
+ platform: variant.platform,
+ viewport: variant.viewport,
+ status: 'failed',
+ screenshots: [],
+ errors: [],
+ warnings: [],
+ hostMissing: [],
+ focus: [],
+ timings: {},
+ };
+ let opened;
+ let timer;
+ const started = performance.now();
+ const capture = async (name, captureOptions = {}) => {
+ 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);
+ };
+ // `--focus`: a 2x crop around one element plus its measured box, so small spacing and
+ // truncation changes are readable without opening the full screenshot.
+ const captureFocus = async (name) => {
+ const element = opened.page.locator(options.focus).first();
+ const box = (await element.count()) ? await element.boundingBox() : null;
+ // Absent at some captures is normal (e.g. before an event shows it).
+ if (!box) return;
+ const pad = 16;
+ const { width, height } = variant.viewport;
+ const x = Math.max(0, box.x - pad);
+ const y = Math.max(0, box.y - pad);
+ const clip = {
+ x,
+ y,
+ width: Math.min(width, box.x + box.width + pad) - x,
+ height: Math.min(height, box.y + box.height + pad) - y,
+ };
+ const file = path.join(dir, `${name}.focus.png`);
+ await opened.page.screenshot({
+ path: path.join(evidence, file),
+ clip,
+ scale: 'device',
+ timeout: 5000,
+ });
+ const metrics = await element.evaluate((el) => {
+ const style = getComputedStyle(el);
+ const text = [...el.querySelectorAll('*')]
+ .concat(el)
+ .filter((node) => node.scrollWidth > node.clientWidth + 1);
+ return {
+ padding: style.padding,
+ gap: style.gap,
+ font: `${style.fontSize}/${style.lineHeight} ${style.fontWeight}`,
+ clippedChildren: text.length,
+ };
+ });
+ result.focus.push({
+ capture: name,
+ file: file.split(path.sep).join('/'),
+ box: {
+ x: Math.round(box.x),
+ y: Math.round(box.y),
+ width: Math.round(box.width),
+ height: Math.round(box.height),
+ },
+ ...metrics,
+ });
+ };
+ try {
+ const work = (async () => {
+ opened = await openVariant(variant, item.bundles[role], definition);
+ result.timings.readyMs = Math.round(performance.now() - started);
+ const { page } = opened;
+ if (definition.adhoc && options.cases === 'all' && !item.expanded) {
+ item.expanded = true;
+ const cases = await page.evaluate(() => window.__uiPage.cases ?? null);
+ if (cases?.length) {
+ definition.cases = Object.fromEntries(cases.map((name) => [name, { about: name }]));
+ const all = variantsFor(definition, { ...options, cases: 'all' });
+ Object.assign(variant, all[0]);
+ Object.assign(result, { id: variant.id, case: variant.case, about: variant.case });
+ // Replace the provisional `default` variants with the declared case matrix.
+ item.variants.splice(0, item.variants.length, variant, ...all.slice(1));
+ }
+ }
+ 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,
+ data: current.context.data,
+ definition,
+ page,
+ capture,
+ t: (key, values) => page.evaluate(([k, v]) => window.__uiPage.t(k, v), [key, values]),
+ emit: (name, payload) =>
+ page.evaluate(([n, p]) => window.__uiPage.emit(n, p), [name, payload]),
+ };
+ if (role === 'after') await definition.check?.call(definition, page, ui);
+ else
+ await definition.check?.call(definition, page, ui).catch((error) => {
+ result.warnings.push(
+ `check on ${options.compare} stopped: ${String(error.message).split('\n')[0]}`,
+ );
+ });
+ result.timings.checkMs = Math.round(performance.now() - checkStarted);
+ const mutations = await page.evaluate(() => window.__uiPage.mutations);
+ if (mutations.length && role === 'after')
+ result.errors.push(`host mutations attempted: ${mutations.join(', ')}`);
+ if (
+ definition.check &&
+ !result.screenshots.includes(`${dir ? `${dir}/` : ''}final.png`)
+ )
+ await capture('final');
+ }
+ })();
+ work.catch(() => {});
+ await Promise.race([
+ work,
+ new Promise((_, reject) => {
+ timer = setTimeout(() => {
+ 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.
+ if (opened?.context) void opened.context.close().catch(() => {});
+ else if (app)
+ void Promise.race([
+ electronPage.goto('about:blank'),
+ delay(3000).then(() => Promise.reject(new Error('renderer hung'))),
+ ]).catch(() => stopRuntime().catch(() => {}));
+ }, options.timeout);
+ }),
+ new Promise((_, reject) => {
+ if (controller.signal.aborted) reject(controller.signal.reason);
+ controller.signal.addEventListener('abort', () => reject(controller.signal.reason), {
+ once: true,
+ });
+ }),
+ ]);
+ if (opened) 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)
+ result.errors.push(`unexpected network requests: ${current.blocked.join(', ')}`);
+ if (role === 'before') result.status = 'captured';
+ else result.status = result.errors.length ? 'failed' : 'passed';
+ } catch (error) {
+ result.errors.unshift(String(error?.stack ?? error));
+ if (opened) 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(() => {});
+ result.status = role === 'before' ? 'before-failed' : 'failed';
+ } finally {
+ clearTimeout(timer);
+ opened?.detach();
+ if (opened?.context) await opened.context.close().catch(() => {});
+ result.timings.totalMs = Math.round(performance.now() - started);
+ }
+ summary.variants.push(result);
+ return result;
+ };
+
+ if (options.mode === 'preview') {
+ const item = plan.pages[0];
+ const variant = item.variants[0];
+ const definition = item.definition;
+ const opened = await openVariant(variant, item.bundles.after, definition);
+ summary.status = 'preview-open';
+ console.log(
+ `UI_PREVIEW_READY ${evidence}\n关闭窗口或按 Ctrl+C 结束;源文件变化会重新编译并重置场景。`,
+ );
+ let reloads = 0;
+ while (!controller.signal.aborted && !opened.page.isClosed()) {
+ await delay(750, undefined, { signal: controller.signal }).catch(() => {});
+ if (controller.signal.aborted || opened.page.isClosed()) break;
+ if (!(await inputsChanged(item.bundles.after.fingerprints))) continue;
+ try {
+ item.bundles.after = await buildPage(definition);
+ current.bundle = item.bundles.after;
+ if (app) {
+ await writeBundle(path.join(scratch, 'bundle'), current.bundle);
+ await writeFile(
+ current.document,
+ pageResponse(`${origin}/`, current.bundle, current.context).body,
+ );
+ }
+ await opened.page.reload();
+ await opened.page.waitForFunction(() => window.__uiPage?.ready);
+ reloads++;
+ await opened.page.screenshot({ path: path.join(evidence, `reload-${reloads}.png`) });
+ console.log('UI_PREVIEW_RELOADED');
+ } catch (error) {
+ console.error(`预览更新失败:${error.message}。修正文件后会再次尝试。`);
+ }
+ }
+ summary.reloads = reloads;
+ summary.status = opened.errors.length || current.blocked.length ? 'failed' : 'preview-closed';
+ summary.errors.push(...opened.errors, ...current.blocked.map((url) => `blocked ${url}`));
+ } else {
+ for (const item of plan.pages) {
+ for (let index = 0; index < item.variants.length; index++) {
+ controller.signal.throwIfAborted();
+ const variant = item.variants[index];
+ const before = item.bundles.before
+ ? await measure('variantsMs', () => runVariant(item, variant, 'before'))
+ : null;
+ const after = await measure('variantsMs', () => runVariant(item, variant, 'after'));
+ rows.push({
+ title: `${variant.page} · ${variant.case}`,
+ subtitle: `${variant.theme} · ${variant.locale} · ${variant.viewport.width}×${variant.viewport.height}`,
+ status: after.status,
+ warnings: after.warnings.length,
+ // Before/after of the same capture sit side by side.
+ images: (after.focus.length
+ ? after.focus.map((item) => item.file)
+ : after.screenshots
+ ).flatMap((src) => {
+ const name = path.basename(src, '.png');
+ const pair = (
+ before?.focus.length ? before.focus.map((item) => item.file) : before?.screenshots
+ )?.find((file) => path.basename(file, '.png') === name);
+ return [
+ ...(pair ? [{ src: pair, label: `${name} · ${options.compare}` }] : []),
+ { src, label: before ? `${name} · now` : name },
+ ];
+ }),
+ });
+ if (app && app.process().exitCode !== null)
+ throw new Error('Electron exited during the run');
+ }
+ }
+ await measure('overviewMs', async () => {
+ const context = app
+ ? electronPage.context()
+ : await browser.newContext({ viewport: { width: 1600, height: 900 } });
+ if (!app) await routePage(context);
+ const page = app ? electronPage : await context.newPage();
+ if (app)
+ await app.evaluate(({ BrowserWindow }) =>
+ BrowserWindow.getAllWindows()[0].setContentSize(1600, 900),
+ );
+ // A few rows per image keeps each overview readable when opened at screen size.
+ summary.overviews = [];
+ for (let start = 0; start < rows.length; start += OVERVIEW_ROWS) {
+ const suffix = start ? `-${start / OVERVIEW_ROWS + 1}` : '';
+ current.overview = overviewHtml(rows.slice(start, start + OVERVIEW_ROWS));
+ if (app) {
+ await writeFile(
+ path.join(scratch, 'bundle', `overview${suffix}.html`),
+ current.overview,
+ );
+ await page.goto(`${origin}/overview${suffix}.html`);
+ } else await page.goto(`${origin}/__overview?${suffix}`);
+ await page.evaluate(async () => {
+ await Promise.all(
+ Array.from(document.images).map((img) => img.decode().catch(() => {})),
+ );
+ });
+ const file = path.join(evidence, `overview${suffix}.png`);
+ await page.screenshot({ path: file, fullPage: true, scale: 'css' });
+ summary.overviews.push(file);
+ }
+ summary.overview = summary.overviews[0] ?? null;
+ if (!app) await context.close();
+ });
+ const failed = summary.variants.filter(
+ (variant) => variant.role === 'after' && variant.status !== 'passed',
+ );
+ summary.status = failed.length ? 'failed' : 'passed';
+ }
+ } catch (error) {
+ summary.status = 'failed';
+ summary.errors.push(String(controller.signal.reason?.stack ?? error?.stack ?? error));
+ } finally {
+ externalSignal?.removeEventListener('abort', abort);
+ const closingAt = performance.now();
+ try {
+ await stopRuntime();
+ await rm(scratch, { recursive: true, force: true, maxRetries: 3 });
+ summary.cleanup.scratchRemoved = !existsSync(scratch);
+ } catch (error) {
+ summary.status = 'failed';
+ summary.cleanup.error = error.message;
+ }
+ if (!browser && !app) summary.cleanup.runtimeClosed = true;
+ summary.timings.closeMs = Math.round(performance.now() - closingAt);
+ summary.timings.totalMs = Math.round(performance.now() - startedAt);
+ summary.finishedAt = new Date().toISOString();
+ await writeFile(path.join(evidence, 'summary.json'), JSON.stringify(summary, null, 2));
+ }
+ return summary;
+}
diff --git a/apps/desktop/scripts/ui-page/runner.selftest.mjs b/apps/desktop/scripts/ui-page/runner.selftest.mjs
new file mode 100644
index 0000000000..f90fc5551f
--- /dev/null
+++ b/apps/desktop/scripts/ui-page/runner.selftest.mjs
@@ -0,0 +1,129 @@
+// Runner self-test: `pnpm ui:check:selftest`. It drives the real CLI against throwaway
+// entries, so it is node:test (not vitest) and opens Electron; it is not part of test:unit.
+import assert from 'node:assert/strict';
+import { spawn, execFileSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { after, before, test } from 'node:test';
+import { fileURLToPath } from 'node:url';
+
+const cli = fileURLToPath(new URL('./cli.mjs', import.meta.url));
+const harness = fileURLToPath(new URL('./harness/index.tsx', import.meta.url));
+let dir;
+
+function run(args, { interruptAfterMs } = {}) {
+ return new Promise((resolve) => {
+ const env = { ...process.env, NODE_DEBUG: '' };
+ const child = spawn(process.execPath, [cli, ...args], {
+ env,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', (chunk) => (stdout += chunk));
+ child.stderr.on('data', (chunk) => (stderr += chunk));
+ if (interruptAfterMs) setTimeout(() => child.kill('SIGINT'), interruptAfterMs);
+ child.on('exit', (code) => resolve({ code, stdout, stderr }));
+ });
+}
+
+const leftoverRunners = () => {
+ try {
+ return execFileSync('pgrep', ['-f', 'ui-page/electron.cjs'], { encoding: 'utf8' }).trim();
+ } catch {
+ return '';
+ }
+};
+
+async function entry(name, source) {
+ const file = path.join(dir, `${name}.tsx`);
+ await writeFile(file, `import { mountPage, forbid } from ${JSON.stringify(harness)};\n${source}`);
+ return file;
+}
+
+before(async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), 'cindy-ui-selftest-'));
+});
+after(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+test('one run reports each failure kind on its own variant', async () => {
+ const file = await entry(
+ 'matrix',
+ `
+function Page({ kind }: { kind: string }) {
+ if (kind === 'throws') throw new Error('selftest render failure');
+ if (kind === 'network') void fetch('https://example.com/selftest').catch(() => {});
+ if (kind === 'mutation') try { (window as any).electronAPI.maker.send({}); } catch {}
+ if (kind === 'missing') void (window as any).electronAPI.selftest?.unknownCall;
+ return <div>{kind === 'raw-key' ? 'bots.list.startChat' : 'Ready'}</div>;
+}
+mountPage({
+ cases: ['ok', 'throws', 'network', 'mutation', 'missing', 'raw-key'],
+ host: { maker: { send: forbid('maker.send') } },
+ render: (ctx) => <Page kind={ctx.case} />,
+});
+`,
+ );
+ const { code, stdout } = await run([
+ '--entry',
+ file,
+ '--case',
+ 'all',
+ '--json',
+ '--timeout',
+ '8000',
+ ]);
+ assert.equal(code, 1);
+ const summary = JSON.parse(stdout);
+ const byCase = Object.fromEntries(summary.variants.map((variant) => [variant.case, variant]));
+ assert.deepEqual(Object.keys(byCase).sort(), [
+ 'missing',
+ 'mutation',
+ 'network',
+ 'ok',
+ 'raw-key',
+ 'throws',
+ ]);
+ assert.equal(byCase.ok.status, 'passed');
+ assert.ok(existsSync(path.join(summary.evidence, byCase.ok.screenshots[0])));
+ assert.match(byCase.throws.errors.join('\n'), /selftest render failure/);
+ assert.match(byCase.network.errors.join('\n'), /example\.com/);
+ assert.match(byCase.mutation.errors.join('\n'), /maker\.send/);
+ assert.equal(byCase.missing.status, 'passed');
+ assert.ok(byCase.missing.hostMissing.some((key) => key.startsWith('selftest')));
+ assert.match(byCase['raw-key'].errors.join('\n'), /bots\.list\.startChat/);
+ assert.ok(existsSync(path.join(summary.evidence, 'summary.json')));
+ // The PR description lists the failing variants it came from.
+ assert.match(await readFile(summary.pr, 'utf8'), /未通过:`entry\.throws\./);
+});
+
+test('a page that never mounts fails at the timeout and leaves no runtime behind', async () => {
+ const file = await entry('stuck', `export {};\n`);
+ const started = Date.now();
+ const { code, stdout } = await run(['--entry', file, '--json', '--timeout', '1500']);
+ assert.equal(code, 1);
+ assert.match(
+ JSON.parse(stdout).variants[0].errors.join('\n'),
+ /mountPage\(\) never finished|timed out/,
+ );
+ assert.ok(Date.now() - started < 15000);
+ assert.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'], {
+ interruptAfterMs: 3000,
+ });
+ 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(), '');
+});
diff --git a/docs/design-evidence/2026-09-28/group-control-notice.md b/docs/design-evidence/2026-09-28/group-control-notice.md
index e9a5bce94d..b5556b0096 100644
--- a/docs/design-evidence/2026-09-28/group-control-notice.md
+++ b/docs/design-evidence/2026-09-28/group-control-notice.md
@@ -23,9 +23,11 @@
按 [治理合同 §6](../../design-rules/design-governance.md#6-证据合同),栅格文件只保留在 Git 忽略的临时目录,不提交到仓库。本 PR 尚未上传公开图片附件;下列命令可重建四张供审阅的 PNG,均带 fixture 标记。上传附件后可将对应 PR 评论链接追加到本索引。
```sh
-node apps/desktop/scripts/check-group-control-layout.mjs /path/to/chromium tmp/group-control-evidence/review-screenshots
+pnpm ui:check --page group-chat --case all --theme all --viewport 720x600,800x600,1280x800
```
+(原 `check-group-control-layout.mjs` 已并入单页验证;截图写到 `artifacts/ui-check/`。)
+
已目检:Light 1280px 单行、Dark 720px 八行,侧栏均为 280px;展开和收起各一张。保留的截图 SHA-256 用于核对原始文件;重跑时呼吸动画可能使图片字节不同。
| 文件 | SHA-256 |
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 9591fbe271..58bc914aab 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -517,7 +517,7 @@ Ordinary confirmations opt into standard buttons with `presentation="standard"`
- **Menu text** (`components/ui/dropdown-menu.tsx`): option rows (Item / CheckboxItem / RadioItem / SubTrigger) are `text-14` / `leading-[1.43]` (32px row with `py-1.5`) on `--cmd-palette-item-text`; shortcuts `text-12` / `leading-[1.33]` / 400 on `--cmd-palette-item-meta`; group labels `text-12` / 500 on `--cmd-palette-item-meta`; destructive rows `variant="danger"` on `--error-fg`; disabled rows 50% opacity. The text colour is the same at rest and on hover. The highlighted (`data-menu-active` / `data-[highlighted]`), checked or open row is 500 (§3 ladder) and its default-stroke Lucide icons go 1.5 → 2, on `--motion-instant` / `--motion-ease-out` (instant under reduced motion). Width never moves: row text and `truncate` spans reserve the 500 width with an invisible zero-height `::after` copy (`content: attr(data-menu-label) / ""`, so `textContent`, typeahead and the accessible name are unchanged), and the shared panels lock their laid-out width (`lockMenuWidth`, re-measured on content, window, image or font changes). A caller's own text colour, weight or inline width wins.
- **Menu hover highlight** (`components/ui/dropdown-menu-highlight.ts`): one `--sidebar-item-hover` surface (8px) per `DropdownMenuContent` / `DropdownMenuSubContent` glides between rows with `transform`; the row nearest the pointer anywhere in the panel wins, and separators do not interrupt the glide. Entering fades in from the checked row (or the target), leaving fades out; keyboard follows Radix's highlighted item, and an open SubTrigger stays highlighted while its submenu is in use. Motion: `transform` / `opacity` on `--motion-instant` / `--motion-ease-out` (fade-out `--motion-ease-in`), size snaps, no slide under reduced motion. Danger rows use the same grey layer. Rows whose caller sets its own `focus:` / `hover:` / `data-[highlighted]:` / `data-[state=open]:` background keep it and get no layer; `hoverHighlight={false}` restores per-row fills. Sidebar menus (`features/cc-agent/sidebar/menuStyles.ts`: `MENU_ITEM_CLASS` / `MENU_ROW_CLASS` = `h-8 gap-2`, triggers `cursor-pointer`) use the same highlight.
- **Panel width must bind to the trigger width** — never narrower or wider than the control that opened it, except for the explicitly scoped device-navigation treatment below. Radix Select: `position="popper"` + `width: var(--radix-select-trigger-width)`; other primitives measure the trigger. Ordinary form fields retain this equal-width invariant.
-- **Compact Cindy device navigation (sidebar and teammate chat header only)**: the trigger fits the device label, unread indicator and chevron, retaining its 24px height. The sidebar's remaining row area opens chat; the header trigger caps at 176px and may shrink with its available space. Long labels truncate and retain their full title. Its listbox is independently 256px wide, capped by the available viewport width, so device names, offline state and unread indicators remain usable even when the trigger says only “本机”. This exception belongs to `CindyDevicePicker`, not the shared Select default or other dropdowns. Keep the existing Radix keyboard/focus behavior and theme tokens. Browser hit-target regression: `apps/desktop/scripts/fixtures/cindy-device-picker/verify-device-picker.cjs`.
+- **Compact Cindy device navigation (sidebar and teammate chat header only)**: the trigger fits the device label, unread indicator and chevron, retaining its 24px height. The sidebar's remaining row area opens chat; the header trigger caps at 176px and may shrink with its available space. Long labels truncate and retain their full title. Its listbox is independently 256px wide, capped by the available viewport width, so device names, offline state and unread indicators remain usable even when the trigger says only “本机”. This exception belongs to `CindyDevicePicker`, not the shared Select default or other dropdowns. Keep the existing Radix keyboard/focus behavior and theme tokens. Hit-target and layout regression: `pnpm ui:check --page device-picker --case all --theme all --locale all`.
- **Select listbox option rows** (Select only; dropdown menu rows follow the Menu entries above): selected / hovered highlight fills use the **8px inner radius** (see §5 — the panel is a 12px container, the row highlight is the inner 8px tier; the inner radius must be smaller than the container's to nest cleanly). Highlight bg via `--surface-hover` / Radix `data-[highlighted]`; selected rows get the chip fill, unselected rows stay transparent.
- **Composer dropdown rows — one contract with the shared menu** (2026-10-04, supersedes 2026-07-22): the composer menus keep their own shells — MorphPopover (model / permission / + / agent; §14.4 container transform unchanged), the / and @ lists, the bot-chat @ list and the settings search results — but use the shared menu row parts from `components/ui/menu-row.tsx`: `COMPOSER_MENU_ROW` (8px radius, menu text / weight / motion), `menuRowAttrs`, `withMenuLabels`, and one glide highlight per panel (`useMenuPanel` + `MenuHighlightLayer`, the same `--sidebar-item-hover` layer as the shared menu). Rows inside a glide panel set no `hover:` / `focus:` fill of their own (rows that sit outside any glide panel — the model config card's engine rows, the legacy follow-session and "manage providers" rows — keep a `hover:bg-sidebar-item-hover` fill in the same grey). The selected row is marked by a check + 500 and never by a fill — permission, + and agent menus. **The model menu is the one exception** (owner ruling 2026-10-04, keeping the 2026-08-13 ruling): its chosen row keeps a whole-row `--sidebar-item-hover` fill with no check (`data-[menu-active]:bg-transparent`, so the fill steps aside while the glide layer covers that row instead of stacking two translucent layers), the model name stays 500, and the effort / follow-session rows keep their fill and existing check; it still takes the shared glide highlight and the glass panel. Danger-tier orange / blue tints the **text only**. Lists that keep focus in a text input (/, @, bot @, settings search) stay focus-in-input: the highlight follows their own current index (`data-menu-current` or `aria-selected`) through `attachMenuHighlight`'s `current` option, never Radix focus. Panels: MorphPopover ends on `--menu-panel-surface` (the shared menu's glass under Cindy themes, opaque on Windows) with `--cmd-palette-border` and `--shadow-menu`; the / and @ lists and the model config flyout use the same 12px panel and `--shadow-menu` (the softer `--cmd-palette-shadow` stays for the command palette and the / tooltip). Group labels use the shared label (12 / 500 / `--cmd-palette-item-meta`). When touching any composer menu's row styles, change them through `menu-row.tsx` — never one menu alone.
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index 51938813c5..5b47500b89 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -7,6 +7,9 @@
## Agent 启动入口
+只为检查界面改动(样式、布局、文案、深浅色、多语言)时不必启动 Desktop,先用下文
+「单页 UI 快速验证」;需要真实 IPC、登录、数据库或跨设备行为时再按本节启动。
+
Agent 启动 Desktop 只使用仓库根的安全包装命令,并显式选择目标区域。restart
命令默认使用固定的 `dev` 命名隔离沙箱(等价于自动附加 `--isolated=dev`),
不再默认共享 Cindy 账号登录态与业务数据。OpenAI 模型登录态是刻意保留的例外:
@@ -203,6 +206,51 @@ pnpm test:unit
对应规则,不以本页命令替代专项验证。
- 记录实际执行和结果;未执行的高相关检查必须说明原因。
+## 单页 UI 快速验证
+
+`pnpm ui:check` 只编译被改的真实 renderer 组件,在一个隔离的 Electron 窗口(与 Cindy 同一
+Chromium)里按「场景 × 主题 × 语言 × 窗口尺寸」逐个截图、做通用检查后退出,不加载 main、
+登录、数据库或 Agent。一个场景约 0.5 秒,整页全矩阵通常在 20 秒内,可以在每次改 UI 后自检,
+不必为此启动完整 Desktop。
+
+```bash
+pnpm ui:check --changed --theme all
+pnpm ui:check --page group-chat --case all --theme all --locale all
+pnpm ui:check --page group-chat --case long-device --compare
+pnpm ui:check --list
+pnpm ui:preview --page device-picker
+pnpm ui:check:publish
+pnpm ui:check:selftest
+```
+
+- `--changed` 按本分支改动选出加载了这些文件的页面;输出里 `UNCOVERED` 的文件**没有被验证**,
+ 需要补场景、用 `--entry` 临时挂载,或回到完整 Desktop。
+- 报告首行 `UI_CHECK passed|failed`,`overview.png`(变体多时还有 `overview-2.png` 等)是截图
+ 总览,失败原因、宿主缺失接口和被替换的模块都写在 `summary.json`。自检读 overview 判断视觉
+ 效果,不靠“命令通过”下结论。
+- `ui:preview` 只在需要人工手动验收时使用:保持一个窗口、改文件自动重载,关窗或 Ctrl+C 结束。
+- 场景数据、宿主模拟、多语言和对比模式的写法见
+ [单页验证说明](../../apps/desktop/scripts/ui-page/README.md)。
+
+### 按改动选择验证方式
+
+| 改动 | 先做 | 何时升级 |
+| --- | --- | --- |
+| renderer 组件的样式、布局、文案、图标、深浅色 | `pnpm ui:check --changed --theme all` | 有 `UNCOVERED` 时补场景或用 `--entry`;文案改动加 `--locale all`;间距、截断类改动加 `--focus <选择器>` 看放大图和实测尺寸 |
+| 修已有界面 bug,需要改前/改后对照 | `pnpm ui:check --page <页面> --case <场景> --compare` | 修复依赖真实数据流时补定向 vitest |
+| 新组件或还没有页面覆盖的组件 | 写 `tmp/` 下的临时入口:`pnpm ui:check --entry tmp/<名>.tsx` | 会反复回归的组件在 `scripts/fixtures/` 下注册页面 |
+| renderer 逻辑、hook、store、数据转换 | 定向 vitest | 结果显示在界面上时再跑 `ui:check` |
+| main、preload、IPC、数据库、登录、发送、跨设备、窗口生命周期 | 定向测试 + 隔离 Desktop(见「Agent 启动入口」) | `ui:check` 不覆盖这些行为,不能替代 |
+
+普通界面改动的 PR 截图直接用单页验证:检查通过后运行 `pnpm ui:check:publish`,它把最近一次
+运行的总览截图推到作者 fork 的 `pr-assets/<当前分支>`(不进上游仓库,也不动工作区),并输出
+一段带图片链接的「UI 变化」:命令、平台、版本、场景、通过情况、未覆盖的行为和 `--focus` 实测的
+改前/改后数值,原样写进 PR 正文。登录、发送、跨设备等单页验证覆盖不到的变化,仍按原方式附
+完整 Cindy 截图。
+
+`ui:check` 通过只说明列出的场景在真实组件上渲染正确;报告里 `not covered` 列出的行为仍须按
+对应流程验收,正式 PR 前的真实运行验收要求不变。
+
## Linux 系统托盘
Linux 主窗口创建时注册 Electron Tray,提供显示主窗口、打开日志目录、退出 Cindy。
diff --git a/package.json b/package.json
index 35b10c31e7..35db9c7ece 100644
--- a/package.json
+++ b/package.json
@@ -101,6 +101,10 @@
"install:pi": "node scripts/ensure-agent-binaries.mjs --kinds=pi",
"install:agent-binaries": "node scripts/ensure-agent-binaries.mjs",
"postinstall": "node scripts/ensure-agent-binaries.mjs --best-effort && node scripts/fix-node-pty-perms.mjs && node scripts/ensure-deps.mjs --electron-binary",
+ "ui:check": "node apps/desktop/scripts/ui-page/cli.mjs",
+ "ui:preview": "node apps/desktop/scripts/ui-page/cli.mjs --preview",
+ "ui:check:selftest": "node --test apps/desktop/scripts/ui-page/runner.selftest.mjs",
+ "ui:check:publish": "node apps/desktop/scripts/ui-page/publish.mjs",
"dev:desktop": "node scripts/ensure-deps.mjs && node scripts/ensure-dev-runtime-assets.mjs && pnpm --filter desktop dev",
"dev:desktop:remote": "node scripts/ensure-deps.mjs && node scripts/ensure-dev-runtime-assets.mjs && pnpm --filter desktop dev:remote",
"restart:desktop:remote": "node scripts/desktop-restart-runner.mjs --wait-ready",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b0810cf61b..c912fad3f0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -518,7 +518,7 @@ importers:
devDependencies:
'@electron-forge/cli':
specifier: ^7.11.1
'@electron-forge/maker-deb':
specifier: ^7.11.1
version: 7.11.2
@@ -594,6 +594,9 @@ importers:
electron:
specifier: 42.11.12
version: 42.11.12
+ esbuild:
+ specifier: 0.28.1
+ version: 0.28.1
eslint:
specifier: ^9.0.0
version: 9.39.5([email protected])
@@ -603,6 +606,9 @@ importers:
jsdom:
specifier: ^29.1.1
version: 29.1.1(@noble/[email protected])
+ playwright-core:
+ specifier: 1.60.0
+ version: 1.60.0
postcss:
specifier: ^8.4.49
version: 8.5.19
@@ -12437,9 +12443,9 @@ snapshots:
dependencies:
'@types/hammerjs': 2.0.46
dependencies:
- '@electron-forge/core': 7.11.2([email protected])([email protected])
+ '@electron-forge/core': 7.11.2([email protected])([email protected])([email protected])
'@electron-forge/core-utils': 7.11.2
'@electron-forge/shared-types': 7.11.2
'@electron/get': 3.1.0
@@ -12484,7 +12490,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@electron-forge/core-utils': 7.11.2
'@electron-forge/maker-base': 7.11.2
@@ -12495,7 +12501,7 @@ snapshots:
'@electron-forge/template-vite': 7.11.2
'@electron-forge/template-vite-typescript': 7.11.2
'@electron-forge/template-webpack': 7.11.2
- '@electron-forge/template-webpack-typescript': 7.11.2([email protected])([email protected])
+ '@electron-forge/template-webpack-typescript': 7.11.2([email protected])([email protected])([email protected])
'@electron-forge/tracer': 7.11.2
'@electron/get': 3.1.0
'@electron/packager': 18.4.4
@@ -12649,13 +12655,13 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@electron-forge/shared-types': 7.11.2
'@electron-forge/template-base': 7.11.2
fs-extra: 10.1.0
typescript: 5.4.5
transitivePeerDependencies:
- '@minify-html/node'
- '@swc/core'
@@ -20450,14 +20456,15 @@ snapshots:
dependencies:
'@jridgewell/trace-mapping': 0.3.31
jest-worker: 27.5.1
schema-utils: 4.3.3
terser: 5.49.0
optionalDependencies:
+ esbuild: 0.28.1
lightningcss: 1.33.0
postcss: 8.5.19
@@ -22972,7 +22979,7 @@ snapshots:
dependencies:
'@types/estree': 1.0.9
'@types/json-schema': 7.0.15
@@ -22990,7 +22997,7 @@ snapshots:
graceful-fs: 4.2.11
loader-runner: 4.3.2
mime-db: 1.54.0
neo-async: 2.6.2
schema-utils: 4.3.3
tapable: 2.3.3