Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(windows): stabilize unit test portability
MagicLizi2f4035832664
diff --git a/apps/desktop/src/main/doc-tools/__tests__/htmlPdfRenderer.test.ts b/apps/desktop/src/main/doc-tools/__tests__/htmlPdfRenderer.test.tsindex ddd68dcf65..0d96f3ad91 100644--- a/apps/desktop/src/main/doc-tools/__tests__/htmlPdfRenderer.test.ts+++ b/apps/desktop/src/main/doc-tools/__tests__/htmlPdfRenderer.test.ts@@ -11,13 +11,30 @@*/import { EventEmitter } from 'node:events';-import { promises as fs } from 'node:fs';+import fsSync, { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';import { pathToFileURL } from 'node:url';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+// Windows 未开启开发者模式且进程无特权时创建文件 symlink 会 EPERM。精确探测+// 本文件需要的链接形态,能力缺失时仅跳过两条 symlink 专属安全覆盖。+const canSymlinkFile = (() => {+ const probeDir = fsSync.mkdtempSync(path.join(os.tmpdir(), 'cindy-docs-renderer-symlink-probe-'));+ try {+ const target = path.join(probeDir, 'target.txt');+ fsSync.writeFileSync(target, 'probe');+ fsSync.symlinkSync(target, path.join(probeDir, 'link.txt'), 'file');+ return true;+ } catch {+ return false;+ } finally {+ fsSync.rmSync(probeDir, { recursive: true, force: true });+ }+})();+const fileSymlinkIt = canSymlinkFile ? it : it.skip;+interface FakeWindowOptions {webPreferences?: Record<string, unknown>;show?: boolean;@@ -195,7 +212,7 @@ describe('渲染窗的安全配置', () => {expect(win.shown).toBe(false);});- it('本地资源路径含 symlink 时 fail closed,不把 file URL 交给 Chromium', async () => {+ fileSymlinkIt('本地资源路径含 symlink 时 fail closed,不把 file URL 交给 Chromium', async () => {const sourceDir = path.join(tempRoot, 'source');const outsideDir = path.join(tempRoot, 'outside');await Promise.all([fs.mkdir(sourceDir), fs.mkdir(outsideDir)]);@@ -295,7 +312,7 @@ describe('渲染主流程', () => {await expect(fs.stat(source)).resolves.toBeTruthy();});- it('主文档快照完成后源路径被换成外部链接也不会改变待打印内容', async () => {+ fileSymlinkIt('主文档快照完成后源路径被换成外部链接也不会改变待打印内容', async () => {const source = path.join(tempRoot, 'src.html');const outside = path.join(tempRoot, 'outside.html');const moved = path.join(tempRoot, 'src-original.html');diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.tsindex 4aa4e97a58..943c09b339 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts@@ -128,6 +128,18 @@ afterEach(() => {});describe('Codex system credential suppression marker', () => {+ it('qualifies the Windows ACL principal when the machine and user names can collide', async () => {+ const { resolveWindowsAclPrincipal } = await import('../auth-adapters.js');++ expect(+ resolveWindowsAclPrincipal({ USERDOMAIN: 'WORKSTATION', USERNAME: 'alex' }, 'fallback'),+ ).toBe('WORKSTATION\\alex');+ expect(+ resolveWindowsAclPrincipal({ USERDOMAIN: 'WORKSTATION', USERNAME: 'DOMAIN\\alex' }, 'fallback'),+ ).toBe('DOMAIN\\alex');+ expect(resolveWindowsAclPrincipal({}, 'fallback')).toBe('fallback');+ });+it('user disconnect persists as reconcile suppression without surfacing an auth error', () => {const { codexHome, systemAuth, localAuth } = fixture();writeInvalidatedSystemCodexAuthMarker(diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex 4dbac037d3..73d60631cb 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -389,10 +389,23 @@ export async function clearCodexAuthBoundaryStateBeforeLogin(* Windows: 用 icacls 把文件权限收紧为"仅当前用户 Full"。* 失败仅 stderr 告警, 不抛 —— userData ACL + 0o600 已经是双保险, icacls 是第三道。*/+export function resolveWindowsAclPrincipal(+ env: Partial<Pick<NodeJS.ProcessEnv, 'USERDOMAIN' | 'USERNAME'>> = process.env,+ fallbackUsername = os.userInfo().username,+): string {+ const username = env.USERNAME?.trim() || fallbackUsername.trim();+ const domain = env.USERDOMAIN?.trim();+ if (!domain || username.includes('\\') || username.includes('@')) return username;+ return `${domain}\\${username}`;+}+async function tightenAclWindows(file: string): Promise<void> {- const username = process.env.USERNAME ?? os.userInfo().username;+ const principal = resolveWindowsAclPrincipal();try {- await execFileP('icacls', [file, '/inheritance:r', '/grant:r', `${username}:F`]);+ // 先落当前用户的显式 ACE,再移除继承。若 principal 解析失败,第一步会失败,+ // 文件仍保留原继承权限,不能出现“收紧失败反而把当前用户锁在门外”的半提交状态。+ await execFileP('icacls', [file, '/grant:r', `${principal}:F`]);+ await execFileP('icacls', [file, '/inheritance:r']);} catch (err) {credPathLog.warn('icacls failed', { file, error: (err as Error).message });}diff --git a/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.tsindex 5bbe070991..1d1fe28122 100644--- a/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts@@ -1183,10 +1183,16 @@ describe('路径边界与覆盖语义', () => {}});- it('经 symlink 指向工作目录外也被拒', async () => {+ it('经目录链接指向工作目录外也被拒', async () => {const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-outside-'));created.push(outside);- await fs.symlink(outside, path.join(workdir, 'link'), 'dir');+ // Windows junction 不需要开发者模式,仍会让 realpath 穿到工作目录外;POSIX+ // 使用目录 symlink。两端都保留真实文件系统的路径逃逸回归覆盖。+ await fs.symlink(+ outside,+ path.join(workdir, 'link'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );const client = await connect();const result = await callTool(client, 'make_docx', {markdown: '# x',diff --git a/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts b/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.tsindex 3e092bcb05..b24e645f86 100644--- a/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts+++ b/packages/maker-core/src/agents/pi/windows-git-path-powershell.test.ts@@ -1,4 +1,4 @@-import { execFileSync, spawnSync } from 'node:child_process';+import { execFileSync, spawn, spawnSync } from 'node:child_process';import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';@@ -142,73 +142,104 @@ describe('Windows Git PATH PowerShell probes', () => {}});- it.runIf(process.platform === 'win32')('kills probe descendants after the coordinator times out', () => {- const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;- if (!systemRoot) throw new Error('Windows system root is unavailable');- const powershell = path.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');- const encodedSleepCommand = Buffer.from('Start-Sleep -Seconds 30', 'utf16le').toString('base64');- const script = [- '$startInfo = New-Object System.Diagnostics.ProcessStartInfo',- `$startInfo.FileName = '${powershell.replaceAll("'", "''")}'`,- `$startInfo.Arguments = '-NoLogo -NoProfile -NonInteractive -EncodedCommand ${encodedSleepCommand}'`,- '$startInfo.UseShellExecute = $false',- '$startInfo.CreateNoWindow = $true',- '$process = New-Object System.Diagnostics.Process',- '$process.StartInfo = $startInfo',- '[void]$process.Start()',- '[Console]::Out.WriteLine($process.Id)',- '[Console]::Out.Flush()',- 'Start-Sleep -Seconds 30',- ].join('\n');- let childPid: number | undefined;- let coordinatorPid: number | undefined;- try {- execFileSync(- powershell,- ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],- {- encoding: 'utf8',- stdio: ['ignore', 'pipe', 'pipe'],- timeout: 1_500,- windowsHide: true,- },+ it.runIf(process.platform === 'win32')(+ 'kills probe descendants after the coordinator is terminated',+ async () => {+ const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;+ if (!systemRoot) throw new Error('Windows system root is unavailable');+ const powershell = path.join(+ systemRoot,+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe',);- throw new Error('coordinator unexpectedly completed before its timeout');- } catch (error) {- const failure = error as NodeJS.ErrnoException & { stdout?: string | Buffer };- expect(failure.code).toBe('ETIMEDOUT');- coordinatorPid = failure.pid;- const output = Buffer.isBuffer(failure.stdout)- ? failure.stdout.toString('utf8')- : failure.stdout ?? '';- childPid = Number(output.trim().split(/\r?\n/).at(-1));- expect(Number.isInteger(childPid) && childPid > 0).toBe(true);- }+ const encodedSleepCommand = Buffer.from('Start-Sleep -Seconds 30', 'utf16le').toString(+ 'base64',+ );+ const script = [+ '$startInfo = New-Object System.Diagnostics.ProcessStartInfo',+ `$startInfo.FileName = '${powershell.replaceAll("'", "''")}'`,+ `$startInfo.Arguments = '-NoLogo -NoProfile -NonInteractive -EncodedCommand ${encodedSleepCommand}'`,+ '$startInfo.UseShellExecute = $false',+ '$startInfo.CreateNoWindow = $true',+ '$process = New-Object System.Diagnostics.Process',+ '$process.StartInfo = $startInfo',+ '[void]$process.Start()',+ '[Console]::Out.WriteLine($process.Id)',+ '[Console]::Out.Flush()',+ 'Start-Sleep -Seconds 30',+ ].join('\n');+ let childPid: number | undefined;+ let coordinatorPid: number | undefined;+ let coordinator: ReturnType<typeof spawn> | undefined;+ try {+ coordinator = spawn(+ powershell,+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],+ {+ stdio: ['ignore', 'pipe', 'pipe'],+ windowsHide: true,+ },+ );+ coordinatorPid = coordinator.pid;+ expect(Number.isInteger(coordinatorPid) && (coordinatorPid ?? 0) > 0).toBe(true);- terminateWindowsPowerShellDescendants(powershell, coordinatorPid);+ let output = '';+ coordinator.stdout?.setEncoding('utf8');+ coordinator.stdout?.on('data', (chunk: string) => {+ output += chunk;+ });+ await vi.waitFor(+ () => {+ childPid = Number(output.trim().split(/\r?\n/).at(-1));+ expect(Number.isInteger(childPid) && childPid > 0).toBe(true);+ },+ { timeout: 5_000, interval: 50 },+ );- try {- execFileSync(- powershell,- [- '-NoLogo',- '-NoProfile',- '-NonInteractive',- '-Command',+ const coordinatorExit = new Promise<void>((resolve) => {+ coordinator?.once('exit', () => resolve());+ });+ expect(coordinator.kill()).toBe(true);+ await coordinatorExit;++ terminateWindowsPowerShellDescendants(powershell, coordinatorPid);++ execFileSync(+ powershell,[- '$deadline = [DateTime]::UtcNow.AddSeconds(3)',- `while (Get-Process -Id ${childPid} -ErrorAction SilentlyContinue) {`,- ' if ([DateTime]::UtcNow -ge $deadline) { exit 1 }',- ' Start-Sleep -Milliseconds 50',- '}',- ].join('\n'),- ],- { stdio: 'ignore', timeout: 5_000, windowsHide: true },- );- } finally {- spawnSync('taskkill.exe', ['/PID', String(childPid), '/F'], { stdio: 'ignore', windowsHide: true });- }- }, 12_000);+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ [+ '$deadline = [DateTime]::UtcNow.AddSeconds(3)',+ `while (Get-Process -Id ${childPid} -ErrorAction SilentlyContinue) {`,+ ' if ([DateTime]::UtcNow -ge $deadline) { exit 1 }',+ ' Start-Sleep -Milliseconds 50',+ '}',+ ].join('\n'),+ ],+ { stdio: 'ignore', timeout: 5_000, windowsHide: true },+ );+ } finally {+ if (coordinatorPid) {+ spawnSync('taskkill.exe', ['/PID', String(coordinatorPid), '/F'], {+ stdio: 'ignore',+ windowsHide: true,+ });+ }+ if (childPid) {+ spawnSync('taskkill.exe', ['/PID', String(childPid), '/F'], {+ stdio: 'ignore',+ windowsHide: true,+ });+ }+ }+ },+ 12_000,+ );it('reports recoverable script failures only when a logger is supplied', () => {const warn = vi.fn();