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
8 changes: 8 additions & 0 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,14 @@ device go through `captureServerError` as `testing.tool` and `testing.release`.
labels, placeholders, testIDs, roles, bounds, bundle ids, project paths, device identifiers or
emitted test source are attached to any of these.

Physical-iPhone runs add two bounded server metrics. `testing.device.settle.samples` and
`testing.device.settle.duration` (milliseconds) measure how long the phone took to let go of the
recorder's XCTest runner after its session closed, with `outcome` `settled`, `timeout` or
`unavailable`. `testing.run.launch_retry` counts the single retry of a run whose first launch failed
with CoreDevice error 10004, with `outcome` `recovered` or `failed`. Both carry only `component`,
`surface`, `platform` and `outcome`: no device or app identifiers. The 10004 failure itself is still
reported through `captureServerError` as `testing.tool`.

An **agent recording** — the user's own coding agent writing the flow through
`mobile_testing_agent_*`, see [docs/agent-recording.md](agent-recording.md) — is measured on both
sides of the one boundary it crosses. In the server, `testing.agent.screen.duration` times the
Expand Down
38 changes: 38 additions & 0 deletions packages/core/src/coredevice-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* What a CoreDevice launch failure means, in words that match its cause.
*
* agent-device ends every `devicectl` launch failure it cannot classify with one hint: "Ensure the
* iOS device is unlocked, trusted, and available in Xcode > Devices". That is right for a locked or
* unpaired phone and wrong for the two codes below, which arrive on a phone that is unlocked, paired
* and in front of the user. Those two get their own explanation; every other failure keeps its hint.
*/

const GENERIC_HINT = /(?:Hint:\s*)?Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry\.?/i;

export type CoreDeviceLaunchCode = "10002" | "10004";

/** The launch error code in devicectl or agent-device output, when it is one of the two explained here. */
export function coreDeviceLaunchCode(text: string): CoreDeviceLaunchCode | undefined {
const match = /CoreDeviceError error (10002|10004)\b/.exec(text);
return match ? match[1] as CoreDeviceLaunchCode : undefined;
}

/** Apple's own apps (Settings, Safari, Maps) never carry a developer signature. */
export function isAppleBundle(appId: string | undefined): boolean {
return appId !== undefined && /^com\.apple\./i.test(appId);
}

export function coreDeviceLaunchHint(code: CoreDeviceLaunchCode, appId?: string): string {
if (code === "10004")
return "The app was starting or stopping as it was opened, so the phone could not report its process. This usually clears within a few seconds: wait a moment and try again. If it repeats, open the app on the phone once to check that it does not quit at launch.";
if (isAppleBundle(appId))
return "The phone refused to open this Apple app from the Mac (the phone itself is reachable). Open it on the phone yourself and try again; if it still fails, pick one of your own apps instead.";
return "The phone refused to start the app although it is reachable. Check the phone for a prompt, make sure the screen is on, and that the app is installed and its developer profile is trusted (Settings → General → VPN & Device Management), then try again.";
}

/** Replaces agent-device's generic unlock-and-trust hint when the failure is one of the codes above. `knownCode` is for an error whose code sits in its details rather than its text. */
export function rewriteCoreDeviceHint(text: string, appId?: string, knownCode?: CoreDeviceLaunchCode): string {
const code = knownCode ?? coreDeviceLaunchCode(text);
if (code === undefined || !GENERIC_HINT.test(text)) return text;
return text.replace(GENERIC_HINT, coreDeviceLaunchHint(code, appId)).trim();
}
27 changes: 27 additions & 0 deletions packages/core/src/device-apps/apps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,33 @@ export async function runningPhysicalApps(deviceId: string, signal?: AbortSignal
return parsePhysicalApps(results[0].stdout, results[1].stdout);
}

/**
* The bundle id of the physical-device app running as `pid`, Apple's own apps included. The monitoring
* list above leaves those out because nothing can be sampled in them, but Testing Studio records
* against whatever app is in front, Settings or Safari as much as the user's own.
*/
export function parsePhysicalBundleForPid(apps: string, processes: string, pid: number): string | undefined {
const installed = appResponse.parse(JSON.parse(apps) as unknown);
const running = processResponse.parse(JSON.parse(processes) as unknown);
const process = running.result.runningProcesses.find(entry => entry.processIdentifier === pid && entry.executable !== undefined);
if (process?.executable === undefined) return undefined;
const directory = dirname(devicePath(process.executable));
for (const app of installed.result.apps) if (devicePath(app.url) === directory) return app.bundleIdentifier;
return undefined;
}

