diff --git a/docs/architecture.md b/docs/architecture.md index c0b80e68c..65dc5cd38 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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. diff --git a/docs/telemetry.md b/docs/telemetry.md index 86eabc820..ba592b3ae 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -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. diff --git a/package.json b/package.json index 9d2eb9820..a14689aa6 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/packages/core/src/agent-device-catalog.ts b/packages/core/src/agent-device-catalog.ts index f383d638b..a5e59a9f1 100644 --- a/packages/core/src/agent-device-catalog.ts +++ b/packages/core/src/agent-device-catalog.ts @@ -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; const read: Annotations = { readOnlyHint: true, destructiveHint: false, openWorldHint: false }; @@ -71,7 +71,7 @@ const commandAnnotations: Record = { 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, diff --git a/packages/core/src/baguette.ts b/packages/core/src/baguette.ts index 6211e845c..2ae62f091 100644 --- a/packages/core/src/baguette.ts +++ b/packages/core/src/baguette.ts @@ -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 } }; @@ -72,6 +72,17 @@ async function kickstartAccessibilityBridge(udid: string, signal: AbortSignal): }); } +async function bootTvSimulator(udid: string, signal: AbortSignal): Promise { + 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({ @@ -98,14 +109,16 @@ export class Baguette { private readonly kickstartBridge: (udid: string, signal: AbortSignal) => Promise; private readonly bridgeRestarts = new Map(); private readonly launchBackend: (host: string, port: string, signal: AbortSignal) => Promise; + private readonly bootTv: (udid: string, signal: AbortSignal) => Promise; 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 { @@ -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(); @@ -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 { udidSchema.parse(udid); const previous = this.deviceChanges.get(udid); @@ -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); @@ -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); diff --git a/packages/core/src/panel-tools.ts b/packages/core/src/panel-tools.ts index 19aaac354..6e30282f8 100644 --- a/packages/core/src/panel-tools.ts +++ b/packages/core/src/panel-tools.ts @@ -162,7 +162,10 @@ function registerPanel(server: McpServer, { android, cpu, fps, drivers, page, sh type PanelInputStatus = { inputStatus: InputStatus; inputRepairMessage?: string }; const automaticRepairs = new Map }>(); - async function panelInputStatus(udid: string): Promise { + async function panelInputStatus(udid: string, runtime: string): Promise { + // 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); @@ -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}.`), diff --git a/packages/core/src/stream-sessions.ts b/packages/core/src/stream-sessions.ts index 59fd37784..379c47e9a 100644 --- a/packages/core/src/stream-sessions.ts +++ b/packages/core/src/stream-sessions.ts @@ -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; @@ -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:"; @@ -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."); diff --git a/packages/core/src/telemetry.ts b/packages/core/src/telemetry.ts index 44711f1ce..0526c3a9a 100644 --- a/packages/core/src/telemetry.ts +++ b/packages/core/src/telemetry.ts @@ -21,6 +21,13 @@ export function recordResourceSaving(platform: "ios" | "android", enabled: boole Sentry.metrics.distribution("resource_saving.duration", duration, { unit: "millisecond", attributes }); } +/** Separates simulator boot request latency from the subsequent reported-state wait. */ +export function recordSimulatorBoot(phase: "request" | "state_wait", runtime: "ios" | "tvos", duration: number) { + if (process.env.MOBILE_DEV_TELEMETRY === "off") return; + const attributes = { component: "server", surface: "simulator", device_platform: "ios", device_kind: "simulator", runtime, phase }; + Sentry.metrics.distribution("simulator.boot.duration", duration, { unit: "millisecond", attributes }); +} + export function recordBrowserPanelSessions(active: number) { if (process.env.MOBILE_DEV_TELEMETRY === "off") return; Sentry.metrics.gauge("browser_panel.sessions", active, { attributes: { component: "server" } }); diff --git a/packages/core/test/agent-device-catalog.test.ts b/packages/core/test/agent-device-catalog.test.ts index 532efc30c..02054e330 100644 --- a/packages/core/test/agent-device-catalog.test.ts +++ b/packages/core/test/agent-device-catalog.test.ts @@ -78,7 +78,8 @@ test("the committed catalog is the pinned runtime's commands that Mobile Dev ser const committed = JSON.parse(await readFile(agentDeviceCatalogFile, "utf8")); assert.deepEqual(committed, JSON.parse(JSON.stringify(agentDeviceCatalog(upstreamCatalog.tools)))); const names = committed.map((entry: { name: string }) => entry.name); - for (const name of ["logs", "perf", "install-from-source", "artifacts", "viewport", "tv-remote", "audio", "hover"]) assert.equal(names.includes(name), false, name); + for (const name of ["logs", "perf", "install-from-source", "artifacts", "viewport", "audio", "hover"]) assert.equal(names.includes(name), false, name); + assert.ok(names.includes("tv-remote")); for (const name of ["action-button", "fold", "hardware-button", "telephony", "uninstall", "help"]) { const included = names.includes(name); assert.ok(included, name); diff --git a/packages/core/test/ios-lifecycle.test.ts b/packages/core/test/ios-lifecycle.test.ts index 5a8d66dde..754de2ded 100644 --- a/packages/core/test/ios-lifecycle.test.ts +++ b/packages/core/test/ios-lifecycle.test.ts @@ -57,6 +57,30 @@ test("a simulator already booting finishes without a second boot request", async assert.equal(fake.requests.some(request => request.path.endsWith("/boot")), false); }); +test("tvOS uses the quick CoreSimulator boot and still waits for Booted", async t => { + const fake = await fakeBaguette(); + fake.setState("Shutdown"); + const booted: string[] = []; + const baguette = new Baguette(fake.url, undefined, undefined, undefined, async udid => { + booted.push(udid); + fake.setState("Booting"); + }); + let optimized = false; + baguette.resourceSaving = { async apply() { optimized = true; }, forget() {} } as unknown as NonNullable; + t.after(async () => { baguette.dispose(); await fake.close(); }); + fake.setRuntime("tvOS 27.0"); + let finished = false; + const pending = baguette.changeDeviceState(UDID, "boot").then(status => { finished = true; return status; }); + await waitFor(() => booted.length === 1); + assert.equal(finished, false); + assert.equal(fake.requests.some(request => request.path.endsWith("/boot")), false); + fake.setState("Booted"); + const status = await pending; + assert.equal(booted[0], UDID); + assert.equal(optimized, true); + assert.equal(status.devices.find(device => device.udid === UDID)?.state, "Booted"); +}); + test("a boot failure does not prevent a later boot", async t => { const fake = await fakeBaguette(); fake.setState("Shutdown"); fake.setLifecycleFailure(true); diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index 3a382dcd0..7a4a4bc96 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -460,6 +460,31 @@ test("Device Hub blockage repairs automatically, limits repeated repairs, and pe assert.equal(wrongSession._meta?.inputBlocked, undefined); }); +test("tvOS stream skips the Device Hub input check and repair", async t => { + const fake = await fakeBaguette(); + fake.setRuntime("tvOS 27.0"); + let checks = 0; + let repairs = 0; + const input = { + async status() { checks++; return { state: "blocked" as const }; }, + async repair() { repairs++; return { state: "ready" as const }; }, + }; + const plugin = await createTestPlugin("Mobile Dev", { panel: createPanel({ baguette: new Baguette(fake.url), simulatorInput: input }) }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "tvos-input-test", version: "1" }); + t.after(async () => { await client.close(); await plugin.close(); await fake.close(); }); + await plugin.server.connect(serverTransport); + await client.connect(clientTransport); + + const session = await client.callTool({ name: "mobile_stream_session", arguments: { udid: UDID } }); + assert.equal(session.isError, undefined); + assert.deepEqual(session.structuredContent?.inputStatus, { state: "ready" }); + assert.equal(session.structuredContent?.inputRepairMessage, undefined); + assert.equal((await client.readResource({ uri: session._meta?.frameUri as string })).contents[0].mimeType, "image/jpeg"); + assert.equal(checks, 0); + assert.equal(repairs, 0); +}); + test("only a loopback HTTP origin can become a backend target", () => { for (const value of ["https://127.0.0.1", "http://example.com", "http://user:pass@localhost", "http://localhost/path", "http://localhost?url=x"]) { assert.throws(() => parseBaseUrl(value)); diff --git a/packages/core/test/stream.test.ts b/packages/core/test/stream.test.ts index 8e4f6ebd6..100dbb1fa 100644 --- a/packages/core/test/stream.test.ts +++ b/packages/core/test/stream.test.ts @@ -28,6 +28,23 @@ test("panel sessions carry frames and validated input without a browser socket", await assert.rejects(frame(streams, id, 0), /expired or closed/); }); +test("tvOS stream rejects all Baguette input before it reaches the simulator", async t => { + const fake = await fakeBaguette(); + class TvBaguette extends Baguette { + async device(udid: string, mustBeBooted = false) { + return { ...await super.device(udid, mustBeBooted), runtime: "tvOS 27.0" }; + } + } + const streams = new StreamSessions(new TvBaguette(fake.url)); + t.after(async () => { streams.close(); await fake.close(); }); + const id = await streams.open(UDID, 30); + await frame(streams, id, 0); + assert.throws(() => streams.input(id, [{ type: "touch1-down", x: 120, y: 300, ...SCREEN }]), /Use the TV remote/); + assert.throws(() => streams.input(id, [{ type: "key", code: "ArrowDown" }]), /Use the TV remote/); + assert.throws(() => streams.input(id, [{ type: "button", button: "home" }]), /Use the TV remote/); + assert.equal(fake.inputs.some(message => ["touch1-down", "key", "button"].includes((message as { type?: string }).type ?? "")), false); +}); + test("unknown panel sessions cannot read frames or send input", async t => { const fake = await fakeBaguette(); const streams = new StreamSessions(new Baguette(fake.url)); diff --git a/packages/core/test/telemetry.test.ts b/packages/core/test/telemetry.test.ts index b0db64de7..3caca824d 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, recordBaguetteFrameworkRestart, recordResourceSaving } from "../src/telemetry.ts"; +import { captureServerError, installTracePropagation, instrumentMcpServer, IOSLogProcessingTelemetry, recordAndroidBackendStartup, recordAndroidBootWait, recordIosMirrorSharing, recordIosHitchOperation, recordBrowserPanelContext, recordBrowserPanelSessions, recordPanelRuntime, recordBaguetteDiscoveryTime, recordBaguetteFrameworkRestart, recordResourceSaving, recordSimulatorBoot } 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"; @@ -276,6 +276,30 @@ test("Android backend startup metrics retain product attribution and honor opt-o assert.equal(afterOptOut, sent); }); +test("simulator boot phases use bounded runtime attribution and honor opt-out", async t => { + const envelopes: Envelope[] = []; + Sentry.init({ + dsn: "https://public@example.com/1", defaultIntegrations: false, beforeSendMetric: scrubMetric, + transport: () => ({ async send(envelope) { envelopes.push(envelope); return { statusCode: 200 }; }, async flush() { return true; } }), + }); + const previous = process.env.MOBILE_DEV_TELEMETRY; + delete process.env.MOBILE_DEV_TELEMETRY; + t.after(async () => { + if (previous === undefined) delete process.env.MOBILE_DEV_TELEMETRY; + else process.env.MOBILE_DEV_TELEMETRY = previous; + await Sentry.close(); + }); + recordSimulatorBoot("request", "tvos", 120); + recordSimulatorBoot("state_wait", "tvos", 350); + await Sentry.flush(); + const sent = JSON.stringify(envelopes); + for (const fragment of ["simulator.boot.duration", "millisecond", '"surface":{"value":"simulator"', '"device_platform":{"value":"ios"', '"runtime":{"value":"tvos"', '"phase":{"value":"request"', '"phase":{"value":"state_wait"']) contains(sent, fragment); + process.env.MOBILE_DEV_TELEMETRY = "off"; + recordSimulatorBoot("request", "ios", 999); + await Sentry.flush(); + assert.equal(JSON.stringify(envelopes), sent); +}); + test("plugin update metrics measure plugin work without device context and honor opt-out", async t => { const envelopes: Envelope[] = []; Sentry.init({ diff --git a/packages/core/test/tvos-definition.test.ts b/packages/core/test/tvos-definition.test.ts new file mode 100644 index 000000000..19c24a6fc --- /dev/null +++ b/packages/core/test/tvos-definition.test.ts @@ -0,0 +1,38 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { once } from "node:events"; +import { Baguette } from "../src/baguette.ts"; +import { PNG, UDID } from "../../test-support/fixtures.ts"; + +test("tvOS simulators use screenshot geometry when Baguette has no chrome identifier", async t => { + const requests: string[] = []; + const server = createServer((request, response) => { + const path = request.url ?? ""; + requests.push(path); + if (path === "/simulators.json") { + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify({ running: [{ udid: UDID, name: "Apple TV 4K (3rd generation)", + state: "Booted", runtime: "tvOS 27.0" }], available: [] })); + } else if (path.endsWith("/definition.json")) { + response.writeHead(404, { "Content-Type": "application/json" }); + response.end(JSON.stringify({ definition_diagnostic: { + schema: "1", stage: "profile_chrome_identifier", failure: "missing", + } })); + } else if (path.endsWith("/screenshot.png")) { + response.writeHead(200, { "Content-Type": "image/png" }); + response.end(PNG); + } else response.writeHead(404).end(); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + assert.ok(address && typeof address === "object"); + const baguette = new Baguette(`http://127.0.0.1:${address.port}`); + t.after(() => { baguette.dispose(); server.closeAllConnections(); server.close(); }); + + const definition = await baguette.definition(UDID); + assert.deepEqual(definition.identity, { udid: UDID, name: "Apple TV 4K (3rd generation)", model: "Apple TV 4K (3rd generation)" }); + assert.deepEqual(definition.screen.rect, { width: 1, height: 1 }); + assert.equal(requests.filter(path => path.endsWith("/screenshot.png")).length, 1); +}); diff --git a/packages/runtimes/agent-device/tools.json b/packages/runtimes/agent-device/tools.json index 1f9f65f1e..33eec54ac 100644 --- a/packages/runtimes/agent-device/tools.json +++ b/packages/runtimes/agent-device/tools.json @@ -3287,6 +3287,84 @@ "openWorldHint": false } }, + { + "name": "tv-remote", + "description": "Press or long-press a TV remote button on Android TV, tvOS, or Vega OS. Android TV also supports volume, power, media, channel, guide, captions, input, color keys, and android-keycode:N. tvOS and Vega OS support up, down, left, right, select, menu, home, and back. Phones and WebDriver sessions are unsupported. The aliases ok, center, and enter map to select. Times out after 90s.", + "inputSchema": { + "type": "object", + "properties": { + "session": { + "type": "string", + "minLength": 1, + "pattern": "\\S", + "description": "Named session opened with open." + }, + "button": { + "description": "TV remote button. Android TV also accepts android-keycode: with n from 1 to 2147483647.", + "oneOf": [ + { + "type": "string", + "enum": [ + "up", + "down", + "left", + "right", + "select", + "menu", + "home", + "back", + "volume-up", + "volume-down", + "mute", + "power", + "sleep", + "wake", + "media-play-pause", + "media-next", + "media-previous", + "media-rewind", + "media-fast-forward", + "channel-up", + "channel-down", + "last-channel", + "guide", + "info", + "captions", + "tv-input", + "color-red", + "color-green", + "color-yellow", + "color-blue" + ] + }, + { + "type": "string", + "pattern": "^android-keycode:(?:[1-9][0-9]{0,8}|1[0-9]{9}|20[0-9]{8}|21[0-3][0-9]{7}|214[0-6][0-9]{6}|2147[0-3][0-9]{5}|21474[0-7][0-9]{4}|214748[0-2][0-9]{3}|2147483[0-5][0-9]{2}|21474836[0-3][0-9]|214748364[0-7])(?![\\s\\S])" + } + ] + }, + "durationMs": { + "type": "integer", + "description": "Press duration in milliseconds. tvOS and Vega OS use the exact hold duration; Android TV maps any positive value to an ADB longpress (longpress).", + "minimum": 0 + }, + "noRecord": { + "type": "boolean", + "description": "Do not record this action." + } + }, + "required": [ + "button", + "session" + ], + "additionalProperties": false + }, + "annotations": { + "readOnlyHint": false, + "destructiveHint": false, + "openWorldHint": false + } + }, { "name": "type", "description": "Append text to the currently focused input. Use fill when the existing field value should be replaced, and focus first when no input is active. Times out after 90s.", diff --git a/packages/test-support/fixtures.ts b/packages/test-support/fixtures.ts index 0959084d2..8382cf4a1 100644 --- a/packages/test-support/fixtures.ts +++ b/packages/test-support/fixtures.ts @@ -37,6 +37,7 @@ export function fakeSimulatorInput() { export async function fakeBaguette() { let state = "Booted"; + let runtime = "iOS 26.0"; let sendFrames = true; let lifecycleState: string | undefined; let lifecycleFails = false; @@ -49,8 +50,8 @@ export async function fakeBaguette() { response.setHeader("Content-Type", "application/json"); if (path === "/simulators.json") { response.end(JSON.stringify({ - running: state === "Booted" ? [{ udid: UDID, name: "iPhone 17", state, runtime: "iOS 26.0" }] : [], - available: [{ udid: UDID, name: "iPhone 17", state, runtime: "iOS 26.0" }, { udid: OTHER_UDID, name: "iPad", state: "Shutdown", runtime: "iOS 26.0" }], + running: state === "Booted" ? [{ udid: UDID, name: "iPhone 17", state, runtime }] : [], + available: [{ udid: UDID, name: "iPhone 17", state, runtime }, { udid: OTHER_UDID, name: "iPad", state: "Shutdown", runtime: "iOS 26.0" }], })); } else if (path.endsWith("/interface.json") || path.endsWith("/interface")) { if (request.method === "POST") { let body = ""; for await (const chunk of request) body += chunk; Object.assign(settings, JSON.parse(body)); } @@ -87,6 +88,7 @@ export async function fakeBaguette() { return { url: `http://127.0.0.1:${address.port}`, inputs, requests, websocket, setState(next: string) { state = next; }, + setRuntime(next: string) { runtime = next; }, setFrames(enabled: boolean) { sendFrames = enabled; }, setLifecycleState(next?: string) { lifecycleState = next; }, setLifecycleFailure(enabled: boolean) { lifecycleFails = enabled; }, diff --git a/packages/ui/src/components/simulator-view.tsx b/packages/ui/src/components/simulator-view.tsx index ec58aa400..155366b2a 100644 --- a/packages/ui/src/components/simulator-view.tsx +++ b/packages/ui/src/components/simulator-view.tsx @@ -1,4 +1,4 @@ -import { CameraIcon, HouseIcon, CopyIcon, PowerIcon, SmartphoneIcon, type LucideIcon } from "lucide-react"; +import { ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon, CameraIcon, CheckIcon, HouseIcon, LoaderCircleIcon, CopyIcon, PowerIcon, SmartphoneIcon, Undo2Icon, type LucideIcon } from "lucide-react"; import { memo, useLayoutEffect, useRef, useState } from "react"; import { Button } from "./ui/button"; import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "./ui/empty"; @@ -13,6 +13,14 @@ const deviceButtons: { action: string; icon: LucideIcon; label: string }[] = [ { action: "home", icon: HouseIcon, label: "Home" }, { action: "app-switcher", icon: CopyIcon, label: "App switcher" }, ]; +const tvButtons: { code: string; icon: LucideIcon; label: string }[] = [ + { code: "ArrowLeft", icon: ArrowLeftIcon, label: "TV left" }, + { code: "ArrowUp", icon: ArrowUpIcon, label: "TV up" }, + { code: "ArrowDown", icon: ArrowDownIcon, label: "TV down" }, + { code: "ArrowRight", icon: ArrowRightIcon, label: "TV right" }, + { code: "Enter", icon: CheckIcon, label: "TV select" }, + { code: "Escape", icon: Undo2Icon, label: "TV menu" }, +]; // The stream controller owns the canvas after mount; keep this subtree stable so log batches never reset a live device. export const SimulatorView = memo(function SimulatorView({ workspace, paneKey, deviceId, platform, name, active }: { workspace: DeviceWorkspace; paneKey: number; deviceId?: string; platform: Platform; name: string; active: boolean }) { @@ -24,7 +32,8 @@ export const SimulatorView = memo(function SimulatorView({ workspace, paneKey, d return
- {label} + {label} + {tvButtons.map(({ code, icon: Icon, label }) => )} {deviceButtons.map(({ action, icon: Icon, label }) => )} @@ -37,6 +46,7 @@ export const SimulatorView = memo(function SimulatorView({ workspace, paneKey, d + diff --git a/packages/ui/src/simulator-panel.ts b/packages/ui/src/simulator-panel.ts index fe501d92a..713747e15 100644 --- a/packages/ui/src/simulator-panel.ts +++ b/packages/ui/src/simulator-panel.ts @@ -41,6 +41,7 @@ export function createSimulatorPanel( inventory: DeviceInventory, panelContext: PanelContext, activate: () => void, + options: { tvRemoteWarmupDelayMs?: number } = {}, ) { function element(id: string): T { return root.querySelector(`[data-element="${id}"]`) as T; } const platform = inventory.platform; @@ -61,6 +62,12 @@ export function createSimulatorPanel( bezelImage.addEventListener("error", () => { setBezel(); fitScreen(); }); const screenshotButton = element("screenshot"); let selected: SimulatorDevice | undefined; + const tvRemoteSession = `mobile-dev-tv-${crypto.randomUUID()}`; + let tvRemoteDeviceId: string | undefined; + let tvRemoteQueue = Promise.resolve(); + // True from the first TV frame until the remote session is open (or failed), and during a retry open. + let tvRemotePreparing = false; + let tvWarmupTimer: ReturnType | undefined; type PanelStream = { id: string; frameUri: string; epoch: number; platform: "ios" | "android"; physicalIos: boolean; generation?: number; controller: AbortController; input?: StreamInput; reader?: FrameStream; closing?: Promise }; const reconnect = new ReconnectLoop(); let stream: PanelStream | undefined; @@ -116,14 +123,27 @@ export function createSimulatorPanel( return physicalIos ? selected?.state === "connected" : selected?.state === "Booted"; } + function isTvOS() { return selected?.runtime.startsWith("tvOS ") === true; } + function deviceButtons() { const state = annotations.getSnapshot(); const unsupported = selected?.kind === "physical" && selected.platform === "ios"; const active = ready && stream != null && !unsupported && !stream.physicalIos && !inputBlocked && !busy && toolsAvailable && !state.selecting && !state.draft; + const tv = isTvOS(); + element("tv-remote-status").hidden = !(tv && tvRemotePreparing && !unsupported); + const label = element("platform-label"); + if (label) label.textContent = tv ? "tvOS" : platform === "ios" ? "iOS" : "Android"; + canvas.ariaLabel = tv ? "tvOS screen. Use the remote controls or arrow keys, Enter, and Escape to interact." : `${platform === "ios" ? "iOS" : "Android"} screen. Click or drag to interact. Focus to type.`; + root.querySelectorAll("[data-tv-key]").forEach(button => { + button.hidden = !tv; + button.classList?.toggle("hidden", !tv); + button.disabled = !tv || !active || tvRemotePreparing; + }); const buttons = root.querySelectorAll("[data-button]"); buttons.forEach(button => { + button.hidden = tv && button.dataset.button === "app-switcher"; const label = button.dataset.button === "home" ? "Home" : "App switcher"; - button.disabled = !active; + button.disabled = !active || button.hidden || tv && tvRemotePreparing; button.dataset.unsupported = unsupported ? "true" : "false"; button.title = unsupported ? `${label} is unavailable on physical iOS devices` : label; }); @@ -131,6 +151,8 @@ export function createSimulatorPanel( function send(message: StreamMessage) { if (!ready || !stream || inputBlocked) return; + // Baguette's simulated HID input can abort tvOS backboardd, including keyboard keys. + if (isTvOS()) return; // Every input can change the screen, so a tree read before it no longer describes what the // next tap lands on. Typing and the hardware buttons go through here too, not just touches. if (isRecordingSelected()) testRecorder.invalidate(); @@ -143,6 +165,74 @@ export function createSimulatorPanel( stream.input?.send(message); } + // Opens the agent-device session the TV remote drives. Runs on tvRemoteQueue. Returns false when the + // device changed or the panel closed while opening, after releasing the session. + async function ensureTvRemoteSession(deviceId: string): Promise { + if (tvRemoteDeviceId !== deviceId) { + const setupStarted = performance.now(); + if (tvRemoteDeviceId) await call("device_close", { session: tvRemoteSession }, { timeout: 30000 }); + tvRemoteDeviceId = undefined; + await call("device_open", { platform: "ios", udid: deviceId, session: tvRemoteSession }, { timeout: 90000 }); + tvRemoteDeviceId = deviceId; + recordUiTiming("ui.tv_remote.setup", performance.now() - setupStarted); + } + if (selected?.udid === deviceId && !disposed) return true; + await call("device_close", { session: tvRemoteSession }, { timeout: 30000 }).catch(() => {}); + tvRemoteDeviceId = undefined; + return false; + } + + function cancelTvWarmup() { + if (tvWarmupTimer !== undefined) clearTimeout(tvWarmupTimer); + tvWarmupTimer = undefined; + if (tvRemotePreparing) { tvRemotePreparing = false; deviceButtons(); } + } + + // The first open starts (and after a runner change, builds) the agent-device runner, which can take + // seconds to minutes and competes with a simulator that is still settling after boot. Start it a few + // seconds after the first TV frame, with the remote locked and a spinner shown, so the first press is + // instant. A failure stays quiet and unlocks the remote: the next press retries and reports it. + function warmTvRemote() { + const deviceId = selected?.udid; + if (!deviceId || !isTvOS() || disposed || tvRemoteDeviceId === deviceId || tvWarmupTimer !== undefined || testRecorder.isAgentRecording(deviceId)) return; + tvRemotePreparing = true; + tvWarmupTimer = setTimeout(() => { + tvWarmupTimer = undefined; + tvRemoteQueue = tvRemoteQueue.catch(() => {}).then(async () => { + try { + if (await ensureTvRemoteSession(deviceId)) { + // device_open does not start the XCUITest runner; the first runner command does, and costs + // seconds (measured ~2-6s, versus ~0.34s afterwards). A read-only alert lookup pays that + // here, behind the spinner, without sending a remote press. "No alert" is the expected answer. + await call("device_alert", { session: tvRemoteSession, action: "get" }, { timeout: 90000 }).catch(() => {}); + } + } catch (error) { captureUiError(error, "ui.tv_remote.warmup"); } + finally { if (tvWarmupTimer === undefined) { tvRemotePreparing = false; deviceButtons(); } } + }); + }, options.tvRemoteWarmupDelayMs ?? 4000); + } + + function sendTvRemote(code: string) { + const button = ({ ArrowLeft: "left", ArrowUp: "up", ArrowDown: "down", ArrowRight: "right", Enter: "select", Escape: "menu", Home: "home" } as Record)[code]; + const deviceId = selected?.udid; + if (!button || !deviceId || !isTvOS() || !ready || tvRemotePreparing || inputBlocked || disposed || testRecorder.isAgentRecording(deviceId)) return; + if (isRecordingSelected()) testRecorder.invalidate(); + tvRemoteQueue = tvRemoteQueue.catch(() => {}).then(async () => { + try { + if (tvRemoteDeviceId !== deviceId) { tvRemotePreparing = true; deviceButtons(); } + try { if (!await ensureTvRemoteSession(deviceId)) return; } + finally { if (tvWarmupTimer === undefined && tvRemotePreparing) { tvRemotePreparing = false; deviceButtons(); } } + const inputStarted = performance.now(); + try { await call("device_tv-remote", { session: tvRemoteSession, button }, { timeout: 90000 }); } + finally { recordUiTiming("ui.device_input.round_trip", performance.now() - inputStarted); } + notice(); + } catch (error) { + notice(error instanceof Error ? `TV remote: ${error.message}` : "TV remote failed."); + captureUiError(error, "ui.tv_remote.input"); + } + }); + } + function flushInput(session: PanelStream): Promise { return session.input?.flush() ?? Promise.resolve(); } @@ -173,7 +263,7 @@ export function createSimulatorPanel( if (session.epoch !== epoch) return; const failure = error as Error & { inputBlocked?: boolean; streamDisconnected?: boolean }; if (failure.inputBlocked) inputBlocked = true; - ready = false; + ready = false; cancelTvWarmup(); cancelPointer(); notice(failure.streamDisconnected ? "Reconnecting…" : failure.message ?? "Simulator input failed."); controls(); @@ -201,7 +291,7 @@ export function createSimulatorPanel( session.closing = (async () => { if (graceful) await flushInput(session); session.input?.close(); - if (stream === session) { cancelPointer(); stream = undefined; ready = false; controls(); } + if (stream === session) { cancelPointer(); stream = undefined; ready = false; cancelTvWarmup(); controls(); } try { await call(session.physicalIos ? "mobile_ios_mirror_close" : session.platform === "android" ? "mobile_android_stream_close" : "mobile_stream_close", { sessionId: session.id }, { timeout: 3000 }); } catch { /* Idle streams also expire on the server. */ } })(); @@ -215,7 +305,7 @@ export function createSimulatorPanel( reconnect.stop(); epoch++; stream = undefined; - ready = false; + ready = false; cancelTvWarmup(); inputRepairMessage = ""; if (inputBlocked) { inputBlocked = false; notice(); } controls(); @@ -499,6 +589,16 @@ export function createSimulatorPanel( if (disposed) return; const wasActive = isDeviceActive(selected); const changed = selected?.udid !== device?.udid; + if (changed || (wasActive && !isDeviceActive(device) && isTvOS())) { + cancelTvWarmup(); + // Also close on shutdown: the same UDID gets a new runner process after reboot. + // Checked inside the queue so a warm-up still opening for the old boot is closed too. + tvRemoteQueue = tvRemoteQueue.catch(() => {}).then(async () => { + if (!tvRemoteDeviceId) return; + await call("device_close", { session: tvRemoteSession }, { timeout: 30000 }).catch(() => {}); + tvRemoteDeviceId = undefined; + }); + } const active = isDeviceActive(device); if (reconnect.active && (changed || !active)) void disconnect(); if (changed || (wasActive && !active)) detachRecorder(); @@ -538,7 +638,7 @@ export function createSimulatorPanel( const sessionEpoch = epoch; const udid = selected.udid; const showStreamError = (error: unknown) => { - ready = false; + ready = false; cancelTvWarmup(); const message = error instanceof Error ? error.message : String(error); if (selected?.kind === "physical" && selected.platform === "ios") empty("Screen unavailable", message); notice(message); @@ -573,7 +673,7 @@ export function createSimulatorPanel( notice(); if (physicalIos === false) points = { width: data.definition.screen.rect.width, height: data.definition.screen.rect.height }; stream = { id, frameUri, epoch: sessionEpoch, platform: streamPlatform, physicalIos, controller: new AbortController() }; - ready = false; + ready = false; cancelTvWarmup(); seenFrames = 0; firstFrameStartedAt = connectionStartedAt; controls(); @@ -599,7 +699,7 @@ export function createSimulatorPanel( if (signal.aborted || session.epoch !== epoch) return; session.input?.clear(); session.reader?.clearFrames(); - releasePointer(); ready = false; + releasePointer(); ready = false; cancelTvWarmup(); notice("Recovering iOS video…"); controls(); await flushInput(session); if (signal.aborted || session.epoch !== epoch) return; @@ -618,7 +718,7 @@ export function createSimulatorPanel( browserArrivedAt, result.frame?.sequence ?? null); if (result.connectionState === "reconnecting") { reader.clearFrames(); - ready = false; cancelPointer(); session.input?.clear(); + ready = false; cancelTvWarmup(); cancelPointer(); session.input?.clear(); notice("Reconnecting…"); controls(); } return { ...result, browserArrivedAt }; @@ -671,7 +771,7 @@ export function createSimulatorPanel( const frameMetric = platform === "ios" ? "ui.video.ios.frames" : "ui.video.android.frames"; countUiEvent(frameMetric); frame.hidden = false; element("empty").hidden = true; - if (!ready) { ready = true; reconnect.connected(); notice(); controls(); } + if (!ready) { ready = true; reconnect.connected(); notice(); warmTvRemote(); controls(); } if (!frozenSelection && (!seenFrames || resized)) fitScreen(); seenFrames++; } @@ -685,7 +785,7 @@ export function createSimulatorPanel( if (signal.aborted || session.epoch !== epoch) return; session.input?.clear(); cancelPointer(); - ready = false; + ready = false; cancelTvWarmup(); notice("Recovering physical device video…"); controls(); void call("mobile_ios_mirror_reset", { sessionId: session.id }, { timeout: 5000 }).catch(error => { @@ -704,7 +804,7 @@ export function createSimulatorPanel( if (session.generation !== batch.generation) { session.input?.clear(); cancelPointer(); - ready = false; + ready = false; cancelTvWarmup(); session.generation = batch.generation; controls(); } @@ -725,7 +825,7 @@ export function createSimulatorPanel( }, () => { if (signal.aborted || session.epoch !== epoch) return; session.input?.clear(); - releasePointer(); ready = false; + releasePointer(); ready = false; cancelTvWarmup(); notice("Recovering Android video…"); controls(); }); const uri = new URL(session.frameUri); @@ -742,7 +842,7 @@ export function createSimulatorPanel( if (!content || !("text" in content)) throw new Error("The plugin returned an invalid Android video batch."); const batch = JSON.parse(content.text) as AndroidVideoBatch; after = batch.sequence; - if (generation !== batch.generation) { generation = batch.generation; session.input?.clear(); releasePointer(); ready = false; controls(); } + if (generation !== batch.generation) { generation = batch.generation; session.input?.clear(); releasePointer(); ready = false; cancelTvWarmup(); controls(); } await decoder.accept(batch); if (seenFrames !== previousFrames) { lastFrame = performance.now(); previousFrames = seenFrames; } if (performance.now() - lastFrame > 15000) throw new Error("Android video stopped producing frames. Reconnecting."); @@ -810,6 +910,7 @@ export function createSimulatorPanel( // drivers on one screen is solved by locking, not by hoping. if (testRecorder.isAgentRecording(selected?.udid)) return; if (!ready || inputBlocked || busy || event.button !== 0 || pointer) return; + if (isTvOS()) { canvas.focus(); return; } const position = mappedPoint(event); const edge: TouchInput["edge"] = position.y > points.height - 14 ? "bottom" : position.y < 14 ? "top" : undefined; const touch = { ...position, ...points, ...(edge ? { edge } : {}) }; @@ -892,7 +993,13 @@ export function createSimulatorPanel( return; } if (stream?.physicalIos) return; - if (!ready || inputBlocked || busy || event.metaKey || event.ctrlKey || event.altKey) return; + if (!ready || tvRemotePreparing || inputBlocked || busy || event.metaKey || event.ctrlKey || event.altKey) return; + if (isTvOS()) { + if (/^(Enter|Escape|Arrow(Up|Down|Left|Right))$/.test(event.code)) { + event.preventDefault(); sendTvRemote(event.code); + } + return; + } if (/^[\x20-\x7e]$/.test(event.key)) { event.preventDefault(); send({ type: "type", text: event.key }); } else if (/^(Enter|Escape|Backspace|Tab|Arrow(Up|Down|Left|Right))$/.test(event.code)) { @@ -902,7 +1009,7 @@ export function createSimulatorPanel( function paste(event: ClipboardEvent) { const annotationState = annotations.getSnapshot(); if (annotationState.selecting || annotationState.draft) return; - if (!ready || !stream || stream.physicalIos || inputBlocked || busy || !toolsAvailable || disposed) return; + if (!ready || !stream || stream.physicalIos || isTvOS() || inputBlocked || busy || !toolsAvailable || disposed) return; event.preventDefault(); const text = event.clipboardData?.getData("text/plain") ?? ""; if (text.length === 0) return; @@ -917,7 +1024,15 @@ export function createSimulatorPanel( canvas.addEventListener("paste", paste); element("start-device").addEventListener("click", () => { void action(start); }); root.querySelectorAll("[data-button]").forEach(button => { - button.addEventListener("click", () => { send({ type: "button", button: button.dataset.button === "home" ? "home" : "app-switcher" }); }); + button.addEventListener("click", () => { + if (isTvOS()) sendTvRemote("Home"); + else send({ type: "button", button: button.dataset.button === "home" ? "home" : "app-switcher" }); + }); + }); + root.querySelectorAll("[data-tv-key]").forEach(button => { + button.addEventListener("click", () => { + if (isTvOS() && !button.disabled) sendTvRemote(button.dataset.tvKey!); + }); }); screenshotButton.addEventListener("click", () => { void action(async () => { if (!selected || !selectedDeviceConnected() || !panelContext.canAttachScreenshots) return; @@ -990,6 +1105,7 @@ export function createSimulatorPanel( dispose() { if (disposing) return disposing; disposed = true; + cancelTvWarmup(); detachRecorder(); window.removeEventListener("keydown", dismissRecorderMenu, true); settings.dispose(); @@ -1008,7 +1124,11 @@ export function createSimulatorPanel( window.removeEventListener("focus", onVisibility); root.removeEventListener("pointerdown", activate, { capture: true }); root.removeEventListener("focusin", activate); - return disposing = disconnect(); + return disposing = (async () => { + await disconnect(); + await tvRemoteQueue; + if (tvRemoteDeviceId) await call("device_close", { session: tvRemoteSession }, { timeout: 30000 }).catch(() => {}); + })(); }, }; } diff --git a/packages/ui/test/simulator-panel.test.ts b/packages/ui/test/simulator-panel.test.ts index db3e00606..d2d04a5e1 100644 --- a/packages/ui/test/simulator-panel.test.ts +++ b/packages/ui/test/simulator-panel.test.ts @@ -34,6 +34,7 @@ class Element extends EventTarget { children: Element[] = []; elements = new Map(); buttons: Element[] = []; + tvButtons: Element[] = []; captures = new Set(); draws = 0; append(child: Element) { this.children.push(child); if (this.children.length === 1) this.value = child.value; } @@ -52,14 +53,15 @@ class Element extends EventTarget { if (element) return this.elements.get(element); return this.buttons.find(button => button.dataset.button === selector.match(/data-button="([^"]+)"/)?.[1]); } - querySelectorAll() { return this.buttons; } + querySelectorAll(selector: string) { return selector.includes("data-tv-key") ? this.tvButtons : this.buttons; } } function createPanelRoot() { const root = new Element(); - for (const name of ["settings", "screen", "device-frame", "stage", "device-bezel", "screenshot", "notice", "notice-message", "empty", "empty-description", "stopped", "start-device", "screenshot-status"]) root.elements.set(name, new Element()); + for (const name of ["settings", "screen", "device-frame", "stage", "device-bezel", "screenshot", "notice", "notice-message", "empty", "empty-description", "stopped", "start-device", "screenshot-status", "platform-label", "tv-remote-status"]) root.elements.set(name, new Element()); root.elements.get("device-frame")!.hidden = true; for (const button of ["home", "app-switcher"]) { const element = new Element(); element.dataset.button = button; root.buttons.push(element); } + for (const code of ["ArrowLeft", "ArrowUp", "ArrowDown", "ArrowRight", "Enter", "Escape"]) { const element = new Element(); element.dataset.tvKey = code; root.tvButtons.push(element); } return root; } @@ -76,6 +78,8 @@ function fixture(t: TestContext) { let screenshotEncodingError = ""; let sessionNumber = 0; let delayedOpen: Promise | undefined; + let heldTvOpen: Promise | undefined; + let tvOpenFailures = 0; let blockedIos = false; let stopped = false; let physicalDevices: PhysicalIosDevice[] = []; @@ -176,6 +180,10 @@ function fixture(t: TestContext) { } if (call.name === "mobile_list_simulators" && iosDevices) return { content: [], structuredContent: { connected: true, devices: iosDevices } }; if (call.name === "mobile_list_simulators" && simulatorError) return { isError: true, content: [{ type: "text", text: simulatorError }] }; + if (call.name === "device_open") { + await heldTvOpen; + if (tvOpenFailures > 0) { tvOpenFailures--; return { isError: true, content: [{ type: "text", text: "Runner failed" }] }; } + } const inputTool = failedInputPlatform === "android" ? "mobile_android_stream_input" : "mobile_stream_input"; if (failedInputPlatform && call.name === inputTool) { failedInputPlatform = undefined; @@ -247,7 +255,7 @@ function fixture(t: TestContext) { async attachAnnotation(annotation: ScreenAnnotation) { attachedAnnotations.push(annotation); return true; }, } as unknown as PanelContext; const inventory = new DeviceInventory(app, platform); - const panel = createSimulatorPanel(app, root as unknown as HTMLElement, inventory, panelContext, () => selections.push({ platform, active: true })); + const panel = createSimulatorPanel(app, root as unknown as HTMLElement, inventory, panelContext, () => selections.push({ platform, active: true }), { tvRemoteWarmupDelayMs: 40 }); panel.setAvailable(true); let last: SimulatorDevice | undefined; let target: PanelTarget | undefined; @@ -288,7 +296,7 @@ function fixture(t: TestContext) { for (const { panel } of panels) await panel.dispose(); for (const reset of restore) reset(); }); - return { workspace, get activeDevice() { return activeDevice; }, setIosDevices(devices: SimulatorDevice[]) { iosDevices = devices; }, calls, closed, selections, failInspection() { inspectionFailure = true; }, setAndroidAccessibility(value: NonNullable) { androidAccessibility = value; }, screenshots, attachedAnnotations, ios: panels[0], android: panels[1], failClipboard() { screenshotCopied = false; }, setAndroidDevices(devices: SimulatorDevice[], names?: AndroidBookingNames) { androidDevices = devices; bookingNames = names; }, setPhysicalDevices(devices: PhysicalIosDevice[]) { physicalDevices = devices; }, failDiscovery(message: string) { physicalError = message; }, failSimulators(message: string) { simulatorError = message; }, delayDiscovery(value: Promise) { delayedDiscovery = value; }, failInput(platform: "ios" | "android") { failedInputPlatform = platform; }, delayOpen(value: Promise) { delayedOpen = value; }, blockIos() { blockedIos = true; }, stopDevices() { stopped = true; }, + return { workspace, get activeDevice() { return activeDevice; }, setIosDevices(devices: SimulatorDevice[]) { iosDevices = devices; }, calls, closed, selections, failInspection() { inspectionFailure = true; }, setAndroidAccessibility(value: NonNullable) { androidAccessibility = value; }, screenshots, attachedAnnotations, ios: panels[0], android: panels[1], failClipboard() { screenshotCopied = false; }, setAndroidDevices(devices: SimulatorDevice[], names?: AndroidBookingNames) { androidDevices = devices; bookingNames = names; }, setPhysicalDevices(devices: PhysicalIosDevice[]) { physicalDevices = devices; }, failDiscovery(message: string) { physicalError = message; }, failSimulators(message: string) { simulatorError = message; }, delayDiscovery(value: Promise) { delayedDiscovery = value; }, failInput(platform: "ios" | "android") { failedInputPlatform = platform; }, delayOpen(value: Promise) { delayedOpen = value; }, holdTvOpen(value: Promise) { heldTvOpen = value; }, failTvOpen(times = 1) { tvOpenFailures = times; }, blockIos() { blockedIos = true; }, stopDevices() { stopped = true; }, visibility(value: string) { document.visibilityState = value; document.dispatchEvent(new Event("visibilitychange")); }, frame(platform: "ios" | "android", sequence: number, options: { generation?: number; empty?: boolean } = {}) { const id = [...pendingReads.keys()].find(id => id.startsWith(platform)); assert.ok(id); @@ -430,6 +438,103 @@ test("two same-platform screens and an Android screen route input independently screens[2].unmount(); }); +test("tvOS mirror uses the TV remote and never forwards Baguette input", async t => { + const f = fixture(t); + f.setIosDevices([{ udid: "apple-tv", name: "Apple TV", runtime: "tvOS 27.0", state: "Booted" }]); + await f.ios.load(); + await waitFor(() => f.ios.element("screen").draws > 0); + const screen = f.ios.element("screen"); + assert.equal(f.ios.element("platform-label").textContent, "tvOS"); + await waitFor(() => f.ios.root.tvButtons.every(button => !button.disabled)); + assert.equal(f.ios.root.tvButtons.every(button => !button.hidden && !button.disabled), true); + assert.equal(f.ios.root.buttons[1]!.hidden, true); + dispatch(screen, "pointerdown", { pointerId: 1, button: 0, clientX: 75, clientY: 150 }); + dispatch(screen, "pointerup", { pointerId: 1 }); + dispatch(f.ios.root.tvButtons[2]!, "click"); + dispatch(screen, "keydown", { key: "Enter", code: "Enter" }); + await waitFor(() => f.calls.filter(call => call.name === "device_tv-remote").length === 2); + assert.equal(f.calls.some(call => call.name === "mobile_stream_input"), false); + assert.deepEqual(f.calls.filter(call => call.name === "device_open" || call.name === "device_tv-remote").map(call => [call.name, call.arguments.udid ?? call.arguments.button]), [ + ["device_open", "apple-tv"], ["device_tv-remote", "down"], ["device_tv-remote", "select"], + ]); +}); + +test("tvOS remote opens a fresh session after the same simulator restarts", async t => { + const f = fixture(t); + const tv = { udid: "apple-tv", name: "Apple TV", runtime: "tvOS 27.0", state: "Booted" }; + f.setIosDevices([tv]); + await f.ios.load(); + await waitFor(() => f.calls.filter(call => call.name === "device_open").length === 1); + f.ios.inventory.apply({ connected: true, devices: [{ ...tv, state: "Shutdown" }] }); + await waitFor(() => f.calls.filter(call => call.name === "device_close").length === 1); + f.ios.inventory.apply({ connected: true, devices: [tv] }); + await waitFor(() => f.calls.filter(call => call.name === "device_open").length === 2); + assert.deepEqual(f.calls.filter(call => ["device_open", "device_close"].includes(call.name)).map(call => call.name), ["device_open", "device_close", "device_open"]); +}); + +test("tvOS warm-up is deferred after the first frame and the remote stays locked until it opens", async t => { + const f = fixture(t); + const release = Promise.withResolvers(); + f.holdTvOpen(release.promise); + f.setIosDevices([{ udid: "apple-tv", name: "Apple TV", runtime: "tvOS 27.0", state: "Booted" }]); + await f.ios.load(); + await waitFor(() => f.ios.element("screen").draws > 0); + const status = f.ios.element("tv-remote-status"); + assert.equal(f.calls.some(call => call.name === "device_open"), false, "warm-up must not start with the first frame"); + assert.equal(status.hidden, false); + assert.equal(f.ios.root.tvButtons.every(button => button.disabled), true); + assert.equal(f.ios.root.buttons[0]!.disabled, true); + dispatch(f.ios.root.tvButtons[0]!, "click"); + dispatch(f.ios.element("screen"), "keydown", { key: "Enter", code: "Enter" }); + await waitFor(() => f.calls.some(call => call.name === "device_open")); + assert.equal(status.hidden, false); + assert.equal(f.ios.root.tvButtons.every(button => button.disabled), true); + assert.equal(f.calls.some(call => call.name === "device_tv-remote"), false); + release.resolve(); + await waitFor(() => status.hidden && f.ios.root.tvButtons.every(button => !button.disabled)); + assert.equal(f.ios.root.buttons[0]!.disabled, false); + assert.deepEqual(f.calls.filter(call => call.name.startsWith("device_")).map(call => call.name), ["device_open", "device_alert"], "runner is warmed with a read-only command, not a press"); + dispatch(f.ios.root.tvButtons[0]!, "click"); + await waitFor(() => f.calls.some(call => call.name === "device_tv-remote")); + assert.equal(f.calls.filter(call => call.name === "device_open").length, 1); +}); + +test("tvOS remote unlocks after a failed warm-up and the next press retries and reports the error", async t => { + const f = fixture(t); + f.failTvOpen(2); + f.setIosDevices([{ udid: "apple-tv", name: "Apple TV", runtime: "tvOS 27.0", state: "Booted" }]); + await f.ios.load(); + await waitFor(() => f.calls.some(call => call.name === "device_open")); + await waitFor(() => f.ios.element("tv-remote-status").hidden && f.ios.root.tvButtons.every(button => !button.disabled)); + assert.equal(f.calls.some(call => call.name === "device_tv-remote"), false); + dispatch(f.ios.root.tvButtons[0]!, "click"); + await waitFor(() => /TV remote/.test(f.ios.element("notice-message").textContent)); + assert.equal(f.calls.filter(call => call.name === "device_open").length, 2); + assert.equal(f.ios.root.tvButtons.every(button => !button.disabled), true); + dispatch(f.ios.root.tvButtons[0]!, "click"); + await waitFor(() => f.calls.some(call => call.name === "device_tv-remote")); +}); + +test("a pending tvOS warm-up is cancelled when the panel is disposed", async t => { + const f = fixture(t); + f.setIosDevices([{ udid: "apple-tv", name: "Apple TV", runtime: "tvOS 27.0", state: "Booted" }]); + await f.ios.load(); + await waitFor(() => f.ios.element("screen").draws > 0); + await f.ios.panel.dispose(); + await new Promise(resolve => setTimeout(resolve, 80)); + assert.equal(f.calls.some(call => call.name === "device_open"), false); +}); + +test("iOS mirror does not open a TV remote session", async t => { + const f = fixture(t); + f.setIosDevices([{ udid: "iphone-1", name: "iPhone", runtime: "iOS 26.0", state: "Booted" }]); + await f.ios.load(); + await waitFor(() => f.ios.element("screen").draws > 0); + await new Promise(resolve => setTimeout(resolve, 100)); + assert.equal(f.calls.some(call => call.name === "device_open"), false); + assert.equal(f.ios.element("tv-remote-status").hidden, true); +}); + test("background tabs suspend their streams and visible splits survive tab switches", async t => { const f = fixture(t); const iphone: SimulatorDevice = { udid: "iphone-1", name: "iPhone", runtime: "iOS", state: "Booted" }; diff --git a/tooling/build.mjs b/tooling/build.mjs index d184d0176..de752ee69 100644 --- a/tooling/build.mjs +++ b/tooling/build.mjs @@ -97,6 +97,8 @@ const pinned = JSON.parse(lock).packages["node_modules/agent-device"]; const installed = JSON.parse(await readFile(`${runtime}/node_modules/agent-device/package.json`, "utf8")); const wanted = JSON.parse(await readFile(`${runtime}/package.json`, "utf8")).dependencies["agent-device"]; if (installed.version !== wanted || pinned.version !== installed.version) throw new Error("Run npm run vendor:agent-device to install the pinned runtime."); +const runnerDispatch = await readFile(`${runtime}/node_modules/agent-device/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift`, "utf8"); +if (!runnerDispatch.includes("mobile-dev patch: a remote press")) throw new Error("Run npm run vendor:agent-device to apply the tvOS remote patch."); await cp(`${runtime}/node_modules`, "dist/agent-device/node_modules", { recursive: true, verbatimSymlinks: true }); await copyFile(`${runtime}/config.json`, "dist/agent-device/config.json"); await copyFile(`${runtime}/package-lock.json`, "dist/agent-device/package-lock.json"); diff --git a/tooling/patch-agent-device.mjs b/tooling/patch-agent-device.mjs new file mode 100644 index 000000000..15eef7c32 --- /dev/null +++ b/tooling/patch-agent-device.mjs @@ -0,0 +1,21 @@ +#!/usr/bin/env node +import { readFile, writeFile } from "node:fs/promises"; +import { resolve } from "node:path"; + +// agent-device 0.21.x brings its own runner app to the foreground before every command that names +// no app, remote presses included. On tvOS that sends each press to the blank runner instead of +// the focused app. Remote presses go to whatever is frontmost, so a press without an app must +// skip that step. So must `alert get`, which the panel runs to start the runner without a press. Runs after `npm run vendor:agent-device`; safe to run twice. +const file = resolve("packages/runtimes/agent-device/node_modules/agent-device/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift"); +const anchor = " var activeApp = mainOwned.app ?? app\n"; +const guard = " if requestedBundleId == nil, (command.command == .remotePress || (command.command == .alert && (command.action ?? \"get\").lowercased() == \"get\")) {\n // mobile-dev patch: a remote press (and the read-only alert lookup that warms the runner) must not bring the runner host app to the front.\n return .context(ActiveCommandContext(app: mainOwned.app ?? app))\n }\n\n"; +const unscoped = " if requestedBundleId == nil, command.command == .remotePress || (command.command == .alert && (command.action ?? \"get\").lowercased() == \"get\") {\n // mobile-dev patch: a remote press (and the read-only alert lookup that warms the runner) must not bring the runner host app to the front.\n return .context(ActiveCommandContext(app: mainOwned.app ?? app))\n }\n\n"; +// Earlier revision of the guard, covering remote presses only; upgraded in place. +const previous = " if requestedBundleId == nil, command.command == .remotePress {\n // mobile-dev patch: a remote press must reach the frontmost tvOS app, not the runner host app.\n return .context(ActiveCommandContext(app: mainOwned.app ?? app))\n }\n\n"; + +const source = await readFile(file, "utf8"); +if (source.includes(guard)) process.exit(0); +if (source.includes(unscoped)) { await writeFile(file, source.replace(unscoped, guard)); process.exit(0); } +if (source.includes(previous)) { await writeFile(file, source.replace(previous, guard)); process.exit(0); } +if (source.split(anchor).length !== 2) throw new Error("agent-device runner changed; update tooling/patch-agent-device.mjs for the new pin."); +await writeFile(file, source.replace(anchor, guard + anchor)); diff --git a/tooling/test/agent-device-runner-patch.test.ts b/tooling/test/agent-device-runner-patch.test.ts new file mode 100644 index 000000000..52e35cff1 --- /dev/null +++ b/tooling/test/agent-device-runner-patch.test.ts @@ -0,0 +1,40 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawnSync } from "node:child_process"; + +const dispatch = "packages/runtimes/agent-device/node_modules/agent-device/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift"; +const patch = join(process.cwd(), "tooling/patch-agent-device.mjs"); + +test("the pinned runner lets tvOS remote presses skip host-app activation", async () => { + const source = await readFile(dispatch, "utf8"); + assert.match(source, /requestedBundleId == nil, \(command\.command == \.remotePress \|\| \(command\.command == \.alert/); + assert.ok(source.indexOf("command.command == .remotePress") < source.indexOf("var activeApp = mainOwned.app ?? app")); +}); + +test("the runner patch applies once and refuses an unknown runner", async () => { + const root = await mkdtemp(join(tmpdir(), "patch-agent-device-")); + const file = join(root, dispatch); + await mkdir(join(file, ".."), { recursive: true }); + await writeFile(file, " var activeApp = mainOwned.app ?? app\n"); + const run = () => spawnSync(process.execPath, [patch], { cwd: root, encoding: "utf8" }); + assert.equal(run().status, 0); + const patched = await readFile(file, "utf8"); + assert.equal(run().status, 0); + assert.equal(await readFile(file, "utf8"), patched); + // The unscoped alert guard is corrected without duplicating the patch. + const unscoped = patched.replace("requestedBundleId == nil, (command.command == .remotePress || (command.command == .alert && (command.action ?? \"get\").lowercased() == \"get\"))", "requestedBundleId == nil, command.command == .remotePress || (command.command == .alert && (command.action ?? \"get\").lowercased() == \"get\")"); + assert.notEqual(unscoped, patched); + await writeFile(file, unscoped); + assert.equal(run().status, 0); + assert.equal(await readFile(file, "utf8"), patched); + // A runner patched by the earlier revision is upgraded in place. + const old = " if requestedBundleId == nil, command.command == .remotePress {\n // mobile-dev patch: a remote press must reach the frontmost tvOS app, not the runner host app.\n return .context(ActiveCommandContext(app: mainOwned.app ?? app))\n }\n\n var activeApp = mainOwned.app ?? app\n"; + await writeFile(file, old); + assert.equal(run().status, 0); + assert.equal(await readFile(file, "utf8"), patched); + await writeFile(file, "unrelated\n"); + assert.notEqual(run().status, 0); +});