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
4 changes: 2 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,9 @@ When a socket drops, the server reopens it for the same device and preserves the

An iOS JPEG decode error restarts capture through `mobile_stream_reset` with the same panel session. Reset requests have a one-second cooldown. Three failed frames in a row reopen the panel stream with a delay. Late decode results release their bitmap and cannot draw on a closed panel.

iOS boot and shutdown calls run in order for each device and wait up to two minutes for the reported state. Boot skips the backend route if the device already runs or is booting. This avoids a second boot and Baguette's input repair on a running device. Shutdown closes that device's panel streams after the device stops.
iOS boot and shutdown calls run in order for each device and wait up to four minutes for the reported state. Boot skips the backend route if the device already runs or is booting. iOS uses Baguette's boot route for its Device Hub input repair. tvOS uses `simctl boot` because Baguette's HID input is unsupported there and its boot route can keep waiting for guest startup for roughly a minute after CoreSimulator reports `Booted`. Both paths wait for the reported state and then apply the device's saved resource-saving mode. Shutdown closes that device's panel streams after the device stops.

On macOS 27 with Xcode 27, the bundled Baguette can list simulators and capture frames. Device Hub can stop taps, buttons, and keys from reaching an iOS 27 device. Connections await a fresh status check. Gestures use the last completed result while one expired check refreshes in the background, so the approximately 150–200 ms command no longer delays every second of input. A new block becomes visible when that refresh completes. When blocked, it shows a notice. Ask Codex to repair input with `mobile_repair_input`. The tool runs the bundled Baguette's `heal` command. Reconnect capture afterward to use new input handles. It restarts backboardd and SpringBoard without rebooting the device. CoreSimulatorBridge can afterwards report no accessibility data for every foreground app until it restarts. UI reads that report no accessibility data restart the bridge and retry once, at most every 10 seconds per device. Relaunching Device Hub can block input again. The panel automatically repairs a confirmed Device Hub block when connecting and reconnects if input becomes blocked later. Repair closes running apps. It limits automatic attempts to once per device per minute; a repeated block or failed repair remains visible in the bottom bar. Model input alone does not trigger automatic repair. Baguette's boot route also repairs input after boot. Do not run the repair to diagnose video. See [Baguette's Device Hub notes](https://github.com/tddworks/baguette/blob/main/docs/features/device-hub/README.md).
On macOS 27 with Xcode 27, the bundled Baguette can list simulators and capture frames. Device Hub can stop taps, buttons, and keys from reaching an iOS 27 device. iOS connections await a fresh status check. tvOS connections skip this check and automatic repair because Apple TV input uses the TV remote; its Device Hub HID flag can be blocked even while the remote works. Gestures use the last completed result while one expired check refreshes in the background, so the approximately 150–200 ms command no longer delays every second of input. A new block becomes visible when that refresh completes. When blocked, it shows a notice. Ask Codex to repair input with `mobile_repair_input`. The tool runs the bundled Baguette's `heal` command. Reconnect capture afterward to use new input handles. It restarts backboardd and SpringBoard without rebooting the device. CoreSimulatorBridge can afterwards report no accessibility data for every foreground app until it restarts. UI reads that report no accessibility data restart the bridge and retry once, at most every 10 seconds per device. Relaunching Device Hub can block input again. The panel automatically repairs a confirmed Device Hub block when connecting and reconnects if input becomes blocked later. Repair closes running apps. It limits automatic attempts to once per device per minute; a repeated block or failed repair remains visible in the bottom bar. Model input alone does not trigger automatic repair. Baguette's boot route also repairs input after boot. Do not run the repair to diagnose video. See [Baguette's Device Hub notes](https://github.com/tddworks/baguette/blob/main/docs/features/device-hub/README.md).

UI resource addresses include the release version so Codex can load new HTML after an update. The original simulator and workspace addresses and the old v1 through v6 simulator addresses still return the current UI. After updating, restart Codex once if it still uses an older MCP process.

Expand Down
2 changes: 2 additions & 0 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ The App Flow runtime state-variant pass has been removed from the product, and w
Since 0.1.141, the `path` attribute on `app_flow.runtime.verify` covers a wider set of arrivals on the `runtime` side. Deterministic Fast now accepts the runtime's own readiness snapshot whenever that snapshot is complete — the target screen found and focused, its parameters matching, content present, and the dispatched navigator path focused — regardless of whether the readiness poll ended on `settled` or gave up on a timeout. Screens that never go quiet (live feeds) previously fell through to the vision judge and were counted as `judge`; they are now counted as `runtime`. The series name, unit (milliseconds), attribute names and verdict values are unchanged, so durations stay comparable across releases while the runtime/judge split shifts towards `runtime` at this release. The judge path remains for incomplete evidence. No new data is collected.
Since 0.1.172, an owned Android backend starts only after the device reports `sys.boot_completed=1`, because adb lists a device seconds before Android starts the system services scrcpy needs. `android.backend.boot_wait.samples` and `android.backend.boot_wait.duration` measure that wait in milliseconds, only when the first check found the device still booting, with a fixed `outcome` of `booted` or `timeout` (after 120 s). They use the simulator surface and Android device platform, send no serials, device names or adb output, and honor telemetry opt-out. The wait ends before process spawn, so `android.backend.startup.duration` keeps excluding device boot.

`simulator.boot.duration` measures the simulator boot request and the subsequent reported-state wait as separate millisecond distributions (`phase=request|state_wait`, `runtime=ios|tvos`). It covers the active Baguette request on iOS and the direct CoreSimulator request on tvOS. Resource optimization remains measured by `resource_saving.duration` after the state wait. The series has simulator surface and iOS platform attribution, with no device identifiers or paths, and honors telemetry opt-out.

Android panel stream-opening calls allow 180 s for the boot wait, backend startup and request overhead. Existing UI connection and first-frame timings continue to measure the whole connection attempt.

Since 0.1.140, `android.emulator.adb_reconnects` counts adb transport reconnects for emulators that stay unauthorized, with a fixed `trigger` (`boot` while waiting for an AVD, `selection` for an already running emulator). It uses the simulator surface and Android emulator context and sends no serials, AVD names or adb output. Existing Android startup diagnostics and MCP tool errors cover the boot outcome.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"public-release": "node tooling/public-release.mjs",
"vendor:baguette": "node tooling/vendor-baguette.mjs",
"vendor:resource-saving": "node tooling/vendor-resource-saving.mjs",
"vendor:agent-device": "npm ci --prefix packages/runtimes/agent-device --ignore-scripts --no-audit --no-fund",
"vendor:agent-device": "npm ci --prefix packages/runtimes/agent-device --ignore-scripts --no-audit --no-fund && node tooling/patch-agent-device.mjs",
"vendor:e2e": "node tooling/vendor-e2e.mjs",
"catalog:agent-device": "node tooling/agent-device-catalog.mjs",
"rebuild:baguette": "node tooling/rebuild-baguette.mjs",
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/agent-device-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ export function compactAgentDeviceTool(tool: Tool): Tool {
}

// Commands that Mobile Dev's own tools cover (logs, performance), or that need a remote
// daemon, a TV or a browser.
const omitted = new Set(["logs", "perf", "install-from-source", "artifacts", "viewport", "tv-remote", "audio", "hover"]);
// daemon or a browser. The TV remote also drives the mirrored tvOS panel.
const omitted = new Set(["logs", "perf", "install-from-source", "artifacts", "viewport", "audio", "hover"]);

type Annotations = NonNullable<Tool["annotations"]>;
const read: Annotations = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };
Expand All @@ -71,7 +71,7 @@ const commandAnnotations: Record<string, Annotations> = {
alert: write, "app-switcher": write, back: write, boot: write, click: write, close: write, fill: write,
find: write, focus: write, fold: write, gesture: write, "hardware-button": write, home: write, keyboard: write, longpress: write, open: write,
orientation: write, press: write, push: write, "react-native": write, scroll: write, settings: write,
shutdown: write, swipe: write, type: write,
shutdown: write, swipe: write, type: write, "tv-remote": write,
"action-button": destructive, batch: destructive, clipboard: destructive, debug: destructive, diff: destructive, install: destructive,
record: destructive, reinstall: destructive, replay: destructive, session: destructive, test: destructive,
telephony: destructive, trace: destructive, "trigger-app-event": destructive, uninstall: destructive,
Expand Down
56 changes: 52 additions & 4 deletions packages/core/src/baguette.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,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, recordBaguetteFrameworkRestart } from "./telemetry.ts";
import { captureServerError, recordAccessibilityBridgeRestart, recordBaguetteFrameworkRestart, recordSimulatorBoot } from "./telemetry.ts";
import type { ResourceSaving } from "./resource-saving.ts";

type DescribedUi = { tree?: { label?: unknown } };
Expand Down Expand Up @@ -72,6 +72,17 @@ async function kickstartAccessibilityBridge(udid: string, signal: AbortSignal):
});
}