export async function physicalBundleForPid(deviceId: string, pid: number, signal?: AbortSignal, run: DeviceCommand = execute): Promise<string | undefined> {
const prefix = ["devicectl", "device", "info"];
const options = ["--device", deviceId, "--quiet", "--timeout", "10", "--omit-deprecated-fields-in-json", "--json-output", "-"];
const settings: Parameters<DeviceCommand>[2] = { encoding: "utf8", timeout: 15000, maxBuffer: 8 * 1024 * 1024, signal };
// `--include-all-apps` is what brings Apple's preinstalled apps back: devicectl hides them (and
// anything that is not a developer build) unless asked, which is why Settings or Safari never resolved.
const installed = runDiscoveryCommand("ios_physical_apps", "/usr/bin/xcrun", [...prefix, "apps", "--include-all-apps", ...options], settings, run);
const running = runDiscoveryCommand("ios_physical_processes", "/usr/bin/xcrun", [...prefix, "processes", ...options], settings, run);
const results = await Promise.all([installed, running]);
return parsePhysicalBundleForPid(results[0].stdout, results[1].stdout, pid);
}

/** The running simulator apps in `launchctl list` output. Apple's own apps are left out unless `includeSystem`. */
export function parseRunningApps(output: string, includeSystem = false): DeviceApp[] {
const apps: DeviceApp[] = [];
Expand Down
21 changes: 21 additions & 0 deletions packages/core/src/ios-signing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { promisify } from "node:util";
import { ExpectedOperationError } from "@mobile-dev/shared/error-reporting.ts";
import { APP_FLOW_DIRECTORY } from "./app-flow-host.ts";
import { TESTING_DIRECTORY } from "./testing-projects.ts";
import { coreDeviceLaunchCode, rewriteCoreDeviceHint } from "./coredevice-errors.ts";

/**
* Code signing for the XCTest runner agent-device builds for a physical iPhone.
Expand Down Expand Up @@ -306,8 +307,28 @@ const USER_FIXABLE_REASONS = /^(?:signing_|bundle_identifier_already_registered|
*/
export function withAgentDeviceHint(error: unknown, hint: (error: unknown) => string | undefined, message: (error: unknown) => string): unknown {
if (error instanceof ExpectedOperationError || error === null || typeof error !== "object") return error;
const explained = explainCoreDeviceLaunch(error, message);
if (explained !== undefined) return explained;
const details = (error as { details?: { reason?: unknown } }).details;
const reason = typeof details?.reason === "string" ? details.reason : "";
if (!USER_FIXABLE_REASONS.test(reason) || !hint(error)) return error;
return new ExpectedOperationError(reason.startsWith("signing_") || reason.startsWith("bundle_") ? "invalid_input" : "device_unavailable", message(error));
}

/**
* agent-device's launch failures 10002 and 10004 end in its generic "unlocked, trusted" hint, which is
* wrong for both. Returns the same failure with an accurate explanation, or undefined for any other
* error. 10002 is something the user sorts out on the phone (expected); 10004 is a launch racing the
* app's own shutdown, which stays a reported error so the race remains visible.
*/
function explainCoreDeviceLaunch(error: object, message: (error: unknown) => string): Error | undefined {
const details = (error as { details?: { reason?: unknown; appBundleId?: unknown } }).details;
// A classified failure (locked, Developer Mode, signing) already carries its own accurate hint.
if (typeof details?.reason === "string" && USER_FIXABLE_REASONS.test(details.reason)) return undefined;
const text = message(error);
const code = coreDeviceLaunchCode(`${text}\n${JSON.stringify(details ?? "")}`);
const appId = typeof details?.appBundleId === "string" ? details.appBundleId : undefined;
const rewritten = code === undefined ? text : rewriteCoreDeviceHint(text, appId, code);
if (code === undefined || rewritten === text) return undefined;
return code === "10002" ? new ExpectedOperationError("device_unavailable", rewritten) : new Error(rewritten, { cause: error });
}
57 changes: 57 additions & 0 deletions packages/core/src/physical-ios-settle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { recordTestingDeviceSettle } from "./telemetry.ts";

const execute = promisify(execFile);

type Run = (file: string, args: string[], options: { timeout: number; maxBuffer: number }) => Promise<{ stdout: string }>;

/** A simulator UDID is a UUID; hardware UDIDs are `<8 hex>-<16 hex>` (or a bare 40-hex legacy UDID). */
export function isHardwareUdid(deviceId: string): boolean {
return /^[0-9A-F]{8}-[0-9A-F]{16}$/i.test(deviceId) || /^[0-9a-f]{40}$/i.test(deviceId);
}

const RUNNER = /AgentDeviceRunner/;
const BOUND_MS = 10_000;
const POLL_MS = 500;
/** One quiet poll can be the gap between the runner process exiting and the app it drove being torn down. */
const GRACE_MS = 750;

/**
* Waits for a physical iPhone to let go of the recorder's XCTest runner.
*
* Closing the recorder's agent-device session returns once the daemon has asked the runner to stop;
* the phone then tears the runner down on its own clock, and XCTest takes the app it was driving
* with it. A test run that launches that app in the meantime has the new process killed under it,
* which devicectl reports as "process identifier ... could not be determined" (CoreDevice 10004).
* Running again works only because by then the teardown has finished. Waiting for the runner to
* leave the process list removes the overlap instead of retrying through it.
*
* Best effort and bounded: a phone that cannot list processes, or a runner that outlives the bound,
* does not block the run, which then proceeds exactly as it did before.
*/
export async function settlePhysicalIos(deviceId: string, run: Run = execute, sleep: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms)), now: () => number = Date.now): Promise<void> {
const startedAt = now();
const args = ["devicectl", "device", "info", "processes", "--device", deviceId, "--quiet", "--timeout", "10", "--omit-deprecated-fields-in-json", "--json-output", "-"];
while (true) {
let running: boolean;
try {
const { stdout } = await run("/usr/bin/xcrun", args, { timeout: 15_000, maxBuffer: 4 * 1024 * 1024 });
const parsed = JSON.parse(stdout) as { result?: { runningProcesses?: { executable?: unknown }[] } };
running = (parsed.result?.runningProcesses ?? []).some(entry => typeof entry.executable === "string" && RUNNER.test(entry.executable));
} catch {
recordTestingDeviceSettle("unavailable", now() - startedAt);
return;
}
if (!running) {
await sleep(GRACE_MS);
recordTestingDeviceSettle("settled", now() - startedAt);
return;
}
if (now() - startedAt >= BOUND_MS) {
recordTestingDeviceSettle("timeout", now() - startedAt);
return;
}
await sleep(POLL_MS);
}
}
17 changes: 17 additions & 0 deletions packages/core/src/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,23 @@ export function recordTestingAgentRead(outcome: "success" | "failed", duration:
if (outcome === "success") Sentry.metrics.gauge("testing.agent.screen.elements", elements, { attributes });
}

