Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
test(desktop): 分层协调多 worktree 测试资源 (#796)
DavidShenXD45c50e4fbca7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7e21ddf16f..9e3cb279d8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -117,3 +117,58 @@ jobs:- name: Run mobile scope guardrun: pnpm --filter mobile test:scope++ git-integration:+ name: Desktop Git integration+ runs-on: ubuntu-latest+ timeout-minutes: 25++ steps:+ - name: Checkout client+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ fetch-depth: 0+ lfs: true++ # `.gitmodules` comes from the PR branch. Pin the public protocol source+ # before recursively initializing it, matching the verify job boundary.+ - name: Verify cindy-protocol submodule source+ run: |+ set -euo pipefail+ expected_url='https://github.com/makecindy/cindy-protocol.git'+ expected_path='cindy-protocol'+ actual_url="$(git config -f .gitmodules --get submodule.cindy-protocol.url || true)"+ actual_path="$(git config -f .gitmodules --get submodule.cindy-protocol.path || true)"+ if [ "$actual_url" != "$expected_url" ] || [ "$actual_path" != "$expected_path" ]; then+ echo "::error file=.gitmodules::cindy-protocol source mismatch: url='$actual_url' path='$actual_path' (expected url='$expected_url' path='$expected_path')"+ exit 1+ fi+ echo "cindy-protocol submodule source verified: $actual_url"++ - name: Fetch cindy-protocol submodule+ run: |+ git submodule sync -- cindy-protocol+ git submodule update --init --force --recursive -- cindy-protocol++ - name: Setup pnpm+ uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6+ with:+ run_install: false++ - name: Setup Node.js+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: 22+ cache: pnpm+ cache-dependency-path: pnpm-lock.yaml++ - name: Install dependencies+ run: pnpm install --frozen-lockfile++ - name: Install bundled ripgrep+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: pnpm install:ripgrep++ - name: Run Desktop Git integration tests+ run: pnpm test:git-integrationdiff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 4cceabc031..0bac6f4a8c 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -31,6 +31,7 @@"ensure-deps": "node ../../scripts/ensure-deps.mjs","ensure-dev-runtime-assets": "node ../../scripts/ensure-dev-runtime-assets.mjs","test": "vitest run",+ "test:git-integration": "pnpm --dir ../.. test:runner && node ../../scripts/test-workspaces.mjs --tier git-integration","test:db": "pnpm --dir ../.. test:runner && node ../../scripts/test-workspaces.mjs --tier db","test:db-proxy-perf": "cross-env XDT_DB_PROXY_PERF_STRICT=1 vitest run src/main/localDb/__tests__/drizzle-proxy-perf.test.ts","test:migration": "pnpm --dir ../.. test:runner && node ../../scripts/test-workspaces.mjs --tier migration",diff --git a/apps/desktop/src/main/__tests__/codexFileRewindExecutor.test.ts b/apps/desktop/src/main/__tests__/codexFileRewindExecutor.git-integration.test.tssimilarity index 95%rename from apps/desktop/src/main/__tests__/codexFileRewindExecutor.test.tsrename to apps/desktop/src/main/__tests__/codexFileRewindExecutor.git-integration.test.tsindex 85a1b49ea2..730a63c22f 100644--- a/apps/desktop/src/main/__tests__/codexFileRewindExecutor.test.ts+++ b/apps/desktop/src/main/__tests__/codexFileRewindExecutor.git-integration.test.ts@@ -1,9 +1,9 @@import { promises as fs } from 'node:fs';-import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { TestDirectoryTemplate } from '../../test/vitest/testDirectoryTemplate';import {compensateCodexFileRewindExecution,executeCodexFileRewindPlan,@@ -17,14 +17,20 @@ import { gitExec, GitExecError } from '../worktree/gitExec';const REAL_GIT_TEST_TIMEOUT_MS = process.platform === 'win32' ? 60_000 : 20_000;let repoPath: string;-async function initRepo() {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-codex-rewind-'));++const repoTemplate = new TestDirectoryTemplate('xdt-codex-rewind-', async (dir) => {await gitExec(['init'], dir);+ for (const args of [['config', 'user.email', '[email protected]'], ['config', 'user.name', 'XDT Test'], ['config', 'commit.gpgsign', 'false'], ['config', 'core.autocrlf', 'false']]) await gitExec(args, dir);+});++async function initRepo() {+ const dir = await repoTemplate.createCopy();// 仓库级覆写 core.excludesFile:宿主机全局 gitignore(常见如 *.tmp)会吞掉- // 未跟踪文件,让 status 断言在部分开发机上失真。+ // 未跟踪文件,让 status 断言在部分开发机上失真。复制后再写绝对路径,+ // 避免模板仓库路径泄漏进副本配置。const excludesOverride = path.join(dir, '.git', 'xdt-test-empty-excludes');await fs.writeFile(excludesOverride, '', 'utf8');- for (const args of [['config', 'core.excludesFile', excludesOverride], ['config', 'user.email', '[email protected]'], ['config', 'user.name', 'XDT Test'], ['config', 'commit.gpgsign', 'false'], ['config', 'core.autocrlf', 'false']]) await gitExec(args, dir);+ await gitExec(['config', 'core.excludesFile', excludesOverride], dir);return dir;}@@ -90,6 +96,7 @@ async function editedSavepoint(content = 'edited\n') { await commitFile('app.txtbeforeEach(async () => { repoPath = await initRepo(); });afterEach(async () => { await fs.rm(repoPath, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); });+afterAll(async () => { await repoTemplate.dispose(); });describe('executeCodexFileRewindPlan', () => {it('restores files, records rollback, and can compensate it', async () => {diff --git a/apps/desktop/src/main/__tests__/desktopTestResourceLock.test.ts b/apps/desktop/src/main/__tests__/desktopTestResourceLock.test.tsnew file mode 100644index 0000000000..7cf08c1091--- /dev/null+++ b/apps/desktop/src/main/__tests__/desktopTestResourceLock.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest';++import {+ classifyDesktopTestLockProbeError,+ decideDesktopTestLock,+ type DesktopTestLockProbeResult,+} from '../../test/vitest/desktopTestResourceLock';++function probes(...results: DesktopTestLockProbeResult[]) {+ return results.map((result, index) => ({ port: 50_000 + index, result }));+}++describe('decideDesktopTestLock', () => {+ it('waits for an existing owner on a fallback port before taking an earlier free port', () => {+ expect(decideDesktopTestLock(probes('retry', 'owner', 'collision'))).toEqual({+ type: 'wait',+ });+ });++ it('takes the first available candidate only when no existing owner was found', () => {+ expect(decideDesktopTestLock(probes('collision', 'retry', 'retry'))).toEqual({+ type: 'acquire',+ port: 50_001,+ });+ });++ it('fails closed when every deterministic candidate belongs to an unrelated service', () => {+ expect(decideDesktopTestLock(probes('collision', 'collision'))).toEqual({+ type: 'unavailable',+ });+ });+});++describe('classifyDesktopTestLockProbeError', () => {+ it('only retries when the candidate port refused the connection', () => {+ expect(classifyDesktopTestLockProbeError('ECONNREFUSED')).toBe('retry');+ expect(classifyDesktopTestLockProbeError('ECONNRESET')).toBe('collision');+ expect(classifyDesktopTestLockProbeError('ETIMEDOUT')).toBe('collision');+ });+});diff --git a/apps/desktop/src/main/__tests__/gitSnapshotService.test.ts b/apps/desktop/src/main/__tests__/gitSnapshotService.git-integration.test.tssimilarity index 97%rename from apps/desktop/src/main/__tests__/gitSnapshotService.test.tsrename to apps/desktop/src/main/__tests__/gitSnapshotService.git-integration.test.tsindex ee0c67d9c5..561571d664 100644--- a/apps/desktop/src/main/__tests__/gitSnapshotService.test.ts+++ b/apps/desktop/src/main/__tests__/gitSnapshotService.git-integration.test.ts@@ -3,11 +3,11 @@*/import { promises as fs } from 'node:fs';-import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest';+import { TestDirectoryTemplate } from '../../test/vitest/testDirectoryTemplate';import {createSnapshot,createSnapshotDetailed,@@ -27,15 +27,13 @@ const originalGitLocaleEnv = {LANGUAGE: process.env.LANGUAGE,};-async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-create-snapshot-'));+const repoTemplate = new TestDirectoryTemplate('xdt-create-snapshot-', async (dir) => {await gitExec(['init'], dir);await gitExec(['config', 'user.email', '[email protected]'], dir);await gitExec(['config', 'user.name', 'XDT Test'], dir);await gitExec(['config', 'commit.gpgsign', 'false'], dir);await gitExec(['config', 'core.autocrlf', 'false'], dir);- return dir;-}+});async function writeRepoFile(gitPath: string, content: string | Buffer): Promise<void> {const filePath = path.join(repoPath, ...gitPath.split('/'));@@ -99,7 +97,7 @@ beforeEach(async () => {process.env.LC_ALL = 'C';process.env.LANG = 'C';delete process.env.LANGUAGE;- repoPath = await initRepo();+ repoPath = await repoTemplate.createCopy();});afterEach(async () => {@@ -112,6 +110,10 @@ afterEach(async () => {else process.env.LANGUAGE = originalGitLocaleEnv.LANGUAGE;});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('createSnapshot', () => {it('returns null in a clean repo and does not call the label factory', async () => {const initialHead = await commitSeed();diff --git a/apps/desktop/src/main/__tests__/projectGitBootstrap.test.ts b/apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.tssimilarity index 100%rename from apps/desktop/src/main/__tests__/projectGitBootstrap.test.tsrename to apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.tsdiff --git a/apps/desktop/src/main/__tests__/snapshotFileFilter.test.ts b/apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.tssimilarity index 100%rename from apps/desktop/src/main/__tests__/snapshotFileFilter.test.tsrename to apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.tsdiff --git a/apps/desktop/src/main/__tests__/vitestCliExclude.test.ts b/apps/desktop/src/main/__tests__/vitestCliExclude.test.tsnew file mode 100644index 0000000000..058ddb2cac--- /dev/null+++ b/apps/desktop/src/main/__tests__/vitestCliExclude.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import { parseVitestCliExclude } from '../../test/vitest/cliExclude';++describe('parseVitestCliExclude', () => {+ it('collects repeated split and inline exclude options', () => {+ expect(+ parseVitestCliExclude([+ 'run',+ '--exclude',+ 'src/main/localDb/**',+ '--maxWorkers=8',+ '--exclude=**/*.bench.ts',+ ]),+ ).toEqual(['src/main/localDb/**', '**/*.bench.ts']);+ });++ it('ignores missing and empty exclude values', () => {+ expect(parseVitestCliExclude(['run', '--exclude', '--reporter=dot', '--exclude='])).toEqual(+ [],+ );+ });+});diff --git a/apps/desktop/src/main/__tests__/worktreeIncludePatternsEngine.test.ts b/apps/desktop/src/main/__tests__/worktreeIncludePatternsEngine.git-integration.test.tssimilarity index 100%rename from apps/desktop/src/main/__tests__/worktreeIncludePatternsEngine.test.tsrename to apps/desktop/src/main/__tests__/worktreeIncludePatternsEngine.git-integration.test.tsdiff --git a/apps/desktop/src/main/git-review/__tests__/branchReader.test.ts b/apps/desktop/src/main/git-review/__tests__/branchReader.git-integration.test.tssimilarity index 97%rename from apps/desktop/src/main/git-review/__tests__/branchReader.test.tsrename to apps/desktop/src/main/git-review/__tests__/branchReader.git-integration.test.tsindex e1569a9f1f..9d8af984ec 100644--- a/apps/desktop/src/main/git-review/__tests__/branchReader.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/branchReader.git-integration.test.ts@@ -2,24 +2,28 @@ import { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';// Windows 上 git 子进程明显更慢(每次 spawn 数百毫秒),多步 git 编排用例会超默认 5s。vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });+import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';import { isSafeBranchBaseRef, listBranchBaseCandidates, readBranchDiff } from '../branchReader';import { runGit } from '../gitRunner';import type { ReviewScope } from '../types';const repos: string[] = [];-async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-branch-'));- repos.push(dir);+const repoTemplate = new TestDirectoryTemplate('xdt-git-review-branch-', async (dir) => {await runGit(['init', '-b', 'main'], { cwd: dir });await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });+});++async function initRepo(): Promise<string> {+ const dir = await repoTemplate.createCopy();+ repos.push(dir);return dir;}@@ -93,6 +97,10 @@ afterEach(async () => {));});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('git-review branchReader', () => {it('uses a three-dot merge-base diff so base branch advances are not reversed into the result', async () => {const repoPath = await initRepo();diff --git a/apps/desktop/src/main/git-review/__tests__/commitOps.test.ts b/apps/desktop/src/main/git-review/__tests__/commitOps.git-integration.test.tssimilarity index 93%rename from apps/desktop/src/main/git-review/__tests__/commitOps.test.tsrename to apps/desktop/src/main/git-review/__tests__/commitOps.git-integration.test.tsindex 5e7ab94be7..12e659b21a 100644--- a/apps/desktop/src/main/git-review/__tests__/commitOps.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/commitOps.git-integration.test.ts@@ -1,11 +1,11 @@import { promises as fs } from 'node:fs';-import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// Windows 上 git 子进程明显更慢(每次 spawn 数百毫秒),多步 git 编排用例会超默认 5s。vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });+import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';import { commitStagedChanges, GitReviewCommitError } from '../commitOps';import { runGit } from '../gitRunner';import { readStatus } from '../statusReader';@@ -13,8 +13,7 @@ import type { ReviewScope } from '../types';let repoPath: string;-async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-commit-op-'));+const repoTemplate = new TestDirectoryTemplate('xdt-git-review-commit-op-', async (dir) => {await runGit(['init'], { cwd: dir });await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });@@ -22,8 +21,7 @@ async function initRepo(): Promise<string> {await fs.writeFile(path.join(dir, 'file.txt'), 'one\n');await runGit(['add', 'file.txt'], { cwd: dir });await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });- return dir;-}+});function scope(): ReviewScope {return {@@ -45,13 +43,17 @@ function scope(): ReviewScope {}beforeEach(async () => {- repoPath = await initRepo();+ repoPath = await repoTemplate.createCopy();});afterEach(async () => {await fs.rm(repoPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('git-review commitOps', () => {it('commits staged changes with stdin message', async () => {await fs.writeFile(path.join(repoPath, 'file.txt'), 'two\n');diff --git a/apps/desktop/src/main/git-review/__tests__/commitReader.test.ts b/apps/desktop/src/main/git-review/__tests__/commitReader.git-integration.test.tssimilarity index 96%rename from apps/desktop/src/main/git-review/__tests__/commitReader.test.tsrename to apps/desktop/src/main/git-review/__tests__/commitReader.git-integration.test.tsindex 6740aee803..7b4581b278 100644--- a/apps/desktop/src/main/git-review/__tests__/commitReader.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/commitReader.git-integration.test.ts@@ -2,23 +2,27 @@ import { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';// Windows 上 git 子进程明显更慢(每次 spawn 数百毫秒),多步 git 编排用例会超默认 5s。vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });+import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';import { listBranchCommits, readCommitDiff } from '../commitReader';import { runGit } from '../gitRunner';import type { ReviewScope } from '../types';const repos: string[] = [];-async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-commit-'));- repos.push(dir);+const repoTemplate = new TestDirectoryTemplate('xdt-git-review-commit-', async (dir) => {await runGit(['init', '-b', 'main'], { cwd: dir });await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });+});++async function initRepo(): Promise<string> {+ const dir = await repoTemplate.createCopy();+ repos.push(dir);return dir;}@@ -86,6 +90,10 @@ afterEach(async () => {));});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('git-review commitReader', () => {it('lists branch commits from base..HEAD and reads a normal commit diff against first parent', async () => {const repoPath = await initRepo();diff --git a/apps/desktop/src/main/git-review/__tests__/diffReader.test.ts b/apps/desktop/src/main/git-review/__tests__/diffReader.git-integration.test.tssimilarity index 98%rename from apps/desktop/src/main/git-review/__tests__/diffReader.test.tsrename to apps/desktop/src/main/git-review/__tests__/diffReader.git-integration.test.tsindex f451a9e2a8..0a8e55d4a4 100644--- a/apps/desktop/src/main/git-review/__tests__/diffReader.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/diffReader.git-integration.test.ts@@ -1,12 +1,12 @@import { promises as fs } from 'node:fs';-import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// Windows 上 git 子进程明显更慢(每次 spawn 数百毫秒),多步 git 编排用例会超默认 5s。vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });+import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';import { runGit } from '../gitRunner';import { readStatus } from '../statusReader';import { mapWithConcurrency, readCappedFileDiff, readDiffs, readDiffSummaryEntries, readFileDiff } from '../diffReader';@@ -14,8 +14,7 @@ import type { ReviewScope } from '../types';let repoPath: string;-async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-'));+const repoTemplate = new TestDirectoryTemplate('xdt-git-review-diff-', async (dir) => {await runGit(['init'], { cwd: dir });await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });@@ -25,8 +24,7 @@ async function initRepo(): Promise<string> {await fs.writeFile(path.join(dir, 'seed.txt'), 'seed\n');await runGit(['add', 'seed.txt'], { cwd: dir });await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });- return dir;-}+});async function tryCreateFileSymlink(target: string, linkPath: string): Promise<boolean> {try {@@ -59,13 +57,17 @@ function scope(): ReviewScope {}beforeEach(async () => {- repoPath = await initRepo();+ repoPath = await repoTemplate.createCopy();});afterEach(async () => {await fs.rm(repoPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('git-review diffReader', () => {it('reads untracked files through --no-index /dev/null', async () => {await fs.writeFile(path.join(repoPath, 'new file.txt'), 'hello\nworld\n');diff --git a/apps/desktop/src/main/git-review/__tests__/gitReviewSmoke.test.ts b/apps/desktop/src/main/git-review/__tests__/gitReviewSmoke.test.tsnew file mode 100644index 0000000000..19db50c1dd--- /dev/null+++ b/apps/desktop/src/main/git-review/__tests__/gitReviewSmoke.test.ts@@ -0,0 +1,59 @@+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { runGit } from '../gitRunner';+import { readStatus } from '../statusReader';+import type { ReviewScope } from '../types';++let repoPath: string | null = null;++function scope(): ReviewScope {+ if (!repoPath) throw new Error('smoke repository is not initialized');+ return {+ sessionId: 'smoke',+ workdir: repoPath,+ worktreePath: repoPath,+ workingDir: repoPath,+ repoRoot: repoPath,+ branch: 'main',+ headOid: null,+ isDetached: false,+ isUnborn: true,+ source: 'worktree',+ aheadBehind: { ahead: 0, behind: 0, upstream: null, stale: true },+ disabledReason: null,+ disabledMessage: null,+ resolutionChain: [],+ };+}++afterEach(async () => {+ if (!repoPath) return;+ const cleanupPath = repoPath;+ repoPath = null;+ await fs.rm(cleanupPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });+});++describe('git-review real Git smoke', () => {+ it('initializes a repository and reads its untracked status', async () => {+ repoPath = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-git-review-smoke-'));+ await runGit(['init', '-b', 'main'], { cwd: repoPath });+ await fs.writeFile(path.join(repoPath, 'smoke.txt'), 'smoke\n');++ const status = await readStatus(scope());++ expect(status).toMatchObject({+ dirty: true,+ stagedCount: 0,+ unstagedCount: 1,+ untrackedCount: 1,+ });+ expect(status.files).toContainEqual(expect.objectContaining({+ path: 'smoke.txt',+ worktreeStatus: 'untracked',+ }));+ });+});diff --git a/apps/desktop/src/main/git-review/__tests__/imageReader.test.ts b/apps/desktop/src/main/git-review/__tests__/imageReader.git-integration.test.tssimilarity index 97%rename from apps/desktop/src/main/git-review/__tests__/imageReader.test.tsrename to apps/desktop/src/main/git-review/__tests__/imageReader.git-integration.test.tsindex b3dd854199..10a5d0ff1a 100644--- a/apps/desktop/src/main/git-review/__tests__/imageReader.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/imageReader.git-integration.test.ts@@ -1,11 +1,11 @@import { promises as fs } from 'node:fs';-import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// Windows 上 git 子进程明显更慢(每次 spawn 数百毫秒),多步 git 编排用例会超默认 5s。vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });+import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';import { readCommitDiff } from '../commitReader';import { readBranchDiff } from '../branchReader';import { readDiffs } from '../diffReader';@@ -26,8 +26,7 @@ const oldPng = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00const newPng = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x03, 0xfe]);const worktreePng = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x09, 0xf0]);-async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-image-'));+const repoTemplate = new TestDirectoryTemplate('xdt-git-review-image-', async (dir) => {await runGit(['init', '-b', 'main'], { cwd: dir });await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });@@ -35,8 +34,7 @@ async function initRepo(): Promise<string> {await fs.writeFile(path.join(dir, 'seed.txt'), 'seed\n');await runGit(['add', 'seed.txt'], { cwd: dir });await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });- return dir;-}+});function scope(branch = 'main'): ReviewScope {return {@@ -88,13 +86,17 @@ function expectDataUrl(side: { dataUrl?: string }, mime: string, bytes: Buffer):}beforeEach(async () => {- repoPath = await initRepo();+ repoPath = await repoTemplate.createCopy();});afterEach(async () => {await fs.rm(repoPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('git-review imageReader', () => {it('recognizes raster extensions and intentionally excludes svg', () => {expect(isPreviewableRasterPath('image.PNG')).toBe(true);diff --git a/apps/desktop/src/main/git-review/__tests__/ipc.git-integration.test.ts b/apps/desktop/src/main/git-review/__tests__/ipc.git-integration.test.tsnew file mode 100644index 0000000000..9914b97a66--- /dev/null+++ b/apps/desktop/src/main/git-review/__tests__/ipc.git-integration.test.ts@@ -0,0 +1,438 @@+import { promises as fs, symlinkSync, unlinkSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';++// Windows 上 git 子进程明显更慢;完整 workspace 并发测试时,hunk 的多步+// stage/unstage/discard 编排会超过 30s,给真实 Git 集成用例留足余量。+vi.setConfig({ testTimeout: 60_000 });++// Windows 未开发者模式/无特权时创建文件 symlink 会 EPERM;探测一次,不可用则跳过 symlink 用例。+const canSymlink = (() => {+ const probe = path.join(os.tmpdir(), `xdt-symlink-probe-${process.pid}-${Math.random().toString(36).slice(2, 8)}`);+ try {+ symlinkSync(`${probe}-target`, probe, 'file');+ unlinkSync(probe);+ return true;+ } catch {+ return false;+ }+})();++import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';+import {+ parseCommitDiffPayload,+ parseHunkPayload,+ parseImagePreviewPayload,+ parseMarkdownPreviewPayload,+ parseOpenFilePayload,+ parseTarget,+ openReviewFile,+ runReviewFileStageOperation,+ runReviewHunkStageOperation,+} from '../ipc';+import { readDiffs } from '../diffReader';+import { runGit } from '../gitRunner';+import { readStatus } from '../statusReader';+import type { FileDiff, GitReviewDeps, ReviewDiffReadOptions, ReviewScope } from '../types';++const repos: string[] = [];+const HEX_OID = '0123456789abcdef0123456789abcdef01234567';+const SHORT_HEX_OID = 'abc1234';++function baseDiff(patch: Partial<FileDiff> = {}): FileDiff {+ return {+ id: 'unstaged:file.txt',+ source: 'unstaged',+ path: 'file.txt',+ oldPath: null,+ status: 'modified',+ kind: 'text',+ size: 10,+ additions: 1,+ deletions: 0,+ isBinary: false,+ isSubmodule: false,+ isTooLarge: false,+ mode: { old: null, new: null },+ index: { oldOid: null, newOid: null },+ rawHeader: '',+ rawPatch: '',+ hunks: [{ index: 0, header: '@@ -1 +1 @@', oldStart: 1, oldLines: 1, newStart: 1, newLines: 1, section: '', lines: [], selectableLines: [], raw: '' }],+ error: null,+ ...patch,+ };+}++const repoTemplate = new TestDirectoryTemplate('xdt-git-review-ipc-', async (dir) => {+ await runGit(['init', '-b', 'main'], { cwd: dir });+ await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });+ await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });+ await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });+ // 测试内容显式用 LF 断言;屏蔽全局 autocrlf=true(Windows 默认)对 checkout/apply 的换行改写。+ await runGit(['config', 'core.autocrlf', 'false'], { cwd: dir });+ await fs.writeFile(path.join(dir, 'seed.txt'), 'seed\n');+ await runGit(['add', 'seed.txt'], { cwd: dir });+ await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });+});++async function initRepo(): Promise<string> {+ const dir = await repoTemplate.createCopy();+ repos.push(dir);+ return dir;+}++function gitDeps(baseScope: ReviewScope): GitReviewDeps {+ return {+ resolveScope: vi.fn(async () => baseScope),+ readStatus,+ readDiffs,+ isSessionRunning: () => false,+ };+}++function scope(repoPath: string): ReviewScope {+ return {+ sessionId: 's1',+ workdir: repoPath,+ worktreePath: repoPath,+ workingDir: repoPath,+ repoRoot: repoPath,+ branch: 'main',+ headOid: null,+ isDetached: false,+ isUnborn: false,+ source: 'worktree',+ aheadBehind: { ahead: 0, behind: 0, upstream: null, stale: true },+ disabledReason: null,+ disabledMessage: null,+ resolutionChain: [],+ };+}++afterEach(async () => {+ await Promise.all(repos.splice(0).map((repoPath) =>+ fs.rm(repoPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }),+ ));+});++afterAll(async () => {+ await repoTemplate.dispose();+});++describe('git-review IPC payload guards', () => {+ it('rejects unsafe file targets before write operations reach stageOps', () => {+ expect(() => parseTarget({ source: 'unstaged', path: '../secret.txt' })).toThrow(/\[INVALID_PARAMS\]/);+ expect(() => parseTarget({ source: 'unstaged', path: 'C:\\Users\\secret.txt' })).toThrow(/\[INVALID_PARAMS\]/);+ expect(() => parseTarget({ source: 'unstaged', path: 'file.txt', oldPath: '../old.txt' })).toThrow(/\[INVALID_PARAMS\]/);+ });++ it('rejects unsafe open-file paths before resolving the worktree file', () => {+ expect(() => parseOpenFilePayload({ sessionId: 's1', path: '../secret.txt' })).toThrow(/\[INVALID_PARAMS\]/);+ expect(() => parseOpenFilePayload({ sessionId: 's1', path: 'C:\\Users\\secret.txt' })).toThrow(/\[INVALID_PARAMS\]/);+ });++ it('rejects unsafe hunk diff paths from renderer payloads', () => {+ expect(() => parseHunkPayload({+ sessionId: 's1',+ diff: baseDiff({ path: 'docs/../secret.md' }),+ hunkIndex: 0,+ })).toThrow(/\[INVALID_PARAMS\]/);+ expect(() => parseHunkPayload({+ sessionId: 's1',+ diff: baseDiff({ oldPath: '../old.txt' }),+ hunkIndex: 0,+ })).toThrow(/\[INVALID_PARAMS\]/);+ });++ it('requires hunk ignoreWhitespace to be a strict boolean when provided', () => {+ expect(parseHunkPayload({+ sessionId: 's1',+ diff: baseDiff(),+ hunkIndex: 0,+ ignoreWhitespace: true,+ }).options).toEqual({ ignoreWhitespace: true });+ expect(() => parseHunkPayload({+ sessionId: 's1',+ diff: baseDiff(),+ hunkIndex: 0,+ ignoreWhitespace: 'true',+ })).toThrow(/\[INVALID_PARAMS\]/);+ });++ it('keeps hex diff index oids, including git abbreviations, and drops non-hex revspecs', () => {+ const image = parseImagePreviewPayload({+ sessionId: 's1',+ diff: baseDiff({+ source: 'staged',+ kind: 'binary',+ path: 'asset.png',+ index: { oldOid: SHORT_HEX_OID, newOid: HEX_OID },+ }),+ });+ const markdown = parseMarkdownPreviewPayload({+ sessionId: 's1',+ diff: baseDiff({+ path: 'README.md',+ index: { oldOid: HEX_OID, newOid: 'main:README.md' },+ }),+ });++ expect(image.request.diff.index).toEqual({ oldOid: SHORT_HEX_OID, newOid: HEX_OID });+ expect(markdown.request.diff.index).toEqual({ oldOid: HEX_OID, newOid: null });+ });++ it('rejects non-hex commit ids for commit diffs and preview requests', () => {+ expect(() => parseCommitDiffPayload({ sessionId: 's1', oid: 'HEAD' })).toThrow(/\[INVALID_PARAMS\]/);+ expect(() => parseImagePreviewPayload({+ sessionId: 's1',+ diff: baseDiff({ source: 'commit', kind: 'binary', path: 'asset.png' }),+ commitOid: 'HEAD',+ })).toThrow(/\[INVALID_PARAMS\]/);+ expect(() => parseMarkdownPreviewPayload({+ sessionId: 's1',+ diff: baseDiff({ source: 'commit', path: 'README.md' }),+ commitOid: 'feature',+ })).toThrow(/\[INVALID_PARAMS\]/);+ });+});++describe('git-review scoped open file', () => {+ it('opens safe worktree files after IPC parsing and realpath containment checks', async () => {+ const repoPath = await initRepo();+ const filePath = path.join(repoPath, 'huge.txt');+ await fs.writeFile(filePath, 'large file placeholder\n');+ const openPath = vi.fn(async () => '');+ const parsed = parseOpenFilePayload(JSON.parse(JSON.stringify({+ sessionId: 's1',+ path: 'huge.txt',+ })));++ await openReviewFile(parsed.sessionId, parsed.path, { resolveScope: vi.fn(async () => scope(repoPath)) }, openPath);++ expect(openPath).toHaveBeenCalledWith(await fs.realpath(filePath));+ });++ it('rejects missing worktree files without calling shell.openPath', async () => {+ const repoPath = await initRepo();+ const openPath = vi.fn(async () => '');+ const parsed = parseOpenFilePayload({+ sessionId: 's1',+ path: 'missing.txt',+ });++ await expect(openReviewFile(+ parsed.sessionId,+ parsed.path,+ { resolveScope: vi.fn(async () => scope(repoPath)) },+ openPath,+ )).rejects.toThrow(/\[PRECONDITION_FAILED\].*does not exist/);+ expect(openPath).not.toHaveBeenCalled();+ });++ it.skipIf(!canSymlink)('rejects symlinks that resolve outside the repository', async () => {+ const repoPath = await initRepo();+ const outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-outside-'));+ repos.push(outsideDir);+ const outsideFile = path.join(outsideDir, 'secret.txt');+ await fs.writeFile(outsideFile, 'secret\n');+ await fs.symlink(outsideFile, path.join(repoPath, 'escape.txt'));+ const openPath = vi.fn(async () => '');+ const parsed = parseOpenFilePayload({+ sessionId: 's1',+ path: 'escape.txt',+ });++ await expect(openReviewFile(+ parsed.sessionId,+ parsed.path,+ { resolveScope: vi.fn(async () => scope(repoPath)) },+ openPath,+ )).rejects.toThrow(/\[PRECONDITION_FAILED\].*outside/);+ expect(openPath).not.toHaveBeenCalled();+ });+});++describe('git-review write busy gate', () => {+ it('rejects queued writes while the session is running', async () => {+ const deps: GitReviewDeps = {+ resolveScope: vi.fn(),+ readStatus: vi.fn(),+ readDiffs: vi.fn(),+ isSessionRunning: () => true,+ };++ await expect(runReviewFileStageOperation('s1', 'stage', [+ { source: 'unstaged', path: 'file.txt', oldPath: null },+ ], deps)).rejects.toMatchObject({ code: 'SESSION_RUNNING' });+ expect(deps.resolveScope).not.toHaveBeenCalled();+ });++ it('allows normal writes when the session is idle', async () => {+ const repoPath = await initRepo();+ await fs.writeFile(path.join(repoPath, 'new.txt'), 'new\n');+ const baseScope = scope(repoPath);+ const deps: GitReviewDeps = {+ resolveScope: vi.fn(async () => baseScope),+ readStatus,+ readDiffs,+ isSessionRunning: () => false,+ };++ const result = await runReviewFileStageOperation('s1', 'stage', [+ { source: 'unstaged', path: 'new.txt', oldPath: null },+ ], deps);++ expect(result.operation.failed).toHaveLength(0);+ expect(result.operation.succeeded).toEqual(['new.txt']);+ expect((await readStatus(baseScope)).files.find((file) => file.path === 'new.txt')?.indexStatus).toBe('added');+ });++ it('stages untracked files from expanded directory entries after IPC parsing', async () => {+ const repoPath = await initRepo();+ const baseScope = scope(repoPath);+ const deps = gitDeps(baseScope);+ await fs.mkdir(path.join(repoPath, 'new-dir'), { recursive: true });+ await fs.writeFile(path.join(repoPath, 'new-dir', 'a.txt'), 'alpha\n');++ const current = await readStatus(baseScope);+ const diff = (await readDiffs(current.scope, current)).unstaged.find((item) => item.path === 'new-dir/a.txt');+ expect(diff).toMatchObject({+ path: 'new-dir/a.txt',+ oldPath: null,+ status: 'untracked',+ });++ const target = parseTarget(JSON.parse(JSON.stringify({+ source: 'unstaged',+ path: diff!.path,+ oldPath: diff!.oldPath,+ })));+ const result = await runReviewFileStageOperation('s1', 'stage', [target], deps);++ expect(result.operation.failed).toHaveLength(0);+ expect(result.operation.succeeded).toEqual(['new-dir/a.txt']);+ expect((await runGit(['status', '--porcelain', '--untracked-files=all'], { cwd: repoPath })).stdout)+ .toContain('A new-dir/a.txt');+ });+});++describe('git-review hunk IPC roundtrip', () => {+ async function parseCurrentHunk(+ repoPath: string,+ source: 'staged' | 'unstaged',+ options: ReviewDiffReadOptions,+ ) {+ const baseScope = scope(repoPath);+ const current = await readStatus(baseScope);+ const diff = (await readDiffs(current.scope, current, options))[source][0];+ expect(diff?.hunks[0]).toBeTruthy();++ const payload = JSON.parse(JSON.stringify({+ sessionId: 's1',+ diff,+ hunkIndex: diff.hunks[0].index,+ ignoreWhitespace: options.ignoreWhitespace,+ }));+ const parsed = parseHunkPayload(payload);+ expect(parsed.diff.index).toEqual(diff.index);+ expect(parsed.diff.index.oldOid ?? parsed.diff.index.newOid).toMatch(/^[0-9a-f]{4,64}$/i);+ return { baseScope, parsed };+ }++ it('keeps abbreviated index oids fresh through hunk stage, unstage, and discard IPC parsing', async () => {+ const repoPath = await initRepo();+ const baseScope = scope(repoPath);+ const deps = gitDeps(baseScope);+ await fs.writeFile(path.join(repoPath, 'seed.txt'), 'changed\n');++ let parsed = (await parseCurrentHunk(repoPath, 'unstaged', {})).parsed;+ await runReviewHunkStageOperation('s1', 'stage', parsed.diff, parsed.hunkIndex, parsed.options, deps);+ expect((await runGit(['diff', '--cached', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+changed');++ parsed = (await parseCurrentHunk(repoPath, 'staged', {})).parsed;+ await runReviewHunkStageOperation('s1', 'unstage', parsed.diff, parsed.hunkIndex, parsed.options, deps);+ expect((await runGit(['diff', '--cached', '--', 'seed.txt'], { cwd: repoPath })).stdout).toBe('');+ expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+changed');++ parsed = (await parseCurrentHunk(repoPath, 'unstaged', {})).parsed;+ await runReviewHunkStageOperation('s1', 'discard', parsed.diff, parsed.hunkIndex, parsed.options, deps);+ expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toBe('');+ expect(await fs.readFile(path.join(repoPath, 'seed.txt'), 'utf8')).toBe('seed\n');+ });++ it('keeps hidden-whitespace hunk IPC operations fresh without dropping whitespace-only edits', async () => {+ const repoPath = await initRepo();+ const baseScope = scope(repoPath);+ const deps = gitDeps(baseScope);+ await fs.writeFile(path.join(repoPath, 'seed.txt'), 'one\nalpha\nkeep = 1;\nbeta\ngamma\n');+ await runGit(['add', 'seed.txt'], { cwd: repoPath });+ await runGit(['commit', '--no-gpg-sign', '-m', 'whitespace fixture'], { cwd: repoPath });+ await fs.writeFile(path.join(repoPath, 'seed.txt'), 'one\nalpha\nkeep = 2;\n beta\ngamma\n');++ let parsed = (await parseCurrentHunk(repoPath, 'unstaged', { ignoreWhitespace: true })).parsed;+ await runReviewHunkStageOperation('s1', 'stage', parsed.diff, parsed.hunkIndex, parsed.options, deps);+ expect((await runGit(['diff', '--cached', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+keep = 2;');+ expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+ beta');++ parsed = (await parseCurrentHunk(repoPath, 'staged', { ignoreWhitespace: true })).parsed;+ await runReviewHunkStageOperation('s1', 'unstage', parsed.diff, parsed.hunkIndex, parsed.options, deps);+ expect((await runGit(['diff', '--cached', '--', 'seed.txt'], { cwd: repoPath })).stdout).toBe('');+ expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+keep = 2;');+ expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+ beta');++ parsed = (await parseCurrentHunk(repoPath, 'unstaged', { ignoreWhitespace: true })).parsed;+ await runReviewHunkStageOperation('s1', 'discard', parsed.diff, parsed.hunkIndex, parsed.options, deps);+ const worktree = await fs.readFile(path.join(repoPath, 'seed.txt'), 'utf8');+ expect(worktree).toContain('keep = 1;');+ expect(worktree).toContain(' beta');+ const remaining = (await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout;+ expect(remaining).toContain('+ beta');+ expect(remaining).not.toContain('+keep = 2;');+ });++ it('rejects modified rename hunk unstage after IPC parsing without splitting the rename', async () => {+ const repoPath = await initRepo();+ const baseScope = scope(repoPath);+ const deps = gitDeps(baseScope);+ await runGit(['config', 'diff.renames', 'false'], { cwd: repoPath });+ await fs.writeFile(path.join(repoPath, 'seed.txt'), 'one\ntwo\nthree\n');+ await runGit(['add', 'seed.txt'], { cwd: repoPath });+ await runGit(['commit', '--no-gpg-sign', '-m', 'rename fixture'], { cwd: repoPath });+ await runGit(['mv', 'seed.txt', 'renamed.txt'], { cwd: repoPath });+ await fs.writeFile(path.join(repoPath, 'renamed.txt'), 'one\nTWO\nthree\n');+ await runGit(['add', '-A'], { cwd: repoPath });++ const current = await readStatus(baseScope);+ const diff = (await readDiffs(current.scope, current)).staged.find((item) => item.path === 'renamed.txt');+ expect(diff).toMatchObject({+ path: 'renamed.txt',+ oldPath: 'seed.txt',+ status: 'renamed',+ });+ expect(diff?.hunks[0]).toBeTruthy();++ const payload = JSON.parse(JSON.stringify({+ sessionId: 's1',+ diff,+ hunkIndex: diff!.hunks[0].index,+ }));+ const parsed = parseHunkPayload(payload);++ await expect(runReviewHunkStageOperation(+ 's1',+ 'unstage',+ parsed.diff,+ parsed.hunkIndex,+ parsed.options,+ deps,+ )).rejects.toThrow(/\[PRECONDITION_FAILED\].*rename/s);++ const cachedNameStatus = (await runGit(['diff', '--cached', '--name-status', '-M'], { cwd: repoPath })).stdout;+ expect(cachedNameStatus).toContain('R');+ expect(cachedNameStatus).toContain('seed.txt');+ expect(cachedNameStatus).toContain('renamed.txt');+ expect((await runGit(['status', '--porcelain', '--renames'], { cwd: repoPath })).stdout).not.toContain('?? renamed.txt');+ });+});diff --git a/apps/desktop/src/main/git-review/__tests__/ipc.test.ts b/apps/desktop/src/main/git-review/__tests__/ipc.test.tsindex 9ed40fe0e0..7102653c7f 100644--- a/apps/desktop/src/main/git-review/__tests__/ipc.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/ipc.test.ts@@ -1,24 +1,4 @@-import { promises as fs, symlinkSync, unlinkSync } from 'node:fs';-import os from 'node:os';-import path from 'node:path';--import { afterEach, describe, expect, it, vi } from 'vitest';--// Windows 上 git 子进程明显更慢;完整 workspace 并发测试时,hunk 的多步-// stage/unstage/discard 编排会超过 30s,给真实 Git 集成用例留足余量。-vi.setConfig({ testTimeout: 60_000 });--// Windows 未开发者模式/无特权时创建文件 symlink 会 EPERM;探测一次,不可用则跳过 symlink 用例。-const canSymlink = (() => {- const probe = path.join(os.tmpdir(), `xdt-symlink-probe-${process.pid}-${Math.random().toString(36).slice(2, 8)}`);- try {- symlinkSync(`${probe}-target`, probe, 'file');- unlinkSync(probe);- return true;- } catch {- return false;- }-})();+import { describe, expect, it, vi } from 'vitest';import {parseCommitDiffPayload,@@ -27,16 +7,10 @@ import {parseMarkdownPreviewPayload,parseOpenFilePayload,parseTarget,- openReviewFile,runReviewFileStageOperation,- runReviewHunkStageOperation,} from '../ipc';-import { readDiffs } from '../diffReader';-import { runGit } from '../gitRunner';-import { readStatus } from '../statusReader';-import type { FileDiff, GitReviewDeps, ReviewDiffReadOptions, ReviewScope } from '../types';+import type { FileDiff, GitReviewDeps } from '../types';-const repos: string[] = [];const HEX_OID = '0123456789abcdef0123456789abcdef01234567';const SHORT_HEX_OID = 'abc1234';@@ -58,61 +32,23 @@ function baseDiff(patch: Partial<FileDiff> = {}): FileDiff {index: { oldOid: null, newOid: null },rawHeader: '',rawPatch: '',- hunks: [{ index: 0, header: '@@ -1 +1 @@', oldStart: 1, oldLines: 1, newStart: 1, newLines: 1, section: '', lines: [], selectableLines: [], raw: '' }],+ hunks: [{+ index: 0,+ header: '@@ -1 +1 @@',+ oldStart: 1,+ oldLines: 1,+ newStart: 1,+ newLines: 1,+ section: '',+ lines: [],+ selectableLines: [],+ raw: '',+ }],error: null,...patch,};}-async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-ipc-'));- repos.push(dir);- await runGit(['init', '-b', 'main'], { cwd: dir });- await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });- await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });- await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });- // 测试内容显式用 LF 断言;屏蔽全局 autocrlf=true(Windows 默认)对 checkout/apply 的换行改写。- await runGit(['config', 'core.autocrlf', 'false'], { cwd: dir });- await fs.writeFile(path.join(dir, 'seed.txt'), 'seed\n');- await runGit(['add', 'seed.txt'], { cwd: dir });- await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });- return dir;-}--function gitDeps(baseScope: ReviewScope): GitReviewDeps {- return {- resolveScope: vi.fn(async () => baseScope),- readStatus,- readDiffs,- isSessionRunning: () => false,- };-}--function scope(repoPath: string): ReviewScope {- return {- sessionId: 's1',- workdir: repoPath,- worktreePath: repoPath,- workingDir: repoPath,- repoRoot: repoPath,- branch: 'main',- headOid: null,- isDetached: false,- isUnborn: false,- source: 'worktree',- aheadBehind: { ahead: 0, behind: 0, upstream: null, stale: true },- disabledReason: null,- disabledMessage: null,- resolutionChain: [],- };-}--afterEach(async () => {- await Promise.all(repos.splice(0).map((repoPath) =>- fs.rm(repoPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }),- ));-});-describe('git-review IPC payload guards', () => {it('rejects unsafe file targets before write operations reach stageOps', () => {expect(() => parseTarget({ source: 'unstaged', path: '../secret.txt' })).toThrow(/\[INVALID_PARAMS\]/);@@ -190,64 +126,8 @@ describe('git-review IPC payload guards', () => {});});-describe('git-review scoped open file', () => {- it('opens safe worktree files after IPC parsing and realpath containment checks', async () => {- const repoPath = await initRepo();- const filePath = path.join(repoPath, 'huge.txt');- await fs.writeFile(filePath, 'large file placeholder\n');- const openPath = vi.fn(async () => '');- const parsed = parseOpenFilePayload(JSON.parse(JSON.stringify({- sessionId: 's1',- path: 'huge.txt',- })));-- await openReviewFile(parsed.sessionId, parsed.path, { resolveScope: vi.fn(async () => scope(repoPath)) }, openPath);-- expect(openPath).toHaveBeenCalledWith(await fs.realpath(filePath));- });-- it('rejects missing worktree files without calling shell.openPath', async () => {- const repoPath = await initRepo();- const openPath = vi.fn(async () => '');- const parsed = parseOpenFilePayload({- sessionId: 's1',- path: 'missing.txt',- });-- await expect(openReviewFile(- parsed.sessionId,- parsed.path,- { resolveScope: vi.fn(async () => scope(repoPath)) },- openPath,- )).rejects.toThrow(/\[PRECONDITION_FAILED\].*does not exist/);- expect(openPath).not.toHaveBeenCalled();- });-- it.skipIf(!canSymlink)('rejects symlinks that resolve outside the repository', async () => {- const repoPath = await initRepo();- const outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-outside-'));- repos.push(outsideDir);- const outsideFile = path.join(outsideDir, 'secret.txt');- await fs.writeFile(outsideFile, 'secret\n');- await fs.symlink(outsideFile, path.join(repoPath, 'escape.txt'));- const openPath = vi.fn(async () => '');- const parsed = parseOpenFilePayload({- sessionId: 's1',- path: 'escape.txt',- });-- await expect(openReviewFile(- parsed.sessionId,- parsed.path,- { resolveScope: vi.fn(async () => scope(repoPath)) },- openPath,- )).rejects.toThrow(/\[PRECONDITION_FAILED\].*outside/);- expect(openPath).not.toHaveBeenCalled();- });-});-describe('git-review write busy gate', () => {- it('rejects queued writes while the session is running', async () => {+ it('rejects queued writes before resolving or touching a repository', async () => {const deps: GitReviewDeps = {resolveScope: vi.fn(),readStatus: vi.fn(),@@ -260,171 +140,48 @@ describe('git-review write busy gate', () => {], deps)).rejects.toMatchObject({ code: 'SESSION_RUNNING' });expect(deps.resolveScope).not.toHaveBeenCalled();});-- it('allows normal writes when the session is idle', async () => {- const repoPath = await initRepo();- await fs.writeFile(path.join(repoPath, 'new.txt'), 'new\n');- const baseScope = scope(repoPath);- const deps: GitReviewDeps = {- resolveScope: vi.fn(async () => baseScope),- readStatus,- readDiffs,- isSessionRunning: () => false,- };-- const result = await runReviewFileStageOperation('s1', 'stage', [- { source: 'unstaged', path: 'new.txt', oldPath: null },- ], deps);-- expect(result.operation.failed).toHaveLength(0);- expect(result.operation.succeeded).toEqual(['new.txt']);- expect((await readStatus(baseScope)).files.find((file) => file.path === 'new.txt')?.indexStatus).toBe('added');- });-- it('stages untracked files from expanded directory entries after IPC parsing', async () => {- const repoPath = await initRepo();- const baseScope = scope(repoPath);- const deps = gitDeps(baseScope);- await fs.mkdir(path.join(repoPath, 'new-dir'), { recursive: true });- await fs.writeFile(path.join(repoPath, 'new-dir', 'a.txt'), 'alpha\n');-- const current = await readStatus(baseScope);- const diff = (await readDiffs(current.scope, current)).unstaged.find((item) => item.path === 'new-dir/a.txt');- expect(diff).toMatchObject({- path: 'new-dir/a.txt',- oldPath: null,- status: 'untracked',- });-- const target = parseTarget(JSON.parse(JSON.stringify({- source: 'unstaged',- path: diff!.path,- oldPath: diff!.oldPath,- })));- const result = await runReviewFileStageOperation('s1', 'stage', [target], deps);-- expect(result.operation.failed).toHaveLength(0);- expect(result.operation.succeeded).toEqual(['new-dir/a.txt']);- expect((await runGit(['status', '--porcelain', '--untracked-files=all'], { cwd: repoPath })).stdout)- .toContain('A new-dir/a.txt');- });});-describe('git-review hunk IPC roundtrip', () => {- async function parseCurrentHunk(- repoPath: string,- source: 'staged' | 'unstaged',- options: ReviewDiffReadOptions,- ) {- const baseScope = scope(repoPath);- const current = await readStatus(baseScope);- const diff = (await readDiffs(current.scope, current, options))[source][0];- expect(diff?.hunks[0]).toBeTruthy();-- const payload = JSON.parse(JSON.stringify({+describe('git-review hunk IPC serialization', () => {+ function parseSerializedHunk(diff: FileDiff, ignoreWhitespace = false) {+ return parseHunkPayload(JSON.parse(JSON.stringify({sessionId: 's1',diff,hunkIndex: diff.hunks[0].index,- ignoreWhitespace: options.ignoreWhitespace,- }));- const parsed = parseHunkPayload(payload);- expect(parsed.diff.index).toEqual(diff.index);- expect(parsed.diff.index.oldOid ?? parsed.diff.index.newOid).toMatch(/^[0-9a-f]{4,64}$/i);- return { baseScope, parsed };+ ignoreWhitespace,+ })));}- it('keeps abbreviated index oids fresh through hunk stage, unstage, and discard IPC parsing', async () => {- const repoPath = await initRepo();- const baseScope = scope(repoPath);- const deps = gitDeps(baseScope);- await fs.writeFile(path.join(repoPath, 'seed.txt'), 'changed\n');-- let parsed = (await parseCurrentHunk(repoPath, 'unstaged', {})).parsed;- await runReviewHunkStageOperation('s1', 'stage', parsed.diff, parsed.hunkIndex, parsed.options, deps);- expect((await runGit(['diff', '--cached', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+changed');-- parsed = (await parseCurrentHunk(repoPath, 'staged', {})).parsed;- await runReviewHunkStageOperation('s1', 'unstage', parsed.diff, parsed.hunkIndex, parsed.options, deps);- expect((await runGit(['diff', '--cached', '--', 'seed.txt'], { cwd: repoPath })).stdout).toBe('');- expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+changed');-- parsed = (await parseCurrentHunk(repoPath, 'unstaged', {})).parsed;- await runReviewHunkStageOperation('s1', 'discard', parsed.diff, parsed.hunkIndex, parsed.options, deps);- expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toBe('');- expect(await fs.readFile(path.join(repoPath, 'seed.txt'), 'utf8')).toBe('seed\n');- });-- it('keeps hidden-whitespace hunk IPC operations fresh without dropping whitespace-only edits', async () => {- const repoPath = await initRepo();- const baseScope = scope(repoPath);- const deps = gitDeps(baseScope);- await fs.writeFile(path.join(repoPath, 'seed.txt'), 'one\nalpha\nkeep = 1;\nbeta\ngamma\n');- await runGit(['add', 'seed.txt'], { cwd: repoPath });- await runGit(['commit', '--no-gpg-sign', '-m', 'whitespace fixture'], { cwd: repoPath });- await fs.writeFile(path.join(repoPath, 'seed.txt'), 'one\nalpha\nkeep = 2;\n beta\ngamma\n');-- let parsed = (await parseCurrentHunk(repoPath, 'unstaged', { ignoreWhitespace: true })).parsed;- await runReviewHunkStageOperation('s1', 'stage', parsed.diff, parsed.hunkIndex, parsed.options, deps);- expect((await runGit(['diff', '--cached', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+keep = 2;');- expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+ beta');+ it('preserves abbreviated index oids', () => {+ const diff = baseDiff({+ index: { oldOid: SHORT_HEX_OID, newOid: HEX_OID },+ });- parsed = (await parseCurrentHunk(repoPath, 'staged', { ignoreWhitespace: true })).parsed;- await runReviewHunkStageOperation('s1', 'unstage', parsed.diff, parsed.hunkIndex, parsed.options, deps);- expect((await runGit(['diff', '--cached', '--', 'seed.txt'], { cwd: repoPath })).stdout).toBe('');- expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+keep = 2;');- expect((await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout).toContain('+ beta');+ const parsed = parseSerializedHunk(diff);- parsed = (await parseCurrentHunk(repoPath, 'unstaged', { ignoreWhitespace: true })).parsed;- await runReviewHunkStageOperation('s1', 'discard', parsed.diff, parsed.hunkIndex, parsed.options, deps);- const worktree = await fs.readFile(path.join(repoPath, 'seed.txt'), 'utf8');- expect(worktree).toContain('keep = 1;');- expect(worktree).toContain(' beta');- const remaining = (await runGit(['diff', '--', 'seed.txt'], { cwd: repoPath })).stdout;- expect(remaining).toContain('+ beta');- expect(remaining).not.toContain('+keep = 2;');+ expect(parsed.diff.index).toEqual(diff.index);});- it('rejects modified rename hunk unstage after IPC parsing without splitting the rename', async () => {- const repoPath = await initRepo();- const baseScope = scope(repoPath);- const deps = gitDeps(baseScope);- await runGit(['config', 'diff.renames', 'false'], { cwd: repoPath });- await fs.writeFile(path.join(repoPath, 'seed.txt'), 'one\ntwo\nthree\n');- await runGit(['add', 'seed.txt'], { cwd: repoPath });- await runGit(['commit', '--no-gpg-sign', '-m', 'rename fixture'], { cwd: repoPath });- await runGit(['mv', 'seed.txt', 'renamed.txt'], { cwd: repoPath });- await fs.writeFile(path.join(repoPath, 'renamed.txt'), 'one\nTWO\nthree\n');- await runGit(['add', '-A'], { cwd: repoPath });-- const current = await readStatus(baseScope);- const diff = (await readDiffs(current.scope, current)).staged.find((item) => item.path === 'renamed.txt');- expect(diff).toMatchObject({- path: 'renamed.txt',- oldPath: 'seed.txt',- status: 'renamed',+ it('preserves hidden-whitespace options and line selection', () => {+ const diff = baseDiff({+ hunks: [{+ index: 3,+ header: '@@ -1,2 +1,2 @@',+ oldStart: 1,+ oldLines: 2,+ newStart: 1,+ newLines: 2,+ section: '',+ lines: [],+ selectableLines: [0, 1],+ raw: '',+ }],});- expect(diff?.hunks[0]).toBeTruthy();-- const payload = JSON.parse(JSON.stringify({- sessionId: 's1',- diff,- hunkIndex: diff!.hunks[0].index,- }));- const parsed = parseHunkPayload(payload);- await expect(runReviewHunkStageOperation(- 's1',- 'unstage',- parsed.diff,- parsed.hunkIndex,- parsed.options,- deps,- )).rejects.toThrow(/\[PRECONDITION_FAILED\].*rename/s);+ const parsed = parseSerializedHunk(diff, true);- const cachedNameStatus = (await runGit(['diff', '--cached', '--name-status', '-M'], { cwd: repoPath })).stdout;- expect(cachedNameStatus).toContain('R');- expect(cachedNameStatus).toContain('seed.txt');- expect(cachedNameStatus).toContain('renamed.txt');- expect((await runGit(['status', '--porcelain', '--renames'], { cwd: repoPath })).stdout).not.toContain('?? renamed.txt');+ expect(parsed.hunkIndex).toBe(3);+ expect(parsed.options).toEqual({ ignoreWhitespace: true });+ expect(parsed.diff.hunks[0].selectableLines).toEqual([0, 1]);});});diff --git a/apps/desktop/src/main/git-review/__tests__/markdownReader.test.ts b/apps/desktop/src/main/git-review/__tests__/markdownReader.git-integration.test.tssimilarity index 97%rename from apps/desktop/src/main/git-review/__tests__/markdownReader.test.tsrename to apps/desktop/src/main/git-review/__tests__/markdownReader.git-integration.test.tsindex 0261cab779..874ffa4adf 100644--- a/apps/desktop/src/main/git-review/__tests__/markdownReader.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/markdownReader.git-integration.test.ts@@ -1,11 +1,11 @@import { promises as fs } from 'node:fs';-import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// Windows 上 git 子进程明显更慢(每次 spawn 数百毫秒),多步 git 编排用例会超默认 5s。vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });+import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';import { readBranchDiff } from '../branchReader';import { readCommitDiff } from '../commitReader';import { readDiffs } from '../diffReader';@@ -21,8 +21,7 @@ import type { FileDiff, ReviewScope } from '../types';let repoPath: string;-async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-markdown-'));+const repoTemplate = new TestDirectoryTemplate('xdt-git-review-markdown-', async (dir) => {await runGit(['init', '-b', 'main'], { cwd: dir });await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });@@ -30,8 +29,7 @@ async function initRepo(): Promise<string> {await fs.writeFile(path.join(dir, 'seed.txt'), 'seed\n');await runGit(['add', 'seed.txt'], { cwd: dir });await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });- return dir;-}+});function scope(branch = 'main'): ReviewScope {return {@@ -108,13 +106,17 @@ function fakeMarkdownDiff(patch: Partial<FileDiff> = {}): FileDiff {}beforeEach(async () => {- repoPath = await initRepo();+ repoPath = await repoTemplate.createCopy();});afterEach(async () => {await fs.rm(repoPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('git-review markdownReader', () => {it('recognizes markdown diffs and excludes deleted/binary/large files', () => {expect(isPreviewableMarkdownDiff(fakeMarkdownDiff({ path: 'README.MD' }))).toBe(true);diff --git a/apps/desktop/src/main/git-review/__tests__/patchFormatter.test.ts b/apps/desktop/src/main/git-review/__tests__/patchFormatter.git-integration.test.tssimilarity index 94%rename from apps/desktop/src/main/git-review/__tests__/patchFormatter.test.tsrename to apps/desktop/src/main/git-review/__tests__/patchFormatter.git-integration.test.tsindex 107cb67f11..cc0973dbf8 100644--- a/apps/desktop/src/main/git-review/__tests__/patchFormatter.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/patchFormatter.git-integration.test.ts@@ -1,11 +1,11 @@import { promises as fs } from 'node:fs';-import os from 'node:os';import path from 'node:path';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });+import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';import { parseGitDiff } from '../diffParser';import { formatPatchForSelection, PatchFormatError } from '../patchFormatter';import { runGit } from '../gitRunner';@@ -13,6 +13,15 @@ import type { DiffSelection, FileDiff } from '../types';const repos: string[] = [];+const repoTemplate = new TestDirectoryTemplate('xdt-git-review-patch-', async (dir) => {+ await runGit(['init', '-b', 'main'], { cwd: dir });+ await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });+ await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });+ await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });+ // 测试内容显式用 LF 断言;屏蔽全局 autocrlf=true(Windows 默认)对 checkout/apply 的换行改写。+ await runGit(['config', 'core.autocrlf', 'false'], { cwd: dir });+});+function parse(raw: string, path = 'file.txt'): FileDiff {return parseGitDiff(raw, { source: 'unstaged', pathHint: path, kind: 'text' });}@@ -22,14 +31,8 @@ function select(hunkIndex: number, lineIndices: number[]): DiffSelection {}async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-patch-'));+ const dir = await repoTemplate.createCopy();repos.push(dir);- await runGit(['init', '-b', 'main'], { cwd: dir });- await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });- await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });- await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });- // 测试内容显式用 LF 断言;屏蔽全局 autocrlf=true(Windows 默认)对 checkout/apply 的换行改写。- await runGit(['config', 'core.autocrlf', 'false'], { cwd: dir });return dir;}@@ -58,6 +61,10 @@ afterEach(async () => {));});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('git-review patchFormatter', () => {it('turns an unselected delete before a selected add into context', () => {const diff = parse([diff --git a/apps/desktop/src/main/git-review/__tests__/pushOps.test.ts b/apps/desktop/src/main/git-review/__tests__/pushOps.git-integration.test.tssimilarity index 97%rename from apps/desktop/src/main/git-review/__tests__/pushOps.test.tsrename to apps/desktop/src/main/git-review/__tests__/pushOps.git-integration.test.tsindex 5fc4411f85..e2760fca85 100644--- a/apps/desktop/src/main/git-review/__tests__/pushOps.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/pushOps.git-integration.test.ts@@ -2,10 +2,11 @@ import { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';// Windows 上 git 子进程明显更慢(每次 spawn 数百毫秒),多步 git 编排用例会超默认 5s。vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });+import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';import { runGit } from '../gitRunner';import { GitReviewPushError, pushBranch } from '../pushOps';import { readStatus } from '../statusReader';@@ -13,6 +14,16 @@ import type { ReviewScope, ReviewStatus } from '../types';const roots: string[] = [];+const repoTemplate = new TestDirectoryTemplate('xdt-git-review-push-', async (dir) => {+ await runGit(['init', '-b', 'main'], { cwd: dir });+ await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });+ await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });+ await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });+ await fs.writeFile(path.join(dir, 'file.txt'), 'one\n');+ await runGit(['add', 'file.txt'], { cwd: dir });+ await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });+});+async function mkTemp(prefix: string): Promise<string> {const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));roots.push(dir);@@ -26,15 +37,8 @@ async function initBareRemote(): Promise<string> {}async function initRepo(): Promise<string> {- const dir = await mkTemp('xdt-git-review-push-');- await runGit(['init'], { cwd: dir });- await runGit(['symbolic-ref', 'HEAD', 'refs/heads/main'], { cwd: dir });- await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });- await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });- await runGit(['config', 'commit.gpgsign', 'false'], { cwd: dir });- await fs.writeFile(path.join(dir, 'file.txt'), 'one\n');- await runGit(['add', 'file.txt'], { cwd: dir });- await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });+ const dir = await repoTemplate.createCopy();+ roots.push(dir);return dir;}@@ -102,6 +106,10 @@ afterEach(async () => {));});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('git-review pushOps', () => {it('sets upstream on first push', async () => {const remotePath = await initBareRemote();diff --git a/apps/desktop/src/main/git-review/__tests__/stageOps.test.ts b/apps/desktop/src/main/git-review/__tests__/stageOps.git-integration.test.tssimilarity index 93%rename from apps/desktop/src/main/git-review/__tests__/stageOps.test.tsrename to apps/desktop/src/main/git-review/__tests__/stageOps.git-integration.test.tsindex a2bfc51cdb..554b8d910e 100644--- a/apps/desktop/src/main/git-review/__tests__/stageOps.test.ts+++ b/apps/desktop/src/main/git-review/__tests__/stageOps.git-integration.test.ts@@ -2,10 +2,11 @@ import { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';vi.setConfig({ testTimeout: process.platform === 'win32' ? 60_000 : 30_000 });+import { TestDirectoryTemplate } from '../../../test/vitest/testDirectoryTemplate';import { readDiffs, readFileDiff } from '../diffReader';import { runGit } from '../gitRunner';import { applyFileBatch, applyHunkSelection, GitReviewStageError } from '../stageOps';@@ -14,8 +15,7 @@ import type { DiffSelection, FileDiff, ReviewDiffReadOptions, ReviewFileTarget,let repoPath: string;-async function initRepo(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-git-review-stage-'));+const repoTemplate = new TestDirectoryTemplate('xdt-git-review-stage-', async (dir) => {await runGit(['init'], { cwd: dir });await runGit(['config', 'user.email', '[email protected]'], { cwd: dir });await runGit(['config', 'user.name', 'XDT Test'], { cwd: dir });@@ -25,8 +25,7 @@ async function initRepo(): Promise<string> {await fs.writeFile(path.join(dir, 'file.txt'), 'one\ntwo\nthree\n');await runGit(['add', 'file.txt'], { cwd: dir });await runGit(['commit', '--no-gpg-sign', '-m', 'seed'], { cwd: dir });- return dir;-}+});function scope(): ReviewScope {return {@@ -116,13 +115,17 @@ async function tryCreateDirSymlink(target: string, linkPath: string): Promise<bo}beforeEach(async () => {- repoPath = await initRepo();+ repoPath = await repoTemplate.createCopy();});afterEach(async () => {await fs.rm(repoPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });});+afterAll(async () => {+ await repoTemplate.dispose();+});+describe('git-review stageOps', () => {it('stages and unstages whole files', async () => {await fs.writeFile(path.join(repoPath, 'file.txt'), 'one\nTWO\nthree\n');@@ -152,12 +155,12 @@ describe('git-review stageOps', () => {expect((await runGit(['diff', '--', 'file.txt'], { cwd: repoPath })).stdout).toContain('+ONE');});- it('applies hidden-whitespace hunk operations without dropping whitespace-only edits', async () => {+ it('stages substantive hunks without dropping hidden whitespace-only edits', async () => {await seedWhitespaceFixture();await writeSubstantiveAndWhitespaceChanges();- let current = await status();- let unstaged = (await diffs({ ignoreWhitespace: true })).unstaged[0];+ const current = await status();+ const unstaged = (await diffs({ ignoreWhitespace: true })).unstaged[0];expect(unstaged.hunks).toHaveLength(1);await applyHunkSelection(scope(), current, 'stage', unstaged, selectHunk(unstaged), { ignoreWhitespace: true });@@ -165,33 +168,39 @@ describe('git-review stageOps', () => {const afterStageWorktree = (await runGit(['diff', '--', 'file.txt'], { cwd: repoPath })).stdout;expect(afterStageWorktree).not.toContain('+keep = 2;');expect(afterStageWorktree).toContain('+ beta');+ });- current = await status();- let staged = (await diffs({ ignoreWhitespace: true })).staged[0];+ it('unstages substantive hunks without dropping hidden whitespace-only edits', async () => {+ await seedWhitespaceFixture();+ await writeSubstantiveAndWhitespaceChanges();+ await runGit(['add', 'file.txt'], { cwd: repoPath });++ const current = await status();+ const staged = (await diffs({ ignoreWhitespace: true })).staged[0];await applyHunkSelection(scope(), current, 'unstage', staged, selectHunk(staged), { ignoreWhitespace: true });- expect((await runGit(['diff', '--cached', '--', 'file.txt'], { cwd: repoPath })).stdout).toBe('');- expect((await runGit(['diff', '--', 'file.txt'], { cwd: repoPath })).stdout).toContain('+keep = 2;');- expect((await runGit(['diff', '--', 'file.txt'], { cwd: repoPath })).stdout).toContain('+ beta');- current = await status();- unstaged = (await diffs({ ignoreWhitespace: true })).unstaged[0];+ const cachedWhitespaceOnly = (await runGit(['diff', '--cached', '--', 'file.txt'], { cwd: repoPath })).stdout;+ expect(cachedWhitespaceOnly).not.toContain('+keep = 2;');+ expect(cachedWhitespaceOnly).toContain('+ beta');+ const worktree = (await runGit(['diff', '--', 'file.txt'], { cwd: repoPath })).stdout;+ expect(worktree).toContain('+keep = 2;');+ expect(worktree).not.toContain('+ beta');+ });++ it('discards substantive hunks without dropping hidden whitespace-only edits', async () => {+ await seedWhitespaceFixture();+ await writeSubstantiveAndWhitespaceChanges();++ const current = await status();+ const unstaged = (await diffs({ ignoreWhitespace: true })).unstaged[0];await applyHunkSelection(scope(), current, 'discard', unstaged, selectHunk(unstaged), { ignoreWhitespace: true });+const afterDiscard = await fs.readFile(path.join(repoPath, 'file.txt'), 'utf8');expect(afterDiscard).toContain('keep = 1;');expect(afterDiscard).toContain(' beta');const remainingDiff = (await runGit(['diff', '--', 'file.txt'], { cwd: repoPath })).stdout;expect(remainingDiff).not.toContain('+keep = 2;');expect(remainingDiff).toContain('+ beta');-- await runGit(['reset', '--hard', 'HEAD'], { cwd: repoPath });- await writeSubstantiveAndWhitespaceChanges();- await runGit(['add', 'file.txt'], { cwd: repoPath });- current = await status();- staged = (await diffs({ ignoreWhitespace: true })).staged[0];- await applyHunkSelection(scope(), current, 'unstage', staged, selectHunk(staged), { ignoreWhitespace: true });- const cachedWhitespaceOnly = (await runGit(['diff', '--cached', '--', 'file.txt'], { cwd: repoPath })).stdout;- expect(cachedWhitespaceOnly).not.toContain('+keep = 2;');- expect(cachedWhitespaceOnly).toContain('+ beta');});it('supports partial staging and partial/full unstaging of new files', async () => {diff --git a/apps/desktop/src/main/hook-control/__tests__/paths.test.ts b/apps/desktop/src/main/hook-control/__tests__/paths.test.tsindex 662f3f0e1e..aa84fd089c 100644--- a/apps/desktop/src/main/hook-control/__tests__/paths.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/paths.test.ts@@ -42,18 +42,18 @@ describe('isPathWithin', () => {expect(isPathWithin(process.cwd(), '')).toBe(false);});- it('大小写: Windows 不敏感, 其它平台敏感(规则 15)', () => {- // 路径格式和 path 实现都按目标平台构造,避免宿主系统语义污染模拟分支。- const windowsBase = path.win32.resolve('C:\\repos\\demo');- expect(- isPathWithin(windowsBase, path.win32.join(windowsBase.toUpperCase(), 'SUB'), 'win32'),- ).toBe(true);- expect(isPathWithin(windowsBase.toUpperCase(), windowsBase, 'win32')).toBe(true);-- const posixBase = path.posix.resolve('/repos/demo');- expect(isPathWithin(posixBase, path.posix.join(posixBase.toUpperCase(), 'SUB'), 'linux')).toBe(- false,- );- expect(isPathWithin(posixBase.toUpperCase(), posixBase, 'linux')).toBe(false);+ it('Windows 路径在任意 CI 主机上都按大小写不敏感和 win32 分隔符判定', () => {+ const windowsBase = 'C:\\Repos\\Demo';+ expect(isPathWithin(windowsBase, 'c:\\repos\\demo', 'win32')).toBe(true);+ expect(isPathWithin(windowsBase, 'c:\\REPOS\\DEMO\\sub', 'win32')).toBe(true);+ expect(isPathWithin(windowsBase, 'C:\\Repos\\Demo-2', 'win32')).toBe(false);+ expect(isPathWithin(windowsBase, 'C:\\Repos\\Demo\\sub\\..\\..\\outside', 'win32')).toBe(false);+ });++ it('POSIX 路径在任意 CI 主机上都保持大小写敏感', () => {+ const posixBase = '/repos/demo';+ expect(isPathWithin(posixBase, '/repos/demo/sub', 'linux')).toBe(true);+ expect(isPathWithin(posixBase, '/REPOS/DEMO/sub', 'linux')).toBe(false);+ expect(isPathWithin('/REPOS/DEMO', posixBase, 'darwin')).toBe(false);});});diff --git a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.tsindex 9e455891e1..bd4e85877a 100644--- a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts@@ -60,15 +60,18 @@ describe('WorkerThreadTransport', () => {useInlineWorker: true,maxInFlightRpcs: 1,maxQueuedRpcs: 1,- rpcTimeoutMs: 100,+ // Leave enough startup/scheduling headroom for Windows worker threads;+ // the assertion below still verifies that queue wait consumes the+ // request's total budget.+ rpcTimeoutMs: 500,});const startedAt = Date.now();try {- const active = transport.send('sleep', { ms: 70 });- const queued = transport.send('sleep', { ms: 100 });- await expect(active).resolves.toEqual({ slept: 70 });+ const active = transport.send('sleep', { ms: 200 });+ const queued = transport.send('sleep', { ms: 400 });+ await expect(active).resolves.toEqual({ slept: 200 });await expect(queued).rejects.toThrow(/RPC timeout/);- expect(Date.now() - startedAt).toBeLessThan(140);+ expect(Date.now() - startedAt).toBeLessThan(700);} finally {await transport.close();}diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-artifacts.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-artifacts.test.tsindex 1cfd48d857..ca00982a8e 100644--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-artifacts.test.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/rsb-webview-artifacts.test.ts@@ -64,6 +64,13 @@ function downloadItem(let root = '';+// Most cases exercise handling after a known download event, not the production+// grace window. Keep those cases deterministic; the delayed-start case opts+// into a short non-zero window to preserve that separate timing contract.+function createArtifacts(downloadGraceMs = 0): RsbWebviewArtifacts {+ return new RsbWebviewArtifacts(() => root, { warn: vi.fn() }, downloadGraceMs);+}+beforeEach(() => {root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-browser-artifact-test-'));});@@ -78,7 +85,7 @@ describe('RsbWebviewArtifacts', () => {await fs.promises.mkdir(staleRoot, { recursive: true });await fs.promises.writeFile(path.join(staleRoot, 'stale.txt'), 'stale');const harness = artifactHarness();- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() }, 0);+ const artifacts = createArtifacts();await artifacts.capture(harness.wc,@@ -92,7 +99,7 @@ describe('RsbWebviewArtifacts', () => {it('stores a completed download in an isolated directory with a safe name', async () => {const harness = artifactHarness();const item = downloadItem('completed');- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();const result = await artifacts.capture(harness.wc,@@ -119,7 +126,7 @@ describe('RsbWebviewArtifacts', () => {it('removes partial files after a cancelled download', async () => {const harness = artifactHarness();const item = downloadItem('cancelled');- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();const result = await artifacts.capture(harness.wc,@@ -137,7 +144,7 @@ describe('RsbWebviewArtifacts', () => {it('does not intercept downloads outside an active agent action', async () => {const harness = artifactHarness();- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();await artifacts.capture(harness.wc, { sessionId: 'session-three' }, async () => undefined);const item = downloadItem('completed');@@ -149,16 +156,16 @@ describe('RsbWebviewArtifacts', () => {it('captures a download that starts after the action returns', async () => {const harness = artifactHarness();const item = downloadItem('completed');- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts(100);const result = await artifacts.capture(harness.wc,- { sessionId: 'delayed-download', timeoutMs: 2_000 },+ { sessionId: 'delayed-download', timeoutMs: 1_000 },async () => {setTimeout(() => {harness.emitDownload(item);setTimeout(() => item.finish(), 0);- }, 300);+ }, 10);return 'clicked';},);@@ -169,7 +176,7 @@ describe('RsbWebviewArtifacts', () => {it('limits artifact diagnostics to the requested session', async () => {const harness = artifactHarness();- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();for (const sessionId of ['session-a', 'session-b']) {const item = downloadItem('completed');@@ -191,7 +198,7 @@ describe('RsbWebviewArtifacts', () => {it('cancels a download that exceeds the per-file quota before saving', async () => {const harness = artifactHarness();const item = downloadItem('cancelled', { totalBytes: 32 * 1024 * 1024 + 1 });- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();const result = await artifacts.capture(harness.wc,@@ -210,7 +217,7 @@ describe('RsbWebviewArtifacts', () => {it('cancels a download that crosses the quota while streaming', async () => {const harness = artifactHarness();const item = downloadItem('cancelled', { totalBytes: 0, receivedBytes: 0 });- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();const result = await artifacts.capture(harness.wc,@@ -233,7 +240,7 @@ describe('RsbWebviewArtifacts', () => {const items = Array.from({ length: 4 }, () => (downloadItem('completed', { totalBytes: 16 * 1024 * 1024 })));- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();const result = await artifacts.capture(harness.wc,@@ -261,7 +268,7 @@ describe('RsbWebviewArtifacts', () => {const items = Array.from({ length: 9 }, () => (downloadItem('completed', { totalBytes: 20 * 1024 * 1024 })));- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();const result = await artifacts.capture(harness.wc,@@ -288,7 +295,7 @@ describe('RsbWebviewArtifacts', () => {downloadItem('completed', { totalBytes: 32 * 1024 * 1024 }),downloadItem('completed', { totalBytes: 32 * 1024 * 1024 }),];- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();const result = await artifacts.capture(harness.wc,@@ -314,7 +321,7 @@ describe('RsbWebviewArtifacts', () => {it('removes retained artifacts when the backend is disposed', async () => {const harness = artifactHarness();const item = downloadItem('completed');- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() });+ const artifacts = createArtifacts();const result = await artifacts.capture(harness.wc,@@ -333,7 +340,7 @@ describe('RsbWebviewArtifacts', () => {it('evicts the oldest files when retained bytes exceed the global budget', async () => {const harness = artifactHarness();- const artifacts = new RsbWebviewArtifacts(() => root, { warn: vi.fn() }, 0);+ const artifacts = createArtifacts();const savedPaths: string[] = [];for (let captureIndex = 0; captureIndex < 5; captureIndex += 1) {diff --git a/apps/desktop/src/test/vitest/cliExclude.ts b/apps/desktop/src/test/vitest/cliExclude.tsnew file mode 100644index 0000000000..9aa2531668--- /dev/null+++ b/apps/desktop/src/test/vitest/cliExclude.ts@@ -0,0 +1,21 @@+export function parseVitestCliExclude(args: readonly string[]): string[] {+ const patterns: string[] = [];++ for (let index = 0; index < args.length; index += 1) {+ const arg = args[index];+ if (arg === '--exclude') {+ const pattern = args[index + 1];+ if (pattern && !pattern.startsWith('--')) {+ patterns.push(pattern);+ index += 1;+ }+ continue;+ }+ if (arg.startsWith('--exclude=')) {+ const pattern = arg.slice('--exclude='.length);+ if (pattern) patterns.push(pattern);+ }+ }++ return patterns;+}diff --git a/apps/desktop/src/test/vitest/desktopTestResourceLock.ts b/apps/desktop/src/test/vitest/desktopTestResourceLock.tsnew file mode 100644index 0000000000..9cfb76cd7f--- /dev/null+++ b/apps/desktop/src/test/vitest/desktopTestResourceLock.ts@@ -0,0 +1,197 @@+import { createHash } from 'node:crypto';+import { promises as fs } from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const LOCK_HOST = '127.0.0.1';+const LOCK_PORT_START = 49_152;+const LOCK_PORT_COUNT = 16_000;+const LOCK_PORT_CANDIDATES = 32;+const RETRY_DELAY_MS = 250;+const PROBE_TIMEOUT_MS = 1_000;+const LOCK_PROTOCOL = 'cindy-desktop-test-lock-v1';+const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..', '..');++interface DesktopTestLock {+ port: number;+ release: () => Promise<void>;+}++export type DesktopTestLockProbeResult = 'owner' | 'retry' | 'collision';++export type DesktopTestLockDecision =+ | { type: 'wait' }+ | { type: 'acquire'; port: number }+ | { type: 'unavailable' };++export function classifyDesktopTestLockProbeError(+ code: string | undefined,+): DesktopTestLockProbeResult {+ return code === 'ECONNREFUSED' ? 'retry' : 'collision';+}++/**+ * Decide only after every deterministic candidate has been probed. An owner+ * can be on a fallback port because an earlier unrelated service occupied the+ * primary port when it started; taking a now-free earlier port before checking+ * the fallbacks would split the shared budget between two worktrees.+ */+export function decideDesktopTestLock(+ probes: readonly { port: number; result: DesktopTestLockProbeResult }[],+): DesktopTestLockDecision {+ if (probes.some(({ result }) => result === 'owner')) return { type: 'wait' };+ const available = probes.find(({ result }) => result === 'retry');+ return available ? { type: 'acquire', port: available.port } : { type: 'unavailable' };+}++function delay(durationMs: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, durationMs));+}++async function resolveGitCommonDir(repoRoot: string): Promise<string> {+ const dotGitPath = path.join(repoRoot, '.git');+ let dotGitStat;+ try {+ dotGitStat = await fs.stat(dotGitPath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ // Source archives and exported checkouts may not carry Git metadata.+ // They still get a stable per-checkout lock instead of failing test setup.+ return fs.realpath(repoRoot);+ }+ if (dotGitStat.isDirectory()) return fs.realpath(dotGitPath);++ const gitDirLine = (await fs.readFile(dotGitPath, 'utf8')).trim();+ const gitDirMatch = /^gitdir:\s*(.+)$/i.exec(gitDirLine);+ if (!gitDirMatch) throw new Error(`Invalid gitdir file: ${dotGitPath}`);+ const gitDir = path.resolve(repoRoot, gitDirMatch[1]);+ try {+ const commonDir = (await fs.readFile(path.join(gitDir, 'commondir'), 'utf8')).trim();+ return fs.realpath(path.resolve(gitDir, commonDir));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ return fs.realpath(gitDir);+ }+}++function lockIdentity(commonDir: string): string {+ const normalized = process.platform === 'win32' ? commonDir.toLowerCase() : commonDir;+ return createHash('sha256').update(normalized).digest('hex');+}++function lockPort(identity: string, candidate: number): number {+ const baseOffset = Number.parseInt(identity.slice(0, 8), 16) % LOCK_PORT_COUNT;+ return LOCK_PORT_START + ((baseOffset + candidate) % LOCK_PORT_COUNT);+}++function listen(server: net.Server, port: number): Promise<void> {+ return new Promise((resolve, reject) => {+ const onError = (error: Error) => {+ server.off('listening', onListening);+ reject(error);+ };+ const onListening = () => {+ server.off('error', onError);+ resolve();+ };+ server.once('error', onError);+ server.once('listening', onListening);+ server.listen({ host: LOCK_HOST, port, exclusive: true });+ });+}++function close(server: net.Server): Promise<void> {+ return new Promise((resolve, reject) => {+ server.close((error) => {+ if (error) reject(error);+ else resolve();+ });+ });+}++async function probeLock(port: number, expectedBanner: string): Promise<DesktopTestLockProbeResult> {+ return new Promise((resolve) => {+ const socket = net.createConnection({ host: LOCK_HOST, port });+ let response = '';+ let settled = false;++ const finish = (result: DesktopTestLockProbeResult) => {+ if (settled) return;+ settled = true;+ socket.destroy();+ resolve(result);+ };++ socket.setEncoding('utf8');+ socket.setTimeout(PROBE_TIMEOUT_MS);+ socket.on('data', (chunk) => {+ response += chunk;+ if (response.includes('\n')) {+ finish(response.trim() === expectedBanner ? 'owner' : 'collision');+ }+ });+ socket.on('end', () => finish(response.trim() === expectedBanner ? 'owner' : 'collision'));+ socket.on('timeout', () => finish('collision'));+ socket.on('error', (error: NodeJS.ErrnoException) => {+ finish(classifyDesktopTestLockProbeError(error.code));+ });+ });+}++export async function acquireDesktopTestLock(repoRoot: string): Promise<DesktopTestLock> {+ const commonDir = await resolveGitCommonDir(repoRoot);+ const identity = lockIdentity(commonDir);+ const banner = `${LOCK_PROTOCOL}:${identity}`;+ let reportedWait = false;+ const ports = Array.from(+ { length: LOCK_PORT_CANDIDATES },+ (_, candidate) => lockPort(identity, candidate),+ );++ while (true) {+ const probes = await Promise.all(ports.map(async (port) => ({+ port,+ result: await probeLock(port, banner),+ })));+ const decision = decideDesktopTestLock(probes);++ if (decision.type === 'wait') {+ if (!reportedWait) {+ reportedWait = true;+ process.stdout.write('WAIT desktop tests: another worktree is using the shared Desktop test budget\n');+ }+ await delay(RETRY_DELAY_MS);+ continue;+ }+ if (decision.type === 'unavailable') {+ // A random or OS-assigned fallback cannot be rediscovered by later+ // worktrees and would silently break mutual exclusion. Fail closed only+ // after the expanded deterministic window is genuinely unavailable.+ throw new Error(+ `All ${LOCK_PORT_CANDIDATES} Desktop test resource-lock ports are occupied by other local services`,+ );+ }++ const server = net.createServer((socket) => {+ socket.end(`${banner}\n`);+ });+ try {+ await listen(server, decision.port);+ return {+ port: decision.port,+ release: () => close(server),+ };+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error;+ // Another contender may have won between the probe and listen phases.+ // Re-scan every candidate so its owner banner is observed before retrying.+ await delay(RETRY_DELAY_MS);+ }+ }+}++export default async function setupDesktopTestResourceLock(): Promise<() => Promise<void>> {+ const lock = await acquireDesktopTestLock(REPO_ROOT);+ return lock.release;+}diff --git a/apps/desktop/src/test/vitest/testDirectoryTemplate.ts b/apps/desktop/src/test/vitest/testDirectoryTemplate.tsnew file mode 100644index 0000000000..7d9adaf4eb--- /dev/null+++ b/apps/desktop/src/test/vitest/testDirectoryTemplate.ts@@ -0,0 +1,58 @@+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++/**+ * Builds an immutable temporary directory once and gives every test a private+ * copy. Real-Git suites use this to avoid repeating git init/config/seed commits+ * in every beforeEach while preserving isolated repository state per test.+ */+export class TestDirectoryTemplate {+ private templatePromise: Promise<string> | null = null;+ private readonly prefix: string;+ private readonly initialize: (directory: string) => Promise<void>;++ constructor(+ prefix: string,+ initialize: (directory: string) => Promise<void>,+ ) {+ this.prefix = prefix;+ this.initialize = initialize;+ }++ async createCopy(): Promise<string> {+ const templatePath = await this.getOrCreateTemplate();+ const copyPath = await fs.mkdtemp(path.join(os.tmpdir(), this.prefix));+ try {+ await fs.cp(templatePath, copyPath, { recursive: true });+ return copyPath;+ } catch (error) {+ await fs.rm(copyPath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });+ throw error;+ }+ }++ async dispose(): Promise<void> {+ const pending = this.templatePromise;+ this.templatePromise = null;+ if (!pending) return;+ const templatePath = await pending;+ await fs.rm(templatePath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });+ }++ private getOrCreateTemplate(): Promise<string> {+ this.templatePromise ??= this.createTemplate();+ return this.templatePromise;+ }++ private async createTemplate(): Promise<string> {+ const templatePath = await fs.mkdtemp(path.join(os.tmpdir(), `${this.prefix}template-`));+ try {+ await this.initialize(templatePath);+ return templatePath;+ } catch (error) {+ await fs.rm(templatePath, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });+ throw error;+ }+ }+}diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.tsindex 3b3aaee116..b7b5ffabaf 100644--- a/apps/desktop/vitest.config.ts+++ b/apps/desktop/vitest.config.ts@@ -1,8 +1,26 @@import { defineConfig } from 'vitest/config';import path from 'node:path';import { desktopClientBuildEnv } from '../../scripts/shared/client-endpoint-build-env.mjs';+import { parseVitestCliExclude } from './src/test/vitest/cliExclude';const clientBuildEnv = desktopClientBuildEnv({ allowEnvOverride: false });+const cliTestExclude = parseVitestCliExclude(process.argv.slice(2));+const desktopTestInclude = [+ 'src/main/__tests__/**/*.test.ts',+ 'src/main/**/__tests__/**/*.test.ts',+ 'src/renderer/__tests__/**/*.test.ts',+ 'src/renderer/**/__tests__/**/*.test.ts',+ // renderer 组件测试(React,tsx):按文件头 `// @vitest-environment jsdom`+ // 切 DOM 环境;此前 include 只收 .test.ts,tsx 用例根本不会被跑。+ 'src/renderer/**/__tests__/**/*.test.tsx',+ 'src/preload/__tests__/**/*.test.ts',+ // shared 是 main/renderer 共用的纯函数层;此前漏配导致 src/shared/__tests__+ // 下的测试(如 workingDir.test.ts)从未跑过。+ 'src/shared/__tests__/**/*.test.ts',+];+const gitIntegrationTestInclude = [+ 'src/main/**/*.git-integration.test.ts',+];export default defineConfig({define: {@@ -65,18 +83,27 @@ export default defineConfig({// Main-process code is pure Node — no DOM needed. Renderer tests (if/when// added) should switch to 'jsdom' via per-file `// @vitest-environment`.environment: 'node',- include: [- 'src/main/__tests__/**/*.test.ts',- 'src/main/**/__tests__/**/*.test.ts',- 'src/renderer/__tests__/**/*.test.ts',- 'src/renderer/**/__tests__/**/*.test.ts',- // renderer 组件测试(React,tsx):按文件头 `// @vitest-environment jsdom`- // 切 DOM 环境;此前 include 只收 .test.ts,tsx 用例根本不会被跑。- 'src/renderer/**/__tests__/**/*.test.tsx',- 'src/preload/__tests__/**/*.test.ts',- // shared 是 main/renderer 共用的纯函数层;此前漏配导致 src/shared/__tests__- // 下的测试(如 workingDir.test.ts)从未跑过。- 'src/shared/__tests__/**/*.test.ts',+ // Keep include arrays project-local: Vitest merges array options inherited+ // through extends:true, so a root include would make the resource project+ // collect standard tests too. The two projects remain mutually exclusive.+ projects: [+ {+ extends: true,+ test: {+ name: 'standard',+ include: desktopTestInclude,+ exclude: [...gitIntegrationTestInclude, ...cliTestExclude],+ },+ },+ {+ extends: true,+ test: {+ name: 'git-integration',+ include: gitIntegrationTestInclude,+ exclude: cliTestExclude,+ globalSetup: ['src/test/vitest/desktopTestResourceLock.ts'],+ },+ },],},});diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.tsindex 98264e6522..67f8a3c595 100644--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts@@ -117,11 +117,11 @@ describe('mobile auth-server login', () => {const authSource = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'),'utf8',- );+ ).replace(/\r\n/g, '\n');const envSource = readFileSync(resolve(process.cwd(), 'src/config/env.ts'),'utf8',- );+ ).replace(/\r\n/g, '\n');expect(authSource).toContain("kind: 'sso'");expect(authSource).toMatch(@@ -149,7 +149,7 @@ describe('mobile auth-server login', () => {const authSource = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'),'utf8',- );+ ).replace(/\r\n/g, '\n');expect(authSource).toContain("action.type === 'discover' ||");expect(authSource).toContain("action.type === 'request-code' ||");expect(authSource).toContain("action.type === 'verify-code' ||");diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.mdindex e24eca473d..640dfc93ef 100644--- a/docs/dev-rules/desktop-unit-test-performance.md+++ b/docs/dev-rules/desktop-unit-test-performance.md@@ -60,6 +60,39 @@ workers),说明存在资源争用;但墙钟仍持续下降。综合速度因此分池优先按“真实 Git/子进程长尾”和“其余测试”隔离,而不是只按 node/jsdom 环境机械拆分。+## 多 worktree 资源协调++Desktop 测试按成本拆成默认层与显式层:++- `standard`:普通单测,以及一条代表性的真实 Git smoke;默认 `test:unit` 只运行这一层。+- `git-integration`:文件名为 `*.git-integration.test.ts` 的完整真实 Git 覆盖,由+ `pnpm test:git-integration` 显式运行,并通过 global setup 获取以 Git common-dir+ 派生的本机回环端口锁。++远端 `client-ci` 以独立并行 job 在每个 PR、`main` push 和手动触发时运行完整+`git-integration` 层;本地提交前门禁仍只要求默认 `test:unit`,修改真实 Git 行为时可按需+显式补跑完整层。++因此同一仓库的多个 worktree 可以并行完成默认单测;只有显式运行完整 Git 集成层时才排队:++- 同一主仓的 worktree 共享 common-dir,因此只有重型层排队执行。+- 独立仓库不共享锁,不会互相阻塞。+- 锁只监听 `127.0.0.1`,不发起业务网络请求;测试进程退出后由操作系统自动释放,不产生+ stale lock 文件。+- 无 `.git` 的源码归档按 checkout 实际路径派生锁,不因缺少 Git 元数据而启动失败。+- 两个 project 的 include/exclude 必须互补;默认层以低成本 smoke 守住主链路,完整层保留+ index、patch、hook、ref、worktree 等组合语义。+- Vitest 3.2 的 inline project 不会自动继承根 CLI 的 `--exclude`;配置必须把这些排除项+ 显式传入两个 project,确保 unit、DB、migration 等 tier 的测试边界保持不变。++真实 Git 测试的 fixture 还应优先复用 `src/test/vitest/testDirectoryTemplate.ts`:每个测试+文件初始化一次不可变基准仓库,再为每个用例复制独立目录。默认层不复制完整矩阵;完整层+不得为了提速把需要验证 Git index、patch、hook 或 ref 语义的集成覆盖全部 mock 掉。++2026-07-28 在 Windows 上测得旧 `resource-intensive` 范围为 22 files、219 passed /+3 skipped,墙钟 252.07s;其中 15 个真实 Git 文件的测试耗时合计占主要长尾。该数据是拆层+前基线,后续比较必须分别报告默认 smoke 与显式完整层,不能把两者相加后宣称默认层变快。+## 分池评估分池把 21 个 Git/子进程长尾文件放入 `git-io`,其余文件放入 `standard`;两个池并发,diff --git a/docs/dev-rules/engineering-conventions.md b/docs/dev-rules/engineering-conventions.mdindex d6a419a800..ddcd805696 100644--- a/docs/dev-rules/engineering-conventions.md+++ b/docs/dev-rules/engineering-conventions.md@@ -64,6 +64,31 @@ UI 文案的语气与措辞另见 [`DESIGN.md`](../design-rules/DESIGN.md) 的 V- 新增 handler 至少覆盖主路径与关键错误路径;修改已有 handler 时补上能复现本次风险的回归用例。+### 3.1 测试资源与分层++默认 `test:unit` 必须适合多个 worktree 同时运行。新增、生成或改写测试时遵守:++- 默认单测优先使用进程内依赖注入、内存 fake 和表驱动用例;同一模块的重复初始化应合并到+ 文件级 fixture,不要为每个断言重复启动子进程、仓库、数据库或监听服务。+- 默认单测不得访问业务外网、真实云服务或开发者账号。需要验证 HTTP/WebSocket 协议时,+ 优先直接调用 handler;确需真实 socket 时只绑定 loopback,使用 `listen(0)` 的系统分配+ 端口,并在 `afterAll`/`finally` 中关闭。禁止固定端口。+- 临时文件必须放在 `os.tmpdir()` 下由 `mkdtemp` 创建的唯一目录并可靠清理;禁止复用仓库外+ 的固定目录、用户配置目录或跨 worktree 共享文件。测试不得修改全局 Git 配置、系统代理或+ 其它机器级状态。+- 默认单测中真实 Git 只保留一条代表性 smoke;覆盖 index、patch、hook、ref、worktree 等+ 组合语义的完整用例命名为 `*.git-integration.test.ts`,由+ `pnpm test:git-integration` 显式执行。不得因 review 或补回归把完整真实 Git 链路重新放回+ 默认层。+- SQLite migration、runtime asset、严格性能计时等已有专用 tier 的资源测试继续进入对应+ tier。新增资源类型若无法进程内隔离,必须先在 `scripts/test-workspaces.config.mjs` 声明+ 专用 tier,并按实际共享资源增加跨 worktree 协调;不要在测试文件里自行发明全局锁。+- “合并测试”只合并重复 fixture 和等价输入矩阵,不合并语义不同的失败路径,也不以删除断言+ 换速度。若单文件仍有大量真实 I/O,迁移 tier,而不是继续扩大 timeout。++`scripts/__tests__/test-workspaces.test.mjs` 是 tier 边界的可执行契约;调整测试命名、include+或 exclude 时必须同步更新并运行 `pnpm test:runner`。+## 4. 跨平台双端兼容(macOS / Windows)任何功能都必须同时考虑 macOS / Windows,并在两端做到最优性能。@@ -215,12 +240,14 @@ UI 文案的语气与措辞另见 [`DESIGN.md`](../design-rules/DESIGN.md) 的 V正则解码?`{success}` 风格是否只用在确实需要 fallback data 的查询型 handler?3. main 侧新/改业务逻辑是否带了主路径 + 关键错误路径的测试?handler 业务体是否可注入依赖、便于免 Electron 测试?-4. 路径、子进程、FS、性能、快捷键是否在 macOS / Windows 两端都成立?未实测平台是否+4. 新增测试是否避免外网、固定端口、共享临时路径和重复真实子进程?资源测试是否进入正确+ tier,并保留了低成本默认 smoke?+5. 路径、子进程、FS、性能、快捷键是否在 macOS / Windows 两端都成立?未实测平台是否标注?-5. UI 文案是否全部走 `t()`、4 种语言齐全且翻译准确、无孤儿 key?术语是否照 `i18n/GLOSSARY.md`+6. UI 文案是否全部走 `t()`、4 种语言齐全且翻译准确、无孤儿 key?术语是否照 `i18n/GLOSSARY.md`写、没有自造译法?是否跑过 `pnpm check:i18n` 与 `pnpm check:i18n-glossary`?-6. 新增类/核心逻辑是否有职责注释?-7. 新增常驻动画是否 compositor-only(HTML 元素 + `transform`/`opacity` + wrapper)、+7. 新增类/核心逻辑是否有职责注释?+8. 新增常驻动画是否 compositor-only(HTML 元素 + `transform`/`opacity` + wrapper)、响应 `prefers-reduced-motion`?界面切换是否无跳变/空白帧、未引入不必要的 loading 态?验证按 [`desktop-development.md`](desktop-development.md) 的分层选择:改 TypeScript 至少跑相关diff --git a/package.json b/package.jsonindex ce74e0a09d..60bd27510e 100644--- a/package.json+++ b/package.json@@ -114,6 +114,7 @@"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:git-integration": "pnpm test:runner && node scripts/test-workspaces.mjs --tier git-integration","test:db": "pnpm test:runner && node scripts/test-workspaces.mjs --tier db","test:guard": "node scripts/test-workspaces.mjs --tier guard","ci:scheduler-guard": "node scripts/scheduler-ci-guard.mjs",diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjsindex 161f26ddc4..999ec9a25e 100644--- a/scripts/__tests__/test-workspaces.test.mjs+++ b/scripts/__tests__/test-workspaces.test.mjs@@ -28,6 +28,7 @@ import {parseWorkspaceSelectorValue,planRuns,printSummary,+ readAllFiles,resolvePnpmInvocation,resolveOutputStream,runCommand,@@ -78,6 +79,10 @@ test("root unit and all scripts run runner self-tests before workspace sweep", (test("root db and guard delegate to the workspace runner", () => {const scripts = readRootScripts();+ assert.equal(+ scripts["test:git-integration"],+ "pnpm test:runner && node scripts/test-workspaces.mjs --tier git-integration",+ );assert.equal(scripts["test:db"],"pnpm test:runner && node scripts/test-workspaces.mjs --tier db",@@ -85,6 +90,19 @@ test("root db and guard delegate to the workspace runner", () => {assert.equal(scripts["test:guard"], "node scripts/test-workspaces.mjs --tier guard");});+test("client CI owns the complete Desktop Git integration tier", () => {+ const workflow = fs.readFileSync(+ path.join(ROOT, ".github", "workflows", "ci.yml"),+ "utf8",+ ).replace(/\r\n/g, "\n");+ const job = workflow.match(/\n git-integration:\n([\s\S]*)$/);+ assert.ok(job, "client CI must define an independent git-integration job");+ assert.match(+ job[1],+ /^\s{6}- name: Run Desktop Git integration tests\n\s{8}run: pnpm test:git-integration$/m,+ );+});+test("help groups copyable desktop, binary, and Mobile workflows", async () => {const { printHelp } = await import("../help.mjs");const lines = [];@@ -289,6 +307,7 @@ test("desktop unit excludes migration, direct db-tier, and source-contract guardconst tier = {status: "required",exclude: [+ "**/*.git-integration.test.ts","src/main/localDb/**","src/main/__tests__/*Migration.test.ts","src/main/__tests__/schemaDriftRepair.test.ts",@@ -304,6 +323,7 @@ test("desktop unit excludes migration, direct db-tier, and source-contract guard};assert.deepEqual(selectFilesForTier(workspace, tier, [+ "apps/desktop/src/main/git-review/__tests__/stageOps.git-integration.test.ts","apps/desktop/src/main/localDb/ipc/messages.test.ts","apps/desktop/src/main/__tests__/sessionWorkspaceKindMigration.test.ts","apps/desktop/src/main/__tests__/codexProjectlessMigration.test.ts",@@ -326,6 +346,71 @@ test("desktop unit excludes migration, direct db-tier, and source-contract guard);});+test("desktop real-Git coverage is an explicit coordinated tier outside default unit", () => {+ const desktopPackage = readWorkspacePackageJson("apps/desktop");+ const desktop = manifest.workspaces.find(+ (workspace) => workspace.cwd === "apps/desktop",+ );+ const tier = desktop.tiers["git-integration"];++ assert.equal(tier.status, "manual");+ assert.equal(tier.execution, "exclusive");+ assert.equal(tier.coverage, "allowlist");+ assert.deepEqual(tier.include, ["src/main/**/*.git-integration.test.ts"]);+ assert.deepEqual(tier.command, {+ type: "packageBin",+ bin: "vitest",+ args: ["run", `--maxWorkers=${desktopUnitWorkerCount()}`],+ });+ assert.match(+ desktopPackage.scripts["test:git-integration"],+ /test-workspaces\.mjs --tier git-integration/,+ );++ const files = [+ "apps/desktop/src/main/git-review/__tests__/stageOps.git-integration.test.ts",+ "apps/desktop/src/main/__tests__/gitSnapshotService.git-integration.test.ts",+ "apps/desktop/src/main/git-review/__tests__/gitReviewSmoke.test.ts",+ ];+ assert.deepEqual(selectFilesForTier(desktop, desktop.tiers.unit, files), [+ "apps/desktop/src/main/git-review/__tests__/gitReviewSmoke.test.ts",+ ]);+ assert.deepEqual(selectFilesForTier(desktop, tier, files), files.slice(0, 2));+});++test("default desktop unit keeps real Git subprocess coverage to one smoke", () => {+ const files = discoverTestFiles(readAllFiles(ROOT))+ .filter((file) =>+ file.startsWith("apps/desktop/src/main/") &&+ file.endsWith(".test.ts") &&+ !file.endsWith(".git-integration.test.ts"),+ )+ .filter((file) => /\b(?:runGit|gitExec)\(/.test(+ fs.readFileSync(path.join(ROOT, file), "utf8"),+ ));++ assert.deepEqual(files, [+ "apps/desktop/src/main/git-review/__tests__/gitReviewSmoke.test.ts",+ // This file mocks child_process.spawn and tests the adapter itself.+ "apps/desktop/src/main/git-review/__tests__/gitRunner.test.ts",+ ]);+});++test("tests never bind a fixed numeric port", () => {+ const violations = [];+ for (const file of discoverTestFiles(readAllFiles(ROOT))) {+ const source = fs.readFileSync(path.join(ROOT, file), "utf8");+ const directPort = /\.listen\s*\(\s*(\d+)/g;+ const objectPort = /\.listen\s*\(\s*\{[\s\S]{0,300}?\bport\s*:\s*(\d+)/g;+ for (const pattern of [directPort, objectPort]) {+ for (const match of source.matchAll(pattern)) {+ if (Number(match[1]) !== 0) violations.push(`${file}:${match[1]}`);+ }+ }+ }+ assert.deepEqual(violations, []);+});+test("desktop guard selects source-contract tests only", () => {const workspace = manifest.workspaces.find((candidate) => candidate.cwd === "apps/desktop",diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex 698f532bb6..5956973514 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -19,6 +19,9 @@ const desktopDbExclude = ['src/main/localDb/__tests__/migrationReplay.test.ts','src/main/localDb/__tests__/drizzle-proxy-perf.test.ts',];+const desktopGitIntegrationInclude = [+ 'src/main/**/*.git-integration.test.ts',+];export function desktopUnitWorkerCount(availableParallelism = os.availableParallelism(),@@ -66,6 +69,7 @@ export default {// It runs exclusively so these workers never overlap outer workspaces.command: vitestBin('run', `--maxWorkers=${desktopUnitWorkerCount()}`),exclude: [+ '**/*.git-integration.test.ts','src/main/localDb/**','src/main/__tests__/*Migration.test.ts','src/main/__tests__/schemaDriftRepair.test.ts',@@ -79,6 +83,14 @@ export default {'**/*.bench.ts',],},+ 'git-integration': {+ status: 'manual',+ reason: 'Full real-Git coverage is explicit because it spawns hundreds of local subprocesses and is coordinated across worktrees.',+ execution: 'exclusive',+ coverage: 'allowlist',+ command: vitestBin('run', `--maxWorkers=${desktopUnitWorkerCount()}`),+ include: desktopGitIntegrationInclude,+ },db: {status: 'manual',reason: 'Desktop DB tests remain an explicit DB tier because they bootstrap runtime assets and cover localDb behavior outside fast unit.',