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): reconcile ownership per account

JiangJiahaoc66027b33ce5
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 3296f71402..b30e9e5d50 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
@@ -649,6 +649,176 @@ describe('iOS Simulator host', () => {
});
});
+ it('reconciles ownership again for a new account generation and releases stale capacity', async () => {
+ let ownerScopeKey = 'cloud:owner-a:1';
+ let ownerBoundaryPending = false;
+ let sessionExists = true;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const attached = actor.attach({
+ sessionId: 'owner-a-session',
+ worktreeRoot: '/tmp/owner-a-session',
+ sourceFingerprint: 'owner-a-fingerprint',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'agent-booted',
+ });
+ const resourceScheduler = new IOSSimulatorResourceScheduler({
+ softLimit: 1,
+ hardLimit: 1,
+ freeMemoryBytes: () => 100 * 1024 ** 3,
+ });
+ const inspect = vi.fn(async () => READY_REPORT);
+ const getSession = vi.fn(async (id: string) => (sessionExists ? localSession(id) : null));
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ resourceScheduler,
+ runtime: { inspect },
+ getSession,
+ getOwnerScopeKey: () => ownerScopeKey,
+ isOwnerBoundaryPending: () => ownerBoundaryPending,
+ });
+
+ try {
+ await host.reconcileOwnership();
+ expect(actor.getOwned(attached.sessionId, attached.instanceId)).toBeDefined();
+ expect(resourceScheduler.runningCount()).toBe(1);
+ expect(inspect).toHaveBeenCalledTimes(1);
+
+ await host.reconcileOwnership();
+ expect(inspect).toHaveBeenCalledTimes(1);
+
+ ownerScopeKey = 'cloud:owner-b:2';
+ sessionExists = false;
+ ownerBoundaryPending = true;
+ await host.reconcileOwnership();
+ expect(inspect).toHaveBeenCalledTimes(1);
+ expect(resourceScheduler.runningCount()).toBe(1);
+
+ ownerBoundaryPending = false;
+ await host.reconcileOwnership();
+ expect(inspect).toHaveBeenCalledTimes(2);
+ expect(getSession).toHaveBeenCalledTimes(2);
+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(
+ attached.simulatorUdid,
+ expect.any(AbortSignal),
+ );
+ expect(actor.listAll()).toEqual([]);
+ expect(resourceScheduler.runningCount()).toBe(0);
+ } finally {
+ await host.dispose();
+ }
+ });
+
+ it.each(['success', 'failure'] as const)(
+ 'waits for an old-owner reconciliation (%s) and then reruns for the current owner',
+ async (oldOwnerResult) => {
+ let ownerScopeKey = 'cloud:owner-a:1';
+ let resolveFirstInspectionStarted: (() => void) | undefined;
+ let releaseFirstInspection: (() => void) | undefined;
+ const firstInspectionStarted = new Promise<void>((resolve) => {
+ resolveFirstInspectionStarted = resolve;
+ });
+ const firstInspectionGate = new Promise<void>((resolve) => {
+ releaseFirstInspection = resolve;
+ });
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const attached = actor.attach({
+ sessionId: 'owner-a-session',
+ worktreeRoot: '/tmp/owner-a-session',
+ sourceFingerprint: 'owner-a-fingerprint',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'agent-booted',
+ });
+ const resourceScheduler = new IOSSimulatorResourceScheduler({
+ softLimit: 1,
+ hardLimit: 1,
+ freeMemoryBytes: () => 100 * 1024 ** 3,
+ });
+ let sessionReadCount = 0;
+ const getSession = vi.fn(async (id: string) => {
+ sessionReadCount += 1;
+ if (oldOwnerResult === 'success' && sessionReadCount === 1) {
+ return localSession(id);
+ }
+ return null;
+ });
+ let inspectionCount = 0;
+ const inspect = vi.fn(async () => {
+ inspectionCount += 1;
+ if (inspectionCount === 1) {
+ resolveFirstInspectionStarted?.();
+ await firstInspectionGate;
+ if (oldOwnerResult === 'failure') throw new Error('old owner DB closed');
+ }
+ return READY_REPORT;
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ resourceScheduler,
+ runtime: { inspect },
+ getSession,
+ getOwnerScopeKey: () => ownerScopeKey,
+ isOwnerBoundaryPending: () => false,
+ });
+
+ try {
+ const ownerAReconcile = host.reconcileOwnership();
+ const ownerAOutcome = ownerAReconcile.then(
+ () => ({ ok: true as const, error: null }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+ await firstInspectionStarted;
+ ownerScopeKey = 'cloud:owner-b:2';
+ const ownerBReconcile = host.reconcileOwnership();
+ releaseFirstInspection?.();
+ await ownerBReconcile;
+ const ownerASettled = await ownerAOutcome;
+
+ if (oldOwnerResult === 'failure') {
+ expect(ownerASettled).toMatchObject({
+ ok: false,
+ error: expect.objectContaining({ message: 'old owner DB closed' }),
+ });
+ } else {
+ expect(ownerASettled).toEqual({ ok: true, error: null });
+ }
+
+ expect(getSession).toHaveBeenCalledTimes(oldOwnerResult === 'failure' ? 1 : 2);
+ expect(inspect).toHaveBeenCalledTimes(2);
+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(
+ attached.simulatorUdid,
+ expect.any(AbortSignal),
+ );
+ expect(actor.listAll()).toEqual([]);
+ expect(resourceScheduler.runningCount()).toBe(0);
+ } finally {
+ releaseFirstInspection?.();
+ await host.dispose();
+ }
+ },
+ );
+
it('restores persisted detach grace and releases scheduler capacity at its deadline', async () => {
let now = 1_000;
const lifecycle: IOSSimulatorSimctlLifecycle = {
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 2e52604723..6ff105e16d 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -83,6 +83,7 @@ import type {
GhostIOSSimulatorStatusProbeResult,
GhostIOSSimulatorStatusSnapshot,
} from '../../shared/ghost.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import { createLogger } from '../logger.js';
import { redact } from '../log-upload/redact.js';
import { withSessionRouteLock } from '../localDb/sessionRouteLock.js';
@@ -185,6 +186,10 @@ export interface IOSSimulatorHostOptions {
resourceScheduler?: IOSSimulatorResourceScheduler;
/** Fail-closed gate supplied by the persisted registry owner. */
canReconcilePendingCreates?: () => boolean;
+ /** Main-owned account generation used to scope persisted ownership reconciliation. */
+ getOwnerScopeKey?: () => string;
+ /** Fail closed while the active account runtime is being replaced. */
+ isOwnerBoundaryPending?: () => boolean;
/** Recycle an idle WDA process while retaining the booted simulator binding. */
idleRecycleMs?: number;
/** Minimum interval between exact-UDID CoreSimulator liveness checks. */
@@ -1021,8 +1026,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
promise: Promise<IOSSimulatorInstance> | null;
}
>();
- let ownershipReconciled = false;
- let ownershipReconcilePromise: Promise<void> | null = null;
+ const getOwnerScopeKey = options.getOwnerScopeKey ?? activeOwnerScopeKey;
+ const isOwnerBoundaryPending =
+ options.isOwnerBoundaryPending ?? isAppSessionBoundaryPending;
+ let ownershipReconciledScopeKey: string | null = null;
+ let ownershipReconcilePromise: { scopeKey: string; promise: Promise<void> } | null = null;
let pendingCreateReconcileController: AbortController | null = null;
let pendingCreateReconcilePromise: Promise<unknown> | null = null;
let startupPendingCreateRecoveryAttempted = false;
@@ -1951,7 +1959,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (cleanupSucceeded) {
actor.forget(instance.instanceId, instance.sessionId);
} else {
- ownershipReconciled = false;
+ ownershipReconciledScopeKey = null;
actor.reconcile(
instance.instanceId,
instance.sessionId,
@@ -2377,9 +2385,40 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
async function reconcilePersistedOwnership(): Promise<void> {
if (disposePromise) return;
- if (ownershipReconciled) return;
- if (ownershipReconcilePromise) return ownershipReconcilePromise;
- ownershipReconcilePromise = (async () => {
+ if (isOwnerBoundaryPending()) return;
+ const requestedScopeKey = getOwnerScopeKey();
+ if (ownershipReconciledScopeKey === requestedScopeKey) return;
+ const inFlight = ownershipReconcilePromise;
+ if (inFlight) {
+ try {
+ await inFlight.promise;
+ } catch (error) {
+ if (disposePromise || isOwnerBoundaryPending()) return;
+ if (getOwnerScopeKey() !== requestedScopeKey) return;
+ // A failed old-owner pass is not the new owner's result. Retry against
+ // the current DB instead of surfacing stale-owner failure or leaving
+ // the old scheduler occupancy latched until the next process start.
+ if (inFlight.scopeKey !== requestedScopeKey) {
+ return reconcilePersistedOwnership();
+ }
+ throw error;
+ }
+ if (disposePromise || isOwnerBoundaryPending()) return;
+ // A new owner must not treat the previous owner's reconciliation as its
+ // own. Wait for the old pass to settle, then run a fresh pass against
+ // the new owner DB. A caller whose own scope became stale simply exits.
+ if (getOwnerScopeKey() !== requestedScopeKey) return;
+ if (
+ inFlight.scopeKey !== requestedScopeKey &&
+ ownershipReconciledScopeKey !== requestedScopeKey
+ ) {
+ return reconcilePersistedOwnership();
+ }
+ return;
+ }
+ const scopeKey = requestedScopeKey;
+ let reconciliation!: Promise<void>;
+ reconciliation = (async () => {
let complete = true;
if (!startupPendingCreateRecoveryAttempted && lifecycle.recoverPendingCreatesAtStartup) {
if (!canReconcilePendingCreates()) {
@@ -2452,11 +2491,19 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
);
if (!instanceComplete) complete = false;
}
- ownershipReconciled = complete;
+ // Every DB/session read above belongs to the captured owner generation.
+ // Never latch it across an account boundary or let an old in-flight pass
+ // suppress the new owner's required cleanup and scheduler reconciliation.
+ if (!isOwnerBoundaryPending() && getOwnerScopeKey() === scopeKey) {
+ ownershipReconciledScopeKey = complete ? scopeKey : null;
+ }
})().finally(() => {
- ownershipReconcilePromise = null;
+ if (ownershipReconcilePromise?.promise === reconciliation) {
+ ownershipReconcilePromise = null;
+ }
});
- return ownershipReconcilePromise;
+ ownershipReconcilePromise = { scopeKey, promise: reconciliation };
+ return reconciliation;
}
async function ensureDriver(