async function bootTvSimulator(udid: string, signal: AbortSignal): Promise<void> {
try {
await promisify(execFile)("/usr/bin/xcrun", ["simctl", "boot", udid], {
timeout: 15000, maxBuffer: 64 * 1024, encoding: "utf8", signal,
});
} catch (error) {
// Another client may have started the same simulator after our initial list.
if (!/current state: (?:Booted|Booting)|already booted|already booting/i.test(String((error as { stderr?: string }).stderr ?? error))) throw error;
}
}

export const definitionSchema = z.object({
identity: z.object({ udid: udidSchema, name: z.string(), model: z.string() }),
screen: z.object({
Expand All @@ -98,14 +109,16 @@ export class Baguette {
private readonly kickstartBridge: (udid: string, signal: AbortSignal) => Promise<void>;
private readonly bridgeRestarts = new Map<string, number>();
private readonly launchBackend: (host: string, port: string, signal: AbortSignal) => Promise<ChildProcess>;
private readonly bootTv: (udid: string, signal: AbortSignal) => Promise<void>;
private readonly startFailures = new FailureEpisodes();

constructor(baseUrl?: string, kickstartBridge = kickstartAccessibilityBridge, launchBackend = launchBundledBaguette, frameworkPath = CORE_SIMULATOR_BINARY) {
constructor(baseUrl?: string, kickstartBridge = kickstartAccessibilityBridge, launchBackend = launchBundledBaguette, frameworkPath = CORE_SIMULATOR_BINARY, bootTv = bootTvSimulator) {
this.embedded = baseUrl == null;
this.baseUrl = parseBaseUrl(baseUrl ?? "http://127.0.0.1:0");
this.kickstartBridge = kickstartBridge;
this.launchBackend = launchBackend;
this.frameworkPath = frameworkPath;
this.bootTv = bootTv;
}

async json(path: string, options: RequestInit = {}, timeout = 10000): Promise<unknown> {
Expand Down Expand Up @@ -366,12 +379,16 @@ export class Baguette {
}

async definition(udid: string) {
await this.device(udid, true);
const listed = await this.device(udid, true);
try {
const payload = await this.json(`/simulators/${udid}/definition.json`);
return definitionSchema.parse(payload);
} catch (error) {
const diagnostic = getDefinitionDiagnostic(error);
if (listed.runtime.startsWith("tvOS ") && diagnostic?.stage === "profile_chrome_identifier"
&& diagnostic.failure === "missing") {
return this.tvosDefinition(udid, listed.name);
}
if (diagnostic !== undefined) {
diagnostic.deviceBefore = "Booted";
const status = await this.status();
Expand All @@ -384,6 +401,24 @@ export class Baguette {
}
}

private async tvosDefinition(udid: string, name: string) {
const path = `/simulators/${udid}/screenshot.png`;
const response = await fetch(new URL(path, this.baseUrl), {
redirect: "error", signal: AbortSignal.any([this.lifecycle.signal, AbortSignal.timeout(10000)]),
});
if (!response.ok || response.headers.get("content-type")?.split(";", 1)[0] !== "image/png") {
throw new Error(`Baguette could not capture the tvOS simulator screen (HTTP ${response.status}).`);
}
const bytes = Buffer.from(await response.arrayBuffer());
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
if (bytes.length < 24 || bytes.length > 20 * 1024 * 1024 || !bytes.subarray(0, 8).equals(signature)
|| bytes.toString("ascii", 12, 16) !== "IHDR") {
throw new Error("Baguette returned an invalid tvOS simulator screenshot.");
}
const width = bytes.readUInt32BE(16), height = bytes.readUInt32BE(20);
return definitionSchema.parse({ identity: { udid, name, model: name }, screen: { rect: { width, height } } });
}

async changeDeviceState(udid: string, action: "boot" | "shutdown", timeout = 240000): Promise<Status> {
udidSchema.parse(udid);
const previous = this.deviceChanges.get(udid);
Expand All @@ -396,7 +431,19 @@ export class Baguette {
const signal = AbortSignal.any([this.lifecycle.signal, AbortSignal.timeout(timeout)]);
try {
const inProgress = device.state === (action === "boot" ? "Booting" : "ShuttingDown");
if (!inProgress) await this.json(`/simulators/${udid}/${action}`, { method: "POST", signal }, timeout);
if (!inProgress) {
const requestStarted = performance.now();
const tvBoot = action === "boot" && device.runtime.startsWith("tvOS ");
try {
// Baguette's boot route waits for guest startup and repairs its HID surface. tvOS
// uses the TV remote instead, so its long post-Booted wait and repair are unnecessary.
if (tvBoot) await this.bootTv(udid, signal);
else await this.json(`/simulators/${udid}/${action}`, { method: "POST", signal }, timeout);
} finally {
if (action === "boot") recordSimulatorBoot("request", tvBoot ? "tvos" : "ios", performance.now() - requestStarted);
}
}
const readyStarted = performance.now();
while (true) {
signal.throwIfAborted();
const status = await this.status(signal);
Expand All @@ -405,6 +452,7 @@ export class Baguette {
const current = status.devices.find(item => item.udid === udid);
if (!current) throw new SimulatorUnavailableError("This simulator is no longer available. Refresh the device list.");
if (current.state === expected) {
if (action === "boot") recordSimulatorBoot("state_wait", device.runtime.startsWith("tvOS ") ? "tvos" : "ios", performance.now() - readyStarted);
const target = { platform: "ios" as const, id: udid, key: udid, state: current.state };
if (action === "boot") {
await this.resourceSaving?.apply(target, signal);
Expand Down
8 changes: 6 additions & 2 deletions packages/core/src/panel-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,10 @@ function registerPanel(server: McpServer, { android, cpu, fps, drivers, page, sh

type PanelInputStatus = { inputStatus: InputStatus; inputRepairMessage?: string };
const automaticRepairs = new Map<string, { attemptedAt: number; pending: Promise<PanelInputStatus> }>();
async function panelInputStatus(udid: string): Promise<PanelInputStatus> {
async function panelInputStatus(udid: string, runtime: string): Promise<PanelInputStatus> {
// Apple TV input uses the remote, not Device Hub's simulated HID surface. On tvOS the
// Device Hub flag can be set even when the remote works, and repair delays first video.
if (runtime.startsWith("tvOS ")) return { inputStatus: { state: "ready" } };
const inputStatus = await simulatorInput.status(udid, { fresh: true });
if (inputStatus.state !== "blocked") return { inputStatus };
const previous = automaticRepairs.get(udid);
Expand Down Expand Up @@ -372,9 +375,10 @@ function registerPanel(server: McpServer, { android, cpu, fps, drivers, page, sh
_meta: { ui: { resourceUri: APP_URI, visibility: ["app"] } },
}, guarded(async ({ udid, fps }: { udid: string; fps: number }, context) => {
context.signal.throwIfAborted();
const device = await baguette.device(udid, true);
const definition = await baguette.definition(udid);
const bezel = await readBezel(baguette, udid, definition.screen);
const { inputStatus, inputRepairMessage } = await panelInputStatus(udid);
const { inputStatus, inputRepairMessage } = await panelInputStatus(udid, device.runtime);
const sessionId = await openRequestSession(context.signal, () => streams.open(udid, fps), id => streams.closeSession(id));
return {
...result({ udid, definition, fps, inputStatus, ...(inputRepairMessage ? { inputRepairMessage } : {}) }, `Stream ready for ${definition.identity.name}.`),
Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/stream-sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { Baguette } from "./baguette.ts";
type Frame = { sequence: number; bytes: Buffer; receivedAt: number; data?: string };
type Session = {
udid: string;
runtime?: string;
fps: number;
socket?: WebSocket;
connecting?: Promise<void>;
Expand Down Expand Up @@ -71,7 +72,8 @@ export class StreamSessions {
}

private async connect(session: Session) {
await this.baguette.device(session.udid, true);
const device = await this.baguette.device(session.udid, true);
session.runtime = device.runtime;
if (session.closed || this.disposed) return;
const target = new URL(`/simulators/${session.udid}/stream?format=mjpeg`, this.baguette.baseUrl);
target.protocol = "ws:";
Expand Down Expand Up @@ -227,6 +229,9 @@ export class StreamSessions {
if (session.socket?.readyState !== WebSocket.OPEN || session.connecting || !session.frame) throw new ExpectedOperationError("device_unavailable", "The simulator stream is reconnecting.");
const socket = session.socket;
const validated = messages.map(message => streamMessageSchema.parse(message));
if (session.runtime?.startsWith("tvOS ")) {
throw new ExpectedOperationError("unsupported_platform", "Use the TV remote for Apple TV input. Baguette HID input can crash the tvOS simulator.");
}
const sent = session.input.then(() => {
this.session(id);
if (session.socket !== socket || socket.readyState !== WebSocket.OPEN || session.connecting || !session.frame) throw new ExpectedOperationError("device_unavailable", "The simulator stream is reconnecting.");
Expand Down
Loading
Loading