/**
* How long a physical iPhone took to let go of the recorder's runner after its session closed, and
* whether it did within the bound. Outcome and duration only: no device or app identifiers.
*/
export function recordTestingDeviceSettle(outcome: "settled" | "timeout" | "unavailable", duration: number) {
if (process.env.MOBILE_DEV_TELEMETRY === "off") return;
const attributes = { component: "server", surface: "testing", platform: "ios", outcome };
Sentry.metrics.count("testing.device.settle.samples", 1, { attributes });
Sentry.metrics.distribution("testing.device.settle.duration", Math.max(0, duration), { unit: "millisecond", attributes });
}

/** A physical-iPhone run that was started again once after CoreDevice reported the app's process gone (error 10004). */
export function countTestingLaunchRetry(outcome: "recovered" | "failed") {
if (process.env.MOBILE_DEV_TELEMETRY === "off") return;
Sentry.metrics.count("testing.run.launch_retry", 1, { attributes: { component: "server", surface: "testing", platform: "ios", outcome } });
}

/**
* Setup telemetry is deliberately structural: operation, bounded outcome and provider id only.
* It never includes prompts, source, project paths, app identifiers, model ids, URLs or tokens.
Expand Down
13 changes: 12 additions & 1 deletion packages/core/src/testing-device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { ScreenComponent, ScreenSize } from "@mobile-dev/shared/screen-anno
import { APP_FLOW_DIRECTORY, loadVendoredAgentDevice } from "./app-flow-host.ts";
import { bundledE2eRoot } from "./e2e-runtime.ts";
import { captureServerError } from "./telemetry.ts";
import { isHardwareUdid, settlePhysicalIos } from "./physical-ios-settle.ts";

/**
* The element tree the Testing Studio panel's recorder names selectors from: the one the `e2e` runner
Expand Down Expand Up @@ -274,7 +275,12 @@ export class TestingDevices {

private readonly load: typeof loadVendoredAgentDevice;

constructor(load = loadVendoredAgentDevice) { this.load = load; }
/** Lets a physical iPhone finish tearing the recorder's runner down once its session is closed. */
private readonly settle: (deviceId: string) => Promise<void>;
/** The device the attached session holds, kept so its release knows whether to settle. */
private attachedDevice?: { deviceId: string; platform: "ios" | "android" };

