Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mobile-dev",
"version": "0.1.198",
"version": "0.1.199",
"private": true,
"workspaces": [
"packages/shared",
Expand Down
56 changes: 52 additions & 4 deletions packages/core/src/baguette.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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 } };
Expand All @@ -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<Status, unknown>();

Expand Down Expand Up @@ -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<Status>;
private readonly lifecycle = new AbortController();
private readonly deviceChanges = new Map<string, Promise<Status>>();
Expand All @@ -96,11 +100,12 @@ export class Baguette {
private readonly launchBackend: (host: string, port: string, signal: AbortSignal) => Promise<ChildProcess>;
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<unknown> {
Expand Down Expand Up @@ -218,9 +223,50 @@ export class Baguette {

private async ensureStarted(): Promise<Status> {
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<Status> {
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.`);
Expand Down Expand Up @@ -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; });
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" };
Expand Down
52 changes: 49 additions & 3 deletions packages/core/test/baguette-start.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;';

Expand All @@ -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.
Expand Down
6 changes: 5 additions & 1 deletion packages/core/test/telemetry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
Expand All @@ -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");
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion packages/shared/src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const PLUGIN_VERSION = "0.1.198";
export const PLUGIN_VERSION = "0.1.199";
3 changes: 2 additions & 1 deletion packages/ui/src/components/device-picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <section key={platform} aria-label={label} className="min-w-0 p-2">
Expand All @@ -78,7 +79,7 @@ export function DevicePicker({ workspace, children }: { workspace: DeviceWorkspa
</Fragment>;
})}
{missing.map(pane => <PopoverClose asChild key={pane.key}><Button variant="ghost" aria-pressed="true" className="w-full justify-between" onClick={() => workspace.remove(pane.key)}>{pane.last.name} · Offline<CheckIcon /></Button></PopoverClose>)}
{!items.length && !missing.length && <p className="px-2 py-3 text-xs text-muted-foreground">{emptyMessage}</p>}
{(simulatorListFailed || (!items.length && !missing.length)) && <p className="px-2 py-3 text-xs text-muted-foreground">{simulatorListFailed ? "Could not load iOS simulators." : emptyMessage}</p>}
{discoveryError && discoveryError !== emptyMessage && <details className="mt-1 px-2 text-xs text-muted-foreground"><summary className="cursor-pointer">Discovery details</summary><p className="mt-1 break-words">{discoveryError}</p></details>}
</section>;
}
Expand Down
26 changes: 26 additions & 0 deletions tooling/hosts/hosts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Loading