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。

fix(desktop): 单页验证对照图片资源、两段翻译 key 与自测等待

Chris762b3d876f5c
diff --git a/apps/desktop/scripts/ui-page/README.md b/apps/desktop/scripts/ui-page/README.md
index 11dbbc32f2..e8cd776c76 100644
--- a/apps/desktop/scripts/ui-page/README.md
+++ b/apps/desktop/scripts/ui-page/README.md
@@ -180,8 +180,8 @@ mountPage({ cases: ['off', 'on'], render: (ctx) => <Switch checked={ctx.case ===
## 改前/改后对照
-`--compare [<ref>]` 把本页面加载的产品源码、样式与翻译(`apps/desktop/src`、`packages` 下的
-脚本、CSS、JSON,含全局样式)换回 `<ref>` 的版本再渲染一次,此后移动或删除的文件也按 `<ref>`
+`--compare [<ref>]` 把本页面加载的产品源码、样式、翻译与图片字体(`apps/desktop/src`、
+`apps/desktop/resources`、`packages` 下的脚本、CSS、JSON 与资源文件,含全局样式)换回 `<ref>` 的版本再渲染一次,此后移动或删除的文件也按 `<ref>`
补回;不写 `<ref>` 时用本分支与上游主干的分叉点,也就是“本分支改动之前”。场景与
harness 始终用当前版本,所以两边执行同样的步骤、截同样的图。没有文件不同时不重复渲染。
改前一侧的断言失败不影响结果,在报告里以 `before <ref>:` 开头逐条列出;`<ref>` 之后才新增的文件按当前版本使用并列出。
diff --git a/apps/desktop/scripts/ui-page/audit.mjs b/apps/desktop/scripts/ui-page/audit.mjs
index 77b944c138..7c2e167ee9 100644
--- a/apps/desktop/scripts/ui-page/audit.mjs
+++ b/apps/desktop/scripts/ui-page/audit.mjs
@@ -31,13 +31,16 @@ export function pageAudit() {
if (!el.closest('[title]')) truncatedWithoutTitle.push(item);
} else if (overflowX || overflowY) clipped.push({ ...item, axis: overflowX ? 'x' : 'y' });
}
+ const runtime = window.__uiPage;
+ // Three or more segments read as a key on their own; two-segment text (`bots.send`, but also
+ // `example.com`) counts only when it is an actual translation key.
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);
+ if (!/^[a-z][a-zA-Z0-9_-]*(\.[a-zA-Z0-9_-]+)+$/.test(value)) continue;
+ if (/(\.[^.]+){2,}/.test(value) || runtime.isTranslationKey?.(value)) rawKeys.push(value);
}
- const runtime = window.__uiPage;
return {
horizontalOverflow: document.documentElement.scrollWidth > innerWidth,
rawKeys,
diff --git a/apps/desktop/scripts/ui-page/build.mjs b/apps/desktop/scripts/ui-page/build.mjs
index f569ece219..b3313d58ab 100644
--- a/apps/desktop/scripts/ui-page/build.mjs
+++ b/apps/desktop/scripts/ui-page/build.mjs
@@ -22,10 +22,19 @@ const assetLoaders = Object.fromEntries(
]),
);
const SOURCE = /\.[cm]?[jt]sx?$/;
-// Inputs `--compare` can take from another revision: source, styles and translations.
-const OVERLAY = /\.(?:[cm]?[jt]sx?|css|json)$/;
+// Inputs `--compare` can take from another revision: source, styles, translations and assets.
+const ASSET = new RegExp(`(?:${Object.keys(assetLoaders).join('|').replaceAll('.', '\\.')})$`);
+const OVERLAY = /\.(?:[cm]?[jt]sx?|css|json|png|jpe?g|gif|webp|avif|svg|woff2?|ttf|otf)$/;
const loaderFor = (file) =>
- file.endsWith('.css') ? 'css' : file.endsWith('.json') ? 'json' : /x$/.test(file) ? 'tsx' : 'ts';
+ ASSET.test(file)
+ ? 'file'
+ : file.endsWith('.css')
+ ? 'css'
+ : file.endsWith('.json')
+ ? 'json'
+ : /x$/.test(file)
+ ? 'tsx'
+ : 'ts';
const CONTENT_TYPES = {
'.js': 'text/javascript',
'.css': 'text/css',
diff --git a/apps/desktop/scripts/ui-page/harness/index.tsx b/apps/desktop/scripts/ui-page/harness/index.tsx
index 70a77dd9c3..df9e5db0f3 100644
--- a/apps/desktop/scripts/ui-page/harness/index.tsx
+++ b/apps/desktop/scripts/ui-page/harness/index.tsx
@@ -41,6 +41,8 @@ export interface PageDefinition {
render: (ctx: UiPageContext) => ReactNode;
}
+const requestedKeys = new Set<string>();
+
/** 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;
@@ -52,6 +54,7 @@ function trackMissingTranslations(): void {
...rest: unknown[]
) => {
const list = (Array.isArray(keys) ? keys : [keys]).filter((key) => typeof key === 'string');
+ for (const key of list) requestedKeys.add(key);
const lng = (options?.lng as string | undefined) ?? i18n.language;
if (
list.length &&
@@ -80,6 +83,8 @@ export async function mountPage(definition: PageDefinition): Promise<void> {
await i18n.changeLanguage(ctx.locale);
trackMissingTranslations();
runtime.t = (key, options) => i18n.t(key, options) as string;
+ // Lets the audit tell a rendered translation key from ordinary dotted text.
+ runtime.isTranslationKey = (text) => requestedKeys.has(text) || i18n.exists(text);
const content = definition.render(ctx);
createRoot(document.getElementById('root')!).render(
<ThemeProvider syncWindowVibrancy={false}>
diff --git a/apps/desktop/scripts/ui-page/harness/types.ts b/apps/desktop/scripts/ui-page/harness/types.ts
index bc50d179e7..c52c46d73c 100644
--- a/apps/desktop/scripts/ui-page/harness/types.ts
+++ b/apps/desktop/scripts/ui-page/harness/types.ts
@@ -25,5 +25,7 @@ export interface UiPageRuntime {
/** 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;
+ /** True when `text` is a key the page requested through t() or one the resources define. */
+ isTranslationKey?: (text: string) => boolean;
cases?: string[];
}
diff --git a/apps/desktop/scripts/ui-page/run.mjs b/apps/desktop/scripts/ui-page/run.mjs
index b96b2c39d9..adafd58502 100644
--- a/apps/desktop/scripts/ui-page/run.mjs
+++ b/apps/desktop/scripts/ui-page/run.mjs
@@ -86,7 +86,8 @@ function browserPath(explicit) {
return found;
}
-const COMPARE_SCOPE = ['apps/desktop/src', 'packages'];
+const COMPARE_SCOPE = ['apps/desktop/src', 'apps/desktop/resources', 'packages'];
+const BINARY = /\.(?:png|jpe?g|gif|webp|avif|woff2?|ttf|otf)$/;
const MODULE_SUFFIXES = [
'',
'.ts',
@@ -126,11 +127,16 @@ function compareOverlay(ref) {
get(file) {
if (!this.has(file)) return undefined;
this.used.add(file);
- if (!contents.has(file))
+ if (!contents.has(file)) {
+ const spec = `${ref}:${path.relative(root, file).split(path.sep).join('/')}`;
+ // Images and fonts stay bytes; source, styles and translations are text.
contents.set(
file,
- git(['show', `${ref}:${path.relative(root, file).split(path.sep).join('/')}`]),
+ BINARY.test(file)
+ ? execFileSync('git', ['show', spec], { cwd: root, maxBuffer: 64 * 1024 * 1024 })
+ : git(['show', spec]),
);
+ }
return contents.get(file);
},
resolve(candidate) {
@@ -455,6 +461,8 @@ export async function runPlan(plan, options, externalSignal) {
const runVariant = async (item, variant, role) => {
const definition = item.definition;
+ // Lets an observer (the runner self-test) act once a variant is in progress.
+ if (process.env.CINDY_UI_PROGRESS) process.stderr.write(`UI_VARIANT ${variant.id} ${role}\n`);
const dir = path.join(variant.id, role === 'before' ? 'before' : '');
await mkdir(path.join(evidence, dir), { recursive: true });
const result = {
diff --git a/apps/desktop/scripts/ui-page/runner.selftest.mjs b/apps/desktop/scripts/ui-page/runner.selftest.mjs
index f90fc5551f..f0b98b3390 100644
--- a/apps/desktop/scripts/ui-page/runner.selftest.mjs
+++ b/apps/desktop/scripts/ui-page/runner.selftest.mjs
@@ -13,18 +13,25 @@ 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 } = {}) {
+function run(args, { interruptWhenRunning } = {}) {
return new Promise((resolve) => {
- const env = { ...process.env, NODE_DEBUG: '' };
+ const env = { ...process.env, NODE_DEBUG: '', CINDY_UI_PROGRESS: '1' };
const child = spawn(process.execPath, [cli, ...args], {
env,
stdio: ['ignore', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
+ let interrupted = false;
child.stdout.on('data', (chunk) => (stdout += chunk));
- child.stderr.on('data', (chunk) => (stderr += chunk));
- if (interruptAfterMs) setTimeout(() => child.kill('SIGINT'), interruptAfterMs);
+ child.stderr.on('data', (chunk) => {
+ stderr += chunk;
+ // Interrupt as soon as the runtime is up and a variant is waiting on the page.
+ if (interruptWhenRunning && !interrupted && /^UI_VARIANT /m.test(stderr)) {
+ interrupted = true;
+ child.kill('SIGINT');
+ }
+ });
child.on('exit', (code) => resolve({ code, stdout, stderr }));
});
}
@@ -59,7 +66,15 @@ function Page({ kind }: { kind: string }) {
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>;
+ return kind === 'raw-key' ? (
+ <div>
+ <p>bots.list.startChat</p>
+ <p>bots.send</p>
+ <p>cindy.app</p>
+ </div>
+ ) : (
+ <div>Ready</div>
+ );
}
mountPage({
cases: ['ok', 'throws', 'network', 'mutation', 'missing', 'raw-key'],
@@ -95,7 +110,8 @@ mountPage({
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/);
+ // Two-segment keys count when they are real keys; ordinary dotted text does not.
+ assert.match(byCase['raw-key'].errors.join('\n'), /bots\.list\.startChat, bots\.send$/m);
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\./);
@@ -104,7 +120,7 @@ mountPage({
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']);
+ const { code, stdout } = await run(['--entry', file, '--json', '--timeout', '1000']);
assert.equal(code, 1);
assert.match(
JSON.parse(stdout).variants[0].errors.join('\n'),
@@ -118,7 +134,7 @@ 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,
+ interruptWhenRunning: true,
});
assert.equal(code, 1);
const summaryFile = /summary:\s+(\S+)/.exec(stdout)?.[1];