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。

perf(test): 优化单测并行与 Desktop worker 配置 (#543)

DavidShenXDcd1aee1f100a
diff --git a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
index ef3c21ef5c..83f1793ab4 100644
--- a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
@@ -11,11 +11,11 @@ import { describe, expect, it } from 'vitest';
const sidebarSource = readFileSync(
resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),
'utf8',
-);
+).replace(/\r\n?/g, '\n');
const filterHookSource = readFileSync(
resolve(__dirname, '..', 'features', 'cc-agent', 'hooks', 'useSidebarFilter.ts'),
'utf8',
-);
+).replace(/\r\n?/g, '\n');
describe('pinned project sidebar integration', () => {
it('keeps pinned projects out of expanded Projects but available in the collapsed rail', () => {
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index a88f7a4f33..33e945d997 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -102,6 +102,9 @@ pnpm test:unit
- 改 TypeScript 至少运行相关类型检查和定向测试。
- 跨模块、共享 package、构建链或广泛重构再扩大到 Desktop 全量测试、构建或根级单测。
+- 调整 Desktop Vitest worker 或测试分池前,先读取
+ [`desktop-unit-test-performance.md`](desktop-unit-test-performance.md),并用其中的
+ benchmark 在相同测试范围下做前后对比。
- 数据库 migration、协议、更新器、权限与用户数据另有高风险专项规则;命中时先读取
对应规则,不以本页命令替代专项验证。
- 记录实际执行和结果;未执行的高相关检查必须说明原因。
diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.md
new file mode 100644
index 0000000000..e24eca473d
--- /dev/null
+++ b/docs/dev-rules/desktop-unit-test-performance.md
@@ -0,0 +1,87 @@
+# Desktop 单测性能基准
+
+> **读取时机**:调整 Desktop Vitest worker、测试分池或根级单测资源配额前
+
+## 可复现命令
+
+`benchmark:desktop-workers` 复用 `test-workspaces.config.mjs` 中 Desktop unit tier 的
+完整排除规则,不会混入 DB、migration、guard 或 `*.bench.ts`。
+
+```bash
+pnpm benchmark:desktop-workers -- --workers 1,2,4,8 --runs 1 --output <report.json>
+```
+
+报告包含机器信息、墙钟、文件数、测试数、文件耗时 P50/P95/P99 和最慢文件。调整 worker
+或分池前后必须使用同一 checkout、同一机器和同一测试范围比较;单次数据需同时保留稳定性
+结果,不得只挑最快的一次。
+
+## 2026-07-26 Windows 基线
+
+环境:Windows x64、Node v24.15.0、32 available CPUs、63.8 GiB RAM。测试范围为
+1,213 个文件、13,062 个测试。
+
+| Workers | 结果 | 墙钟 | 相比上一档 | 相比 1 worker |
+|---:|---|---:|---:|---:|
+| 1 | 通过 | 710.6s | — | 1.00x |
+| 2 | 通过 | 353.7s | -50.2% | 2.01x |
+| 4 | 通过 | 183.5s | -48.1% | 3.87x |
+| 8 | 通过 | 108.3s | -41.0% | 6.56x |
+
+8-worker 复跑为 114.9s,说明该档在本机约为 108–115s。2-worker 首次运行曾在 116.7s
+触发一次 `ERR_IPC_CHANNEL_CLOSED`,重跑 353.7s 通过;worker 数降低本身不能消除
+Vitest/tinypool fork 通道的偶发退出问题。
+
+随着 workers 增加,所有文件自身耗时之和从 247.0s(1 worker)升至 317.5s(8
+workers),说明存在资源争用;但墙钟仍持续下降。综合速度、资源和实现复杂度,正式配置
+采用单池最多 8 workers;低于 8 CPU 的主机按 `os.availableParallelism()` 自动下调。
+
+## 长尾分布
+
+8-worker 复跑中,最慢 200 个文件按路径聚合:
+
+| 路径 | 文件数 | 文件耗时之和 |
+|---|---:|---:|
+| `src/main/git-review/**` | 10 | 180.7s |
+| `src/main/__tests__/**` | 27 | 49.7s |
+| `src/renderer/**` | 92 | 31.8s |
+| `src/main/hook-control/**` | 1 | 11.9s |
+
+最慢的单文件主要是创建真实 Git 仓库或子进程的测试:
+
+| 文件 | 8-worker 文件耗时 |
+|---|---:|
+| `git-review/__tests__/stageOps.test.ts` | 42.1s |
+| `git-review/__tests__/pushOps.test.ts` | 28.6s |
+| `git-review/__tests__/branchReader.test.ts` | 23.8s |
+| `main/__tests__/codexFileRewindExecutor.test.ts` | 23.4s |
+| `git-review/__tests__/ipc.test.ts` | 22.0s |
+| `git-review/__tests__/diffReader.test.ts` | 19.5s |
+
+因此分池优先按“真实 Git/子进程长尾”和“其余测试”隔离,而不是只按 node/jsdom 环境
+机械拆分。
+
+## 分池评估
+
+分池把 21 个 Git/子进程长尾文件放入 `git-io`,其余文件放入 `standard`;两个池并发,
+且完整覆盖仍为 1,213 个文件、13,062 个测试。
+
+| 配置 | 结果 | 总墙钟 | 说明 |
+|---|---|---:|---|
+| 单池 8 forks | 通过 | 108.3–114.9s | PR3 单池基线 |
+| 3 forks + 5 forks | 通过 | 126.9s | standard 池成为长板 |
+| 2 forks + 6 forks | 通过 | 111.6s | 与单池持平 |
+| 2 threads + 6 forks | 通过 | 114.8s | standard 使用 threads 无收益 |
+| 2 threads + 7 forks | 通过 | 111.1s | git-io 成为长板 |
+| 3 threads + 7 forks | 连续两次通过 | 102.2–103.0s | 最快分池候选 |
+
+另一次 `2 forks + 7 forks` 中,standard 池在 100.6s 完成,但 git-io 池触发
+`ERR_IPC_CHANNEL_CLOSED`,因此不作为有效性能样本。
+
+最快分池候选的平均墙钟为 102.6s:
+
+- 相比现有单池 4 workers 的 183.5s,减少 80.9s(44.1%)。
+- 相比单池 8 workers 的平均 111.6s,减少 9.0s(8.1%)。
+- 但 worker 上限会从 8 提高到两池合计 10,并引入分区维护和双执行器复杂度。
+
+因此分池相对单池 8 workers 的额外 8.1% 收益不足以抵消资源与维护成本,正式配置不采用
+分池,保留单池最多 8 workers。
diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.md
index 40d092830f..e93f246fa4 100644
--- a/docs/dev-rules/development-workflow.md
+++ b/docs/dev-rules/development-workflow.md
@@ -66,11 +66,19 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径
宿主删除/归档会话时自动存的内容快照(见第 1 节),以及会话必须收尾、测试却来不及
修好时的收尾 commit——后者 commit message 必须标注 `WIP`,且在门禁通过前不得
push、不得提 PR。
- - **完整单测的外层超时**:`pnpm test:unit` 是全仓串行门禁,正常执行可能超过数分钟。
+ - **完整单测的外层超时**:`pnpm test:unit` 是全仓完整门禁,正常执行可能超过数分钟。
调用它的 agent/自动化工具不得使用 120 秒或更短的绝对超时;未知当前耗时时,外层
兜底超时至少设为 15 分钟。工具支持后台运行或 yielded process handle 时优先使用该
模式并短轮询进度,不要因为调用端停止等待就误判失败、杀掉仍在正常运行的测试或重复
启动一轮。Vitest 的单测试例超时仍由各 package 配置控制,不受这条外层约束影响。
+ - **workspace 有界并行**:`test-workspaces.mjs` 默认最多并行
+ `min(4, os.availableParallelism())` 个普通 workspace;每个普通 Vitest workspace 只使用
+ 1 个 worker。Mobile 使用完整的 4-worker 配额;Desktop 使用基准验证过的单池最多
+ 8-worker 配额,低于 8 CPU 时按 `os.availableParallelism()` 自动下调。重型 workspace
+ 必须独占执行,避免外层并发与内部 worker 池相乘。
+ 排查并发相关问题时可用
+ `pnpm test:unit -- --workspace-concurrency=1` 临时退回 workspace 串行;该参数只改变
+ workspace 调度,不减少测试覆盖。
- **在门禁之上按风险追加验证**:跨模块、高风险或基础设施改动追加更广泛验证(如仓库根
`pnpm test:all`),**最终以 CI 门禁为准**。不得通过 skip、删除或弱化测试制造通过;
PR「怎么验证的」一节必须**如实**填写,没跑不许写已跑。
diff --git a/package.json b/package.json
index 14657452f9..eca03a83ed 100644
--- a/package.json
+++ b/package.json
@@ -95,6 +95,7 @@
"dev:desktop:inspect": "node scripts/ensure-deps.mjs && node scripts/ensure-dev-runtime-assets.mjs && pnpm --filter desktop dev:inspect",
"benchmark:voice-input": "node scripts/voice-input-benchmark.mjs",
"benchmark:browser": "node --import tsx scripts/browser-capability-benchmark.mjs",
+ "benchmark:desktop-workers": "node scripts/desktop-worker-benchmark.mjs",
"dev:embed:search": "node scripts/dev-embed-search.mjs",
"build": "node scripts/ensure-deps.mjs && pnpm --filter desktop build",
"release:package": "node scripts/ensure-deps.mjs && node apps/desktop/scripts/package-desktop.mjs",
@@ -110,7 +111,7 @@
"licenses:generate": "node scripts/generate-third-party-notices.mjs",
"lint": "pnpm -r lint",
"format": "pnpm -r format",
- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/glossary-rules.test.mjs",
+ "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/glossary-rules.test.mjs",
"test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit",
"test:all": "pnpm test:runner && node scripts/test-workspaces.mjs --all",
"test:db": "pnpm test:runner && node scripts/test-workspaces.mjs --tier db",
diff --git a/scripts/__tests__/desktop-worker-benchmark.test.mjs b/scripts/__tests__/desktop-worker-benchmark.test.mjs
new file mode 100644
index 0000000000..65a4da21a9
--- /dev/null
+++ b/scripts/__tests__/desktop-worker-benchmark.test.mjs
@@ -0,0 +1,149 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ desktopUnitBenchmarkPnpmArgs,
+ median,
+ parseDesktopWorkerBenchmarkOptions,
+ percentile,
+ removeBenchmarkOutputFile,
+ summarizeDesktopWorkerSamples,
+} from '../desktop-worker-benchmark.mjs';
+
+test('desktop worker benchmark parses bounded worker and output options', () => {
+ assert.deepEqual(
+ parseDesktopWorkerBenchmarkOptions([
+ '--',
+ '--workers=4, 1,4',
+ '--runs',
+ '2',
+ '--top=5',
+ '--output',
+ 'result.json',
+ ]),
+ {
+ workers: [4, 1],
+ runs: 2,
+ top: 5,
+ output: process.platform === 'win32'
+ ? `${process.cwd()}\\result.json`
+ : `${process.cwd()}/result.json`,
+ help: false,
+ },
+ );
+});
+
+test('desktop worker benchmark rejects invalid numeric options', () => {
+ for (const args of [
+ ['--workers=0'],
+ ['--workers=1,nope'],
+ ['--runs=1.5'],
+ ['--top', '-1'],
+ ]) {
+ assert.throws(
+ () => parseDesktopWorkerBenchmarkOptions(args),
+ /requires (a positive integer|a value)/,
+ );
+ }
+});
+
+test('desktop worker benchmark reuses the unit tier exclusions', () => {
+ const args = desktopUnitBenchmarkPnpmArgs(2, 'report.json');
+ assert.ok(args.includes('--maxWorkers=2'));
+ assert.ok(args.includes('--reporter=json'));
+ assert.ok(args.includes('--outputFile=report.json'));
+ assert.ok(args.includes('src/main/localDb/**'));
+ assert.ok(args.includes('**/*.bench.ts'));
+});
+
+test('percentile uses the nearest-rank value', () => {
+ assert.equal(percentile([], 0.95), 0);
+ assert.equal(percentile([40, 10, 30, 20], 0.5), 20);
+ assert.equal(percentile([40, 10, 30, 20], 0.95), 40);
+});
+
+test('median averages the two middle values for even-sized samples', () => {
+ assert.equal(median([]), 0);
+ assert.equal(median([30, 10, 20]), 20);
+ assert.equal(median([40, 10, 30, 20]), 25);
+});
+
+test('desktop worker benchmark summarizes median wall time and speedup', () => {
+ assert.deepEqual(
+ summarizeDesktopWorkerSamples([
+ { workers: 1, wallMs: 100 },
+ { workers: 1, wallMs: 120 },
+ { workers: 2, wallMs: 60 },
+ { workers: 2, wallMs: 70 },
+ ]),
+ [
+ {
+ workers: 1,
+ runs: 2,
+ passed: 2,
+ failed: 0,
+ medianWallMs: 110,
+ minWallMs: 100,
+ maxWallMs: 120,
+ speedupVsOneWorker: 1,
+ },
+ {
+ workers: 2,
+ runs: 2,
+ passed: 2,
+ failed: 0,
+ medianWallMs: 65,
+ minWallMs: 60,
+ maxWallMs: 70,
+ speedupVsOneWorker: 110 / 65,
+ },
+ ],
+ );
+});
+
+test('desktop worker benchmark keeps failed configurations in the summary', () => {
+ assert.deepEqual(
+ summarizeDesktopWorkerSamples([
+ { workers: 2, success: false, wallMs: 100 },
+ { workers: 4, success: true, wallMs: 80 },
+ ]),
+ [
+ {
+ workers: 2,
+ runs: 1,
+ passed: 0,
+ failed: 1,
+ medianWallMs: null,
+ minWallMs: null,
+ maxWallMs: null,
+ speedupVsOneWorker: null,
+ },
+ {
+ workers: 4,
+ runs: 1,
+ passed: 1,
+ failed: 0,
+ medianWallMs: 80,
+ minWallMs: 80,
+ maxWallMs: 80,
+ speedupVsOneWorker: null,
+ },
+ ],
+ );
+});
+
+test('benchmark cleanup never masks the benchmark result', () => {
+ const warnings = [];
+ assert.equal(
+ removeBenchmarkOutputFile('locked-report.json', {
+ remove: () => {
+ throw Object.assign(new Error('file is busy'), { code: 'EBUSY' });
+ },
+ warn: (message) => warnings.push(message),
+ }),
+ false,
+ );
+ assert.deepEqual(warnings, [
+ 'Warning: could not remove benchmark report locked-report.json: file is busy',
+ ]);
+});
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index 356839be9f..161f26ddc4 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -5,19 +5,26 @@ 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";
+import manifest, {
+ desktopUnitWorkerCount,
+} from "../test-workspaces.config.mjs";
import {
buildPnpmArgs,
checkIncludeCoverage,
checkTestFiles,
classifyFailure,
+ createBoundedOutputBuffer,
createOutputForwarder,
+ createWorkspaceRunReporter,
+ defaultWorkspaceConcurrency,
discoverTestFiles,
expandWorkspacePatterns,
filterRunsByWorkspace,
+ mapWithConcurrency,
normalizeRelPath,
parseWorkspacePatterns,
parseCliOptions,
+ parseWorkspaceConcurrency,
parseWorkspaceSelectorValue,
planRuns,
printSummary,
@@ -25,6 +32,7 @@ import {
resolveOutputStream,
runCommand,
runPlannedTests,
+ runWithExclusiveBarriers,
selectFilesForTier,
validateManifest,
validateManifestCoverage,
@@ -41,6 +49,14 @@ function readWorkspacePackageJson(cwd) {
return JSON.parse(fs.readFileSync(path.join(ROOT, cwd, "package.json"), "utf8"));
}
+async function waitFor(predicate, message = "condition was not reached") {
+ for (let attempt = 0; attempt < 100; attempt += 1) {
+ if (predicate()) return;
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ throw new Error(message);
+}
+
test("parseWorkspacePatterns reads pnpm-workspace.yaml package globs", () => {
assert.deepEqual(
parseWorkspacePatterns('packages:\n - "apps/*"\n - "packages/*"\n'),
@@ -106,8 +122,38 @@ test("orca workflow unit tier uses its own declared test runner", () => {
assert.equal(orcaPackage.scripts.test, "vitest run");
assert.equal(orcaPackage.devDependencies.vitest, "^3.2.4");
assert.deepEqual(orcaWorkspace.tiers.unit.command, {
- type: "packageScript",
- script: "test",
+ type: "packageBin",
+ bin: "vitest",
+ args: ["run", "--maxWorkers=1"],
+ });
+});
+
+test("unit workspace concurrency reserves the full worker budget for heavy workspaces", () => {
+ const desktop = manifest.workspaces.find(
+ (workspace) => workspace.cwd === "apps/desktop",
+ );
+ const mobile = manifest.workspaces.find(
+ (workspace) => workspace.cwd === "apps/mobile",
+ );
+ const makerCore = manifest.workspaces.find(
+ (workspace) => workspace.cwd === "packages/maker-core",
+ );
+ assert.equal(desktop.tiers.unit.execution, "exclusive");
+ assert.deepEqual(desktop.tiers.unit.command.args, [
+ "run",
+ `--maxWorkers=${desktopUnitWorkerCount()}`,
+ ]);
+ assert.equal(desktopUnitWorkerCount(1), 1);
+ assert.equal(desktopUnitWorkerCount(4), 4);
+ assert.equal(desktopUnitWorkerCount(32), 8);
+ assert.equal(desktopUnitWorkerCount(Number.NaN), 1);
+ assert.equal(mobile.tiers.unit.execution, "exclusive");
+ assert.deepEqual(mobile.tiers.unit.command.args, ["run", "--maxWorkers=4"]);
+ assert.equal(makerCore.tiers.unit.execution, undefined);
+ assert.deepEqual(makerCore.tiers.unit.command, {
+ type: "packageBin",
+ bin: "vitest",
+ args: ["run", "--maxWorkers=1"],
});
});
@@ -375,6 +421,23 @@ test("validateManifest rejects invalid status and missing reason", () => {
]),
/requires command/,
);
+ assert.throws(
+ () =>
+ validateManifest([
+ {
+ cwd: "x",
+ status: "required",
+ tiers: {
+ unit: {
+ status: "required",
+ command: { type: "packageScript", script: "test" },
+ execution: "parallel-ish",
+ },
+ },
+ },
+ ]),
+ /invalid execution mode/,
+ );
assert.throws(
() =>
validateManifest([
@@ -555,6 +618,7 @@ test("parseCliOptions rejects --tier without a value", () => {
tier: "unit",
workspaces: [],
excludeWorkspaces: [],
+ workspaceConcurrency: undefined,
});
});
@@ -575,6 +639,7 @@ test("parseCliOptions supports workspace include and exclude selectors", () => {
tier: "unit",
workspaces: ["desktop", "apps/server", "@cindy/maker-core"],
excludeWorkspaces: ["packages/orca-workflow"],
+ workspaceConcurrency: undefined,
},
);
assert.deepEqual(parseWorkspaceSelectorValue(" desktop, apps/server "), [
@@ -587,6 +652,32 @@ test("parseCliOptions supports workspace include and exclude selectors", () => {
);
});
+test("workspace concurrency defaults to a bounded CPU count and accepts both CLI forms", () => {
+ assert.equal(defaultWorkspaceConcurrency(1), 1);
+ assert.equal(defaultWorkspaceConcurrency(2), 2);
+ assert.equal(defaultWorkspaceConcurrency(32), 4);
+ assert.equal(defaultWorkspaceConcurrency(Number.NaN), 1);
+ assert.equal(parseWorkspaceConcurrency("8"), 8);
+ assert.equal(
+ parseCliOptions(["--workspace-concurrency", "3"]).workspaceConcurrency,
+ 3,
+ );
+ assert.equal(
+ parseCliOptions(["--", "--workspace-concurrency=2"]).workspaceConcurrency,
+ 2,
+ );
+ for (const value of ["0", "-1", "1.5", "nope", "999999999999999999999"]) {
+ assert.throws(
+ () => parseWorkspaceConcurrency(value),
+ /requires a positive integer/,
+ );
+ }
+ assert.throws(
+ () => parseCliOptions(["--workspace-concurrency"]),
+ /requires a positive integer/,
+ );
+});
+
test("resolvePnpmInvocation uses current pnpm through node when npm_execpath is present on any platform", () => {
assert.deepEqual(
resolvePnpmInvocation(["--dir", "apps/server", "run", "test"], {
@@ -701,6 +792,35 @@ test("resolveOutputStream preserves explicit null while defaulting undefined", (
assert.equal(resolveOutputStream(null, fallback), null);
});
+test("createBoundedOutputBuffer keeps bounded head and tail diagnostics", () => {
+ const output = createBoundedOutputBuffer(20);
+ output.append("0123456789");
+ output.append("abcdefghij");
+ output.append("KLMNOPQRST");
+ assert.equal(
+ output.toString(),
+ "01234\n... 10 output characters omitted ...\nfghijKLMNOPQRST",
+ );
+});
+
+test("runCommand bounds captured output while retaining head and tail", async () => {
+ const result = await runCommand(
+ process.execPath,
+ ["-e", "process.stdout.write(`HEAD${'x'.repeat(100)}TAIL`)"],
+ {
+ shell: false,
+ stdout: null,
+ stderr: null,
+ maxOutputChars: 20,
+ },
+ );
+ assert.equal(result.exitCode, 0);
+ assert.match(result.output, /^HEAD/);
+ assert.match(result.output, /output characters omitted/);
+ assert.match(result.output, /TAIL$/);
+ assert.ok(result.output.length < 100);
+});
+
test("runCommand completes successfully when its output consumer closes with EPIPE", async () => {
class ClosedStream extends EventEmitter {
write() {}
@@ -717,6 +837,102 @@ test("runCommand completes successfully when its output consumer closes with EPI
assert.match(result.output, /child-finished/);
});
+test("mapWithConcurrency stays within the bound, remains work-conserving, and preserves result order", async () => {
+ const releases = [];
+ const started = [];
+ let active = 0;
+ let maxActive = 0;
+ const pending = mapWithConcurrency(["a", "b", "c"], 2, async (item) => {
+ started.push(item);
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ await new Promise((resolve) => releases.push(resolve));
+ active -= 1;
+ return item.toUpperCase();
+ });
+
+ await waitFor(() => started.length === 2);
+ assert.deepEqual(started, ["a", "b"]);
+ assert.equal(active, 2);
+ releases.shift()();
+ await waitFor(() => started.length === 3);
+ assert.deepEqual(started, ["a", "b", "c"]);
+ assert.equal(active, 2, "the freed slot should be reused immediately");
+ for (const release of releases.splice(0)) release();
+
+ assert.deepEqual(await pending, ["A", "B", "C"]);
+ assert.equal(maxActive, 2);
+});
+
+test("runWithExclusiveBarriers never overlaps exclusive and normal work", async () => {
+ const runs = [
+ { id: "a", tierConfig: {} },
+ { id: "b", tierConfig: {} },
+ { id: "desktop", tierConfig: { execution: "exclusive" } },
+ { id: "c", tierConfig: {} },
+ ];
+ let normalActive = 0;
+ let exclusiveActive = false;
+ let maxNormalActive = 0;
+ const started = [];
+ const results = await runWithExclusiveBarriers(runs, 2, async (run) => {
+ started.push(run.id);
+ if (run.tierConfig.execution === "exclusive") {
+ assert.equal(normalActive, 0);
+ assert.equal(exclusiveActive, false);
+ exclusiveActive = true;
+ } else {
+ assert.equal(exclusiveActive, false);
+ normalActive += 1;
+ maxNormalActive = Math.max(maxNormalActive, normalActive);
+ }
+ await new Promise((resolve) => setImmediate(resolve));
+ if (run.tierConfig.execution === "exclusive") exclusiveActive = false;
+ else normalActive -= 1;
+ return run.id;
+ });
+
+ assert.deepEqual(started, ["a", "b", "desktop", "c"]);
+ assert.deepEqual(results, ["a", "b", "desktop", "c"]);
+ assert.equal(maxNormalActive, 2);
+});
+
+test("createWorkspaceRunReporter keeps passing output concise and flushes failed output as one block", () => {
+ let timestamp = 1_000;
+ const writes = [];
+ const reporter = createWorkspaceRunReporter({
+ stdout: { write: (chunk) => writes.push(String(chunk)) },
+ now: () => timestamp,
+ });
+ const run = {
+ workspace: { cwd: "packages/a" },
+ tier: "unit",
+ };
+ reporter.onRunStart(run);
+ reporter.onCommandComplete({
+ run,
+ stage: "test",
+ commandResult: { output: "passing output", exitCode: 0 },
+ });
+ reporter.onCommandComplete({
+ run,
+ stage: "test",
+ commandResult: { output: "failed output", exitCode: 1 },
+ });
+ timestamp = 2_250;
+ reporter.onRunComplete(run, {
+ exitCode: 1,
+ failure: "COMMAND_FAILED",
+ durationMs: 1_500,
+ });
+ assert.equal(
+ writes.join(""),
+ "START packages/a unit\n" +
+ "\n[packages/a unit test]\nfailed output\n" +
+ "FAIL COMMAND_FAILED packages/a unit (1.5s)\n",
+ );
+});
+
test("runPlannedTests skips test command when preflight fails", async () => {
const calls = [];
const manifest = {
@@ -875,6 +1091,96 @@ test("runPlannedTests continues after one workspace test fails", async () => {
assert.equal(result[1].exitCode, 0);
});
+test("runPlannedTests applies bounded concurrency while keeping results in manifest order", async () => {
+ const workspaces = ["a", "b", "c"].map((name) => ({
+ name,
+ cwd: `packages/${name}`,
+ status: "required",
+ tiers: {
+ unit: {
+ status: "required",
+ command: { type: "packageBin", bin: "vitest", args: ["run"] },
+ },
+ },
+ }));
+ const delays = new Map([
+ ["packages/a", 20],
+ ["packages/b", 1],
+ ["packages/c", 5],
+ ]);
+ let active = 0;
+ let maxActive = 0;
+ const result = await runPlannedTests({
+ root: "F:/repo",
+ workspaceCwds: workspaces.map((workspace) => workspace.cwd),
+ allFiles: workspaces.map(
+ (workspace) => `${workspace.cwd}/src/example.test.ts`,
+ ),
+ manifest: { workspaces },
+ tier: "unit",
+ workspaceConcurrency: 2,
+ runCommandImpl: async (_command, _args, options) => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ const workspace = normalizeRelPath(options.cwd).replace("F:/repo/", "");
+ await new Promise((resolve) => setTimeout(resolve, delays.get(workspace)));
+ active -= 1;
+ return { exitCode: 0, output: workspace };
+ },
+ });
+
+ assert.equal(maxActive, 2);
+ assert.deepEqual(
+ result.map((entry) => entry.workspace),
+ ["packages/a", "packages/b", "packages/c"],
+ );
+});
+
+test("runPlannedTests treats an exclusive workspace as a concurrency barrier", async () => {
+ const workspaces = [
+ { name: "a", cwd: "packages/a", execution: undefined },
+ { name: "desktop", cwd: "apps/desktop", execution: "exclusive" },
+ { name: "b", cwd: "packages/b", execution: undefined },
+ ].map(({ name, cwd, execution }) => ({
+ name,
+ cwd,
+ status: "required",
+ tiers: {
+ unit: {
+ status: "required",
+ command: { type: "packageBin", bin: "vitest", args: ["run"] },
+ ...(execution ? { execution } : {}),
+ },
+ },
+ }));
+ let normalActive = 0;
+ let desktopActive = false;
+ await runPlannedTests({
+ root: "F:/repo",
+ workspaceCwds: workspaces.map((workspace) => workspace.cwd),
+ allFiles: workspaces.map(
+ (workspace) => `${workspace.cwd}/src/example.test.ts`,
+ ),
+ manifest: { workspaces },
+ tier: "unit",
+ workspaceConcurrency: 2,
+ runCommandImpl: async (_command, _args, options) => {
+ const workspace = normalizeRelPath(options.cwd).replace("F:/repo/", "");
+ if (workspace === "apps/desktop") {
+ assert.equal(normalActive, 0);
+ desktopActive = true;
+ } else {
+ assert.equal(desktopActive, false);
+ normalActive += 1;
+ }
+ await new Promise((resolve) => setImmediate(resolve));
+ if (workspace === "apps/desktop") desktopActive = false;
+ else normalActive -= 1;
+ return { exitCode: 0, output: workspace };
+ },
+ });
+});
+
test("runPlannedTests passes selected include files to packageBin commands", async () => {
const calls = [];
const manifest = {
diff --git a/scripts/desktop-worker-benchmark.mjs b/scripts/desktop-worker-benchmark.mjs
new file mode 100644
index 0000000000..4be224f7fe
--- /dev/null
+++ b/scripts/desktop-worker-benchmark.mjs
@@ -0,0 +1,350 @@
+#!/usr/bin/env node
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { performance } from 'node:perf_hooks';
+import { fileURLToPath } from 'node:url';
+
+import manifest from './test-workspaces.config.mjs';
+import {
+ buildPnpmArgs,
+ normalizeRelPath,
+ resolvePnpmInvocation,
+ runCommand,
+} from './test-workspaces.mjs';
+
+const ROOT = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
+const DEFAULT_WORKERS = [1, 2, 4, 8];
+
+function positiveInteger(value, option) {
+ if (!/^[1-9]\d*$/.test(String(value))) {
+ throw new Error(`${option} requires a positive integer`);
+ }
+ const parsed = Number(value);
+ if (!Number.isSafeInteger(parsed)) {
+ throw new Error(`${option} requires a positive integer`);
+ }
+ return parsed;
+}
+
+function readOptionValue(args, index, option) {
+ const arg = args[index];
+ const prefix = `${option}=`;
+ if (arg.startsWith(prefix)) return { value: arg.slice(prefix.length), consumed: 0 };
+ const value = args[index + 1];
+ if (!value || value.startsWith('--')) throw new Error(`${option} requires a value`);
+ return { value, consumed: 1 };
+}
+
+export function parseDesktopWorkerBenchmarkOptions(args) {
+ const options = {
+ workers: DEFAULT_WORKERS,
+ runs: 1,
+ top: 10,
+ output: undefined,
+ help: false,
+ };
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+ if (arg === '--') continue;
+ if (arg === '--help' || arg === '-h') {
+ options.help = true;
+ continue;
+ }
+ if (arg === '--workers' || arg.startsWith('--workers=')) {
+ const { value, consumed } = readOptionValue(args, index, '--workers');
+ const workers = value
+ .split(',')
+ .map((item) => positiveInteger(item.trim(), '--workers'));
+ if (workers.length === 0) throw new Error('--workers requires at least one value');
+ options.workers = [...new Set(workers)];
+ index += consumed;
+ continue;
+ }
+ if (arg === '--runs' || arg.startsWith('--runs=')) {
+ const { value, consumed } = readOptionValue(args, index, '--runs');
+ options.runs = positiveInteger(value, '--runs');
+ index += consumed;
+ continue;
+ }
+ if (arg === '--top' || arg.startsWith('--top=')) {
+ const { value, consumed } = readOptionValue(args, index, '--top');
+ options.top = positiveInteger(value, '--top');
+ index += consumed;
+ continue;
+ }
+ if (arg === '--output' || arg.startsWith('--output=')) {
+ const { value, consumed } = readOptionValue(args, index, '--output');
+ options.output = path.resolve(value);
+ index += consumed;
+ continue;
+ }
+ throw new Error(`Unknown option: ${arg}`);
+ }
+ return options;
+}
+
+export function percentile(values, quantile) {
+ if (values.length === 0) return 0;
+ const sorted = [...values].sort((left, right) => left - right);
+ const index = Math.ceil(quantile * sorted.length) - 1;
+ return sorted[Math.max(0, Math.min(sorted.length - 1, index))];
+}
+
+export function median(values) {
+ if (values.length === 0) return 0;
+ const sorted = [...values].sort((left, right) => left - right);
+ const middle = Math.floor(sorted.length / 2);
+ return sorted.length % 2 === 0
+ ? (sorted[middle - 1] + sorted[middle]) / 2
+ : sorted[middle];
+}
+
+export function summarizeDesktopWorkerSamples(samples) {
+ const successfulSamples = samples.filter((sample) => sample.success !== false);
+ const baseline = successfulSamples.find((sample) => sample.workers === 1);
+ return [...new Set(samples.map((sample) => sample.workers))].map((workers) => {
+ const workerSamples = samples.filter((sample) => sample.workers === workers);
+ const successful = workerSamples.filter((sample) => sample.success !== false);
+ const wallValues = successful.map((sample) => sample.wallMs);
+ const medianWallMs = wallValues.length > 0 ? median(wallValues) : null;
+ return {
+ workers,
+ runs: workerSamples.length,
+ passed: successful.length,
+ failed: workerSamples.length - successful.length,
+ medianWallMs,
+ minWallMs: wallValues.length > 0 ? Math.min(...wallValues) : null,
+ maxWallMs: wallValues.length > 0 ? Math.max(...wallValues) : null,
+ speedupVsOneWorker:
+ baseline && medianWallMs !== null && medianWallMs > 0
+ ? median(
+ successfulSamples
+ .filter((sample) => sample.workers === 1)
+ .map((sample) => sample.wallMs),
+ ) / medianWallMs
+ : null,
+ };
+ });
+}
+
+export function desktopUnitBenchmarkPnpmArgs(workers, outputFile) {
+ const workspace = manifest.workspaces.find(({ cwd }) => cwd === 'apps/desktop');
+ const unit = workspace?.tiers?.unit;
+ const command = unit?.command;
+ if (!workspace || command?.type !== 'packageBin') {
+ throw new Error('Desktop unit tier must use a packageBin command');
+ }
+ const args = buildPnpmArgs(ROOT, workspace, command, unit, []).filter(
+ (arg) =>
+ !arg.startsWith('--maxWorkers=') &&
+ !arg.startsWith('--reporter=') &&
+ !arg.startsWith('--outputFile='),
+ );
+ args.push(
+ `--maxWorkers=${workers}`,
+ '--reporter=json',
+ `--outputFile=${outputFile}`,
+ );
+ return args;
+}
+
+function desktopUnitCommand(workers, outputFile) {
+ return {
+ cwd: path.join(ROOT, 'apps/desktop'),
+ pnpmArgs: desktopUnitBenchmarkPnpmArgs(workers, outputFile),
+ };
+}
+
+function roundMs(value) {
+ return Math.round(value * 10) / 10;
+}
+
+export function removeBenchmarkOutputFile(
+ outputFile,
+ { remove = fs.rmSync, warn = console.warn } = {},
+) {
+ try {
+ remove(outputFile, { force: true });
+ return true;
+ } catch (error) {
+ warn(
+ `Warning: could not remove benchmark report ${outputFile}: ` +
+ `${error?.message ?? String(error)}`,
+ );
+ return false;
+ }
+}
+
+async function runSample({ workers, iteration, top }) {
+ const outputFile = path.join(
+ os.tmpdir(),
+ `cindy-desktop-worker-benchmark-${process.pid}-${workers}-${iteration}.json`,
+ );
+ const { cwd, pnpmArgs } = desktopUnitCommand(workers, outputFile);
+ const invocation = resolvePnpmInvocation(pnpmArgs);
+ const startedAt = performance.now();
+ try {
+ const result = await runCommand(invocation.command, invocation.args, {
+ cwd,
+ shell: invocation.shell,
+ stdout: null,
+ stderr: null,
+ });
+ const wallMs = performance.now() - startedAt;
+ const report = fs.existsSync(outputFile)
+ ? JSON.parse(fs.readFileSync(outputFile, 'utf8'))
+ : null;
+ if (result.exitCode !== 0 || !report?.success) {
+ process.stderr.write(result.output);
+ const failedFiles = [];
+ for (const file of report?.testResults ?? []) {
+ if (file.status !== 'failed') continue;
+ const relativeFile = normalizeRelPath(path.relative(ROOT, file.name));
+ failedFiles.push(relativeFile);
+ process.stderr.write(`\nFAILED ${relativeFile}\n`);
+ for (const assertion of file.assertionResults ?? []) {
+ for (const message of assertion.failureMessages ?? []) {
+ process.stderr.write(`${message}\n`);
+ }
+ }
+ }
+ return {
+ workers,
+ iteration,
+ success: false,
+ exitCode: result.exitCode,
+ wallMs: roundMs(wallMs),
+ files: report?.testResults?.length ?? 0,
+ tests: report?.numTotalTests ?? 0,
+ failedFiles,
+ error: result.output.includes('ERR_IPC_CHANNEL_CLOSED')
+ ? 'ERR_IPC_CHANNEL_CLOSED'
+ : 'TEST_RUN_FAILED',
+ };
+ }
+ const files = report.testResults.map((file) => ({
+ file: normalizeRelPath(path.relative(ROOT, file.name)),
+ durationMs: roundMs(Math.max(0, file.endTime - file.startTime)),
+ }));
+ const fileDurations = files.map((file) => file.durationMs);
+ return {
+ workers,
+ iteration,
+ success: true,
+ exitCode: 0,
+ wallMs: roundMs(wallMs),
+ files: files.length,
+ tests: report.numTotalTests,
+ fileDurationMs: {
+ sum: roundMs(fileDurations.reduce((sum, value) => sum + value, 0)),
+ p50: roundMs(percentile(fileDurations, 0.5)),
+ p95: roundMs(percentile(fileDurations, 0.95)),
+ p99: roundMs(percentile(fileDurations, 0.99)),
+ max: roundMs(Math.max(...fileDurations)),
+ },
+ slowestFiles: files
+ .sort((left, right) => right.durationMs - left.durationMs)
+ .slice(0, top),
+ };
+ } finally {
+ removeBenchmarkOutputFile(outputFile);
+ }
+}
+
+function printUsage() {
+ console.log(`Desktop unit worker benchmark
+
+Usage:
+ pnpm benchmark:desktop-workers -- [options]
+
+Options:
+ --workers <list> Comma-separated worker counts. Default: 1,2,4,8
+ --runs <n> Repetitions per worker count. Default: 1
+ --top <n> Slowest files kept per sample. Default: 10
+ --output <path> Write the complete JSON report
+`);
+}
+
+function printSummary(report) {
+ console.log('\nDesktop unit worker benchmark\n');
+ console.log(
+ `Host: ${report.machine.platform}-${report.machine.arch}, Node ${report.machine.node}, ` +
+ `${report.machine.availableParallelism} available CPUs, ${report.machine.memoryGiB} GiB RAM`,
+ );
+ console.log('\nworkers pass/run median wall min max speedup vs 1');
+ for (const row of report.summary) {
+ const speedup =
+ row.speedupVsOneWorker === null ? '-' : `${row.speedupVsOneWorker.toFixed(2)}x`;
+ const formatSeconds = (value) =>
+ value === null ? '-'.padEnd(10) : (value / 1_000).toFixed(1).padEnd(10);
+ console.log(
+ `${String(row.workers).padEnd(9)}` +
+ `${`${row.passed}/${row.runs}`.padEnd(10)}` +
+ `${formatSeconds(row.medianWallMs).padEnd(13)}` +
+ `${formatSeconds(row.minWallMs)}` +
+ `${formatSeconds(row.maxWallMs)}` +
+ speedup,
+ );
+ }
+}
+
+async function main() {
+ const options = parseDesktopWorkerBenchmarkOptions(process.argv.slice(2));
+ if (options.help) {
+ printUsage();
+ return;
+ }
+ const samples = [];
+ for (const workers of options.workers) {
+ for (let iteration = 1; iteration <= options.runs; iteration += 1) {
+ console.log(`START workers=${workers} run=${iteration}/${options.runs}`);
+ const sample = await runSample({ workers, iteration, top: options.top });
+ samples.push(sample);
+ if (sample.success) {
+ console.log(
+ `PASS workers=${workers} run=${iteration}/${options.runs} ` +
+ `wall=${(sample.wallMs / 1_000).toFixed(1)}s`,
+ );
+ } else {
+ console.log(
+ `FAIL workers=${workers} run=${iteration}/${options.runs} ` +
+ `wall=${(sample.wallMs / 1_000).toFixed(1)}s error=${sample.error}`,
+ );
+ }
+ }
+ }
+ const report = {
+ schemaVersion: 1,
+ generatedAt: new Date().toISOString(),
+ machine: {
+ platform: process.platform,
+ arch: process.arch,
+ node: process.version,
+ availableParallelism: os.availableParallelism(),
+ memoryGiB: roundMs(os.totalmem() / 1024 ** 3),
+ cpu: os.cpus()[0]?.model ?? 'unknown',
+ },
+ options: {
+ workers: options.workers,
+ runs: options.runs,
+ top: options.top,
+ },
+ samples,
+ summary: summarizeDesktopWorkerSamples(samples),
+ };
+ printSummary(report);
+ if (options.output) {
+ fs.mkdirSync(path.dirname(options.output), { recursive: true });
+ fs.writeFileSync(options.output, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
+ console.log(`\nJSON report: ${options.output}`);
+ }
+ if (samples.some((sample) => !sample.success)) process.exitCode = 1;
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ main().catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+ });
+}
diff --git a/scripts/help.mjs b/scripts/help.mjs
index b96e4173c2..6ef07fd6d7 100644
--- a/scripts/help.mjs
+++ b/scripts/help.mjs
@@ -66,6 +66,9 @@ export function printHelp(log = console.log) {
log(' pnpm lint');
log(' pnpm test:runner');
log(' pnpm test:unit');
+ log(' # 排查并发相关问题时,可把 workspace runner 临时退回串行');
+ log(' pnpm test:unit -- --workspace-concurrency=1');
+ log(' pnpm benchmark:desktop-workers -- --workers=1,2,4,8 --output=<report.json>');
log(' pnpm test:all');
log(' pnpm test:db');
log(' pnpm test:guard');
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index f2394b7864..698f532bb6 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -1,5 +1,10 @@
-const unitVitestScript = { type: 'packageScript', script: 'test' };
+import os from 'node:os';
+
const vitestBin = (...args) => ({ type: 'packageBin', bin: 'vitest', args });
+// Workspace-level parallelism owns the global process budget. Keep ordinary
+// Vitest workspaces at one worker each so outer concurrency cannot multiply
+// every child process's default CPU-sized pool.
+const unitVitestCommand = (workers = 1) => vitestBin('run', `--maxWorkers=${workers}`);
const noCollectableTestsReason = 'No collectable tests yet. Add tests and mark a tier required when this workspace gains testable logic.';
const desktopDbInclude = [
'src/main/localDb/**/__tests__/*.test.ts',
@@ -15,6 +20,15 @@ const desktopDbExclude = [
'src/main/localDb/__tests__/drizzle-proxy-perf.test.ts',
];
+export function desktopUnitWorkerCount(
+ availableParallelism = os.availableParallelism(),
+) {
+ const available = Number.isFinite(availableParallelism)
+ ? Math.floor(availableParallelism)
+ : 1;
+ return Math.max(1, Math.min(8, available));
+}
+
const noCollectableWorkspace = (name, cwd, reason = noCollectableTestsReason) => ({
name,
cwd,
@@ -23,11 +37,17 @@ const noCollectableWorkspace = (name, cwd, reason = noCollectableTestsReason) =>
tiers: {},
});
-const requiredUnitWorkspace = (name, cwd) => ({
+const requiredUnitWorkspace = (name, cwd, { workers = 1, execution } = {}) => ({
name,
cwd,
status: 'required',
- tiers: { unit: { status: 'required', command: unitVitestScript } },
+ tiers: {
+ unit: {
+ status: 'required',
+ ...(execution ? { execution } : {}),
+ command: unitVitestCommand(workers),
+ },
+ },
});
export default {
@@ -39,9 +59,12 @@ export default {
tiers: {
unit: {
status: 'required',
- // Desktop unit tests spawn many Git/filesystem subprocesses; cap workers so
- // Windows does not exhaust process and file-lock budgets under full-suite load.
- command: vitestBin('run', '--maxWorkers=4'),
+ execution: 'exclusive',
+ // Desktop unit tests spawn many Git/filesystem subprocesses. Benchmarking
+ // found eight workers to be the best complexity/resource tradeoff.
+ // Lower-CPU hosts stay capped by their available parallelism.
+ // It runs exclusively so these workers never overlap outer workspaces.
+ command: vitestBin('run', `--maxWorkers=${desktopUnitWorkerCount()}`),
exclude: [
'src/main/localDb/**',
'src/main/__tests__/*Migration.test.ts',
@@ -100,7 +123,9 @@ export default {
},
},
},
- requiredUnitWorkspace('mobile', 'apps/mobile'),
+ // Mobile has enough test files to become the critical path at one worker.
+ // Give it the full worker budget, but never overlap it with other workspaces.
+ requiredUnitWorkspace('mobile', 'apps/mobile', { workers: 4, execution: 'exclusive' }),
requiredUnitWorkspace('@cindy/anthropic-compat-proxy', 'packages/anthropic-compat-proxy'),
requiredUnitWorkspace('@cindy/anthropic-responses-bridge', 'packages/anthropic-responses-bridge'),
requiredUnitWorkspace('@cindy/responses-chat-bridge', 'packages/responses-chat-bridge'),
@@ -128,7 +153,7 @@ export default {
tiers: {
unit: {
status: 'required',
- command: unitVitestScript,
+ command: unitVitestCommand(),
include: ['src/__tests__/**/*.test.ts'],
},
},
diff --git a/scripts/test-workspaces.mjs b/scripts/test-workspaces.mjs
index 487497cc49..9d3f336404 100644
--- a/scripts/test-workspaces.mjs
+++ b/scripts/test-workspaces.mjs
@@ -1,6 +1,7 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import fs from "node:fs";
+import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -23,6 +24,9 @@ const VALID_STATUSES = new Set([
"deferred",
]);
const VALID_COVERAGE_MODES = new Set(["workspace", "allowlist"]);
+const VALID_EXECUTION_MODES = new Set(["normal", "exclusive"]);
+const MAX_DEFAULT_WORKSPACE_CONCURRENCY = 4;
+const DEFAULT_CAPTURED_OUTPUT_LIMIT = 2 * 1024 * 1024;
export function normalizeRelPath(value) {
return value.replace(/\\/g, "/");
@@ -41,9 +45,11 @@ export function parseCliOptions(args) {
tier: "unit",
workspaces: [],
excludeWorkspaces: [],
+ workspaceConcurrency: undefined,
};
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
+ if (arg === "--") continue;
if (arg === "--all") {
options.all = true;
continue;
@@ -67,11 +73,43 @@ export function parseCliOptions(args) {
index += 1;
continue;
}
+ if (
+ arg === "--workspace-concurrency" ||
+ arg.startsWith("--workspace-concurrency=")
+ ) {
+ const inlineValue = arg.startsWith("--workspace-concurrency=")
+ ? arg.slice("--workspace-concurrency=".length)
+ : undefined;
+ const value = inlineValue ?? args[index + 1];
+ if (!value || (!inlineValue && value.startsWith("--")))
+ throw new Error("--workspace-concurrency requires a positive integer");
+ options.workspaceConcurrency = parseWorkspaceConcurrency(value);
+ if (inlineValue === undefined) index += 1;
+ continue;
+ }
throw new Error(`Unknown option: ${arg}`);
}
return options;
}
+export function parseWorkspaceConcurrency(value) {
+ if (!/^[1-9]\d*$/.test(String(value)))
+ throw new Error("--workspace-concurrency requires a positive integer");
+ const parsed = Number(value);
+ if (!Number.isSafeInteger(parsed))
+ throw new Error("--workspace-concurrency requires a positive integer");
+ return parsed;
+}
+
+export function defaultWorkspaceConcurrency(
+ availableParallelism = os.availableParallelism(),
+) {
+ const available = Number.isFinite(availableParallelism)
+ ? Math.floor(availableParallelism)
+ : 1;
+ return Math.max(1, Math.min(MAX_DEFAULT_WORKSPACE_CONCURRENCY, available));
+}
+
export function parseWorkspaceSelectorValue(value) {
return value
.split(",")
@@ -281,6 +319,13 @@ export function validateManifest(manifestWorkspaces) {
throw new Error(`${workspace.cwd} ${tier} requires reason`);
if (isRunnableTier(config) && !config.command)
throw new Error(`${workspace.cwd} ${tier} requires command`);
+ if (
+ config.execution !== undefined &&
+ !VALID_EXECUTION_MODES.has(config.execution)
+ )
+ throw new Error(
+ `${workspace.cwd} ${tier} has invalid execution mode`,
+ );
}
}
}
@@ -470,6 +515,43 @@ export function resolveOutputStream(configured, fallback) {
return configured === undefined ? fallback : configured;
}
+export function createBoundedOutputBuffer(
+ maxChars = DEFAULT_CAPTURED_OUTPUT_LIMIT,
+) {
+ const limit =
+ Number.isFinite(maxChars) && maxChars > 0
+ ? Math.floor(maxChars)
+ : DEFAULT_CAPTURED_OUTPUT_LIMIT;
+ const headLimit = Math.floor(limit / 4);
+ const tailLimit = limit - headLimit;
+ let head = "";
+ let tail = "";
+ let totalChars = 0;
+ return {
+ append(value) {
+ let text = String(value);
+ totalChars += text.length;
+ if (head.length < headLimit) {
+ const headRemaining = headLimit - head.length;
+ head += text.slice(0, headRemaining);
+ text = text.slice(headRemaining);
+ }
+ if (text.length > 0) {
+ const tailInput =
+ text.length > tailLimit ? text.slice(-tailLimit) : text;
+ tail = `${tail}${tailInput}`.slice(-tailLimit);
+ }
+ },
+ toString() {
+ if (totalChars <= limit) return `${head}${tail}`;
+ const omitted = totalChars - head.length - tail.length;
+ return (
+ `${head}\n... ${omitted} output characters omitted ...\n${tail}`
+ );
+ },
+ };
+}
+
export function runCommand(command, args, options = {}) {
return new Promise((resolve) => {
const child = spawn(command, args, {
@@ -477,7 +559,7 @@ export function runCommand(command, args, options = {}) {
shell: options.shell,
windowsHide: true,
});
- let output = "";
+ const output = createBoundedOutputBuffer(options.maxOutputChars);
let settled = false;
const stdout = createOutputForwarder(resolveOutputStream(options.stdout, process.stdout));
const stderr = createOutputForwarder(resolveOutputStream(options.stderr, process.stderr));
@@ -488,24 +570,26 @@ export function runCommand(command, args, options = {}) {
const stderrError = stderr.finish();
const forwardingError = stdoutError ?? stderrError;
if (forwardingError) {
- output += `\nOutput forwarding failed: ${forwardingError.message ?? String(forwardingError)}`;
- resolve({ exitCode: 1, output });
+ output.append(
+ `\nOutput forwarding failed: ${forwardingError.message ?? String(forwardingError)}`,
+ );
+ resolve({ exitCode: 1, output: output.toString() });
return;
}
- resolve({ ...result, output });
+ resolve({ ...result, output: output.toString() });
};
child.stdout?.on("data", (chunk) => {
const text = chunk.toString();
- output += text;
+ output.append(text);
stdout.write(chunk);
});
child.stderr?.on("data", (chunk) => {
const text = chunk.toString();
- output += text;
+ output.append(text);
stderr.write(chunk);
});
child.on("error", (error) => {
- output += error.message;
+ output.append(error.message);
finish({ exitCode: 1 });
});
child.on("close", (code) => {
@@ -514,6 +598,110 @@ export function runCommand(command, args, options = {}) {
});
}
+/**
+ * Runs independent tasks with a fixed upper bound while preserving result order.
+ * Workers pull the next task as soon as they finish, so one slow workspace does
+ * not hold an entire batch open.
+ */
+export async function mapWithConcurrency(items, concurrency, runItem) {
+ const limit = parseWorkspaceConcurrency(concurrency);
+ const results = new Array(items.length);
+ let nextIndex = 0;
+ const workers = Array.from(
+ { length: Math.min(limit, items.length) },
+ async () => {
+ while (true) {
+ const index = nextIndex;
+ nextIndex += 1;
+ if (index >= items.length) return;
+ results[index] = await runItem(items[index], index);
+ }
+ },
+ );
+ await Promise.all(workers);
+ return results;
+}
+
+/**
+ * Exclusive runs form barriers around normal runs. This keeps a heavyweight
+ * workspace such as Desktop from multiplying its internal worker pool with the
+ * outer workspace concurrency.
+ */
+export async function runWithExclusiveBarriers(
+ runs,
+ concurrency,
+ runItem,
+) {
+ const results = [];
+ let normalSegment = [];
+ const flushNormalSegment = async () => {
+ if (normalSegment.length === 0) return;
+ results.push(
+ ...(await mapWithConcurrency(normalSegment, concurrency, runItem)),
+ );
+ normalSegment = [];
+ };
+ for (const run of runs) {
+ if (run.tierConfig.execution !== "exclusive") {
+ normalSegment.push(run);
+ continue;
+ }
+ await flushNormalSegment();
+ results.push(await runItem(run));
+ }
+ await flushNormalSegment();
+ return results;
+}
+
+function formatElapsed(durationMs) {
+ if (durationMs < 1_000) return `${durationMs}ms`;
+ return `${(durationMs / 1_000).toFixed(1)}s`;
+}
+
+/**
+ * Buffers each child command and flushes it as one block on completion. Parallel
+ * workspaces remain observable without interleaving Vitest output line-by-line.
+ */
+export function createWorkspaceRunReporter({
+ stdout = process.stdout,
+ now = Date.now,
+} = {}) {
+ const startedAt = new Map();
+ return {
+ onRunStart(run) {
+ const key = `${run.workspace.cwd}\0${run.tier}`;
+ startedAt.set(key, now());
+ stdout.write(`START ${run.workspace.cwd} ${run.tier}\n`);
+ },
+ onCommandComplete({ run, stage, commandResult }) {
+ // Successful Vitest workspaces can contain thousands of per-file lines.
+ // The elapsed PASS line is sufficient; retain full output only when a
+ // command fails so diagnostics stay available without flooding CI logs.
+ if (commandResult.exitCode === 0 || !commandResult.output) return;
+ const output = commandResult.output.endsWith("\n")
+ ? commandResult.output
+ : `${commandResult.output}\n`;
+ stdout.write(
+ `\n[${run.workspace.cwd} ${run.tier} ${stage}]\n${output}`,
+ );
+ },
+ onRunComplete(run, result) {
+ const key = `${run.workspace.cwd}\0${run.tier}`;
+ const started = startedAt.get(key);
+ const fallbackDurationMs =
+ started === undefined ? 0 : Math.max(0, now() - started);
+ const durationMs = Number.isFinite(result.durationMs)
+ ? Math.max(0, result.durationMs)
+ : fallbackDurationMs;
+ startedAt.delete(key);
+ const status = result.exitCode === 0 ? "PASS" : `FAIL ${result.failure}`;
+ stdout.write(
+ `${status} ${run.workspace.cwd} ${run.tier} (${formatElapsed(durationMs)})\n`,
+ );
+ },
+ };
+}
+
export function readAllFiles(root) {
const files = [];
function visit(absDir) {
@@ -542,6 +730,9 @@ export async function runPlannedTests({
workspaceCwds,
allFiles,
runCommandImpl = runCommand,
+ workspaceConcurrency,
+ reporter,
+ now = Date.now,
}) {
const manifestWorkspaces = manifest.workspaces;
const actualWorkspaceCwds =
@@ -563,6 +754,8 @@ export async function runPlannedTests({
const discoveredFiles = allFiles ?? discoverTestFiles(readAllFiles(root));
const tiers = all ? listConfiguredTiers(manifestWorkspaces) : [tier];
const results = [];
+ const concurrency =
+ workspaceConcurrency ?? defaultWorkspaceConcurrency();
for (const currentTier of tiers) {
const runs = filterRunsByWorkspace(
planRuns(manifestWorkspaces, {
@@ -576,7 +769,12 @@ export async function runPlannedTests({
`No runnable test runs configured for tier ${currentTier}. ${describeTierStatus(manifestWorkspaces, currentTier)}`,
);
}
- for (const run of runs) {
+ const tierResults = await runWithExclusiveBarriers(
+ runs,
+ concurrency,
+ async (run) => {
+ const startedAt = now();
+ reporter?.onRunStart?.(run);
const fileCheck = checkTestFiles(
run.workspace,
currentTier,
@@ -590,17 +788,26 @@ export async function runPlannedTests({
discoveredFiles,
);
const cwd = path.join(root, run.workspace.cwd);
- let preflightFailed = false;
for (const preflight of run.tierConfig.preflight ?? []) {
const pnpmArgs = buildPreflightArgs(root, run.workspace, preflight);
const invocation = resolvePnpmInvocation(pnpmArgs);
const commandResult = await runCommandImpl(
invocation.command,
invocation.args,
- { cwd, shell: invocation.shell },
+ {
+ cwd,
+ shell: invocation.shell,
+ stdout: reporter ? null : undefined,
+ stderr: reporter ? null : undefined,
+ },
);
+ reporter?.onCommandComplete?.({
+ run,
+ stage: "preflight",
+ commandResult,
+ });
if (commandResult.exitCode !== 0) {
- results.push({
+ const result = {
workspace: run.workspace.cwd,
tier: currentTier,
stage: "preflight",
@@ -613,12 +820,12 @@ export async function runPlannedTests({
exitCode: commandResult.exitCode,
output: commandResult.output,
}),
- });
- preflightFailed = true;
- break;
+ durationMs: Math.max(0, now() - startedAt),
+ };
+ reporter?.onRunComplete?.(run, result);
+ return result;
}
}
- if (preflightFailed) continue;
const pnpmArgs = buildPnpmArgs(
root,
run.workspace,
@@ -630,9 +837,19 @@ export async function runPlannedTests({
const commandResult = await runCommandImpl(
invocation.command,
invocation.args,
- { cwd, shell: invocation.shell },
+ {
+ cwd,
+ shell: invocation.shell,
+ stdout: reporter ? null : undefined,
+ stderr: reporter ? null : undefined,
+ },
);
- results.push({
+ reporter?.onCommandComplete?.({
+ run,
+ stage: "test",
+ commandResult,
+ });
+ const result = {
workspace: run.workspace.cwd,
tier: currentTier,
stage: "test",
@@ -645,8 +862,13 @@ export async function runPlannedTests({
exitCode: commandResult.exitCode,
output: commandResult.output,
}),
- });
- }
+ durationMs: Math.max(0, now() - startedAt),
+ };
+ reporter?.onRunComplete?.(run, result);
+ return result;
+ },
+ );
+ results.push(...tierResults.filter(Boolean));
}
return results;
}
@@ -656,7 +878,11 @@ export function printSummary(results, manifest) {
for (const result of results) {
const status = result.exitCode === 0 ? "PASS" : `FAIL ${result.failure}`;
const workspaceCwd = result.workspace?.cwd ?? result.workspace;
- console.log(`${status} ${workspaceCwd} ${result.tier}`);
+ const elapsed =
+ Number.isFinite(result.durationMs)
+ ? ` (${formatElapsed(result.durationMs)})`
+ : "";
+ console.log(`${status} ${workspaceCwd} ${result.tier}${elapsed}`);
if (result.command)
console.log(` command: ${[result.command, ...(result.args ?? [])].join(" ")}`);
}
@@ -671,9 +897,13 @@ export function printSummary(results, manifest) {
}
async function main() {
- const { all, tier, workspaces, excludeWorkspaces } = parseCliOptions(
- process.argv.slice(2),
- );
+ const {
+ all,
+ tier,
+ workspaces,
+ excludeWorkspaces,
+ workspaceConcurrency,
+ } = parseCliOptions(process.argv.slice(2));
const manifest = (await import("./test-workspaces.config.mjs")).default;
const results = await runPlannedTests({
root: ROOT,
@@ -682,6 +912,8 @@ async function main() {
all,
workspaces,
excludeWorkspaces,
+ workspaceConcurrency,
+ reporter: createWorkspaceRunReporter(),
});
printSummary(results, manifest);
if (results.some((result) => result.exitCode !== 0)) process.exitCode = 1;