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): cancel pending project lease acquisition
JiangJiahaod3d993487e99
diff --git a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.tsindex 3de5f7eddc..e9a33b63b7 100644--- a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts@@ -81,6 +81,52 @@ async function writeStaleReclaimGate(lock: string): Promise<void> {await fsp.utimes(gate, old, old);}+describe('advisory lock cancellation', () => {+ it('does not publish a lock or enter the task when already cancelled', async () => {+ const lock = path.join(dir, 'cancelled-lock');+ const controller = new AbortController();+ controller.abort();+ const task = vi.fn(async () => undefined);++ await expect(withAdvisoryCrossProcessLock(lock, { label: 'cancelled' }, task, controller.signal))+ .rejects.toMatchObject({ name: 'AbortError' });+ expect(task).not.toHaveBeenCalled();+ expect(fs.readdirSync(dir)).toEqual([]);+ });++ it.each(['acquired', 'busy'] as const)('cancels at the %s boundary without leaking or removing another owner', async (state) => {+ const lock = path.join(dir, 'cancelled-lock');+ const ownerRecord = JSON.stringify({ pid: process.pid, nonce: 'existing-owner' });+ if (state === 'busy') await fsp.writeFile(lock, ownerRecord);+ const controller = new AbortController();+ const task = vi.fn(async () => undefined);+ const originalOpen = fsp.open;+ const openSpy = vi.spyOn(fsp, 'open').mockImplementation(async (...args) => {+ try {+ return await originalOpen(...args);+ } finally {+ // Cancel during acquisition, including the last attempt at the deadline.+ if (args[0] === lock) controller.abort();+ }+ });+ try {+ await expect(withAdvisoryCrossProcessLock(lock, { label: 'cancelled', waitMs: 0 }, task, controller.signal))+ .rejects.toMatchObject({ name: 'AbortError' });+ expect(task).not.toHaveBeenCalled();+ if (state === 'busy') {+ expect(await fsp.readFile(lock, 'utf8')).toBe(ownerRecord);+ await fsp.rm(lock);+ } else {+ await expect(fsp.stat(lock)).rejects.toMatchObject({ code: 'ENOENT' });+ }+ } finally {+ openSpy.mockRestore();+ }+ await expect(withAdvisoryCrossProcessLock(lock, { label: 'next' }, async (status) => status))+ .resolves.toEqual({ held: true });+ });+});+describe('接管陈旧锁', () => {it('删得掉 → 接管成功,task 拿到 held=true', async () => {const lock = path.join(dir, 'lock');diff --git a/apps/desktop/src/main/device-link/crossProcessLock.ts b/apps/desktop/src/main/device-link/crossProcessLock.tsindex e0162f7ff0..8d6832ad6f 100644--- a/apps/desktop/src/main/device-link/crossProcessLock.ts+++ b/apps/desktop/src/main/device-link/crossProcessLock.ts@@ -141,6 +141,7 @@ export async function withCrossProcessLock<T>(lockPath: string,opts: FileLockOptions,task: (status: LockStatus) => Promise<T>,+ signal?: AbortSignal,): Promise<T> {const deadline = Date.now() + (opts.waitMs ?? LOCK_WAIT_MS);let held = false;@@ -149,6 +150,7 @@ export async function withCrossProcessLock<T>(let ownLock: AdvisoryPublishedLock | null = null;for (;;) {+ signal?.throwIfAborted();await recoverPendingAdvisoryLock(lockPath);if (await ordinaryReclaimInProgress(lockPath)) {reason = 'busy';@@ -204,6 +206,9 @@ export async function withCrossProcessLock<T>(heartbeat?.unref?.();try {+ // Cancellation can race the final acquisition or timeout. Check inside the+ // release scope so a just-published lock is never abandoned on cancellation.+ signal?.throwIfAborted();return await task(held ? { held: true } : { held: false, reason });} finally {if (heartbeat) clearInterval(heartbeat);diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.tsindex bc0efe41f6..7b45e9af36 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts@@ -1,5 +1,5 @@import { spawn } from 'node:child_process';-import {+import fsp, {mkdir,mkdtemp,readFile,@@ -73,7 +73,7 @@ vi.mock('../../appSessionState.js', async (importOriginal) => {import type { IOSSimulatorPublicRouteStatus } from '../../../shared/iosSimulatorIpc';import { newRecycleRecord, writeRecycleRecord } from '../../worktree/recycleJournal';-import { physicalWorktreeKey, withWorktreeResourceLock } from '../../worktree/resourceLock';+import { physicalWorktreeKey, withWorktreeResourceLock, worktreeResourceId } from '../../worktree/resourceLock';import { readWorktreeRuntimePaths } from '../../worktree/runtimeLeases';import {cancelIOSSimulatorSessionOperations,@@ -495,6 +495,68 @@ describe('iOS Simulator host', () => {} finally { unblock(); await h.close(); }});+ it.each([+ ['build_app', 'task-cancel'], ['build_app', 'host-dispose'],+ ['launch_app', 'task-cancel'], ['launch_app', 'host-dispose'],+ ] as const)('cancels %s while its project lock is held during %s', async (tool, reason) => {+ const h = await projectSelectionHarness(tool === 'launch_app');+ let unlock: () => void = () => undefined;+ let holding: Promise<void> | undefined;+ let operation: ReturnType<typeof h.host.callTool> | undefined;+ let cancelling: Promise<void> | undefined;+ const openSpy = vi.spyOn(fsp, 'open');+ try {+ let artifactId: string | undefined;+ if (tool === 'launch_app') {+ expect(await h.host.callTool('build_app', { ...h.route, projectDir: h.projectRoot }, h.context)).toMatchObject({ ok: true });+ artifactId = (await h.inspectArtifact.mock.results[0]!.value).artifactId;+ expect(await h.host.callTool('install_app', { ...h.route, artifactId }, h.context)).toMatchObject({ ok: true });+ }+ h.build.mockClear();+ h.inspect.mockClear();+ let acquired: () => void = () => undefined;+ const ready = new Promise<void>((resolve) => { acquired = resolve; });+ const gate = new Promise<void>((resolve) => { unlock = resolve; });+ holding = withWorktreeResourceLock(h.projectRoot, async () => { acquired(); await gate; });+ await ready;+ const uid = typeof process.getuid === 'function' ? process.getuid() : 0;+ const lockPath = path.join(os.tmpdir(), `cindy-worktree-${uid}-${worktreeResourceId(await physicalWorktreeKey(h.projectRoot))}.lock`);+ const ownerRecord = await readFile(lockPath, 'utf8');+ openSpy.mockClear();++ let finished = false;+ operation = h.host.callTool(tool, { ...h.route, projectDir: h.projectRoot, artifactId, args: [] }, h.context);+ void operation.then(() => { finished = true; });+ // Wait for actual contention, before project inspection or lease creation.+ await vi.waitFor(() => expect(openSpy).toHaveBeenCalledWith(lockPath, 'wx'));+ let cancellationFinished = false;+ cancelling = (reason === 'host-dispose' ? h.host.dispose() : h.host.cancelSessionOperations('session-a'))+ .then(() => { cancellationFinished = true; });+ await vi.waitFor(() => {+ expect(finished).toBe(true);+ expect(cancellationFinished).toBe(true);+ }, { timeout: 2_000 });+ expect(await operation).toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });+ expect(await readFile(lockPath, 'utf8')).toBe(ownerRecord);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());++ unlock();+ await holding;+ await withWorktreeResourceLock(h.projectRoot, async () => undefined);+ expect(h.inspect).not.toHaveBeenCalled();+ expect(h.build).not.toHaveBeenCalled();+ expect(h.validateLaunch).not.toHaveBeenCalled();+ expect(h.launchExact).not.toHaveBeenCalled();+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ } finally {+ unlock();+ await holding;+ await Promise.allSettled([operation, cancelling]);+ openSpy.mockRestore();+ await h.close();+ }+ });+it.each(['source-recycle', 'task-cancel'] as const)('keeps B protected until the external build drains after %s', async (reason) => {const h = await projectSelectionHarness();let unblock: () => void = () => undefined;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 9d4f087587..c2334c5530 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@@ -30,12 +30,14 @@ export async function acquireIOSSimulatorProjectUse(sessionId: string,projectRoot: string,controller: AbortController,+ signal: AbortSignal = controller.signal,): Promise<(() => Promise<void>) | null> {const managedRoot = managedWorktreeRoot(projectRoot);if (!managedRoot) return null;return withWorktreeResourceLock(managedRoot, async () => {// Recheck after taking the deletion lock: selection may have raced reclamation.const available = await stat(projectRoot).then((value) => value.isDirectory(), () => false);+ signal.throwIfAborted();if (!available) {throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'The selected project directory is unavailable.');}@@ -68,5 +70,10 @@ export async function acquireIOSSimulatorProjectUse(await release();throw error;}+ }, signal).catch((error) => {+ if (signal.aborted) {+ throw new IOSSimulatorInstanceError('MUTATION_CANCELLED', 'The app operation was cancelled while acquiring its project worktree.', true);+ }+ throw error;});}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex aad0d16b1b..ecd22f283f 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -6662,7 +6662,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst sourceController = new AbortController();const sourceSignal = AbortSignal.any([signal, sourceController.signal]);const releaseProjectUse = await acquireIOSSimulatorProjectUse(- instance.sessionId, stored.artifact.worktreeRoot, sourceController,+ instance.sessionId, stored.artifact.worktreeRoot, sourceController, sourceSignal,);try {if (sourceSignal.aborted) {diff --git a/apps/desktop/src/main/worktree/resourceLock.ts b/apps/desktop/src/main/worktree/resourceLock.tsindex d1584a90fd..0ec0c336fa 100644--- a/apps/desktop/src/main/worktree/resourceLock.ts+++ b/apps/desktop/src/main/worktree/resourceLock.ts@@ -31,8 +31,9 @@ export function worktreeResourceId(key: string): string {}/** One physical directory, across tasks, aliases and Cindy processes. */-export async function withWorktreeResourceLock<T>(value: string, task: () => Promise<T>): Promise<T> {+export async function withWorktreeResourceLock<T>(value: string, task: () => Promise<T>, signal?: AbortSignal): Promise<T> {const key = await physicalWorktreeKey(value);+ signal?.throwIfAborted();const inherited = heldResources.getStore();if (inherited?.get(key)?.active) return task();const uid = typeof process.getuid === 'function' ? process.getuid() : 0;@@ -45,7 +46,7 @@ export async function withWorktreeResourceLock<T>(value: string, task: () => Pro} finally {token.active = false;}- });+ }, signal);}/** Stable physical ordering prevents overlapping batch status/move operations from deadlocking. */