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。

test: 提升跨平台单测基础设施稳定性 (#449)

DavidShenXD09c6b564c0c9
diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
index 3c5e9815c3..b9362d4cc6 100644
--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
@@ -18,6 +18,22 @@ async function tempRoot(): Promise<string> {
return root;
}
+/**
+ * Chromium uses a relative file symlink for SingletonLock on macOS/Linux.
+ * Windows local test hosts may not have file-symlink privileges, so use a
+ * directory junction whose readlink target preserves the same trailing PID.
+ */
+async function writeSingletonLock(root: string, pid: number): Promise<void> {
+ const lockTarget = `myhost-${pid}`;
+ if (process.platform === 'win32') {
+ const junctionTarget = path.join(root, 'singleton-lock-targets', lockTarget);
+ await fs.mkdir(junctionTarget, { recursive: true });
+ await fs.symlink(junctionTarget, path.join(root, 'SingletonLock'), 'junction');
+ return;
+ }
+ await fs.symlink(lockTarget, path.join(root, 'SingletonLock'));
+}
+
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
});
@@ -197,7 +213,7 @@ describe('claimLegacyOwnerNamespace', () => {
const root = await tempRoot();
await fs.writeFile(path.join(root, 'slack-hook.json'), 'legacy-hook');
// 历史 packaged build 不写 .dev-instances,但持有 Chromium 单例锁 symlink。
- await fs.symlink('myhost-4242', path.join(root, 'SingletonLock'));
+ await writeSingletonLock(root, 4242);
const result = await claimLegacyOwnerNamespace(
{ mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },
@@ -216,7 +232,7 @@ describe('claimLegacyOwnerNamespace', () => {
it('ignores a stale SingletonLock whose pid is dead and migrates normally', async () => {
const root = await tempRoot();
await fs.writeFile(path.join(root, 'slack-hook.json'), 'legacy-hook');
- await fs.symlink('myhost-4242', path.join(root, 'SingletonLock'));
+ await writeSingletonLock(root, 4242);
const result = await claimLegacyOwnerNamespace(
{ mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },
@@ -461,7 +477,7 @@ describe('hasLegacyOwnerNamespaceClaim', () => {
path.join(root, __testing.CLAIM_MARKER),
JSON.stringify({ version: 1, ownerKey: dataOwnerStorageKey('cloud-a'), complete: true }),
);
- await fs.symlink('myhost-4242', path.join(root, 'SingletonLock'));
+ await writeSingletonLock(root, 4242);
expect(hasLegacyOwnerNamespaceClaim('cloud-a', root, (pid) => pid === 4242)).toBe(false);
expect(hasLegacyOwnerNamespaceClaim('cloud-a', root, () => false)).toBe(true);
});
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.ts
index e1b3190c54..2b407f067d 100644
--- a/apps/desktop/src/main/__tests__/updateService.test.ts
+++ b/apps/desktop/src/main/__tests__/updateService.test.ts
@@ -1,13 +1,13 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { TEST_CDN_BASE_URL as CDN_EXTERNAL_BASE_URL } from '../../test/vitest/clientEndpointsFixture';
const originalPlatform = process.platform;
-const TEST_ROOT = path.join(os.tmpdir(), 'xdt-maker-update-service-test');
-const TEST_USER_DATA = path.join(TEST_ROOT, 'user-data');
-const TEST_EXE = path.join(TEST_ROOT, 'app', 'xdt-maker.exe');
+let TEST_ROOT: string;
+let TEST_USER_DATA: string;
+let TEST_EXE: string;
const browserWindowGetAllWindows = vi.fn(() => []);
const ipcMainHandle = vi.fn();
@@ -114,6 +114,15 @@ async function freshUpdateService(platform: NodeJS.Platform) {
return import('../updateService');
}
+beforeAll(() => {
+ TEST_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-maker-update-service-test-'));
+ TEST_USER_DATA = path.join(TEST_ROOT, 'user-data');
+ TEST_EXE = path.join(TEST_ROOT, 'app', 'xdt-maker.exe');
+});
+afterAll(() => {
+ if (!TEST_ROOT) return;
+ fs.rmSync(TEST_ROOT, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
+});
beforeEach(() => {
browserWindowGetAllWindows.mockReset();
browserWindowGetAllWindows.mockReturnValue([]);
diff --git a/apps/desktop/src/renderer/__tests__/builtinToolsWorkingDirScope.test.ts b/apps/desktop/src/renderer/__tests__/builtinToolsWorkingDirScope.test.ts
index 1b22956475..450f089fd9 100644
--- a/apps/desktop/src/renderer/__tests__/builtinToolsWorkingDirScope.test.ts
+++ b/apps/desktop/src/renderer/__tests__/builtinToolsWorkingDirScope.test.ts
@@ -6,7 +6,7 @@ import { describe, expect, it } from 'vitest';
const source = readFileSync(
resolve(__dirname, '..', 'components', 'settings', 'BuiltinToolsSection.tsx'),
'utf8',
-);
+).replace(/\r\n?/g, '\n');
describe('BuiltinToolsSection working directory scope', () => {
it('groups managed worktrees locally without changing the shared active cwd', () => {
diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.md
index aab880fdfb..40d092830f 100644
--- a/docs/dev-rules/development-workflow.md
+++ b/docs/dev-rules/development-workflow.md
@@ -66,6 +66,11 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径
宿主删除/归档会话时自动存的内容快照(见第 1 节),以及会话必须收尾、测试却来不及
修好时的收尾 commit——后者 commit message 必须标注 `WIP`,且在门禁通过前不得
push、不得提 PR。
+ - **完整单测的外层超时**:`pnpm test:unit` 是全仓串行门禁,正常执行可能超过数分钟。
+ 调用它的 agent/自动化工具不得使用 120 秒或更短的绝对超时;未知当前耗时时,外层
+ 兜底超时至少设为 15 分钟。工具支持后台运行或 yielded process handle 时优先使用该
+ 模式并短轮询进度,不要因为调用端停止等待就误判失败、杀掉仍在正常运行的测试或重复
+ 启动一轮。Vitest 的单测试例超时仍由各 package 配置控制,不受这条外层约束影响。
- **在门禁之上按风险追加验证**:跨模块、高风险或基础设施改动追加更广泛验证(如仓库根
`pnpm test:all`),**最终以 CI 门禁为准**。不得通过 skip、删除或弱化测试制造通过;
PR「怎么验证的」一节必须**如实**填写,没跑不许写已跑。
diff --git a/scripts/__tests__/check-dco.test.mjs b/scripts/__tests__/check-dco.test.mjs
index 117211edf9..5eb3504c42 100644
--- a/scripts/__tests__/check-dco.test.mjs
+++ b/scripts/__tests__/check-dco.test.mjs
@@ -31,6 +31,7 @@ import {
resolveHooksDir,
resolveHooksPathFrom,
} from '../install-dco-hook.mjs';
+import { resolvePosixShell } from '../lib/posix-shell.mjs';
const ROOT = path.resolve(fileURLToPath(new URL('../..', import.meta.url)));
const CHECK_DCO = path.join(ROOT, 'scripts', 'check-dco.mjs');
@@ -360,7 +361,7 @@ test('legacy hooks-path fallback resolves against the caller cwd', () => {
assert.equal(resolveHooksPathFrom(path.resolve('/abs/.git/hooks'), '/anywhere'), path.resolve('/abs/.git/hooks'));
});
-test('the hook source is a POSIX sh script that pins its trailer behaviour', () => {
+test('the hook source pins its POSIX trailer behaviour', () => {
const source = readHookSource();
assert.match(source, /^#!\/bin\/sh\n/);
assert.ok(source.includes(HOOK_MARKER), 'hook 必须带 marker,否则安装器无法认领它');
@@ -372,8 +373,77 @@ test('the hook source is a POSIX sh script that pins its trailer behaviour', ()
// 配成 doNothing 时 hook 会在已有他人签名的提交上静默漏签,必须显式钉住。
assert.match(source, /--if-exists addIfDifferent/);
assert.match(source, /--if-missing add/);
- // 语法必须是 POSIX sh:hook 由 git 用 /bin/sh 执行,bashism 在 dash 上会直接失败。
- execFileSync('sh', ['-n', path.join(ROOT, HOOK_SOURCE_PATH)]);
+});
+
+const posixSh = resolvePosixShell('sh');
+test(
+ 'the hook source passes POSIX sh syntax validation',
+ { skip: posixSh === null ? 'POSIX sh is unavailable on this host' : false },
+ () => {
+ // Git for Windows 自带 sh 但不保证其 bin 目录进入 PATH;macOS/Linux 仍走系统 sh。
+ execFileSync(posixSh, ['-n', path.join(ROOT, HOOK_SOURCE_PATH)]);
+ },
+);
+
+test('resolvePosixShell preserves Unix PATH lookup and locates Git for Windows shells', () => {
+ const mustNotProbe = () => {
+ throw new Error('non-Windows resolution must not probe the Windows filesystem');
+ };
+ assert.equal(
+ resolvePosixShell('sh', {
+ platform: 'linux',
+ spawnSyncImpl: mustNotProbe,
+ existsSync: mustNotProbe,
+ }),
+ 'sh',
+ );
+ assert.equal(
+ resolvePosixShell('bash', {
+ platform: 'darwin',
+ spawnSyncImpl: mustNotProbe,
+ existsSync: mustNotProbe,
+ }),
+ 'bash',
+ );
+
+ const expected = path.win32.join('D:\\Tools\\Git', 'bin', 'sh.exe');
+ assert.equal(
+ resolvePosixShell('sh', {
+ platform: 'win32',
+ env: {},
+ spawnSyncImpl: () => ({
+ status: 0,
+ stdout: 'D:\\Tools\\Git\\cmd\\git.exe\r\n',
+ }),
+ existsSync: (candidate) => candidate === expected,
+ }),
+ expected,
+ );
+});
+
+test('resolvePosixShell never probes relative candidates from blank or invalid Windows env paths', () => {
+ const candidates = [];
+ assert.equal(
+ resolvePosixShell('sh', {
+ platform: 'win32',
+ env: {
+ ProgramFiles: '',
+ 'ProgramFiles(x86)': 'relative',
+ LOCALAPPDATA: ' ',
+ },
+ spawnSyncImpl: () => ({ status: 1, stdout: '' }),
+ existsSync: (candidate) => {
+ candidates.push(candidate);
+ return false;
+ },
+ }),
+ null,
+ );
+ assert.deepEqual(candidates, [
+ path.win32.join('C:\\Program Files', 'Git', 'bin', 'sh.exe'),
+ path.win32.join('C:\\Program Files (x86)', 'Git', 'bin', 'sh.exe'),
+ ]);
+ assert.ok(candidates.every((candidate) => path.win32.isAbsolute(candidate)));
});
// --- 端到端:真 git 仓库 ---
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index e4125af829..406cc6b327 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { EventEmitter } from "node:events";
import test from "node:test";
import { fileURLToPath } from "node:url";
import manifest from "../test-workspaces.config.mjs";
@@ -10,6 +11,7 @@ import {
checkIncludeCoverage,
checkTestFiles,
classifyFailure,
+ createOutputForwarder,
discoverTestFiles,
expandWorkspacePatterns,
filterRunsByWorkspace,
@@ -20,6 +22,7 @@ import {
planRuns,
printSummary,
resolvePnpmInvocation,
+ resolveOutputStream,
runCommand,
runPlannedTests,
selectFilesForTier,
@@ -675,6 +678,44 @@ test("runCommand resolves spawn errors as failed command results", async () => {
assert.match(result.output, /ENOENT|not found|找不到|无法|spawn/i);
});
+test("createOutputForwarder stops writing after EPIPE without treating it as a command failure", () => {
+ class FakeStream extends EventEmitter {
+ writes = [];
+ write(chunk) {
+ this.writes.push(chunk.toString());
+ }
+ }
+ const stream = new FakeStream();
+ const forwarder = createOutputForwarder(stream);
+ forwarder.write(Buffer.from("before"));
+ stream.emit("error", Object.assign(new Error("broken pipe"), { code: "EPIPE" }));
+ assert.doesNotThrow(() => forwarder.write(Buffer.from("after")));
+ assert.deepEqual(stream.writes, ["before"]);
+ assert.equal(forwarder.finish(), null);
+});
+
+test("resolveOutputStream preserves explicit null while defaulting undefined", () => {
+ const fallback = new EventEmitter();
+ assert.equal(resolveOutputStream(undefined, fallback), fallback);
+ assert.equal(resolveOutputStream(null, fallback), null);
+});
+
+test("runCommand completes successfully when its output consumer closes with EPIPE", async () => {
+ class ClosedStream extends EventEmitter {
+ write() {}
+ }
+ const stream = new ClosedStream();
+ const pending = runCommand(
+ process.execPath,
+ ["-e", "setTimeout(() => process.stdout.write('child-finished'), 20)"],
+ { shell: false, stdout: stream, stderr: stream },
+ );
+ stream.emit("error", Object.assign(new Error("broken pipe"), { code: "EPIPE" }));
+ const result = await pending;
+ assert.equal(result.exitCode, 0);
+ assert.match(result.output, /child-finished/);
+});
+
test("runPlannedTests skips test command when preflight fails", async () => {
const calls = [];
const manifest = {
diff --git a/scripts/lib/posix-shell.mjs b/scripts/lib/posix-shell.mjs
new file mode 100644
index 0000000000..92a7c61d7f
--- /dev/null
+++ b/scripts/lib/posix-shell.mjs
@@ -0,0 +1,47 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { spawnSync } from 'node:child_process';
+
+/**
+ * Locate a shell bundled with Git for Windows without falling back to the WSL
+ * launcher in System32. Non-Windows callers keep using their normal PATH.
+ */
+export function resolvePosixShell(
+ shellName,
+ {
+ platform = process.platform,
+ env = process.env,
+ spawnSyncImpl = spawnSync,
+ existsSync = fs.existsSync,
+ } = {},
+) {
+ if (platform !== 'win32') return shellName;
+
+ const winPath = path.win32;
+ const executable = `${shellName}.exe`;
+ const candidates = [];
+ const absoluteEnvDir = (value, fallback = null) => {
+ const normalized = typeof value === 'string' ? value.trim() : '';
+ return normalized && winPath.isAbsolute(normalized) ? normalized : fallback;
+ };
+ const probe = spawnSyncImpl('where.exe', ['git.exe'], { encoding: 'utf8' });
+ if (probe.status === 0 && typeof probe.stdout === 'string') {
+ for (const line of probe.stdout.split(/\r?\n/)) {
+ const gitExe = line.trim();
+ if (!gitExe) continue;
+ candidates.push(winPath.join(winPath.dirname(winPath.dirname(gitExe)), 'bin', executable));
+ }
+ }
+
+ const programFiles = absoluteEnvDir(env.ProgramFiles, 'C:\\Program Files');
+ const programFilesX86 = absoluteEnvDir(env['ProgramFiles(x86)'], 'C:\\Program Files (x86)');
+ const localAppData = absoluteEnvDir(env.LOCALAPPDATA);
+ candidates.push(
+ winPath.join(programFiles, 'Git', 'bin', executable),
+ winPath.join(programFilesX86, 'Git', 'bin', executable),
+ );
+ if (localAppData) {
+ candidates.push(winPath.join(localAppData, 'Programs', 'Git', 'bin', executable));
+ }
+ return candidates.find((candidate) => candidate && existsSync(candidate)) ?? null;
+}
diff --git a/scripts/run-bash.mjs b/scripts/run-bash.mjs
index 990d8e6211..762360a714 100644
--- a/scripts/run-bash.mjs
+++ b/scripts/run-bash.mjs
@@ -10,47 +10,21 @@
*
* 用法:node scripts/run-bash.mjs <script.sh> [args...](cwd 即脚本所在包目录)
*/
-import fs from 'node:fs';
-import path from 'node:path';
import { spawnSync } from 'node:child_process';
+import { resolvePosixShell } from './lib/posix-shell.mjs';
const err = (msg) => console.error(`\x1b[31m[run-bash]\x1b[0m ${msg}`);
-/** 在 Windows 上定位 Git Bash 的 bash.exe(绝不回退到 System32 的 WSL bash) */
-function findGitBashWin() {
- // 1. 从 PATH 里的 git.exe 反推安装目录(git 在 <root>/cmd/git.exe,bash 在 <root>/bin/bash.exe)
- const probe = spawnSync('where', ['git.exe'], { encoding: 'utf8' });
- if (probe.status === 0) {
- for (const line of probe.stdout.split(/\r?\n/)) {
- const gitExe = line.trim();
- if (!gitExe) continue;
- const root = path.dirname(path.dirname(gitExe));
- const candidate = path.join(root, 'bin', 'bash.exe');
- if (fs.existsSync(candidate)) return candidate;
- }
- }
- // 2. 常见安装位置兜底
- const candidates = [
- path.join(process.env.ProgramFiles ?? 'C:\\Program Files', 'Git', 'bin', 'bash.exe'),
- path.join(process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)', 'Git', 'bin', 'bash.exe'),
- path.join(process.env.LOCALAPPDATA ?? '', 'Programs', 'Git', 'bin', 'bash.exe'),
- ];
- return candidates.find((c) => c && fs.existsSync(c)) ?? null;
-}
-
const [, , script, ...args] = process.argv;
if (!script) {
err('usage: node scripts/run-bash.mjs <script.sh> [args...]');
process.exit(1);
}
-let bash = 'bash';
-if (process.platform === 'win32') {
- bash = findGitBashWin();
- if (!bash) {
- err('未找到 Git Bash(bin\\bash.exe)。请安装 Git for Windows: https://git-scm.com/download/win');
- process.exit(1);
- }
+const bash = resolvePosixShell('bash');
+if (!bash) {
+ err('未找到 Git Bash(bin\\bash.exe)。请安装 Git for Windows: https://git-scm.com/download/win');
+ process.exit(1);
}
const result = spawnSync(bash, [script, ...args], { stdio: 'inherit' });
diff --git a/scripts/test-workspaces.mjs b/scripts/test-workspaces.mjs
index 0afe857917..487497cc49 100644
--- a/scripts/test-workspaces.mjs
+++ b/scripts/test-workspaces.mjs
@@ -442,6 +442,34 @@ export function buildPreflightArgs(root, workspace, preflight) {
throw new Error(`Unsupported preflight type: ${preflight.type}`);
}
+export function createOutputForwarder(stream) {
+ let writable = Boolean(stream);
+ let unexpectedError = null;
+ const onError = (error) => {
+ writable = false;
+ if (error?.code !== "EPIPE") unexpectedError = error;
+ };
+ stream?.on?.("error", onError);
+ return {
+ write(chunk) {
+ if (!writable) return;
+ try {
+ stream.write(chunk);
+ } catch (error) {
+ onError(error);
+ }
+ },
+ finish() {
+ stream?.off?.("error", onError);
+ return unexpectedError;
+ },
+ };
+}
+
+export function resolveOutputStream(configured, fallback) {
+ return configured === undefined ? fallback : configured;
+}
+
export function runCommand(command, args, options = {}) {
return new Promise((resolve) => {
const child = spawn(command, args, {
@@ -451,27 +479,37 @@ export function runCommand(command, args, options = {}) {
});
let output = "";
let settled = false;
+ const stdout = createOutputForwarder(resolveOutputStream(options.stdout, process.stdout));
+ const stderr = createOutputForwarder(resolveOutputStream(options.stderr, process.stderr));
const finish = (result) => {
if (settled) return;
settled = true;
- resolve(result);
+ const stdoutError = stdout.finish();
+ const stderrError = stderr.finish();
+ const forwardingError = stdoutError ?? stderrError;
+ if (forwardingError) {
+ output += `\nOutput forwarding failed: ${forwardingError.message ?? String(forwardingError)}`;
+ resolve({ exitCode: 1, output });
+ return;
+ }
+ resolve({ ...result, output });
};
child.stdout?.on("data", (chunk) => {
const text = chunk.toString();
output += text;
- process.stdout.write(chunk);
+ stdout.write(chunk);
});
child.stderr?.on("data", (chunk) => {
const text = chunk.toString();
output += text;
- process.stderr.write(chunk);
+ stderr.write(chunk);
});
child.on("error", (error) => {
output += error.message;
- finish({ exitCode: 1, output });
+ finish({ exitCode: 1 });
});
child.on("close", (code) => {
- finish({ exitCode: code ?? 1, output });
+ finish({ exitCode: code ?? 1 });
});
});
}
@@ -650,6 +688,14 @@ async function main() {
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ // A supervising terminal/tool may close its output pipe while the workspace
+ // child keeps running. Keep later summary writes from crashing on EPIPE;
+ // unexpected stream failures remain fatal.
+ for (const stream of [process.stdout, process.stderr]) {
+ stream.on("error", (error) => {
+ if (error?.code !== "EPIPE") throw error;
+ });
+ }
main().catch((error) => {
console.error(error);
process.exitCode = 1;