Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(ios-simulator): cancel xcresult reads on exit

JiangJiahaof016e474543f
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.ts
index 2641887de2..9e1a9fe595 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
@@ -2218,6 +2218,116 @@ describe('iOS Simulator host', () => {
}
});
+ it('aborts and drains active xcresult readers before host disposal completes', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'force-quit-xcresult-session',
+ worktreeRoot: '/tmp/force-quit-xcresult-session',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ });
+ const resultBundlePath = `/tmp/CindyBuild-${crypto.randomUUID()}.xcresult`;
+ const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>(async (input) => ({
+ kind: 'xcode-project',
+ worktreeRoot: input.worktreeRoot,
+ projectRoot: input.worktreeRoot,
+ containerPath: `${input.worktreeRoot}/Demo.xcodeproj`,
+ scheme: 'Demo',
+ appPath: `${input.worktreeRoot}/Demo.app`,
+ resultBundlePath,
+ buildLogTail: 'build succeeded',
+ }));
+ let readSignal: AbortSignal | undefined;
+ let releaseRead!: () => void;
+ let projectBuilder!: IOSSimulatorProjectBuilderAdapter;
+ const readXcresult = vi.fn(function (
+ this: IOSSimulatorProjectBuilderAdapter,
+ _path: string,
+ _maxBufferBytes?: number,
+ signal?: AbortSignal,
+ ) {
+ expect(this).toBe(projectBuilder);
+ return new Promise<string>((resolve) => {
+ readSignal = signal;
+ releaseRead = () => {
+ resolve('late xcresult content that must not be cached');
+ };
+ });
+ });
+ projectBuilder = { build, readXcresult };
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ projectBuilder,
+ appLifecycle: {
+ inspectArtifact: vi.fn(async () => ({
+ artifactId: 'artifact-xcresult',
+ worktreeRoot: '/tmp/force-quit-xcresult-session',
+ appPath: '/tmp/force-quit-xcresult-session/Demo.app',
+ bundleId: 'com.example.demo',
+ createdAt: '2026-08-08T00:00:00.000Z',
+ })),
+ installExact: vi.fn(async () => undefined),
+ launchExact: vi.fn(async () => undefined),
+ terminateExact: vi.fn(async () => undefined),
+ openUrlExact: vi.fn(async () => undefined),
+ },
+ mediaCapture: {
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async () => localSession('force-quit-xcresult-session')),
+ });
+ await host.reconcileOwnership();
+ const current = actor.getOwned('force-quit-xcresult-session', instance.instanceId);
+ const built = await host.callTool(
+ 'build_app',
+ {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ },
+ { sessionId: current.sessionId, origin: 'user' },
+ );
+ expect(built).toMatchObject({ ok: true });
+ const diagnosticsId = (built as { ok: true; data: { diagnostics: { diagnosticsId: string } } })
+ .data.diagnostics.diagnosticsId;
+ const readPromise = host.callTool(
+ 'read_build_diagnostics',
+ { diagnosticsId, source: 'xcresult' },
+ { sessionId: current.sessionId, origin: 'agent' },
+ );
+ await vi.waitFor(() => expect(readXcresult).toHaveBeenCalledOnce());
+
+ expect(() => host.abortOperationsForExit()).not.toThrow();
+ expect(readSignal?.aborted).toBe(true);
+ let disposeSettled = false;
+ const disposePromise = host.dispose().then(() => {
+ disposeSettled = true;
+ });
+ await Promise.resolve();
+ expect(disposeSettled).toBe(false);
+
+ releaseRead();
+
+ await disposePromise;
+ await expect(readPromise).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ expect(readXcresult).toHaveBeenCalledWith(resultBundlePath, undefined, readSignal);
+ });
+
it('synchronously aborts active builds before updater force-quit', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 537c6790d5..8fbb339b3d 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -917,6 +917,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const buildDiagnostics = new Map<string, BuildDiagnosticRecord>();
const buildDiagnosticExpiryTimers = new Map<string, ReturnType<typeof setTimeout>>();
const buildDiagnosticReaders = new Map<string, number>();
+ const buildDiagnosticReadExitController = new AbortController();
+ const activeBuildDiagnosticReads = new Set<Promise<void>>();
const pendingBuildDiagnosticRemoval = new Map<string, BuildDiagnosticRecord>();
let buildResultBundlesReconciled = false;
let buildResultBundlesReconcilePromise: Promise<void> | null = null;
@@ -5385,16 +5387,36 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
};
}
if (diagnostic.xcresultText === null) {
- buildDiagnosticReaders.set(
- diagnosticsId,
- (buildDiagnosticReaders.get(diagnosticsId) ?? 0) + 1,
- );
- try {
- diagnostic.xcresultText = publicBuildText(
- await projectBuilder.readXcresult(diagnostic.resultBundlePath),
+ const readXcresult = projectBuilder.readXcresult.bind(projectBuilder);
+ const readOperation = (async () => {
+ buildDiagnosticReaders.set(
+ diagnosticsId,
+ (buildDiagnosticReaders.get(diagnosticsId) ?? 0) + 1,
);
+ try {
+ const rawXcresult = await readXcresult(
+ diagnostic.resultBundlePath!,
+ undefined,
+ buildDiagnosticReadExitController.signal,
+ );
+ if (buildDiagnosticReadExitController.signal.aborted) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The Xcode result bundle read was cancelled because the simulator host is shutting down.',
+ true,
+ );
+ }
+ assertHostActive();
+ diagnostic.xcresultText = publicBuildText(rawXcresult);
+ } finally {
+ await releaseBuildDiagnosticReader(diagnosticsId);
+ }
+ })();
+ activeBuildDiagnosticReads.add(readOperation);
+ try {
+ await readOperation;
} finally {
- await releaseBuildDiagnosticReader(diagnosticsId);
+ activeBuildDiagnosticReads.delete(readOperation);
}
}
text = diagnostic.xcresultText;
@@ -5911,6 +5933,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
},
abortOperationsForExit() {
void abortPendingCreateReconciliation();
+ buildDiagnosticReadExitController.abort();
try {
actor.abortOperationsForExit();
} catch (error) {
@@ -5946,6 +5969,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (disposePromise) return disposePromise;
disposePromise = (async () => {
const pendingCreateReconciliation = abortPendingCreateReconciliation();
+ buildDiagnosticReadExitController.abort();
+ const buildDiagnosticReads = [...activeBuildDiagnosticReads];
actor.abortOperationsForExit();
const lifecycleStarts = actor.cancelAllLifecycleStarts();
const mutations = actor.cancelAllMutations();
@@ -5963,6 +5988,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
lifecycleStarts,
mutations,
...builds.map((build) => build.settled),
+ Promise.allSettled(buildDiagnosticReads).then(() => undefined),
]);
clearVisualBaselines();
await Promise.all(
diff --git a/packages/ios-simulator-runtime/src/project-adapter.test.ts b/packages/ios-simulator-runtime/src/project-adapter.test.ts
index 1b7d60dc65..1cd727bb27 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.test.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.test.ts
@@ -542,4 +542,52 @@ describe("IOSSimulatorProjectBuilder", () => {
code: "ENOENT",
});
});
+
+ it("cancels an in-flight xcresult read through the command runner", async () => {
+ const controller = new AbortController();
+ const run = vi.fn(
+ async (
+ _command: string,
+ _args: readonly string[],
+ options?: Parameters<IOSSimulatorCommandRunner["run"]>[2],
+ ) => {
+ await new Promise<void>((resolve) => {
+ if (options?.signal?.aborted) resolve();
+ else
+ options?.signal?.addEventListener("abort", () => resolve(), {
+ once: true,
+ });
+ });
+ return { stdout: "", stderr: "", exitCode: null };
+ },
+ );
+ const builder = new IOSSimulatorProjectBuilder({ commandRunner: { run } });
+ const readPromise = builder.readXcresult(
+ "/tmp/CindyBuild-cancelled.xcresult",
+ 1024,
+ controller.signal,
+ );
+ await vi.waitFor(() => expect(run).toHaveBeenCalledOnce());
+
+ controller.abort();
+
+ await expect(readPromise).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
+ expect(run).toHaveBeenCalledWith(
+ "xcrun",
+ [
+ "xcresulttool",
+ "get",
+ "--path",
+ "/tmp/CindyBuild-cancelled.xcresult",
+ "--format",
+ "json",
+ ],
+ expect.objectContaining({
+ signal: controller.signal,
+ maxBufferBytes: 1024,
+ }),
+ );
+ });
});
diff --git a/packages/ios-simulator-runtime/src/project-adapter.ts b/packages/ios-simulator-runtime/src/project-adapter.ts
index 041e212255..c922617d67 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.ts
@@ -582,6 +582,7 @@ export class IOSSimulatorProjectBuilder {
async readXcresult(
resultBundlePath: string,
maxBufferBytes = 2 * 1024 * 1024,
+ signal?: AbortSignal,
): Promise<string> {
const result = await this.#runner.run(
"xcrun",
@@ -590,8 +591,16 @@ export class IOSSimulatorProjectBuilder {
timeoutMs: 60_000,
maxBufferBytes,
env: this.#childEnvironment,
+ signal,
},
);
+ if (signal?.aborted) {
+ throw new IOSSimulatorInstanceError(
+ "MUTATION_CANCELLED",
+ "The Xcode result bundle read was cancelled because the simulator host is shutting down.",
+ true,
+ );
+ }
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"APP_BUILD_FAILED",