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): stabilize builds and device shutdown

JiangJiahao12c63df6166e
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 33dbef540d..0fc3005ec5 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,3 +1,7 @@
+import { mkdir, rm, stat, utimes } from 'node:fs/promises';
+import path from 'node:path';
+
+import { app } from 'electron';
import { describe, expect, it, vi } from 'vitest';
import {
@@ -5,6 +9,7 @@ import {
evaluateIOSSimulatorNativeCapabilityAdmission,
IOSSimulatorInstanceActor,
IOSSimulatorOwnershipStore,
+ IOSSimulatorProjectBuildError,
IOSSimulatorResourceScheduler,
WdaError,
type IOSSimulatorEnvironmentReport,
@@ -87,6 +92,71 @@ describe('iOS Simulator host', () => {
expect(environment).not.toHaveProperty('data.devices.0.availabilityError');
});
+ it('keeps build diagnostics host-available without a running simulator instance', async () => {
+ 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 host = createIOSSimulatorHost({
+ actor,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+
+ await expect(host.describeTools('session-a')).resolves.toMatchObject({
+ tools: {
+ build_app: { state: 'requires-instance', backend: 'host' },
+ read_build_diagnostics: { state: 'available', backend: 'host' },
+ },
+ });
+ });
+
+ it('removes stale orphaned xcresult bundles during ownership reconciliation', async () => {
+ const projectRoot = path.join(
+ app.getPath('userData'),
+ 'ios-simulator',
+ 'projects',
+ `orphan-reconcile-${crypto.randomUUID()}`,
+ );
+ const staleBundle = path.join(projectRoot, `CindyBuild-${crypto.randomUUID()}.xcresult`);
+ const freshBundle = path.join(projectRoot, `CindyBuild-${crypto.randomUUID()}.xcresult`);
+ await mkdir(staleBundle, { recursive: true });
+ await mkdir(freshBundle, { recursive: true });
+ const staleTime = new Date(Date.now() - 31 * 60_000);
+ await utimes(staleBundle, staleTime, staleTime);
+ 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 host = createIOSSimulatorHost({
+ actor,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+
+ try {
+ await host.reconcileOwnership();
+
+ await expect(stat(staleBundle)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(stat(freshBundle)).resolves.toBeDefined();
+ } finally {
+ await host.dispose();
+ await rm(projectRoot, { recursive: true, force: true });
+ }
+ });
+
it('reconciles a persisted binding with fresh generation and lease on startup', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
@@ -739,6 +809,85 @@ describe('iOS Simulator host', () => {
expect(stopDriver).toHaveBeenCalled();
});
+ it('does not retain build results that finish after host disposal', 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: 'dispose-build-session',
+ worktreeRoot: '/tmp/dispose-build-session',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ });
+ const projectRoot = path.join(
+ app.getPath('userData'),
+ 'ios-simulator',
+ 'projects',
+ `dispose-build-${crypto.randomUUID()}`,
+ );
+ const resultBundlePath = path.join(projectRoot, `CindyBuild-${crypto.randomUUID()}.xcresult`);
+ await mkdir(resultBundlePath, { recursive: true });
+ let finishBuild!: (
+ result: Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>,
+ ) => void;
+ const build = vi.fn(
+ () =>
+ new Promise<Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>>((resolve) => {
+ finishBuild = resolve;
+ }),
+ );
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ projectBuilder: { build },
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async () => localSession('dispose-build-session')),
+ });
+ await host.reconcileOwnership();
+ const current = actor.getOwned('dispose-build-session', instance.instanceId);
+ const callPromise = host.callTool(
+ 'build_app',
+ {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ },
+ { sessionId: 'dispose-build-session', origin: 'user' },
+ );
+ await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(1));
+
+ await host.dispose();
+ finishBuild({
+ kind: 'xcode-project',
+ worktreeRoot: instance.worktreeRoot,
+ projectRoot: path.join(instance.worktreeRoot, 'ios'),
+ containerPath: path.join(instance.worktreeRoot, 'ios', 'Demo.xcodeproj'),
+ scheme: 'Demo',
+ appPath: path.join(instance.worktreeRoot, 'build', 'Demo.app'),
+ resultBundlePath,
+ buildLogTail: 'BUILD SUCCEEDED',
+ });
+
+ try {
+ await expect(callPromise).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator host is shutting down.',
+ });
+ await expect(stat(resultBundlePath)).rejects.toMatchObject({ code: 'ENOENT' });
+ } finally {
+ await rm(projectRoot, { recursive: true, force: true });
+ }
+ });
+
it('rejects SSH sessions before touching local Apple tooling', async () => {
const inspect = vi.fn();
const host = createIOSSimulatorHost({
@@ -1369,9 +1518,10 @@ describe('iOS Simulator host', () => {
);
});
- it('reboots a shutdown simulator before rebuilding WDA for a visible pane', async () => {
+ it('stops the embedded viewer when the exact external simulator is shut down', async () => {
+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };
const lifecycle: IOSSimulatorSimctlLifecycle = {
- findExact: vi.fn(),
+ findExact: vi.fn(async () => shutdownDevice),
bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),
shutdownExact: vi.fn(async () => undefined),
createExact: vi.fn(),
@@ -1387,36 +1537,107 @@ describe('iOS Simulator host', () => {
sourceFingerprint: 'fingerprint-a',
device: { ...READY_REPORT.devices[0]!, state: 'Booted' },
});
- const driver = {
- getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),
- getOrientation: vi.fn(async () => 'PORTRAIT' as const),
- configureStream: vi.fn(
- async (sessionId: string, profile: IOSSimulatorStreamProfile) => profile,
- ),
+ const initialGeneration = attached.generation;
+ const driverManager = {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
};
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ driverManager,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ resourceScheduler: testResourceScheduler(),
+ deviceLivenessIntervalMs: 0,
+ });
+ const route = {
+ instanceId: attached.instanceId,
+ generation: attached.generation,
+ leaseId: attached.lease.id,
+ };
+
+ const result = await host.setViewerVisibility('session-a', route, true);
+
+ expect(result).toMatchObject({
+ ok: true,
+ data: {
+ instance: {
+ generation: initialGeneration + 1,
+ lifecycleState: 'stopped',
+ healthState: 'healthy',
+ errorCode: null,
+ },
+ stream: null,
+ viewport: null,
+ },
+ });
+ expect(lifecycle.bootExact).not.toHaveBeenCalled();
+ expect(driverManager.start).not.toHaveBeenCalled();
+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);
+ });
+
+ it('does not resurrect a viewer when driver startup finishes after an external shutdown', async () => {
+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi
+ .fn()
+ .mockResolvedValueOnce(READY_REPORT.devices[0]!)
+ .mockResolvedValue(shutdownDevice),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const attached = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ });
+ let resolveStart!: (running: WdaRunningInstance) => void;
+ let liveRunning: WdaRunningInstance | null = null;
const running = {
instanceId: attached.instanceId,
simulatorUdid: attached.simulatorUdid,
pid: 42,
- driver,
+ driver: {},
driverSessionId: 'wda-session',
} as unknown as WdaRunningInstance;
const driverManager = {
- get: vi.fn(() => null),
- start: vi.fn(async () => running),
- stop: vi.fn(async () => undefined),
+ get: vi.fn(() => liveRunning),
+ start: vi.fn(
+ () =>
+ new Promise<WdaRunningInstance>((resolve) => {
+ resolveStart = (value) => {
+ liveRunning = value;
+ resolve(value);
+ };
+ }),
+ ),
+ stop: vi.fn(async () => {
+ liveRunning = null;
+ }),
};
- const shutdownEnvironment = {
- ...READY_REPORT,
- devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],
+ const framePump = {
+ setVisible: vi.fn(),
+ snapshot: vi.fn(() => null),
+ clear: vi.fn(),
};
const host = createIOSSimulatorHost({
actor,
lifecycle,
driverManager,
- runtime: { inspect: vi.fn(async () => shutdownEnvironment) },
+ framePump: framePump as never,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
getSession: vi.fn(async (id) => localSession(id)),
resourceScheduler: testResourceScheduler(),
+ deviceLivenessIntervalMs: 0,
});
const route = {
instanceId: attached.instanceId,
@@ -1424,25 +1645,240 @@ describe('iOS Simulator host', () => {
leaseId: attached.lease.id,
};
- const result = await host.setViewerVisibility('session-a', route, true);
+ const viewer = host.setViewerVisibility('session-a', route, true);
+ await vi.waitFor(() => expect(driverManager.start).toHaveBeenCalledTimes(1));
+ await expect(host.getStatus('session-a')).resolves.toMatchObject({
+ ok: true,
+ instances: [
+ {
+ instanceId: attached.instanceId,
+ lifecycleState: 'stopped',
+ healthState: 'healthy',
+ errorCode: null,
+ },
+ ],
+ });
- expect(result).toMatchObject({
+ resolveStart(running);
+
+ await expect(viewer).resolves.toMatchObject({
ok: true,
data: {
- instance: { generation: attached.generation + 1, lifecycleState: 'ready' },
- viewport: { width: 393, height: 852 },
+ instance: {
+ instanceId: attached.instanceId,
+ lifecycleState: 'stopped',
+ healthState: 'healthy',
+ errorCode: null,
+ },
+ stream: null,
+ viewport: null,
},
});
- expect(lifecycle.bootExact).toHaveBeenCalledWith(attached.simulatorUdid);
- expect(driverManager.start).toHaveBeenCalledWith(
+ expect(framePump.setVisible).not.toHaveBeenCalled();
+ expect(driverManager.stop).toHaveBeenCalledTimes(2);
+ });
+
+ it('ignores an exact-device probe that finishes after the binding is detached', async () => {
+ let resolveProbe!: (device: (typeof READY_REPORT.devices)[number] | null) => void;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(
+ () =>
+ new Promise<(typeof READY_REPORT.devices)[number] | null>((resolve) => {
+ resolveProbe = resolve;
+ }),
+ ),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const attached = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ deviceLivenessIntervalMs: 0,
+ });
+
+ const status = host.getStatus('session-a');
+ await vi.waitFor(() => expect(lifecycle.findExact).toHaveBeenCalledTimes(1));
+ const current = actor.getOwned('session-a', attached.instanceId);
+ await actor.detach({
+ instanceId: current.instanceId,
+ sessionId: current.sessionId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ });
+ resolveProbe(READY_REPORT.devices[0]!);
+
+ await expect(status).resolves.toMatchObject({ ok: true, instances: [] });
+ });
+
+ it('marks an unavailable exact simulator as orphaned even when it reports Shutdown', async () => {
+ const unavailableDevice = {
+ ...READY_REPORT.devices[0]!,
+ state: 'Shutdown' as const,
+ isAvailable: false,
+ availabilityError: 'runtime unavailable',
+ };
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => unavailableDevice),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const attached = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ deviceLivenessIntervalMs: 0,
+ });
+
+ await expect(host.getStatus('session-a')).resolves.toMatchObject({
+ ok: true,
+ instances: [
+ {
+ instanceId: attached.instanceId,
+ lifecycleState: 'error',
+ healthState: 'degraded',
+ errorCode: 'ORPHANED_DEVICE',
+ },
+ ],
+ });
+ });
+
+ it('marks an externally deleted exact simulator as orphaned', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => null),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const attached = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },
+ });
+ const initialGeneration = attached.generation;
+ const driverManager = {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ };
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ driverManager,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ deviceLivenessIntervalMs: 0,
+ });
+
+ const status = await host.getStatus('session-a');
+
+ expect(status).toMatchObject({
+ ok: true,
+ instances: [
+ {
+ instanceId: attached.instanceId,
+ generation: initialGeneration + 2,
+ lifecycleState: 'error',
+ healthState: 'degraded',
+ errorCode: 'ORPHANED_DEVICE',
+ },
+ ],
+ });
+ expect(lifecycle.bootExact).not.toHaveBeenCalled();
+ expect(driverManager.start).not.toHaveBeenCalled();
+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);
+ });
+
+ it('deduplicates concurrent exact-device liveness probes for one generation', async () => {
+ let resolveProbe!: (device: (typeof READY_REPORT.devices)[number] | null) => void;
+ const probe = new Promise<(typeof READY_REPORT.devices)[number] | null>((resolve) => {
+ resolveProbe = resolve;
+ });
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(() => probe),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const attached = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },
+ });
+ const initialGeneration = attached.generation;
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ deviceLivenessIntervalMs: 1_000,
+ });
+
+ const statuses = Promise.all([host.getStatus('session-a'), host.getStatus('session-a')]);
+ await vi.waitFor(() => expect(lifecycle.findExact).toHaveBeenCalledTimes(1));
+ resolveProbe({ ...READY_REPORT.devices[0]!, state: 'Booted' });
+
+ await expect(statuses).resolves.toEqual([
expect.objectContaining({
- instanceId: attached.instanceId,
- runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',
- runtimeBuildVersion: '23E244',
- xcodeBuild: 'Xcode 26.4\nBuild version 17E192',
- architecture: process.arch === 'x64' ? 'x86_64' : 'arm64',
+ ok: true,
+ instances: [
+ expect.objectContaining({
+ instanceId: attached.instanceId,
+ generation: initialGeneration + 1,
+ lifecycleState: 'ready',
+ }),
+ ],
}),
- );
+ expect.objectContaining({
+ ok: true,
+ instances: [
+ expect.objectContaining({
+ instanceId: attached.instanceId,
+ generation: initialGeneration + 1,
+ lifecycleState: 'ready',
+ }),
+ ],
+ }),
+ ]);
+ expect(lifecycle.findExact).toHaveBeenCalledTimes(1);
});
it('creates and attaches a Cindy-owned simulator from an exact template device', async () => {
@@ -1913,11 +2349,7 @@ describe('iOS Simulator host', () => {
ok: true,
data: { screenMap: { generation: instance.generation, elements: [{ label: 'Continue' }] } },
});
- const doctor = await host.callTool(
- 'doctor',
- {},
- { sessionId: 'session-a', origin: 'agent' },
- );
+ const doctor = await host.callTool('doctor', {}, { sessionId: 'session-a', origin: 'agent' });
expect(doctor).toMatchObject({
ok: true,
data: {
@@ -2799,4 +3231,109 @@ describe('iOS Simulator host', () => {
);
expect(requestViewerFocus).toHaveBeenCalledWith('session-a', instance.instanceId);
});
+
+ it('returns readable diagnostics when build_app fails', async () => {
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle: {
+ findExact: vi.fn(),
+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ },
+ });
+ const driverManager = {
+ get: vi.fn(() => null),
+ start: vi.fn(
+ async (options) =>
+ ({
+ instanceId: options.instanceId,
+ simulatorUdid: options.simulatorUdid,
+ pid: 42,
+ driver: {},
+ driverSessionId: 'wda-session',
+ }) as unknown as Promise<WdaRunningInstance>,
+ ),
+ stop: vi.fn(async () => undefined),
+ };
+ const resultBundlePath =
+ '/tmp/cindy-user-data/ios-simulator/projects/build/CindyBuild-failed.xcresult';
+ const projectBuilder: IOSSimulatorProjectBuilderAdapter = {
+ build: vi.fn(async () => {
+ throw new IOSSimulatorProjectBuildError(
+ 'APP_BUILD_FAILED',
+ 'The Xcode project could not be built.',
+ 'compile /Users/secret/project.swift\nerror: BUILD_FAILURE_MARKER',
+ resultBundlePath,
+ true,
+ true,
+ );
+ }),
+ readXcresult: vi.fn(async () => 'xcresult BUILD_FAILURE_MARKER'),
+ };
+ const host = createIOSSimulatorHost({
+ actor,
+ driverManager,
+ projectBuilder,
+ resourceScheduler: testResourceScheduler(),
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),
+ });
+
+ await host.callTool(
+ 'attach_device',
+ { udid: READY_REPORT.devices[0]!.udid },
+ { sessionId: 'session-a', origin: 'user' },
+ );
+ const instance = actor.list('session-a')[0]!;
+ const route = {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ };
+ const failed = await host.callTool('build_app', route, {
+ sessionId: 'session-a',
+ origin: 'user',
+ });
+
+ expect(failed).toMatchObject({
+ ok: false,
+ errorCode: 'APP_BUILD_FAILED',
+ message: 'The Xcode project could not be built.',
+ data: {
+ diagnostics: {
+ diagnosticsId: expect.any(String),
+ buildLogTail: expect.stringMatching(/<redacted-path>.*BUILD_FAILURE_MARKER/s),
+ xcresultAvailable: true,
+ outputTruncated: true,
+ },
+ },
+ });
+ const diagnosticsId = (
+ failed as unknown as { ok: false; data: { diagnostics: { diagnosticsId: string } } }
+ ).data.diagnostics.diagnosticsId;
+ await expect(
+ host.callTool(
+ 'read_build_diagnostics',
+ { diagnosticsId, source: 'build-log' },
+ { sessionId: 'session-a', origin: 'agent' },
+ ),
+ ).resolves.toMatchObject({
+ ok: true,
+ data: {
+ diagnosticsId,
+ available: true,
+ text: expect.stringContaining('BUILD_FAILURE_MARKER'),
+ },
+ });
+ await expect(
+ host.callTool(
+ 'read_build_diagnostics',
+ { diagnosticsId, source: 'build-log' },
+ { sessionId: 'session-b', origin: 'agent' },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });
+ });
});
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index bac28b8f84..755fb90054 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -1,5 +1,6 @@
import { createHash, randomUUID } from 'node:crypto';
-import { realpath } from 'node:fs/promises';
+import type { Dirent } from 'node:fs';
+import { readdir, realpath, rm, stat } from 'node:fs/promises';
import { release as hostOsRelease } from 'node:os';
import path from 'node:path';
@@ -19,6 +20,7 @@ import {
IOSSimulatorInstanceError,
IOSSimulatorOwnershipStore,
IOSSimulatorOwnershipRegistryFile,
+ IOSSimulatorProjectBuildError,
IOSSimulatorProjectBuilder,
IOSSimulatorResourceScheduler,
IOSSimulatorScreenMapStore,
@@ -80,6 +82,10 @@ import { resolveIOSSimulatorDesktopAdmissionPolicy } from './ios-simulator-admis
import { compareIOSSimulatorPngBuffers, IOSSimulatorMediaCapture } from './ios-simulator-media.js';
const logger = createLogger('mcp/cindy_ios_simulator');
+const BUILD_DIAGNOSTICS_TTL_MS = 30 * 60_000;
+const MAX_BUILD_DIAGNOSTICS = 32;
+const MANAGED_BUILD_RESULT_BUNDLE_PATTERN = /^CindyBuild(?:-[0-9a-f-]+)?\.xcresult$/i;
+const DEFAULT_DEVICE_LIVENESS_INTERVAL_MS = 1_000;
interface IOSSimulatorSessionSnapshot {
id: string;
@@ -90,6 +96,7 @@ interface IOSSimulatorSessionSnapshot {
interface IOSSimulatorDriverManager {
get(instanceId: string): WdaRunningInstance | null;
+ probe?(instanceId: string): Promise<WdaRunningInstance | null>;
start(options: WdaStartOptions): Promise<WdaRunningInstance>;
stop(instanceId: string): Promise<void>;
recoverNativeSidecar?(
@@ -147,6 +154,8 @@ export interface IOSSimulatorHostOptions {
resourceScheduler?: IOSSimulatorResourceScheduler;
/** Recycle an idle WDA process while retaining the booted simulator binding. */
idleRecycleMs?: number;
+ /** Minimum interval between exact-UDID CoreSimulator liveness checks. */
+ deviceLivenessIntervalMs?: number;
getSession?: (sessionId: string) => Promise<IOSSimulatorSessionSnapshot | null>;
resolveWorktreeRoot?: (workDir: string) => Promise<string>;
requestViewerFocus?: (sessionId: string, instanceId: string) => void;
@@ -589,17 +598,21 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
artifact: IOSSimulatorAppArtifact;
}
>();
- const buildDiagnostics = new Map<
- string,
- {
- sessionId: string;
- instanceId: string;
- logTail: string;
- resultBundlePath: string | null;
- xcresultText: string | null;
- createdAt: number;
- }
- >();
+ type BuildDiagnosticRecord = {
+ sessionId: string;
+ instanceId: string;
+ logTail: string;
+ resultBundlePath: string | null;
+ xcresultText: string | null;
+ outputTruncated: boolean;
+ createdAt: number;
+ };
+ const buildDiagnostics = new Map<string, BuildDiagnosticRecord>();
+ const buildDiagnosticExpiryTimers = new Map<string, ReturnType<typeof setTimeout>>();
+ const buildDiagnosticReaders = new Map<string, number>();
+ const pendingBuildDiagnosticRemoval = new Map<string, BuildDiagnosticRecord>();
+ let buildResultBundlesReconciled = false;
+ let buildResultBundlesReconcilePromise: Promise<void> | null = null;
const mediaCapture = options.mediaCapture ?? new IOSSimulatorMediaCapture();
const visualBaselines = new Map<
string,
@@ -621,6 +634,21 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const viewerOrientationOverrides = new Map<string, 'PORTRAIT' | 'LANDSCAPE'>();
const streamProfiles = new Map<string, IOSSimulatorStreamProfile>();
const viewerEncodings = new Map<string, 'jpeg' | 'h264'>();
+ const configuredDeviceLivenessIntervalMs =
+ options.deviceLivenessIntervalMs ?? DEFAULT_DEVICE_LIVENESS_INTERVAL_MS;
+ const deviceLivenessIntervalMs =
+ Number.isFinite(configuredDeviceLivenessIntervalMs) && configuredDeviceLivenessIntervalMs >= 0
+ ? configuredDeviceLivenessIntervalMs
+ : DEFAULT_DEVICE_LIVENESS_INTERVAL_MS;
+ const exactDeviceProbeAvailable = options.actor === undefined || options.lifecycle !== undefined;
+ const deviceLivenessChecks = new Map<
+ string,
+ {
+ generation: number;
+ checkedAt: number;
+ promise: Promise<IOSSimulatorInstance> | null;
+ }
+ >();
let ownershipReconciled = false;
let ownershipReconcilePromise: Promise<void> | null = null;
let disposePromise: Promise<void> | null = null;
@@ -635,6 +663,215 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
errorCode: 'IOS_SIMULATOR_HOST_ERROR',
message: 'The iOS Simulator host is shutting down.',
});
+ function managedBuildResultsRoot(): string {
+ return path.join(app.getPath('userData'), 'ios-simulator', 'projects');
+ }
+ function isManagedBuildResultBundle(resultBundlePath: string): boolean {
+ const managedRoot = managedBuildResultsRoot();
+ const relative = path.relative(managedRoot, resultBundlePath);
+ return (
+ relative !== '' &&
+ relative !== '..' &&
+ !relative.startsWith(`..${path.sep}`) &&
+ !path.isAbsolute(relative) &&
+ MANAGED_BUILD_RESULT_BUNDLE_PATTERN.test(path.basename(resultBundlePath))
+ );
+ }
+ async function discardManagedBuildResultBundle(
+ resultBundlePath: string | null,
+ diagnosticsId?: string,
+ ): Promise<void> {
+ if (!resultBundlePath || !isManagedBuildResultBundle(resultBundlePath)) return;
+ await rm(resultBundlePath, { recursive: true, force: true }).catch((error) => {
+ logger.warn('iOS Simulator could not remove a managed build result bundle', {
+ ...(diagnosticsId ? { diagnosticsId } : {}),
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
+ async function removeBuildDiagnostic(
+ diagnosticsId: string,
+ diagnostic: BuildDiagnosticRecord,
+ ): Promise<void> {
+ if (buildDiagnostics.get(diagnosticsId) === diagnostic) {
+ buildDiagnostics.delete(diagnosticsId);
+ }
+ const expiryTimer = buildDiagnosticExpiryTimers.get(diagnosticsId);
+ if (expiryTimer) clearTimeout(expiryTimer);
+ buildDiagnosticExpiryTimers.delete(diagnosticsId);
+ if ((buildDiagnosticReaders.get(diagnosticsId) ?? 0) > 0) {
+ pendingBuildDiagnosticRemoval.set(diagnosticsId, diagnostic);
+ return;
+ }
+ pendingBuildDiagnosticRemoval.delete(diagnosticsId);
+ await discardManagedBuildResultBundle(diagnostic.resultBundlePath, diagnosticsId);
+ }
+ async function releaseBuildDiagnosticReader(diagnosticsId: string): Promise<void> {
+ const remaining = (buildDiagnosticReaders.get(diagnosticsId) ?? 1) - 1;
+ if (remaining > 0) {
+ buildDiagnosticReaders.set(diagnosticsId, remaining);
+ return;
+ }
+ buildDiagnosticReaders.delete(diagnosticsId);
+ const pending = pendingBuildDiagnosticRemoval.get(diagnosticsId);
+ if (!pending) return;
+ pendingBuildDiagnosticRemoval.delete(diagnosticsId);
+ await discardManagedBuildResultBundle(pending.resultBundlePath, diagnosticsId);
+ }
+ function scheduleBuildDiagnosticExpiry(
+ diagnosticsId: string,
+ diagnostic: BuildDiagnosticRecord,
+ ): void {
+ const timer = setTimeout(() => {
+ void removeBuildDiagnostic(diagnosticsId, diagnostic);
+ }, BUILD_DIAGNOSTICS_TTL_MS);
+ if (typeof timer === 'object' && 'unref' in timer) timer.unref();
+ buildDiagnosticExpiryTimers.set(diagnosticsId, timer);
+ }
+ async function reconcileOrphanedBuildResultBundles(): Promise<void> {
+ if (buildResultBundlesReconciled || disposePromise) return;
+ if (buildResultBundlesReconcilePromise) return buildResultBundlesReconcilePromise;
+ buildResultBundlesReconcilePromise = (async () => {
+ let complete = true;
+ const root = managedBuildResultsRoot();
+ const candidates: string[] = [];
+ let projectEntries: Dirent[];
+ try {
+ projectEntries = await readdir(root, { withFileTypes: true });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ buildResultBundlesReconciled = true;
+ return;
+ }
+ logger.warn('iOS Simulator could not inspect managed build result bundles', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return;
+ }
+ for (const projectEntry of projectEntries) {
+ if (!projectEntry.isDirectory()) continue;
+ const projectPath = path.join(root, projectEntry.name);
+ if (MANAGED_BUILD_RESULT_BUNDLE_PATTERN.test(projectEntry.name)) {
+ candidates.push(projectPath);
+ continue;
+ }
+ try {
+ const entries = await readdir(projectPath, { withFileTypes: true });
+ candidates.push(
+ ...entries
+ .filter(
+ (entry) =>
+ entry.isDirectory() && MANAGED_BUILD_RESULT_BUNDLE_PATTERN.test(entry.name),
+ )
+ .map((entry) => path.join(projectPath, entry.name)),
+ );
+ } catch (error) {
+ complete = false;
+ logger.warn('iOS Simulator could not inspect a project build result directory', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ const activePaths = new Set(
+ [...buildDiagnostics.values()].flatMap((diagnostic) =>
+ diagnostic.resultBundlePath ? [diagnostic.resultBundlePath] : [],
+ ),
+ );
+ const now = Date.now();
+ await Promise.all(
+ candidates.map(async (candidate) => {
+ if (activePaths.has(candidate)) return;
+ try {
+ const metadata = await stat(candidate);
+ if (now - metadata.mtimeMs <= BUILD_DIAGNOSTICS_TTL_MS) return;
+ await discardManagedBuildResultBundle(candidate);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ complete = false;
+ logger.warn('iOS Simulator could not reconcile a build result bundle', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }),
+ );
+ buildResultBundlesReconciled = complete;
+ })().finally(() => {
+ buildResultBundlesReconcilePromise = null;
+ });
+ return buildResultBundlesReconcilePromise;
+ }
+ async function storeBuildDiagnostics(input: {
+ sessionId: string;
+ instanceId: string;
+ logTail: string;
+ resultBundlePath: string | null;
+ outputTruncated?: boolean;
+ }): Promise<{
+ diagnosticsId: string;
+ buildLogTail: string;
+ xcresultAvailable: boolean;
+ outputTruncated: boolean;
+ }> {
+ if (disposePromise) {
+ await discardManagedBuildResultBundle(input.resultBundlePath);
+ throw new IOSSimulatorHostDisposedError();
+ }
+ const now = Date.now();
+ await Promise.all(
+ [...buildDiagnostics.entries()]
+ .filter(([, diagnostic]) => now - diagnostic.createdAt > BUILD_DIAGNOSTICS_TTL_MS)
+ .map(([diagnosticsId, diagnostic]) => removeBuildDiagnostic(diagnosticsId, diagnostic)),
+ );
+ if (disposePromise) {
+ await discardManagedBuildResultBundle(input.resultBundlePath);
+ throw new IOSSimulatorHostDisposedError();
+ }
+ const diagnosticsId = randomUUID();
+ const logTail = publicBuildText(input.logTail);
+ const diagnostic = {
+ sessionId: input.sessionId,
+ instanceId: input.instanceId,
+ logTail,
+ resultBundlePath: input.resultBundlePath,
+ xcresultText: null,
+ outputTruncated: Boolean(input.outputTruncated),
+ createdAt: now,
+ };
+ buildDiagnostics.set(diagnosticsId, diagnostic);
+ scheduleBuildDiagnosticExpiry(diagnosticsId, diagnostic);
+ if (buildDiagnostics.size > MAX_BUILD_DIAGNOSTICS) {
+ const oldest = [...buildDiagnostics.entries()].sort(
+ ([, left], [, right]) => left.createdAt - right.createdAt,
+ )[0];
+ if (oldest) await removeBuildDiagnostic(oldest[0], oldest[1]);
+ }
+ if (disposePromise) {
+ await removeBuildDiagnostic(diagnosticsId, diagnostic);
+ throw new IOSSimulatorHostDisposedError();
+ }
+ return {
+ diagnosticsId,
+ buildLogTail: logTail,
+ xcresultAvailable: Boolean(input.resultBundlePath),
+ outputTruncated: diagnostic.outputTruncated,
+ };
+ }
+ function buildFailureWithDiagnostics(
+ error: unknown,
+ sessionId: string,
+ diagnostics: Awaited<ReturnType<typeof storeBuildDiagnostics>>,
+ ): IOSSimulatorHostResult {
+ const failure = safeHostError(error, sessionId, 'build_app');
+ if (failure.ok) return failure;
+ return {
+ ...failure,
+ data: {
+ ...(failure.data ?? {}),
+ diagnostics,
+ },
+ };
+ }
function clearVisualBaselines(instanceId?: string): void {
for (const [baselineId, baseline] of visualBaselines) {
if (!instanceId || baseline.instanceId === instanceId) visualBaselines.delete(baselineId);
@@ -686,6 +923,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
driverManager ??= createDefaultDriverManager();
return driverManager;
};
+ const getHealthyDriver = async (instanceId: string): Promise<WdaRunningInstance | null> => {
+ const manager = getDriverManager();
+ return manager.probe ? manager.probe(instanceId) : manager.get(instanceId);
+ };
const getSession =
options.getSession ??
(async (sessionId: string) => {
@@ -740,6 +981,157 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return { ok: true, sessionId: normalizedSessionId, session };
}
+ function currentOwnedInstance(instance: IOSSimulatorInstance): IOSSimulatorInstance {
+ return actor.getOwned(instance.sessionId, instance.instanceId);
+ }
+
+ function currentReadyGeneration(instance: IOSSimulatorInstance): IOSSimulatorInstance | null {
+ let current: IOSSimulatorInstance;
+ try {
+ current = currentOwnedInstance(instance);
+ } catch {
+ return null;
+ }
+ return current.generation === instance.generation &&
+ current.simulatorUdid.toUpperCase() === instance.simulatorUdid.toUpperCase() &&
+ current.lifecycleState === 'ready'
+ ? current
+ : null;
+ }
+
+ function viewerRouteRefreshResult(instance: IOSSimulatorInstance): IOSSimulatorHostResult {
+ return {
+ ok: true,
+ data: {
+ instance: publicInstance(instance),
+ stream: null,
+ viewport: null,
+ mutation: actor.mutationState(instance.instanceId),
+ },
+ };
+ }
+
+ function isInstanceError(error: unknown, code: IOSSimulatorMcpErrorCode): boolean {
+ return error instanceof IOSSimulatorInstanceError && error.code === code;
+ }
+
+ async function releaseExternallyStoppedRuntime(instance: IOSSimulatorInstance): Promise<void> {
+ cancelIdleRecycle(instance.instanceId);
+ framePump.clear(instance.instanceId);
+ h264FramePump.clear(instance.instanceId);
+ viewerEncodings.delete(instance.instanceId);
+ streamProfiles.delete(instance.instanceId);
+ clearViewportState(instance.instanceId);
+ screenMaps.clear(instance.instanceId);
+ clearVisualBaselines(instance.instanceId);
+ await mediaCapture.discardInstance(instance.instanceId).catch((error) => {
+ logger.warn('iOS Simulator external stop could not discard recording', {
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ if (driverManager) {
+ await driverManager.stop(instance.instanceId).catch((error) => {
+ logger.warn('iOS Simulator external stop could not stop driver runtime', {
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
+ resourceScheduler.markStopped(instance.instanceId);
+ }
+
+ async function reconcileLiveDevice(
+ instance: IOSSimulatorInstance,
+ ): Promise<IOSSimulatorInstance> {
+ if (!exactDeviceProbeAvailable || disposePromise) return currentOwnedInstance(instance);
+ const existing = deviceLivenessChecks.get(instance.instanceId);
+ const now = Date.now();
+ if (existing?.generation === instance.generation) {
+ if (existing.promise) return existing.promise;
+ if (deviceLivenessIntervalMs > 0 && now - existing.checkedAt < deviceLivenessIntervalMs) {
+ return currentOwnedInstance(instance);
+ }
+ }
+
+ const record = {
+ generation: instance.generation,
+ checkedAt: now,
+ promise: null as Promise<IOSSimulatorInstance> | null,
+ };
+ const promise = (async () => {
+ let device: Awaited<ReturnType<IOSSimulatorSimctlLifecycle['findExact']>> | undefined;
+ try {
+ device = await lifecycle.findExact(instance.simulatorUdid);
+ } catch (error) {
+ logger.debug('iOS Simulator exact-device liveness probe failed', {
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return currentOwnedInstance(instance);
+ }
+ // Some injected test/extension lifecycles predate the exact probe seam.
+ // Treat an undefined result as indeterminate; the production lifecycle
+ // always returns either the exact device or null.
+ if (device === undefined) {
+ return currentOwnedInstance(instance);
+ }
+ const normalizedDeviceState = device?.state.trim().toLowerCase();
+ const observedState =
+ device === null || device.isAvailable === false
+ ? 'missing'
+ : normalizedDeviceState === 'shutdown'
+ ? 'shutdown'
+ : null;
+ if (!observedState) return currentOwnedInstance(instance);
+ const result = await actor.reconcileExternalDeviceState(
+ {
+ sessionId: instance.sessionId,
+ instanceId: instance.instanceId,
+ simulatorUdid: instance.simulatorUdid,
+ expectedGeneration: instance.generation,
+ state: observedState,
+ },
+ async (previous) => releaseExternallyStoppedRuntime(previous),
+ );
+ if (result.applied) {
+ logger.info('iOS Simulator external device state reconciled', {
+ instanceId: instance.instanceId,
+ simulatorUdid: instance.simulatorUdid,
+ state: observedState,
+ generation: result.instance.generation,
+ });
+ }
+ return result.instance;
+ })();
+ record.promise = promise;
+ deviceLivenessChecks.set(instance.instanceId, record);
+ try {
+ return await promise;
+ } finally {
+ if (deviceLivenessChecks.get(instance.instanceId) === record) {
+ record.promise = null;
+ record.checkedAt = Date.now();
+ }
+ }
+ }
+
+ async function reconcileLiveDevices(instances: IOSSimulatorInstance[]): Promise<void> {
+ await Promise.all(
+ instances.map(async (instance) => {
+ try {
+ await reconcileLiveDevice(instance);
+ } catch (error) {
+ // A concurrent detach/delete makes this probe obsolete. The caller
+ // reads the actor again after all probes settle, so the released
+ // binding should disappear rather than fail the whole status call.
+ if (isInstanceError(error, 'INSTANCE_NOT_FOUND')) return;
+ throw error;
+ }
+ }),
+ );
+ }
+
async function inspectForSession(sessionId: string): Promise<IOSSimulatorSessionStatus> {
if (disposePromise) return hostDisposedStatus(sessionId);
const resolved = await resolveSession(sessionId);
@@ -747,6 +1139,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (disposePromise) return hostDisposedStatus(resolved.sessionId);
await reconcilePersistedOwnership();
if (disposePromise) return hostDisposedStatus(resolved.sessionId);
+ await reconcileLiveDevices(actor.list(resolved.sessionId));
+ if (disposePromise) return hostDisposedStatus(resolved.sessionId);
const environment = await runtime.inspect();
if (disposePromise) return hostDisposedStatus(resolved.sessionId);
const instances = actor
@@ -767,6 +1161,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (ownershipReconciled) return;
if (ownershipReconcilePromise) return ownershipReconcilePromise;
ownershipReconcilePromise = (async () => {
+ await reconcileOrphanedBuildResultBundles();
+ if (disposePromise) return;
const environment = await runtime.inspect();
if (disposePromise) return;
if (!environment?.ready) return;
@@ -935,9 +1331,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
instance: IOSSimulatorInstance,
environment: IOSSimulatorEnvironmentReport,
): Promise<WdaRunningInstance> {
+ const manager = getDriverManager();
try {
assertHostActive();
- const running = await getDriverManager().start({
+ const running = await manager.start({
instanceId: instance.instanceId,
simulatorUdid: instance.simulatorUdid,
runtimeIdentifier: instance.runtimeIdentifier,
@@ -949,19 +1346,41 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
generation: instance.generation,
});
if (disposePromise) {
- await getDriverManager()
- .stop(instance.instanceId)
- .catch(() => undefined);
+ await manager.stop(instance.instanceId).catch(() => undefined);
throw new IOSSimulatorHostDisposedError();
}
+ if (!currentReadyGeneration(instance)) {
+ await manager.stop(instance.instanceId).catch(() => undefined);
+ throw new IOSSimulatorInstanceError(
+ 'STALE_GENERATION',
+ 'The simulator changed while its automation driver was starting.',
+ true,
+ );
+ }
const profile = streamProfiles.get(instance.instanceId);
if (profile && typeof running.driver.configureStream === 'function') {
await running.driver.configureStream(running.driverSessionId, profile);
}
- actor.markHealth(instance.sessionId, instance.instanceId, 'healthy', null);
+ const current = currentReadyGeneration(instance);
+ if (!current) {
+ await manager.stop(instance.instanceId).catch(() => undefined);
+ throw new IOSSimulatorInstanceError(
+ 'STALE_GENERATION',
+ 'The simulator changed while its automation driver was starting.',
+ true,
+ );
+ }
+ actor.markHealth(current.sessionId, current.instanceId, 'healthy', null);
return running;
} catch (error) {
- actor.markHealth(instance.sessionId, instance.instanceId, 'degraded', 'WDA_UNAVAILABLE');
+ const current = currentReadyGeneration(instance);
+ if (
+ current &&
+ !(error instanceof IOSSimulatorHostDisposedError) &&
+ !isInstanceError(error, 'STALE_GENERATION')
+ ) {
+ actor.markHealth(current.sessionId, current.instanceId, 'degraded', 'WDA_UNAVAILABLE');
+ }
throw error;
}
}
@@ -1075,10 +1494,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
.map((entry) => entry.driver?.driverRouter?.capabilityReport?.())
.filter((report): report is NonNullable<typeof report> => Boolean(report));
const hasNativeInput = capabilityReports.some(
- (report) => report.routes.continuousInput.selected === 'native-sidecar' && !report.routes.continuousInput.fallback,
+ (report) =>
+ report.routes.continuousInput.selected === 'native-sidecar' &&
+ !report.routes.continuousInput.fallback,
);
const hasMultiTouch = capabilityReports.some(
- (report) => report.nativeSidecar.capabilities?.multiTouch === true && report.nativeSidecar.available,
+ (report) =>
+ report.nativeSidecar.capabilities?.multiTouch === true && report.nativeSidecar.available,
);
const hasInstance = instances.length > 0;
const hasRunning = running.length > 0;
@@ -1099,6 +1521,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
attach_device: inspected.ready
? { state: 'available', backend: 'host' }
: { state: 'unavailable', reasonCode: inspected.issue ?? 'ENVIRONMENT_NOT_READY' },
+ read_build_diagnostics: { state: 'available', backend: 'host' },
start_instance: { ...requiresInstance, backend: 'simctl' },
stop_instance: { ...requiresInstance, backend: 'simctl' },
detach_device: { ...requiresInstance, backend: 'host' },
@@ -1142,7 +1565,6 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'lock_screen',
'unlock_screen',
'build_app',
- 'read_build_diagnostics',
'install_app',
'launch_app',
'terminate_app',
@@ -1172,7 +1594,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
function sleepWithAbort(delayMs: number, signal: AbortSignal): Promise<void> {
if (signal.aborted) {
return Promise.reject(
- new IOSSimulatorInstanceError('MUTATION_CANCELLED', 'The UI operation was cancelled.', true),
+ new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The UI operation was cancelled.',
+ true,
+ ),
);
}
return new Promise((resolve, reject) => {
@@ -1184,7 +1610,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
clearTimeout(timer);
signal.removeEventListener('abort', onAbort);
reject(
- new IOSSimulatorInstanceError('MUTATION_CANCELLED', 'The UI operation was cancelled.', true),
+ new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The UI operation was cancelled.',
+ true,
+ ),
);
};
signal.addEventListener('abort', onAbort, { once: true });
@@ -1728,13 +2158,24 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
},
};
}
+ instance = await reconcileLiveDevice(instance);
+ assertHostActive();
+ if (instance.lifecycleState !== 'ready') {
+ return viewerRouteRefreshResult(instance);
+ }
cancelIdleRecycle(instance.instanceId);
const driverManager = getDriverManager();
- let running = driverManager.get(instance.instanceId);
+ let running = await getHealthyDriver(instance.instanceId);
+ let current = currentReadyGeneration(instance);
+ if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));
+ instance = current;
if (!running) {
actor.markHealth(resolved.sessionId, instance.instanceId, 'recovering', null);
const environment = await runtime.inspect();
assertHostActive();
+ current = currentReadyGeneration(instance);
+ if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));
+ instance = current;
if (!environment.ready) {
throw new IOSSimulatorInstanceError(
'INVALID_INSTANCE_STATE',
@@ -1745,25 +2186,31 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const device = environment.devices.find(
(candidate) => candidate.udid.toUpperCase() === instance.simulatorUdid.toUpperCase(),
);
- if (!device) {
- throw new IOSSimulatorInstanceError(
- 'SIMULATOR_NOT_FOUND',
- 'The attached simulator is no longer installed.',
- true,
+ if (!device || !device.isAvailable || device.state.toLowerCase() !== 'booted') {
+ const reconciled = await actor.reconcileExternalDeviceState(
+ {
+ sessionId: instance.sessionId,
+ instanceId: instance.instanceId,
+ simulatorUdid: instance.simulatorUdid,
+ expectedGeneration: instance.generation,
+ state: !device || !device.isAvailable ? 'missing' : 'shutdown',
+ },
+ async (previous) => releaseExternallyStoppedRuntime(previous),
);
+ instance = reconciled.instance;
+ return viewerRouteRefreshResult(instance);
}
- let recoveredInstance = instance;
- if (device.state.toLowerCase() !== 'booted') {
- recoveredInstance = await resourceScheduler.runStart(
- instance.instanceId,
- () => (assertHostActive(), actor.recover(mutationRoute)),
+ try {
+ running = await resourceScheduler.runStart(instance.instanceId, () =>
+ ensureDriver(instance, environment),
);
+ } catch (error) {
+ if (isInstanceError(error, 'STALE_GENERATION')) {
+ return viewerRouteRefreshResult(currentOwnedInstance(instance));
+ }
+ throw error;
}
- running = await resourceScheduler.runStart(instance.instanceId, () =>
- ensureDriver(recoveredInstance, environment),
- );
assertHostActive();
- instance = recoveredInstance;
}
if (
preferredEncoding === 'h264' &&
@@ -1774,9 +2221,22 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
(await driverManager.recoverNativeSidecar(instance.instanceId, { rearm: true })) ??
running;
assertHostActive();
+ current = currentReadyGeneration(instance);
+ if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));
+ instance = current;
+ }
+ let viewport: IOSSimulatorPublicViewport;
+ try {
+ viewport = await readViewport(running);
+ } catch (error) {
+ current = currentReadyGeneration(instance);
+ if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));
+ throw error;
}
- const viewport = await readViewport(running);
assertHostActive();
+ current = currentReadyGeneration(instance);
+ if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));
+ instance = current;
// Driver recovery can outlive the lease that authorized it. Renew once
// more after all slow startup work so the successful response always
// carries a live viewer route.
@@ -1812,14 +2272,27 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const resolved = await resolveSession(sessionId);
if (!resolved.ok) return resolved;
assertHostActive();
- const instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });
+ let instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });
+ instance = await reconcileLiveDevice(instance);
+ assertHostActive();
+ if (instance.lifecycleState !== 'ready') {
+ return {
+ ok: true,
+ data: {
+ instance: publicInstance(instance),
+ stream: null,
+ viewport: null,
+ mutation: actor.mutationState(instance.instanceId),
+ },
+ };
+ }
let selectedEncoding = viewerEncodings.get(instance.instanceId) ?? 'jpeg';
let snapshot: IOSSimulatorFramePumpSnapshot | null =
selectedEncoding === 'h264'
? h264FramePump.snapshot(instance.instanceId)
: framePump.snapshot(instance.instanceId);
if (selectedEncoding === 'h264' && snapshot?.state === 'disconnected') {
- const running = getDriverManager().get(instance.instanceId);
+ const running = await getHealthyDriver(instance.instanceId);
h264FramePump.clear(instance.instanceId);
if (running) {
snapshot = startViewerStream(instance, running, 'jpeg');
@@ -1837,6 +2310,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return {
ok: true,
data: {
+ instance: publicInstance(instance),
stream: null,
viewport: null,
mutation: actor.mutationState(instance.instanceId),
@@ -2215,7 +2689,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
ok: true,
data: {
interaction: 'tap',
- screenMapInvalidated: !Boolean(captured.observation),
+ screenMapInvalidated: !captured.observation,
...captured,
},
};
@@ -2259,7 +2733,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
ok: true,
data: {
interaction: 'swipe',
- screenMapInvalidated: !Boolean(captured.observation),
+ screenMapInvalidated: !captured.observation,
...captured,
},
};
@@ -2293,7 +2767,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
ok: true,
data: {
interaction: 'drag',
- screenMapInvalidated: !Boolean(captured.observation),
+ screenMapInvalidated: !captured.observation,
...captured,
},
};
@@ -2325,7 +2799,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
ok: true,
data: {
interaction: 'long_press',
- screenMapInvalidated: !Boolean(captured.observation),
+ screenMapInvalidated: !captured.observation,
...captured,
},
};
@@ -2347,7 +2821,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
ok: true,
data: {
interaction: 'key_press',
- screenMapInvalidated: !Boolean(captured.observation),
+ screenMapInvalidated: !captured.observation,
...captured,
},
};
@@ -2485,7 +2959,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
ok: true,
data: {
interaction: 'touch_path',
- screenMapInvalidated: !Boolean(captured.observation),
+ screenMapInvalidated: !captured.observation,
...captured,
},
};
@@ -2523,7 +2997,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
ok: true,
data: {
interaction: 'touch2_path',
- screenMapInvalidated: !Boolean(captured.observation),
+ screenMapInvalidated: !captured.observation,
...captured,
},
};
@@ -2554,7 +3028,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
ok: true,
data: {
interaction: 'type_text',
- screenMapInvalidated: !Boolean(captured.observation),
+ screenMapInvalidated: !captured.observation,
...captured,
},
};
@@ -2578,7 +3052,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
ok: true,
data: {
interaction: 'press_home',
- screenMapInvalidated: !Boolean(captured.observation),
+ screenMapInvalidated: !captured.observation,
...captured,
},
};
@@ -2966,48 +3440,70 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'projects',
createHash('sha256').update(instance.instanceId).digest('hex').slice(0, 20),
);
- const built = await projectBuilder.build({
- worktreeRoot: instance.worktreeRoot,
- derivedDataPath,
- containerPath: readOptionalString(args, 'containerPath', 4_096),
- scheme: typeof args.scheme === 'string' ? args.scheme : undefined,
+ let built: IOSSimulatorProjectBuildResult;
+ try {
+ built = await projectBuilder.build({
+ worktreeRoot: instance.worktreeRoot,
+ derivedDataPath,
+ containerPath: readOptionalString(args, 'containerPath', 4_096),
+ scheme: typeof args.scheme === 'string' ? args.scheme : undefined,
+ });
+ } catch (error) {
+ if (!(error instanceof IOSSimulatorProjectBuildError)) throw error;
+ if (disposePromise) {
+ await discardManagedBuildResultBundle(error.resultBundlePath);
+ throw new IOSSimulatorHostDisposedError();
+ }
+ const diagnostics = await storeBuildDiagnostics({
+ sessionId: instance.sessionId,
+ instanceId: instance.instanceId,
+ logTail: error.buildLogTail,
+ resultBundlePath: error.resultBundlePath,
+ outputTruncated: error.outputTruncated,
+ });
+ return buildFailureWithDiagnostics(error, sessionId, diagnostics);
+ }
+ if (disposePromise) {
+ await discardManagedBuildResultBundle(built.resultBundlePath ?? null);
+ throw new IOSSimulatorHostDisposedError();
+ }
+ const diagnostics = await storeBuildDiagnostics({
+ sessionId: instance.sessionId,
+ instanceId: instance.instanceId,
+ logTail: built.buildLogTail ?? '',
+ resultBundlePath: built.resultBundlePath ?? null,
+ outputTruncated: built.outputTruncated,
});
+ assertHostActive();
let artifact: IOSSimulatorAppArtifact;
try {
- artifact = await appLifecycle.inspectArtifact(instance.worktreeRoot, built.appPath);
+ try {
+ artifact = await appLifecycle.inspectArtifact(instance.worktreeRoot, built.appPath);
+ } catch (error) {
+ if (
+ !(error instanceof IOSSimulatorInstanceError) ||
+ error.code !== 'APP_ARTIFACT_INVALID'
+ ) {
+ throw error;
+ }
+ artifact = await appLifecycle.inspectArtifact(
+ instance.worktreeRoot,
+ built.appPath,
+ derivedDataPath,
+ );
+ }
} catch (error) {
- if (
- !(error instanceof IOSSimulatorInstanceError) ||
- error.code !== 'APP_ARTIFACT_INVALID'
- ) {
- throw error;
+ if (disposePromise || error instanceof IOSSimulatorHostDisposedError) {
+ throw new IOSSimulatorHostDisposedError();
}
- artifact = await appLifecycle.inspectArtifact(
- instance.worktreeRoot,
- built.appPath,
- derivedDataPath,
- );
+ return buildFailureWithDiagnostics(error, sessionId, diagnostics);
}
+ assertHostActive();
appArtifacts.set(artifact.artifactId, {
instanceId: instance.instanceId,
projectKind: built.kind,
artifact,
});
- const diagnosticsId = randomUUID();
- buildDiagnostics.set(diagnosticsId, {
- sessionId: instance.sessionId,
- instanceId: instance.instanceId,
- logTail: publicBuildText(built.buildLogTail ?? ''),
- resultBundlePath: built.resultBundlePath ?? null,
- xcresultText: null,
- createdAt: Date.now(),
- });
- if (buildDiagnostics.size > 32) {
- const oldest = [...buildDiagnostics.entries()].sort(
- ([, left], [, right]) => left.createdAt - right.createdAt,
- )[0];
- if (oldest) buildDiagnostics.delete(oldest[0]);
- }
return {
ok: true,
data: {
@@ -3018,11 +3514,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
scheme: built.scheme,
createdAt: artifact.createdAt,
},
- diagnostics: {
- diagnosticsId,
- buildLogTail: publicBuildText(built.buildLogTail ?? ''),
- xcresultAvailable: Boolean(built.resultBundlePath),
- },
+ diagnostics,
},
};
}
@@ -3035,11 +3527,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'limit must be at most 65536');
}
const diagnostic = buildDiagnostics.get(diagnosticsId);
- if (
- !diagnostic ||
- diagnostic.sessionId !== sessionId ||
- Date.now() - diagnostic.createdAt > 30 * 60_000
- ) {
+ if (!diagnostic || diagnostic.sessionId !== sessionId) {
+ throw new IOSSimulatorInstanceError(
+ 'INVALID_ARGUMENT',
+ 'The build diagnostics entry does not exist or has expired.',
+ );
+ }
+ if (Date.now() - diagnostic.createdAt > BUILD_DIAGNOSTICS_TTL_MS) {
+ await removeBuildDiagnostic(diagnosticsId, diagnostic);
throw new IOSSimulatorInstanceError(
'INVALID_ARGUMENT',
'The build diagnostics entry does not exist or has expired.',
@@ -3062,9 +3557,17 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
};
}
if (diagnostic.xcresultText === null) {
- diagnostic.xcresultText = publicBuildText(
- await projectBuilder.readXcresult(diagnostic.resultBundlePath),
+ buildDiagnosticReaders.set(
+ diagnosticsId,
+ (buildDiagnosticReaders.get(diagnosticsId) ?? 0) + 1,
);
+ try {
+ diagnostic.xcresultText = publicBuildText(
+ await projectBuilder.readXcresult(diagnostic.resultBundlePath),
+ );
+ } finally {
+ await releaseBuildDiagnosticReader(diagnosticsId);
+ }
}
text = diagnostic.xcresultText;
} else if (source !== 'build-log') {
@@ -3372,8 +3875,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (
instances.some(
(entry) =>
- entry.running &&
- entry.capabilityReport?.routes.continuousInput.fallback === true,
+ entry.running && entry.capabilityReport?.routes.continuousInput.fallback === true,
)
) {
recommendedActions.push('continue_with_wda_mjpeg_fallback');
@@ -3483,6 +3985,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (disposePromise) return disposePromise;
disposePromise = (async () => {
clearVisualBaselines();
+ await Promise.all(
+ [...buildDiagnostics.entries()].map(([diagnosticsId, diagnostic]) =>
+ removeBuildDiagnostic(diagnosticsId, diagnostic),
+ ),
+ );
+ appArtifacts.clear();
for (const timer of idleRecycleTimers.values()) clearTimeout(timer);
idleRecycleTimers.clear();
const instances = actor.listAll();
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
index 8561638088..fd6efd69cc 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
@@ -65,6 +65,8 @@ const STREAM_PROFILES: Record<
high: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
};
+const FRAME_FRESHNESS_TIMEOUT_MS = 3_000;
+
/** Translate stable discovery codes instead of leaking host-side English guidance into the UI. */
export function setupStepKeys(issue: IOSSimulatorRuntimeErrorCode | null): string[] {
switch (issue) {
@@ -134,6 +136,7 @@ function resultMutation(result: IOSSimulatorToolResponse): IOSSimulatorMutationS
interface PointerGesture {
pointerId: number;
gestureId: string;
+ route: ReturnType<typeof routeFor>;
startedAt: number;
startClientX: number;
startClientY: number;
@@ -160,6 +163,8 @@ export function IOSSimulatorTabBody({
const [operation, setOperation] = useState<Operation>(null);
const [frameUrl, setFrameUrl] = useState<string | null>(null);
const [framePresentation, setFramePresentation] = useState<'jpeg' | 'h264' | null>(null);
+ const [presentationRouteKey, setPresentationRouteKey] = useState<string | null>(null);
+ const [frameFresh, setFrameFresh] = useState(false);
const [streamState, setStreamState] = useState<IOSSimulatorFramePumpSnapshot['state']>('idle');
const [streamFps, setStreamFps] = useState(0);
const [viewport, setViewport] = useState<IOSSimulatorPublicViewport | null>(null);
@@ -177,6 +182,56 @@ export function IOSSimulatorTabBody({
const interactiveProfileActiveRef = useRef(false);
const profileRestoreTimerRef = useRef<number | null>(null);
const h264CanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const frameUrlRef = useRef<string | null>(null);
+ const presentationEpochRef = useRef(0);
+ const frameFreshnessTimerRef = useRef<number | null>(null);
+
+ const replaceFrameUrl = useCallback((next: string | null) => {
+ const previous = frameUrlRef.current;
+ if (previous && previous !== next) URL.revokeObjectURL(previous);
+ frameUrlRef.current = next;
+ setFrameUrl(next);
+ }, []);
+
+ const clearViewerPresentation = useCallback(
+ (nextState: IOSSimulatorFramePumpSnapshot['state'] = 'idle') => {
+ presentationEpochRef.current += 1;
+ if (frameFreshnessTimerRef.current !== null) {
+ window.clearTimeout(frameFreshnessTimerRef.current);
+ frameFreshnessTimerRef.current = null;
+ }
+ replaceFrameUrl(null);
+ setFramePresentation(null);
+ setPresentationRouteKey(null);
+ setFrameFresh(false);
+ setStreamState(nextState);
+ setStreamFps(0);
+ setViewport(null);
+ frameSequenceRef.current = 0;
+ frameEncodingRef.current = null;
+ fpsWindowRef.current = { startedAt: 0, frames: 0 };
+ const canvas = h264CanvasRef.current;
+ const context = canvas?.getContext('2d', { alpha: false });
+ if (canvas && context) context.clearRect(0, 0, canvas.width, canvas.height);
+ },
+ [replaceFrameUrl],
+ );
+
+ const markFramePresented = useCallback(
+ (routeKey: string, presentation: 'jpeg' | 'h264') => {
+ if (frameFreshnessTimerRef.current !== null) {
+ window.clearTimeout(frameFreshnessTimerRef.current);
+ }
+ setPresentationRouteKey(routeKey);
+ setFramePresentation(presentation);
+ setFrameFresh(true);
+ frameFreshnessTimerRef.current = window.setTimeout(() => {
+ frameFreshnessTimerRef.current = null;
+ setFrameFresh(false);
+ }, FRAME_FRESHNESS_TIMEOUT_MS);
+ },
+ [],
+ );
const refresh = useCallback(async () => {
const requestVersion = ++requestVersionRef.current;
@@ -207,6 +262,9 @@ export function IOSSimulatorTabBody({
const instances = status?.ok ? status.instances : [];
const attachedInstance =
instances.find((instance) => instance.instanceId === state.instanceId) ?? instances[0] ?? null;
+ const viewerRouteKey = attachedInstance
+ ? `${attachedInstance.instanceId}:${attachedInstance.generation}`
+ : null;
const grant =
status?.ok && attachedInstance
? status.deviceGrants.find(
@@ -231,12 +289,31 @@ export function IOSSimulatorTabBody({
const viewerVisible = Boolean(
active && shellVisible && attachedInstance?.lifecycleState === 'ready',
);
+ const presentationMatchesRoute = Boolean(
+ viewerRouteKey && presentationRouteKey === viewerRouteKey && framePresentation !== null,
+ );
+ const viewerInteractive = Boolean(
+ viewerVisible &&
+ streamState === 'streaming' &&
+ presentationMatchesRoute &&
+ frameFresh &&
+ !busy,
+ );
useEffect(() => {
const nextId = attachedInstance?.instanceId ?? null;
if ((state.instanceId ?? null) !== nextId) ctx.patchState({ instanceId: nextId });
}, [attachedInstance?.instanceId, ctx, state.instanceId]);
+ useEffect(() => {
+ clearViewerPresentation('idle');
+ }, [
+ attachedInstance?.generation,
+ attachedInstance?.instanceId,
+ attachedInstance?.lifecycleState,
+ clearViewerPresentation,
+ ]);
+
useEffect(() => {
if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;
const route = { sessionId: ctx.sessionId, ...routeFor(attachedInstance) };
@@ -246,14 +323,34 @@ export function IOSSimulatorTabBody({
let routeRecoveryPending = false;
let pollTimer: number | null = null;
let preferredEncoding: 'jpeg' | 'h264' = 'jpeg';
+ let mediaDisconnected = false;
+ let routeInactive = false;
+ const routeKey = `${route.instanceId}:${route.generation}`;
const decoderRuntime = createBrowserIOSSimulatorH264DecoderRuntime();
let decoder: IOSSimulatorH264Decoder | null = null;
frameSequenceRef.current = 0;
frameEncodingRef.current = null;
fpsWindowRef.current = { startedAt: 0, frames: 0 };
setViewport(null);
+ const disconnectViewer = () => {
+ if (cancelled) return;
+ mediaDisconnected = true;
+ preferredEncoding = 'jpeg';
+ decoder?.close();
+ decoder = null;
+ clearViewerPresentation('disconnected');
+ };
const acceptStream = (stream: IOSSimulatorFramePumpSnapshot | null) => {
- if (cancelled || !stream) return;
+ if (cancelled) return;
+ if (!stream || stream.state === 'disconnected') {
+ disconnectViewer();
+ return;
+ }
+ if (stream.instanceId !== route.instanceId || stream.generation !== route.generation) {
+ disconnectViewer();
+ return;
+ }
+ mediaDisconnected = false;
setStreamState(stream.state);
const frame = stream.latestFrame;
if (frame && frame.encoding !== frameEncodingRef.current) {
@@ -280,38 +377,50 @@ export function IOSSimulatorTabBody({
const candidateUrl = URL.createObjectURL(
new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'image/jpeg' }),
);
+ const candidateEpoch = presentationEpochRef.current;
+ const candidateSequence = frame.sequence;
const image = new Image();
image.onload = () => {
- if (cancelled) {
+ if (
+ cancelled ||
+ mediaDisconnected ||
+ presentationEpochRef.current !== candidateEpoch ||
+ frameEncodingRef.current !== 'jpeg' ||
+ frameSequenceRef.current !== candidateSequence
+ ) {
URL.revokeObjectURL(candidateUrl);
return;
}
- setFrameUrl((previous) => {
- if (previous) URL.revokeObjectURL(previous);
- return candidateUrl;
- });
- setFramePresentation('jpeg');
+ replaceFrameUrl(candidateUrl);
+ markFramePresented(routeKey, 'jpeg');
};
image.onerror = () => URL.revokeObjectURL(candidateUrl);
image.src = candidateUrl;
};
const acceptViewerResult = (result: IOSSimulatorToolResponse) => {
if (!result.ok) {
+ disconnectViewer();
if (
viewerVisible &&
!routeRecoveryPending &&
(result.errorCode === 'LEASE_EXPIRED' || result.errorCode === 'STALE_GENERATION')
) {
routeRecoveryPending = true;
- setStreamState('disconnected');
void refresh().finally(() => {
routeRecoveryPending = false;
});
}
return;
}
+ const nextInstance = resultInstance(result);
+ if (nextInstance && nextInstance.lifecycleState !== 'ready') {
+ routeInactive = true;
+ disconnectViewer();
+ void refresh();
+ return;
+ }
acceptStream(resultStream(result));
- if (resultInstance(result)) void refresh();
+ if (nextInstance) void refresh();
const nextViewport = resultViewport(result);
if (!cancelled && nextViewport) setViewport(nextViewport);
const nextMutation = resultMutation(result);
@@ -353,11 +462,13 @@ export function IOSSimulatorTabBody({
context.drawImage(frame as unknown as CanvasImageSource, 0, 0, width, height);
},
onFrameRendered() {
- if (!cancelled) setFramePresentation('h264');
+ if (!cancelled && !mediaDisconnected) markFramePresented(routeKey, 'h264');
},
onFallback() {
if (cancelled) return;
preferredEncoding = 'jpeg';
+ decoder?.close();
+ decoder = null;
if (pollTimer !== null) window.clearTimeout(pollTimer);
pollTimer = null;
void window.electronAPI.maker.iosSimulator
@@ -368,7 +479,7 @@ export function IOSSimulatorTabBody({
})
.then(acceptViewerResult)
.catch(() => {
- if (!cancelled) setStreamState('disconnected');
+ disconnectViewer();
});
},
});
@@ -377,6 +488,21 @@ export function IOSSimulatorTabBody({
if (polling || cancelled) return;
polling = true;
try {
+ if (
+ mediaDisconnected &&
+ viewerVisible &&
+ !routeInactive &&
+ performance.now() >= nextRecoveryAt
+ ) {
+ nextRecoveryAt = performance.now() + 3_000;
+ const recovered = await window.electronAPI.maker.iosSimulator.setViewerVisibility({
+ ...route,
+ visible: true,
+ preferredEncoding: 'jpeg',
+ });
+ acceptViewerResult(recovered);
+ return;
+ }
const result = await window.electronAPI.maker.iosSimulator.latestFrame(route);
acceptViewerResult(result);
const stream = resultStream(result);
@@ -394,7 +520,7 @@ export function IOSSimulatorTabBody({
acceptViewerResult(recovered);
}
} catch {
- if (!cancelled) setStreamState('disconnected');
+ disconnectViewer();
} finally {
polling = false;
}
@@ -406,20 +532,25 @@ export function IOSSimulatorTabBody({
pollTimer = null;
void poll().finally(schedulePoll);
},
- preferredEncoding === 'h264' ? 1_000 : 50,
+ mediaDisconnected ? 250 : preferredEncoding === 'h264' ? 1_000 : 50,
);
};
- void window.electronAPI.maker.iosSimulator
- .setViewerVisibility({ ...route, visible: viewerVisible, preferredEncoding })
- .then(acceptViewerResult)
- .catch(() => {
- if (!cancelled) setStreamState('disconnected');
- });
- // H.264 frames arrive through the Main push channel. Poll slowly as a
- // recovery watchdog; JPEG keeps the compatibility polling cadence.
- if (viewerVisible) {
- void poll().finally(schedulePoll);
- }
+ const startViewer = async () => {
+ try {
+ const result = await window.electronAPI.maker.iosSimulator.setViewerVisibility({
+ ...route,
+ visible: viewerVisible,
+ preferredEncoding,
+ });
+ acceptViewerResult(result);
+ } catch {
+ disconnectViewer();
+ }
+ // H.264 frames arrive through the Main push channel. Poll slowly as a
+ // recovery watchdog; JPEG keeps the compatibility polling cadence.
+ if (viewerVisible && !cancelled) void poll().finally(schedulePoll);
+ };
+ void startViewer();
return () => {
cancelled = true;
decoder?.close();
@@ -429,13 +560,27 @@ export function IOSSimulatorTabBody({
.setViewerVisibility({ ...route, visible: false })
.catch(() => undefined);
};
- }, [attachedInstance, ctx.sessionId, refresh, viewerVisible]);
+ }, [
+ attachedInstance,
+ clearViewerPresentation,
+ ctx.sessionId,
+ markFramePresented,
+ refresh,
+ replaceFrameUrl,
+ viewerVisible,
+ ]);
useEffect(
() => () => {
- if (frameUrl) URL.revokeObjectURL(frameUrl);
+ const current = frameUrlRef.current;
+ frameUrlRef.current = null;
+ if (current) URL.revokeObjectURL(current);
+ if (frameFreshnessTimerRef.current !== null) {
+ window.clearTimeout(frameFreshnessTimerRef.current);
+ frameFreshnessTimerRef.current = null;
+ }
},
- [frameUrl],
+ [],
);
const call = useCallback(
@@ -600,12 +745,7 @@ export function IOSSimulatorTabBody({
| 'unlock_screen',
args: Record<string, unknown>,
) => {
- if (
- !attachedInstance ||
- attachedInstance.lifecycleState !== 'ready' ||
- interactionBusy ||
- agentBusy
- ) {
+ if (!attachedInstance || !viewerInteractive) {
return false;
}
setInteractionBusy(true);
@@ -644,7 +784,7 @@ export function IOSSimulatorTabBody({
setInteractionBusy(false);
}
},
- [agentBusy, attachedInstance, ctx.sessionId, interactionBusy, t],
+ [attachedInstance, ctx.sessionId, refresh, t, viewerInteractive],
);
const pointerRatio = useCallback(
@@ -660,23 +800,23 @@ export function IOSSimulatorTabBody({
const invokeLiveTouch = useCallback(
async (
- gesture: Pick<PointerGesture, 'gestureId'>,
+ gesture: Pick<PointerGesture, 'gestureId' | 'route'>,
phase: 'begin' | 'move' | 'end' | 'cancel',
point: { xRatio: number; yRatio: number },
) => {
- if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') {
+ if (phase !== 'cancel' && !viewerInteractive) {
throw new Error('Simulator instance is unavailable');
}
const result = await window.electronAPI.maker.iosSimulator.liveTouch({
sessionId: ctx.sessionId,
- ...routeFor(attachedInstance),
+ ...gesture.route,
gestureId: gesture.gestureId,
phase,
...point,
});
if (!result.ok) throw new Error(result.message);
},
- [attachedInstance, ctx.sessionId],
+ [ctx.sessionId, viewerInteractive],
);
const queueLiveMove = useCallback(
@@ -698,11 +838,19 @@ export function IOSSimulatorTabBody({
const onViewerPointerDown = useCallback(
(event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {
- if (pointerGestureRef.current || interactionBusy || agentBusy || event.button !== 0) return;
+ if (
+ !attachedInstance ||
+ !viewerInteractive ||
+ pointerGestureRef.current ||
+ event.button !== 0
+ ) {
+ return;
+ }
const point = pointerRatio(event);
const gesture: PointerGesture = {
pointerId: event.pointerId,
gestureId: `viewer-${Date.now()}-${++gestureSequenceRef.current}`,
+ route: routeFor(attachedInstance),
startedAt: performance.now(),
startClientX: event.clientX,
startClientY: event.clientY,
@@ -720,13 +868,13 @@ export function IOSSimulatorTabBody({
event.currentTarget.setPointerCapture(event.pointerId);
event.preventDefault();
},
- [agentBusy, beginInteractiveFrameRate, interactionBusy, invokeLiveTouch, pointerRatio],
+ [attachedInstance, beginInteractiveFrameRate, invokeLiveTouch, pointerRatio, viewerInteractive],
);
const onViewerPointerMove = useCallback(
(event: ReactPointerEvent<HTMLImageElement | HTMLCanvasElement>) => {
const gesture = pointerGestureRef.current;
- if (!gesture || gesture.pointerId !== event.pointerId) return;
+ if (!viewerInteractive || !gesture || gesture.pointerId !== event.pointerId) return;
const coalesced = event.nativeEvent.getCoalescedEvents?.() ?? [event.nativeEvent];
const latest = coalesced.at(-1) ?? event.nativeEvent;
const bounds = event.currentTarget.getBoundingClientRect();
@@ -739,7 +887,7 @@ export function IOSSimulatorTabBody({
queueLiveMove(gesture, point);
event.preventDefault();
},
- [queueLiveMove],
+ [queueLiveMove, viewerInteractive],
);
const onViewerPointerUp = useCallback(
@@ -797,9 +945,10 @@ export function IOSSimulatorTabBody({
[endInteractiveFrameRate, invokeLiveTouch],
);
- useEffect(
- () => () => {
+ const cancelActivePointerGesture = useCallback(
+ (restoreProfile: boolean) => {
const gesture = pointerGestureRef.current;
+ const hadInteractiveProfile = interactiveProfileActiveRef.current;
pointerGestureRef.current = null;
if (gesture) {
gesture.pendingMove = null;
@@ -811,15 +960,33 @@ export function IOSSimulatorTabBody({
yRatio: gesture.lastYRatio,
}),
)
- .catch(() => undefined);
+ .catch(() => undefined)
+ .finally(() => {
+ if (restoreProfile) endInteractiveFrameRate();
+ });
+ } else if (restoreProfile && hadInteractiveProfile) {
+ endInteractiveFrameRate();
}
- if (profileRestoreTimerRef.current !== null) {
- window.clearTimeout(profileRestoreTimerRef.current);
- profileRestoreTimerRef.current = null;
+ if (!restoreProfile) {
+ if (profileRestoreTimerRef.current !== null) {
+ window.clearTimeout(profileRestoreTimerRef.current);
+ profileRestoreTimerRef.current = null;
+ }
+ interactiveProfileActiveRef.current = false;
}
- interactiveProfileActiveRef.current = false;
},
- [invokeLiveTouch],
+ [endInteractiveFrameRate, invokeLiveTouch],
+ );
+
+ useEffect(() => {
+ if (!viewerInteractive) cancelActivePointerGesture(true);
+ }, [cancelActivePointerGesture, viewerInteractive]);
+
+ useEffect(
+ () => () => {
+ cancelActivePointerGesture(false);
+ },
+ [cancelActivePointerGesture],
);
const sendTextInput = useCallback(async () => {
@@ -992,38 +1159,39 @@ export function IOSSimulatorTabBody({
</span>
</div>
- {(agentBusy || mutation?.agentPaused) && (
- <div className="mt-3 flex items-center justify-between gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface)] p-3">
- <div className="min-w-0">
- <div className="text-[11px] font-medium text-[var(--warning-accent)]">
- {t(
- agentBusy
- ? 'rightSidebar.iosSimulator.agentBusyTitle'
- : 'rightSidebar.iosSimulator.manualControlTitle',
- )}
+ {attachedInstance.lifecycleState === 'ready' &&
+ (agentBusy || mutation?.agentPaused) && (
+ <div className="mt-3 flex items-center justify-between gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface)] p-3">
+ <div className="min-w-0">
+ <div className="text-[11px] font-medium text-[var(--warning-accent)]">
+ {t(
+ agentBusy
+ ? 'rightSidebar.iosSimulator.agentBusyTitle'
+ : 'rightSidebar.iosSimulator.manualControlTitle',
+ )}
+ </div>
+ <div className="mt-0.5 text-pretty text-[10px] leading-relaxed text-[var(--text-secondary)]">
+ {t(
+ mutation?.takeoverPending
+ ? 'rightSidebar.iosSimulator.takeoverPendingDescription'
+ : agentBusy
+ ? 'rightSidebar.iosSimulator.agentBusyDescription'
+ : 'rightSidebar.iosSimulator.manualControlDescription',
+ )}
+ </div>
</div>
- <div className="mt-0.5 text-pretty text-[10px] leading-relaxed text-[var(--text-secondary)]">
- {t(
- mutation?.takeoverPending
- ? 'rightSidebar.iosSimulator.takeoverPendingDescription'
- : agentBusy
- ? 'rightSidebar.iosSimulator.agentBusyDescription'
- : 'rightSidebar.iosSimulator.manualControlDescription',
+ <ActionButton
+ label={t(
+ mutation?.agentPaused
+ ? 'rightSidebar.iosSimulator.resumeAgentInput'
+ : 'rightSidebar.iosSimulator.takeControl',
)}
- </div>
+ icon={mutation?.agentPaused ? Play : ShieldCheck}
+ disabled={operation !== null || mutation?.takeoverPending}
+ onClick={() => void setMutationControl()}
+ />
</div>
- <ActionButton
- label={t(
- mutation?.agentPaused
- ? 'rightSidebar.iosSimulator.resumeAgentInput'
- : 'rightSidebar.iosSimulator.takeControl',
- )}
- icon={mutation?.agentPaused ? Play : ShieldCheck}
- disabled={operation !== null || mutation?.takeoverPending}
- onClick={() => void setMutationControl()}
- />
- </div>
- )}
+ )}
{attachedInstance.lifecycleState === 'ready' && (
<>
@@ -1053,7 +1221,7 @@ export function IOSSimulatorTabBody({
</div>
<div className="mt-3 overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface)]">
<div className="relative flex min-h-48 items-center justify-center p-2">
- {frameUrl && (
+ {frameUrl && presentationMatchesRoute && (
<img
src={frameUrl}
alt={t('rightSidebar.iosSimulator.streamAlt', {
@@ -1063,9 +1231,11 @@ export function IOSSimulatorTabBody({
className={cn(
'max-h-[520px] max-w-full touch-none select-none object-contain',
framePresentation === 'jpeg' ? null : 'hidden',
- interactionBusy || agentBusy
+ busy
? 'cursor-wait opacity-80'
- : 'cursor-crosshair',
+ : !viewerInteractive
+ ? 'pointer-events-none cursor-default opacity-80'
+ : 'cursor-crosshair',
)}
draggable={false}
onPointerDown={onViewerPointerDown}
@@ -1080,21 +1250,25 @@ export function IOSSimulatorTabBody({
aria-label={t('rightSidebar.iosSimulator.streamAlt', {
device: attachedInstance.simulatorName,
})}
- aria-hidden={framePresentation !== 'h264'}
+ aria-hidden={!(presentationMatchesRoute && framePresentation === 'h264')}
title={t('rightSidebar.iosSimulator.gestureHint')}
className={cn(
'max-h-[520px] max-w-full touch-none select-none object-contain',
- framePresentation === 'h264' ? null : 'hidden',
- interactionBusy || agentBusy
+ presentationMatchesRoute && framePresentation === 'h264'
+ ? null
+ : 'hidden',
+ busy
? 'cursor-wait opacity-80'
- : 'cursor-crosshair',
+ : !viewerInteractive
+ ? 'pointer-events-none cursor-default opacity-80'
+ : 'cursor-crosshair',
)}
onPointerDown={onViewerPointerDown}
onPointerMove={onViewerPointerMove}
onPointerUp={onViewerPointerUp}
onPointerCancel={onViewerPointerCancel}
/>
- {!framePresentation && (
+ {!presentationMatchesRoute && (
<div className="flex flex-col items-center gap-2 p-8 text-center text-[11px] text-[var(--text-secondary)]">
<Smartphone size={22} aria-hidden="true" />
<span className="text-pretty">
@@ -1130,7 +1304,7 @@ export function IOSSimulatorTabBody({
void sendTextInput();
}
}}
- disabled={interactionBusy || agentBusy}
+ disabled={!viewerInteractive}
aria-label={t('rightSidebar.iosSimulator.textInputLabel')}
placeholder={t('rightSidebar.iosSimulator.textInputPlaceholder')}
className="h-8 w-full rounded-full border border-[var(--border-default)] bg-[var(--surface)] pl-8 pr-3 text-[11px] text-[var(--text-primary)] placeholder:text-[var(--text-placeholder)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50"
@@ -1139,19 +1313,19 @@ export function IOSSimulatorTabBody({
<ActionButton
label={t('rightSidebar.iosSimulator.sendText')}
icon={Send}
- disabled={interactionBusy || agentBusy || !textInput}
+ disabled={!viewerInteractive || !textInput}
onClick={() => void sendTextInput()}
/>
<ActionButton
label={t('rightSidebar.iosSimulator.pressHome')}
icon={House}
- disabled={interactionBusy || agentBusy}
+ disabled={!viewerInteractive}
onClick={() => void runInteraction('press_home', {})}
/>
<ActionButton
label={t('rightSidebar.iosSimulator.rotateDevice')}
icon={RotateCw}
- disabled={interactionBusy || agentBusy || !viewport}
+ disabled={!viewerInteractive || !viewport}
onClick={() =>
void runInteraction('set_orientation', {
orientation:
@@ -1162,13 +1336,13 @@ export function IOSSimulatorTabBody({
<ActionButton
label={t('rightSidebar.iosSimulator.lockScreen')}
icon={LockKeyhole}
- disabled={interactionBusy || agentBusy}
+ disabled={!viewerInteractive}
onClick={() => void runInteraction('lock_screen', {})}
/>
<ActionButton
label={t('rightSidebar.iosSimulator.unlockScreen')}
icon={UnlockKeyhole}
- disabled={interactionBusy || agentBusy}
+ disabled={!viewerInteractive}
onClick={() => void runInteraction('unlock_screen', {})}
/>
</div>
@@ -1178,6 +1352,28 @@ export function IOSSimulatorTabBody({
</>
)}
+ {attachedInstance.lifecycleState === 'stopped' && (
+ <div
+ role="status"
+ aria-live="polite"
+ className="mt-3 flex gap-2.5 rounded-xl border border-[var(--border-default)] bg-[var(--surface)] p-3"
+ >
+ <Square
+ size={15}
+ className="mt-0.5 shrink-0 text-[var(--text-secondary)]"
+ aria-hidden="true"
+ />
+ <div className="min-w-0">
+ <div className="text-[12px] font-medium">
+ {t('rightSidebar.iosSimulator.viewerStoppedTitle')}
+ </div>
+ <div className="mt-1 text-pretty text-[11px] leading-relaxed text-[var(--text-secondary)]">
+ {t('rightSidebar.iosSimulator.viewerStoppedDescription')}
+ </div>
+ </div>
+ </div>
+ )}
+
<div className="mt-3 flex flex-wrap gap-2">
{attachedInstance.lifecycleState === 'ready' ? (
<ActionButton
@@ -1204,26 +1400,28 @@ export function IOSSimulatorTabBody({
/>
</div>
- <div className="mt-3 flex items-center justify-between gap-3 border-t border-[var(--border-default)] pt-3">
- <div className="min-w-0">
- <div className="text-[11px] font-medium">
- {t('rightSidebar.iosSimulator.agentControlTitle')}
- </div>
- <div className="mt-0.5 text-[10px] leading-relaxed text-[var(--text-secondary)]">
- {t('rightSidebar.iosSimulator.agentControlDescription')}
+ {attachedInstance.lifecycleState === 'ready' && (
+ <div className="mt-3 flex items-center justify-between gap-3 border-t border-[var(--border-default)] pt-3">
+ <div className="min-w-0">
+ <div className="text-[11px] font-medium">
+ {t('rightSidebar.iosSimulator.agentControlTitle')}
+ </div>
+ <div className="mt-0.5 text-[10px] leading-relaxed text-[var(--text-secondary)]">
+ {t('rightSidebar.iosSimulator.agentControlDescription')}
+ </div>
</div>
+ <ActionButton
+ label={t(
+ grant?.agentControl === 'allowed'
+ ? 'rightSidebar.iosSimulator.disableAgentControl'
+ : 'rightSidebar.iosSimulator.allowAgentControl',
+ )}
+ icon={grant?.agentControl === 'allowed' ? ShieldOff : ShieldCheck}
+ disabled={busy}
+ onClick={() => void setAgentControl()}
+ />
</div>
- <ActionButton
- label={t(
- grant?.agentControl === 'allowed'
- ? 'rightSidebar.iosSimulator.disableAgentControl'
- : 'rightSidebar.iosSimulator.allowAgentControl',
- )}
- icon={grant?.agentControl === 'allowed' ? ShieldOff : ShieldCheck}
- disabled={busy}
- onClick={() => void setAgentControl()}
- />
- </div>
+ )}
</section>
)}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
index 2f18ff0472..2d2ed671da 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
@@ -1,11 +1,12 @@
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type {
IOSSimulatorH264FramePush,
IOSSimulatorLiveTouchRequest,
+ IOSSimulatorPublicInstance,
IOSSimulatorSessionStatus,
IOSSimulatorToolResponse,
} from '../../../../../../shared/iosSimulatorIpc';
@@ -27,6 +28,79 @@ const ctx: TabKindHostContext = {
setCloseInterceptor: () => () => undefined,
};
+function streamingJpegResult(generation = 2, sequence = 1): IOSSimulatorToolResponse {
+ return {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: 'instance-a',
+ generation,
+ state: 'streaming',
+ reconnectAttempt: 0,
+ latestFrame: {
+ instanceId: 'instance-a',
+ generation,
+ sequence,
+ encoding: 'jpeg',
+ receivedAt: '2026-07-24T00:00:00.000Z',
+ bytes: new Uint8Array([1, 2, 3]),
+ },
+ },
+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },
+ },
+ };
+}
+
+function readyInstance(generation = 2): IOSSimulatorPublicInstance {
+ return {
+ instanceId: 'instance-a',
+ sessionId: 'session-a',
+ sessionKind: 'local',
+ sourceFingerprint: 'fingerprint-a',
+ simulatorUdid: 'DEVICE-UDID-123',
+ simulatorName: 'iPhone 17 Pro',
+ runtimeIdentifier: 'runtime',
+ deviceTypeIdentifier: 'type',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ generation,
+ lifecycleState: 'ready',
+ viewerState: 'attached',
+ healthState: 'healthy',
+ lease: {
+ id: `lease-${generation}`,
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ };
+}
+
+function readyStatus(instance = readyInstance()): IOSSimulatorSessionStatus {
+ return {
+ ok: true,
+ sessionId: 'session-a',
+ deviceGrants: [],
+ mutationStates: [],
+ instances: [instance],
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ },
+ };
+}
+
function installStatus(statusValue: IOSSimulatorSessionStatus) {
const status = vi.fn(async () => statusValue);
const call = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({
@@ -34,7 +108,10 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {
data: {},
}));
const setAgentControl = vi.fn(async () => ({ ok: true as const, data: {} }));
- const setViewerVisibility = vi.fn(async () => ({ ok: true as const, data: { stream: null } }));
+ const setViewerVisibility = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({
+ ok: true,
+ data: { stream: null },
+ }));
const setStreamProfile = vi.fn(async () => ({ ok: true as const, data: {} }));
let h264FrameListener: ((payload: IOSSimulatorH264FramePush) => void) | null = null;
const onH264Frame = vi.fn((callback: (payload: IOSSimulatorH264FramePush) => void) => {
@@ -43,10 +120,13 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {
if (h264FrameListener === callback) h264FrameListener = null;
};
});
- const liveTouch = vi.fn(async (_request: IOSSimulatorLiveTouchRequest) => ({
- ok: true as const,
- data: {},
- }));
+ const liveTouch = vi.fn(async (request: IOSSimulatorLiveTouchRequest) => {
+ void request;
+ return {
+ ok: true as const,
+ data: {},
+ };
+ });
const latestFrame = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({
ok: true,
data: { stream: null },
@@ -97,12 +177,41 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {
};
}
+beforeEach(() => {
+ let objectUrlSequence = 0;
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ writable: true,
+ value: vi.fn(() => `blob:ios-simulator-${++objectUrlSequence}`),
+ });
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ configurable: true,
+ writable: true,
+ value: vi.fn(),
+ });
+ vi.stubGlobal(
+ 'Image',
+ class TestImage {
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+
+ set src(_value: string) {
+ queueMicrotask(() => this.onload?.());
+ }
+ },
+ );
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(
+ () => ({ clearRect: vi.fn(), drawImage: vi.fn() }) as never,
+ );
+});
+
afterEach(() => {
cleanup();
vi.restoreAllMocks();
delete (globalThis as { VideoDecoder?: unknown }).VideoDecoder;
delete (globalThis as { EncodedVideoChunk?: unknown }).EncodedVideoChunk;
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+ vi.unstubAllGlobals();
});
describe('IOSSimulatorTabBody', () => {
@@ -329,12 +438,14 @@ describe('IOSSimulatorTabBody', () => {
setupSteps: [],
},
});
- render(
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ api.latestFrame.mockResolvedValue(streamingJpegResult());
+ const rendered = render(
<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
);
- await waitFor(() => expect(document.querySelector('canvas')).toBeTruthy());
- const canvas = document.querySelector('canvas') as HTMLCanvasElement;
- Object.defineProperties(canvas, {
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ const image = rendered.container.querySelector('img') as HTMLImageElement;
+ Object.defineProperties(image, {
setPointerCapture: { configurable: true, value: vi.fn() },
hasPointerCapture: { configurable: true, value: vi.fn(() => true) },
releasePointerCapture: { configurable: true, value: vi.fn() },
@@ -344,9 +455,9 @@ describe('IOSSimulatorTabBody', () => {
},
});
- fireEvent.pointerDown(canvas, { pointerId: 7, button: 0, clientX: 20, clientY: 40 });
- fireEvent.pointerMove(canvas, { pointerId: 7, clientX: 100, clientY: 200 });
- fireEvent.pointerUp(canvas, { pointerId: 7, clientX: 180, clientY: 360 });
+ fireEvent.pointerDown(image, { pointerId: 7, button: 0, clientX: 20, clientY: 40 });
+ fireEvent.pointerMove(image, { pointerId: 7, clientX: 100, clientY: 200 });
+ fireEvent.pointerUp(image, { pointerId: 7, clientX: 180, clientY: 360 });
await waitFor(() => {
expect(api.liveTouch.mock.calls.map(([request]) => request.phase)).toEqual([
@@ -389,6 +500,177 @@ describe('IOSSimulatorTabBody', () => {
);
});
+ it('rejects a frame that belongs to an obsolete simulator generation', async () => {
+ const api = installStatus(readyStatus());
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult(1));
+ api.latestFrame.mockResolvedValue(streamingJpegResult(1));
+
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ await waitFor(() => {
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({ instanceId: 'instance-a', generation: 2, visible: true }),
+ );
+ });
+ expect(rendered.container.querySelector('img')).toBeNull();
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ });
+
+ it('disables simulator input when the presented frame stops refreshing', async () => {
+ const api = installStatus(readyStatus());
+ let resolveViewer!: (result: IOSSimulatorToolResponse) => void;
+ api.setViewerVisibility.mockImplementationOnce(
+ () =>
+ new Promise<IOSSimulatorToolResponse>((resolve) => {
+ resolveViewer = resolve;
+ }),
+ );
+ api.latestFrame.mockImplementation(() => new Promise<IOSSimulatorToolResponse>(() => {}));
+ let expireFreshness: (() => void) | null = null;
+ const originalSetTimeout = window.setTimeout.bind(window);
+ vi.spyOn(window, 'setTimeout').mockImplementation(
+ ((handler: TimerHandler, timeout?: number, ...args: unknown[]) => {
+ if (timeout === 3_000 && typeof handler === 'function') {
+ expireFreshness = () => handler(...args);
+ return 30_001;
+ }
+ return originalSetTimeout(handler, timeout, ...args);
+ }) as typeof window.setTimeout,
+ );
+
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+ await waitFor(() => expect(api.setViewerVisibility).toHaveBeenCalledTimes(1));
+ act(() => resolveViewer(streamingJpegResult()));
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ const homeButton = screen.getByRole('button', {
+ name: 'rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement;
+ expect(homeButton.disabled).toBe(false);
+
+ act(() => expireFreshness?.());
+
+ expect(homeButton.disabled).toBe(true);
+ });
+
+ it('clears the last frame and keeps only recovery actions after an external shutdown', async () => {
+ const readyInstance = {
+ instanceId: 'instance-a',
+ sessionId: 'session-a',
+ sessionKind: 'local' as const,
+ sourceFingerprint: 'fingerprint-a',
+ simulatorUdid: 'DEVICE-UDID-123',
+ simulatorName: 'iPhone 17 Pro',
+ runtimeIdentifier: 'runtime',
+ deviceTypeIdentifier: 'type',
+ creationProvenance: 'external' as const,
+ bootProvenance: 'preexisting' as const,
+ generation: 2,
+ lifecycleState: 'ready' as const,
+ viewerState: 'attached' as const,
+ healthState: 'healthy' as const,
+ lease: {
+ id: 'lease-a',
+ issuedAt: '2026-07-23T00:00:00.000Z',
+ expiresAt: '2026-07-23T00:10:00.000Z',
+ },
+ createdAt: '2026-07-23T00:00:00.000Z',
+ lastActiveAt: '2026-07-23T00:00:00.000Z',
+ stoppedAt: null,
+ graceExpiresAt: null,
+ errorCode: null,
+ };
+ const stoppedInstance = {
+ ...readyInstance,
+ generation: 3,
+ lifecycleState: 'stopped' as const,
+ stoppedAt: '2026-08-04T09:00:00.000Z',
+ lease: {
+ id: 'lease-b',
+ issuedAt: '2026-08-04T09:00:00.000Z',
+ expiresAt: '2026-08-04T09:10:00.000Z',
+ },
+ };
+ const environment = {
+ platform: 'darwin' as const,
+ supported: true,
+ ready: true,
+ xcodeVersion: 'Xcode 26.4',
+ runtimes: [],
+ devices: [],
+ issue: null,
+ error: null,
+ setupSteps: [],
+ };
+ const readyStatus: IOSSimulatorSessionStatus = {
+ ok: true,
+ sessionId: 'session-a',
+ deviceGrants: [],
+ mutationStates: [],
+ instances: [readyInstance],
+ environment,
+ };
+ const stoppedStatus: IOSSimulatorSessionStatus = {
+ ...readyStatus,
+ instances: [stoppedInstance],
+ };
+ const api = installStatus(readyStatus);
+ api.status.mockResolvedValueOnce(readyStatus).mockResolvedValue(stoppedStatus);
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
+ let resolveLatestFrame: ((result: IOSSimulatorToolResponse) => void) | null = null;
+ api.latestFrame.mockImplementationOnce(
+ () =>
+ new Promise<IOSSimulatorToolResponse>((resolve) => {
+ resolveLatestFrame = resolve;
+ }),
+ );
+
+ const rendered = render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ await waitFor(() => expect(rendered.container.querySelector('img')).toBeTruthy());
+ act(() => {
+ resolveLatestFrame?.({
+ ok: true,
+ data: {
+ instance: stoppedInstance,
+ stream: null,
+ viewport: null,
+ },
+ });
+ });
+
+ await waitFor(() => {
+ expect(rendered.container.querySelector('img')).toBeNull();
+ expect(screen.getByText('rightSidebar.iosSimulator.viewerStoppedTitle')).toBeTruthy();
+ expect(screen.getByText('rightSidebar.iosSimulator.viewerStoppedDescription')).toBeTruthy();
+ });
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:ios-simulator-1');
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.iosSimulator.startDevice' }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.iosSimulator.detachDevice' }),
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: 'rightSidebar.iosSimulator.pressHome' }),
+ ).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'rightSidebar.iosSimulator.stopDevice' }),
+ ).toBeNull();
+ expect(screen.queryByText('rightSidebar.iosSimulator.agentControlTitle')).toBeNull();
+ });
+
it('maps host error codes to stable localized setup steps', () => {
expect(setupStepKeys('XCODE_NOT_FOUND')).toEqual([
'rightSidebar.iosSimulator.setup.installXcode',
@@ -399,7 +681,7 @@ describe('IOSSimulatorTabBody', () => {
it('requests H.264 when WebCodecs is available and presents the first decoded canvas frame', async () => {
const drawImage = vi.fn();
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(
- () => ({ drawImage }) as never,
+ () => ({ clearRect: vi.fn(), drawImage }) as never,
);
class FakeVideoDecoder {
static async isConfigSupported() {
@@ -473,6 +755,21 @@ describe('IOSSimulatorTabBody', () => {
setupSteps: [],
},
});
+ const connectingH264: IOSSimulatorToolResponse = {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: 'instance-a',
+ generation: 2,
+ state: 'connecting',
+ reconnectAttempt: 0,
+ latestFrame: null,
+ },
+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },
+ },
+ };
+ api.setViewerVisibility.mockResolvedValue(connectingH264);
+ api.latestFrame.mockResolvedValue(connectingH264);
const rendered = render(
<IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
);
@@ -484,23 +781,23 @@ describe('IOSSimulatorTabBody', () => {
act(() => {
api.emitH264Frame({
frame: {
- instanceId: 'instance-a',
- generation: 2,
- sequence: 1,
- encoding: 'h264',
- format: 'annex-b',
- bytes: new Uint8Array([
- 0, 0, 0, 1, 0x67, 0x64, 0, 0x28, 0, 0, 0, 1, 0x68, 0xee, 0x3c, 0x80, 0, 0, 0, 1, 0x65,
- 0x88,
- ]).buffer,
- receivedAt: '2026-07-24T00:00:00.000Z',
- width: 1206,
- height: 2622,
- orientation: 'PORTRAIT',
- scale: 3,
- colorSpace: 'srgb',
- timestampMicros: 0,
- keyFrame: true,
+ instanceId: 'instance-a',
+ generation: 2,
+ sequence: 1,
+ encoding: 'h264',
+ format: 'annex-b',
+ bytes: new Uint8Array([
+ 0, 0, 0, 1, 0x67, 0x64, 0, 0x28, 0, 0, 0, 1, 0x68, 0xee, 0x3c, 0x80, 0, 0, 0, 1, 0x65,
+ 0x88,
+ ]).buffer,
+ receivedAt: '2026-07-24T00:00:00.000Z',
+ width: 1206,
+ height: 2622,
+ orientation: 'PORTRAIT',
+ scale: 3,
+ colorSpace: 'srgb',
+ timestampMicros: 0,
+ keyFrame: true,
},
});
});
@@ -562,13 +859,14 @@ describe('IOSSimulatorTabBody', () => {
.mockResolvedValueOnce(statusWithLease('lease-expired'))
.mockResolvedValueOnce(statusWithLease('lease-renewed'))
.mockResolvedValue(statusWithLease('lease-retried'));
+ api.setViewerVisibility.mockResolvedValue(streamingJpegResult());
api.latestFrame
.mockResolvedValueOnce({
ok: false,
errorCode: 'LEASE_EXPIRED',
message: 'The simulator control lease expired.',
})
- .mockResolvedValue({ ok: true, data: { stream: null } });
+ .mockResolvedValue(streamingJpegResult(2, 2));
api.call
.mockResolvedValueOnce({
ok: false,
@@ -586,6 +884,13 @@ describe('IOSSimulatorTabBody', () => {
expect(api.setViewerVisibility).toHaveBeenCalledWith(
expect.objectContaining({ leaseId: 'lease-renewed', visible: true }),
);
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false);
});
fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.iosSimulator.pressHome' }));
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 48221def30..705a9e18e5 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4365,6 +4365,8 @@
"retryHint": "Refresh the status and try again.",
"streamAlt": "Live simulator view for {{device}}",
"waitingForFrame": "The live view will appear here when connected.",
+ "viewerStoppedTitle": "Simulator stopped",
+ "viewerStoppedDescription": "Start this device to resume the live view and controls.",
"gestureHint": "Click the live view to tap, or drag across it to swipe.",
"textInputLabel": "Text to type in the simulator",
"textInputPlaceholder": "Type text in the simulator",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 016e26fcbb..467276e058 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4363,6 +4363,8 @@
"retryHint": "状態を更新してから、もう一度お試しください。",
"streamAlt": "{{device}} のライブシミュレータ画面",
"waitingForFrame": "接続されると、ここにライブ画面が表示されます。",
+ "viewerStoppedTitle": "シミュレータは停止しました",
+ "viewerStoppedDescription": "このデバイスを起動すると、ライブ画面と操作を再開できます。",
"gestureHint": "ライブ画面をクリックしてタップ、ドラッグしてスワイプできます。",
"textInputLabel": "シミュレータに入力するテキスト",
"textInputPlaceholder": "シミュレータに送るテキストを入力",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 15d2f1c7c8..9234ed7cde 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4363,6 +4363,8 @@
"retryHint": "상태를 새로 고친 후 다시 시도하세요.",
"streamAlt": "{{device}}의 실시간 시뮬레이터 화면",
"waitingForFrame": "연결되면 실시간 화면이 여기에 표시됩니다.",
+ "viewerStoppedTitle": "시뮬레이터가 중지됨",
+ "viewerStoppedDescription": "이 기기를 시작하면 실시간 화면과 제어를 다시 사용할 수 있습니다.",
"gestureHint": "실시간 화면을 클릭하면 탭하고, 드래그하면 스와이프할 수 있습니다.",
"textInputLabel": "시뮬레이터에 입력할 텍스트",
"textInputPlaceholder": "시뮬레이터에 보낼 텍스트 입력",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index cc991ae888..1eea8088ae 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4330,17 +4330,17 @@
},
"iosSimulator": {
"title": "iOS 模拟器",
- "description": "查看当前本机会话可用的 Xcode 环境和模拟器设备。",
+ "description": "查看当前本地任务可用的 Xcode 环境和模拟器设备。",
"refresh": "刷新",
"checking": "正在检查",
"readyTitle": "模拟器环境已就绪",
"unavailableTitle": "模拟器不可用",
"connectionError": "Cindy 无法检查本机模拟器环境,请重试。",
- "remoteUnsupported": "iOS 模拟器仅支持本地 macOS 会话,不支持 SSH 或远程会话。",
- "sessionUnavailable": "当前 Cindy 会话已不可用。",
+ "remoteUnsupported": "iOS 模拟器仅支持本地 macOS 任务,不支持 SSH 或远程任务。",
+ "sessionUnavailable": "当前 Cindy 任务已不可用。",
"setupTitle": "配置清单",
"devicesTitle": "可用设备",
- "instancesTitle": "当前会话的模拟器",
+ "instancesTitle": "当前任务的模拟器",
"instancesOverview": "多实例概览",
"instancesCount": "{{count}} 台就绪",
"openDevice": "打开设备",
@@ -4354,7 +4354,7 @@
"detachDevice": "断开设备",
"startDevice": "启动设备",
"stopDevice": "停止设备",
- "attachedDescription": "此设备已绑定到当前 Cindy 会话。",
+ "attachedDescription": "此设备已绑定到当前 Cindy 任务。",
"agentControlTitle": "Agent 控制",
"agentControlDescription": "允许后,Agent 才能启动、停止或操作这台设备。",
"allowAgentControl": "允许 Agent 控制",
@@ -4363,6 +4363,8 @@
"retryHint": "请刷新状态后重试。",
"streamAlt": "{{device}} 的实时模拟器画面",
"waitingForFrame": "画面连接后会显示在这里。",
+ "viewerStoppedTitle": "模拟器已停止",
+ "viewerStoppedDescription": "启动此设备后可恢复实时画面和控制。",
"gestureHint": "点击实时画面可轻点,拖动画面可滑动。",
"textInputLabel": "输入到模拟器的文本",
"textInputPlaceholder": "输入要发送到模拟器的文本",
@@ -4408,7 +4410,7 @@
"control": "正在更新输入控制…"
},
"setup": {
- "localMac": "请在 Mac 上的本地 Cindy 会话中打开此项目。",
+ "localMac": "请在 Mac 上的本地 Cindy 任务中打开此项目。",
"installXcode": "从 Mac App Store 或 Apple Developer 下载并安装 Xcode。",
"selectXcode": "打开一次 Xcode,并选择它的命令行开发者工具。",
"installRuntime": "在 Xcode 设置中安装一个 iOS 模拟器运行时。",
diff --git a/packages/ios-simulator-runtime/src/command-runner.test.ts b/packages/ios-simulator-runtime/src/command-runner.test.ts
new file mode 100644
index 0000000000..0a8daf937f
--- /dev/null
+++ b/packages/ios-simulator-runtime/src/command-runner.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+
+import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";
+
+describe("createNodeIOSSimulatorCommandRunner", () => {
+ it("keeps draining a successful process after the output buffer fills", async () => {
+ const result = await createNodeIOSSimulatorCommandRunner().run(
+ process.execPath,
+ [
+ "-e",
+ [
+ "process.stdout.write('x'.repeat(4096));",
+ "setTimeout(() => {",
+ " process.stdout.write('BUILD_FINISHED');",
+ "}, 20);",
+ ].join("\n"),
+ ],
+ { timeoutMs: 5_000, maxBufferBytes: 128 },
+ );
+
+ expect(result.exitCode).toBe(0);
+ expect(result.outputTruncated).toBe(true);
+ expect(result.stdout).toContain("BUILD_FINISHED");
+ expect(
+ Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr),
+ ).toBeLessThanOrEqual(128);
+ });
+});
diff --git a/packages/ios-simulator-runtime/src/command-runner.ts b/packages/ios-simulator-runtime/src/command-runner.ts
index 7b7eb481fc..fd4d5ff17d 100644
--- a/packages/ios-simulator-runtime/src/command-runner.ts
+++ b/packages/ios-simulator-runtime/src/command-runner.ts
@@ -24,13 +24,14 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunner
const maxBufferBytes =
options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
- const stdout: Buffer[] = [];
- const stderr: Buffer[] = [];
+ const chunks: Array<{ stream: "stdout" | "stderr"; bytes: Buffer }> =
+ [];
let outputBytes = 0;
+ let outputTruncated = false;
let settled = false;
- let stopping = false;
+ let timedOut = false;
let timer: ReturnType<typeof setTimeout> | null = setTimeout(() => {
- stopping = true;
+ timedOut = true;
killProcessTree(child);
}, timeoutMs);
if (timer && typeof timer === "object" && "unref" in timer) {
@@ -41,28 +42,45 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunner
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
+ const stdout = chunks
+ .filter((chunk) => chunk.stream === "stdout")
+ .map((chunk) => chunk.bytes);
+ const stderr = chunks
+ .filter((chunk) => chunk.stream === "stderr")
+ .map((chunk) => chunk.bytes);
resolve({
stdout: Buffer.concat(stdout).toString("utf8"),
stderr: Buffer.concat(stderr).toString("utf8"),
exitCode,
+ outputTruncated,
});
};
- const append = (target: Buffer[], chunk: Buffer) => {
- if (settled || outputBytes >= maxBufferBytes) return;
- const remaining = maxBufferBytes - outputBytes;
- const bounded =
- chunk.byteLength > remaining ? chunk.subarray(0, remaining) : chunk;
- target.push(bounded);
- outputBytes += bounded.byteLength;
- if (bounded.byteLength < chunk.byteLength) {
- stopping = true;
- killProcessTree(child);
+ const append = (stream: "stdout" | "stderr", chunk: Buffer) => {
+ if (settled || chunk.byteLength === 0) return;
+ if (maxBufferBytes <= 0) {
+ outputTruncated = true;
+ return;
+ }
+ chunks.push({ stream, bytes: Buffer.from(chunk) });
+ outputBytes += chunk.byteLength;
+ while (outputBytes > maxBufferBytes) {
+ outputTruncated = true;
+ const first = chunks[0];
+ if (!first) break;
+ const overflow = outputBytes - maxBufferBytes;
+ if (first.bytes.byteLength <= overflow) {
+ chunks.shift();
+ outputBytes -= first.bytes.byteLength;
+ continue;
+ }
+ first.bytes = first.bytes.subarray(overflow);
+ outputBytes -= overflow;
}
};
- child.stdout?.on("data", (chunk: Buffer) => append(stdout, chunk));
- child.stderr?.on("data", (chunk: Buffer) => append(stderr, chunk));
+ child.stdout?.on("data", (chunk: Buffer) => append("stdout", chunk));
+ child.stderr?.on("data", (chunk: Buffer) => append("stderr", chunk));
child.once("error", () => finish(null));
- child.once("close", (code) => finish(stopping ? null : code));
+ child.once("close", (code) => finish(timedOut ? null : code));
});
},
};
diff --git a/packages/ios-simulator-runtime/src/frame-pump.test.ts b/packages/ios-simulator-runtime/src/frame-pump.test.ts
index bc5686ee98..f7f3fbd81e 100644
--- a/packages/ios-simulator-runtime/src/frame-pump.test.ts
+++ b/packages/ios-simulator-runtime/src/frame-pump.test.ts
@@ -79,6 +79,25 @@ describe("IOSSimulatorFramePump", () => {
expect(driver.streamFrames).toHaveBeenCalledTimes(3);
});
+ it("drops the retained JPEG frame after the stream becomes disconnected", async () => {
+ const driver = driverWithStreams(["frame", "eof"]);
+ const pump = new IOSSimulatorFramePump({
+ maxReconnectAttempts: 0,
+ reconnectDelaysMs: [0],
+ });
+ pump.setVisible({
+ instanceId: "instance-a",
+ generation: 1,
+ driver,
+ visible: true,
+ });
+
+ await vi.waitFor(() =>
+ expect(pump.snapshot("instance-a")?.state).toBe("disconnected"),
+ );
+ expect(pump.snapshot("instance-a")?.latestFrame).toBeNull();
+ });
+
it("drops retained bytes when an instance is cleared", () => {
const pump = new IOSSimulatorFramePump();
const driver = driverWithStreams([]);
@@ -142,7 +161,23 @@ function nativeDriverWithStreams(streams: Array<"frame" | "eof">) {
describe("IOSSimulatorH264FramePump", () => {
it("configures a capability-selected native stream and owns one copied access unit", async () => {
- const driver = nativeDriverWithStreams(["frame", "eof"]);
+ const driver = nativeDriverWithStreams([]);
+ driver.streamNativeFrames.mockImplementationOnce(
+ async ({ signal, onFrame }) => {
+ await onFrame(h264Frame(0));
+ await new Promise<void>((resolve) => {
+ signal?.addEventListener("abort", () => resolve(), { once: true });
+ });
+ return {
+ frameCount: 1,
+ byteCount: 6,
+ startedAt: "now",
+ firstFrameAt: "now",
+ endedAt: "now",
+ endReason: "aborted",
+ };
+ },
+ );
const pump = new IOSSimulatorH264FramePump({
maxReconnectAttempts: 0,
reconnectDelaysMs: [0],
@@ -187,6 +222,7 @@ describe("IOSSimulatorH264FramePump", () => {
expect(pump.snapshot("instance-a")?.latestFrame?.bytes).not.toBe(
first.latestFrame?.bytes,
);
+ pump.clear("instance-a");
});
it("notifies the host immediately for each accepted H.264 access unit", async () => {
@@ -257,6 +293,30 @@ describe("IOSSimulatorH264FramePump", () => {
expect(pump.snapshot("instance-a")).toBeNull();
});
+ it("drops the retained H.264 frame after the stream becomes disconnected", async () => {
+ const driver = nativeDriverWithStreams(["frame", "eof"]);
+ const pump = new IOSSimulatorH264FramePump({
+ maxReconnectAttempts: 0,
+ reconnectDelaysMs: [0],
+ });
+ pump.setVisible({
+ instanceId: "instance-a",
+ generation: 1,
+ driver,
+ profile: {
+ encoding: "h264",
+ framesPerSecond: 5,
+ scalingPercent: 50,
+ },
+ visible: true,
+ });
+
+ await vi.waitFor(() =>
+ expect(pump.snapshot("instance-a")?.state).toBe("disconnected"),
+ );
+ expect(pump.snapshot("instance-a")?.latestFrame).toBeNull();
+ });
+
it("keeps host sequence monotonic when the stream profile changes", async () => {
const driver = nativeDriverWithStreams([]);
let streamCall = 0;
diff --git a/packages/ios-simulator-runtime/src/frame-pump.ts b/packages/ios-simulator-runtime/src/frame-pump.ts
index 13ca362684..f4de28d59b 100644
--- a/packages/ios-simulator-runtime/src/frame-pump.ts
+++ b/packages/ios-simulator-runtime/src/frame-pump.ts
@@ -187,6 +187,7 @@ export class IOSSimulatorFramePump {
entry.reconnectAttempt += 1;
if (entry.reconnectAttempt > this.#maxReconnectAttempts) {
entry.state = "disconnected";
+ entry.latestFrame = null;
return;
}
entry.state = "reconnecting";
@@ -383,6 +384,7 @@ export class IOSSimulatorH264FramePump {
entry.reconnectAttempt += 1;
if (entry.reconnectAttempt > this.#maxReconnectAttempts) {
entry.state = "disconnected";
+ entry.latestFrame = null;
return;
}
entry.state = "reconnecting";
diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.ts
index ac26568835..d7c4763105 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts
@@ -114,6 +114,156 @@ describe("IOSSimulatorInstanceActor", () => {
});
});
+ it("records an external shutdown without issuing another simctl mutation", async () => {
+ const harness = createHarness({ booted: true });
+ const releaseRuntime = vi.fn(async () => undefined);
+
+ const result = await harness.actor.reconcileExternalDeviceState(
+ {
+ sessionId: harness.instance.sessionId,
+ instanceId: harness.instance.instanceId,
+ simulatorUdid: harness.instance.simulatorUdid,
+ expectedGeneration: harness.instance.generation,
+ state: "shutdown",
+ },
+ releaseRuntime,
+ );
+
+ expect(result).toMatchObject({
+ applied: true,
+ previousGeneration: harness.instance.generation,
+ instance: {
+ lifecycleState: "stopped",
+ healthState: "healthy",
+ errorCode: null,
+ generation: harness.instance.generation + 1,
+ viewerState: "attached",
+ },
+ });
+ expect(releaseRuntime).toHaveBeenCalledTimes(1);
+ expect(harness.lifecycle.bootExact).not.toHaveBeenCalled();
+ expect(harness.lifecycle.shutdownExact).not.toHaveBeenCalled();
+ expect(harness.lifecycle.deleteExact).not.toHaveBeenCalled();
+ });
+
+ it("marks an externally missing device as orphaned", async () => {
+ const harness = createHarness({ booted: true });
+
+ const result = await harness.actor.reconcileExternalDeviceState({
+ sessionId: harness.instance.sessionId,
+ instanceId: harness.instance.instanceId,
+ simulatorUdid: harness.instance.simulatorUdid,
+ expectedGeneration: harness.instance.generation,
+ state: "missing",
+ });
+
+ expect(result).toMatchObject({
+ applied: true,
+ instance: {
+ lifecycleState: "error",
+ healthState: "degraded",
+ errorCode: "ORPHANED_DEVICE",
+ generation: harness.instance.generation + 1,
+ },
+ });
+ expect(harness.lifecycle.bootExact).not.toHaveBeenCalled();
+ expect(harness.lifecycle.shutdownExact).not.toHaveBeenCalled();
+ expect(harness.lifecycle.deleteExact).not.toHaveBeenCalled();
+ });
+
+ it("cancels active and queued Agent mutations before applying external state", async () => {
+ const harness = createHarness({ booted: true });
+ let releaseActive: () => void = () => undefined;
+ let activeSignal: AbortSignal | undefined;
+ const active = harness.actor.runMutation(
+ harness.route(),
+ async (_instance, signal) => {
+ activeSignal = signal;
+ await new Promise<void>((resolve) => {
+ releaseActive = resolve;
+ });
+ },
+ );
+ const queued = harness.actor
+ .runMutation(harness.route(), async () => "should-not-run")
+ .catch((error: unknown) => error);
+
+ await vi.waitFor(() => expect(activeSignal).toBeDefined());
+ const reconcile = harness.actor.reconcileExternalDeviceState({
+ sessionId: harness.instance.sessionId,
+ instanceId: harness.instance.instanceId,
+ simulatorUdid: harness.instance.simulatorUdid,
+ expectedGeneration: harness.instance.generation,
+ state: "shutdown",
+ });
+ expect(activeSignal?.aborted).toBe(true);
+ releaseActive();
+
+ await expect(active).rejects.toMatchObject({ code: "MUTATION_CANCELLED" });
+ await expect(queued).resolves.toMatchObject({ code: "MUTATION_CANCELLED" });
+ await expect(reconcile).resolves.toMatchObject({
+ applied: true,
+ instance: { lifecycleState: "stopped" },
+ });
+ });
+
+ it("ignores a stale liveness result without cancelling the new generation", async () => {
+ const harness = createHarness({ booted: true });
+ const recovered = await harness.actor.recover(harness.route());
+ let releaseMutation: () => void = () => undefined;
+ let mutationSignal: AbortSignal | undefined;
+ const mutation = harness.actor.runMutation(
+ harness.route(recovered),
+ async (_instance, signal) => {
+ mutationSignal = signal;
+ await new Promise<void>((resolve) => {
+ releaseMutation = resolve;
+ });
+ return "completed";
+ },
+ );
+ await vi.waitFor(() => expect(mutationSignal).toBeDefined());
+
+ const result = await harness.actor.reconcileExternalDeviceState({
+ sessionId: recovered.sessionId,
+ instanceId: recovered.instanceId,
+ simulatorUdid: recovered.simulatorUdid,
+ expectedGeneration: harness.instance.generation,
+ state: "shutdown",
+ });
+
+ expect(result).toMatchObject({
+ applied: false,
+ instance: { generation: recovered.generation, lifecycleState: "ready" },
+ });
+ expect(mutationSignal?.aborted).toBe(false);
+ releaseMutation();
+ await expect(mutation).resolves.toBe("completed");
+ });
+
+ it("does not advance generation for a repeated external shutdown", async () => {
+ const harness = createHarness({ booted: true });
+ const first = await harness.actor.reconcileExternalDeviceState({
+ sessionId: harness.instance.sessionId,
+ instanceId: harness.instance.instanceId,
+ simulatorUdid: harness.instance.simulatorUdid,
+ expectedGeneration: harness.instance.generation,
+ state: "shutdown",
+ });
+ const second = await harness.actor.reconcileExternalDeviceState({
+ sessionId: first.instance.sessionId,
+ instanceId: first.instance.instanceId,
+ simulatorUdid: first.instance.simulatorUdid,
+ expectedGeneration: first.instance.generation,
+ state: "shutdown",
+ });
+
+ expect(second).toMatchObject({
+ applied: false,
+ instance: { generation: first.instance.generation },
+ });
+ });
+
it("keeps agent-booted devices for grace then shuts down and releases", async () => {
const harness = createHarness();
const started = await harness.actor.start(harness.route());
diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.ts
index 2bd4f37a9f..d14667ada9 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.ts
@@ -33,6 +33,20 @@ export interface IOSSimulatorMutationState {
takeoverPending: boolean;
}
+export interface IOSSimulatorExternalDeviceReconcileInput {
+ sessionId: string;
+ instanceId: string;
+ simulatorUdid: string;
+ expectedGeneration: number;
+ state: "shutdown" | "missing";
+}
+
+export interface IOSSimulatorExternalDeviceReconcileResult {
+ applied: boolean;
+ instance: IOSSimulatorInstance;
+ previousGeneration: number;
+}
+
interface MutableMutationState {
activeSource: IOSSimulatorMutationSource | null;
lastSource: IOSSimulatorMutationSource | null;
@@ -168,6 +182,92 @@ export class IOSSimulatorInstanceActor {
});
}
+ /**
+ * Apply an exact CoreSimulator state observed outside Cindy without issuing
+ * another simctl mutation. The generation/UDID compare-and-swap is checked
+ * both before and inside the serialized lifecycle queue so an old liveness
+ * result cannot tear down a replacement instance.
+ */
+ async reconcileExternalDeviceState(
+ input: IOSSimulatorExternalDeviceReconcileInput,
+ releaseRuntime: (
+ previous: IOSSimulatorInstance,
+ next: IOSSimulatorInstance,
+ ) => void | Promise<void> = () => undefined,
+ ): Promise<IOSSimulatorExternalDeviceReconcileResult> {
+ const before = this.#store.requireOwned(input.instanceId, input.sessionId);
+ if (
+ before.generation !== input.expectedGeneration ||
+ before.simulatorUdid.toUpperCase() !== input.simulatorUdid.toUpperCase()
+ ) {
+ return {
+ applied: false,
+ instance: before,
+ previousGeneration: input.expectedGeneration,
+ };
+ }
+ const alreadyReconciled =
+ input.state === "shutdown"
+ ? before.lifecycleState === "stopped" &&
+ before.healthState === "healthy" &&
+ before.errorCode === null
+ : before.lifecycleState === "error" &&
+ before.healthState === "degraded" &&
+ before.errorCode === "ORPHANED_DEVICE";
+ if (alreadyReconciled) {
+ return {
+ applied: false,
+ instance: before,
+ previousGeneration: input.expectedGeneration,
+ };
+ }
+
+ // Invalidate mutations that entered the queue before this transition and
+ // abort the currently active Agent operation. User operations remain
+ // serialized and will revalidate their now-stale route afterwards.
+ this.#mutationState(input.instanceId).takeoverEpoch += 1;
+ this.#cancelActiveAgentMutation(input.instanceId);
+ this.#cancelGrace.get(input.instanceId)?.();
+ this.#cancelGrace.delete(input.instanceId);
+
+ return this.#serialize(input.instanceId, async () => {
+ const current = this.#store.requireOwned(
+ input.instanceId,
+ input.sessionId,
+ );
+ if (
+ current.generation !== input.expectedGeneration ||
+ current.simulatorUdid.toUpperCase() !==
+ input.simulatorUdid.toUpperCase()
+ ) {
+ return {
+ applied: false,
+ instance: current,
+ previousGeneration: input.expectedGeneration,
+ };
+ }
+
+ const now = new Date(this.#clock.now()).toISOString();
+ const renewed = this.#store.renew(current.instanceId, current.sessionId);
+ const next = this.#store.update(current.instanceId, current.sessionId, {
+ generation: current.generation + 1,
+ lifecycleState: input.state === "shutdown" ? "stopped" : "error",
+ healthState: input.state === "shutdown" ? "healthy" : "degraded",
+ errorCode: input.state === "shutdown" ? null : "ORPHANED_DEVICE",
+ lease: renewed.lease,
+ stoppedAt: input.state === "shutdown" ? now : current.stoppedAt,
+ lastActiveAt: now,
+ graceExpiresAt: null,
+ });
+ await releaseRuntime(current, next);
+ return {
+ applied: true,
+ instance: this.#store.requireOwned(input.instanceId, input.sessionId),
+ previousGeneration: current.generation,
+ };
+ });
+ }
+
getOwned(sessionId: string, instanceId: string): IOSSimulatorInstance {
return this.#store.requireOwned(instanceId, sessionId);
}
@@ -268,7 +368,7 @@ export class IOSSimulatorInstanceActor {
) {
throw new IOSSimulatorInstanceError(
"MUTATION_CANCELLED",
- "The queued simulator action was cancelled when the user took control.",
+ "The queued simulator action was cancelled because simulator control changed.",
true,
);
}
@@ -301,7 +401,7 @@ export class IOSSimulatorInstanceActor {
if (source === "agent" && controller.signal.aborted) {
throw new IOSSimulatorInstanceError(
"MUTATION_CANCELLED",
- "The active simulator action was cancelled when the user took control.",
+ "The active simulator action was cancelled because simulator control changed.",
true,
);
}
diff --git a/packages/ios-simulator-runtime/src/project-adapter.test.ts b/packages/ios-simulator-runtime/src/project-adapter.test.ts
index 5f61bcaf95..dcf9ad3981 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.test.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.test.ts
@@ -11,7 +11,10 @@ import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { IOSSimulatorProjectBuilder } from "./project-adapter.js";
+import {
+ IOSSimulatorProjectBuildError,
+ IOSSimulatorProjectBuilder,
+} from "./project-adapter.js";
const roots: string[] = [];
afterEach(async () => {
@@ -112,12 +115,12 @@ describe("IOSSimulatorProjectBuilder", () => {
roots.push(root);
await mkdir(path.join(root, "One.xcworkspace"));
await mkdir(path.join(root, "Two.xcworkspace"));
- await expect(new IOSSimulatorProjectBuilder().inspect(root)).rejects.toMatchObject(
- {
- code: "AMBIGUOUS_XCODE_PROJECT",
- message: expect.stringContaining("One.xcworkspace"),
- },
- );
+ await expect(
+ new IOSSimulatorProjectBuilder().inspect(root),
+ ).rejects.toMatchObject({
+ code: "AMBIGUOUS_XCODE_PROJECT",
+ message: expect.stringContaining("One.xcworkspace"),
+ });
});
it("builds an explicitly selected Xcode container without repository-specific rules", async () => {
@@ -189,9 +192,11 @@ describe("IOSSimulatorProjectBuilder", () => {
).rejects.toMatchObject({
code: "PROJECT_NOT_FOUND",
});
- await expect(builder.inspect(root, outsideWorkspace)).rejects.toMatchObject({
- code: "INVALID_ARGUMENT",
- });
+ await expect(builder.inspect(root, outsideWorkspace)).rejects.toMatchObject(
+ {
+ code: "INVALID_ARGUMENT",
+ },
+ );
await expect(
builder.inspect(root, "Escape.xcworkspace"),
).rejects.toMatchObject({
@@ -224,9 +229,7 @@ describe("IOSSimulatorProjectBuilder", () => {
}),
).rejects.toMatchObject({
code: "AMBIGUOUS_XCODE_PROJECT",
- message: expect.stringMatching(
- /Scheme-01.*Scheme-08.*and 4 more/,
- ),
+ message: expect.stringMatching(/Scheme-01.*Scheme-08.*and 4 more/),
});
});
@@ -281,5 +284,108 @@ describe("IOSSimulatorProjectBuilder", () => {
]),
expect.any(Object),
);
+ const settingsCall = run.mock.calls.find(([, args]) =>
+ args.includes("-showBuildSettings"),
+ );
+ expect(settingsCall?.[1]).not.toContain("-resultBundlePath");
+ });
+
+ it("uses a fresh xcresult bundle for each build", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));
+ roots.push(root);
+ const workspace = path.join(root, "Example.xcworkspace");
+ const appPath = path.join(root, "derived", "Build", "Example.app");
+ await mkdir(workspace);
+ await mkdir(appPath, { recursive: true });
+ const run = vi.fn(async (_command: string, args: readonly string[]) => {
+ if (args.includes("-list")) {
+ return {
+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ if (args.includes("-showBuildSettings")) {
+ return {
+ stdout: JSON.stringify([
+ {
+ buildSettings: {
+ TARGET_BUILD_DIR: path.dirname(appPath),
+ WRAPPER_NAME: "Example.app",
+ },
+ },
+ ]),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ const resultBundleIndex = args.indexOf("-resultBundlePath");
+ if (resultBundleIndex >= 0) {
+ await mkdir(args[resultBundleIndex + 1]!, { recursive: true });
+ }
+ return { stdout: "build succeeded", stderr: "", exitCode: 0 };
+ });
+ const builder = new IOSSimulatorProjectBuilder({ commandRunner: { run } });
+ const input = {
+ worktreeRoot: root,
+ derivedDataPath: path.join(root, "derived"),
+ };
+
+ const first = await builder.build(input);
+ const second = await builder.build(input);
+
+ expect(first.resultBundlePath).toMatch(/CindyBuild-[0-9a-f-]+\.xcresult$/);
+ expect(second.resultBundlePath).toMatch(/CindyBuild-[0-9a-f-]+\.xcresult$/);
+ expect(second.resultBundlePath).not.toBe(first.resultBundlePath);
+ });
+
+ it("retains bounded build diagnostics when xcodebuild fails", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));
+ roots.push(root);
+ await mkdir(path.join(root, "Example.xcworkspace"));
+ const run = vi.fn(async (_command: string, args: readonly string[]) => {
+ if (args.includes("-list")) {
+ return {
+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ const resultBundleIndex = args.indexOf("-resultBundlePath");
+ if (resultBundleIndex >= 0) {
+ await mkdir(args[resultBundleIndex + 1]!, { recursive: true });
+ }
+ return {
+ stdout: "compile output\nBUILD_FAILURE_MARKER",
+ stderr: "error: compile failed",
+ exitCode: 65,
+ outputTruncated: true,
+ };
+ });
+
+ const error = await new IOSSimulatorProjectBuilder({
+ commandRunner: { run },
+ })
+ .build({
+ worktreeRoot: root,
+ derivedDataPath: path.join(root, "derived"),
+ })
+ .then(
+ () => null,
+ (reason: unknown) => reason,
+ );
+
+ expect(error).toBeInstanceOf(IOSSimulatorProjectBuildError);
+ expect(error).toMatchObject({
+ name: "IOSSimulatorProjectBuildError",
+ code: "APP_BUILD_FAILED",
+ buildLogTail: expect.stringMatching(
+ /Earlier command output.*BUILD_FAILURE_MARKER.*compile failed/s,
+ ),
+ resultBundlePath: expect.stringMatching(
+ /CindyBuild-[0-9a-f-]+\.xcresult$/,
+ ),
+ outputTruncated: true,
+ });
});
});
diff --git a/packages/ios-simulator-runtime/src/project-adapter.ts b/packages/ios-simulator-runtime/src/project-adapter.ts
index f28c87c88d..4bcdf33043 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.ts
@@ -1,9 +1,13 @@
+import { randomUUID } from "node:crypto";
import { readdir, readFile, realpath, stat } from "node:fs/promises";
import path from "node:path";
import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";
import { IOSSimulatorInstanceError } from "./instance-errors.js";
-import type { IOSSimulatorCommandRunner } from "./types.js";
+import type {
+ IOSSimulatorCommandResult,
+ IOSSimulatorCommandRunner,
+} from "./types.js";
export type IOSSimulatorProjectKind =
"cindy-mobile" | "xcode-workspace" | "xcode-project";
@@ -20,6 +24,22 @@ export interface IOSSimulatorProjectBuildResult extends IOSSimulatorProjectDescr
appPath: string;
resultBundlePath?: string | null;
buildLogTail?: string;
+ outputTruncated?: boolean;
+}
+
+/** Build failure that retains bounded diagnostics without exposing raw process state. */
+export class IOSSimulatorProjectBuildError extends IOSSimulatorInstanceError {
+ constructor(
+ code: "APP_BUILD_FAILED" | "APP_ARTIFACT_INVALID",
+ message: string,
+ readonly buildLogTail: string,
+ readonly resultBundlePath: string | null,
+ readonly outputTruncated = false,
+ retryable = false,
+ ) {
+ super(code, message, retryable);
+ this.name = "IOSSimulatorProjectBuildError";
+ }
}
export interface IOSSimulatorProjectBuilderOptions {
@@ -64,7 +84,26 @@ async function containersIn(directory: string): Promise<string[]> {
}
function tail(value: string, maxBytes = 32 * 1024): string {
- return value.length <= maxBytes ? value : value.slice(-maxBytes);
+ if (maxBytes <= 0) return "";
+ const bytes = Buffer.from(value, "utf8");
+ return bytes.byteLength <= maxBytes
+ ? value
+ : bytes.subarray(-maxBytes).toString("utf8");
+}
+
+function commandLogTail(
+ results: readonly IOSSimulatorCommandResult[],
+ maxBytes = 32 * 1024,
+): string {
+ const outputTruncated = results.some((result) => result.outputTruncated);
+ const output = results
+ .flatMap((result) => [result.stdout, result.stderr])
+ .filter(Boolean)
+ .join("\n");
+ if (!outputTruncated) return tail(output, maxBytes);
+ const marker =
+ "[Earlier command output was omitted after the capture limit was reached.]\n";
+ return `${marker}${tail(output, maxBytes - Buffer.byteLength(marker))}`;
}
function isWithinRoot(root: string, candidate: string): boolean {
@@ -132,7 +171,10 @@ export class IOSSimulatorProjectBuilder {
"containerPath must remain inside the current worktree.",
);
}
- if (!isXcodeContainer(containerPath) || !(await stat(containerPath)).isDirectory()) {
+ if (
+ !isXcodeContainer(containerPath) ||
+ !(await stat(containerPath)).isDirectory()
+ ) {
throw new IOSSimulatorInstanceError(
"INVALID_ARGUMENT",
"containerPath must identify an .xcworkspace or .xcodeproj directory.",
@@ -210,10 +252,7 @@ export class IOSSimulatorProjectBuilder {
containerPath?: string;
scheme?: string;
}): Promise<IOSSimulatorProjectBuildResult> {
- const project = await this.inspect(
- input.worktreeRoot,
- input.containerPath,
- );
+ const project = await this.inspect(input.worktreeRoot, input.containerPath);
if (project.kind === "cindy-mobile") {
const result = await this.#runner.run(
"pnpm",
@@ -225,9 +264,12 @@ export class IOSSimulatorProjectBuilder {
},
);
if (result.exitCode !== 0) {
- throw new IOSSimulatorInstanceError(
+ throw new IOSSimulatorProjectBuildError(
"APP_BUILD_FAILED",
"Cindy Mobile could not be built.",
+ commandLogTail([result]),
+ null,
+ Boolean(result.outputTruncated),
true,
);
}
@@ -243,9 +285,12 @@ export class IOSSimulatorProjectBuilder {
name.endsWith(".app"),
);
if (apps.length !== 1) {
- throw new IOSSimulatorInstanceError(
+ throw new IOSSimulatorProjectBuildError(
"APP_ARTIFACT_INVALID",
"The Cindy Mobile build did not produce one unambiguous app artifact.",
+ commandLogTail([result]),
+ null,
+ Boolean(result.outputTruncated),
);
}
return {
@@ -253,7 +298,8 @@ export class IOSSimulatorProjectBuilder {
scheme: apps[0]!.slice(0, -4),
appPath: await realpath(path.join(products, apps[0]!)),
resultBundlePath: null,
- buildLogTail: tail(`${result.stdout}\n${result.stderr}`),
+ buildLogTail: commandLogTail([result]),
+ outputTruncated: Boolean(result.outputTruncated),
};
}
@@ -268,10 +314,13 @@ export class IOSSimulatorProjectBuilder {
maxBufferBytes: 1024 * 1024,
},
);
- if (list.exitCode !== 0) {
- throw new IOSSimulatorInstanceError(
+ if (list.exitCode !== 0 || list.outputTruncated) {
+ throw new IOSSimulatorProjectBuildError(
"APP_BUILD_FAILED",
"Xcode could not inspect the project.",
+ commandLogTail([list]),
+ null,
+ Boolean(list.outputTruncated),
true,
);
}
@@ -292,8 +341,7 @@ export class IOSSimulatorProjectBuilder {
schemes = [];
}
const requestedScheme = input.scheme?.trim();
- const scheme =
- requestedScheme || (schemes.length === 1 ? schemes[0]! : "");
+ const scheme = requestedScheme || (schemes.length === 1 ? schemes[0]! : "");
if (!scheme || (!requestedScheme && schemes.length !== 1)) {
throw new IOSSimulatorInstanceError(
"AMBIGUOUS_XCODE_PROJECT",
@@ -308,7 +356,7 @@ export class IOSSimulatorProjectBuilder {
`The selected Xcode scheme is unavailable. Available schemes: ${summarize(schemes)}.`,
);
}
- const common = [
+ const commonArgs = [
containerFlag,
project.containerPath!,
"-scheme",
@@ -322,34 +370,46 @@ export class IOSSimulatorProjectBuilder {
];
const resultBundlePath = path.join(
input.derivedDataPath,
- "CindyBuild.xcresult",
+ `CindyBuild-${randomUUID()}.xcresult`,
);
- common.push("-resultBundlePath", resultBundlePath);
- const build = await this.#runner.run("xcodebuild", [...common, "build"], {
- cwd: project.projectRoot,
- timeoutMs: this.#buildTimeoutMs,
- maxBufferBytes: 1024 * 1024,
- });
+ const build = await this.#runner.run(
+ "xcodebuild",
+ [...commonArgs, "-resultBundlePath", resultBundlePath, "build"],
+ {
+ cwd: project.projectRoot,
+ timeoutMs: this.#buildTimeoutMs,
+ maxBufferBytes: 1024 * 1024,
+ },
+ );
+ const availableResultBundlePath = (await exists(resultBundlePath))
+ ? resultBundlePath
+ : null;
if (build.exitCode !== 0) {
- throw new IOSSimulatorInstanceError(
+ throw new IOSSimulatorProjectBuildError(
"APP_BUILD_FAILED",
"The Xcode project could not be built.",
+ commandLogTail([build]),
+ availableResultBundlePath,
+ Boolean(build.outputTruncated),
true,
);
}
const settings = await this.#runner.run(
"xcodebuild",
- [...common, "-showBuildSettings", "-json"],
+ [...commonArgs, "-showBuildSettings", "-json"],
{
cwd: project.projectRoot,
timeoutMs: 60_000,
maxBufferBytes: 4 * 1024 * 1024,
},
);
- if (settings.exitCode !== 0) {
- throw new IOSSimulatorInstanceError(
+ if (settings.exitCode !== 0 || settings.outputTruncated) {
+ throw new IOSSimulatorProjectBuildError(
"APP_ARTIFACT_INVALID",
"Xcode build settings are unavailable.",
+ commandLogTail([build, settings]),
+ availableResultBundlePath,
+ Boolean(build.outputTruncated || settings.outputTruncated),
);
}
let appPaths: string[] = [];
@@ -371,17 +431,21 @@ export class IOSSimulatorProjectBuilder {
}
const uniqueApps = [...new Set(appPaths)];
if (uniqueApps.length !== 1 || !(await exists(uniqueApps[0]!))) {
- throw new IOSSimulatorInstanceError(
+ throw new IOSSimulatorProjectBuildError(
"APP_ARTIFACT_INVALID",
"The Xcode build did not produce one unambiguous app artifact.",
+ commandLogTail([build]),
+ availableResultBundlePath,
+ Boolean(build.outputTruncated),
);
}
return {
...project,
scheme,
appPath: await realpath(uniqueApps[0]!),
- resultBundlePath,
- buildLogTail: tail(`${build.stdout}\n${build.stderr}`),
+ resultBundlePath: availableResultBundlePath,
+ buildLogTail: commandLogTail([build]),
+ outputTruncated: Boolean(build.outputTruncated),
};
}
diff --git a/packages/ios-simulator-runtime/src/types.ts b/packages/ios-simulator-runtime/src/types.ts
index 526ff362cc..a3fbfe779a 100644
--- a/packages/ios-simulator-runtime/src/types.ts
+++ b/packages/ios-simulator-runtime/src/types.ts
@@ -54,6 +54,8 @@ export interface IOSSimulatorCommandResult {
stdout: string;
stderr: string;
exitCode: number | null;
+ /** Earlier output was discarded after the bounded rolling buffer filled. */
+ outputTruncated?: boolean;
}
export interface IOSSimulatorCommandRunner {
diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts b/packages/ios-simulator-runtime/src/wda/process-manager.test.ts
index c6afb59e92..557a8dbe49 100644
--- a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts
+++ b/packages/ios-simulator-runtime/src/wda/process-manager.test.ts
@@ -95,7 +95,7 @@ async function createHarness(
})),
configureStream: vi.fn(async (_sessionId, profile) => profile),
deleteSession: vi.fn(async () => undefined),
- } as unknown as IOSSimulatorAutomationDriver;
+ };
let now = 1_000;
const ports = [18_100, 19_100];
const manager = new WdaProcessManager({
@@ -105,7 +105,9 @@ async function createHarness(
commandRunner: { run },
processLauncher: { launch: vi.fn(() => process) },
allocatePort: vi.fn(async () => ports.shift()!),
- createDriver: vi.fn(() => driver),
+ createDriver: vi.fn(
+ () => driver as unknown as IOSSimulatorAutomationDriver,
+ ),
clock: {
now: () => now,
sleep: async (ms) => {
@@ -179,6 +181,24 @@ describe("WdaProcessManager", () => {
expect(harness.manager.get("instance-a")).toBeNull();
});
+ it("drops a cached running record when the live WDA probe fails", async () => {
+ const harness = await createHarness();
+ await harness.manager.start({
+ instanceId: "instance-a",
+ simulatorUdid: UDID,
+ runtimeIdentifier: "runtime",
+ xcodeBuild: "build",
+ architecture: "arm64",
+ });
+ harness.driver.probe.mockRejectedValueOnce(new Error("connection refused"));
+
+ await expect(harness.manager.probe("instance-a")).resolves.toBeNull();
+
+ expect(harness.manager.get("instance-a")).toBeNull();
+ expect(harness.driver.deleteSession).toHaveBeenCalledWith("wda-session");
+ expect(harness.killed).toEqual(["SIGINT"]);
+ });
+
it("waits for an in-flight start and deterministically stops the late process", async () => {
const harness = await createHarness();
const runBuild = harness.run.getMockImplementation()!;
diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.ts b/packages/ios-simulator-runtime/src/wda/process-manager.ts
index e055a3dc92..7990e13671 100644
--- a/packages/ios-simulator-runtime/src/wda/process-manager.ts
+++ b/packages/ios-simulator-runtime/src/wda/process-manager.ts
@@ -278,6 +278,33 @@ export class WdaProcessManager {
return safe;
}
+ /**
+ * Revalidate the cached WDA session. A still-running xcodebuild process is
+ * not sufficient evidence that the driver remains reachable after its
+ * CoreSimulator device exits.
+ */
+ async probe(instanceId: string): Promise<WdaRunningInstance | null> {
+ const stopping = this.#stopping.get(instanceId);
+ if (stopping) {
+ await stopping;
+ return null;
+ }
+ const running = this.#running.get(instanceId);
+ if (!running) return null;
+ try {
+ const health = await running.driver.probe();
+ if (!health.ready) throw new Error("WebDriverAgent is not ready");
+ if (this.#running.get(instanceId) !== running)
+ return this.get(instanceId);
+ running.health = health;
+ return this.get(instanceId);
+ } catch {
+ if (this.#running.get(instanceId) === running)
+ await this.stop(instanceId);
+ return null;
+ }
+ }
+
diagnostics(instanceId: string): {
running: boolean;
logTail: string;
diff --git a/packages/lizi-mcps/src/ios-simulator/tools.ts b/packages/lizi-mcps/src/ios-simulator/tools.ts
index 1247653402..924f737605 100644
--- a/packages/lizi-mcps/src/ios-simulator/tools.ts
+++ b/packages/lizi-mcps/src/ios-simulator/tools.ts
@@ -614,7 +614,7 @@ export function registerIOSSimulatorTools(
registry.register({
name: "read_build_diagnostics",
description:
- "Read a bounded chunk of build output or xcresult diagnostics returned by build_app.",
+ "Read a bounded chunk of build output or xcresult diagnostics returned by a successful or failed build_app call.",
readOnly: true,
inputShape: {
diagnosticsId: z.string().uuid(),