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): keep plugin status passive

JiangJiahaoe2fab92976c3
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 ec70cf6d92..ca8e85d05c 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
@@ -36,6 +36,7 @@ import {
createRegistryBackedIOSSimulatorActor,
disposeIOSSimulatorHost,
flushIOSSimulatorOwnershipRegistry,
+ getIOSSimulatorPluginStatus,
getIOSSimulatorMcpDeps,
reconcilePersistedIOSSimulatorOwnership,
type IOSSimulatorAppLifecycleAdapter,
@@ -108,6 +109,85 @@ describe('iOS Simulator host', () => {
}
});
+ it('keeps a cold plugin status probe passive and leaves the ownership writer available', async () => {
+ const acquireWriter = vi.spyOn(
+ IOSSimulatorOwnershipRegistryFile.prototype,
+ 'acquireWriterSync',
+ );
+ const inspectEnvironment = vi.fn(async () => READY_REPORT);
+ try {
+ await expect(
+ getIOSSimulatorPluginStatus('passive-session', {
+ getSession: vi.fn(async (id) => localSession(id)),
+ inspectEnvironment,
+ }),
+ ).resolves.toEqual({
+ ok: true,
+ status: {
+ environment: {
+ platform: 'darwin',
+ supported: true,
+ ready: true,
+ xcodeVersion: READY_REPORT.xcodeVersion,
+ availableDeviceCount: 1,
+ },
+ instances: [],
+ routeStatuses: [],
+ },
+ });
+ expect(inspectEnvironment).toHaveBeenCalledOnce();
+ expect(acquireWriter).not.toHaveBeenCalled();
+ } finally {
+ acquireWriter.mockRestore();
+ }
+ });
+
+ it.each([
+ ['missing', null, 'SESSION_NOT_FOUND'],
+ ['archived', { ...localSession('archived'), status: 'archived' as const }, 'SESSION_NOT_FOUND'],
+ [
+ 'remote',
+ { ...localSession('remote'), remoteHostId: 'remote-host' },
+ 'UNSUPPORTED_SESSION_KIND',
+ ],
+ ])(
+ 'rejects a %s passive plugin task before inspecting the simulator environment',
+ async (_case, session, errorCode) => {
+ const inspectEnvironment = vi.fn(async () => READY_REPORT);
+
+ await expect(
+ getIOSSimulatorPluginStatus('passive-session', {
+ getSession: vi.fn(async () => session),
+ inspectEnvironment,
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode });
+ expect(inspectEnvironment).not.toHaveBeenCalled();
+ },
+ );
+
+ it('fails a cold plugin status read closed when the account changes during task lookup', async () => {
+ let ownerScopeKey = 'cloud:owner-a:1';
+ const inspectEnvironment = vi.fn(async () => READY_REPORT);
+
+ await expect(
+ getIOSSimulatorPluginStatus('passive-session', {
+ getSession: vi.fn(async (id) => {
+ ownerScopeKey = 'cloud:owner-b:2';
+ return localSession(id);
+ }),
+ inspectEnvironment,
+ getOwnerScopeKey: () => ownerScopeKey,
+ isOwnerBoundaryPending: () => false,
+ isHostClosing: () => false,
+ }),
+ ).resolves.toEqual({
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ });
+ expect(inspectEnvironment).not.toHaveBeenCalled();
+ });
+
itMac('fences an ordinary removed task without retaining the default Host lease', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-lazy-cleanup-'));
const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);
@@ -536,6 +616,89 @@ describe('iOS Simulator host', () => {
await host.dispose();
});
+ it('fails plugin status closed while the account boundary is pending', async () => {
+ const getSession = vi.fn(async (id: string) => localSession(id));
+ const inspect = vi.fn(async () => READY_REPORT);
+ const host = createIOSSimulatorHost({
+ runtime: { inspect },
+ getSession,
+ getOwnerScopeKey: () => 'cloud:owner-a:1',
+ isOwnerBoundaryPending: () => true,
+ });
+
+ try {
+ await expect(host.getPluginStatus('session-a')).resolves.toEqual({
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ });
+ expect(getSession).not.toHaveBeenCalled();
+ expect(inspect).not.toHaveBeenCalled();
+ } finally {
+ await host.dispose();
+ }
+ });
+
+ it('does not return an old-owner plugin snapshot when the account changes mid-inspection', async () => {
+ let ownerScopeKey = 'cloud:owner-a:1';
+ let markInspectionStarted: () => void = () => undefined;
+ let releaseInspection: () => void = () => undefined;
+ const inspectionStarted = new Promise<void>((resolve) => {
+ markInspectionStarted = resolve;
+ });
+ const inspectionGate = new Promise<void>((resolve) => {
+ releaseInspection = resolve;
+ });
+ 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 attached = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'private-fingerprint',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'preexisting',
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ runtime: {
+ inspect: vi.fn(async () => {
+ markInspectionStarted();
+ await inspectionGate;
+ return READY_REPORT;
+ }),
+ },
+ getSession: vi.fn(async (id) => localSession(id)),
+ getOwnerScopeKey: () => ownerScopeKey,
+ isOwnerBoundaryPending: () => false,
+ });
+
+ try {
+ const statusPromise = host.getPluginStatus('session-a');
+ await inspectionStarted;
+ ownerScopeKey = 'cloud:owner-b:2';
+ releaseInspection();
+
+ const status = await statusPromise;
+ expect(status).toEqual({
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ });
+ expect(JSON.stringify(status)).not.toContain(attached.instanceId);
+ } finally {
+ releaseInspection();
+ await host.dispose();
+ }
+ });
+
it('keeps build diagnostics host-available without a running simulator instance', async () => {
const actor = new IOSSimulatorInstanceActor({
store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 6ff105e16d..f59e2781bf 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -121,6 +121,19 @@ interface IOSSimulatorSessionSnapshot {
status?: 'active' | 'archived' | 'deleted' | null;
}
+interface IOSSimulatorPluginStatusReadOptions {
+ /** Test seam; production uses the active Main-owned task database. */
+ getSession?: (sessionId: string) => Promise<IOSSimulatorSessionSnapshot | null>;
+ /** Test seam; production uses the shared passive environment cache. */
+ inspectEnvironment?: () => Promise<IOSSimulatorEnvironmentReport>;
+ /** Test seam for account-generation fencing around passive async reads. */
+ getOwnerScopeKey?: () => string;
+ /** Test seam for the fail-closed account replacement boundary. */
+ isOwnerBoundaryPending?: () => boolean;
+ /** Test seam for Desktop shutdown racing a passive status read. */
+ isHostClosing?: () => boolean;
+}
+
interface IOSSimulatorDriverManager {
get(instanceId: string): WdaRunningInstance | null;
probe?(instanceId: string): Promise<WdaRunningInstance | null>;
@@ -295,6 +308,18 @@ function sessionError(
return { ok: false, sessionId, errorCode, message };
}
+function projectPluginEnvironment(
+ environment: IOSSimulatorEnvironmentReport,
+): GhostIOSSimulatorStatusSnapshot['environment'] {
+ return {
+ platform: environment.platform,
+ supported: environment.supported,
+ ready: environment.ready,
+ xcodeVersion: environment.xcodeVersion,
+ availableDeviceCount: environment.devices.filter((device) => device.isAvailable).length,
+ };
+}
+
function reportDetachCleanupError(error: unknown, instance: IOSSimulatorInstance): void {
logger.warn('iOS Simulator deferred detach cleanup failed and will retry', {
instanceId: instance.instanceId,
@@ -2151,18 +2176,6 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
);
}
- function projectPluginEnvironment(
- environment: IOSSimulatorEnvironmentReport,
- ): GhostIOSSimulatorStatusSnapshot['environment'] {
- return {
- platform: environment.platform,
- supported: environment.supported,
- ready: environment.ready,
- xcodeVersion: environment.xcodeVersion,
- availableDeviceCount: environment.devices.filter((device) => device.isAvailable).length,
- };
- }
-
async function readPluginEnvironment(): Promise<GhostIOSSimulatorStatusSnapshot['environment']> {
const now = Date.now();
if (pluginEnvironmentCache && pluginEnvironmentCache.expiresAt > now) {
@@ -2191,7 +2204,22 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
message: 'The iOS Simulator host is shutting down.',
};
}
+ if (isOwnerBoundaryPending()) {
+ return {
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ };
+ }
+ const ownerScopeKey = getOwnerScopeKey();
const resolved = await resolveSession(sessionId);
+ if (isOwnerBoundaryPending() || getOwnerScopeKey() !== ownerScopeKey) {
+ return {
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ };
+ }
if (!resolved.ok)
return { ok: false, errorCode: resolved.errorCode, message: resolved.message };
try {
@@ -2203,6 +2231,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
message: 'The iOS Simulator host is shutting down.',
};
}
+ if (isOwnerBoundaryPending() || getOwnerScopeKey() !== ownerScopeKey) {
+ return {
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ };
+ }
const instances = actor.list(resolved.sessionId);
return {
ok: true,
@@ -6145,6 +6180,138 @@ interface DefaultIOSSimulatorRuntime {
let defaultIOSSimulatorRuntime: DefaultIOSSimulatorRuntime | null = null;
let defaultIOSSimulatorRuntimeClosing = false;
let defaultIOSSimulatorRuntimeDisposePromise: Promise<void> | null = null;
+let passivePluginRuntime: IOSSimulatorRuntime | null = null;
+let passivePluginEnvironmentCache: {
+ expiresAt: number;
+ value: GhostIOSSimulatorStatusSnapshot['environment'];
+} | null = null;
+let passivePluginEnvironmentInFlight: Promise<
+ GhostIOSSimulatorStatusSnapshot['environment']
+> | null = null;
+
+async function readPassivePluginEnvironment(): Promise<
+ GhostIOSSimulatorStatusSnapshot['environment']
+> {
+ const now = Date.now();
+ if (passivePluginEnvironmentCache && passivePluginEnvironmentCache.expiresAt > now) {
+ return passivePluginEnvironmentCache.value;
+ }
+ if (passivePluginEnvironmentInFlight) return passivePluginEnvironmentInFlight;
+ passivePluginRuntime ??= createIOSSimulatorRuntime();
+ passivePluginEnvironmentInFlight = passivePluginRuntime.inspect().then((environment) => {
+ const value = projectPluginEnvironment(environment);
+ passivePluginEnvironmentCache = {
+ value,
+ expiresAt: Date.now() + PLUGIN_ENVIRONMENT_CACHE_MS,
+ };
+ return value;
+ });
+ try {
+ return await passivePluginEnvironmentInFlight;
+ } finally {
+ passivePluginEnvironmentInFlight = null;
+ }
+}
+
+async function readPassiveIOSSimulatorPluginStatus(
+ sessionId: string,
+ options: IOSSimulatorPluginStatusReadOptions,
+): Promise<GhostIOSSimulatorStatusProbeResult> {
+ const normalizedSessionId = sessionId.trim();
+ if (!normalizedSessionId) {
+ return {
+ ok: false,
+ errorCode: 'SESSION_CONTEXT_REQUIRED',
+ message: 'A Cindy session is required.',
+ };
+ }
+ try {
+ const getOwnerScopeKey = options.getOwnerScopeKey ?? activeOwnerScopeKey;
+ const isOwnerBoundaryPending =
+ options.isOwnerBoundaryPending ?? isAppSessionBoundaryPending;
+ const isHostClosing =
+ options.isHostClosing ?? (() => defaultIOSSimulatorRuntimeClosing);
+ if (isHostClosing() || isOwnerBoundaryPending()) {
+ return {
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ };
+ }
+ const ownerScopeKey = getOwnerScopeKey();
+ const getSession =
+ options.getSession ??
+ (async (id: string) => {
+ const session = await desktopSessionStorage.get(id);
+ if (!session) return null;
+ return {
+ ...session,
+ status: await desktopSessionStorage.getStatus(id),
+ };
+ });
+ const session = await getSession(normalizedSessionId);
+ if (
+ isHostClosing() ||
+ isOwnerBoundaryPending() ||
+ getOwnerScopeKey() !== ownerScopeKey
+ ) {
+ return {
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ };
+ }
+ if (!session || (session.status && session.status !== 'active')) {
+ return {
+ ok: false,
+ errorCode: 'SESSION_NOT_FOUND',
+ message: 'The Cindy session no longer exists.',
+ };
+ }
+ if (session.remoteHostId) {
+ return {
+ ok: false,
+ errorCode: 'UNSUPPORTED_SESSION_KIND',
+ message: 'SSH and remote sessions cannot access simulators on this Mac.',
+ };
+ }
+ const environment = options.inspectEnvironment
+ ? projectPluginEnvironment(await options.inspectEnvironment())
+ : await readPassivePluginEnvironment();
+ if (
+ isHostClosing() ||
+ isOwnerBoundaryPending() ||
+ getOwnerScopeKey() !== ownerScopeKey
+ ) {
+ return {
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ };
+ }
+ return {
+ ok: true,
+ status: {
+ environment,
+ // Without an in-process Host there is no controllable task ownership
+ // or live route state to project. Never claim another process's
+ // persisted instances merely to satisfy a passive plugin probe.
+ instances: [],
+ routeStatuses: [],
+ },
+ };
+ } catch (error) {
+ logger.warn('Passive iOS Simulator plugin status snapshot failed', {
+ sessionId: normalizedSessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return {
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator status is temporarily unavailable.',
+ };
+ }
+}
function installDefaultIOSSimulatorHost(
lifecycle: IOSSimulatorSimctlLifecycle,
@@ -6222,8 +6389,18 @@ export function getIOSSimulatorSessionStatus(
export function getIOSSimulatorPluginStatus(
sessionId: string,
+ options: IOSSimulatorPluginStatusReadOptions = {},
): Promise<GhostIOSSimulatorStatusProbeResult> {
- return initializeIOSSimulatorHost().getPluginStatus(sessionId);
+ const host = currentIOSSimulatorHost();
+ if (host) return host.getPluginStatus(sessionId);
+ if (defaultIOSSimulatorRuntimeClosing) {
+ return Promise.resolve({
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',
+ message: 'The iOS Simulator host is shutting down.',
+ });
+ }
+ return readPassiveIOSSimulatorPluginStatus(sessionId, options);
}
export function callIOSSimulatorHostTool(