diff --git a/docs/telemetry.md b/docs/telemetry.md index 3134fe56a..1bc8e6131 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -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 diff --git a/packages/core/src/coredevice-errors.ts b/packages/core/src/coredevice-errors.ts new file mode 100644 index 000000000..e78c9fe19 --- /dev/null +++ b/packages/core/src/coredevice-errors.ts @@ -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(); +} diff --git a/packages/core/src/device-apps/apps.ts b/packages/core/src/device-apps/apps.ts index 19ba7fea7..af1d72474 100644 --- a/packages/core/src/device-apps/apps.ts +++ b/packages/core/src/device-apps/apps.ts @@ -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 { + const prefix = ["devicectl", "device", "info"]; + const options = ["--device", deviceId, "--quiet", "--timeout", "10", "--omit-deprecated-fields-in-json", "--json-output", "-"]; + const settings: Parameters[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[] = []; diff --git a/packages/core/src/ios-signing.ts b/packages/core/src/ios-signing.ts index 03128b1c1..b03949ecb 100644 --- a/packages/core/src/ios-signing.ts +++ b/packages/core/src/ios-signing.ts @@ -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. @@ -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 }); +} diff --git a/packages/core/src/physical-ios-settle.ts b/packages/core/src/physical-ios-settle.ts new file mode 100644 index 000000000..b1e6d5386 --- /dev/null +++ b/packages/core/src/physical-ios-settle.ts @@ -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 = ms => new Promise(resolve => setTimeout(resolve, ms)), now: () => number = Date.now): Promise { + 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); + } +} diff --git a/packages/core/src/telemetry.ts b/packages/core/src/telemetry.ts index 19a45b746..7d0bc8e84 100644 --- a/packages/core/src/telemetry.ts +++ b/packages/core/src/telemetry.ts @@ -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. diff --git a/packages/core/src/testing-device.ts b/packages/core/src/testing-device.ts index 5e90dcbe9..4afe8f5e0 100644 --- a/packages/core/src/testing-device.ts +++ b/packages/core/src/testing-device.ts @@ -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 @@ -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; + /** 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 = settlePhysicalIos) { this.load = load; this.settle = settle; } private async connect(): Promise { pinStateDir(); @@ -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. */ @@ -446,6 +453,8 @@ 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) { @@ -453,5 +462,7 @@ export class TestingDevices { // 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); } } diff --git a/packages/core/src/testing-prepare.ts b/packages/core/src/testing-prepare.ts index 861d47b30..c896e1aa8 100644 --- a/packages/core/src/testing-prepare.ts +++ b/packages/core/src/testing-prepare.ts @@ -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. */ @@ -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$/; diff --git a/packages/core/src/testing-run.ts b/packages/core/src/testing-run.ts index 65fc3c945..db42e2ea5 100644 --- a/packages/core/src/testing-run.ts +++ b/packages/core/src/testing-run.ts @@ -1,3 +1,5 @@ +import { coreDeviceLaunchCode, rewriteCoreDeviceHint } from "./coredevice-errors.ts"; +import { countTestingLaunchRetry } from "./telemetry.ts"; import { spawn } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import { mkdir, mkdtemp, readFile, readdir, realpath, rm, symlink, writeFile } from "node:fs/promises"; @@ -356,6 +358,8 @@ export interface TestRunDeps { /** Kills the run's process when aborted, for a matrix lane the user cancels. */ signal?: AbortSignal; release?: () => Promise; + /** Pause before the one retry of a launch that raced the app's shutdown; tests shorten it. */ + retryDelayMs?: number; /** Called for each live `step` event, as it arrives. */ onProgress?: (progress: TestRunProgress) => void; /** The working directory a workspace run spawns from; {@link RUNNER_CWD} unless a test overrides it. */ @@ -450,6 +454,36 @@ function refusedTheConfig(result: TestRunResult): boolean { } export async function runRecordedTest(request: TestRunRequest, deps: TestRunDeps = {}): Promise { + let result = await dispatchRun(request, deps); + if (launchRacedShutdown(result)) { + // The settle in `TestingDevices.release` removes the usual cause. This is the one bounded retry for + // what it cannot see: the run died on its first launch (no step passed, so nothing it did needs + // undoing) because CoreDevice lost the app's process, which the phone clears within seconds. + await new Promise(resolve => setTimeout(resolve, deps.retryDelayMs ?? 2_000)); + if (!deps.signal?.aborted) { + const retried = await dispatchRun(request, deps); + countTestingLaunchRetry(retried.status === "passed" || !launchRacedShutdown(retried) ? "recovered" : "failed"); + result = retried; + } + } + return explainLaunchFailure(result, request.bundledTarget?.bundleId); +} + +/** A run whose very first launch failed with CoreDevice error 10004: the app's process vanished as it started. */ +function launchRacedShutdown(result: TestRunResult): boolean { + if (result.status === "passed" || result.steps.some(step => step.status === "passed")) return false; + return coreDeviceLaunchCode(`${result.error ?? ""}\n${result.steps.map(step => step.error ?? "").join("\n")}`) === "10004"; +} + +/** The runner passes agent-device's generic "unlocked, trusted" hint through; see `coredevice-errors.ts`. */ +function explainLaunchFailure(result: TestRunResult, appId?: string): TestRunResult { + if (result.status === "passed") return result; + const rewrite = (text: string | undefined) => text === undefined ? undefined : rewriteCoreDeviceHint(text, appId); + const error = rewrite(result.error); + return { ...result, ...(error === undefined ? {} : { error }), steps: result.steps.map(step => step.error === undefined ? step : { ...step, error: rewrite(step.error) }) }; +} + +async function dispatchRun(request: TestRunRequest, deps: TestRunDeps): Promise { if (request.runtime?.mode === "bundled") return runBundledTest(request, deps); if (request.projectLane) return runProjectLane(request, deps); if (request.untilSource !== undefined) return runProjectPreview(request, deps); diff --git a/packages/core/src/testing-tools.ts b/packages/core/src/testing-tools.ts index 853da9ba1..45605cdcc 100644 --- a/packages/core/src/testing-tools.ts +++ b/packages/core/src/testing-tools.ts @@ -24,7 +24,7 @@ import { ensureIosSigning, iosSigningStatus, projectStateDir, saveIosTeam, withA import { LAUNCHER_APP, createLaneExecutor } from "./testing-prepare.ts"; import type { DeviceOps } from "./testing-prepare.ts"; import { deviceIdSchema } from "@mobile-dev/shared/panel-target.ts"; -import { simulatorBundleForPid } from "./device-apps/apps.ts"; +import { physicalBundleForPid, simulatorBundleForPid } from "./device-apps/apps.ts"; import { listIosDevices } from "./ios-devices.ts"; import type { BundledModelProvider } from "./testing-run.ts"; import { answerTestingSetup, applyTestingSetup, cancelTestingSetup, inspectTestingSetup, planTestingSetup, readTestingLoginStatus, readTestingModelPreference, saveTestingModelPreference, SETUP_PROVIDERS, startTestingLogin, testingSetupProgress } from "./testing-setup.ts"; @@ -327,14 +327,15 @@ export function registerTestingTools(server: McpServer, projects: TestingProject projectPath, foregroundPlatform: z.enum(["ios", "android"]).optional(), foregroundBundleId: z.string().min(1).max(512).optional(), foregroundDeviceId: deviceIdSchema.optional().describe("With foregroundPid, for an iOS simulator app the device's app list leaves out (Apple's own apps)."), foregroundPid: z.number().int().positive().optional(), + foregroundKind: z.enum(["simulator", "physical"]).optional().describe("With foregroundPid, whether the device is a physical iPhone or iPad (resolved through devicectl) or a simulator."), }, annotations: read, _meta: appVisibility, - }, safe(async ({ projectPath: selected, foregroundPlatform, foregroundBundleId, foregroundDeviceId, foregroundPid }: { projectPath: string; foregroundPlatform?: "ios" | "android"; foregroundBundleId?: string; foregroundDeviceId?: string; foregroundPid?: number }) => { + }, safe(async ({ projectPath: selected, foregroundPlatform, foregroundBundleId, foregroundDeviceId, foregroundPid, foregroundKind }: { projectPath: string; foregroundPlatform?: "ios" | "android"; foregroundBundleId?: string; foregroundDeviceId?: string; foregroundPid?: number; foregroundKind?: "simulator" | "physical" }) => { // The panel's device list names only apps that can be monitored, so an Apple app in front (Fitness, // Settings) arrives as a pid alone. The home screen is never an app to record. const resolved = foregroundBundleId ?? (foregroundPlatform === "ios" && foregroundDeviceId && foregroundPid - ? await (matrix.foregroundBundle ?? simulatorBundleForPid)(foregroundDeviceId, foregroundPid).catch(() => undefined) : undefined); + ? await (matrix.foregroundBundle ?? (foregroundKind === "physical" ? physicalBundleForPid : simulatorBundleForPid))(foregroundDeviceId, foregroundPid).catch(() => undefined) : undefined); const bundleId = resolved && !LAUNCHER_APP.test(resolved) ? resolved : undefined; const project = await inspectProject(selected, foregroundPlatform && bundleId ? { platform: foregroundPlatform, bundleId } : undefined); const needsRuntime = project.runtimeMode === "bundled" && testingRuntimeDownload && testingRuntimeDownload.progress.phase !== "ready"; diff --git a/packages/core/test/coredevice-errors.test.ts b/packages/core/test/coredevice-errors.test.ts new file mode 100644 index 000000000..064cd6af4 --- /dev/null +++ b/packages/core/test/coredevice-errors.test.ts @@ -0,0 +1,54 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { ExpectedOperationError } from "@mobile-dev/shared/error-reporting.ts"; +import { errorHint, errorMessage } from "@mobile-dev/shared/protocol.ts"; +import { coreDeviceLaunchCode, rewriteCoreDeviceHint } from "../src/coredevice-errors.ts"; +import { withAgentDeviceHint } from "../src/ios-signing.ts"; +import { physicalIosError } from "../src/testing-prepare.ts"; + +const GENERIC = "Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry."; +const system = `Failed to launch iOS app: The application failed to launch. (com.apple.dt.CoreDeviceError error 10002 (0x2712)) Hint: ${GENERIC}`; +const raced = `open com.example.app failed: Failed to launch iOS app: The process identifier of the launched application could not be determined. It may have already terminated. (com.apple.dt.CoreDeviceError error 10004 (0x2714)) Hint: ${GENERIC}`; + +test("only 10002 and 10004 are recognised", () => { + assert.equal(coreDeviceLaunchCode(system), "10002"); + assert.equal(coreDeviceLaunchCode(raced), "10004"); + assert.equal(coreDeviceLaunchCode("CoreDeviceError error 1234"), undefined); +}); + +test("the unlock-and-trust hint is dropped for the codes it does not explain, and kept for others", () => { + const apple = rewriteCoreDeviceHint(system, "com.apple.Preferences"); + assert.doesNotMatch(apple, /unlocked, trusted/); + assert.match(apple, /Apple app/); + assert.match(rewriteCoreDeviceHint(system, "com.example.app"), /developer profile is trusted/); + const race = rewriteCoreDeviceHint(raced, "com.example.app"); + assert.doesNotMatch(race, /unlocked, trusted/); + assert.match(race, /wait a moment and try again/); + const other = `Failed to list iOS apps (CoreDeviceError error 1234) Hint: ${GENERIC}`; + assert.equal(rewriteCoreDeviceHint(other), other, "a failure this does not explain keeps its hint"); + assert.equal(rewriteCoreDeviceHint("Developer Mode is disabled. CoreDeviceError error 10002"), "Developer Mode is disabled. CoreDeviceError error 10002"); +}); + +test("agent-device launch failures reach the panel with an accurate hint, and 10004 stays a reported error", () => { + const failure = (stderr: string, appBundleId: string) => Object.assign(new Error("Failed to launch iOS app"), { details: { stderr, appBundleId, hint: GENERIC } }); + const apple = withAgentDeviceHint(failure("The application failed to launch. (com.apple.dt.CoreDeviceError error 10002 (0x2712))", "com.apple.mobilesafari"), errorHint, errorMessage) as Error; + assert.ok(apple instanceof ExpectedOperationError); + assert.doesNotMatch(apple.message, /unlocked, trusted/); + const race = withAgentDeviceHint(failure("could not be determined (com.apple.dt.CoreDeviceError error 10004 (0x2714))", "com.example.app"), errorHint, errorMessage) as Error; + assert.ok(!(race instanceof ExpectedOperationError), "a launch racing the app's shutdown is still worth knowing about"); + assert.match(race.message, /wait a moment and try again/); + const locked = Object.assign(new Error("Failed to launch iOS app"), { details: { reason: "device_locked", stderr: "CoreDeviceError error 10002", hint: GENERIC } }); + assert.match((withAgentDeviceHint(locked, errorHint, errorMessage) as Error).message, /unlocked, trusted/, "a classified lock keeps its own hint"); +}); + +test("our own devicectl launch explains 10002 and 10004 without blaming unlock or trust", () => { + const launch = (stderr: string, appId: string) => physicalIosError(Object.assign(new Error("Command failed"), { stderr }), "Opening the app", appId); + const refused = launch("ERROR: The application failed to launch. (com.apple.dt.CoreDeviceError error 10002 (0x2712))", "com.apple.Preferences"); + assert.ok(refused instanceof ExpectedOperationError); + assert.match(refused.message, /Apple app/); + assert.doesNotMatch(refused.message, /unlocked, trusted/); + const race = launch("ERROR: could not be determined. (com.apple.dt.CoreDeviceError error 10004 (0x2714))", "com.example.app"); + assert.ok(!(race instanceof ExpectedOperationError)); + assert.match(race.message, /try again/); + assert.match(launch("The device is locked. (CoreDeviceError error 10002)", "com.example.app").message, /locked\. Unlock it/, "a real lock is still named"); +}); diff --git a/packages/core/test/cpu-physical.test.ts b/packages/core/test/cpu-physical.test.ts index 119b53551..0834fb331 100644 --- a/packages/core/test/cpu-physical.test.ts +++ b/packages/core/test/cpu-physical.test.ts @@ -12,7 +12,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { cpuDeviceSchema } from "../../shared/src/cpu.ts"; import type { CpuTarget } from "../../shared/src/cpu.ts"; -import { parsePhysicalApps, runningPhysicalApps } from "../src/device-apps/apps.ts"; +import { parsePhysicalApps, parsePhysicalBundleForPid, physicalBundleForPid, runningPhysicalApps } from "../src/device-apps/apps.ts"; import { openPhysicalDebugserver } from "../src/cpu/physical.ts"; import { CpuSessions } from "../src/cpu/sessions.ts"; import { registerCpuTools } from "../src/cpu/tools.ts"; @@ -55,6 +55,38 @@ test("physical app discovery joins bundle URLs to main processes and excludes ex assert.throws(() => parsePhysicalApps(apps, malformed)); }); +test("the app in front resolves to its bundle id even when it is one of Apple's own", () => { + const apps = response({ apps: [app, + { bundleIdentifier: "com.apple.Preferences", url: "file:///Applications/Preferences.app/", builtByDeveloper: false }, + { bundleIdentifier: "com.apple.mobilesafari", url: "file:///private/var/containers/Bundle/Application/C958/MobileSafari.app/", builtByDeveloper: false }] }); + const processes = response({ runningProcesses: [ + { processIdentifier: 11, executable: "file:///Applications/Preferences.app/Preferences" }, + { processIdentifier: 12, executable: "file:///private/var/containers/Bundle/Application/C958/MobileSafari.app/MobileSafari" }, + { processIdentifier: 13, executable: appPath + "PlugIns/Extension.appex/Extension" }, + { processIdentifier: 123, executable: appPath + "Example App" }, + ] }); + assert.equal(parsePhysicalBundleForPid(apps, processes, 11), "com.apple.Preferences"); + assert.equal(parsePhysicalBundleForPid(apps, processes, 12), "com.apple.mobilesafari"); + assert.equal(parsePhysicalBundleForPid(apps, processes, 123), target.bundleId); + assert.equal(parsePhysicalBundleForPid(apps, processes, 13), undefined, "an extension is not an app to record"); + assert.equal(parsePhysicalBundleForPid(apps, processes, 999), undefined, "a pid that is not running"); + // The monitoring list is unchanged: nothing can be sampled in an Apple app. + assert.deepEqual(parsePhysicalApps(apps, processes), [{ bundleId: target.bundleId, pid: 123 }]); +}); + +test("resolving the front app asks devicectl for every app, which is what brings the preinstalled ones back", async () => { + const seen: string[][] = []; + const bundle = await physicalBundleForPid(udid, 11, undefined, async (_file, args) => { + seen.push(args); + return { stdout: args[3] === "apps" + ? response({ apps: [{ bundleIdentifier: "com.apple.Preferences", url: "file:///Applications/Preferences.app/", builtByDeveloper: false }] }) + : response({ runningProcesses: [{ processIdentifier: 11, executable: "file:///Applications/Preferences.app/Preferences" }] }) }; + }); + assert.equal(bundle, "com.apple.Preferences"); + assert.ok(seen.find(args => args[3] === "apps")?.includes("--include-all-apps")); + assert.ok(seen.every(args => args.includes(udid) && args.includes("--timeout"))); +}); + test("physical app discovery only issues bounded read-only devicectl commands and forwards cancellation", async () => { const abort = new AbortController(); const calls: string[] = []; diff --git a/packages/core/test/physical-ios-settle.test.ts b/packages/core/test/physical-ios-settle.test.ts new file mode 100644 index 000000000..bf81d45b9 --- /dev/null +++ b/packages/core/test/physical-ios-settle.test.ts @@ -0,0 +1,42 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { isHardwareUdid, settlePhysicalIos } from "../src/physical-ios-settle.ts"; + +const processes = (...executables: string[]) => ({ stdout: JSON.stringify({ result: { runningProcesses: executables.map((executable, index) => ({ processIdentifier: index + 1, executable })) } }) }); + +test("hardware UDIDs are told apart from simulator UUIDs", () => { + assert.equal(isHardwareUdid("00008150-000A5C3421B8C01C"), true); + assert.equal(isHardwareUdid("ED794517-E3AE-49DB-A8E9-E47F49119A96"), false); + assert.equal(isHardwareUdid("emulator-5554"), false); +}); + +test("settling waits until the recorder's runner has left the phone, then one grace period", async () => { + let clock = 0; + const answers = [ + processes("file:///private/var/containers/Bundle/Application/X/AgentDeviceRunnerUITests-Runner.app/AgentDeviceRunnerUITests-Runner", "file:///var/App.app/App"), + processes("file:///private/var/containers/Bundle/Application/X/AgentDeviceRunnerUITests-Runner.app/AgentDeviceRunnerUITests-Runner"), + processes("file:///var/App.app/App"), + ]; + const sleeps: number[] = []; + await settlePhysicalIos("00008150-000A5C3421B8C01C", async (file, args) => { + assert.equal(file, "/usr/bin/xcrun"); + assert.deepEqual(args.slice(0, 4), ["devicectl", "device", "info", "processes"]); + return answers.shift()!; + }, async ms => { sleeps.push(ms); clock += ms; }, () => clock); + assert.equal(answers.length, 0); + assert.deepEqual(sleeps, [500, 500, 750]); +}); + +test("a runner that never leaves does not hold the run past the bound", async () => { + let clock = 0, polls = 0; + await settlePhysicalIos("00008150-000A5C3421B8C01C", async () => { polls += 1; return processes("file:///x/AgentDeviceRunnerUITests-Runner.app/AgentDeviceRunnerUITests-Runner"); }, + async ms => { clock += ms; }, () => clock); + assert.ok(clock >= 10_000 && clock <= 11_000, `waited ${clock}ms`); + assert.ok(polls > 1); +}); + +test("a phone that cannot list processes is not waited on", async () => { + let polls = 0; + await settlePhysicalIos("00008150-000A5C3421B8C01C", async () => { polls += 1; throw new Error("unreachable"); }, async () => assert.fail("no sleeping"), () => 0); + assert.equal(polls, 1); +}); diff --git a/packages/core/test/testing-device.test.ts b/packages/core/test/testing-device.test.ts index 5dcecf7d7..a4c5f4b70 100644 --- a/packages/core/test/testing-device.test.ts +++ b/packages/core/test/testing-device.test.ts @@ -143,7 +143,7 @@ test("releasing closes the session, so the next e2e run is not refused the devic test("a physical iOS field is filled by the runner ref and the session is released", async () => { const calls: Record[] = []; - const devices = new TestingDevices(fakeAgentDevice(calls, () => ({ nodes: [{ kind: "text-field", ref: "e4", node: { role: "textbox", name: "Search", rect } }] })) as never); + const devices = new TestingDevices(fakeAgentDevice(calls, () => ({ nodes: [{ kind: "text-field", ref: "e4", node: { role: "textbox", name: "Search", rect } }] })) as never, async () => undefined); (devices as unknown as { projections: Map }).projections.set("/project", Promise.resolve(projection)); const phone = { ...target, deviceId: "00008150-0000111122223333" }; const read = await devices.read(phone); @@ -332,7 +332,7 @@ test("releaseOn waits for an in-flight physical screen read before handing the d const calls: Record[] = []; let finishSnapshot!: () => void; const pending = new Promise(resolve => { finishSnapshot = resolve; }); - const devices = new TestingDevices(fakeAgentDevice(calls, async () => { await pending; return { nodes: [] }; }) as never); + const devices = new TestingDevices(fakeAgentDevice(calls, async () => { await pending; return { nodes: [] }; }) as never, async () => undefined); (devices as unknown as { projections: Map }).projections.set("/project", Promise.resolve(projection)); const phone = { ...target, deviceId: "00008150-0000111122223333" }; const read = devices.read(phone); @@ -350,7 +350,7 @@ test("a fill lands on the field it named even after the screen was re-read and r reads += 1; // After the first read a new field appears above and the refs are renumbered. return { nodes: reads === 1 ? [field("e1", "City", 10), field("e2", "Zip", 40)] : [field("e7", "Banner", 0), field("e8", "City", 10), field("e9", "Zip", 40)] }; - }) as never); + }) as never, async () => undefined); (devices as unknown as { projections: Map }).projections.set("/project", Promise.resolve(projection)); const phone = { ...target, deviceId: "00008150-0000111122223333" }; const first = await devices.read(phone); @@ -362,3 +362,36 @@ test("a fill lands on the field it named even after the screen was re-read and r await assert.rejects(devices.fillNode(phone, "s-gone", "x"), /no longer on the current screen/); await devices.release(); }); + +test("releasing a physical iPhone waits for it to settle; a simulator is not waited on", async () => { + const calls: Record[] = []; + const order: string[] = []; + const settled: string[] = []; + const load = fakeAgentDevice(calls, () => ({ nodes: [] })); + const settle = async (deviceId: string) => { settled.push(deviceId); order.push("settle"); }; + const devices = new TestingDevices((async () => { + const module = await load(); + return { createAgentDeviceClient: () => { + const client = module.createAgentDeviceClient(); + const close = client.sessions.close; + client.sessions.close = async (options: Record) => { await close(options); order.push("close"); }; + return client; + } }; + }) as never, settle); + (devices as unknown as { projections: Map }).projections.set("/project", Promise.resolve(projection)); + const phone = { ...target, deviceId: "00008150-0000111122223333" }; + await devices.read(phone); + await devices.release(); + assert.deepEqual(order, ["close", "settle"], "the run is only handed the device after the phone let go of the runner"); + assert.deepEqual(settled, [phone.deviceId]); + await devices.read(target); + await devices.release(); + assert.deepEqual(settled, [phone.deviceId], "a simulator has no runner to wait out"); +}); + +test("a settle that fails does not fail the release", async () => { + const devices = new TestingDevices(fakeAgentDevice([], () => ({ nodes: [] })) as never, async () => { throw new Error("devicectl missing"); }); + (devices as unknown as { projections: Map }).projections.set("/project", Promise.resolve(projection)); + await devices.read({ ...target, deviceId: "00008150-0000111122223333" }); + await devices.release(); +}); diff --git a/packages/core/test/testing-run.test.ts b/packages/core/test/testing-run.test.ts index a0706cd59..94ee94059 100644 --- a/packages/core/test/testing-run.test.ts +++ b/packages/core/test/testing-run.test.ts @@ -652,3 +652,60 @@ test("the sweep removes lane files of a dead process and keeps those of a live o await sweepLaneFiles(root); assert.deepEqual((await readdir(root)).filter(name => name !== "node_modules").sort(), [`${LANE_FILE_PREFIX}${process.pid}-live.ts`, "e2e.config.ts"].sort()); }); + +const GENERIC_HINT = "Hint: Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry."; +const RACED = `open com.example.app failed: Failed to launch iOS app: The process identifier of the launched application could not be determined. (com.apple.dt.CoreDeviceError error 10004 (0x2714)) ${GENERIC_HINT}`; + +/** A spawner that answers each call with the next canned report, so a retry sees a different run. */ +function sequence(reports: unknown[], launches: { count: number }) { + return ((command: string, args: readonly string[], options: { cwd?: string }) => { + const next = reports[Math.min(launches.count, reports.length - 1)]; + launches.count += 1; + return spawner(JSON.stringify(next), next === reports[reports.length - 1] && (next as { run: { status: string } }).run.status === "passed" ? 0 : 1)(command, args, options as never); + }) as never; +} +const failedOpen = (message: string) => ({ ...report([], "failed"), run: { ...report([], "failed").run, errors: [{ message }] } }); + +test("a run that died on its first launch with CoreDevice 10004 is started once more, and the second answer stands", async () => { + const root = await project(); + const launches = { count: 0 }; + let released = 0; + const result = await runRecordedTest({ projectPath: root, relativePath: FILE }, { + release: async () => { released += 1; }, retryDelayMs: 0, + spawner: sequence([failedOpen(RACED), report([{ line: 8, status: "passed" }])], launches), + }); + assert.equal(launches.count, 2); + assert.equal(result.status, "passed"); + assert.equal(released, 2, "each attempt hands the device over before it spawns"); +}); + +test("the retry is bounded and its failure keeps an accurate hint instead of unlock-and-trust", async () => { + const root = await project(); + const launches = { count: 0 }; + const result = await runRecordedTest({ projectPath: root, relativePath: FILE }, { retryDelayMs: 0, spawner: sequence([failedOpen(RACED)], launches) }); + assert.equal(launches.count, 2, "one retry, never a loop"); + assert.equal(result.status, "failed"); + assert.doesNotMatch(result.error ?? "", /unlocked, trusted/); + assert.match(result.error ?? "", /wait a moment and try again/); +}); + +test("a run that got past its first step, or failed for any other reason, is never started again", async () => { + const root = await project(); + for (const reports of [ + [{ ...report([{ line: 8, status: "passed" }], "failed"), run: { ...report([{ line: 8, status: "passed" }], "failed").run, errors: [{ message: RACED }] } }], + [failedOpen("Timed out waiting for Explore")], + [failedOpen(RACED.replace("10004", "10002"))], + ]) { + const launches = { count: 0 }; + await runRecordedTest({ projectPath: root, relativePath: FILE }, { retryDelayMs: 0, spawner: sequence(reports, launches) }); + assert.equal(launches.count, 1); + } +}); + +test("a 10002 refusal of an Apple app is explained as such, not as a locked or untrusted phone", async () => { + const root = await project(); + const message = `open com.apple.Preferences failed: Failed to launch iOS app: The application failed to launch. (com.apple.dt.CoreDeviceError error 10002 (0x2712)) ${GENERIC_HINT}`; + const result = await runRecordedTest({ projectPath: root, relativePath: FILE, runtime: { mode: "bundled", root }, bundledTarget: { platform: "ios", bundleId: "com.apple.Preferences", device: "x" } } as never, { retryDelayMs: 0, spawner: sequence([failedOpen(message)], { count: 0 }) }).catch(error => error); + // A bundled run needs its runtime; what matters is that no path reports the generic hint for this code. + assert.doesNotMatch(String(result.error ?? result.message ?? ""), /unlocked, trusted/); +}); diff --git a/packages/ui/src/testing-panel.ts b/packages/ui/src/testing-panel.ts index 5ed06b76d..0722d7f3f 100644 --- a/packages/ui/src/testing-panel.ts +++ b/packages/ui/src/testing-panel.ts @@ -628,7 +628,7 @@ export class TestingPanel { try { const platform = recordablePlatform(device); const response = await this.call("mobile_testing_project_config", { projectPath, foregroundPlatform: platform, - ...(foregroundBundleId ? { foregroundBundleId } : { foregroundDeviceId: device.udid, foregroundPid: pid }) }); + ...(foregroundBundleId ? { foregroundBundleId } : { foregroundDeviceId: device.udid, foregroundPid: pid, ...(device.kind === "physical" ? { foregroundKind: "physical" } : {}) }) }); if (revision !== this.loadRevision || this.snapshot.runtimeMode !== "bundled") return; const data = object(response.structuredContent) ?? {}; const targets = parseTargets(data); diff --git a/packages/ui/test/testing-panel.test.ts b/packages/ui/test/testing-panel.test.ts index c81d943f0..0e91152c2 100644 --- a/packages/ui/test/testing-panel.test.ts +++ b/packages/ui/test/testing-panel.test.ts @@ -590,3 +590,21 @@ test("an Apple app in front replaces the last app's target in No project mode in assert.equal(calls.filter(call => call.name === "mobile_testing_project_config").length, 1, "the same unnamed app is read once"); } finally { panel.dispose(); } }); + +test("a physical iPhone's front app known only by its pid is resolved as a physical device", async () => { + const listeners = new Set<() => void>(); + let snapshot: Record = { device: { udid: "00008150-000A5C3421B8C01C", name: "iPhone", state: "connected", pairingState: "paired", runtime: "", platform: "ios", kind: "physical" }, apps: [], foregroundApp: { bundleId: "com.bare.rn", pid: 2 }, ready: true }; + const apps = { subscribe: (listener: () => void) => { listeners.add(listener); return () => listeners.delete(listener); }, getSnapshot: () => snapshot } as unknown as DeviceAppsStore; + const calls: { name: string; arguments: Record }[] = []; + const panel = new TestingPanel(host({ mobile_testing_project_config: { runtimeMode: "bundled", targetSource: "foreground", targets: [{ name: "ios", platform: "ios", bundleId: "com.apple.Preferences" }] } }, calls), apps); + panel.setAvailable(true); + (panel as unknown as { update(fields: Record): void }).update({ projectPath: PROJECT, studioPath: PROJECT, runtimeMode: "bundled", targetSource: "foreground", targets: [{ name: "ios", platform: "ios", bundleId: "com.bare.rn" }] }); + snapshot = { ...snapshot, foregroundApp: { bundleId: null, pid: 9 } }; + for (const listener of listeners) listener(); + await new Promise(resolve => setTimeout(resolve, 0)); + try { + const read = calls.find(call => call.name === "mobile_testing_project_config"); + assert.deepEqual(read?.arguments, { projectPath: PROJECT, foregroundPlatform: "ios", foregroundDeviceId: "00008150-000A5C3421B8C01C", foregroundPid: 9, foregroundKind: "physical" }); + assert.equal(panel.target?.bundleId, "com.apple.Preferences"); + } finally { panel.dispose(); } +});