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
21 changes: 21 additions & 0 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@ Since 0.1.134, physical iOS capture runs in the shared `ios-mirror-service` Node

`ios.mirror.shared.captures` and `ios.mirror.shared.subscribers` report active counts. `ios.mirror.shared.queue_dropped` counts frames discarded by subscriber queue overflow. Counts aggregate in 30-second windows and flush on service shutdown, using the simulator surface and physical iOS context. No per-frame events, device identifiers, subscription IDs, payloads, or paths are sent. The service clears its collection timer on shutdown and honors telemetry opt-out.

Apple TV mirroring adds `ios.mirror.shared.apple_tv_captures` (a gauge on the same 30-second window) and `ios.mirror.stream_configured`, one count per decoder configuration, with the closed attributes `device_os` (`ios`/`tvos`) and `stream_class` (`uhd`/`hd`/`sd` × `8bit`/`10bit`), so 4K HDR streams are separable from SD ones. The panel counts `ui.video.ios.degraded` once per degraded (screenshot) mirror session. The native helper's own timings (`Connect`, `FrameProcess`, `Input`) are unchanged and carry no attributes, so they need no rebuild of the shared telemetry. Device identifiers, pairing records and addresses are never sent.

Since 0.1.170, a physical iOS bezel that can't be rendered no longer fails `mobile_ios_mirror_session`. Mirroring opens without the frame, and an unexpected render failure reports a handled `ios-mirror.bezel` error. The server keeps a missing frame for five minutes, so each hardware model reports at most once in that window instead of on every panel reconnect. A device type that Xcode doesn't have is expected: it counts as an `unsupported_platform` outcome and sends no event. Earlier releases reported these failures as `mobile_ios_mirror_session` errors, so compare `ios-mirror.bezel` with those events when reading trends. No metrics are added. The existing `server.error.outcome` count carries the new operation value.

Since 0.1.132, `plugin.update.operations` counts release checks and installations
Expand Down Expand Up @@ -945,3 +947,22 @@ this feature. Benchmark process measurements are local report artifacts and are
not submitted to Sentry. Existing startup, stream and input coverage is retained.

Physical iPhone recording and replay add no metrics. Testing Studio timings (`ui.testing.*`) already carry `device_platform` and `device_kind` (`physical` for hardware) from the device workspace whenever one device is shown, so hardware series are separable from simulator ones. agent-device failures now include its `details.hint` in the user-facing message and, for signing, Developer Mode and locked-device classes, are reported as expected outcomes. Hints have local paths replaced with `<path>`; log paths, team IDs, identities and device identifiers are never sent.

## Testing Studio on Apple TV

Testing Studio's measurements carry an `os` attribute, `ios` or `tvos`, for the work that differs between
an iPhone/iPad and an Apple TV. Android work has none, and `device_os` on the mirror's stream metric is the
same value under its older name. The panel splits these by `os`: `ui.testing.record_prepare` and
`ui.testing.tree_read` (the recording's device), `ui.testing.run` (the run's device) and
`ui.testing.matrix_run`. A matrix timing carries `os` only when every lane shares an OS family; a mixed
run omits it. `ui.testing.matrix_lane`, `ui.testing.matrix_lane_passed` and `ui.testing.matrix_lane_failed`
count lanes by `os`, and `ui.testing.record_start_os` counts recordings by `os`.

Remote presses are bounded aggregates, never a span each. The panel adds `ui.testing.remote_press` for each
press it takes and `ui.testing.press_until_focused.found` / `.exhausted` for how a `pressUntilFocused`
ended, all with `os=tvos`, in the existing 30-second window. The server adds
`testing.remote.press.samples` and `testing.remote.press.duration` (`outcome=success|failed`) for
`mobile_testing_press`, and `testing.press_until_focused.samples` / `.presses` (`outcome=found|exhausted`)
for an agent recording's `pressUntilFocused`. `mobile_testing_press` is a frequent tool, so it gets no
`tools/call` span. Buttons, selectors, labels, device identifiers and app ids are never sent, and
telemetry opt-out stops them all.
75 changes: 75 additions & 0 deletions docs/testing-panel.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ Maestro YAML is a second emitter behind the same recorder.
Physical iOS (`ios-mirror`) and physical Android are out. Android emulators slot in behind the same
interfaces: the recorder reads the same agent-device snapshot with `{ platform: "android", serial }`.

