Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(ios-simulator): support explicit external project directories
JiangJiahao10cecfa3075d
diff --git a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.tsindex 13a342e429..f1e5f2c00b 100644--- a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts@@ -273,6 +273,16 @@ describe('desktop MCP approval policy', () => {}});+ it('keeps external project builds on the existing task permission policy', () => {+ const route = { instanceId: 'instance-a', generation: 2, leaseId: 'lease-a' };+ for (const projectDir of [undefined, '/projects/worktree-b', '../worktree-b']) {+ expect(getDesktopMcpToolApprovalPolicy({+ serverName: 'cindy_ios_simulator', toolName: 'call_tool',+ toolParams: { name: 'build_app', args: { ...route, projectDir } },+ })).toBe('prompt-each-time');+ }+ });+it('discloses host file access before an agent starts an Xcode build', () => {setMainLocale('en');expect(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 25c3651322..bc0efe41f6 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@@ -48,6 +48,7 @@ import {IOSSimulatorOwnershipStore,IOSSimulatorOwnershipRegistryFile,IOSSimulatorProjectBuildError,+ IOSSimulatorProjectBuilder,IOSSimulatorResourceScheduler,WdaError,WdaProcessManager,@@ -71,6 +72,9 @@ 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 { readWorktreeRuntimePaths } from '../../worktree/runtimeLeases';import {cancelIOSSimulatorSessionOperations,cleanupIOSSimulatorRemovedSession,@@ -318,6 +322,219 @@ describe('iOS Simulator host', () => {return { id, workDir: `/tmp/${id}`, remoteHostId: null };}+ async function projectSelectionHarness(mobile = false) {+ const temp = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-project-dir-'));+ const root = await realpath(temp);+ const taskRoot = path.join(root, 'task-a');+ const otherTaskRoot = path.join(root, 'task-c');+ const projectRoot = path.join(root, '.cindy-worktrees', 'project-b');+ const userData = path.join(root, 'user-data');+ await mkdir(path.join(userData, '.dev-instances'), { recursive: true });+ await mkdir(path.join(taskRoot, 'Demo.xcodeproj'), { recursive: true });+ await mkdir(path.join(otherTaskRoot, 'Demo.xcodeproj'), { recursive: true });+ await mkdir(path.join(projectRoot, 'Demo.xcodeproj'), { recursive: true });+ if (mobile) {+ const mobileRoot = path.join(projectRoot, 'apps', 'mobile');+ await mkdir(mobileRoot, { recursive: true });+ await writeFile(path.join(mobileRoot, 'app.config.js'), 'export default {};');+ await writeFile(path.join(mobileRoot, 'package.json'), JSON.stringify({ name: 'mobile' }));+ }+ const sourceApp = path.join(root, 'Demo.app');+ await mkdir(sourceApp);+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(), bootExact: vi.fn(), shutdownExact: vi.fn(),+ createExact: vi.fn(), deleteExact: vi.fn(),+ },+ });+ const inspector = new IOSSimulatorProjectBuilder();+ const inspect = vi.fn(inspector.inspect.bind(inspector));+ const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>(async (input) => ({+ kind: mobile ? 'cindy-mobile' : 'xcode-project',+ worktreeRoot: input.worktreeRoot,+ projectRoot: input.worktreeRoot,+ containerPath: input.containerPath ?? null,+ scheme: 'Demo', appPath: sourceApp, buildLogTail: '',+ }));+ const validateLaunch = vi.fn<NonNullable<IOSSimulatorProjectBuilderAdapter['validateLaunch']>>(async () => null);+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(async (worktreeRoot, appPath, authorizedRoot) => ({+ artifactId: crypto.randomUUID(), worktreeRoot, appPath,+ authorizedRoot: authorizedRoot ?? path.dirname(appPath),+ bundleId: 'com.example.demo', createdAt: new Date().toISOString(),+ }));+ const installExact = vi.fn(async () => undefined);+ const launchExact = vi.fn(async () => undefined);+ const secondDevice = { ...READY_REPORT.devices[0]!, udid: 'F05BFC28-5AE5-48C8-97E0-EF064558B4D3', state: 'Shutdown' as const };+ const host = createIOSSimulatorHost({+ actor, resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => ({+ ...READY_REPORT, devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }, secondDevice],+ })) },+ getSession: vi.fn(async (id) => ({ id, workDir: id === 'session-c' ? otherTaskRoot : taskRoot, remoteHostId: null })),+ projectBuilder: { inspect, build, validateLaunch },+ appLifecycle: {+ inspectArtifact, installExact, launchExact,+ terminateExact: vi.fn(), openUrlExact: vi.fn(),+ },+ });+ const context = { sessionId: 'session-a', origin: 'user' as const };+ const close = async () => {+ await host.dispose();+ getPath.mockRestore();+ await rm(temp, { recursive: true, force: true });+ };+ try {+ const attached = await host.callTool('attach_device', { udid: READY_REPORT.devices[0]!.udid }, context);+ expect(attached, JSON.stringify(attached)).toMatchObject({ ok: true });+ const attachedInstance = actor.list(context.sessionId)[0]!;+ // Exercise Host app mutations with a ready actor and mocked CoreSimulator;+ // the real viewer/WDA startup is outside these source-selection tests.+ const instance = await actor.start({+ sessionId: context.sessionId, instanceId: attachedInstance.instanceId,+ generation: attachedInstance.generation, leaseId: attachedInstance.lease.id,+ });+ const route = { instanceId: instance.instanceId, generation: instance.generation, leaseId: instance.lease.id };+ return { root, taskRoot, otherTaskRoot, projectRoot, secondDevice, actor, host, context, route, build, inspect, inspectArtifact, installExact, launchExact, validateLaunch, close };+ } catch (error) {+ await close();+ throw error;+ }+ }++ it('selects an external build source per call while keeping ownership, artifacts and caches distinct', async () => {+ const h = await projectSelectionHarness();+ try {+ const original = h.actor.list('session-a')[0]!;+ expect(await h.host.callTool('build_app', h.route, h.context)).toMatchObject({ ok: true });+ const external = await h.host.callTool('build_app', { ...h.route, projectDir: h.projectRoot, containerPath: './Demo.xcodeproj' }, h.context);+ expect(external).toMatchObject({ ok: true, data: { artifact: { project: { name: 'project-b', containerPath: 'Demo.xcodeproj' } } } });+ const alias = path.join(h.root, 'alias-b');+ await symlink(h.projectRoot, alias, 'junction');+ expect(await h.host.callTool('build_app', { ...h.route, projectDir: alias }, h.context)).toMatchObject({ ok: true });+ expect(await h.host.callTool('build_app', h.route, h.context)).toMatchObject({ ok: true });+ const inputs = h.build.mock.calls.map(([input]) => input);+ expect(inputs.map((input) => input.worktreeRoot)).toEqual([h.taskRoot, h.projectRoot, h.projectRoot, h.taskRoot]);+ expect(inputs[0]!.derivedDataPath).not.toBe(inputs[1]!.derivedDataPath);+ expect(inputs[1]!.derivedDataPath).toBe(inputs[2]!.derivedDataPath);+ expect(inputs[0]!.derivedDataPath).toBe(inputs[3]!.derivedDataPath);+ expect(inputs[1]!.clonedSourcePackagesDirPath).toBe(inputs[2]!.clonedSourcePackagesDirPath);+ expect(h.inspectArtifact.mock.calls.map(([source]) => source)).toEqual([h.taskRoot, h.projectRoot, h.projectRoot, h.taskRoot]);+ expect(h.actor.list('session-a')[0]).toMatchObject({+ sessionId: 'session-a', worktreeRoot: h.taskRoot, sourceFingerprint: original.sourceFingerprint,+ instanceId: original.instanceId, generation: original.generation, lease: { id: original.lease.id },+ });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ } finally { await h.close(); }+ });++ it('installs the external artifact on task A and validates Cindy Mobile launch against B', async () => {+ const h = await projectSelectionHarness(true);+ try {+ const result = await h.host.callTool('build_app', { ...h.route, projectDir: path.relative(h.taskRoot, h.projectRoot) }, h.context);+ expect(result).toMatchObject({ ok: true });+ const artifactId = (await h.inspectArtifact.mock.results[0]!.value).artifactId;+ const installed = await h.host.callTool('install_app', { ...h.route, artifactId }, h.context);+ expect(installed, JSON.stringify(installed)).toMatchObject({ ok: true });+ const launched = await h.host.callTool('launch_app', { ...h.route, artifactId, args: [] }, h.context);+ expect(launched, JSON.stringify(launched)).toMatchObject({ ok: true });+ expect(h.validateLaunch).toHaveBeenCalledWith(h.projectRoot, READY_REPORT.devices[0]!.udid, expect.any(AbortSignal));+ expect(h.installExact).toHaveBeenCalledWith(READY_REPORT.devices[0]!.udid, expect.objectContaining({ artifactId, worktreeRoot: h.projectRoot }), expect.any(AbortSignal));+ expect(h.launchExact).toHaveBeenCalledWith(READY_REPORT.devices[0]!.udid, expect.objectContaining({ artifactId, worktreeRoot: h.projectRoot }), [], expect.any(AbortSignal));+ expect(await h.host.callTool('install_app', { ...h.route, artifactId }, { sessionId: 'session-b', origin: 'user' })).toMatchObject({ ok: false });+ } finally { await h.close(); }+ });++ it('rejects invalid project directories and container escapes relative to the selected source', async () => {+ const h = await projectSelectionHarness();+ try {+ const file = path.join(h.root, 'file');+ await writeFile(file, 'not a directory');+ const outside = path.join(h.taskRoot, 'Demo.xcodeproj');+ await symlink(outside, path.join(h.projectRoot, 'Escape.xcodeproj'), 'junction');+ for (const args of [+ { projectDir: path.join(h.root, 'missing') }, { projectDir: file }, { projectDir: '' },+ { projectDir: h.projectRoot, containerPath: outside },+ { projectDir: h.projectRoot, containerPath: path.relative(h.projectRoot, outside) },+ { projectDir: h.projectRoot, containerPath: 'Escape.xcodeproj' },+ { containerPath: path.join(h.projectRoot, 'Demo.xcodeproj') },+ ]) {+ expect(await h.host.callTool('build_app', { ...h.route, ...args }, h.context)).toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });+ }+ expect(h.build).not.toHaveBeenCalled();+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ expect(await h.host.callTool('build_app', { ...h.route, projectDir: h.projectRoot, containerPath: 'Demo.xcodeproj' }, h.context)).toMatchObject({ ok: true });+ } finally { await h.close(); }+ });++ it('serializes two tasks building the same external source through different path spellings', async () => {+ const h = await projectSelectionHarness();+ let unblock: () => void = () => undefined;+ const gate = new Promise<void>((resolve) => { unblock = resolve; });+ const buildImpl = h.build.getMockImplementation()!;+ h.build.mockImplementationOnce(async (input) => { await gate; return buildImpl(input); });+ try {+ const otherContext = { sessionId: 'session-c', origin: 'user' as const };+ expect(await h.host.callTool('attach_device', { udid: h.secondDevice.udid }, otherContext)).toMatchObject({ ok: true });+ const otherInstance = h.actor.list('session-c')[0]!;+ const otherRoute = { instanceId: otherInstance.instanceId, generation: otherInstance.generation, leaseId: otherInstance.lease.id };+ expect(otherInstance.worktreeRoot).toBe(h.otherTaskRoot);+ const first = h.host.callTool('build_app', { ...h.route, projectDir: h.projectRoot }, h.context);+ await vi.waitFor(() => expect(h.build).toHaveBeenCalledOnce());+ const otherArgs = { ...otherRoute, projectDir: path.relative(h.otherTaskRoot, h.projectRoot), containerPath: './Demo.xcodeproj' };+ expect(await h.host.callTool('build_app', otherArgs, otherContext)).toMatchObject({ ok: false, errorCode: 'DEVICE_BUSY' });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(h.projectRoot)]));+ unblock();+ expect(await first).toMatchObject({ ok: true });+ expect(await h.host.callTool('build_app', otherArgs, otherContext)).toMatchObject({ ok: true });+ const [a, c] = h.build.mock.calls.map(([input]) => input);+ expect(a!.derivedDataPath).toBe(c!.derivedDataPath);+ expect(a!.clonedSourcePackagesDirPath).toBe(c!.clonedSourcePackagesDirPath);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ } finally { unblock(); 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;+ const gate = new Promise<void>((resolve) => { unblock = resolve; });+ h.build.mockImplementationOnce(async () => {+ await gate;+ throw new Error('cancelled build drained');+ });+ try {+ const result = h.host.callTool('build_app', { ...h.route, projectDir: h.projectRoot }, h.context);+ await vi.waitFor(() => expect(h.build).toHaveBeenCalledOnce());+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(h.projectRoot)]));+ let cancelFinished = false;+ let cancelling: Promise<void> | undefined;+ if (reason === 'task-cancel') {+ cancelling = h.host.cancelSessionOperations('session-a').then(() => { cancelFinished = true; });+ } else {+ const record = await newRecycleRecord({+ sessionId: 'session-b', name: 'project-b', path: h.projectRoot, baseRepo: h.root,+ branch: 'codex/project-b', sourceBranch: 'main', createdAt: new Date().toISOString(),+ });+ const identity = await stat(h.projectRoot);+ record.directoryIdentity = `${identity.dev}:${identity.ino}:${identity.birthtimeMs}`;+ await withWorktreeResourceLock(h.projectRoot, () => writeRecycleRecord(record));+ }+ await vi.waitFor(() => expect(h.build.mock.calls[0]![0].signal!.aborted).toBe(true));+ expect(cancelFinished).toBe(false);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(h.projectRoot)]));+ unblock();+ expect(await result).toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });+ await cancelling;+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ expect((await stat(h.projectRoot)).isDirectory()).toBe(true);+ if (reason === 'source-recycle') {+ expect(await h.host.callTool('build_app', { ...h.route, projectDir: h.projectRoot }, h.context)).toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });+ expect(h.build).toHaveBeenCalledOnce();+ }+ } finally { unblock(); await h.close(); }+ });+it('keeps the default ownership registry lazy for disabled MCP discovery and teardown', async () => {const getPath = vi.spyOn(app, 'getPath');try {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.tsnew file mode 100644index 0000000000..9d4f087587--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-project-source.ts@@ -0,0 +1,72 @@+import { realpath, stat } from 'node:fs/promises';+import path from 'node:path';++import { IOSSimulatorInstanceError } from '@cindy/ios-simulator-runtime';++import { createLogger } from '../logger';+import { subscribeWorktreeRecycleEvents } from '../worktree/recycleEvents';+import { readRecycleRecord } from '../worktree/recycleJournal';+import { withWorktreeResourceLock, worktreeResourceId } from '../worktree/resourceLock';+import {+ acquireWorktreeRuntimeLease,+ managedWorktreeRoot,+ releaseWorktreeRuntimeLease,+} from '../worktree/runtimeLeases';++const log = createLogger('ios-simulator-project-source');++/** Project selection changes the build source, never the task or device owner. */+export async function resolveIOSSimulatorProjectDir(taskRoot: string, projectDir?: string): Promise<string> {+ if (projectDir === undefined) return taskRoot;+ try {+ const resolved = await realpath(path.resolve(taskRoot, projectDir));+ if ((await stat(resolved)).isDirectory()) return resolved;+ } catch { /* Return a stable tool error rather than a raw filesystem path. */ }+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'projectDir must resolve to an existing local directory.');+}++/** Reuse the worktree recycler's cross-process lease; release only after source I/O has drained. */+export async function acquireIOSSimulatorProjectUse(+ sessionId: string,+ projectRoot: string,+ controller: AbortController,+): 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);+ if (!available) {+ throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'The selected project directory is unavailable.');+ }+ const lease = await acquireWorktreeRuntimeLease(`ios-simulator:${sessionId}`, projectRoot);+ if (!lease) return null;+ const resourceId = worktreeResourceId(lease.physicalPath);+ const unsubscribe = subscribeWorktreeRecycleEvents((event) => {+ if (!event.opportunity && event.resourceId === resourceId) controller.abort();+ });+ const release = async (): Promise<void> => {+ unsubscribe();+ try {+ await releaseWorktreeRuntimeLease(lease);+ } catch {+ // The durable release request is retried by worktree maintenance. Keeping+ // the lease protects the directory until that retry succeeds.+ log.warn('project worktree lease release deferred');+ }+ };+ try {+ const record = await readRecycleRecord(managedRoot);+ if (record && !['removed', 'restored'].includes(record.phase)) {+ const identity = await stat(managedRoot);+ if (record.directoryIdentity === `${identity.dev}:${identity.ino}:${identity.birthtimeMs}`) {+ controller.abort();+ }+ }+ return release;+ } catch (error) {+ await release();+ throw error;+ }+ });+}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex 4818e8c2f7..aad0d16b1b 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -18,6 +18,8 @@ import path from 'node:path';import { app, BrowserWindow } from 'electron';+import { acquireIOSSimulatorProjectUse, resolveIOSSimulatorProjectDir } from './ios-simulator-project-source';+import {createIOSSimulatorRuntime,createIOSSimulatorSimctlLifecycle,@@ -6233,7 +6235,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I// Validate before beginBuild: a rejected argument must not leave a// build registered that never reaches the cleanup finally below.const containerPath = readOptionalString(args, 'containerPath', 4_096);+ const projectDir = readOptionalString(args, 'projectDir', 4_096);const activeBuild = beginBuild(instance, buildAdmissionEpoch);+ let releaseProjectUse: (() => Promise<void>) | null = null;let buildLeaseHeartbeatError: unknown = null;let stopBuildLeaseHeartbeat: (() => void) | null = null;const expectedArch = process.arch === 'x64' ? 'x86_64' : 'arm64';@@ -6259,8 +6263,15 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I// (`Demo.xcodeproj`, `./Demo.xcodeproj`, absolute paths, or the// implicit single-container selection) must share one identity,// while an invalid container must not create empty cache trees.+ const projectRoot = await resolveIOSSimulatorProjectDir(instance.worktreeRoot, projectDir);+ releaseProjectUse = await acquireIOSSimulatorProjectUse(+ instance.sessionId, projectRoot, activeBuild.controller,+ );+ if (activeBuild.controller.signal.aborted) {+ throw new IOSSimulatorInstanceError('MUTATION_CANCELLED', 'The app build was cancelled before project inspection.', true);+ }const inspectedProject = projectBuilder.inspect- ? await projectBuilder.inspect(instance.worktreeRoot, containerPath)+ ? await projectBuilder.inspect(projectRoot, containerPath): null;if (disposePromise) throw new IOSSimulatorHostDisposedError();if (buildLeaseHeartbeatError) throw buildLeaseHeartbeatError;@@ -6272,7 +6283,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I);}actor.assertRoute(route);- const canonicalWorktreeRoot = inspectedProject?.worktreeRoot ?? instance.worktreeRoot;+ const canonicalWorktreeRoot = inspectedProject?.worktreeRoot ?? projectRoot;const canonicalContainerPath = inspectedProject? (inspectedProject.containerPath ?? undefined): containerPath;@@ -6423,7 +6434,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Itry {await assertIOSSimulatorArtifactSymlinksContained(immutableAppPath);artifact = await appLifecycle.inspectArtifact(- instance.worktreeRoot,+ canonicalWorktreeRoot,immutableAppPath,derivedDataPath,activeBuild.controller.signal,@@ -6475,6 +6486,15 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IprojectKind: built.kind,scheme: built.scheme,createdAt: artifact.createdAt,+ project: {+ name: path.basename(canonicalWorktreeRoot),+ sourceFingerprint: sourceFingerprint(canonicalWorktreeRoot),+ containerPath: canonicalContainerPath+ ? (path.isAbsolute(canonicalContainerPath)+ ? path.relative(canonicalWorktreeRoot, canonicalContainerPath)+ : canonicalContainerPath)+ : undefined,+ },},diagnostics,},@@ -6500,6 +6520,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I// live skip callback still protects builds admitted mid-sweep.scheduleBuildCachePrune();}+ await releaseProjectUse?.();finishBuild(instance.instanceId, activeBuild);}}@@ -6638,11 +6659,26 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IrequireControlGrant(instance, context);const stored = appArtifacts.get(artifactId);if (stored?.projectKind === 'cindy-mobile' && projectBuilder.validateLaunch) {- await projectBuilder.validateLaunch(- stored.artifact.worktreeRoot,- instance.simulatorUdid,- signal,+ const sourceController = new AbortController();+ const sourceSignal = AbortSignal.any([signal, sourceController.signal]);+ const releaseProjectUse = await acquireIOSSimulatorProjectUse(+ instance.sessionId, stored.artifact.worktreeRoot, sourceController,);+ try {+ if (sourceSignal.aborted) {+ throw new IOSSimulatorInstanceError('MUTATION_CANCELLED', 'The app launch was cancelled before project validation.', true);+ }+ await projectBuilder.validateLaunch(+ stored.artifact.worktreeRoot,+ instance.simulatorUdid,+ sourceSignal,+ );+ if (sourceSignal.aborted) {+ throw new IOSSimulatorInstanceError('MUTATION_CANCELLED', 'The app launch was cancelled during project validation.', true);+ }+ } finally {+ await releaseProjectUse?.();+ }}await appLifecycle.launchExact(instance.simulatorUdid,diff --git a/docs/ios-simulator-integration-plan.md b/docs/ios-simulator-integration-plan.mdindex 9facbbef97..410e5f5a73 100644--- a/docs/ios-simulator-integration-plan.md+++ b/docs/ios-simulator-integration-plan.md@@ -59,7 +59,7 @@- 已实现 ownership、lease、generation、跨 Session 占用拒绝、每设备 Agent grant、精确 UDID 生命周期与 10 分钟 grace 语义。- 已实现固定 WDA 源码归档随包、校验解包、按 source/Xcode/runtime/arch 缓存的构建与进程管理;Xcode 计划使用 `-quiet` 保持有界日志。- 已实现稳定 element ID、旧 screen snapshot 拒绝、每实例输入串行、操作后 snapshot 失效和 bounded MJPEG 自动重连。-- 已实现 Generic Xcode 与 Cindy Mobile project adapter;App artifact 绑定当前 worktree/实例,不向 MCP 或 renderer 暴露本地路径、端口和原始 Xcode 输出。+- 已实现 Generic Xcode 与 Cindy Mobile project adapter;`build_app.projectDir` 可显式选择任务目录外的本地工程或 worktree,省略时每次回到当前任务目录。App artifact 记录实际构建目录,并继续绑定当前任务的实例;不向 MCP 或 renderer 暴露本地绝对路径、端口和原始 Xcode 输出。- 显式截图/录屏已接入 `cindy-media` Session 引用;stop/detach 会终止活动录屏并清理临时目录,transient frame 始终只在内存。- 已实现 Session 级有界 diagnostics store,以及全局串行 start、soft limit 2、hard limit 4、内存余量拒绝的 resource scheduler。- build 与 open URL 使用逐次审批,设备 mutation 使用 per-device grant,两类权限不能互相替代。@@ -989,7 +989,7 @@ MVP 规则:| `detach_device` | 停止 stream、解除 pane viewer,不等于 shutdown || `start_instance` | boot、等待 ready、连接 driver || `stop_instance` | 安全停止并释放资源 |-| `build_app` | 经 Session permission mode 构建并返回 diagnostics ID |+| `build_app` | 经 Session permission mode 从可选 `projectDir` 构建并返回 artifact / diagnostics ID || `install_app` | 安装已验证来源的 `.app` || `launch_app` | 启动 bundle,支持受控 args/env || `terminate_app` | 停止当前 bundle |@@ -1017,6 +1017,18 @@ MVP 规则:| `start_recording` | 开始显式录屏 || `stop_recording` | 停止并摄入 `cindy-media` |+`build_app.projectDir` 接受本地绝对目录或相对当前任务目录的路径,Host 以 realpath+解析并检查目录存在。`containerPath` 相对所选目录解析,仍必须位于该目录内;显式目录+不改变任务身份、设备 route 或设备控制授权。每次调用独立选择来源,不保存“上次目录”。+DerivedData / SPM 以实际来源目录、架构、container 分组;artifact 保留来源目录,+Cindy Mobile 启动时也对该来源执行 Metro 检查。返回的 project 摘要只含目录名、目录+fingerprint 和相对 container 路径;该 fingerprint 不代表 Git revision 或源码内容。++构建和 Metro 检查借用现有 worktree runtime lease 保护所选托管目录。本进程的回收事件+会取消正在使用该目录的操作,实际读取结束后才释放租约;跨进程回收也必须等待租约释放。+任务 A 结束时排空自己的操作,不因其构建了 B 就把 B 加入 A 的目录删除范围。+这仍是工程选择与目录边界校验,不是对 Xcode build scripts 的文件系统沙箱。+### 13.1.1 稳定性扩展工具与动作契约在 MVP 工具之上,Host 已提供一组面向 Agent 的确定性稳定性能力:diff --git a/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts b/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.tsindex 81c80c12fe..ea0369e726 100644--- a/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts+++ b/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts@@ -262,7 +262,7 @@ describe("createIOSSimulatorMcpServer", () => {await Promise.all([client.close(), server.close()]);});- it("accepts an explicit generic Xcode container for build_app", async () => {+ it.each([undefined, "/projects/worktree-b", "../worktree-b"])("accepts an explicit Xcode container with projectDir %s", async (projectDir) => {const callTool = vi.fn(async () => ({ ok: true, data: { built: true } }));const { client, server } = await connect({ callTool }, "session-a");const args = {@@ -271,6 +271,7 @@ describe("createIOSSimulatorMcpServer", () => {leaseId: "lease-a",containerPath: "Examples/App/App.xcworkspace",scheme: "App",+ ...(projectDir === undefined ? {} : { projectDir }),};const result = await client.callTool({name: "call_tool",@@ -285,6 +286,30 @@ describe("createIOSSimulatorMcpServer", () => {await Promise.all([client.close(), server.close()]);});+ it("rejects malformed project selection and task identity overrides before calling Host", async () => {+ const callTool = vi.fn();+ const { client, server } = await connect({ callTool }, "session-a");+ try {+ for (const extra of [+ { projectDir: " " }, { projectDir: 7 }, { projectDir: "a".repeat(4097) },+ { projectDir: "/projects/b", sessionId: "session-b" },+ { worktreeRoot: "/projects/b" }, { cwd: "/projects/b" },+ ]) {+ const result = await client.callTool({+ name: "call_tool",+ arguments: { name: "build_app", args: {+ instanceId: "instance-a", generation: 1, leaseId: "lease-a", ...extra,+ } },+ });+ expect(result.isError).toBe(true);+ expect(JSON.parse(readResultText(result))).toMatchObject({ errorCode: "INVALID_ARGS" });+ }+ expect(callTool).not.toHaveBeenCalled();+ } finally {+ await Promise.all([client.close(), server.close()]);+ }+ });+it("preserves structured host business errors", async () => {const { client, server } = await connect({diff --git a/packages/lizi-mcps/src/ios-simulator/tools.ts b/packages/lizi-mcps/src/ios-simulator/tools.tsindex 6b95064fe3..51d18ccf0e 100644--- a/packages/lizi-mcps/src/ios-simulator/tools.ts+++ b/packages/lizi-mcps/src/ios-simulator/tools.ts@@ -631,9 +631,10 @@ export function registerIOSSimulatorTools(register({name: "build_app",description:- "Build one iOS app for the embedded simulator instance. Xcode runs the project's build scripts as the current macOS user, so scripts may read or modify files outside the project and build output is returned to the Agent. Approve only for a trusted project. For repositories with multiple or nested Xcode containers, pass containerPath as a worktree-relative path (or an absolute path that still resolves inside the worktree), then select a shared scheme when needed. Continue with install_app and launch_app on this same Cindy session.",+ "Build one iOS app for the embedded simulator instance. Xcode runs the project's build scripts as the current macOS user, so scripts may read or modify files outside the project and build output is returned to the Agent. Approve only for a trusted project. projectDir optionally selects another local project or worktree directory, absolute or relative to this task's worktree; omission uses this task's worktree on every call. Pass containerPath relative to the selected projectDir (or an absolute path inside it) to choose a nested Xcode container, then select a shared scheme when needed. Continue with install_app and launch_app using the returned artifactId on this same Cindy session; projectDir does not transfer task or device ownership.",inputShape: {...routeShape,+ projectDir: z.string().trim().min(1).max(4096).optional(),containerPath: z.string().trim().min(1).max(4096).optional(),scheme: z.string().min(1).max(256).optional(),},