From fa8391446b4b2174652a5d947cfe66edf002a270 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Sun, 29 Nov 2026 17:13:05 +0100 Subject: [PATCH] fix(ios): recover simulator discovery after Xcode updates --- docs/telemetry.md | 2 + package-lock.json | 4 +- package.json | 2 +- packages/core/src/baguette.ts | 56 ++++++++++++++++++-- packages/core/src/telemetry.ts | 6 +++ packages/core/test/baguette-start.test.ts | 52 ++++++++++++++++-- packages/core/test/telemetry.test.ts | 6 ++- packages/shared/src/version.ts | 2 +- packages/ui/src/components/device-picker.tsx | 3 +- tooling/hosts/hosts.spec.ts | 26 +++++++++ 10 files changed, 146 insertions(+), 13 deletions(-) diff --git a/docs/telemetry.md b/docs/telemetry.md index 1bc8e6131..86eabc820 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -209,6 +209,8 @@ Since 0.1.140, `android.emulator.adb_reconnects` counts adb transport reconnects Since 0.1.139, `ios.accessibility_bridge.restarts` counts restarts of the simulator's CoreSimulatorBridge after a describe-UI read reported no accessibility data, with a fixed `outcome` (`recovered`, `unavailable` or `failed`). Failed restarts also report a handled `simulator.accessibility_bridge` error. The existing `inspection.tool` errors, sampled MCP traces and `ui.annotations.inspection` timings cover the retried read. No device identifiers, accessibility content or command output are sent. +`baguette.framework_restart` counts attempts to restart the plugin's simulator backend after Xcode replaces CoreSimulator. Its `outcome` is `restarted` when the replacement process serves its device list or `failed` when recovery fails. File identities stay on the Mac. + Since 0.1.134, physical iOS capture runs in the shared `ios-mirror-service` Node process. Existing native packet-processing, input acknowledgement, connection, resource, and crash instrumentation stays attached to the active capture. Native resource measurements now overlap that service's Node process rather than each chat's MCP process. The service uses centralized server initialization, its packaged development/release environment, and server-owned anonymous installation/process-session identity. UI decode/render timings and sampled MCP operations retain their existing boundaries. Subscriber keyframe requests no longer invalidate the shared native queue or release another panel’s touch. The native packet-processing and recovery measurements remain on this active path; the rebuilt addon retains matching debug symbols. `ios.mirror.shared.captures` and `ios.mirror.shared.subscribers` report active counts. `ios.mirror.shared.queue_dropped` counts frames discarded by subscriber queue overflow. Counts aggregate in 30-second windows and flush on service shutdown, using the simulator surface and physical iOS context. No per-frame events, device identifiers, subscription IDs, payloads, or paths are sent. The service clears its collection timer on shutdown and honors telemetry opt-out. diff --git a/package-lock.json b/package-lock.json index e420d897a..78740b1f6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "mobile-dev", - "version": "0.1.198", + "version": "0.1.199", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mobile-dev", - "version": "0.1.198", + "version": "0.1.199", "workspaces": [ "packages/shared", "packages/core", diff --git a/package.json b/package.json index 01b62a4bd..9d2eb9820 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mobile-dev", - "version": "0.1.198", + "version": "0.1.199", "private": true, "workspaces": [ "packages/shared", diff --git a/packages/core/src/baguette.ts b/packages/core/src/baguette.ts index 2b20c4544..6211e845c 100644 --- a/packages/core/src/baguette.ts +++ b/packages/core/src/baguette.ts @@ -1,7 +1,8 @@ import { execFile, spawn } from "node:child_process"; import { promisify } from "node:util"; import type { ChildProcess } from "node:child_process"; -import { access } from "node:fs/promises"; +import { access, stat } from "node:fs/promises"; +import { once } from "node:events"; import { constants } from "node:fs"; import { createServer } from "node:net"; import { setTimeout as delay } from "node:timers/promises"; @@ -18,7 +19,7 @@ import { annotateDeviceCommand, backendCommand, inheritDeviceCommand } from "@mo import { errorReportSignature } from "@mobile-dev/shared/telemetry.ts"; import { baguetteEnvironment } from "./baguette-runtime.ts"; import { panelRuntimePath } from "./panel-runtime.ts"; -import { captureServerError, recordAccessibilityBridgeRestart } from "./telemetry.ts"; +import { captureServerError, recordAccessibilityBridgeRestart, recordBaguetteFrameworkRestart } from "./telemetry.ts"; import type { ResourceSaving } from "./resource-saving.ts"; type DescribedUi = { tree?: { label?: unknown } }; @@ -32,6 +33,7 @@ function unnamedRoot(described: DescribedUi): boolean { } const BRIDGE_RESTART_INTERVAL = 10000; const PORT_ATTEMPTS = 3; +const CORE_SIMULATOR_BINARY = "/Library/Developer/PrivateFrameworks/CoreSimulator.framework/Versions/Current/CoreSimulator"; // A failed device list keeps its request's error, so errors built from the status say how the request failed. const listFailures = new WeakMap(); @@ -86,6 +88,8 @@ export class Baguette { resourceSaving?: ResourceSaving; readonly baseUrl: URL; private child?: ChildProcess; + private launchedFrameworkId?: string; + private readonly frameworkPath: string; private starting?: Promise; private readonly lifecycle = new AbortController(); private readonly deviceChanges = new Map>(); @@ -96,11 +100,12 @@ export class Baguette { private readonly launchBackend: (host: string, port: string, signal: AbortSignal) => Promise; private readonly startFailures = new FailureEpisodes(); - constructor(baseUrl?: string, kickstartBridge = kickstartAccessibilityBridge, launchBackend = launchBundledBaguette) { + constructor(baseUrl?: string, kickstartBridge = kickstartAccessibilityBridge, launchBackend = launchBundledBaguette, frameworkPath = CORE_SIMULATOR_BINARY) { this.embedded = baseUrl == null; this.baseUrl = parseBaseUrl(baseUrl ?? "http://127.0.0.1:0"); this.kickstartBridge = kickstartBridge; this.launchBackend = launchBackend; + this.frameworkPath = frameworkPath; } async json(path: string, options: RequestInit = {}, timeout = 10000): Promise { @@ -218,9 +223,50 @@ export class Baguette { private async ensureStarted(): Promise { const current = await this.status(); - if (current.connected) return current; + if (current.connected) { + const child = this.child; + if (current.devices.length > 0 || child === undefined) return current; + const installedId = await this.frameworkId(); + if (installedId === this.launchedFrameworkId) return current; + if (installedId === undefined) throw new Error("CoreSimulator is unavailable. Wait for Xcode to finish installing its components."); + return this.restartAfterFrameworkUpdate(child); + } // The port is our running Baguette's own, so its failed device list is not a port conflict. if (this.child) throw listError(current); + return this.startBackend(); + } + + private async frameworkId() { + try { + const file = await stat(this.frameworkPath, { bigint: true }); + return `${file.dev}:${file.ino}`; + } catch (error) { + if (isMissingFile(error)) return undefined; + throw error; + } + } + + // A running Baguette can still answer HTTP with an empty list after Xcode replaces its loaded framework. + private async restartAfterFrameworkUpdate(child: ChildProcess) { + try { + if (this.child === child) { + const deadline = AbortSignal.timeout(5000); + const signal = AbortSignal.any([deadline, this.lifecycle.signal]); + const exit = once(child, "exit", { signal }); + child.kill("SIGTERM"); + await exit; + } + this.lifecycle.signal.throwIfAborted(); + const status = await this.startBackend(); + recordBaguetteFrameworkRestart("restarted"); + return status; + } catch (error) { + if (this.disposed === false) recordBaguetteFrameworkRestart("failed"); + throw error; + } + } + + private async startBackend(): Promise { if (this.embedded === false) { // Refuse to start over a listener that is slow or is not Baguette. if (await this.portInUse()) throw new Error(`Port ${this.baseUrl.port || "80"} is in use, but its listener did not return a Baguette device list.`); @@ -252,12 +298,14 @@ export class Baguette { // Each attempt keeps its own output, so a failed attempt's late output can't explain the next one. let diagnostics = ""; const host = this.baseUrl.hostname.replace(/^\[|\]$/g, ""); + const frameworkId = await this.frameworkId(); const child = await this.launchBackend(host, this.baseUrl.port || "80", this.lifecycle.signal); if (this.disposed) { child.kill("SIGTERM"); throw new Error("The plugin server has closed."); } this.child = child; + this.launchedFrameworkId = frameworkId; let launchError: Error | undefined; const exited = new AbortController(); child.on("error", error => { launchError = error; }); diff --git a/packages/core/src/telemetry.ts b/packages/core/src/telemetry.ts index 7d0bc8e84..44711f1ce 100644 --- a/packages/core/src/telemetry.ts +++ b/packages/core/src/telemetry.ts @@ -51,6 +51,12 @@ export function recordBaguetteDiscoveryTime(operation: "xcode-select" | "otool" Sentry.metrics.distribution("baguette.runtime.command.duration", duration, { unit: "millisecond", attributes }); } +export function recordBaguetteFrameworkRestart(outcome: "restarted" | "failed") { + if (process.env.MOBILE_DEV_TELEMETRY === "off") return; + const attributes = { component: "server", outcome }; + Sentry.metrics.count("baguette.framework_restart", 1, { attributes }); +} + export function recordIosMirrorSharing(captures: number, subscribers: number, dropped: number) { if (process.env.MOBILE_DEV_TELEMETRY === "off") return; const attributes = { component: "ios-mirror-service", surface: "simulator", device_platform: "ios", device_kind: "physical" }; diff --git a/packages/core/test/baguette-start.test.ts b/packages/core/test/baguette-start.test.ts index 1fa0ffadd..878350c0f 100644 --- a/packages/core/test/baguette-start.test.ts +++ b/packages/core/test/baguette-start.test.ts @@ -2,15 +2,19 @@ import test from "node:test"; import type { TestContext } from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; +import { mkdtemp, rename, rm, writeFile } from "node:fs/promises"; import { createServer } from "node:http"; import type { RequestListener } from "node:http"; import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { Baguette } from "../src/baguette.ts"; import { isRepeatedFailure } from "../../shared/src/error-reporting.ts"; import { deviceCommandTags } from "../../shared/src/device-command-diagnostics.ts"; import { UDID } from "../../test-support/fixtures.ts"; const DEVICES = JSON.stringify({ running: [], available: [{ udid: UDID, name: "iPhone 17", state: "Shutdown", runtime: "iOS 26.0" }] }); +const EMPTY = JSON.stringify({ running: [], available: [] }); // What Baguette prints before it exits when another process holds its port. const PORT_TAKEN = 'process.stderr.write("Error: bind(descriptor:ptr:bytes:): Address already in use) (errno: 48)\\n"); process.exitCode = 1;'; @@ -29,22 +33,64 @@ function baguetteProcess(t: TestContext, script = "setInterval(() => {}, 60000)" } /** A started bundled Baguette whose device list answers with `backend.status` after `backend.latency` ms. */ -async function startedBaguette(t: TestContext) { +async function startedBaguette(t: TestContext, frameworkPath?: string, firstDevices = DEVICES) { const backend = { status: 200, latency: 0, requests: 0, launches: [] as string[] }; const baguette = new Baguette(undefined, undefined, async (_host, port) => { backend.launches.push(port); + const devices = backend.launches.length === 1 ? firstDevices : DEVICES; await listen(t, Number(port), (_request, response) => { backend.requests++; response.statusCode = backend.status; - setTimeout(() => response.end(DEVICES), backend.latency); + setTimeout(() => response.end(devices), backend.latency); }); return baguetteProcess(t); - }); + }, frameworkPath); t.after(() => baguette.dispose()); assert.equal((await baguette.start()).managed, true); return { baguette, backend }; } +async function testFramework(t: TestContext) { + const root = tmpdir(); + const prefix = join(root, "mobile-dev-coresimulator-"); + const directory = await mkdtemp(prefix); + t.after(() => rm(directory, { recursive: true, force: true })); + const path = join(directory, "CoreSimulator"); + await writeFile(path, ""); + return path; +} + +test("concurrent device lookups restart one managed Baguette after Xcode replaces CoreSimulator", async t => { + const framework = await testFramework(t); + const { baguette, backend } = await startedBaguette(t, framework, EMPTY); + const replacement = framework + ".new"; + await writeFile(replacement, ""); + await rm(framework); + const updating = baguette.start(); + await assert.rejects(updating, /CoreSimulator is unavailable/); + assert.equal(backend.launches.length, 1); + await rename(replacement, framework); + + const first = baguette.start(); + const second = baguette.start(); + const statuses = await Promise.all([first, second]); + for (const status of statuses) assert.equal(status.devices[0]?.udid, UDID); + const refreshed = await baguette.start(); + assert.equal(refreshed.devices[0]?.udid, UDID); + assert.equal(backend.launches.length, 2); +}); + +test("an empty inventory keeps its managed Baguette while CoreSimulator is unchanged", async t => { + const framework = await testFramework(t); + const { baguette, backend } = await startedBaguette(t, framework, EMPTY); + for (let index = 0; index < 2; index++) { + const status = await baguette.start(); + assert.equal(status.connected, true); + assert.deepEqual(status.devices, []); + } + assert.equal(backend.launches.length, 1); +}); + test("a running Baguette whose device list is slow or fails is never treated as a port conflict", async t => { const { baguette, backend } = await startedBaguette(t); // CoreSimulator can take seconds to list devices while one boots. diff --git a/packages/core/test/telemetry.test.ts b/packages/core/test/telemetry.test.ts index d41a8274c..b0db64de7 100644 --- a/packages/core/test/telemetry.test.ts +++ b/packages/core/test/telemetry.test.ts @@ -11,7 +11,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { z } from "zod"; import { MeasurementWindow, sampleTrace, scrubErrorEvent, scrubMetric, scrubSpan, sampleMetric, createErrorEventFilter, METRIC_SAMPLE_RATE, TELEMETRY_META_KEY } from "../../shared/src/telemetry.ts"; -import { captureServerError, installTracePropagation, instrumentMcpServer, IOSLogProcessingTelemetry, recordAndroidBackendStartup, recordAndroidBootWait, recordIosMirrorSharing, recordIosHitchOperation, recordBrowserPanelContext, recordBrowserPanelSessions, recordPanelRuntime, recordBaguetteDiscoveryTime, recordResourceSaving } from "../src/telemetry.ts"; +import { captureServerError, installTracePropagation, instrumentMcpServer, IOSLogProcessingTelemetry, recordAndroidBackendStartup, recordAndroidBootWait, recordIosMirrorSharing, recordIosHitchOperation, recordBrowserPanelContext, recordBrowserPanelSessions, recordPanelRuntime, recordBaguetteDiscoveryTime, recordBaguetteFrameworkRestart, recordResourceSaving } from "../src/telemetry.ts"; import { recordPluginUpdate } from "../../../apps/codex-plugin/server/plugin-updates.ts"; import { deferEpisodeReport, ExpectedOperationError, FailureEpisodes } from "../../shared/src/error-reporting.ts"; import { parseResourceInput } from "../src/resource-input.ts"; @@ -1452,6 +1452,7 @@ test("browser session counts describe plugin resources and honor telemetry opt-o recordPanelRuntime("testing", "downloaded", 1200, 7_000_000); recordPanelRuntime("panel", "failed", 30, undefined, "network"); recordBaguetteDiscoveryTime("otool", 2362); + recordBaguetteFrameworkRestart("restarted"); recordResourceSaving("ios", true, "success", 2500); recordResourceSaving("android", false, "failed", 100); await Sentry.flush(); @@ -1463,6 +1464,8 @@ test("browser session counts describe plugin resources and honor telemetry opt-o contains(sent, "panel_runtime.ready"); contains(sent, "panel_runtime.download_bytes"); contains(sent, "baguette.runtime.command.duration"); + contains(sent, "baguette.framework_restart"); + contains(sent, '"outcome":{"value":"restarted"'); contains(sent, '"operation":{"value":"otool"'); contains(sent, '"runtime":{"value":"testing"'); contains(sent, "resource_saving.apply"); @@ -1475,6 +1478,7 @@ test("browser session counts describe plugin resources and honor telemetry opt-o recordBrowserPanelContext("stored", 10); recordPanelRuntime("panel", "cached", 5); recordBaguetteDiscoveryTime("swift-stdlib-tool", 3442); + recordBaguetteFrameworkRestart("failed"); recordResourceSaving("ios", false, "success", 10); await Sentry.flush(); assert.equal(JSON.stringify(envelopes), sent); diff --git a/packages/shared/src/version.ts b/packages/shared/src/version.ts index 5faf38e7a..19f48991e 100644 --- a/packages/shared/src/version.ts +++ b/packages/shared/src/version.ts @@ -1 +1 @@ -export const PLUGIN_VERSION = "0.1.198"; +export const PLUGIN_VERSION = "0.1.199"; diff --git a/packages/ui/src/components/device-picker.tsx b/packages/ui/src/components/device-picker.tsx index d5a819019..80f8fabd4 100644 --- a/packages/ui/src/components/device-picker.tsx +++ b/packages/ui/src/components/device-picker.tsx @@ -54,6 +54,7 @@ export function DevicePicker({ workspace, children }: { workspace: DeviceWorkspa const { items, status, error: discoveryError } = workspace.inventory[platform]; const setupHint = status?.setupHint || (platform === "android" ? status?.error : undefined); const emptyMessage = status?.localIosSupported === false ? "Local iOS devices require macOS." : setupHint || (status ? "No devices found" : "Finding devices…"); + const simulatorListFailed = platform === "ios" && status?.localIosSupported !== false && status?.connected === false && Boolean(status.error); const label = platform === "ios" ? "iOS" : "Android"; const missing = state.panes.filter(pane => pane.platform === platform && !pane.device); return
@@ -78,7 +79,7 @@ export function DevicePicker({ workspace, children }: { workspace: DeviceWorkspa ; })} {missing.map(pane => )} - {!items.length && !missing.length &&

{emptyMessage}

} + {(simulatorListFailed || (!items.length && !missing.length)) &&

{simulatorListFailed ? "Could not load iOS simulators." : emptyMessage}

} {discoveryError && discoveryError !== emptyMessage &&
Discovery details

{discoveryError}

}
; } diff --git a/tooling/hosts/hosts.spec.ts b/tooling/hosts/hosts.spec.ts index 42d4d65a7..c0b1ebfbd 100644 --- a/tooling/hosts/hosts.spec.ts +++ b/tooling/hosts/hosts.spec.ts @@ -101,6 +101,32 @@ test.describe("MCP Apps hosts", () => { await expect(picker.getByText(/Install Android SDK Platform-Tools.*SDK Manager/)).toBeVisible(); }); + test("the device picker distinguishes a failed simulator lookup from an empty list", async ({ openView, server }) => { + test.skip(hasPanel(server) === false, "This target opens the workspace in a separate browser tab."); + const callTool = server.client.callTool.bind(server.client); + let failed = true; + server.client.callTool = async (request, ...options) => { + if (request.name === "mobile_list_ios_devices") return { content: [], structuredContent: { physicalDevices: [] } }; + if (request.name === "mobile_list_simulators") { + if (failed) return { isError: true, content: [{ type: "text", text: "Simulator backend could not restart" }] }; + return { content: [], structuredContent: { connected: true, managed: true, baseUrl: "", devices: [] } }; + } + return callTool(request, ...options); + }; + const { view } = await openView("mobile_open_simulator"); + const addDevice = view.getByRole("button", { name: "Add device" }); + await addDevice.click(); + const picker = view.getByRole("dialog", { name: "Choose devices" }); + const ios = picker.getByRole("region", { name: "iOS" }); + const error = ios.getByText("Could not load iOS simulators."); + const empty = ios.getByText("No devices found"); + await expect(error).toBeVisible(); + await expect(empty).toBeHidden(); + failed = false; + await expect(empty).toBeVisible(); + await expect(error).toBeHidden(); + }); + test("the workspace opens every tool without errors", async ({ openView, pageErrors, server }) => { test.skip(hasPanel(server) === false, "This target's server renders no panel in the chat."); const { view } = await openView("mobile_open_workspace");