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): recover deferred cleanup safely

JiangJiahao71b27ed186a7
diff --git a/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts
index f018dfe2a2..91c15edc14 100644
--- a/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts
@@ -61,10 +61,6 @@ describe('runtime-configs', () => {
const claudeConfig = buildDesktopClaudeRuntimeConfig(() => 'http://127.0.0.1:1234');
- expect(claudeConfig.systemPrompt).toContain('embedded iOS Simulator');
- expect(claudeConfig.systemPrompt).toContain('must not choose the simulator');
- expect(desktopCodexRuntimeConfig.systemPrompt).toContain('open -a Simulator');
- expect(desktopCodexRuntimeConfig.systemPrompt).toContain('Only an explicit user request');
expect(claudeConfig.memoryEnabled).toBe(false);
expect(claudeConfig.makerMemoryEnabled).toBe(true);
expect(desktopCodexRuntimeConfig.memoryEnabled).toBe(false);
diff --git a/apps/desktop/src/main/maker-host/host-system-prompt.md b/apps/desktop/src/main/maker-host/host-system-prompt.md
index 45ca1568a4..4dccd23f95 100644
--- a/apps/desktop/src/main/maker-host/host-system-prompt.md
+++ b/apps/desktop/src/main/maker-host/host-system-prompt.md
@@ -1,28 +1,2 @@
You are Cindy, an open-source AI assistant.
Source: https://github.com/makecindy/cindy
-
-## Cindy capability routing: embedded iOS Simulator
-
-When `cindy_ios_simulator` is available, it is the preferred and authoritative
-path for any request to open, run, test, inspect, or debug an iOS app or iOS
-simulator. This rule applies across all sessions, including resumed sessions,
-and takes precedence over a skill's generic local-simulator workflow or a
-repository's instructions for opening Apple's standalone Simulator.app.
-
-Use the embedded workflow in this order:
-
-1. `cindy_ios_simulator.list_tools` and `check_environment`.
-2. `list_devices`, then `create_instance` or `attach_device`.
-3. `start_instance`, followed by `build_app`, `install_app`, and `launch_app`.
-
-Skills may provide project-specific metadata such as a workspace, scheme,
-bundle identifier, or build arguments. They must not choose the simulator
-viewer or replace this workflow with `open -a Simulator`, opening
-`Simulator.app`, or direct `simctl boot` / `simctl launch` commands. Do not use
-`cindy_computer` to launch or inspect the standalone Simulator.app for normal
-iOS work.
-
-Only an explicit user request for an external macOS Simulator.app window
-authorizes that fallback. If the embedded simulator is unavailable, explain
-the limitation and ask before opening the external application; never infer
-that fallback from a skill, repository guide, or a previously used simulator.
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 528edbced8..505839ce2e 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
@@ -485,6 +485,107 @@ describe('iOS Simulator host', () => {
});
});
+ it('restores persisted detach grace and releases scheduler capacity at its deadline', async () => {
+ let now = 1_000;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const seedActor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({
+ clock: { now: () => now },
+ createId: () => crypto.randomUUID(),
+ }),
+ lifecycle,
+ clock: { now: () => now },
+ scheduler: { schedule: () => () => undefined },
+ });
+ const attached = seedActor.attach({
+ sessionId: 'persisted-grace-session',
+ worktreeRoot: '/tmp/persisted-grace-session',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'agent-booted',
+ });
+ const detached = await seedActor.detach({
+ sessionId: attached.sessionId,
+ instanceId: attached.instanceId,
+ generation: attached.generation,
+ leaseId: attached.lease.id,
+ });
+ now = 101_000;
+ const scheduled: Array<{
+ delayMs: number;
+ task: () => void | Promise<void>;
+ cancelled: boolean;
+ }> = [];
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({
+ clock: { now: () => now },
+ createId: () => crypto.randomUUID(),
+ initialInstances: [detached],
+ }),
+ lifecycle,
+ clock: { now: () => now },
+ scheduler: {
+ schedule: (delayMs, task) => {
+ const entry = { delayMs, task, cancelled: false };
+ scheduled.push(entry);
+ return () => {
+ entry.cancelled = true;
+ };
+ },
+ },
+ });
+ const resourceScheduler = new IOSSimulatorResourceScheduler({
+ softLimit: 1,
+ hardLimit: 1,
+ freeMemoryBytes: () => 100 * 1024 ** 3,
+ });
+ const driverManager = {
+ get: vi.fn(() => null),
+ cleanupOrphaned: vi.fn(async () => undefined),
+ start: vi.fn(async () => {
+ throw new Error('not expected');
+ }),
+ stop: vi.fn(async () => undefined),
+ };
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ driverManager,
+ resourceScheduler,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async () => localSession('persisted-grace-session')),
+ });
+
+ try {
+ await host.reconcileOwnership();
+
+ const reconciled = actor.getOwned(detached.sessionId, detached.instanceId);
+ expect(reconciled).toMatchObject({
+ generation: detached.generation + 1,
+ graceExpiresAt: detached.graceExpiresAt,
+ });
+ expect(resourceScheduler.runningCount()).toBe(1);
+ expect(scheduled).toHaveLength(1);
+ expect(scheduled[0]).toMatchObject({
+ delayMs: Date.parse(detached.graceExpiresAt!) - now,
+ cancelled: false,
+ });
+
+ await scheduled[0]!.task();
+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(detached.simulatorUdid);
+ expect(actor.listAll()).toEqual([]);
+ expect(resourceScheduler.runningCount()).toBe(0);
+ } finally {
+ await host.dispose();
+ }
+ });
+
it('recovers persisted WDA ownership before marking a booted binding healthy', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 9e95ac0315..b93290e040 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -284,6 +284,14 @@ function sessionError(
return { ok: false, sessionId, errorCode, message };
}
+function reportDetachCleanupError(error: unknown, instance: IOSSimulatorInstance): void {
+ logger.warn('iOS Simulator deferred detach cleanup failed and will retry', {
+ instanceId: instance.instanceId,
+ simulatorUdid: instance.simulatorUdid,
+ error: error instanceof Error ? error.message : String(error),
+ });
+}
+
export function createRegistryBackedIOSSimulatorActor(
lifecycle: IOSSimulatorSimctlLifecycle,
registry: IOSSimulatorOwnershipRegistryFile,
@@ -339,7 +347,12 @@ export function createRegistryBackedIOSSimulatorActor(
onChange: (instances) => registry.saveSync(instances),
});
return {
- actor: new IOSSimulatorInstanceActor({ store, lifecycle, assertMutationAllowed }),
+ actor: new IOSSimulatorInstanceActor({
+ store,
+ lifecycle,
+ assertMutationAllowed,
+ onDetachCleanupError: reportDetachCleanupError,
+ }),
flush: async () => {
if (registry.isWriter && !startupError) registry.saveSync(store.listAll());
},
@@ -383,6 +396,7 @@ function createInMemoryActor(lifecycle: IOSSimulatorSimctlLifecycle): IOSSimulat
maxInstancesPerSession: MAX_INSTANCES_PER_SESSION,
}),
lifecycle,
+ onDetachCleanupError: reportDetachCleanupError,
});
}
@@ -2163,6 +2177,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (!driverRuntimeRecovered) complete = false;
const device = devices.get(instance.simulatorUdid.toUpperCase());
const deviceState = device?.state.trim().toLowerCase() ?? null;
+ const shouldResumeDetachGrace =
+ instance.bootProvenance === 'agent-booted' &&
+ instance.viewerState === 'detached' &&
+ instance.graceExpiresAt !== null;
if (device && deviceState !== 'shutdown') {
// This scheduler is process-local while ownership is persisted. Restore
// observed occupancy before any fallible lookup/cleanup.
@@ -2214,7 +2232,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
complete = false;
}
}
- actor.reconcile(
+ const reconciled = actor.reconcile(
instance.instanceId,
instance.sessionId,
reconciledDeviceState === 'booted'
@@ -2232,7 +2250,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
? 'healthy'
: 'recovering',
driverRuntimeRecovered ? null : 'WDA_UNAVAILABLE',
+ { preserveDetachGrace: shouldResumeDetachGrace },
);
+ if (shouldResumeDetachGrace && driverRuntimeRecovered && complete) {
+ await actor.resumeDetachGrace(reconciled.instanceId, reconciled.sessionId, () =>
+ resourceScheduler.markStopped(reconciled.instanceId),
+ );
+ }
return complete;
}
diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.ts
index 0719db86eb..0f2dd31af8 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts
@@ -19,7 +19,13 @@ const DEVICE: IOSSimulatorDevice = {
lastBootedAt: null,
};
-function createHarness(options: { booted?: boolean; cindy?: boolean } = {}) {
+function createHarness(
+ options: {
+ booted?: boolean;
+ cindy?: boolean;
+ onDetachCleanupError?: (error: unknown) => void;
+ } = {},
+) {
let now = 1_000;
let id = 0;
const store = new IOSSimulatorOwnershipStore({
@@ -40,11 +46,18 @@ function createHarness(options: { booted?: boolean; cindy?: boolean } = {}) {
lifecycle,
clock: { now: () => now },
detachGraceMs: 10 * 60_000,
+ detachCleanupRetryMs: 1_000,
+ onDetachCleanupError: options.onDetachCleanupError,
scheduler: {
schedule: (_delay, task) => {
- scheduled.push(task);
+ const run = () => {
+ const index = scheduled.indexOf(run);
+ if (index >= 0) scheduled.splice(index, 1);
+ return task();
+ };
+ scheduled.push(run);
return () => {
- const index = scheduled.indexOf(task);
+ const index = scheduled.indexOf(run);
if (index >= 0) scheduled.splice(index, 1);
};
},
@@ -485,6 +498,112 @@ describe("IOSSimulatorInstanceActor", () => {
);
});
+ it("restores the remaining persisted detach grace after reconciliation", async () => {
+ const original = createHarness();
+ const started = await original.actor.start(original.route());
+ const detached = await original.actor.detach(original.route(started));
+ const scheduled: Array<{
+ delayMs: number;
+ task: () => void | Promise<void>;
+ }> = [];
+ let now = 101_000;
+ const lifecycle = {
+ ...original.lifecycle,
+ shutdownExact: vi.fn(async () => undefined),
+ };
+ let restoredId = 0;
+ const store = new IOSSimulatorOwnershipStore({
+ clock: { now: () => now },
+ createId: () => `restored-${++restoredId}`,
+ initialInstances: [detached],
+ });
+ const actor = new IOSSimulatorInstanceActor({
+ store,
+ lifecycle,
+ clock: { now: () => now },
+ scheduler: {
+ schedule: (delayMs, task) => {
+ const entry = { delayMs, task };
+ scheduled.push(entry);
+ return () => {
+ const index = scheduled.indexOf(entry);
+ if (index >= 0) scheduled.splice(index, 1);
+ };
+ },
+ },
+ });
+ const reconciled = actor.reconcile(
+ detached.instanceId,
+ detached.sessionId,
+ "ready",
+ "healthy",
+ null,
+ { preserveDetachGrace: true },
+ );
+ const onResourceStopped = vi.fn();
+
+ await expect(
+ actor.resumeDetachGrace(
+ reconciled.instanceId,
+ reconciled.sessionId,
+ onResourceStopped,
+ ),
+ ).resolves.toBe(true);
+
+ expect(reconciled.graceExpiresAt).toBe(detached.graceExpiresAt);
+ expect(scheduled).toHaveLength(1);
+ expect(scheduled[0]?.delayMs).toBe(
+ Date.parse(detached.graceExpiresAt!) - now,
+ );
+ await scheduled[0]?.task();
+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(UDID);
+ expect(store.get(detached.instanceId)).toBeNull();
+ expect(onResourceStopped).toHaveBeenCalledTimes(1);
+ });
+
+ it("immediately recovers an expired persisted detach grace", async () => {
+ const original = createHarness();
+ const started = await original.actor.start(original.route());
+ const detached = await original.actor.detach(original.route(started));
+ const now = Date.parse(detached.graceExpiresAt!) + 1;
+ const lifecycle = {
+ ...original.lifecycle,
+ shutdownExact: vi.fn(async () => undefined),
+ };
+ let restoredId = 0;
+ const store = new IOSSimulatorOwnershipStore({
+ clock: { now: () => now },
+ createId: () => `restored-${++restoredId}`,
+ initialInstances: [detached],
+ });
+ const actor = new IOSSimulatorInstanceActor({
+ store,
+ lifecycle,
+ clock: { now: () => now },
+ });
+ const reconciled = actor.reconcile(
+ detached.instanceId,
+ detached.sessionId,
+ "ready",
+ "healthy",
+ null,
+ { preserveDetachGrace: true },
+ );
+ const onResourceStopped = vi.fn();
+
+ await expect(
+ actor.resumeDetachGrace(
+ reconciled.instanceId,
+ reconciled.sessionId,
+ onResourceStopped,
+ ),
+ ).resolves.toBe(true);
+
+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(UDID);
+ expect(store.get(detached.instanceId)).toBeNull();
+ expect(onResourceStopped).toHaveBeenCalledTimes(1);
+ });
+
it("releases preexisting devices immediately without shutdown", async () => {
const harness = createHarness({ booted: true });
const onResourceReleased = vi.fn();
@@ -499,8 +618,9 @@ describe("IOSSimulatorInstanceActor", () => {
expect(onResourceReleased).toHaveBeenCalledWith(detached);
});
- it("keeps the resource counted when grace shutdown fails", async () => {
- const harness = createHarness();
+ it("retries grace cleanup without rejecting when shutdown fails", async () => {
+ const onDetachCleanupError = vi.fn();
+ const harness = createHarness({ onDetachCleanupError });
const started = await harness.actor.start(harness.route());
const onResourceReleased = vi.fn();
vi.mocked(harness.lifecycle.shutdownExact).mockRejectedValueOnce(
@@ -511,10 +631,63 @@ describe("IOSSimulatorInstanceActor", () => {
harness.route(started),
onResourceReleased,
);
- await expect(harness.scheduled[0]?.()).rejects.toThrow("shutdown failed");
+ await expect(harness.scheduled[0]?.()).resolves.toBeUndefined();
expect(harness.store.get(detached.instanceId)).not.toBeNull();
expect(onResourceReleased).not.toHaveBeenCalled();
+ expect(onDetachCleanupError).toHaveBeenCalledWith(
+ expect.objectContaining({ message: "shutdown failed" }),
+ expect.objectContaining({ instanceId: detached.instanceId }),
+ );
+ expect(harness.scheduled).toHaveLength(1);
+
+ await expect(harness.scheduled[0]?.()).resolves.toBeUndefined();
+ expect(harness.store.get(detached.instanceId)).toBeNull();
+ expect(onResourceReleased).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps ownership and retries when deferred resource release fails", async () => {
+ const harness = createHarness();
+ const started = await harness.actor.start(harness.route());
+ const onResourceStopped = vi
+ .fn(async () => undefined)
+ .mockRejectedValueOnce(new Error("resource release failed"));
+ const detached = await harness.actor.detach(
+ harness.route(started),
+ onResourceStopped,
+ );
+
+ await expect(harness.scheduled[0]?.()).resolves.toBeUndefined();
+ expect(harness.store.get(detached.instanceId)).not.toBeNull();
+ expect(harness.scheduled).toHaveLength(1);
+
+ await expect(harness.scheduled[0]?.()).resolves.toBeUndefined();
+ expect(harness.store.get(detached.instanceId)).toBeNull();
+ expect(onResourceStopped).toHaveBeenCalledTimes(2);
+ });
+
+ it("cancels a retry when the detached simulator is reattached", async () => {
+ const harness = createHarness();
+ const started = await harness.actor.start(harness.route());
+ vi.mocked(harness.lifecycle.shutdownExact).mockRejectedValueOnce(
+ new Error("shutdown failed"),
+ );
+ await harness.actor.detach(harness.route(started));
+ await harness.scheduled[0]?.();
+ const retry = harness.scheduled[0]!;
+
+ harness.actor.attach({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ device: { ...DEVICE, state: "Booted" },
+ creationProvenance: "external",
+ bootProvenance: "agent-booted",
+ });
+
+ expect(harness.scheduled).toHaveLength(0);
+ await retry();
+ expect(harness.lifecycle.shutdownExact).toHaveBeenCalledTimes(1);
});
it("cancels deferred resource release when a detached device is reattached", async () => {
diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.ts
index 6b10a42886..1d4c95e753 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.ts
@@ -22,6 +22,15 @@ export interface IOSSimulatorInstanceActorOptions {
clock?: IOSSimulatorClock;
scheduler?: IOSSimulatorScheduler;
detachGraceMs?: number;
+ detachCleanupRetryMs?: number;
+ onDetachCleanupError?: (
+ error: unknown,
+ instance: IOSSimulatorInstance,
+ ) => void;
+}
+
+export interface IOSSimulatorReconcileOptions {
+ preserveDetachGrace?: boolean;
}
export type IOSSimulatorMutationSource = "agent" | "user";
@@ -64,6 +73,20 @@ interface ActiveLifecycleStart {
}
const DEFAULT_DETACH_GRACE_MS = 10 * 60_000;
+const DEFAULT_DETACH_CLEANUP_RETRY_MS = 5_000;
+
+interface DetachGraceCleanupContext {
+ instanceId: string;
+ sessionId: string;
+ generation: number;
+ graceExpiresAt: string;
+ onResourceStopped: (instance: IOSSimulatorInstance) => void | Promise<void>;
+}
+
+interface ScheduledDetachGraceCleanup {
+ token: symbol;
+ cancel: () => void;
+}
function defaultScheduler(): IOSSimulatorScheduler {
return {
@@ -81,9 +104,12 @@ export class IOSSimulatorInstanceActor {
readonly #clock: IOSSimulatorClock;
readonly #scheduler: IOSSimulatorScheduler;
readonly #detachGraceMs: number;
+ readonly #detachCleanupRetryMs: number;
+ readonly #onDetachCleanupError:
+ ((error: unknown, instance: IOSSimulatorInstance) => void) | null;
readonly #assertMutationAllowed: (() => void) | null;
readonly #tails = new Map<string, Promise<void>>();
- readonly #cancelGrace = new Map<string, () => void>();
+ readonly #cancelGrace = new Map<string, ScheduledDetachGraceCleanup>();
readonly #mutationStates = new Map<string, MutableMutationState>();
readonly #activeMutations = new Map<
string,
@@ -100,6 +126,9 @@ export class IOSSimulatorInstanceActor {
this.#clock = options.clock ?? { now: () => Date.now() };
this.#scheduler = options.scheduler ?? defaultScheduler();
this.#detachGraceMs = options.detachGraceMs ?? DEFAULT_DETACH_GRACE_MS;
+ this.#detachCleanupRetryMs =
+ options.detachCleanupRetryMs ?? DEFAULT_DETACH_CLEANUP_RETRY_MS;
+ this.#onDetachCleanupError = options.onDetachCleanupError ?? null;
this.#assertMutationAllowed = options.assertMutationAllowed ?? null;
if (
!Number.isSafeInteger(this.#detachGraceMs) ||
@@ -110,12 +139,20 @@ export class IOSSimulatorInstanceActor {
"detachGraceMs must be a positive integer",
);
}
+ if (
+ !Number.isSafeInteger(this.#detachCleanupRetryMs) ||
+ this.#detachCleanupRetryMs <= 0
+ ) {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "detachCleanupRetryMs must be a positive integer",
+ );
+ }
}
attach(input: IOSSimulatorAttachInput): IOSSimulatorInstance {
const instance = this.#store.attach(input);
- this.#cancelGrace.get(instance.instanceId)?.();
- this.#cancelGrace.delete(instance.instanceId);
+ this.#cancelDetachGrace(instance.instanceId);
return this.#store.update(instance.instanceId, instance.sessionId, {
viewerState: "attached",
graceExpiresAt: null,
@@ -212,6 +249,7 @@ export class IOSSimulatorInstanceActor {
this.#store.requireOwned(instanceId, sessionId);
this.#cancelActiveAgentMutation(instanceId);
this.#abortLifecycleStartsForInstance(instanceId);
+ this.#cancelDetachGrace(instanceId);
return this.#store.release(instanceId, sessionId);
}
@@ -222,11 +260,14 @@ export class IOSSimulatorInstanceActor {
lifecycleState: IOSSimulatorInstance["lifecycleState"],
healthState: IOSSimulatorInstance["healthState"],
errorCode: string | null,
+ options: IOSSimulatorReconcileOptions = {},
): IOSSimulatorInstance {
const current = this.#store.requireOwned(instanceId, sessionId);
this.#cancelActiveAgentMutation(instanceId);
this.#abortLifecycleStartsForInstance(instanceId);
- const renewed = this.#store.renew(instanceId, sessionId);
+ const renewed = this.#store.renew(instanceId, sessionId, {
+ preserveGrace: options.preserveDetachGrace,
+ });
return this.#store.update(instanceId, sessionId, {
generation: current.generation + 1,
lifecycleState,
@@ -234,6 +275,9 @@ export class IOSSimulatorInstanceActor {
errorCode,
viewerState: "detached",
lease: renewed.lease,
+ ...(options.preserveDetachGrace
+ ? { graceExpiresAt: current.graceExpiresAt }
+ : { graceExpiresAt: null }),
});
}
@@ -283,8 +327,7 @@ export class IOSSimulatorInstanceActor {
this.#mutationState(input.instanceId).takeoverEpoch += 1;
this.#cancelActiveAgentMutation(input.instanceId);
this.#abortLifecycleStartsForInstance(input.instanceId);
- this.#cancelGrace.get(input.instanceId)?.();
- this.#cancelGrace.delete(input.instanceId);
+ this.#cancelDetachGrace(input.instanceId);
return this.#serialize(input.instanceId, async () => {
const current = this.#store.requireOwned(
@@ -515,8 +558,7 @@ export class IOSSimulatorInstanceActor {
this.#store.requireOwned(instanceId, sessionId);
this.abortMutationsForInstance(instanceId);
this.#abortLifecycleStartsForInstance(instanceId);
- this.#cancelGrace.get(instanceId)?.();
- this.#cancelGrace.delete(instanceId);
+ this.#cancelDetachGrace(instanceId);
return this.#serialize(instanceId, async () => {
const instance = this.#store.requireOwned(instanceId, sessionId);
return task(instance);
@@ -853,9 +895,39 @@ export class IOSSimulatorInstanceActor {
});
}
+ /** Restore a persisted detach deadline after Host startup reconciliation. */
+ async resumeDetachGrace(
+ instanceId: string,
+ sessionId: string,
+ onResourceStopped: (
+ instance: IOSSimulatorInstance,
+ ) => void | Promise<void> = () => undefined,
+ ): Promise<boolean> {
+ const instance = this.#store.requireOwned(instanceId, sessionId);
+ this.#cancelDetachGrace(instanceId);
+ if (
+ instance.bootProvenance !== "agent-booted" ||
+ instance.viewerState !== "detached" ||
+ instance.graceExpiresAt === null
+ ) {
+ return false;
+ }
+ const context = this.#detachGraceContext(instance, onResourceStopped);
+ const expiresAt = Date.parse(instance.graceExpiresAt);
+ const delayMs = Number.isFinite(expiresAt)
+ ? Math.max(0, expiresAt - this.#clock.now())
+ : 0;
+ if (delayMs > 0) {
+ this.#scheduleDetachGraceCleanup(context, delayMs);
+ } else {
+ await this.#attemptDetachGraceCleanup(context);
+ }
+ return true;
+ }
+
detach(
route: IOSSimulatorMutationRoute,
- onResourceReleased: (
+ onResourceStopped: (
instance: IOSSimulatorInstance,
) => void | Promise<void> = () => undefined,
): Promise<IOSSimulatorInstance> {
@@ -875,14 +947,13 @@ export class IOSSimulatorInstanceActor {
this.#abortLifecycleStartsForInstance(admission.instanceId);
return this.#serialize(admission.instanceId, async () => {
const instance = this.#requireAdmittedLifecycleRoute(admission);
- this.#cancelGrace.get(instance.instanceId)?.();
- this.#cancelGrace.delete(instance.instanceId);
+ this.#cancelDetachGrace(instance.instanceId);
if (instance.bootProvenance !== "agent-booted") {
const released = this.#store.release(
instance.instanceId,
instance.sessionId,
);
- await onResourceReleased(released);
+ await onResourceStopped(released);
return released;
}
@@ -897,45 +968,124 @@ export class IOSSimulatorInstanceActor {
graceExpiresAt,
},
);
- const expectedGeneration = detached.generation;
- const cancel = this.#scheduler.schedule(this.#detachGraceMs, async () => {
- try {
- await this.#serialize(detached.instanceId, async () => {
- const current = this.#store.get(detached.instanceId);
- if (
- !current ||
- current.viewerState !== "detached" ||
- current.generation !== expectedGeneration ||
- current.graceExpiresAt !== graceExpiresAt
- ) {
- return;
- }
- this.#assertMutationAllowed?.();
- await this.#lifecycle.shutdownExact(current.simulatorUdid);
- const afterShutdown = this.#store.get(detached.instanceId);
- if (
- !afterShutdown ||
- afterShutdown.viewerState !== "detached" ||
- afterShutdown.generation !== expectedGeneration ||
- afterShutdown.graceExpiresAt !== graceExpiresAt
- ) {
- return;
- }
- const released = this.#store.release(
- afterShutdown.instanceId,
- afterShutdown.sessionId,
- );
- await onResourceReleased(released);
- });
- } finally {
- this.#cancelGrace.delete(detached.instanceId);
- }
- });
- this.#cancelGrace.set(detached.instanceId, cancel);
+ this.#scheduleDetachGraceCleanup(
+ this.#detachGraceContext(detached, onResourceStopped),
+ this.#detachGraceMs,
+ );
return detached;
});
}
+ #detachGraceContext(
+ instance: IOSSimulatorInstance,
+ onResourceStopped: (instance: IOSSimulatorInstance) => void | Promise<void>,
+ ): DetachGraceCleanupContext {
+ if (instance.graceExpiresAt === null) {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "Detached simulator cleanup requires a grace deadline.",
+ );
+ }
+ return {
+ instanceId: instance.instanceId,
+ sessionId: instance.sessionId,
+ generation: instance.generation,
+ graceExpiresAt: instance.graceExpiresAt,
+ onResourceStopped,
+ };
+ }
+
+ #matchingDetachGrace(
+ context: DetachGraceCleanupContext,
+ ): IOSSimulatorInstance | null {
+ const current = this.#store.get(context.instanceId);
+ if (
+ !current ||
+ current.sessionId !== context.sessionId ||
+ current.bootProvenance !== "agent-booted" ||
+ current.viewerState !== "detached" ||
+ current.generation !== context.generation ||
+ current.graceExpiresAt !== context.graceExpiresAt
+ ) {
+ return null;
+ }
+ return current;
+ }
+
+ #cancelDetachGrace(instanceId: string): void {
+ this.#cancelGrace.get(instanceId)?.cancel();
+ this.#cancelGrace.delete(instanceId);
+ }
+
+ #clearDetachGraceAttempt(instanceId: string, token: symbol): void {
+ if (this.#cancelGrace.get(instanceId)?.token === token) {
+ this.#cancelGrace.delete(instanceId);
+ }
+ }
+
+ #scheduleDetachGraceCleanup(
+ context: DetachGraceCleanupContext,
+ delayMs: number,
+ ): void {
+ this.#cancelDetachGrace(context.instanceId);
+ const token = Symbol("detach-grace-cleanup");
+ const cancel = this.#scheduler.schedule(Math.max(0, delayMs), () =>
+ this.#runDetachGraceCleanup(context).then(
+ () => this.#clearDetachGraceAttempt(context.instanceId, token),
+ (error: unknown) => {
+ this.#clearDetachGraceAttempt(context.instanceId, token);
+ this.#retryDetachGraceCleanup(context, error);
+ },
+ ),
+ );
+ this.#cancelGrace.set(context.instanceId, { token, cancel });
+ }
+
+ async #attemptDetachGraceCleanup(
+ context: DetachGraceCleanupContext,
+ ): Promise<void> {
+ try {
+ await this.#runDetachGraceCleanup(context);
+ } catch (error) {
+ this.#retryDetachGraceCleanup(context, error);
+ }
+ }
+
+ #retryDetachGraceCleanup(
+ context: DetachGraceCleanupContext,
+ error: unknown,
+ ): void {
+ const current = this.#matchingDetachGrace(context);
+ if (!current) return;
+ try {
+ this.#onDetachCleanupError?.(error, current);
+ } catch {
+ // Diagnostics must never prevent ownership recovery from retrying.
+ }
+ this.#scheduleDetachGraceCleanup(context, this.#detachCleanupRetryMs);
+ }
+
+ #runDetachGraceCleanup(context: DetachGraceCleanupContext): Promise<void> {
+ return this.#serialize(context.instanceId, async () => {
+ const current = this.#matchingDetachGrace(context);
+ if (!current) return;
+ this.#assertMutationAllowed?.();
+ await this.#lifecycle.shutdownExact(current.simulatorUdid);
+ const afterShutdown = this.#matchingDetachGrace(context);
+ if (!afterShutdown) return;
+ // Resource release is intentionally before ownership release. The Host
+ // callback is idempotent, so either failure leaves a persisted binding
+ // that startup reconciliation or this retry loop can safely recover.
+ await context.onResourceStopped(afterShutdown);
+ const afterResourceStop = this.#matchingDetachGrace(context);
+ if (!afterResourceStop) return;
+ this.#store.release(
+ afterResourceStop.instanceId,
+ afterResourceStop.sessionId,
+ );
+ });
+ }
+
/**
* A teardown admitted before the actor queue may follow a start that advances
* generation. Keep the exact session/instance/lease authority captured at
@@ -971,8 +1121,7 @@ export class IOSSimulatorInstanceActor {
await this.#lifecycle.shutdownExact(instance.simulatorUdid);
}
await this.#lifecycle.deleteExact(instance.simulatorUdid);
- this.#cancelGrace.get(instance.instanceId)?.();
- this.#cancelGrace.delete(instance.instanceId);
+ this.#cancelDetachGrace(instance.instanceId);
return this.#store.release(instance.instanceId, instance.sessionId);
});
}
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts
index 2154aaa89b..c5b1e1ffba 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts
@@ -307,6 +307,32 @@ describe("IOSSimulatorNativeSidecarChannel", () => {
expect(channel.state).toBe("failed");
});
+ it.each([
+ ["missing", undefined],
+ ["non-boolean", "yes"],
+ ])(
+ "rejects a pending request when its reply has a %s ok field",
+ async (_label, ok) => {
+ const { channel, processes } = harness();
+ await channel.start();
+ const pending = channel.request(command("availability"));
+ processes[0]!.stdout.write(
+ encodeIOSSimulatorNativeSidecarJson({
+ id: "sidecar-1",
+ ...(ok === undefined ? {} : { ok }),
+ result: { ready: true },
+ }),
+ );
+
+ await expect(pending).rejects.toMatchObject({
+ code: "PROTOCOL_ERROR",
+ message: "Reply sidecar-1 has invalid ok field",
+ });
+ expect(channel.state).toBe("failed");
+ expect(channel.lastTermination?.reasonCode).toBe("protocol-error");
+ },
+ );
+
it("waits for a faulted process to close before stop or restart completes", async () => {
vi.useFakeTimers();
try {
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.ts
index 11a5428ca9..e2c11be56c 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/channel.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.ts
@@ -812,15 +812,18 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec
throw new IOSSimulatorNativeSidecarProtocolError(
`Unknown reply id ${id}`,
);
- this.#pending.delete(id);
- clearTimeout(pending.timeout);
- pending.removeAbortListener();
- this.#consecutiveTimeouts = 0;
+ // Validate while the request is still registered. A protocol fault
+ // terminates the sidecar and #rejectAll must still be able to settle this
+ // promise instead of leaving startup or an operation hung forever.
if (reply.ok !== true && reply.ok !== false) {
throw new IOSSimulatorNativeSidecarProtocolError(
`Reply ${id} has invalid ok field`,
);
}
+ this.#pending.delete(id);
+ clearTimeout(pending.timeout);
+ pending.removeAbortListener();
+ this.#consecutiveTimeouts = 0;
if (reply.ok) {
pending.resolve(reply.result);
} else {
diff --git a/packages/ios-simulator-runtime/src/ownership-store.ts b/packages/ios-simulator-runtime/src/ownership-store.ts
index 73a03055a8..3a3444cd65 100644
--- a/packages/ios-simulator-runtime/src/ownership-store.ts
+++ b/packages/ios-simulator-runtime/src/ownership-store.ts
@@ -248,13 +248,17 @@ export class IOSSimulatorOwnershipStore {
return instance;
}
- renew(instanceId: string, sessionId: string): IOSSimulatorInstance {
+ renew(
+ instanceId: string,
+ sessionId: string,
+ options: { preserveGrace?: boolean } = {},
+ ): IOSSimulatorInstance {
const instance = this.requireOwned(instanceId, sessionId);
const now = this.#clock.now();
return this.update(instanceId, sessionId, {
lease: this.#newLease(now),
lastActiveAt: new Date(now).toISOString(),
- graceExpiresAt: null,
+ ...(options.preserveGrace ? {} : { graceExpiresAt: null }),
});
}