A physical Apple TV is hidden from every device list unless `MOBILE_DEV_PHYSICAL_APPLE_TV=1` is set. That support is unverified (no hardware, no pairing flow yet); tvOS simulators are unaffected.

## What already exists

Almost every primitive is in place; the panel is mostly wiring.
Expand Down Expand Up @@ -925,6 +927,79 @@ Attaching names the bundle id and passes `relaunch: false`. Never `--foreground`
outright when more than one app is running on the simulator, and never anything that relaunches:
the recorder exists so the user keeps tapping the screen they are already on.

## tvOS (Apple TV)

Testing Studio records, edits and runs tests on Apple TV simulators. tvOS stays `platform: "ios"` for the
runner, which has no TV platform; the panel tells the two apart by `appleOs: "tvos"`
(`packages/shared/src/apple-os.ts`). The runner is `e2e` with `@e2e-dev/mobile`, and every remote press goes
through agent-device's `tvRemote`.

### How tvOS projects and targets are detected

- **Simulators.** A simulator whose runtime reads `tvOS …` is an Apple TV. It is listed with the other
iOS simulators and picked like one.
- **Config targets.** A target is an Apple TV target when its entry says `appleOs: "tvos"` or its name is
`tv`, `tvos` or `appletv`. Targets with no `appleOs` are iPhone/iPad targets, so a project with both
resolves the right one for each device.
- **Native sources.** A Podfile with `platform :tvos`, or an Xcode project with `SDKROOT = appletvos`,
marks the project as tvOS. A project that targets only tvOS turns its otherwise unmarked iOS-engine
targets into Apple TV targets.
- **Pinned apps.** A test pins one app per OS family (`ios`, `tvos`, `android`). An iPhone lane never
runs a test pinned to Apple TV, nor the reverse; the matrix refuses it before anything boots.

### Recording with the remote

An Apple TV has no touch surface, so the mirror's toolbar swaps touch for the remote: **TV left, up, down,
right, select, menu** and **Home**. Arrow keys, Enter and Escape work on the mirror too. While recording,
each press is a step and is taken on the device. Holding select makes it a long press (`durationMs`).
Right-clicking an element offers the focus steps instead of tap and swipe. An agent recording gets the
same steps, plus a `press` kind and an `assertFocused` check, and its `tv_remote` tool exists only on
tvOS runs that have agent steps.

### Step types

| Step | Emits | Use |
| --- | --- | --- |
| `press` | `press(device, "select")` | One remote button; optionally held. |
| `pressUntilFocused` | `pressUntilFocused(device, locator, "down")` | Presses a direction until the element holds focus, up to `maxPresses` (10 by default). Prefer it to counting presses. |
| `assertFocused` | `expect(locator).toBeFocused()` | Checks that the element holds focus now. |

`tap`, `doubleTap`, `longPress`, `swipe` and `scrollUntilVisible` are refused on an Apple TV. A step
that has run out of presses without reaching focus fails the run; while recording, it is not an error and
focus is left where it ended up. Tests that use the remote carry two small helpers (`press`,
`pressUntilFocused`) in their header, so a saved file runs without the plugin.

### Focus assertions

`toBeFocused` reads the focused element from the runner's tree. A view with an `accessibilityLabel`
becomes one accessibility element and hides the text of its children from the tree. Locate such an
element by its label (or test id), not by a child's text, or the locator finds nothing to hold focus.
Elements marked focused in the agent's screen read are the ones holding focus now.

### Matrix runs with iPhone and TV

Tick an iPhone and an Apple TV in the matrix to run one test on both. The lanes are independent and each
takes the app of its own OS family: a project with its own config runs the iPhone target and the tvOS
target; a Testing Studio test needs an app pinned for each (`mobile_testing_set_target` with mode `add`).
A tvOS lane installs a `Debug-appletvsimulator` build when the booted TV has none, and never copies an
iPhone build to it.

### The UIScene requirement on tvOS 27

A tvOS 27 runtime refuses an app without the UIScene lifecycle: it exits right after launch. A lane or run
checks for a `UIApplicationSceneManifest` entry in the app's `Info.plist` first, and fails with an
explanation (add a scene delegate and the manifest, then rebuild) instead of a bare launch failure.
Older tvOS runtimes are not checked.