constructor(load = loadVendoredAgentDevice, settle: (deviceId: string) => Promise<void> = settlePhysicalIos) { this.load = load; this.settle = settle; }

private async connect(): Promise<AgentDeviceClient> {
pinStateDir();
Expand Down Expand Up @@ -308,6 +314,7 @@ export class TestingDevices {
app: target.bundleId, relaunch: false, noRecord: true, timeoutMs: 120_000,
});
this.attached = this.key(target);
this.attachedDevice = { deviceId: target.deviceId, platform: target.platform };
}

/** The runner's own snapshot call, with the runner's own options: a different tree is a different test. */
Expand Down Expand Up @@ -446,12 +453,16 @@ export class TestingDevices {
if (this.attached === undefined || this.client === undefined) return;
this.attached = undefined;
this.lastRefs = {};
const held = this.attachedDevice;
this.attachedDevice = undefined;
try {
await (await this.client).sessions.close({ session: SESSION });
} catch (error) {
// A session that is already gone is the state we wanted; anything else is worth knowing
// about but must not fail the user's stop.
captureServerError(error, "testing.release");
}
// Closing returns before the phone has torn the runner (and the app it drove) down; see `settlePhysicalIos`.
if (held?.platform === "ios" && isHardwareUdid(held.deviceId)) await this.settle(held.deviceId).catch(() => undefined);
}
}
8 changes: 7 additions & 1 deletion packages/core/src/testing-prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { Lane, LaneExecutor, MatrixPlatform } from "./testing-matrix.ts";
import type { TestRunProgress, TestRunResult } from "./testing-run.ts";
import { listIosDevices } from "./ios-devices.ts";
import { ensureIosSigning } from "./ios-signing.ts";
import { coreDeviceLaunchCode, coreDeviceLaunchHint } from "./coredevice-errors.ts";
import { findDeviceBuild } from "./ios-device-build.ts";

/** Home screens and system UI, which are never the app to record. */
Expand Down Expand Up @@ -203,7 +204,12 @@ export function physicalIosError(error: unknown, action: string, appId?: string)
return new ExpectedOperationError("app_unavailable", `${action} failed: ${appId ?? "the app"} is not installed on the device. Build and install it (for an Expo app, \`npx expo run:ios --device\`), then try again.`);
if (/no devices matched|device not found|unavailable|not connected|tunnel/i.test(output))
return new ExpectedOperationError("device_unavailable", `${action} failed: the device is not reachable. Reconnect it, unlock it, and refresh Devices.`);
return commandError(error, action, "devicectl");
const launch = coreDeviceLaunchCode(output);
if (launch === "10002") return new ExpectedOperationError("device_unavailable", `${action} failed: ${coreDeviceLaunchHint(launch, appId)}`);
const failure = commandError(error, action, "devicectl");
// A launch that raced the app's own shutdown is retried by the user, so it stays a reported failure with its real explanation.
if (launch === "10004" && !(failure instanceof ExpectedOperationError)) failure.message = `${failure.message} ${coreDeviceLaunchHint(launch, appId)}`;
return failure;
}

const APK_PATH = /^\/[\w\-./=+@~]+\.apk$/;
Expand Down
Loading
Loading