Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(ios-simulator): share project leases across profiles
JiangJiahaob6dc913416ca
diff --git a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.tsindex 8fd3ff1cb5..277d2714e1 100644--- a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts@@ -6,14 +6,14 @@ import path from 'node:path';import type { WorktreeMeta } from '../worktree/types';import type { LocalWorktreeReference } from '../localDb/worker/worktreeReferences';-const state = vi.hoisted(() => ({ root: '', refs: [] as LocalWorktreeReference[], runtimes: new Set<string>(), registry: new Map<string, WorktreeMeta>() }));+const state = vi.hoisted(() => ({ root: '', userData: '', refs: [] as LocalWorktreeReference[], runtimes: new Set<string>(), registry: new Map<string, WorktreeMeta>() }));const snapshot = vi.hoisted(() => vi.fn());const baselineMatches = vi.hoisted(() => vi.fn());const archive = vi.hoisted(() => vi.fn());const query = vi.hoisted(() => vi.fn());const git = vi.hoisted(() => vi.fn());-vi.mock('electron', () => ({ app: { getPath: () => state.root } }));+vi.mock('electron', () => ({ app: { getPath: (name: string) => name === 'appData' ? path.join(state.root, 'app-data') : (state.userData || state.root) } }));vi.mock('../worktree/worktreeStore', () => ({get: (id: string) => state.registry.get(id) ?? null,getAll: () => [...state.registry.values()], getAllPaths: () => [...state.registry.values()].map((m) => m.path),@@ -21,7 +21,10 @@ vi.mock('../worktree/worktreeStore', () => ({del: async (id: string) => { state.registry.delete(id); },}));vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ readLocalWorktreeReferences: query }) }));-vi.mock('../worktree/runtimeLeases', () => ({ readWorktreeRuntimePaths: async () => state.runtimes }));+vi.mock('../worktree/runtimeLeases', async (original) => ({+ ...await original<typeof import('../worktree/runtimeLeases')>(),+ readWorktreeRuntimePaths: vi.fn(async () => state.runtimes),+}));vi.mock('../worktree/contentSnapshot', () => ({ captureWorktreeContent: snapshot, worktreeContentBaselineMatches: baselineMatches }));vi.mock('../worktree/gitExec', () => ({ gitExec: git }));vi.mock('../worktree/recoveryArchive', async (original) => ({@@ -33,18 +36,22 @@ import { recycleManagedWorktree, requestWorktreeRecycle } from '../worktree/manaimport { readRecycleRecord } from '../worktree/recycleJournal';import { inventoryWorktree } from '../worktree/recoveryArchive';import { physicalWorktreeKey } from '../worktree/resourceLock';+import { readWorktreeRuntimePaths } from '../worktree/runtimeLeases';+import { acquireIOSSimulatorProjectUse } from '../mcp-integrations/ios-simulator-project-source';describe('shared worktree recycling', () => {let meta: WorktreeMeta;let removable: boolean;beforeEach(async () => {state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-recycle-test-'));+ state.userData = '';meta = { sessionId: 'owner', generation: 'generation-one', name: 'one', path: path.join(state.root, 'repo', '.cindy-worktrees', 'one'), baseRepo: path.join(state.root, 'repo'), branch: 'cindy/one', sourceBranch: 'main', createdAt: '2026-09-08T00:00:00Z' };await fs.mkdir(meta.path, { recursive: true });await fs.writeFile(path.join(meta.path, '.git'), 'gitdir: unused-test-link');await fs.writeFile(path.join(meta.path, 'draft.txt'), 'uncommitted contents');state.registry.clear(); state.registry.set(meta.sessionId, meta);state.runtimes.clear();+ vi.mocked(readWorktreeRuntimePaths).mockReset().mockImplementation(async () => state.runtimes);state.refs = [{ id: meta.sessionId, status: 'archived', source: 'desktop', workingDir: meta.path, worktreePath: meta.path, currentDatabase: true }];removable = true;query.mockReset().mockImplementation(async () => state.refs);@@ -115,6 +122,35 @@ describe('shared worktree recycling', () => {expect(await recycle()).toBe(false);expect(archive).not.toHaveBeenCalled();});+ it('protects a simulator source borrowed by another isolated profile until release', async () => {+ const actual = await vi.importActual<typeof import('../worktree/runtimeLeases')>('../worktree/runtimeLeases');+ vi.mocked(readWorktreeRuntimePaths).mockImplementation(actual.readWorktreeRuntimePaths);+ const borrowerProfile = path.join(state.root, 'profile-a');+ const ownerProfile = path.join(state.root, 'profile-b');+ for (const profile of [borrowerProfile, ownerProfile]) {+ await fs.mkdir(path.join(profile, '.dev-instances'), { recursive: true });+ }+ state.userData = borrowerProfile;+ const release = await acquireIOSSimulatorProjectUse('borrower', meta.path, new AbortController());+ expect(release).not.toBeNull();+ try {+ // The recycler has a different userData and no active database reference.+ state.userData = ownerProfile;+ expect(await recycle()).toBe(false);+ expect(archive).not.toHaveBeenCalled();+ expect(await fs.readFile(path.join(meta.path, 'draft.txt'), 'utf8')).toBe('uncommitted contents');+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(meta.path)]));+ // Retain the profile-local evidence that existing readers already consume.+ expect(await fs.readdir(path.join(borrowerProfile, 'worktree-runtime-leases'))).toHaveLength(1);++ await release!();+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ expect(await recycle()).toBe(true);+ await expect(fs.stat(meta.path)).rejects.toMatchObject({ code: 'ENOENT' });+ } finally {+ await release?.();+ }+ });it('protects a borrower running in a subdirectory', async () => {state.refs.push({ ...state.refs[0], id: 'borrower', status: 'active', workingDir: path.join(meta.path, 'src'), worktreePath: null });expect(await recycle()).toBe(false);diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.tsindex 2aaa57aa7d..cdd89b72e7 100644--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts@@ -3,10 +3,10 @@ import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';-const state = vi.hoisted(() => ({ root: '' }));+const state = vi.hoisted(() => ({ root: '', userData: '' }));const notify = vi.hoisted(() => vi.fn());const readIdentity = vi.hoisted(() => vi.fn());-vi.mock('electron', () => ({ app: { getPath: () => state.root } }));+vi.mock('electron', () => ({ app: { getPath: (name: string) => name === 'appData' ? path.join(state.root, 'app-data') : (state.userData || state.root) } }));vi.mock('../worktree/recycleEvents', () => ({ notifyWorktreeRecycleOpportunity: notify }));vi.mock('../desktopProcessIdentity', async (importOriginal) => ({...await importOriginal<typeof import('../desktopProcessIdentity')>(),@@ -21,6 +21,7 @@ describe('worktree runtime evidence and physical locks', () => {const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;beforeEach(async () => {state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-runtime-'));+ state.userData = '';worktree = path.join(state.root, 'repo', '.cindy-worktrees', 'one');await fs.mkdir(path.join(worktree, 'src'), { recursive: true });await fs.mkdir(path.join(state.root, '.dev-instances'));@@ -79,6 +80,57 @@ describe('worktree runtime evidence and physical locks', () => {await releaseWorktreeRuntimeLease(oldLease);});+ it('retries a failed shared lease release from another isolated profile', async () => {+ const lease = (await acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true }))!;+ const unlink = fs.unlink.bind(fs);+ let blocked = true;+ vi.spyOn(fs, 'unlink').mockImplementation(async (file) => {+ if (file === lease.sharedFile && blocked) throw Object.assign(new Error('busy'), { code: 'EBUSY' });+ return unlink(file);+ });+ await expect(releaseWorktreeRuntimeLease(lease)).rejects.toMatchObject({ code: 'EBUSY' });+ await expect(fs.stat(lease.file)).rejects.toMatchObject({ code: 'ENOENT' });+ state.userData = path.join(state.root, 'profile-b');+ await fs.mkdir(path.join(state.userData, '.dev-instances'), { recursive: true });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(1);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ blocked = false;+ expect(await retryPendingWorktreeRuntimeLeaseReleases()).toBe(0);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ await expect(fs.stat(`${lease.sharedFile}.release`)).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it.each(['crashed-owner', 'partial-write'] as const)('keeps shared lease evidence protective after %s', async (reason) => {+ const lease = (await acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true }))!;+ state.userData = path.join(state.root, 'profile-b');+ await fs.mkdir(path.join(state.userData, '.dev-instances'), { recursive: true });+ if (reason === 'partial-write') await fs.writeFile(lease.sharedFile!, '{');+ else vi.spyOn(process, 'kill').mockImplementation(() => {+ throw Object.assign(new Error('owner is gone'), { code: 'ESRCH' });+ });+ expect(await readWorktreeRuntimePaths()).toEqual(reason === 'partial-write' ? null : new Set([await physicalWorktreeKey(worktree)]));+ await releaseWorktreeRuntimeLease(lease);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ });++ it('cleans a failed shared publication without removing an older profile lease', async () => {+ const oldLease = (await acquireWorktreeRuntimeLease('borrower', worktree))!;+ const sharedRoot = path.join(state.root, 'app-data', 'Cindy', 'shared-worktree-runtime-leases');+ const write = fs.writeFile.bind(fs);+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {+ await write(...args);+ if (typeof args[0] === 'string' && path.dirname(args[0]) === sharedRoot) {+ throw Object.assign(new Error('shared publication interrupted'), { code: 'EIO' });+ }+ });+ await expect(acquireWorktreeRuntimeLease('borrower', worktree, { crossProfile: true })).rejects.toThrow('shared publication interrupted');+ expect(await fs.readdir(path.dirname(oldLease.file))).toEqual([path.basename(oldLease.file)]);+ expect(await fs.readdir(sharedRoot)).toEqual([]);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ await releaseWorktreeRuntimeLease(oldLease);+ });+it('preserves when another live instance cannot publish runtime evidence', async () => {vi.spyOn(process, 'kill').mockReturnValue(true);await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'), JSON.stringify({ pid: 4242 }));diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-project-source.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-project-source.tsindex c2334c5530..8404467d42 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-project-source.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-project-source.ts@@ -41,7 +41,7 @@ export async function acquireIOSSimulatorProjectUse(if (!available) {throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'The selected project directory is unavailable.');}- const lease = await acquireWorktreeRuntimeLease(`ios-simulator:${sessionId}`, projectRoot);+ const lease = await acquireWorktreeRuntimeLease(`ios-simulator:${sessionId}`, projectRoot, { crossProfile: true });if (!lease) return null;const resourceId = worktreeResourceId(lease.physicalPath);const unsubscribe = subscribeWorktreeRecycleEvents((event) => {diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.tsindex 5289dafa94..d99c48fb11 100644--- a/apps/desktop/src/main/worktree/runtimeLeases.ts+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts@@ -12,6 +12,11 @@ function runtimeRoot(): string {return path.join(app.getPath('userData'), 'worktree-runtime-leases');}+/** Source borrowing can cross release/dev/isolated profiles on the same machine. */+function sharedRuntimeRoot(): string {+ return path.join(app.getPath('appData'), 'Cindy', 'shared-worktree-runtime-leases');+}+/** Map a local cwd (including descendants) to its managed resource. SSH callers skip this helper. */export function managedWorktreeRoot(value: string): string | null {let current = path.resolve(value);@@ -23,9 +28,9 @@ export function managedWorktreeRoot(value: string): string | null {}}-function leaseFile(sessionId: string): string {+function leaseFile(sessionId: string, directory: string): string {const key = createHash('sha256').update(`${sessionId}:${randomUUID()}`).digest('hex');- return path.join(runtimeRoot(), `${process.pid}-${key}.json`);+ return path.join(directory, `${process.pid}-${key}.json`);}const leaseNamePattern = /^\d+-[a-f0-9]{64}\.json$/;@@ -35,32 +40,57 @@ const releaseRequestPattern = /^\d+-[a-f0-9]{64}\.json\.release$/;export interface WorktreeRuntimeLease {readonly file: string;readonly physicalPath: string;+ readonly sharedFile?: string;}-export async function acquireWorktreeRuntimeLease(sessionId: string, cwd: string): Promise<WorktreeRuntimeLease | null> {+export async function acquireWorktreeRuntimeLease(+ sessionId: string,+ cwd: string,+ options: { crossProfile?: boolean } = {},+): Promise<WorktreeRuntimeLease | null> {const root = managedWorktreeRoot(cwd);if (!root) return null;return withWorktreeResourceLock(root, async () => {- await fs.mkdir(runtimeRoot(), { recursive: true });- const lease = { file: leaseFile(sessionId), physicalPath: await physicalWorktreeKey(root) };- // A partial write is intentionally unreadable, hence protective to deletion.+ const lease = await publishRuntimeLease(sessionId, await physicalWorktreeKey(root), runtimeRoot());+ if (!options.crossProfile) return lease;try {- await fs.writeFile(lease.file, JSON.stringify({- version: 1, pid: process.pid, path: lease.physicalPath,- }), { flag: 'wx', mode: 0o600 });+ // Publish both under the deletion lock. Keep the original profile copy+ // readable by existing clients sharing this userData.+ const shared = await publishRuntimeLease(sessionId, lease.physicalPath, sharedRuntimeRoot());+ return { ...lease, sharedFile: shared.file };} catch (error) {- // No runtime can start after acquisition fails. Only remove this attempt's- // file; an older/newer runtime of the same task keeps its separate lease.- if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {- await fs.unlink(lease.file).catch(() => undefined);- }+ await releaseWorktreeRuntimeLease(lease).catch(() => undefined);throw error;}- return lease;});}+async function publishRuntimeLease(sessionId: string, physicalPath: string, directory: string): Promise<WorktreeRuntimeLease> {+ await fs.mkdir(directory, { recursive: true });+ const lease = { file: leaseFile(sessionId, directory), physicalPath };+ // A partial write is intentionally unreadable, hence protective to deletion.+ try {+ await fs.writeFile(lease.file, JSON.stringify({+ version: 1, pid: process.pid, path: physicalPath,+ }), { flag: 'wx', mode: 0o600 });+ } catch (error) {+ // Only this acquisition's partial write may be removed.+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {+ await fs.unlink(lease.file).catch(() => undefined);+ }+ throw error;+ }+ return lease;+}+export async function releaseWorktreeRuntimeLease(lease: WorktreeRuntimeLease): Promise<void> {+ const files = [lease.file, ...(lease.sharedFile ? [lease.sharedFile] : [])];+ const results = await Promise.allSettled(files.map((file) => releaseRuntimeLeaseFile({ file, physicalPath: lease.physicalPath })));+ const failure = results.find((result) => result.status === 'rejected');+ if (failure?.status === 'rejected') throw failure.reason;+}++async function releaseRuntimeLeaseFile(lease: WorktreeRuntimeLease): Promise<void> {try { await fs.unlink(lease.file); } catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') {await fs.unlink(`${lease.file}.release`).catch(() => undefined);@@ -69,7 +99,7 @@ export async function releaseWorktreeRuntimeLease(lease: WorktreeRuntimeLease):// Keep an explicit, durable intent. The lease itself remains protective until// a later maintenance pass can prove that this terminal cleanup succeeded.try {- await fs.mkdir(runtimeRoot(), { recursive: true });+ await fs.mkdir(path.dirname(lease.file), { recursive: true });await fs.writeFile(`${lease.file}.release`, JSON.stringify({ version: 1, file: lease.file, path: lease.physicalPath }), { flag: 'wx', mode: 0o600 });} catch { /* preserving the lease is the safe fallback */ }// Wake the event-driven maintenance loop; it will retry the durable intent@@ -83,18 +113,26 @@ export async function releaseWorktreeRuntimeLease(lease: WorktreeRuntimeLease):/** Retry only release intents written by a terminal close path. Unknown files stay protective. */export async function retryPendingWorktreeRuntimeLeaseReleases(): Promise<number> {+ let pending = 0;+ for (const directory of [runtimeRoot(), sharedRuntimeRoot()]) {+ pending += await retryPendingRuntimeLeaseReleasesIn(directory);+ }+ return pending;+}++async function retryPendingRuntimeLeaseReleasesIn(directory: string): Promise<number> {let names: string[];- try { names = await fs.readdir(runtimeRoot()); } catch (error) {+ try { names = await fs.readdir(directory); } catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 0;throw error;}let pending = 0;for (const name of names.filter((value) => releaseRequestPattern.test(value))) {- const requestFile = path.join(runtimeRoot(), name);+ const requestFile = path.join(directory, name);try {const request = JSON.parse(await fs.readFile(requestFile, 'utf8')) as { version?: number; file?: string; path?: string };if (request.version !== 1 || typeof request.file !== 'string' || typeof request.path !== 'string'- || path.dirname(request.file) !== runtimeRoot() || !leaseNamePattern.test(path.basename(request.file))) {+ || path.dirname(request.file) !== directory || !leaseNamePattern.test(path.basename(request.file))) {pending++;continue;}@@ -186,26 +224,26 @@ export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return null;}}- let leases: string[];- try {- leases = await fs.readdir(runtimeRoot());- } catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return new Set();- throw error;- }const paths = new Set<string>();- for (const name of leases) {- const match = leaseNamePattern.exec(name);- if (!match) continue;- // Main may have crashed while a detached child still uses the directory.- // Only explicit lease release proves that startup stopped; a dead owner PID- // is not sufficient evidence and its leftover lease remains protective.+ for (const directory of [runtimeRoot(), sharedRuntimeRoot()]) {+ let leases: string[];try {- const lease = JSON.parse(await fs.readFile(path.join(runtimeRoot(), name), 'utf8'));- if (lease.version !== 1 || typeof lease.path !== 'string') return null;- paths.add(lease.path);+ leases = await fs.readdir(directory);} catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return null;+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw error;+ }+ for (const name of leases) {+ if (!leaseNamePattern.test(name)) continue;+ // Main may have crashed while a detached child still uses the directory.+ // Only explicit release proves source I/O stopped, across every profile.+ try {+ const lease = JSON.parse(await fs.readFile(path.join(directory, name), 'utf8'));+ if (lease.version !== 1 || typeof lease.path !== 'string') return null;+ paths.add(lease.path);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return null;+ }}}return paths;diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex 0c748b86f6..2e1413e324 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -70,6 +70,7 @@| 测试生成物 | `os.tmpdir()` 下通过 `mkdtemp` 创建的独立目录,并在测试结束时清理 || Skill 卸载清理回执 | `app.getPath('userData')/skillhub/uninstall-cleanups/<token>.json`,记录操作 owner、旧文件/注册/偏好身份与完成阶段;跨窗口和重启保留,当前 owner 重试完成后删除,不作为授权凭据 || 跨 profile 的共享 Skill 文件互斥 | `app.getPath('appData')/Cindy/shared-skill-mutation-locks`,仅存文件锁及未完成操作的 token/名称哈希,保证正式版/dev/isolated 共用;短期锁复用既有崩溃回收,持久屏障必须等对应清理完成后删除,读取损坏只阻止相关名称 |+| 跨 profile 的 worktree 借用租约 | `app.getPath('appData')/Cindy/shared-worktree-runtime-leases`,模拟器工程借用时在原 profile 租约之外发布共享副本;回收器同时读取两处,源目录 I/O 结束后显式释放,释放失败由现有 `.release` 回执重试;不能因进程退出就移除保护 || 用户明确导出的文件 | 用户选择或任务明确指定的目标路径 |- 禁止把 `process.cwd()`、仓库根或源码目录作为 userData、凭证目录或临时目录的默认回退。diff --git a/docs/ios-simulator-integration-plan.md b/docs/ios-simulator-integration-plan.mdindex 410e5f5a73..e9d1191584 100644--- a/docs/ios-simulator-integration-plan.md+++ b/docs/ios-simulator-integration-plan.md@@ -1026,6 +1026,10 @@ fingerprint 和相对 container 路径;该 fingerprint 不代表 Git revision构建和 Metro 检查借用现有 worktree runtime lease 保护所选托管目录。本进程的回收事件会取消正在使用该目录的操作,实际读取结束后才释放租约;跨进程回收也必须等待租约释放。+模拟器借用会同时发布 profile 内租约和 `appData/Cindy/shared-worktree-runtime-leases`+中的共享副本,回收器合并读取两处,避免隔离 profile 之间看不到对方的借用;释放失败+沿用 `.release` 回执重试,进程退出本身不能证明 Xcode 或 Metro 已停止读取。+跨 profile 借用要求回收方也运行包含共享租约读取支持的版本;profile 内副本保留原读取协议。任务 A 结束时排空自己的操作,不因其构建了 B 就把 B 加入 A 的目录删除范围。这仍是工程选择与目录边界校验,不是对 Xcode build scripts 的文件系统沙箱。