### Limits

- **No touch.** Touch steps and the touch input paths are refused with "An Apple TV has no touchscreen."
- **No `playPause`.** The remote has `up`, `down`, `left`, `right`, `select`, `menu` and `home` only.
- **No recording video.** The mirror of a simulator can be shown, but a recording does not capture video.
- **Physical Apple TV is hidden.** Real hardware only appears with `MOBILE_DEV_PHYSICAL_APPLE_TV=1`,
and is unverified: there was no hardware to test against and there is no pairing flow yet. Simulators are
unaffected, and the panel marks a physical Apple TV as unverified.

## Maestro, later

Nothing above is e2e-specific except the emitter and the run command. Adding Maestro means:
Expand Down
7 changes: 4 additions & 3 deletions packages/core/src/baguette.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { baguetteEnvironment } from "./baguette-runtime.ts";
import { panelRuntimePath } from "./panel-runtime.ts";
import { captureServerError, recordAccessibilityBridgeRestart, recordBaguetteFrameworkRestart, recordSimulatorBoot } from "./telemetry.ts";
import type { ResourceSaving } from "./resource-saving.ts";
import { isTvOSRuntime } from "@mobile-dev/shared/apple-os.ts";

type DescribedUi = { tree?: { label?: unknown } };
const NO_ACCESSIBILITY_DATA = "no accessibility data";
Expand Down Expand Up @@ -385,7 +386,7 @@ export class Baguette {
return definitionSchema.parse(payload);
} catch (error) {
const diagnostic = getDefinitionDiagnostic(error);
if (listed.runtime.startsWith("tvOS ") && diagnostic?.stage === "profile_chrome_identifier"
if (isTvOSRuntime(listed.runtime) && diagnostic?.stage === "profile_chrome_identifier"
&& diagnostic.failure === "missing") {
return this.tvosDefinition(udid, listed.name);
}
Expand Down Expand Up @@ -433,7 +434,7 @@ export class Baguette {
const inProgress = device.state === (action === "boot" ? "Booting" : "ShuttingDown");
if (!inProgress) {
const requestStarted = performance.now();
const tvBoot = action === "boot" && device.runtime.startsWith("tvOS ");
const tvBoot = action === "boot" && isTvOSRuntime(device.runtime);
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.
Expand All @@ -452,7 +453,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);
if (action === "boot") recordSimulatorBoot("state_wait", isTvOSRuntime(device.runtime) ? "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
37 changes: 37 additions & 0 deletions packages/core/src/device-session-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* What it means when the runner cannot get a device because agent-device is already holding it.
*
* agent-device allows one session per simulator and one daemon version per state directory. A run that
* meets either says so in its own words ("Device is already in use by session …", "Daemon (pid …) is newer
* than this client"), which names a mechanism the user never started. These say who holds the device and
* what to close.
*/

const IN_USE = /Device is already in use by session "([^"]+)"/;
const NEWER_DAEMON = /Daemon \(pid (\d+), v([\w.\-]+)\) is newer than this client \(v([\w.\-]+)\)/;

export type BlockingSession = { kind: "session"; session: string } | { kind: "daemon"; pid: number; daemon: string; client: string };

/** The blocking session or daemon in runner output, when the text names one. */
export function blockingSession(text: string): BlockingSession | undefined {
const session = IN_USE.exec(text)?.[1];
if (session) return { kind: "session", session };
const daemon = NEWER_DAEMON.exec(text);
return daemon ? { kind: "daemon", pid: Number(daemon[1]), daemon: daemon[2]!, client: daemon[3]! } : undefined;
}

/** Who holds the device, in words a tester can act on. */
export function explainBlockingSession(blocking: BlockingSession): string {
if (blocking.kind === "daemon")
return `A newer agent-device daemon (pid ${blocking.pid}, v${blocking.daemon}) is running and this runner (v${blocking.client}) will not replace it, so it cannot reach the simulator. Quit the tool that started it, or stop that process, then run again.`;
const own = /^mobile-dev-(?:recorder|tv-|lane-)/.test(blocking.session);
return own
? `The simulator is still held by Mobile Dev's own session "${blocking.session}" (the recorder or the mirror's remote). Stop recording, wait a moment and run again.`
: `The simulator is held by another agent-device session, "${blocking.session}", which is not Mobile Dev's. Close it (the tool or terminal that opened it), or run \`agent-device close --session ${blocking.session}\`, then run again. Only one session can hold a simulator at a time.`;
}

/** Replaces a runner message that names a blocking session or daemon with its explanation; other text is unchanged. */
export function rewriteBlockingSession(text: string): string {
const blocking = blockingSession(text);
return blocking ? explainBlockingSession(blocking) : text;
}
32 changes: 26 additions & 6 deletions packages/core/src/ios-device-build.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { readdir, stat } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { appleOsOfPlatformName, xcodeSdkSuffixes, type AppleOs } from "@mobile-dev/shared/apple-os.ts";
import type { Commands } from "./app-control/commands.ts";

/**
Expand All @@ -19,12 +20,13 @@ async function appsIn(directory: string): Promise<string[]> {
return entries.filter(name => name.endsWith(".app")).map(name => join(directory, name));
}

/** The `*-iphoneos` product directories under the build roots. */
export async function deviceProductDirectories(projectPath?: string, home = homedir()): Promise<string[]> {
/** The device product directories under the build roots: `*-iphoneos`, or `*-appletvos` for an Apple TV. */
export async function deviceProductDirectories(projectPath?: string, home = homedir(), os: AppleOs = "ios", simulator = false): Promise<string[]> {
const products: string[] = [];
const suffixes = simulator ? [os === "tvos" ? "-appletvsimulator" : "-iphonesimulator"] : xcodeSdkSuffixes(os);
const productsOf = async (root: string) => {
for (const configuration of await readdir(root).catch(() => [] as string[])) {
if (configuration.endsWith("-iphoneos")) products.push(join(root, configuration));
if (suffixes.some(suffix => configuration.endsWith(suffix))) products.push(join(root, configuration));
}
};
if (projectPath) await productsOf(join(projectPath, "ios", "build", "Build", "Products"));
Expand All @@ -33,17 +35,35 @@ export async function deviceProductDirectories(projectPath?: string, home = home
return products;
}

export async function findDeviceBuild(appId: string, commands: Pick<Commands, "run">, projectPath?: string, home?: string): Promise<string | undefined> {
export function findDeviceBuild(appId: string, commands: Pick<Commands, "run">, projectPath?: string, home?: string, os: AppleOs = "ios"): Promise<string | undefined> {
return findBuild(os, appId, commands, projectPath, home);
}

/** A simulator build (`Debug-appletvsimulator`, `Debug-iphonesimulator`) of the app, for installing on a simulator that lacks it. */
export function findSimulatorBuild(appId: string, commands: Pick<Commands, "run">, projectPath?: string, home?: string, os: AppleOs = "ios"): Promise<string | undefined> {
return findBuild(os, appId, commands, projectPath, home, true);
}

async function findBuild(os: AppleOs, appId: string, commands: Pick<Commands, "run">, projectPath?: string, home?: string, simulator = false): Promise<string | undefined> {
const candidates: { path: string; time: number }[] = [];
for (const directory of await deviceProductDirectories(projectPath, home)) {
for (const directory of await deviceProductDirectories(projectPath, home, os, simulator)) {
for (const app of await appsIn(directory)) candidates.push({ path: app, time: await modified(app) });
}
candidates.sort((a, b) => b.time - a.time);
for (const { path } of candidates) {
try {
const identifier = (await commands.run("/usr/bin/plutil", ["-extract", "CFBundleIdentifier", "raw", "-o", "-", join(path, "Info.plist")], { timeout: 5_000 })).trim();
if (identifier === appId) return path;
if (identifier !== appId) continue;
// A device product directory is named for its SDK, but only the bundle says what it was built for.
if (!simulator && await builtFor(path, commands) === (os === "tvos" ? "ios" : "tvos")) continue;
return path;
} catch { /* an unreadable bundle is not a match */ }
}
return undefined;
}

/** The OS family the bundle at `app` was built for (`DTPlatformName`), or undefined when it names none. */
async function builtFor(app: string, commands: Pick<Commands, "run">): Promise<AppleOs | undefined> {
try { return appleOsOfPlatformName((await commands.run("/usr/bin/plutil", ["-extract", "DTPlatformName", "raw", "-o", "-", join(app, "Info.plist")], { timeout: 5_000 })).trim()); }
catch { return undefined; }
}
Loading
Loading