diff --git a/docs/telemetry.md b/docs/telemetry.md index a14c0595..9d3124ed 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -936,3 +936,5 @@ names, packages, service lists, paths, command arguments, CLI output or preferen contents are attached. There are no background samplers or per-frame spans for 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 ``; log paths, team IDs, identities and device identifiers are never sent. diff --git a/packages/core/src/agent-device-runtime.ts b/packages/core/src/agent-device-runtime.ts index c3ddf4b5..2efb546c 100644 --- a/packages/core/src/agent-device-runtime.ts +++ b/packages/core/src/agent-device-runtime.ts @@ -9,6 +9,7 @@ import { homedir, tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; +import { SIGNING_ENV_KEYS } from "./ios-signing.ts"; import { startStorageMetrics } from "./storage-metrics.ts"; import { captureServerError } from "./telemetry.ts"; @@ -83,7 +84,8 @@ export class AgentDeviceRuntime { private environment(directory: string) { const env: Record = {}; for (const [key, value] of Object.entries(process.env)) { - if (key.startsWith("AGENT_DEVICE_") === false && value !== undefined) env[key] = value; + // Signing variables are the user's (or Testing Studio's resolved team); the rest of AGENT_DEVICE_* is ours. + if (value !== undefined && (key.startsWith("AGENT_DEVICE_") === false || (SIGNING_ENV_KEYS as readonly string[]).includes(key))) env[key] = value; } env.AGENT_DEVICE_CONFIG = this.config; env.AGENT_DEVICE_STATE_DIR = directory; diff --git a/packages/core/src/ios-device-build.ts b/packages/core/src/ios-device-build.ts new file mode 100644 index 00000000..a288b414 --- /dev/null +++ b/packages/core/src/ios-device-build.ts @@ -0,0 +1,49 @@ +import { readdir, stat } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import type { Commands } from "./app-control/commands.ts"; + +/** + * A build of the app made for physical devices, found where Xcode and Expo leave them. + * + * Only `*-iphoneos` products qualify: a `Debug-iphonesimulator` app has the simulator slice and no + * provisioning profile, so it cannot run on hardware however it is installed. The newest build whose + * `CFBundleIdentifier` matches wins. Roots are the project's own `ios/build` (`expo run:ios --device`) + * and Xcode's DerivedData. + */ + +async function modified(path: string): Promise { return (await stat(path).catch(() => undefined))?.mtimeMs ?? 0; } + +async function appsIn(directory: string): Promise { + const entries = await readdir(directory).catch(() => [] as 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 { + const products: string[] = []; + 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 (projectPath) await productsOf(join(projectPath, "ios", "build", "Build", "Products")); + const derived = join(home, "Library", "Developer", "Xcode", "DerivedData"); + for (const project of await readdir(derived).catch(() => [] as string[])) await productsOf(join(derived, project, "Build", "Products")); + return products; +} + +export async function findDeviceBuild(appId: string, commands: Pick, projectPath?: string, home?: string): Promise { + const candidates: { path: string; time: number }[] = []; + for (const directory of await deviceProductDirectories(projectPath, home)) { + 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; + } catch { /* an unreadable bundle is not a match */ } + } + return undefined; +} diff --git a/packages/core/src/ios-signing.ts b/packages/core/src/ios-signing.ts new file mode 100644 index 00000000..03128b1c --- /dev/null +++ b/packages/core/src/ios-signing.ts @@ -0,0 +1,313 @@ +import { execFile } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +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"; + +/** + * Code signing for the XCTest runner agent-device builds for a physical iPhone. + * + * agent-device signs the runner with Automatic signing and only the team it is told about, so + * without `AGENT_DEVICE_IOS_TEAM_ID` `xcodebuild build-for-testing` fails on hardware. The team is + * resolved in this order, first hit wins: + * + * 1. `MOBILE_DEV_IOS_TEAM_ID`, Mobile Dev's own setting, then an already-set `AGENT_DEVICE_IOS_TEAM_ID`. + * 2. The team the user chose in Testing Studio's E2E setup (saved next to the model preference). + * 3. The project's `DEVELOPMENT_TEAM` build setting, when every target agrees. + * 4. The one team behind the Apple Development identities in the keychain. + * + * More than one candidate is never guessed between: the user names the team. + */ + +const execute = promisify(execFile); + +export type SigningCommand = (file: string, args: string[]) => Promise; +const defaultCommand: SigningCommand = async (file, args) => (await execute(file, args, { encoding: "utf8", timeout: 15_000, maxBuffer: 4 * 1024 * 1024 })).stdout; + +const TEAM_ID = /^[A-Z0-9]{10}$/; + +export const SIGNING_SETUP_HINT = "Choose your signing team in E2E setup → Devices (or set MOBILE_DEV_IOS_TEAM_ID to your 10-character Apple Developer Team ID; find it in Xcode → Settings → Accounts), then try again."; + +/** Where the user's chosen team is saved: beside the Testing Studio model preference. */ +const SIGNING_TEAM_FILE = join(TESTING_DIRECTORY, "ios-signing-team.json"); + +export type SigningTeamSource = "env" | "user" | "project" | "keychain"; +export type SigningTeam = { id: string; name?: string }; + +/** The team the user chose in the panel, if any and still well-formed. */ +export async function readSavedIosTeam(file: string = SIGNING_TEAM_FILE): Promise { + try { + const team = String((JSON.parse(await readFile(file, "utf8")) as { teamId?: unknown }).teamId ?? "").trim().toUpperCase(); + return TEAM_ID.test(team) ? team : undefined; + } catch { return undefined; } +} + +/** Saves the user's team, or clears the choice when `teamId` is undefined. */ +export async function saveIosTeam(teamId: string | undefined, file: string = SIGNING_TEAM_FILE): Promise { + if (!teamId) { await unlink(file).catch(() => undefined); return; } + const team = teamId.trim().toUpperCase(); + if (!TEAM_ID.test(team)) throw new ExpectedOperationError("invalid_input", "A signing team is 10 letters or digits."); + await mkdir(dirname(file), { recursive: true, mode: 0o700 }); + const temporary = `${file}.${randomUUID()}.tmp`; + try { + await writeFile(temporary, JSON.stringify({ teamId: team }, null, 2) + "\n", { mode: 0o600 }); + await rename(temporary, file); + } finally { await unlink(temporary).catch(() => undefined); } +} + +/** The explicit team: Mobile Dev's setting first, then agent-device's own variable. */ +export const TEAM_ENV_VARS = ["MOBILE_DEV_IOS_TEAM_ID", "AGENT_DEVICE_IOS_TEAM_ID"] as const; +export type TeamEnvVar = (typeof TEAM_ENV_VARS)[number]; + +/** The explicit team and the variable that named it. */ +export function configuredTeam(env: NodeJS.ProcessEnv = process.env): { teamId: string; envVar: TeamEnvVar } | undefined { + for (const envVar of TEAM_ENV_VARS) { + const team = env[envVar]?.trim().toUpperCase(); + if (team && TEAM_ID.test(team)) return { teamId: team, envVar }; + } + return undefined; +} + +export function configuredTeamId(env: NodeJS.ProcessEnv = process.env): string | undefined { + return configuredTeam(env)?.teamId; +} + +/** Every distinct `DEVELOPMENT_TEAM = XXXXXXXXXX;` in a project file. */ +export function developmentTeams(pbxproj: string): string[] { + const teams = new Set(); + for (const match of pbxproj.matchAll(/DEVELOPMENT_TEAM\s*=\s*"?([A-Z0-9]{10})"?\s*;/g)) teams.add(match[1]!); + return [...teams]; +} + +/** The team the project at `projectPath` is signed with, when `ios/*.xcodeproj` names exactly one. */ +async function projectTeam(projectPath: string): Promise { + const teams = new Set(); + for (const directory of [projectPath, join(projectPath, "ios")]) { + const entries = await readdir(directory).catch(() => [] as string[]); + for (const entry of entries.filter(name => name.endsWith(".xcodeproj"))) { + const text = await readFile(join(directory, entry, "project.pbxproj"), "utf8").catch(() => ""); + for (const team of developmentTeams(text)) teams.add(team); + } + } + return teams.size === 1 ? [...teams][0] : undefined; +} + +/** The common names of `Apple Development` identities in `security find-identity -v -p codesigning` output. */ +export function developmentIdentities(output: string): string[] { + const names = new Set(); + for (const match of output.matchAll(/^\s*\d+\)\s+[0-9A-F]{40}\s+"((?:Apple Development|iPhone Developer):[^"]+)"/gm)) names.add(match[1]!); + return [...names]; +} + +/** The team (organizational unit) in an `openssl x509 -subject` line. */ +export function teamFromSubject(subject: string): string | undefined { + const match = /OU\s*=\s*([A-Z0-9]{10})/.exec(subject); + return match?.[1]; +} + +/** The organization (`O=`) in an `openssl x509 -subject` line: the team's display name. */ +export function teamNameFromSubject(subject: string): string | undefined { + const match = /(?:^|[,/\s])O\s*=\s*((?:\\.|[^,/\n])+)/.exec(subject); + const name = match?.[1]?.replace(/\\(.)/g, "$1").trim(); + return name || undefined; +} + +/** The distinct teams behind the keychain's Apple Development identities, with names where the certificate gives one. */ +export async function identityTeams(run: SigningCommand): Promise { + let output: string; + try { output = await run("/usr/bin/security", ["find-identity", "-v", "-p", "codesigning"]); } catch { return []; } + const teams = new Map(); + for (const name of developmentIdentities(output)) { + try { + const pem = await run("/usr/bin/security", ["find-certificate", "-c", name, "-p"]); + const subject = await new Promise((resolve, reject) => { + const child = execFile("/usr/bin/openssl", ["x509", "-noout", "-subject", "-nameopt", "RFC2253"], { encoding: "utf8", timeout: 10_000 }, (error, stdout) => error ? reject(error) : resolve(stdout)); + child.stdin?.end(pem); + }); + // RFC2253 prints `OU=XXXXXXXXXX`. + const id = teamFromSubject(subject); + if (id && !teams.get(id)?.name) teams.set(id, { id, ...(teamNameFromSubject(subject) ? { name: teamNameFromSubject(subject)! } : {}) }); + } catch { /* an identity we cannot read is not a candidate */ } + } + return [...teams.values()]; +} + +/** The bundle id the runner is built as. It must be unique to the team, so the team is in it. */ +export function runnerBundleId(teamId: string): string { + return `com.mobiledev.agentdevice.${teamId.toLowerCase()}`; +} + +export interface ResolveOptions { env?: NodeJS.ProcessEnv; projectPath?: string; run?: SigningCommand; daemons?: DaemonRestartOptions; /** The saved-choice file; tests only. */ savedTeamFile?: string } + +/** The team this process last exported to `AGENT_DEVICE_IOS_TEAM_ID` itself: Mobile Dev's own write, not the user's setting. */ +let exportedTeamId: string | undefined; + +/** The environment as the user set it: without the team this process exported on an earlier resolution, or that export would pin the team forever. */ +function userEnvironment(env: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv { + if (env) return env; + if (exportedTeamId && process.env.AGENT_DEVICE_IOS_TEAM_ID?.trim().toUpperCase() === exportedTeamId) return { ...process.env, AGENT_DEVICE_IOS_TEAM_ID: undefined }; + return process.env; +} + +/** The team and where it came from, or an error that says how to name one. */ +export async function resolveIosTeam(options: ResolveOptions = {}): Promise<{ teamId: string; source: SigningTeamSource; envVar?: TeamEnvVar }> { + const explicit = configuredTeam(userEnvironment(options.env)); + if (explicit) return { ...explicit, source: "env" }; + const saved = await readSavedIosTeam(options.savedTeamFile); + if (saved) return { teamId: saved, source: "user" }; + const project = options.projectPath ? await projectTeam(options.projectPath) : undefined; + if (project) return { teamId: project, source: "project" }; + const teams = await identityTeams(options.run ?? defaultCommand); + if (teams.length === 1) return { teamId: teams[0]!.id, source: "keychain" }; + if (teams.length === 0) + throw new ExpectedOperationError("invalid_input", `Testing on an iPhone needs a signing team for the test runner, and none was found: this project does not name a DEVELOPMENT_TEAM and the keychain has no Apple Development identity. Sign in to Xcode with your Apple ID, then ${SIGNING_SETUP_HINT}`); + throw new ExpectedOperationError("invalid_input", `The keychain has Apple Development identities for ${teams.length} teams (${teams.map(team => team.name ? `${team.name} ${team.id}` : team.id).join(", ")}), so Mobile Dev cannot choose the one that signs the test runner. ${SIGNING_SETUP_HINT}`); +} + +/** The signing team for the runner, or an error that says how to name one. */ +export async function resolveIosTeamId(options: ResolveOptions = {}): Promise { + return (await resolveIosTeam(options)).teamId; +} + +export type IosSigningStatus = { + teams: SigningTeam[]; + /** The team the runner would be signed with now; absent when none resolves. */ + resolved?: SigningTeam & { source: SigningTeamSource; /** The variable that pinned the team, when source is env. */ envVar?: TeamEnvVar }; + /** The user's saved choice, which an env setting overrides. */ + saved?: string; + /** Why nothing resolves. */ + error?: string; +}; + +/** What the Testing Studio picker shows: the keychain's teams, the saved choice, and the team in effect. */ +export async function iosSigningStatus(options: ResolveOptions = {}): Promise { + const teams = await identityTeams(options.run ?? defaultCommand); + const saved = await readSavedIosTeam(options.savedTeamFile); + const status: IosSigningStatus = { teams, ...(saved ? { saved } : {}) }; + try { + const { teamId, source, envVar } = await resolveIosTeam(options); + const known = teams.find(team => team.id === teamId); + status.resolved = { id: teamId, ...(known?.name ? { name: known.name } : {}), source, ...(envVar ? { envVar } : {}) }; + } catch (error) { status.error = error instanceof Error ? error.message : String(error); } + return status; +} + +/** The signing variables agent-device reads, for one team. A runner bundle id the user set stays. */ +export function iosSigningEnv(teamId: string, userBundleId?: string): Record { + return { + AGENT_DEVICE_IOS_TEAM_ID: teamId, + AGENT_DEVICE_IOS_BUNDLE_ID: userBundleId?.trim() || runnerBundleId(teamId), + }; +} + +/** Variables the agent-device runtime process may inherit; the rest of `AGENT_DEVICE_*` is Mobile Dev's own. */ +export const SIGNING_ENV_KEYS = ["AGENT_DEVICE_IOS_TEAM_ID", "AGENT_DEVICE_IOS_BUNDLE_ID", "AGENT_DEVICE_IOS_SIGNING_IDENTITY", "AGENT_DEVICE_IOS_PROVISIONING_PROFILE"] as const; + +/** The runner bundle id this module exported, so a later team change can replace it but a user's own value never is. */ +let exportedBundleId: string | undefined; + +/** + * Resolves the team and exports it to this process, which is where the in-process agent-device + * client and the spawned e2e runner both read it. A failure is not cached. + */ +export async function ensureIosSigning(options: ResolveOptions = {}): Promise { + const { teamId, source } = await resolveIosTeam(options); + if (options.env) return teamId; + // Only a team Mobile Dev chose is its own export; one the user's environment named stays theirs. + exportedTeamId = source === "env" ? undefined : teamId; + const current = process.env.AGENT_DEVICE_IOS_BUNDLE_ID; + const user = current && current !== exportedBundleId ? current : undefined; + const signing = iosSigningEnv(teamId, user); + Object.assign(process.env, signing); + exportedBundleId = user ? undefined : signing.AGENT_DEVICE_IOS_BUNDLE_ID; + // Once per signing: a daemon that predates it would keep building the runner without a team. + const signature = JSON.stringify(signing); + if (checkedSigning !== signature) { checkedSigning = signature; await restartStaleDaemons(signing, options.daemons).catch(() => []); } + return teamId; +} + +export interface DaemonRestartOptions { + /** State directories whose daemon may be stopped; by default only Mobile Dev's pinned one. */ + stateDirs?: string[]; + readFile?: (path: string) => Promise; + /** `ps eww -p ` output: the command line and environment of the process. */ + processEnvironment?: (pid: number) => Promise; + kill?: (pid: number) => void; +} + +const defaultProcessEnvironment = async (pid: number): Promise => + (await execute("/bin/ps", ["eww", "-o", "command=", "-p", String(pid)], { encoding: "utf8", timeout: 5_000 })).stdout; + +/** + * Stops an agent-device daemon that was started without this signing. + * + * A daemon reads `AGENT_DEVICE_IOS_TEAM_ID` once, from the environment it was started in, and every + * later client reuses it. One started from a terminal, or before the team was chosen, keeps failing + * `build-for-testing` with a provisioning error however the next run is configured. The next client + * starts a fresh daemon from this process's environment, so the stale one is simply asked to stop. + * Only a process that is an agent-device daemon and does not carry this team and bundle id is touched. + * Returns the pids stopped. + */ +export async function restartStaleDaemons(signing: Record, options: DaemonRestartOptions = {}): Promise { + const read = options.readFile ?? ((path: string) => readFile(path, "utf8")); + const environmentOf = options.processEnvironment ?? defaultProcessEnvironment; + const kill = options.kill ?? ((pid: number) => process.kill(pid, "SIGTERM")); + // Only Mobile Dev's own daemons: one under `~/.agent-device`, or a state dir the user set, may be + // serving their own agent-device work and is not ours to stop. + const dirs = options.stateDirs ?? await mobileDevStateDirs(); + const stopped: number[] = []; + for (const dir of dirs) { + let pid = NaN; + try { pid = Number((JSON.parse(await read(join(dir, "daemon.json"))) as { pid?: unknown }).pid); } catch { continue; } + if (!Number.isInteger(pid) || pid <= 1 || stopped.includes(pid)) continue; + const environment = await environmentOf(pid).catch(() => ""); + if (!/agent-device/.test(environment) || !/daemon/.test(environment)) continue; + const carries = Object.entries(signing).every(([key, value]) => environment.includes(`${key}=${value}`)); + if (carries) continue; + try { kill(pid); stopped.push(pid); } catch { /* already gone */ } + } + return stopped; +} + +let checkedSigning: string | undefined; + +/** + * Where a project-mode run on iOS hardware keeps its agent-device state: one folder per project, under + * the app's directory. Such a run cannot share the app's folder (the project's agent-device is another + * build, and a daemon refuses a client of a different version), and the terminal's `~/.agent-device` + * may hold a daemon started without the signing team, which is the user's and not ours to stop. A + * folder of our own gets a daemon started from this process's signed environment, and a stale one + * left there by an earlier process is restarted like the app's own. + */ +export const PROJECT_STATE_ROOT = join(APP_FLOW_DIRECTORY, "agent-device-projects"); + +export function projectStateDir(projectPath: string): string { + return join(PROJECT_STATE_ROOT, createHash("sha256").update(projectPath).digest("hex").slice(0, 16)); +} + +async function mobileDevStateDirs(): Promise { + const projects = await readdir(PROJECT_STATE_ROOT, { withFileTypes: true }).catch(() => []); + return [join(APP_FLOW_DIRECTORY, "agent-device"), ...projects.filter(entry => entry.isDirectory()).map(entry => join(PROJECT_STATE_ROOT, entry.name))]; +} + +/** Forgets what was exported; tests only. */ +export function resetIosSigning(): void { exportedBundleId = undefined; exportedTeamId = undefined; checkedSigning = undefined; } + +/** Runner startup classes agent-device names in `details.reason` that the user fixes on their machine. */ +const USER_FIXABLE_REASONS = /^(?:signing_|bundle_identifier_already_registered|devtools_security_|developer_mode|device_locked|not_ready)/; + +/** + * Turns an agent-device failure the user can fix (signing, Developer Mode, a locked or unreachable + * phone) into an expected one that carries agent-device's hint, so it reaches the panel as an + * instruction and is not reported as a plugin bug. Anything else is returned unchanged. + */ +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 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)); +} diff --git a/packages/core/src/telemetry.ts b/packages/core/src/telemetry.ts index 7353d72f..72edec98 100644 --- a/packages/core/src/telemetry.ts +++ b/packages/core/src/telemetry.ts @@ -110,7 +110,7 @@ export function recordTestingAgentRead(outcome: "success" | "failed", duration: * 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. */ -export function recordTestingSetupOperation(operation: "plan" | "apply" | "login" | "preference", outcome: "started" | "succeeded" | "failed" | "cancelled", provider: string = "none") { +export function recordTestingSetupOperation(operation: "plan" | "apply" | "login" | "preference" | "signing", outcome: "started" | "succeeded" | "failed" | "cancelled", provider: string = "none") { if (process.env.MOBILE_DEV_TELEMETRY === "off") return; const allowed = ["none", "vercel", "openrouter", "openai-compatible", "chatgpt", "copilot", "opencode-console", "grok"]; const attributes = { component: "server", surface: "testing", operation, outcome, provider: allowed.includes(provider) ? provider : "other" }; diff --git a/packages/core/src/testing-agent.ts b/packages/core/src/testing-agent.ts index ecc44db7..01199b88 100644 --- a/packages/core/src/testing-agent.ts +++ b/packages/core/src/testing-agent.ts @@ -390,8 +390,9 @@ export class TestingAgentRecordings { let device: { deviceId: string; platform: "ios" | "android"; name?: string } | undefined; if (reported?.deviceId) { if (reported.kind === "physical") { - if (reported.platform !== "ios" || !ops?.physicalIos) refused("Physical Android recording is not available yet."); - await ops.physicalIos.ready(reported.deviceId); + const physical = reported.platform === "ios" ? ops?.physicalIos : ops?.physicalAndroid; + if (!physical) refused("Physical device recording is unavailable on this server."); + await physical.ready(reported.deviceId); } device = { deviceId: reported.deviceId, platform: reported.platform }; } @@ -405,7 +406,7 @@ export class TestingAgentRecordings { let bundleId = ""; if (device) { - const front = reported?.kind === "physical" ? null : ops?.foregroundApp ? await ops.foregroundApp(device.platform, device.deviceId).catch(() => null) : null; + const front = reported?.kind === "physical" && device.platform === "ios" ? null : ops?.foregroundApp ? await ops.foregroundApp(device.platform, device.deviceId).catch(() => null) : null; const foreground = front && !LAUNCHER_APP.test(front) ? front : ""; if (bundled) { bundleId = foreground || reported?.bundleId || ""; diff --git a/packages/core/src/testing-device.ts b/packages/core/src/testing-device.ts index 443d3fe0..5e90dcbe 100644 --- a/packages/core/src/testing-device.ts +++ b/packages/core/src/testing-device.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; @@ -196,19 +197,46 @@ function depthOf(entry: ProjectedNode): number { return depth; } +/** + * An id for a component that follows the element, not its position in one read. + * + * The projection mints `n1…nK` per read, so the same field has a different id after the screen + * re-reads, and a fill that arrives after a queued read would land on whichever element now holds + * that number. Derived from what identifies the element (role, names, box), the id is the same + * across reads while the element is, and simply absent when it is not. The typed `value` is left + * out so a field keeps its id while it is being filled. Identical siblings are told apart by order. + */ +function stableId(component: ScreenComponent, seen: Map): string { + const { x, y, width, height } = component.bounds; + const key = [component.role, component.label, component.text, component.identifier, component.placeholder, Math.round(x), Math.round(y), Math.round(width), Math.round(height)].join("\u0000"); + const occurrence = seen.get(key) ?? 0; + seen.set(key, occurrence + 1); + return `s${createHash("sha1").update(key).digest("hex").slice(0, 10)}${occurrence ? `-${occurrence}` : ""}`; +} + export function projectedComponents(projection: EngineProjection, nodes: readonly unknown[]): TestingDeviceTree { let minted = 0; const snapshot = projection.projectSnapshot(nodes, { mintId: () => `n${++minted}` }); const tree: ScreenComponent[] = []; const refs: Record = {}; + const ids = new Map(); + const seen = new Map(); for (const entry of snapshot.index) { const component = toComponent(entry, depthOf(entry)); if (!component) continue; + const id = stableId(component, seen); + ids.set(entry.id, id); + component.nodeId = id; + // A parent without a box is not in the tree; the child then has no parent link, as before. + if (component.parentId !== undefined) { + const parent = ids.get(component.parentId); + if (parent) component.parentId = parent; else delete component.parentId; + } tree.push(component); // agent-device's own refs are `@e20`; the projection strips the `@` for its own use, and // `interactions.click({ ref })` parses a bare `e20` as a selector and refuses it. So the // sigil is put back here, at the one boundary that hands a ref to agent-device. - if (entry.ref) refs[entry.id] = entry.ref.startsWith("@") ? entry.ref : `@${entry.ref}`; + if (entry.ref) refs[id] = entry.ref.startsWith("@") ? entry.ref : `@${entry.ref}`; } return { tree, refs, ...(snapshot.viewport ? { screen: snapshot.viewport } : {}) }; } @@ -325,9 +353,18 @@ export class TestingDevices { return projected; } + /** + * Enters the recorded text into the field the panel named. + * + * The panel's fill is fire-and-forget behind its own refresh, so a read can be queued ahead of + * it and the refs from the read the panel acted on are gone. The field is therefore found again + * on a fresh snapshot, by its stable id, and the fill waits its turn in the queue like any read. + * A field that moved or went away is refused, never filled on a neighbour. + */ async fillNode(target: TestingDeviceTarget, nodeId: string, text: string): Promise { const fill = async () => { - const ref = this.attached === this.key(target) ? this.lastRefs[nodeId] : undefined; + await this.readOnce(target); + const ref = this.lastRefs[nodeId]; if (!ref) throw new ExpectedOperationError("invalid_input", "The selected text field is no longer on the current screen. Read the screen and record the step again."); await this.performOnce(target, { kind: "type", ref, text }); }; diff --git a/packages/core/src/testing-prepare.ts b/packages/core/src/testing-prepare.ts index f035349e..861d47b3 100644 --- a/packages/core/src/testing-prepare.ts +++ b/packages/core/src/testing-prepare.ts @@ -1,7 +1,7 @@ import { join } from "node:path"; import { ExpectedOperationError } from "@mobile-dev/shared/error-reporting.ts"; import { udidSchema } from "@mobile-dev/shared/protocol.ts"; -import { systemCommands, withTemporaryDirectory } from "./app-control/commands.ts"; +import { commandError, commandOutput, systemCommands, withTemporaryDirectory } from "./app-control/commands.ts"; import type { Commands } from "./app-control/commands.ts"; import type { DriverFactory } from "./app-control/tools.ts"; import type { ServeEmu } from "./serve-emu.ts"; @@ -9,6 +9,8 @@ import type { Simctl } from "./simctl.ts"; 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 { findDeviceBuild } from "./ios-device-build.ts"; /** Home screens and system UI, which are never the app to record. */ export const LAUNCHER_APP = /^com\.apple\.springboard$|^com\.android\.systemui$|launcher/i; @@ -17,11 +19,27 @@ export const LAUNCHER_APP = /^com\.apple\.springboard$|^com\.android\.systemui$| export interface MatrixAppIds { ios?: string; android?: string } /** What preparing a device needs from the machine; faked in tests. */ +export interface PhysicalDeviceOps { + /** Connected and usable (for Android: adb-authorized, awake, unlocked); throws what to fix. */ + ready(deviceId: string, options?: { projectPath?: string }): Promise; + hasApp(deviceId: string, appId: string): Promise; + launch(deviceId: string, appId: string): Promise; + /** Android only: installs the app from the first of `sources` (other devices) that has a compatible build. */ + installFrom?(deviceId: string, appId: string, sources: string[]): Promise<"installed" | "no_source">; +} + export interface DeviceOps { + physicalAndroid?: PhysicalDeviceOps; physicalIos?: { - ready(deviceId: string): Promise; + /** Paired, connected, Developer Mode on, and a signing team for the runner; throws what to fix. */ + ready(deviceId: string, options?: { projectPath?: string }): Promise; hasApp(deviceId: string, appId: string): Promise; launch(deviceId: string, appId: string): Promise; + /** + * Installs a device build of the app that is already on this Mac (never a simulator build). + * Resolves "no_build" when none matches, so the caller can say how to build one. + */ + install?(deviceId: string, appId: string, options?: { projectPath?: string }): Promise<"installed" | "no_build">; }; isBooted(platform: MatrixPlatform, deviceId: string): Promise; /** Boots the device and waits for it to be usable. Returns the id to run on (an Android AVD becomes a serial). */ @@ -44,6 +62,8 @@ export interface LaneExecutorDeps { * A device that lacks the app gets it copied from another booted device that has it, as in bundled mode. */ projectMode?: boolean; + /** The project whose build output is searched for a device build to install. */ + projectPath?: string; runTest(lane: Lane, deviceId: string, signal: AbortSignal, onProgress: (progress: TestRunProgress) => void): Promise; } @@ -60,11 +80,35 @@ export function createLaneExecutor(deps: LaneExecutorDeps): LaneExecutor { const appId = deps.apps[lane.platform]; if (!appId) throw new ExpectedOperationError("invalid_input", `No ${lane.platform === "ios" ? "iOS bundle id" : "Android package"} was given for this run, so ${lane.deviceName} cannot run it.`); let deviceId = lane.deviceId; + if (lane.kind === "physical" && lane.platform === "android") { + const physical = deps.ops.physicalAndroid; + if (!physical?.installFrom) throw new ExpectedOperationError("unsupported_platform", "Physical Android runs are unavailable on this server."); + await physical.ready(deviceId, { projectPath: deps.projectPath }); + signal.throwIfAborted(); + if (!await physical.hasApp(deviceId, appId)) { + setState("installing"); + // An APK can be copied between devices, unlike an iOS build. A phone is preferred as the source + // because its ABIs match; the install is checked against this phone's ABIs. + const sources = await androidSources(deps.ops, lane, lanes, deviceId, appId); + const result = await physical.installFrom(deviceId, appId, sources); + if (result === "no_source") throw new ExpectedOperationError("app_unavailable", `App not installed: ${appId} is not on ${lane.deviceName}, and no other connected device has it to copy. Build and install it on this phone (for an Expo app, \`npx expo run:android --device\`), then run again.`); + } + signal.throwIfAborted(); + if (!deps.projectMode) await physical.launch(deviceId, appId); + return deviceId; + } if (lane.kind === "physical") { - if (lane.platform !== "ios" || !deps.ops.physicalIos) throw new ExpectedOperationError("unsupported_platform", "Physical device runs currently support connected iOS devices only."); - await deps.ops.physicalIos.ready(deviceId); + if (!deps.ops.physicalIos) throw new ExpectedOperationError("unsupported_platform", "Physical iOS runs are unavailable on this server."); + const physical = deps.ops.physicalIos; + await physical.ready(deviceId, { projectPath: deps.projectPath }); signal.throwIfAborted(); - if (!await deps.ops.physicalIos.hasApp(deviceId, appId)) throw new ExpectedOperationError("app_unavailable", `App not installed: ${appId} is not on ${lane.deviceName}. Build for a physical iPhone and install it on this device, then run again.`); + if (!await physical.hasApp(deviceId, appId)) { + // A simulator build has the wrong slice and no provisioning, and an installed app cannot be + // pulled back off a phone, so the only source is a device build already on this Mac. + setState("installing"); + const result = physical.install ? await physical.install(deviceId, appId, { projectPath: deps.projectPath }) : "no_build"; + if (result === "no_build") throw new ExpectedOperationError("app_unavailable", `App not installed: ${appId} is not on ${lane.deviceName}, and no device build of it was found on this Mac. Build it for a physical device (for an Expo app, \`npx expo run:ios --device\`), then run again.`); + } signal.throwIfAborted(); if (!deps.projectMode) await deps.ops.physicalIos.launch(deviceId, appId); return deviceId; @@ -104,7 +148,8 @@ async function findSource(ops: DeviceOps, lane: Lane, lanes: readonly Lane[], ow try { return await ops.isBooted(lane.platform, candidate) && await ops.hasApp(lane.platform, candidate, appId); } catch { return false; } }; for (const other of lanes) { - if (other.runId === lane.runId || other.platform !== lane.platform) continue; + // A phone is never a source: a copy would need its container, which a phone does not give out. + if (other.runId === lane.runId || other.platform !== lane.platform || other.kind === "physical") continue; const candidate = other.resolvedDeviceId ?? other.deviceId; if (await usable(candidate)) return candidate; } @@ -113,6 +158,54 @@ async function findSource(ops: DeviceOps, lane: Lane, lanes: readonly Lane[], ow return undefined; } +/** Devices an Android phone may take the app from: phones of this run, other devices of it, then any booted emulator. */ +async function androidSources(ops: DeviceOps, lane: Lane, lanes: readonly Lane[], own: string, appId: string): Promise { + const found: string[] = []; + const usable = async (candidate: string, physical: boolean) => { + if (candidate === own || found.includes(candidate)) return; + try { + const has = physical ? ops.physicalAndroid && await ops.physicalAndroid.hasApp(candidate, appId) : await ops.isBooted("android", candidate) && await ops.hasApp("android", candidate, appId); + if (has) found.push(candidate); + } catch { /* offline or going away: not a source */ } + }; + const others = lanes.filter(other => other.runId !== lane.runId && other.platform === "android"); + for (const other of others.filter(entry => entry.kind === "physical")) await usable(other.resolvedDeviceId ?? other.deviceId, true); + for (const other of others.filter(entry => entry.kind !== "physical")) await usable(other.resolvedDeviceId ?? other.deviceId, false); + for (const device of await ops.bootedDevices?.("android").catch(() => []) ?? []) await usable(device.deviceId, false); + return found; +} + +/** Whether devicectl reports Developer Mode off. An unreadable answer is not a refusal: the runner says so itself. */ +async function developerModeDisabledWith(run: Commands["run"], deviceId: string): Promise { + try { + const output = await run("/usr/bin/xcrun", ["devicectl", "device", "info", "details", "--device", deviceId, "--quiet", "--timeout", "10", "--json-output", "-"], { timeout: 15_000 }); + const status = (JSON.parse(output) as { result?: { deviceProperties?: { developerModeStatus?: string } } }).result?.deviceProperties?.developerModeStatus; + return typeof status === "string" && status.toLowerCase() === "disabled"; + } catch { return false; } +} + +/** + * devicectl's failures as something to act on. The raw text names no fix, and "not installed" and + * "locked" are the two a tester meets first. Anything unrecognised keeps devicectl's own lines. + */ +export function physicalIosError(error: unknown, action: string, appId?: string): Error { + if (error instanceof ExpectedOperationError) return error; + const output = commandOutput(error); + if (/\blocked\b|passcode|DeviceLocked/i.test(output)) + return new ExpectedOperationError("device_unavailable", `${action} failed: the device is locked. Unlock it and keep the screen on, then try again.`); + if (/Developer Mode/i.test(output)) + return new ExpectedOperationError("device_unavailable", `${action} failed: Developer Mode is off. Turn it on in Settings → Privacy & Security → Developer Mode, restart the phone, then try again.`); + if (/not been explicitly trusted|profile has not been|invalid code signature|untrusted developer|0xe8008018/i.test(output)) + return new ExpectedOperationError("device_unavailable", `${action} failed: the developer profile is not trusted on the device. Trust it in Settings → General → VPN & Device Management, then try again.`); + if (/provisioning profile|not provisioned|entitlement|0xe8008015|0xe800801f|doesn't include|not.*included in the profile/i.test(output)) + return new ExpectedOperationError("app_unavailable", `${action} failed: this build is not provisioned for the device${appId ? ` (${appId})` : ""}. Rebuild it with automatic signing while the device is connected (for an Expo app, \`npx expo run:ios --device\`).`); + if (/not installed|could not be found|no such app|ApplicationNotFound|is not an installed/i.test(output)) + 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 APK_PATH = /^\/[\w\-./=+@~]+\.apk$/; /** Parses `adb shell pm path` output: one `package:` line per APK, split APKs included. */ @@ -120,6 +213,61 @@ export function parsePmPaths(output: string): string[] { return output.split(/\r?\n/).map(line => line.trim()).filter(line => line.startsWith("package:")).map(line => line.slice("package:".length)).filter(path => APK_PATH.test(path)); } +/** The CPU ABIs a set of APK entries ships native code for; empty when the APK is pure Java. */ +export function apkAbis(entries: string[]): string[] { + const abis = new Set(); + for (const entry of entries) { + const lib = /^lib\/([^/]+)\//.exec(entry); + if (lib) abis.add(lib[1]!); + } + return [...abis]; +} + +/** ABIs named by split APK file names such as `split_config.arm64_v8a.apk`. */ +export function splitNameAbis(fileNames: string[]): string[] { + const names = ["arm64_v8a", "armeabi_v7a", "x86_64", "x86", "armeabi", "mips64", "mips"]; + const abis = new Set(); + for (const file of fileNames) { + const match = /config\.([a-z0-9_]+)\.apk$/i.exec(file); + if (match && names.includes(match[1]!)) abis.add(match[1]!.replace(/_/g, "-")); + } + return [...abis]; +} + +/** Whether the device can run an APK that ships `apk` ABIs. An APK with no native code runs anywhere. */ +export function abiCompatible(device: string[], apk: string[]): boolean { + return apk.length === 0 || apk.some(abi => device.includes(abi)); +} + +/** Parses `dumpsys window`/`power` into why the screen is not usable, or null when it is awake and unlocked. */ +export function androidScreenBlock(power: string, window: string): "asleep" | "locked" | null { + if (/mWakefulness=(Asleep|Dozing)/.test(power)) return "asleep"; + if (/(?:mShowingLockscreen|isStatusBarKeyguard|mKeyguardShowing|showingLockscreen)=true|mDreamingLockscreen=true/.test(window)) return "locked"; + return null; +} + +/** + * `adb install` and agent-device helper-APK failures as something to act on. Vendor settings + * (Xiaomi "Install via USB", Samsung Auto Blocker) refuse USB installs with generic codes. + */ +export function androidInstallError(error: unknown, action: string, appId?: string): Error { + if (error instanceof ExpectedOperationError) return error; + const output = commandOutput(error); + if (/INSTALL_FAILED_NO_MATCHING_ABIS/.test(output)) + return new ExpectedOperationError("app_unavailable", `${action} failed: this build has no native code for the phone's CPU. Build and install it on this phone (for an Expo app, \`npx expo run:android --device\`).`); + if (/UPDATE_INCOMPATIBLE|INSTALL_FAILED_VERSION_DOWNGRADE|signatures do not match/i.test(output)) + return new ExpectedOperationError("app_unavailable", `${action} failed: a different build of ${appId ?? "the app"} is already on the phone. Uninstall it, or build and install it on this phone (for an Expo app, \`npx expo run:android --device\`).`); + if (/INSTALL_FAILED_USER_RESTRICTED|INSTALL_FAILED_ABORTED|Install canceled|Auto Blocker|Install via USB|USER_RESTRICTED/i.test(output)) + return new ExpectedOperationError("device_unavailable", `${action} failed: the phone blocks installs over USB. Turn on "Install via USB" (Xiaomi, in Developer options), turn off Auto Blocker (Samsung), or accept the prompt on the phone, then try again.`); + if (/INSUFFICIENT_STORAGE/.test(output)) + return new ExpectedOperationError("device_unavailable", `${action} failed: the phone is out of storage.`); + if (/unauthorized/i.test(output)) + return new ExpectedOperationError("device_unavailable", `${action} failed: the phone has not authorized this Mac. Unlock it and accept the USB debugging prompt.`); + if (/offline|device .* not found|no devices/i.test(output)) + return new ExpectedOperationError("device_unavailable", `${action} failed: the phone is not reachable. Reconnect it, unlock it, and refresh Devices.`); + return commandError(error, action, "adb"); +} + /** The real thing: `simctl` for iOS simulators, the emulator through `ServeEmu` and `adb` for Android. */ export function systemDeviceOps(deps: { simulators: Simctl; android: ServeEmu; drivers: DriverFactory; commands?: Commands; foreground?: (platform: MatrixPlatform, deviceId: string) => Promise }): DeviceOps { const commands = deps.commands ?? systemCommands; @@ -129,19 +277,87 @@ export function systemDeviceOps(deps: { simulators: Simctl; android: ServeEmu; d if (!udidSchema.safeParse(id).success) throw new ExpectedOperationError("invalid_input", "Use an iOS simulator UDID here. For a connected iPhone or iPad, select kind physical from device discovery."); return id; }; + const wireless = (serial: string) => /:\d+$|\._adb(?:-tls-connect)?\._tcp\.?$/.test(serial); + const adbShell = async (serial: string, args: string[], timeout = 10_000) => adb(serial, ["shell", ...args], timeout); return { - physicalIos: { + physicalAndroid: { async ready(deviceId) { + const listing = await commands.run(await commands.adb(), ["devices"], { timeout: 10_000 }).catch(error => { throw androidInstallError(error, "Reading the connected Android devices"); }); + const state = listing.split(/\r?\n/).map(line => line.trim().split(/\s+/)).find(parts => parts[0] === deviceId)?.[1]; + if (!state) throw new ExpectedOperationError("device_unavailable", wireless(deviceId) + ? "This wireless Android device is no longer connected; its address changes when it reconnects. Reconnect it and refresh Devices to pick it again." + : "The Android phone is no longer connected. Reconnect it with USB debugging on and refresh Devices."); + if (state === "unauthorized") throw new ExpectedOperationError("device_unavailable", "The Android phone has not authorized this Mac. Unlock it and accept the USB debugging prompt, then try again."); + if (state === "offline") throw new ExpectedOperationError("device_unavailable", "The Android phone is offline. Reconnect the cable, or toggle USB debugging, then refresh Devices."); + if (state !== "device") throw new ExpectedOperationError("device_unavailable", `The Android phone is ${state}. Reconnect it and refresh Devices.`); + const [power, window] = await Promise.all([adbShell(deviceId, ["dumpsys", "power"]), adbShell(deviceId, ["dumpsys", "window"], 15_000)].map(read => read.catch(() => ""))); + const block = androidScreenBlock(power!, window!); + if (block) throw new ExpectedOperationError("device_unavailable", `The Android phone is ${block === "asleep" ? "asleep" : "locked"}. Unlock it and keep the screen on (Developer options → Stay awake), then try again.`); + }, + async hasApp(deviceId, appId) { + const user = (await adbShell(deviceId, ["am", "get-current-user"]).catch(() => "0")).trim(); + const args = /^\d+$/.test(user) ? ["--user", user] : []; + try { return parsePmPaths(await adbShell(deviceId, ["pm", "path", ...args, appId])).length > 0; } catch { return false; } + }, + async launch(deviceId, appId) { + try { await adbShell(deviceId, ["monkey", "-p", appId, "-c", "android.intent.category.LAUNCHER", "1"], 30_000); } + catch (error) { throw androidInstallError(error, "Opening the app", appId); } + }, + async installFrom(deviceId, appId, sources) { + const abis = (await adbShell(deviceId, ["getprop", "ro.product.cpu.abilist"]).catch(() => "")).trim().split(",").filter(Boolean); + let mismatch = false; + for (const source of sources) { + const remotes = parsePmPaths(await adbShell(source, ["pm", "path", appId]).catch(() => "")); + if (remotes.length === 0) continue; + let installed = false; + await withTemporaryDirectory(async directory => { + const files: string[] = []; + for (const [index, remote] of remotes.entries()) { + const local = join(directory, `${index}-${remote.split("/").at(-1)}`); + await adb(source, ["pull", remote, local], 120_000); + files.push(local); + } + const entries: string[] = []; + for (const file of files) entries.push(...(await commands.run("unzip", ["-Z1", file], { timeout: 30_000 }).catch(() => "")).split(/\r?\n/)); + const shipped = [...apkAbis(entries), ...splitNameAbis(files)]; + if (abis.length > 0 && !abiCompatible(abis, shipped)) { mismatch = true; return; } + try { await adb(deviceId, files.length === 1 ? ["install", "-r", files[0]!] : ["install-multiple", "-r", ...files], 300_000); } + catch (error) { throw androidInstallError(error, "Installing the app", appId); } + installed = true; + }); + if (installed) return "installed"; + } + if (mismatch) throw new ExpectedOperationError("app_unavailable", `${appId} on the other devices has no native code for this phone's CPU (${abis.join(", ")}). Build and install it on this phone (for an Expo app, \`npx expo run:android --device\`).`); + return "no_source"; + }, + }, + physicalIos: { + async ready(deviceId, options) { const device = (await listIosDevices()).find(entry => entry.udid === deviceId); if (!device) throw new ExpectedOperationError("device_unavailable", "The iPhone or iPad is no longer in device discovery. Reconnect it and refresh Devices."); if (device.state !== "connected" || device.pairingState !== "paired") throw new ExpectedOperationError("device_unavailable", `${device.name} is not connected and paired. Reconnect and trust this Mac, then refresh Devices.`); + // Developer Mode is what lets the test runner start; a phone without it fails minutes later with a signing-like error. + if (await developerModeDisabledWith(commands.run, deviceId)) throw new ExpectedOperationError("device_unavailable", `Developer Mode is off on ${device.name}. Turn it on in Settings → Privacy & Security → Developer Mode, restart the phone, then try again.`); + await ensureIosSigning({ projectPath: options?.projectPath }); }, async hasApp(deviceId, appId) { - const output = await commands.run("/usr/bin/xcrun", ["devicectl", "device", "info", "apps", "--device", deviceId, "--quiet", "--timeout", "10", "--omit-deprecated-fields-in-json", "--json-output", "-"], { timeout: 15_000 }); - const parsed = JSON.parse(output) as { result?: { apps?: { bundleIdentifier?: string }[] } }; - return parsed.result?.apps?.some(app => app.bundleIdentifier === appId) ?? false; + try { + const output = await commands.run("/usr/bin/xcrun", ["devicectl", "device", "info", "apps", "--device", deviceId, "--include-all-apps", "--quiet", "--timeout", "10", "--omit-deprecated-fields-in-json", "--json-output", "-"], { timeout: 15_000 }); + const parsed = JSON.parse(output) as { result?: { apps?: { bundleIdentifier?: string }[] } }; + return parsed.result?.apps?.some(app => app.bundleIdentifier === appId) ?? false; + } catch (error) { throw physicalIosError(error, "Reading the apps on the device"); } + }, + async launch(deviceId, appId) { + try { await commands.run("/usr/bin/xcrun", ["devicectl", "device", "process", "launch", "--device", deviceId, appId], { timeout: 30_000 }); } + catch (error) { throw physicalIosError(error, "Opening the app", appId); } + }, + async install(deviceId, appId, options) { + const build = await findDeviceBuild(appId, commands, options?.projectPath); + if (!build) return "no_build"; + try { await commands.run("/usr/bin/xcrun", ["devicectl", "device", "install", "app", "--device", deviceId, build], { timeout: 300_000 }); } + catch (error) { throw physicalIosError(error, "Installing the app", appId); } + return "installed"; }, - async launch(deviceId, appId) { await commands.run("/usr/bin/xcrun", ["devicectl", "device", "process", "launch", "--device", deviceId, appId], { timeout: 30_000 }); }, }, async isBooted(platform, deviceId) { if (platform === "ios") return (await deps.simulators.device(ios(deviceId))).state === "Booted"; diff --git a/packages/core/src/testing-run.ts b/packages/core/src/testing-run.ts index 692cff32..6a22773c 100644 --- a/packages/core/src/testing-run.ts +++ b/packages/core/src/testing-run.ts @@ -302,7 +302,8 @@ export interface TestRunRequest { * A project-mode matrix lane: run the project's own config on one chosen device. See `runProjectLane`. * `target` is the config's target name (its engine must be a direct `mobile(...)` call). */ - projectLane?: { target: string; device: string }; + /** `stateDir` gives the lane's runner its own agent-device state; see `projectStateDir`. */ + projectLane?: { target: string; device: string; stateDir?: string }; /** Non-secret preference for a bundled test containing agent.* calls. */ model?: { provider: BundledModelProvider; model: string; endpoint?: string }; } @@ -497,6 +498,24 @@ async function runProjectPreview(request: TestRunRequest, deps: TestRunDeps): Pr function quoted(value: string): string { return JSON.stringify(value); } +/** The ids `@e2e-dev/mobile` treats as an id rather than a device name: a simulator UDID or an emulator serial. */ +const POOL_DEVICE_ID = /^(?:[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}|emulator-\d+)$/i; + +/** + * The `device` option text that pins a run to one device. + * + * `@e2e-dev/mobile` reads a configured string as an id only when it is a simulator UDID or an + * emulator serial; a hardware UDID (`00008110-…`) or a phone's adb serial is treated as a device + * *name* and fails with "No device named …". A `DeviceProvider` that leases the id goes through the + * same selection as `udid`/`serial`, so hardware is pinned by one. Simulators and emulators keep the + * plain string, which is what their configs have always carried. + */ +export function devicePinSource(device: string): string { + if (POOL_DEVICE_ID.test(device)) return quoted(device); + const id = quoted(device); + return `{ name: "mobile-dev-pinned-device", acquire: async () => ({ id: ${id}, deviceId: ${id}, client: {} }), release: async () => {} }`; +} + /* * TODO(e2e-device-flag): everything from here to `runProjectLane` is a workaround and gets replaced * by an upstream `e2e run --device ` flag, which makes `mobile()` read an override that wins over @@ -570,7 +589,7 @@ export function rewriteLaneConfig(source: string, targetName: string, device: st const close = closingBracket(source, open); if (close < 0) throw refuse("its mobile(...) call could not be read."); const original = source.slice(open + 1, close).trim(); - const pinned = `device: ${quoted(device)}, session: ${quoted(session)}`; + const pinned = `device: ${devicePinSource(device)}, session: ${quoted(session)}`; return `${source.slice(0, open + 1)}{ ${original ? `...(${original}), ` : ""}${pinned} }${source.slice(close)}`; } throw refuse(`the config has no target with that name.`); @@ -628,7 +647,7 @@ async function runProjectLane(request: TestRunRequest, deps: TestRunDeps): Promi if (!mirror) await sweepLaneFiles(configDir); const run = (config: string, onProgress?: TestRunDeps["onProgress"]) => spawnRun({ command: bin, cwd: root, runPath: request.relativePath, configName: config, output, - target: lane.target, timeoutMs: request.timeoutMs, spawner: deps.spawner ?? spawn, onProgress, signal: deps.signal, + target: lane.target, ...(lane.stateDir ? { stateDir: lane.stateDir } : {}), timeoutMs: request.timeoutMs, spawner: deps.spawner ?? spawn, onProgress, signal: deps.signal, }); try { if (mirror) { @@ -688,7 +707,7 @@ export function bundledConfigSource(target: BundledTarget, model?: TestRunReques "", "export default {", ...(selected ? [" agents: { default: {", ` model: ${selected.field},`, " system: 'You are a thorough QA agent. Verify every outcome.',", " } },"] : []), - ` targets: [{ name: ${quoted(bundledTargetName(target))}, engine: mobile({ platform: ${quoted(target.platform)}${target.device ? `, device: ${quoted(target.device)}` : ""} }), app: { bundleId: ${quoted(target.bundleId)} } }],`, + ` targets: [{ name: ${quoted(bundledTargetName(target))}, engine: mobile({ platform: ${quoted(target.platform)}${target.device ? `, device: ${devicePinSource(target.device)}` : ""} }), app: { bundleId: ${quoted(target.bundleId)} } }],`, " workers: 1,", "};", "", diff --git a/packages/core/src/testing-tools.ts b/packages/core/src/testing-tools.ts index b51b1429..853da9ba 100644 --- a/packages/core/src/testing-tools.ts +++ b/packages/core/src/testing-tools.ts @@ -2,7 +2,7 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { registerAppTool } from "@modelcontextprotocol/ext-apps/server"; import { z } from "zod"; -import { errorMessage } from "@mobile-dev/shared/protocol.ts"; +import { errorHint, errorMessage } from "@mobile-dev/shared/protocol.ts"; import { ExpectedOperationError } from "@mobile-dev/shared/error-reporting.ts"; import { captureServerError, recordTestingSetupOperation } from "./telemetry.ts"; import type { TestingProjectChoices } from "./testing-projects.ts"; @@ -20,6 +20,7 @@ import { runRecordedTest, sweepLaneFiles } from "./testing-run.ts"; import type { TestRunRequest } from "./testing-run.ts"; import { MatrixRegistry, MAX_MATRIX_LIMIT, snapshotMatrix, startMatrix } from "./testing-matrix.ts"; import type { LaneExecutor, MatrixDevice, MatrixRun } from "./testing-matrix.ts"; +import { ensureIosSigning, iosSigningStatus, projectStateDir, saveIosTeam, withAgentDeviceHint } from "./ios-signing.ts"; import { LAUNCHER_APP, createLaneExecutor } from "./testing-prepare.ts"; import type { DeviceOps } from "./testing-prepare.ts"; import { deviceIdSchema } from "@mobile-dev/shared/panel-target.ts"; @@ -38,6 +39,11 @@ async function connectedPhysicalIos(deviceId: string) { throw new ExpectedOperationError("device_unavailable", "The selected iPhone or iPad is not connected and paired. Reconnect and trust this Mac, then refresh Devices."); return device; } +/** A `kind` that cannot belong to the platform is a caller's mistake, refused before anything runs. */ +export function assertKindMatchesPlatform(device: { kind?: "simulator" | "emulator" | "physical"; platform: "ios" | "android" }): void { + if (device.kind === "simulator" && device.platform !== "ios") throw new ExpectedOperationError("invalid_input", "A simulator is an iOS device; use kind emulator for Android."); + if (device.kind === "emulator" && device.platform !== "android") throw new ExpectedOperationError("invalid_input", "An emulator is an Android device; use kind simulator for iOS."); +} /** The Testing Studio panel drives these itself; the model has its own e2e MCP server for test work. */ const appVisibility = { ui: { visibility: ["app"] as ("app" | "model")[] } }; /** @@ -78,8 +84,10 @@ function safe(handler: (input: T) => Promise) { try { return await handler(input); } catch (error) { - captureServerError(error, "testing.tool"); - return { isError: true, content: [{ type: "text", text: errorMessage(error) }] }; + // A signing or device-state failure carries agent-device's hint and is the user's to fix. + const reported = withAgentDeviceHint(error, errorHint, errorMessage); + captureServerError(reported, "testing.tool"); + return { isError: true, content: [{ type: "text", text: errorMessage(reported) }] }; } }; } @@ -400,6 +408,21 @@ export function registerTestingTools(server: McpServer, projects: TestingProject inputSchema: { preference: z.object({ provider: z.enum(["vercel", "openrouter", "openai-compatible", "chatgpt", "copilot", "opencode-console", "grok"]), model: z.string().min(1).max(256), endpoint: z.string().max(2048).optional() }).optional() }, annotations: write, _meta: appVisibility, }, safe(async ({ preference }: { preference?: { provider: BundledModelProvider; model: string; endpoint?: string } }) => { await saveTestingModelPreference(preference); recordTestingSetupOperation("preference", "succeeded", preference?.provider); return dataResult({ saved: Boolean(preference) }); })); + registerAppTool(server, "mobile_testing_ios_signing", { + title: "Read the iPhone signing team", description: "List the signing teams in the keychain and report which team signs the test runner on a physical iPhone, and whether an environment variable, the saved choice, the project or the keychain picked it.", + inputSchema: { projectPath: projectPath.optional() }, annotations: read, _meta: appVisibility, + }, safe(async ({ projectPath: selected }: { projectPath?: string }) => dataResult({ ...await iosSigningStatus({ projectPath: selected }) }))); + registerAppTool(server, "mobile_testing_ios_signing_team", { + title: "Choose the iPhone signing team", description: "Save the team that signs the test runner on a physical iPhone, or clear the choice. An environment variable still overrides it. A changed team restarts a stale runner daemon so the runner rebuilds.", + inputSchema: { teamId: z.string().regex(/^[A-Za-z0-9]{10}$/).optional(), projectPath: projectPath.optional() }, annotations: write, _meta: appVisibility, + }, safe(async ({ teamId, projectPath: selected }: { teamId?: string; projectPath?: string }) => { + await saveIosTeam(teamId); + recordTestingSetupOperation("signing", "succeeded"); + // Apply now, so the stale-daemon restart does not wait for the next run; no team yet is not an error here. + await ensureIosSigning({ projectPath: selected }).catch(() => undefined); + return dataResult({ ...await iosSigningStatus({ projectPath: selected }) }); + })); + registerAppTool(server, "mobile_testing_read_tree", { title: "Read the runner's element tree", description: @@ -414,7 +437,9 @@ export function registerTestingTools(server: McpServer, projects: TestingProject annotations: read, _meta: appVisibility, }, safe(async ({ deviceId, platform, kind, projectPath: selected, bundleId }: { deviceId: string; platform: "ios" | "android"; kind?: "simulator" | "emulator" | "physical"; projectPath: string; bundleId: string }) => { - if (kind === "physical") { if (platform !== "ios") throw new ExpectedOperationError("unsupported_platform", "Physical Android recording is not available yet."); await connectedPhysicalIos(deviceId); } + assertKindMatchesPlatform({ kind, platform }); + // Android needs no preflight here: starting a recording already checked the phone, and a tree read is frequent. + if (kind === "physical" && platform === "ios") { await connectedPhysicalIos(deviceId); await ensureIosSigning({ projectPath: selected }); } const project = await inspectProject(selected, { platform, bundleId }); // The refs go no further than the server: the panel records selectors and drives the mirror, // so an agent-device handle per element would be a few kilobytes a read that nothing reads. @@ -424,9 +449,13 @@ export function registerTestingTools(server: McpServer, projects: TestingProject })); registerAppTool(server, "mobile_testing_physical_app", { - title: "Check app on physical iOS device", description: "Check whether a selected app is installed on a connected iPhone or iPad.", - inputSchema: { platform: z.literal("ios"), deviceId: deviceIdSchema, bundleId: z.string().min(1).max(512) }, annotations: read, _meta: appVisibility, - }, safe(async ({ deviceId, bundleId }: { deviceId: string; bundleId: string }) => { + title: "Check app on physical device", description: "Check whether a selected app is installed on a connected iPhone, iPad or Android phone.", + inputSchema: { platform: z.enum(["ios", "android"]), deviceId: deviceIdSchema, bundleId: z.string().min(1).max(512) }, annotations: read, _meta: appVisibility, + }, safe(async ({ platform, deviceId, bundleId }: { platform: "ios" | "android"; deviceId: string; bundleId: string }) => { + if (platform === "android") { + if (!matrix.ops?.physicalAndroid) throw new ExpectedOperationError("unsupported_platform", "Physical Android app discovery is unavailable."); + return dataResult({ installed: await matrix.ops.physicalAndroid.hasApp(deviceId, bundleId) }); + } await connectedPhysicalIos(deviceId); if (!matrix.ops?.physicalIos) throw new ExpectedOperationError("unsupported_platform", "Physical iOS app discovery is unavailable."); return dataResult({ installed: await matrix.ops.physicalIos.hasApp(deviceId, bundleId) }); @@ -449,6 +478,7 @@ export function registerTestingTools(server: McpServer, projects: TestingProject annotations: write, _meta: appVisibility, }, safe(async ({ deviceId, projectPath: selected, bundleId, nodeId, text }: { deviceId: string; projectPath: string; bundleId: string; nodeId: string; text: string }) => { await connectedPhysicalIos(deviceId); + await ensureIosSigning({ projectPath: selected }); const project = await inspectProject(selected, { platform: "ios", bundleId }); const runtimeRoot = project.runtimeMode === "bundled" ? await bundledE2eRoot() : project.runtime.root; await devices.fillNode({ deviceId, platform: "ios", projectPath: selected, runtimeRoot, bundleId }, nodeId, text); @@ -510,10 +540,13 @@ export function registerTestingTools(server: McpServer, projects: TestingProject * verdict is already in hand, and a device that cannot be read only costs the element list. */ async function attachFailure(lane: { failure?: import("./testing-failure.ts").LaneFailure }, result: Awaited>, source: string, - read: { deviceId: string; platform: "ios" | "android"; projectPath: string; runtimeRoot: string; bundleId?: string }) { + read: { deviceId: string; platform: "ios" | "android"; projectPath: string; runtimeRoot: string; bundleId?: string; physical?: boolean }) { const failure = describeFailure(result, source); if (!failure) return; lane.failure = failure; + // Reading the screen starts a second XCTest runner on the phone, which can fail on its own signing + // or trust prompt and costs minutes. The lane's own failure and screenshot already say what broke. + if (read.physical) { failure.elementsError = "The device's screen was not re-read after the failure on a physical device; see the failing step and its screenshot."; return; } if (!read.bundleId) { failure.elementsError = "No app id is known for this device, so its screen was not read."; return; } if (!read.deviceId) { failure.elementsError = "The runner chose the device, so its screen was not read. Run with mobile_testing_run_matrix to name one."; return; } try { @@ -585,7 +618,7 @@ export function registerTestingTools(server: McpServer, projects: TestingProject registerAppTool(server, "mobile_testing_run_matrix", { title: "Run a recorded test on several devices", description: - "Run one saved test on several devices at once, one independent lane per device (iOS and Android can be mixed), and return a matrixId immediately; read progress with mobile_testing_run_progress. At most `limit` lanes run at once (default 3, max 8); the rest are queued. Simulators and emulators that are off are booted; a missing app may be copied from another booted virtual device. For a connected, paired iPhone or iPad pass kind physical and its hardware UDID from mobile_list_ios_devices; the app must already be installed for physical hardware. `apps` defaults to the apps the test is pinned to. In project mode each lane runs the config's target for its platform, whose engine must be a direct mobile(...) call. A failure on one device does not stop the others. projectPath defaults to the Testing Studio tab's project.", + "Run one saved test on several devices at once, one independent lane per device (iOS and Android can be mixed), and return a matrixId immediately; read progress with mobile_testing_run_progress. At most `limit` lanes run at once (default 3, max 8); the rest are queued. Simulators and emulators that are off are booted; a missing app may be copied from another booted virtual device. For a connected, paired iPhone or iPad pass kind physical and its hardware UDID from mobile_list_ios_devices; the app must already be installed for physical hardware. For an authorized, unlocked Android phone pass platform android, kind physical and its adb serial; a missing app may be copied from another Android device if its ABIs match. `apps` defaults to the apps the test is pinned to. In project mode each lane runs the config's target for its platform, whose engine must be a direct mobile(...) call. A failure on one device does not stop the others. projectPath defaults to the Testing Studio tab's project.", inputSchema: { projectPath: projectPath.optional(), relativePath: z.string().min(1).max(512).describe("The test to run, relative to the project."), @@ -614,21 +647,29 @@ export function registerTestingTools(server: McpServer, projects: TestingProject const unique = new Set(input.devices.map(device => device.deviceId)); if (unique.size !== input.devices.length) throw new ExpectedOperationError("invalid_input", "Each device can appear only once in a matrix."); if (!matrix.ops) throw new ExpectedOperationError("unsupported_platform", "This server cannot prepare devices for a matrix run."); + const busy = new Set(registry.busyDevices()); for (const device of input.devices) { + assertKindMatchesPlatform(device); + // One XCTest runner per phone: a second lane would fight the first for the device. + if (device.kind === "physical" && busy.has(device.deviceId)) + throw new ExpectedOperationError("device_unavailable", `${device.name ?? "This device"} is already running a test. Wait for it to finish or cancel it, then run again.`); if (device.kind === "physical") { - if (device.platform !== "ios") throw new ExpectedOperationError("unsupported_platform", "Physical Android test runs are not available yet."); - await connectedPhysicalIos(device.deviceId); + if (device.platform === "ios") await connectedPhysicalIos(device.deviceId); + else if (!matrix.ops.physicalAndroid) throw new ExpectedOperationError("unsupported_platform", "Physical Android test runs are unavailable on this server."); + else await matrix.ops.physicalAndroid.ready(device.deviceId); } } + // The runner signs itself for hardware: resolve the team once, before any lane builds it. + if (input.devices.some(device => device.kind === "physical" && device.platform === "ios")) await ensureIosSigning({ projectPath: projectPathValue }); const first = input.devices[0]!; const { request, project } = await prepareRequest({ ...input, platform: first.platform, ...(input.apps[first.platform] ? { bundleId: input.apps[first.platform]! } : {}) }); if (project.runtimeMode === "project") { const lanes = projectLaneTargets(project.targets, input.devices, input.targets); await devices.releaseOn(input.devices.map(device => device.deviceId)).catch(() => undefined); const projectExecutor = createLaneExecutor({ - ops: matrix.ops, projectMode: true, apps: Object.fromEntries(Object.entries(lanes).map(([platform, target]) => [platform, target.bundleId])), + ops: matrix.ops, projectMode: true, projectPath: input.projectPath, apps: Object.fromEntries(Object.entries(lanes).map(([platform, target]) => [platform, target.bundleId])), runTest: (lane, deviceId, signal, onProgress) => runTest( - { ...request, configPath: project.configPath, target: lanes[lane.platform]!.name, projectLane: { target: lanes[lane.platform]!.name, device: deviceId } }, + { ...request, configPath: project.configPath, target: lanes[lane.platform]!.name, projectLane: { target: lanes[lane.platform]!.name, device: deviceId, ...(lane.kind === "physical" && lane.platform === "ios" ? { stateDir: projectStateDir(request.projectPath) } : {}) } }, { release: () => devices.releaseOn([lane.deviceId, deviceId]), onProgress, signal }), }); const { run } = launchMatrix(input.relativePath, input.devices, input.limit, projectExecutor); @@ -641,12 +682,12 @@ export function registerTestingTools(server: McpServer, projects: TestingProject // Only the devices of this matrix lose the recorder; a recorder on another device keeps its session. await devices.releaseOn(input.devices.map(device => device.deviceId)).catch(() => undefined); const executor = createLaneExecutor({ - ops: matrix.ops, apps: input.apps, + ops: matrix.ops, apps: input.apps, projectPath: input.projectPath, runTest: async (lane, deviceId, signal, onProgress) => { const result = await runTest( { ...request, bundledTarget: { platform: lane.platform, bundleId: input.apps[lane.platform]!, device: deviceId } }, { release: () => devices.releaseOn([lane.deviceId, deviceId]), onProgress, signal }); - await attachFailure(lane, result, request.untilSource ?? "", { deviceId, platform: lane.platform, projectPath: input.projectPath, runtimeRoot: project.runtime.root, bundleId: input.apps[lane.platform]! }); + await attachFailure(lane, result, request.untilSource ?? "", { deviceId, platform: lane.platform, projectPath: input.projectPath, runtimeRoot: project.runtime.root, bundleId: input.apps[lane.platform]!, physical: lane.kind === "physical" && lane.platform === "ios" }); return result; }, }); diff --git a/packages/core/test/ios-signing.test.ts b/packages/core/test/ios-signing.test.ts new file mode 100644 index 00000000..f8c696f5 --- /dev/null +++ b/packages/core/test/ios-signing.test.ts @@ -0,0 +1,214 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { errorHint, errorMessage } from "@mobile-dev/shared/protocol.ts"; +import { ExpectedOperationError } from "@mobile-dev/shared/error-reporting.ts"; +import { configuredTeamId, developmentIdentities, developmentTeams, ensureIosSigning, iosSigningEnv, iosSigningStatus, readSavedIosTeam, resolveIosTeam, saveIosTeam, teamNameFromSubject, resetIosSigning, projectStateDir, PROJECT_STATE_ROOT, restartStaleDaemons, resolveIosTeamId, runnerBundleId, teamFromSubject, withAgentDeviceHint } from "../src/ios-signing.ts"; +import { AgentDeviceRuntime } from "../src/agent-device-runtime.ts"; + +/** A saved-choice file that never exists, so a team saved on this machine cannot leak into a test. */ +const NO_SAVED = join(tmpdir(), "mobile-dev-no-saved-team", "none.json"); +const none = async () => { throw new Error("no keychain"); }; + +test("the explicit setting wins over the project and keychain", async () => { + assert.equal(await resolveIosTeamId({ env: { MOBILE_DEV_IOS_TEAM_ID: "abcde12345", AGENT_DEVICE_IOS_TEAM_ID: "ZZZZZ99999" }, run: none }), "ABCDE12345"); + assert.equal(await resolveIosTeamId({ env: { AGENT_DEVICE_IOS_TEAM_ID: "ZZZZZ99999" }, run: none }), "ZZZZZ99999"); + assert.equal(configuredTeamId({ MOBILE_DEV_IOS_TEAM_ID: "not a team" }), undefined); +}); + +test("the project's DEVELOPMENT_TEAM is used when every target agrees, and not when they differ", async () => { + const root = await mkdtemp(join(tmpdir(), "signing-")); + try { + const pbx = (team: string) => `buildSettings = { DEVELOPMENT_TEAM = ${team}; };`; + await mkdir(join(root, "ios", "App.xcodeproj"), { recursive: true }); + await writeFile(join(root, "ios", "App.xcodeproj", "project.pbxproj"), `${pbx("ABCDE12345")}${pbx('"ABCDE12345"')}`); + assert.equal(await resolveIosTeamId({ env: {}, projectPath: root, run: none, savedTeamFile: NO_SAVED }), "ABCDE12345"); + await writeFile(join(root, "ios", "App.xcodeproj", "project.pbxproj"), `${pbx("ABCDE12345")}${pbx("FGHIJ67890")}`); + await assert.rejects(resolveIosTeamId({ env: {}, projectPath: root, run: none, savedTeamFile: NO_SAVED }), /MOBILE_DEV_IOS_TEAM_ID/); + } finally { await rm(root, { recursive: true, force: true }); } + assert.deepEqual(developmentTeams("DEVELOPMENT_TEAM = \"\";"), []); +}); + +test("keychain identities parse, and a team is read from the certificate subject", () => { + const output = [ + ' 1) 0123456789ABCDEF0123456789ABCDEF01234567 "Apple Development: Dev One (PERSONAL12)"', + ' 2) 89ABCDEF0123456789ABCDEF0123456789ABCDEF "Developer ID Application: Acme (ACMETEAM01)"', + ' 2 valid identities found', + ].join("\n"); + assert.deepEqual(developmentIdentities(output), ["Apple Development: Dev One (PERSONAL12)"]); + assert.equal(teamFromSubject("subject=UID=X,CN=Apple Development: A (B),OU=ABCDE12345,O=Acme,C=US"), "ABCDE12345"); +}); + +test("one team behind the keychain identities is chosen, none or several is a message that says what to set", async () => { + const keychain = (teams: string[]) => async (file: string, args: string[]) => { + if (args[0] === "find-identity") return teams.map((_, index) => `${index + 1}) ${String(index).repeat(40)} "Apple Development: Dev ${index} (P${index})"`).join("\n"); + throw new Error("openssl is not available in the fake"); + }; + // The fake cannot produce a certificate subject, so no identity yields a team: the none case. + await assert.rejects(resolveIosTeamId({ env: {}, run: keychain(["A"]), savedTeamFile: NO_SAVED }), (error: unknown) => error instanceof ExpectedOperationError && /signing team/.test(error.message) && /MOBILE_DEV_IOS_TEAM_ID/.test(error.message)); +}); + +test("signing is exported for the in-process client and the e2e runner, and a user's runner bundle id stays", async () => { + const keys = ["MOBILE_DEV_IOS_TEAM_ID", "AGENT_DEVICE_IOS_TEAM_ID", "AGENT_DEVICE_IOS_BUNDLE_ID"] as const; + const saved = Object.fromEntries(keys.map(key => [key, process.env[key]])); + try { + for (const key of keys) delete process.env[key]; + resetIosSigning(); + process.env.MOBILE_DEV_IOS_TEAM_ID = "ABCDE12345"; + await ensureIosSigning({ daemons: { stateDirs: [] }, savedTeamFile: NO_SAVED }); + assert.equal(process.env.AGENT_DEVICE_IOS_TEAM_ID, "ABCDE12345"); + assert.equal(process.env.AGENT_DEVICE_IOS_BUNDLE_ID, runnerBundleId("ABCDE12345")); + process.env.MOBILE_DEV_IOS_TEAM_ID = "FGHIJ67890"; + await ensureIosSigning({ daemons: { stateDirs: [] }, savedTeamFile: NO_SAVED }); + assert.equal(process.env.AGENT_DEVICE_IOS_BUNDLE_ID, runnerBundleId("FGHIJ67890"), "a bundle id this module set follows the team"); + process.env.AGENT_DEVICE_IOS_BUNDLE_ID = "com.me.runner"; + await ensureIosSigning({ daemons: { stateDirs: [] }, savedTeamFile: NO_SAVED }); + assert.equal(process.env.AGENT_DEVICE_IOS_BUNDLE_ID, "com.me.runner"); + assert.deepEqual(iosSigningEnv("ABCDE12345", "com.me.runner"), { AGENT_DEVICE_IOS_TEAM_ID: "ABCDE12345", AGENT_DEVICE_IOS_BUNDLE_ID: "com.me.runner" }); + } finally { + for (const key of keys) { if (saved[key] === undefined) delete process.env[key]; else process.env[key] = saved[key]; } + resetIosSigning(); + } +}); + +test("the agent-device runtime keeps the signing variables and still drops its own", () => { + const keys = ["AGENT_DEVICE_IOS_TEAM_ID", "AGENT_DEVICE_IOS_SIGNING_IDENTITY", "AGENT_DEVICE_DAEMON_BASE_URL"] as const; + const saved = Object.fromEntries(keys.map(key => [key, process.env[key]])); + try { + process.env.AGENT_DEVICE_IOS_TEAM_ID = "ABCDE12345"; + process.env.AGENT_DEVICE_IOS_SIGNING_IDENTITY = "Apple Development"; + process.env.AGENT_DEVICE_DAEMON_BASE_URL = "http://elsewhere"; + const env = (new AgentDeviceRuntime() as unknown as { environment(directory: string): Record }).environment("/state"); + assert.equal(env.AGENT_DEVICE_IOS_TEAM_ID, "ABCDE12345"); + assert.equal(env.AGENT_DEVICE_IOS_SIGNING_IDENTITY, "Apple Development"); + assert.equal(env.AGENT_DEVICE_DAEMON_BASE_URL, undefined); + assert.equal(env.AGENT_DEVICE_STATE_DIR, "/state"); + } finally { + for (const key of keys) { if (saved[key] === undefined) delete process.env[key]; else process.env[key] = saved[key]; } + } +}); + +test("agent-device's hint reaches the message with local paths removed, and a fixable failure is expected", () => { + const failure = Object.assign(new Error("xcodebuild build-for-testing failed"), { + details: { reason: "signing_no_development_team", hint: "Set AGENT_DEVICE_IOS_TEAM_ID. See /Users/someone/.agent-device/logs/build.log for details.", logPath: "/Users/someone/.agent-device/logs/build.log" }, + }); + assert.equal(errorHint(failure), "Set AGENT_DEVICE_IOS_TEAM_ID. See for details."); + const message = errorMessage(failure); + assert.match(message, /^xcodebuild build-for-testing failed Set AGENT_DEVICE_IOS_TEAM_ID/); + assert.doesNotMatch(message, /\/Users\/|logPath/); + const reported = withAgentDeviceHint(failure, errorHint, errorMessage); + assert.ok(reported instanceof ExpectedOperationError); + assert.equal(reported.outcome, "invalid_input"); + assert.equal(withAgentDeviceHint(new Error("plain"), errorHint, errorMessage) instanceof ExpectedOperationError, false); + assert.equal(errorMessage(new Error("plain")), "plain"); +}); + +test("a daemon started without this team is stopped, one that carries it and a stranger are not", async () => { + const signing = iosSigningEnv("ABCDE12345"); + const carried = Object.entries(signing).map(([key, value]) => `${key}=${value}`).join(" "); + const files: Record = { "/a/daemon.json": '{"pid":11}', "/b/daemon.json": '{"pid":22}', "/c/daemon.json": '{"pid":33}', "/d/daemon.json": "not json" }; + const processes: Record = { + 11: "node agent-device/dist/src/internal/daemon.js PATH=/usr/bin", + 22: `node agent-device/dist/src/internal/daemon.js ${carried}`, + 33: "node some-other-server.js", + }; + const killed: number[] = []; + const stopped = await restartStaleDaemons(signing, { + stateDirs: ["/a", "/b", "/c", "/d", "/missing"], + readFile: async path => files[path] ?? Promise.reject(new Error("ENOENT")), + processEnvironment: async pid => processes[pid] ?? Promise.reject(new Error("gone")), + kill: pid => { killed.push(pid); }, + }); + assert.deepEqual(stopped, [11]); + assert.deepEqual(killed, [11]); +}); + +test("each project's hardware runs keep their state in a folder of their own under the app's directory", () => { + const a = projectStateDir("/work/app-a"), b = projectStateDir("/work/app-b"); + assert.equal(dirname(a), PROJECT_STATE_ROOT); + assert.notEqual(a, b); + assert.equal(projectStateDir("/work/app-a"), a, "the same project always gets the same folder"); + assert.equal(a.includes("app-a"), false, "the folder name does not carry the project's path"); +}); + +test("a saved team slots between the environment and the project, and clears back to automatic", async () => { + const root = await mkdtemp(join(tmpdir(), "signing-saved-")); + try { + const savedTeamFile = join(root, "nested", "ios-signing-team.json"); + await mkdir(join(root, "ios", "App.xcodeproj"), { recursive: true }); + await writeFile(join(root, "ios", "App.xcodeproj", "project.pbxproj"), "DEVELOPMENT_TEAM = PROJECT123;"); + assert.equal((await resolveIosTeam({ env: {}, projectPath: root, run: none, savedTeamFile })).source, "project"); + await saveIosTeam("userteam12", savedTeamFile); + assert.equal(await readSavedIosTeam(savedTeamFile), "USERTEAM12"); + assert.deepEqual(await resolveIosTeam({ env: {}, projectPath: root, run: none, savedTeamFile }), { teamId: "USERTEAM12", source: "user" }); + assert.deepEqual(await resolveIosTeam({ env: { MOBILE_DEV_IOS_TEAM_ID: "ENVTEAM123" }, projectPath: root, run: none, savedTeamFile }), { teamId: "ENVTEAM123", source: "env", envVar: "MOBILE_DEV_IOS_TEAM_ID" }); + await saveIosTeam(undefined, savedTeamFile); + assert.equal((await resolveIosTeam({ env: {}, projectPath: root, run: none, savedTeamFile })).source, "project"); + await assert.rejects(saveIosTeam("short", savedTeamFile), ExpectedOperationError); + } finally { await rm(root, { recursive: true, force: true }); } +}); + +test("a saved team resolves ambiguity between several keychain teams, and the error points at the picker", async () => { + const root = await mkdtemp(join(tmpdir(), "signing-many-")); + try { + const savedTeamFile = join(root, "team.json"); + const run = async (file: string, args: string[]) => { + if (args[0] === "find-identity") return ' 1) 0123456789ABCDEF0123456789ABCDEF01234567 "Apple Development: A (AAA)"\n 2) 89ABCDEF0123456789ABCDEF0123456789ABCDEF "Apple Development: B (BBB)"\n'; + throw new Error("no certificate"); + }; + await assert.rejects(resolveIosTeam({ env: {}, run, savedTeamFile }), /E2E setup → Devices/); + await saveIosTeam("ABCDE12345", savedTeamFile); + assert.equal((await resolveIosTeam({ env: {}, run, savedTeamFile })).teamId, "ABCDE12345"); + } finally { await rm(root, { recursive: true, force: true }); } +}); + +test("the team API lists names, the saved choice and the team in effect, or why none resolves", async () => { + const root = await mkdtemp(join(tmpdir(), "signing-status-")); + try { + const savedTeamFile = join(root, "team.json"); + assert.equal(teamNameFromSubject("OU=ABCDE12345,O=Acme\\, Inc.,C=US"), "Acme, Inc."); + const status = await iosSigningStatus({ env: {}, run: none, savedTeamFile }); + assert.deepEqual(status.teams, []); + assert.equal(status.resolved, undefined); + assert.match(status.error ?? "", /E2E setup/); + await saveIosTeam("ABCDE12345", savedTeamFile); + assert.deepEqual(await iosSigningStatus({ env: {}, run: none, savedTeamFile }), { teams: [], saved: "ABCDE12345", resolved: { id: "ABCDE12345", source: "user" } }); + const pinned = await iosSigningStatus({ env: { MOBILE_DEV_IOS_TEAM_ID: "ENVTEAM123" }, run: none, savedTeamFile }); + assert.deepEqual(pinned.resolved, { id: "ENVTEAM123", source: "env", envVar: "MOBILE_DEV_IOS_TEAM_ID" }); + const agentDevice = await iosSigningStatus({ env: { AGENT_DEVICE_IOS_TEAM_ID: "AGENTTEAM1" }, run: none, savedTeamFile }); + assert.deepEqual(agentDevice.resolved, { id: "AGENTTEAM1", source: "env", envVar: "AGENT_DEVICE_IOS_TEAM_ID" }); + assert.equal((await iosSigningStatus({ env: { MOBILE_DEV_IOS_TEAM_ID: "bad", AGENT_DEVICE_IOS_TEAM_ID: "AGENTTEAM1" }, run: none, savedTeamFile })).resolved?.envVar, "AGENT_DEVICE_IOS_TEAM_ID"); + assert.equal(pinned.saved, "ABCDE12345"); + } finally { await rm(root, { recursive: true, force: true }); } +}); + +test("the team this process exported is not mistaken for the user's environment, so a chosen team can change", async () => { + const root = await mkdtemp(join(tmpdir(), "signing-self-")); + const before = { mobile: process.env.MOBILE_DEV_IOS_TEAM_ID, agent: process.env.AGENT_DEVICE_IOS_TEAM_ID, bundle: process.env.AGENT_DEVICE_IOS_BUNDLE_ID }; + try { + delete process.env.MOBILE_DEV_IOS_TEAM_ID; delete process.env.AGENT_DEVICE_IOS_TEAM_ID; delete process.env.AGENT_DEVICE_IOS_BUNDLE_ID; + resetIosSigning(); + const savedTeamFile = join(root, "team.json"); + const options = { run: none, savedTeamFile, daemons: { stateDirs: [] } }; + await saveIosTeam("FIRSTTEAM1", savedTeamFile); + assert.equal(await ensureIosSigning(options), "FIRSTTEAM1"); + assert.equal(process.env.AGENT_DEVICE_IOS_TEAM_ID, "FIRSTTEAM1"); + // The export is ours: the status still says "user", and a new choice takes effect. + assert.equal((await iosSigningStatus(options)).resolved?.source, "user"); + await saveIosTeam("SECONDTEA2", savedTeamFile); + assert.equal(await ensureIosSigning(options), "SECONDTEA2"); + await saveIosTeam(undefined, savedTeamFile); + await assert.rejects(resolveIosTeam(options), ExpectedOperationError); + // A team the user's own environment names is never treated as our export. + process.env.AGENT_DEVICE_IOS_TEAM_ID = "USERENV123"; + resetIosSigning(); + assert.equal(await ensureIosSigning(options), "USERENV123"); + assert.deepEqual((await iosSigningStatus(options)).resolved, { id: "USERENV123", source: "env", envVar: "AGENT_DEVICE_IOS_TEAM_ID" }); + } finally { + for (const [key, value] of [["MOBILE_DEV_IOS_TEAM_ID", before.mobile], ["AGENT_DEVICE_IOS_TEAM_ID", before.agent], ["AGENT_DEVICE_IOS_BUNDLE_ID", before.bundle]] as const) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } + resetIosSigning(); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/core/test/testing-agent.test.ts b/packages/core/test/testing-agent.test.ts index 6aadd070..165e69f1 100644 --- a/packages/core/test/testing-agent.test.ts +++ b/packages/core/test/testing-agent.test.ts @@ -400,7 +400,9 @@ test("booted virtual devices and connected paired iOS hardware are recordable", assert.equal(isRecordableDevice({ ...base, state: "Booted", platform: "ios", kind: "simulator" }), true); assert.equal(isRecordableDevice({ ...base, udid: "emulator-5554", state: "Booted", platform: "android", kind: "emulator" }), true); assert.equal(isRecordableDevice({ ...base, state: "Shutdown", platform: "android", kind: "emulator" }), false); - assert.equal(isRecordableDevice({ ...base, state: "connected", platform: "android", kind: "physical" } as never), false); + assert.equal(isRecordableDevice({ ...base, state: "Booted", platform: "android", kind: "physical" } as never), true); + assert.equal(isRecordableDevice({ ...base, state: "unauthorized", platform: "android", kind: "physical" } as never), false); + assert.equal(isRecordableDevice({ ...base, state: "offline", platform: "android", kind: "physical" } as never), false); assert.equal(isRecordableDevice({ ...base, state: "connected", platform: "ios", kind: "physical", pairingState: "paired" } as never), true); assert.equal(isRecordableDevice({ ...base, state: "connected", platform: "ios", kind: "physical", pairingState: "unpaired" } as never), false); assert.equal(isRecordableDevice(undefined), false); diff --git a/packages/core/test/testing-device.test.ts b/packages/core/test/testing-device.test.ts index a5eed1ca..5dcecf7d 100644 --- a/packages/core/test/testing-device.test.ts +++ b/packages/core/test/testing-device.test.ts @@ -341,3 +341,24 @@ test("releaseOn waits for an in-flight physical screen read before handing the d await Promise.all([read, released]); assert.equal(calls.filter(entry => entry.call === "close").length, 1); }); + +test("a fill lands on the field it named even after the screen was re-read and renumbered", async () => { + const calls: Record[] = []; + let reads = 0; + const field = (ref: string, name: string, y: number) => ({ kind: "text-field", ref, node: { role: "textbox", name, rect: { x: 0, y, width: 100, height: 20 } } }); + const devices = new TestingDevices(fakeAgentDevice(calls, () => { + 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); + (devices as unknown as { projections: Map }).projections.set("/project", Promise.resolve(projection)); + const phone = { ...target, deviceId: "00008150-0000111122223333" }; + const first = await devices.read(phone); + const zip = first.tree.find(component => component.label === "Zip")!.nodeId!; + await devices.read(phone); // a refresh the panel queued ahead of its fill + await devices.fillNode(phone, zip, "10115"); + assert.equal(calls.find(entry => entry.call === "fill")?.ref, "@e9", "the same field, by its new ref"); + assert.ok(reads >= 3, "the fill took a fresh snapshot"); + await assert.rejects(devices.fillNode(phone, "s-gone", "x"), /no longer on the current screen/); + await devices.release(); +}); diff --git a/packages/core/test/testing-matrix.test.ts b/packages/core/test/testing-matrix.test.ts index f5b35bbd..ba1550ed 100644 --- a/packages/core/test/testing-matrix.test.ts +++ b/packages/core/test/testing-matrix.test.ts @@ -173,3 +173,11 @@ test("lanes carry stable unique run ids", () => { const { run } = new MatrixRegistry().create("t", devices(3), 3); assert.equal(new Set(run.lanes.map((lane: Lane) => lane.runId)).size, 3); }); + +test("a kind that cannot belong to the platform is refused before anything runs", async () => { + const { assertKindMatchesPlatform } = await import("../src/testing-tools.ts"); + assert.throws(() => assertKindMatchesPlatform({ kind: "simulator", platform: "android" }), /use kind emulator/); + assert.throws(() => assertKindMatchesPlatform({ kind: "emulator", platform: "ios" }), /use kind simulator/); + assert.doesNotThrow(() => assertKindMatchesPlatform({ kind: "physical", platform: "android" })); + assert.doesNotThrow(() => assertKindMatchesPlatform({ platform: "ios" })); +}); diff --git a/packages/core/test/testing-physical-app.test.ts b/packages/core/test/testing-physical-app.test.ts new file mode 100644 index 00000000..1c7cccaa --- /dev/null +++ b/packages/core/test/testing-physical-app.test.ts @@ -0,0 +1,33 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { registerTestingTools } from "../src/testing-tools.ts"; +import { TestingProjectChoices } from "../src/testing-projects.ts"; +import { TestingDevices } from "../src/testing-device.ts"; +import type { DeviceOps } from "../src/testing-prepare.ts"; + +test("the physical app check answers for an Android phone through adb, not the iPhone path", async () => { + const root = await mkdtemp(join(tmpdir(), "physical-app-")); + const asked: string[] = []; + const ops = { + physicalAndroid: { ready: async () => undefined, hasApp: async (serial: string, appId: string) => { asked.push(`${serial}:${appId}`); return appId === "com.example.app"; }, launch: async () => undefined }, + } as unknown as DeviceOps; + const server = new McpServer({ name: "t", version: "1" }); + registerTestingTools(server, new TestingProjectChoices(join(root, "state")), new TestingDevices(), undefined, { ops }); + const client = new Client({ name: "c", version: "1" }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await Promise.all([server.connect(a), client.connect(b)]); + const check = async (bundleId: string) => { + const result = await client.callTool({ name: "mobile_testing_physical_app", arguments: { platform: "android", deviceId: "R5CT1234ABC", bundleId } }); + assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); + return (result.structuredContent as { installed: boolean }).installed; + }; + assert.equal(await check("com.example.app"), true); + assert.equal(await check("com.example.missing"), false); + assert.deepEqual(asked, ["R5CT1234ABC:com.example.app", "R5CT1234ABC:com.example.missing"]); +}); diff --git a/packages/core/test/testing-prepare.test.ts b/packages/core/test/testing-prepare.test.ts index 0566862d..f0d3ac3a 100644 --- a/packages/core/test/testing-prepare.test.ts +++ b/packages/core/test/testing-prepare.test.ts @@ -1,6 +1,6 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { createLaneExecutor, parsePmPaths, systemDeviceOps } from "../src/testing-prepare.ts"; +import { abiCompatible, androidInstallError, androidScreenBlock, apkAbis, createLaneExecutor, parsePmPaths, splitNameAbis, physicalIosError, systemDeviceOps } from "../src/testing-prepare.ts"; import type { DeviceOps } from "../src/testing-prepare.ts"; import { MatrixRegistry, startMatrix } from "../src/testing-matrix.ts"; import type { LaneState, MatrixDevice } from "../src/testing-matrix.ts"; @@ -92,7 +92,7 @@ test("a physical iPhone without the app fails with hardware install guidance", a const { ops, log } = machine({ phone: { booted: false, apps: [] }, sim: { booted: true, apps: ["com.app"] } }); ops.physicalIos = { ready: async () => undefined, hasApp: async () => false, launch: async () => undefined }; const { matrix } = await run([{ deviceId: "phone", platform: "ios", kind: "physical" }, { deviceId: "sim", platform: "ios" }], ops); - assert.match(matrix.lanes[0]?.error ?? "", /Build for a physical iPhone/); + assert.match(matrix.lanes[0]?.error ?? "", /no device build of it was found.*expo run:ios --device/); assert.equal(log.some(entry => entry.includes("phone")), false, "simulator copy and boot commands never receive the phone UDID"); }); @@ -159,6 +159,8 @@ test("physical app lookup and launch use devicectl, never simctl", async () => { assert.equal(await ops.physicalIos!.hasApp("phone", "com.app"), true); await ops.physicalIos!.launch("phone", "com.app"); assert.equal(calls.length, 2); + // System and App Store apps are only listed with this flag, so without it Settings reads as not installed. + assert.ok(calls[0]!.includes("--include-all-apps")); assert.ok(calls.every(args => args[0] === "/usr/bin/xcrun" && args[1] === "devicectl" && args.includes("phone"))); }); @@ -183,3 +185,126 @@ test("the system ops list only the booted devices of a platform and read the for assert.equal(await ops.foregroundApp!("android", "emulator-5554"), "com.example"); assert.deepEqual(asked, [["android", "emulator-5554"]]); }); + +test("a physical iPhone without the app gets a device build installed, never a simulator copy", async () => { + const { ops, log } = machine({ phone: { booted: false, apps: [] }, sim: { booted: true, apps: ["com.app"] } }); + const installs: string[] = []; + ops.physicalIos = { ready: async () => undefined, hasApp: async () => installs.length > 0, launch: async () => { log.push("launch phone"); }, install: async (id, app) => { installs.push(`${id} ${app}`); return "installed"; } }; + const states: string[] = []; + const executor = createLaneExecutor({ ops, apps: { ios: "com.app" }, runTest: async () => ({ status: "passed", exitCode: 0, steps: [] }) }); + const { run: matrix, done } = startMatrix(new MatrixRegistry(), { testPath: "t", devices: [{ deviceId: "phone", platform: "ios", kind: "physical" }, { deviceId: "sim", platform: "ios" }] }, { + ...executor, prepare: (lane, lanes, signal, setState) => executor.prepare(lane, lanes, signal, state => { states.push(`${lane.deviceId}:${state}`); setState(state); }), + }); + await done; + assert.equal(matrix.lanes[0]!.state, "passed"); + assert.deepEqual(installs, ["phone com.app"]); + assert.ok(states.includes("phone:installing")); + assert.equal(log.some(entry => entry.startsWith("copy")), false); +}); + +test("a simulator lane never takes a physical lane as the app source", async () => { + const { ops, log } = machine({ phone: { booted: true, apps: ["com.app"] }, sim: { booted: true, apps: [] } }); + ops.physicalIos = { ready: async () => undefined, hasApp: async () => true, launch: async () => undefined }; + const { matrix } = await run([{ deviceId: "phone", platform: "ios", kind: "physical" }, { deviceId: "sim", platform: "ios" }], ops); + assert.equal(matrix.lanes[1]!.state, "error"); + assert.equal(log.some(entry => entry.startsWith("copy")), false); +}); + +test("devicectl failures become instructions", () => { + const failure = (stderr: string) => physicalIosError(Object.assign(new Error("Command failed"), { stderr }), "Installing the app", "com.app").message; + assert.match(failure("The device is locked."), /locked\. Unlock it/); + assert.match(failure("Developer Mode is disabled"), /Developer Mode is off/); + assert.match(failure("ApplicationVerificationFailed: its profile has not been explicitly trusted by the user"), /VPN & Device Management/); + assert.match(failure("error: no provisioning profile includes the device (0xe8008015)"), /not provisioned for the device.*expo run:ios --device/); + assert.match(failure("The app could not be found: not installed"), /com\.app is not installed/); + assert.doesNotMatch(failure("The device is unlocked and fine but something else broke"), /Unlock it/); +}); + +/** adb/unzip fake for a physical Android phone: `devices` lists it in `state`, other answers come from `answers`. */ +function phoneOps(state: string, answers: Record, calls: string[][] = []) { + const commands = { + adb: async () => "adb", aapt2: async () => null, readBinary: async () => Buffer.alloc(0), + run: async (file: string, args: string[]) => { + calls.push([file, ...args]); + if (args[0] === "devices") return `List of devices attached\nR5CT1\t${state}\n`; + const key = args[0] === "-Z1" ? "-Z1" : args.slice(2).join(" "); + const hit = Object.entries(answers).find(([prefix]) => key.startsWith(prefix)); + if (!hit) return ""; + if (hit[1].startsWith("throw:")) throw Object.assign(new Error("failed"), { stderr: hit[1].slice(6) }); + return hit[1]; + }, + }; + return systemDeviceOps({ simulators: {} as never, android: {} as never, drivers: (() => ({})) as never, commands }).physicalAndroid!; +} + +test("physical Android ready maps adb states to what to fix", async () => { + await assert.rejects(phoneOps("unauthorized", {}).ready("R5CT1"), /USB debugging prompt/); + await assert.rejects(phoneOps("offline", {}).ready("R5CT1"), /offline/); + await assert.rejects(phoneOps("device", {}).ready("OTHER"), /no longer connected/); + await assert.rejects(phoneOps("device", {}).ready("192.168.1.5:5555"), /address changes/); +}); + +test("physical Android ready refuses a sleeping or locked screen and accepts an unlocked one", async () => { + await assert.rejects(phoneOps("device", { "shell dumpsys power": "mWakefulness=Asleep" }).ready("R5CT1"), /asleep/); + await assert.rejects(phoneOps("device", { "shell dumpsys power": "mWakefulness=Awake", "shell dumpsys window": "mShowingLockscreen=true" }).ready("R5CT1"), /locked/); + await phoneOps("device", { "shell dumpsys power": "mWakefulness=Awake", "shell dumpsys window": "mShowingLockscreen=false" }).ready("R5CT1"); + assert.equal(androidScreenBlock("mWakefulness=Awake", "isStatusBarKeyguard=false"), null); +}); + +test("physical Android hasApp asks for the current user and launch uses monkey", async () => { + const calls: string[][] = []; + const ops = phoneOps("device", { "shell am get-current-user": "10\n", "shell pm path": "package:/data/app/x/base.apk\n" }, calls); + assert.equal(await ops.hasApp("R5CT1", "com.app"), true); + assert.ok(calls.at(-1)!.join(" ").includes("pm path --user 10 com.app")); + await ops.launch("R5CT1", "com.app"); + assert.ok(calls.at(-1)!.join(" ").includes("monkey -p com.app -c android.intent.category.LAUNCHER 1")); +}); + +test("ABI checks compare the phone's ABIs with the APK's native libraries", () => { + assert.deepEqual(apkAbis(["classes.dex", "lib/arm64-v8a/liba.so", "lib/x86_64/liba.so"]), ["arm64-v8a", "x86_64"]); + assert.deepEqual(splitNameAbis(["0-base.apk", "1-split_config.arm64_v8a.apk"]), ["arm64-v8a"]); + assert.equal(abiCompatible(["arm64-v8a", "armeabi-v7a"], ["x86_64"]), false); + assert.equal(abiCompatible(["arm64-v8a"], ["x86_64", "arm64-v8a"]), true); + assert.equal(abiCompatible(["arm64-v8a"], []), true, "pure Java runs anywhere"); +}); + +test("physical Android install copies from a source only when the ABIs match", async () => { + const calls: string[][] = []; + const base = { "shell getprop ro.product.cpu.abilist": "arm64-v8a,armeabi-v7a", "shell pm path": "package:/data/app/x/base.apk\n" }; + const ok = phoneOps("device", { ...base, "-Z1": "lib/arm64-v8a/a.so\nclasses.dex" }, calls); + assert.equal(await ok.installFrom!("R5CT1", "com.app", ["emulator-5554"]), "installed"); + assert.ok(calls.some(call => call.includes("install") && call.includes("R5CT1"))); + const mismatch = phoneOps("device", { ...base, "-Z1": "lib/x86_64/a.so" }); + await assert.rejects(mismatch.installFrom!("R5CT1", "com.app", ["emulator-5554"]), /no native code for this phone/); + assert.equal(await phoneOps("device", base).installFrom!("R5CT1", "com.app", []), "no_source"); +}); + +test("adb install failures say what to fix, including vendor USB-install blocks", () => { + const fail = (stderr: string) => androidInstallError(Object.assign(new Error("x"), { stderr }), "Installing the app", "com.app").message; + assert.match(fail("INSTALL_FAILED_NO_MATCHING_ABIS"), /expo run:android --device/); + assert.match(fail("INSTALL_FAILED_UPDATE_INCOMPATIBLE"), /Uninstall/); + assert.match(fail("INSTALL_FAILED_USER_RESTRICTED: Install canceled by user"), /Install via USB/); +}); + +test("a physical Android lane copies the app from a phone before an emulator and launches it", async () => { + const log: string[] = []; + const ops: DeviceOps = { + ...machine({ "emulator-5554": { booted: true, apps: ["com.app"] } }).ops, + physicalAndroid: { + ready: async id => { log.push(`ready ${id}`); }, + hasApp: async id => id === "phoneB" || log.includes("installed"), + launch: async id => { log.push(`launch ${id}`); }, + installFrom: async (id, _app, sources) => { log.push(`from ${sources.join(",")}`); log.push("installed"); return "installed"; }, + }, + }; + const { matrix } = await run([{ deviceId: "phoneA", platform: "android", kind: "physical" }, { deviceId: "phoneB", platform: "android", kind: "physical" }, { deviceId: "emulator-5554", platform: "android" }], ops); + assert.equal(matrix.lanes[0]!.state, "passed"); + assert.ok(log.includes("from phoneB,emulator-5554")); + assert.ok(log.indexOf("installed") < log.indexOf("launch phoneA")); +}); + +test("a physical Android lane with no source says to build for the phone", async () => { + const ops: DeviceOps = { ...machine({}).ops, physicalAndroid: { ready: async () => undefined, hasApp: async () => false, launch: async () => undefined, installFrom: async () => "no_source" } }; + const { matrix } = await run([{ deviceId: "phone", platform: "android", kind: "physical" }], ops); + assert.match(matrix.lanes[0]!.error ?? "", /expo run:android --device/); +}); diff --git a/packages/core/test/testing-run.test.ts b/packages/core/test/testing-run.test.ts index 7657e40e..a702c561 100644 --- a/packages/core/test/testing-run.test.ts +++ b/packages/core/test/testing-run.test.ts @@ -8,7 +8,7 @@ import { basename, dirname, isAbsolute, join } from "node:path"; import { fileURLToPath } from "node:url"; import { existsSync, realpathSync } from "node:fs"; import { readFileSync } from "node:fs"; -import { RUNNER_CWD, bundledConfigSource, bundledTargetName, parseProgressLine, parseReport, progressConfigSource, reportDuration, reportError, rewriteLaneConfig, sweepLaneFiles, LANE_FILE_PREFIX, reportSteps, reportStatus, runRecordedTest, runnerBin, runnerEnv, untilTestPath } from "../src/testing-run.ts"; +import { RUNNER_CWD, bundledConfigSource, devicePinSource, bundledTargetName, parseProgressLine, parseReport, progressConfigSource, reportDuration, reportError, rewriteLaneConfig, sweepLaneFiles, LANE_FILE_PREFIX, reportSteps, reportStatus, runRecordedTest, runnerBin, runnerEnv, untilTestPath } from "../src/testing-run.ts"; import { bundledE2eRoot } from "../src/e2e-runtime.ts"; const FILE = "tests/a-recorded-flow.e2e.ts"; @@ -418,9 +418,9 @@ test("bundled deterministic tests need no model and agent tests request one", as }); test("a device-pinned bundled config names the device and gives the target its own name", () => { - const source = bundledConfigSource({ platform: "ios", bundleId: "com.example.app", device: "A1B2-C3" }); - assert.match(source, /name: "ios-A1B2-C3"/); - assert.match(source, /mobile\(\{ platform: "ios", device: "A1B2-C3" \}\)/); + const source = bundledConfigSource({ platform: "ios", bundleId: "com.example.app", device: "3F2504E0-4F89-41D3-9A0C-0305E82C3301" }); + assert.match(source, /name: "ios-3F2504E0-4F89-41D3-9A0C-0305E82C3301"/); + assert.match(source, /mobile\(\{ platform: "ios", device: "3F2504E0-4F89-41D3-9A0C-0305E82C3301" \}\)/); assert.match(source, /workers: 1/); assert.equal(bundledTargetName({ platform: "android", bundleId: "x", device: "emulator-5554" }), "android-emulator-5554"); assert.equal(bundledTargetName({ platform: "android", bundleId: "x", device: "avd:Pixel 8" }), "android-avd-Pixel-8"); @@ -490,10 +490,10 @@ export default { `; test("a lane pins the device and session on its own target only, keeping the other options", () => { - const out = rewriteLaneConfig(LANE_CONFIG, "ios", "UDID-1", "lane-1"); - assert.match(out, /engine: mobile\(\{ \.\.\.\(\{ platform: "ios", settle: 300 \}\), device: "UDID-1", session: "lane-1" \}\)/); + const out = rewriteLaneConfig(LANE_CONFIG, "ios", "3F2504E0-4F89-41D3-9A0C-0305E82C3301", "lane-1"); + assert.match(out, /engine: mobile\(\{ \.\.\.\(\{ platform: "ios", settle: 300 \}\), device: "3F2504E0-4F89-41D3-9A0C-0305E82C3301", session: "lane-1" \}\)/); assert.match(out, /engine: mobile\(\{ platform: "android", transition: \{ mode: "fast" \} \}\)/, "the other target is untouched"); - assert.equal(out, LANE_CONFIG.replace('mobile({ platform: "ios", settle: 300 })', 'mobile({ ...({ platform: "ios", settle: 300 }), device: "UDID-1", session: "lane-1" })'), "nothing else changes"); + assert.equal(out, LANE_CONFIG.replace('mobile({ platform: "ios", settle: 300 })', 'mobile({ ...({ platform: "ios", settle: 300 }), device: "3F2504E0-4F89-41D3-9A0C-0305E82C3301", session: "lane-1" })'), "nothing else changes"); }); test("the second target is the one rewritten when it is the one named", () => { @@ -503,24 +503,24 @@ test("the second target is the one rewritten when it is the one named", () => { }); test("a variable argument and a spread are kept by spreading them", () => { - const variable = rewriteLaneConfig('const opts = { platform: "ios" };\nexport default { targets: [\n{ name: "ios", engine: mobile(opts), app: {} },\n] };', "ios", "D", "s"); - assert.match(variable, /mobile\(\{ \.\.\.\(opts\), device: "D", session: "s" \}\)/); - const spread = rewriteLaneConfig('export default { targets: [\n{ name: "a", engine: mobile({ ...base, platform: "android" }) },\n] };', "a", "D", "s"); - assert.match(spread, /mobile\(\{ \.\.\.\(\{ \.\.\.base, platform: "android" \}\), device: "D", session: "s" \}\)/); - const none = rewriteLaneConfig('export default { targets: [{ name: "a", engine: mobile() }] };', "a", "D", "s"); - assert.match(none, /mobile\(\{ device: "D", session: "s" \}\)/); + const variable = rewriteLaneConfig('const opts = { platform: "ios" };\nexport default { targets: [\n{ name: "ios", engine: mobile(opts), app: {} },\n] };', "ios", "emulator-5554", "s"); + assert.match(variable, /mobile\(\{ \.\.\.\(opts\), device: "emulator-5554", session: "s" \}\)/); + const spread = rewriteLaneConfig('export default { targets: [\n{ name: "a", engine: mobile({ ...base, platform: "android" }) },\n] };', "a", "emulator-5554", "s"); + assert.match(spread, /mobile\(\{ \.\.\.\(\{ \.\.\.base, platform: "android" \}\), device: "emulator-5554", session: "s" \}\)/); + const none = rewriteLaneConfig('export default { targets: [{ name: "a", engine: mobile() }] };', "a", "emulator-5554", "s"); + assert.match(none, /mobile\(\{ device: "emulator-5554", session: "s" \}\)/); }); test("parentheses inside strings and comments do not end the call early", () => { - const out = rewriteLaneConfig('export default { targets: [{ name: "a", engine: mobile({ platform: "ios", label: ")(" /* ) */ }) }] };', "a", "D", "s"); + const out = rewriteLaneConfig('export default { targets: [{ name: "a", engine: mobile({ platform: "ios", label: ")(" /* ) */ }) }] };', "a", "emulator-5554", "s"); assert.match(out, /session: "s" \}\) \}\] \};$/); }); test("a target whose engine is not a direct mobile call, or that does not exist, is refused with a reason", () => { - assert.throws(() => rewriteLaneConfig('export default { targets: [{ name: "web", engine: playwright({}) }] };', "web", "D", "s"), /not a direct mobile\(\.\.\.\) call/); - assert.throws(() => rewriteLaneConfig('export default { targets: [{ name: "ios", engine: makeEngine("ios") }] };', "ios", "D", "s"), /not a direct mobile/); - assert.throws(() => rewriteLaneConfig('const targets = []; export default { targets };', "ios", "D", "s"), /no literal `targets/); - assert.throws(() => rewriteLaneConfig(LANE_CONFIG, "tvos", "D", "s"), /no target with that name/); + assert.throws(() => rewriteLaneConfig('export default { targets: [{ name: "web", engine: playwright({}) }] };', "web", "emulator-5554", "s"), /not a direct mobile\(\.\.\.\) call/); + assert.throws(() => rewriteLaneConfig('export default { targets: [{ name: "ios", engine: makeEngine("ios") }] };', "ios", "emulator-5554", "s"), /not a direct mobile/); + assert.throws(() => rewriteLaneConfig('const targets = []; export default { targets };', "ios", "emulator-5554", "s"), /no literal `targets/); + assert.throws(() => rewriteLaneConfig(LANE_CONFIG, "tvos", "emulator-5554", "s"), /no target with that name/); }); async function laneProject() { @@ -531,9 +531,22 @@ async function laneProject() { } /** A spawn that records the lane config as it is while the run is alive, then answers. */ -function laneSpawner(seen: { args?: readonly string[]; cwd?: string; config?: string; existed?: string[] }) { - return ((command: string, args: readonly string[], options: { cwd?: string }) => { - seen.args = args; seen.cwd = options.cwd; +test("a hardware UDID or phone serial is pinned through a provider the runner reads as an id, not a device name", () => { + for (const device of ["00008110-001A2B3C4D5E801E", "R58M123ABC"]) { + const pin = devicePinSource(device); + assert.match(pin, /acquire: async \(\) => \(\{ id: "[^"]+", deviceId: "[^"]+", client: \{\} \}\)/); + assert.ok(pin.includes(JSON.stringify(device))); + assert.match(bundledConfigSource({ platform: "ios", bundleId: "com.example.app", device }), /device: \{ name: "mobile-dev-pinned-device"/); + assert.match(rewriteLaneConfig('export default { targets: [{ name: "a", engine: mobile() }] };', "a", device, "s"), /device: \{ name: "mobile-dev-pinned-device"/); + } + // Simulators and emulators keep the plain string their configs have always carried. + assert.equal(devicePinSource("3F2504E0-4F89-41D3-9A0C-0305E82C3301"), '"3F2504E0-4F89-41D3-9A0C-0305E82C3301"'); + assert.equal(devicePinSource("emulator-5554"), '"emulator-5554"'); +}); + +function laneSpawner(seen: { args?: readonly string[]; cwd?: string; config?: string; existed?: string[]; env?: NodeJS.ProcessEnv }) { + return ((command: string, args: readonly string[], options: { cwd?: string; env?: NodeJS.ProcessEnv }) => { + seen.args = args; seen.cwd = options.cwd; seen.env = options.env; const config = args[args.indexOf("--config") + 1]!; const imported = config.endsWith(".progress.mts") ? readFileSync(config, "utf8").match(/file:\/\/[^"]+/)![0] : undefined; seen.config = readFileSync(imported ? fileURLToPath(imported) : config, "utf8"); @@ -545,7 +558,7 @@ test("a project lane runs a hidden rewritten copy beside the config, with its ow const root = await laneProject(); const seen: { args?: readonly string[]; cwd?: string; config?: string } = {}; const result = await runRecordedTest({ projectPath: root, relativePath: FILE, configPath: join(root, "e2e.config.ts"), target: "ios", - projectLane: { target: "ios", device: "UDID-1" }, runtime: { mode: "project", root } }, { spawner: laneSpawner(seen), onProgress: () => undefined }); + projectLane: { target: "ios", device: "3F2504E0-4F89-41D3-9A0C-0305E82C3301" }, runtime: { mode: "project", root } }, { spawner: laneSpawner(seen), onProgress: () => undefined }); assert.equal(result.status, "passed"); const args = seen.args ?? []; assert.equal(seen.cwd, root); @@ -553,7 +566,7 @@ test("a project lane runs a hidden rewritten copy beside the config, with its ow const config = args[args.indexOf("--config") + 1]!; assert.equal(dirname(config), root, "the lane's config sits beside the project's own"); assert.ok(basename(config).startsWith(LANE_FILE_PREFIX)); - assert.match(seen.config!, /device: "UDID-1", session: "mobile-dev-lane-/); + assert.match(seen.config!, /device: "3F2504E0-4F89-41D3-9A0C-0305E82C3301", session: "mobile-dev-lane-/); assert.notEqual(args[args.indexOf("--output") + 1], undefined); assert.equal(dirname(args[args.indexOf("--output") + 1]!), root, "the runner refuses an --output outside the root it runs from"); assert.equal(existsSync(args[args.indexOf("--output") + 1]!), false, "the output directory is removed"); @@ -561,6 +574,16 @@ test("a project lane runs a hidden rewritten copy beside the config, with its ow assert.equal(readFileSync(join(root, "e2e.config.ts"), "utf8"), LANE_CONFIG, "the project's own config is never touched"); }); +test("a project lane on iOS hardware gets its own agent-device state; other lanes get the terminal's", async () => { + const root = await laneProject(); + const hardware: { env?: NodeJS.ProcessEnv } = {}, simulator: { env?: NodeJS.ProcessEnv } = {}; + const base = { projectPath: root, relativePath: FILE, configPath: join(root, "e2e.config.ts"), target: "ios" }; + await runRecordedTest({ ...base, projectLane: { target: "ios", device: "00008110-001A2C3E0E12801E", stateDir: "/state/project-a" } }, { spawner: laneSpawner(hardware) }); + await runRecordedTest({ ...base, projectLane: { target: "ios", device: "3F2504E0-4F89-41D3-9A0C-0305E82C3301" } }, { spawner: laneSpawner(simulator) }); + assert.equal(hardware.env?.AGENT_DEVICE_STATE_DIR, "/state/project-a"); + assert.equal(simulator.env?.AGENT_DEVICE_STATE_DIR, undefined, "a simulator lane keeps the state a terminal run would get"); +}); + test("two lanes at once use different files and different sessions, and one finishing removes only its own", async () => { const root = await laneProject(); const a: { args?: readonly string[]; config?: string } = {}, b: { args?: readonly string[]; config?: string } = {}; @@ -572,8 +595,8 @@ test("two lanes at once use different files and different sessions, and one fini assert.notEqual(a.args![a.args!.indexOf("--config") + 1], b.args![b.args!.indexOf("--config") + 1]); assert.notEqual(a.args![a.args!.indexOf("--output") + 1], b.args![b.args!.indexOf("--output") + 1]); assert.notEqual(a.config!.match(/session: "([^"]+)"/)![1], b.config!.match(/session: "([^"]+)"/)![1]); - assert.match(a.config!, /device: "A"/); - assert.match(b.config!, /device: "B"/); + assert.match(a.config!, /id: "A"/); + assert.match(b.config!, /id: "B"/); }); test("a lane of the editor's own text runs in an isolated mirror and writes nothing into the project", async () => { diff --git a/packages/shared/src/panel-target.ts b/packages/shared/src/panel-target.ts index 41d734d6..57b93a3e 100644 --- a/packages/shared/src/panel-target.ts +++ b/packages/shared/src/panel-target.ts @@ -22,7 +22,11 @@ export function recordablePlatform(device: SimulatorDevice): "ios" | "android" { export function isRecordableDevice(device?: SimulatorDevice): boolean { if (!device) return false; - if (device.kind === "physical") return device.platform === "ios" && device.state === "connected" && device.pairingState === "paired"; + if (device.kind === "physical") { + // Android phones are listed like emulators: Booted once adb has authorized them. + if (device.platform === "android") return device.state === "Booted"; + return device.platform === "ios" && device.state === "connected" && device.pairingState === "paired"; + } if (device.state !== "Booted") return false; return device.platform === "android" ? device.kind === "emulator" : device.platform === "ios" || device.platform === undefined; } diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index ac6d5271..1a2bbcbd 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -72,6 +72,24 @@ export function parseBaseUrl(value: string, label = "BAGUETTE_URL"): URL { return url; } +/** Absolute and home-relative paths, which never leave the machine in a message that may be reported. */ +const LOCAL_PATH = /(?:~|\/)[^\s"'`()<>]*\/[^\s"'`()<>]*/g; + +/** + * The fix agent-device attaches to a failure (`details.hint`), with local paths removed. agent-device + * throws `{ message, details: { reason, hint, logPath } }`; the hint is what tells the user what to do + * (set a signing team, enable Developer Mode), and the log path stays on this machine. + */ +export function errorHint(error: unknown): string | undefined { + if (error === null || typeof error !== "object" || !("details" in error)) return undefined; + const details = (error as { details?: unknown }).details; + const hint = details !== null && typeof details === "object" ? (details as { hint?: unknown }).hint : undefined; + if (typeof hint !== "string" || !hint.trim()) return undefined; + return hint.replace(LOCAL_PATH, "").trim(); +} + export function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error); + const message = error instanceof Error ? error.message : String(error); + const hint = errorHint(error); + return hint && !message.includes(hint) ? `${message} ${hint}` : message; } diff --git a/packages/skills/mobile-dev-testing/SKILL.md b/packages/skills/mobile-dev-testing/SKILL.md index efe5a055..d5fc5c2a 100644 --- a/packages/skills/mobile-dev-testing/SKILL.md +++ b/packages/skills/mobile-dev-testing/SKILL.md @@ -171,7 +171,7 @@ user the path. Nothing in the test file names a platform until you branch a line at once; read `mobile_testing_run_progress({ matrixId })` until `running` is false. `apps` defaults to the apps the test is pinned to. - **Simulators and emulators that are off are booted by the matrix**, and a missing app is copied - from another booted simulator or emulator that has it. A physical iOS device must already be connected, paired, and have a build for hardware installed. + from another booted simulator or emulator that has it. A physical iOS device must be connected, paired, unlocked and have Developer Mode on. If the app is missing, a matching `Debug-iphoneos` build on this Mac is installed; otherwise ask the user to run `npx expo run:ios --device`. A simulator build is never copied to hardware. A physical Android phone needs USB debugging on and this Mac authorized, the screen awake and unlocked, and (Xiaomi/Samsung) "Install via USB" allowed or Auto Blocker off; pass `kind: "physical"` with its adb serial. A missing app is copied from another Android device only when its ABIs match the phone; otherwise ask the user to run `npx expo run:android --device`. The test runner needs a signing team: on a signing error set `MOBILE_DEV_IOS_TEAM_ID` (Apple Team ID, `security find-identity -v -p codesigning`) and run again; relay the hint the error carries. - The runs show in the Testing Studio tab as live lanes, and the tab is locked while they go. ### A platform has no app yet diff --git a/packages/ui/src/components/testing-matrix.tsx b/packages/ui/src/components/testing-matrix.tsx index 46190344..7dff0933 100644 --- a/packages/ui/src/components/testing-matrix.tsx +++ b/packages/ui/src/components/testing-matrix.tsx @@ -11,6 +11,7 @@ import { Badge } from "./ui/badge.tsx"; import { Button } from "./ui/button.tsx"; import { Input } from "./ui/input.tsx"; import { Label } from "./ui/label.tsx"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/base-select.tsx"; /** One row of the checklist: a checkbox, the device, and what is true of it right now. */ function DeviceRow({ device, checked, busy, appMissing, onToggle }: { device: MatrixDeviceOption; checked: boolean; busy: boolean; appMissing: boolean; onToggle: (value: boolean) => void }) { @@ -25,12 +26,39 @@ function DeviceRow({ device, checked, busy, appMissing, onToggle }: { device: Ma {busy && Busy} {device.kind === "physical" ? device.connectionState : device.booted ? "Booted" : "Off"} - {device.booted && device.installed !== undefined && {device.installed ? "Installed" : "App missing"}} ; } +const SIGNING_SOURCE: Record = { env: "set by the environment", user: "your choice", project: "from the project", keychain: "the only team in your keychain" }; +const AUTOMATIC = "__automatic__"; + +/** The team that signs the test runner on a physical iPhone: read-only when the environment pins it, otherwise a picker. */ +export function SigningTeam({ panel }: { panel: TestingPanel }) { + const state = useSyncExternalStore(panel.subscribe, panel.getSnapshot); + const signing = state.iosSigning; + useEffect(() => { void panel.loadIosSigning(); }, [panel]); + if (!signing) return null; + const label = (team: { id: string; name?: string }) => team.name ? `${team.name} (${team.id})` : team.id; + const resolved = signing.resolved; + if (resolved?.source === "env") return
+

{label(resolved)} · {resolved.envVar ? `set by ${resolved.envVar}` : SIGNING_SOURCE.env}

+

Fixed by the environment, so it can't be changed here. To choose another team, unset {resolved.envVar ?? "MOBILE_DEV_IOS_TEAM_ID"} and restart Mobile Dev.

+
; + const teams = signing.teams.some(team => team.id === signing.saved) || !signing.saved ? signing.teams : [...signing.teams, { id: signing.saved }]; + const items = [{ value: AUTOMATIC, label: resolved && resolved.source !== "user" ? `Automatic · ${label(resolved)}` : "Automatic" }, ...teams.map(team => ({ value: team.id, label: label(team) }))]; + return
+ + {resolved ?

Signs the test runner on iPhones: {SIGNING_SOURCE[resolved.source]}.

+ : No signing team yet. Choose one{signing.teams.length === 0 ? ", after signing in to Xcode with your Apple ID" : ""} to record or run on an iPhone.} +
; +} + /** * The matrix checklist in the setup popover: tick devices to run the open test on all of them. * A project with its own e2e config gets it too: each lane runs the config's target for the device's platform. diff --git a/packages/ui/src/components/testing-setup.tsx b/packages/ui/src/components/testing-setup.tsx index c33476b7..8a25a725 100644 --- a/packages/ui/src/components/testing-setup.tsx +++ b/packages/ui/src/components/testing-setup.tsx @@ -10,7 +10,7 @@ import { Label } from "./ui/label.tsx"; import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover.tsx"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/base-select.tsx"; import { Switch } from "./ui/switch.tsx"; -import { MatrixDevices } from "./testing-matrix.tsx"; +import { MatrixDevices, SigningTeam } from "./testing-matrix.tsx"; type SetupPlanView = { id: string; actions: { action: string; path: string; detail: string }[]; installCommand: string }; type SetupTarget = { name: string; platform: "ios" | "android"; bundleId: string }; @@ -209,6 +209,7 @@ export function TestingSetup({ panel }: { panel: TestingPanel }) { {loginActive && } } ; + const signing = panel.showsSigningTeam ?
: null; const needsModel = state.modelPickerOpen && !state.modelPreference; const modelHint = "Deterministic steps never use a model. Only the provider, model and endpoint are saved, never credentials or prompts."; @@ -235,6 +236,7 @@ export function TestingSetup({ panel }: { panel: TestingPanel }) { + {signing}
@@ -255,6 +257,7 @@ export function TestingSetup({ panel }: { panel: TestingPanel }) { {state.targets.length > 0 ?
    {state.targets.map(target =>
  • {target.name}{target.platform ?? "unknown"} · {target.bundleId ?? "no identifier"}
  • )}
:

No targets configured.

}
+ {signing}
) : <> diff --git a/packages/ui/src/components/testing-view.tsx b/packages/ui/src/components/testing-view.tsx index 5bac8e57..5738d570 100644 --- a/packages/ui/src/components/testing-view.tsx +++ b/packages/ui/src/components/testing-view.tsx @@ -290,8 +290,8 @@ export function TestingView({ panel, deviceApps }: { panel: TestingPanel; device : state.loadingProject ? "" : state.targets.length === 0 ? (panel.noProject ? "Open the app you want to record in the mirror. Testing Studio records against the app in the foreground." : "No mobile app identifier was found. Open the app in the mirror, or use E2E setup to enter one.") : !target?.bundleId ? `Target "${target?.name}" has no app identifier. Enter one in E2E setup.` - : !booted ? "Recording needs a booted simulator, emulator or connected iOS device in the mirror. If one is available, choose it from Add device." - : !isRecordableDevice(device) ? "Pair and trust this iOS device, or choose a simulator or emulator. Physical Android recording is not available yet." + : !booted ? "Recording needs a booted simulator, emulator or connected phone in the mirror. If one is available, choose it from Add device." + : !isRecordableDevice(device) ? "Pair and trust this iOS device, or authorize USB debugging on this Android phone, or choose a simulator or emulator." : mismatch; return
@@ -310,6 +310,7 @@ export function TestingView({ panel, deviceApps }: { panel: TestingPanel; device
+ {state.error && Testing Studio @@ -460,9 +461,9 @@ function TestingControls({ panel, recordable, deviceId, platform }: { panel: Tes : recording ? : state.steps.length > 0 - ? + ? : } + onClick={() => void panel.startRecording(deviceId, platform)}>Record} )} + : No Apple Development identity was found. Sign in to Xcode with your Apple ID, or set MOBILE_DEV_IOS_TEAM_ID.} + + + ; +} diff --git a/packages/ui/src/physical-touch.ts b/packages/ui/src/physical-touch.ts new file mode 100644 index 00000000..88d91ce0 --- /dev/null +++ b/packages/ui/src/physical-touch.ts @@ -0,0 +1,32 @@ +import type { StreamMessage } from "./stream-input.ts"; + +/** The only messages `mobile_ios_mirror_input` accepts: ordered touch samples. */ +export type PhysicalTouchMessage = Extract; + +const SWIPE_STEPS = 8; + +/** + * Expresses a panel input message as the touch samples a physical iPhone's mirror takes. The + * simulator and Android streams take `tap` and `swipe` directly; the physical iOS tool takes only + * touches, and one message of another type rejects the whole batch. Buttons, keys and text have no + * touch form and are dropped (the hardware buttons are disabled on a physical iOS mirror). + */ +export function toPhysicalTouches(message: StreamMessage): PhysicalTouchMessage[] { + switch (message.type) { + case "touch1-down": case "touch1-move": case "touch1-up": return [message]; + case "tap": { + const { x, y, width, height } = message; + return [{ type: "touch1-down", x, y, width, height }, { type: "touch1-up", x, y, width, height }]; + } + case "swipe": { + const { startX, startY, endX, endY, width, height } = message; + const at = (step: number) => ({ x: startX + (endX - startX) * step / SWIPE_STEPS, y: startY + (endY - startY) * step / SWIPE_STEPS, width, height }); + return [ + { type: "touch1-down", ...at(0) }, + ...Array.from({ length: SWIPE_STEPS - 1 }, (_, index) => ({ type: "touch1-move" as const, ...at(index + 1) })), + { type: "touch1-up", ...at(SWIPE_STEPS) }, + ]; + } + default: return []; + } +} diff --git a/packages/ui/src/simulator-panel.ts b/packages/ui/src/simulator-panel.ts index 44d14ca4..fe501d92 100644 --- a/packages/ui/src/simulator-panel.ts +++ b/packages/ui/src/simulator-panel.ts @@ -26,6 +26,7 @@ import { FrameStream } from "./frame-stream.ts"; import { frameArrivals, observeFrameArrivals } from "./frame-arrivals.ts"; import { readFrame } from "./read-frame.ts"; import { BrowserProfile } from "./browser-profile.ts"; +import { toPhysicalTouches } from "./physical-touch.ts"; import { StreamInput } from "./stream-input.ts"; import type { StreamMessage } from "./stream-input.ts"; import { IosVideo } from "./ios-video.ts"; @@ -133,6 +134,12 @@ export function createSimulatorPanel( // 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(); + // A physical iPhone's input tool takes only touch samples, so a recorded tap or swipe becomes touches. + if (stream.physicalIos) { + const touches = toPhysicalTouches(message); + if (touches.length === 1) stream.input?.send(touches[0]!); else stream.input?.sendAll(touches); + return; + } stream.input?.send(message); } @@ -309,7 +316,7 @@ export function createSimulatorPanel( // there is no input message that clears a field. So a `fill` recorded into a field that // already has text leaves the app showing something the test will not produce — the step is // still right, the screen behind it is not. Non-ASCII is refused by the input schema. - else if (selected?.kind === "physical") { + else if (selected?.kind === "physical" && selected.platform === "ios") { if (!action.nodeId) notice("The text field could not be identified. Read the screen and record the step again."); else void testRecorder.fillTree(selected.udid, action.nodeId, action.text).catch(error => notice(error instanceof Error ? error.message : String(error))); } diff --git a/packages/ui/src/stream-input.ts b/packages/ui/src/stream-input.ts index 4cc80f38..bd735fa6 100644 --- a/packages/ui/src/stream-input.ts +++ b/packages/ui/src/stream-input.ts @@ -29,6 +29,18 @@ export class StreamInput { void this.flush(); } + /** Queues a gesture's samples as they are: a swipe's moves are the path, so they are not coalesced. */ + sendAll(messages: StreamMessage[]) { + if (this.accepting === false) return; + this.queued.push(...messages); + if (this.queued.length > 64) { + this.close(); + this.failed(new Error("Simulator input cannot keep up. Reconnect before continuing.")); + return; + } + void this.flush(); + } + flush(): Promise { if (this.sending) return this.sending; this.sending = this.drain().catch(error => { diff --git a/packages/ui/src/test-recorder.ts b/packages/ui/src/test-recorder.ts index cf73a887..a15715a8 100644 --- a/packages/ui/src/test-recorder.ts +++ b/packages/ui/src/test-recorder.ts @@ -486,14 +486,16 @@ export class TestRecorder { * Measured as its own timing: how long Record is unusable for is a number the panel is judged on, * and it is not the same as `ui.testing.tree_read`, which also covers the warm reads during a * recording. A read that fails leaves `preparing` false — the overlay must never outlive the - * thing it is explaining — and the next hover retries as it always did. + * thing it is explaining — and reports why in the recorder's alert; the next hover retries. */ private async prepare(deviceId: string, platform: DevicePlatform): Promise { const startedAt = performance.now(); try { await this.currentComponents(); - } catch { - // Silent: a failed warm read is not an error the user asked for. The first hover says so. + } catch (error) { + // Shown, not swallowed: a recording that cannot read the device (a missing signing team, a + // locked phone) would otherwise just lose its overlay and look like Record did nothing. + if (this.isRecordingDevice(deviceId, platform)) this.update({ error: error instanceof Error ? error.message : String(error) }); } finally { recordUiTiming("ui.testing.record_prepare", performance.now() - startedAt, platform); // Only the recording this prepared for: Stop, or a second Record, owns the flag after that. diff --git a/packages/ui/src/testing-matrix.ts b/packages/ui/src/testing-matrix.ts index c5e24c16..7e244e52 100644 --- a/packages/ui/src/testing-matrix.ts +++ b/packages/ui/src/testing-matrix.ts @@ -106,11 +106,17 @@ export function parseMatrixDevices(platform: MatrixPlatform, value: unknown): Ma const devices = record(value)?.devices; if (!Array.isArray(devices)) return []; return devices.map(record).filter((device): device is Record => device !== null && Boolean(str(device.udid))) - .filter(device => str(device.kind) !== "physical") - .map(device => ({ - deviceId: str(device.udid), name: str(device.name) || str(device.udid), platform, kind: platform === "ios" ? "simulator" : "emulator", runtime: str(device.runtime), - booted: str(device.state) === "Booted" || str(device.state) === "connected" || str(device.state) === "device", - })); + // Physical iOS comes from its own listing; an Android phone is listed with the emulators. + .filter(device => str(device.kind) !== "physical" || platform === "android") + .map(device => { + const physical = str(device.kind) === "physical"; + return { + deviceId: str(device.udid), name: str(device.name) || str(device.udid), platform, kind: physical ? "physical" as const : platform === "ios" ? "simulator" as const : "emulator" as const, runtime: str(device.runtime), + booted: str(device.state) === "Booted" || str(device.state) === "connected" || str(device.state) === "device", + // An unauthorized or offline phone can be listed but not run on. + ...(physical && str(device.state) !== "Booted" ? { connectionState: str(device.state) === "unauthorized" ? "Authorize USB debugging" : "Offline" } : {}), + }; + }); } export function parsePhysicalIosMatrixDevices(value: unknown): MatrixDeviceOption[] { diff --git a/packages/ui/src/testing-panel.ts b/packages/ui/src/testing-panel.ts index b2bf8936..5ed06b76 100644 --- a/packages/ui/src/testing-panel.ts +++ b/packages/ui/src/testing-panel.ts @@ -4,6 +4,7 @@ import type { DeviceAppsStore } from "./device-apps.ts"; import type { SimulatorDevice } from "@mobile-dev/shared/protocol.ts"; import { captureUiError, countUiEvent, getUiTelemetryAttributes, recordUiTiming } from "./telemetry.ts"; import { testRecorder } from "./test-recorder.ts"; +import type { DevicePlatform } from "./test-recorder.ts"; import type { RecorderTreeSource } from "./test-recorder.ts"; import { PANEL_HEARTBEAT_MS, isRecordableDevice, recordablePlatform } from "@mobile-dev/shared/panel-target.ts"; import type { ScreenComponent } from "@mobile-dev/shared/screen-annotations.ts"; @@ -144,6 +145,10 @@ export type TestingSnapshot = { /** Devices the matrix checklist can offer, with whether each is booted and has the app. */ matrixDevices: MatrixDeviceOption[]; matrixLoading: boolean; + /** The signing team for physical iPhones, as the server resolved it; undefined until read. */ + iosSigning?: IosSigningView; + /** Set while Record or Run on a physical iPhone waits for the user to pick a signing team. */ + signingPrompt?: { teams: IosSigningTeamView[] }; /** The devices the user ticked for the current test in this panel session. */ matrixSelected: string[]; /** How many devices run at once; the rest queue. Saved per project. */ @@ -188,7 +193,28 @@ function object(value: unknown): Record | null { return value && typeof value === "object" ? value as Record : null; } function text(value: unknown): string { return typeof value === "string" ? value : ""; } + +function parseIosSigning(value: unknown): IosSigningView { + const data = object(value) ?? {}; + const team = (entry: unknown): IosSigningTeamView | undefined => { const item = object(entry); return item && text(item.id) ? { id: text(item.id), ...(text(item.name) ? { name: text(item.name) } : {}) } : undefined; }; + const resolved = object(data.resolved); + const source = text(resolved?.source); + return { + teams: (Array.isArray(data.teams) ? data.teams : []).map(team).filter((entry): entry is IosSigningTeamView => Boolean(entry)), + ...(resolved && team(resolved) && ["env", "user", "project", "keychain"].includes(source) ? { resolved: { ...team(resolved)!, source: source as "env", ...(source === "env" && ["MOBILE_DEV_IOS_TEAM_ID", "AGENT_DEVICE_IOS_TEAM_ID"].includes(text(resolved.envVar)) ? { envVar: text(resolved.envVar) } : {}) } } : {}), + ...(text(data.saved) ? { saved: text(data.saved) } : {}), + ...(text(data.error) ? { error: text(data.error) } : {}), + }; +} /** How a platform reads in the panel. */ +export type IosSigningTeamView = { id: string; name?: string }; +export type IosSigningView = { + teams: IosSigningTeamView[]; + resolved?: IosSigningTeamView & { source: "env" | "user" | "project" | "keychain"; envVar?: string }; + saved?: string; + error?: string; +}; + export function platformLabel(platform: "ios" | "android"): string { return platform === "ios" ? "iOS" : "Android"; } /** @@ -1653,6 +1679,7 @@ export class TestingPanel { const untilSource = untilLine === undefined ? source : storedTestUntilSource(source, untilLine); if (untilSource === undefined) return; if (!this.hasBundledModel(untilSource, { kind: "stored", ...(untilLine === undefined ? {} : { untilLine }) })) return; + if (!await this.ensureIosTeam()) return; // A Testing Studio test runs against the app it is pinned to, never whichever app is in front. A test // with no app yet takes the one in front and keeps it, so later runs are pinned. // A test with an app on both platforms runs the one for the mirrored device's platform. @@ -1660,6 +1687,13 @@ export class TestingPanel { const mirrored = this.mirroredPlatform; const pinned = stored && mirrored ? this.storedAppOn(mirrored) : stored; const runTarget = pinned ?? (stored ? undefined : this.foregroundTarget); + // A pinned test with no app for the mirrored phone's platform must not fall through to an unpinned + // run on whatever device the runner finds; say why nothing ran. + const mirror = this.deviceApps.getSnapshot().device; + if (stored && !pinned && mirror?.kind === "physical") { + this.update({ error: `This test is pinned to ${stored.platform === "ios" ? "iOS" : "Android"} and has no app for ${mirror.name}'s platform. Show a ${stored.platform === "ios" ? "iOS" : "Android"} device in the mirror, or add an app for this platform first.` }); + return; + } if (this.snapshot.runtimeMode === "bundled" && !runTarget) return; if (this.runsOnMatrix) { await this.runMatrix({ relativePath, source: untilSource, ...(untilLine === undefined ? {} : { untilLine }), callLines: storedTestCallLines(source) }); return; } this.update({ running: true, error: null }); @@ -1736,6 +1770,7 @@ export class TestingPanel { if (options.untilStepId && !until) return; const previewSource = until?.source ?? testRecorder.source; if (!this.hasBundledModel(previewSource, { kind: "recording", options })) return; + if (!await this.ensureIosTeam()) return; const relativePath = this.relativePath; if (this.runsOnMatrix) { await this.runMatrix({ relativePath, source: previewSource, ...(until ? { untilLine: until.untilLine } : {}) }); return; } this.update({ running: true, error: null, pendingRun: false }); @@ -1904,6 +1939,81 @@ export class TestingPanel { } } + /** Reads the keychain's signing teams and the one in effect for physical iPhones. */ + async loadIosSigning() { + if (!this.snapshot.available) return; + try { + const result = await this.call("mobile_testing_ios_signing", this.snapshot.projectPath ? { projectPath: this.snapshot.projectPath } : {}, 30_000); + if (!this.disposed) this.update({ iosSigning: parseIosSigning(result.structuredContent) }); + } catch (error) { + if (!this.disposed) this.update({ error: `Could not read the signing team: ${error instanceof Error ? error.message : String(error)}` }); + } + } + + /** Whether the signing team is relevant: a physical iPhone is mirrored or listed for the matrix. */ + get showsSigningTeam(): boolean { + const mirror = this.deviceApps.getSnapshot().device; + if (mirror?.kind === "physical" && mirror.platform === "ios" && mirror.state === "connected") return true; + // `booted` is connected and paired: an iPhone that is only known to the Mac does not need a team yet. + return this.snapshot.matrixDevices.some(device => device.kind === "physical" && device.platform === "ios" && device.booted); + } + + private get usesPhysicalIos(): boolean { + const mirror = this.deviceApps.getSnapshot().device; + const mirrorPhysical = mirror?.kind === "physical" && mirror.platform === "ios"; + if (!this.runsOnMatrix) return mirrorPhysical; + return this.matrixSelection.some(device => device.kind === "physical" && device.platform === "ios"); + } + + private signingWaiter?: (chosen: boolean) => void; + + /** + * Resolves once a physical iPhone has a signing team, asking the user to pick one when none + * resolves. False means the user declined; true also when no iPhone is involved or the server + * cannot say (the run then reports the real error). + */ + async ensureIosTeam(physicalIos: boolean = this.usesPhysicalIos): Promise { + if (!physicalIos || !this.snapshot.available) return true; + let view: IosSigningView; + try { view = parseIosSigning((await this.call("mobile_testing_ios_signing", this.snapshot.projectPath ? { projectPath: this.snapshot.projectPath } : {}, 30_000)).structuredContent); } + catch { return true; } + if (view.resolved || this.disposed) { if (!this.disposed) this.update({ iosSigning: view }); return true; } + this.signingWaiter?.(false); + countUiEvent("ui.testing.ios_signing_prompt"); + return new Promise(resolve => { + this.signingWaiter = resolve; + this.update({ iosSigning: view, signingPrompt: { teams: view.teams } }); + }); + } + + dismissSigningPrompt() { + const waiter = this.signingWaiter; + this.signingWaiter = undefined; + this.update({ signingPrompt: undefined }); + waiter?.(false); + } + + /** Starts recording, first making sure a physical iPhone has a team to sign the runner with. */ + async startRecording(deviceId: string, platform: DevicePlatform, keepSteps?: boolean) { + const mirror = this.deviceApps.getSnapshot().device; + if (!await this.ensureIosTeam(mirror?.kind === "physical" && mirror.platform === "ios")) return; + testRecorder.start(deviceId, platform, keepSteps); + } + + /** Saves the team that signs the runner on physical iPhones; undefined goes back to the automatic choice. */ + async chooseIosTeam(teamId?: string) { + try { + const result = await this.call("mobile_testing_ios_signing_team", { ...(teamId ? { teamId } : {}), ...(this.snapshot.projectPath ? { projectPath: this.snapshot.projectPath } : {}) }, 60_000); + if (this.disposed) return; + const iosSigning = parseIosSigning(result.structuredContent); + this.update({ iosSigning, error: null, ...(iosSigning.resolved && this.signingWaiter ? { signingPrompt: undefined } : {}) }); + countUiEvent("ui.testing.ios_signing_team"); + if (iosSigning.resolved) { const waiter = this.signingWaiter; this.signingWaiter = undefined; waiter?.(true); } + } catch (error) { + if (!this.disposed) this.update({ error: `Could not save the signing team: ${error instanceof Error ? error.message : String(error)}` }); + } + } + private matrixCallLines?: readonly number[]; private matrixUntilLine?: number; private laneSignature = ""; diff --git a/packages/ui/test/physical-touch.test.ts b/packages/ui/test/physical-touch.test.ts new file mode 100644 index 00000000..9c484c80 --- /dev/null +++ b/packages/ui/test/physical-touch.test.ts @@ -0,0 +1,30 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { streamMessageSchema } from "@mobile-dev/shared/protocol.ts"; +import { touchInputSchema } from "@mobile-dev/shared/protocol.ts"; +import { toPhysicalTouches } from "../src/physical-touch.ts"; + +const SCREEN = { width: 400, height: 800 }; + +test("a recorded tap reaches a physical iPhone as touch-down and touch-up, the only types its tool accepts", () => { + const touches = toPhysicalTouches({ type: "tap", x: 10, y: 20, ...SCREEN }); + assert.deepEqual(touches.map(touch => touch.type), ["touch1-down", "touch1-up"]); + for (const touch of touches) assert.equal(touchInputSchema.safeParse(touch).success, true); +}); + +test("a recorded swipe is a touch path from start to end", () => { + const touches = toPhysicalTouches({ type: "swipe", startX: 0, startY: 100, endX: 0, endY: 500, ...SCREEN, duration: 0.3 }); + assert.equal(touches[0]!.type, "touch1-down"); + assert.equal(touches.at(-1)!.type, "touch1-up"); + assert.deepEqual([touches[0]!.y, touches.at(-1)!.y], [100, 500]); + assert.ok(touches.slice(1, -1).every(touch => touch.type === "touch1-move")); + assert.ok(touches.length <= 64); + for (const touch of touches) assert.equal(touchInputSchema.safeParse(touch).success, true); +}); + +test("touches pass through and messages with no touch form are dropped", () => { + const down = streamMessageSchema.parse({ type: "touch1-down", x: 1, y: 2, ...SCREEN }); + assert.deepEqual(toPhysicalTouches(down), [down]); + for (const message of [{ type: "button", button: "home" }, { type: "type", text: "a" }, { type: "key", code: "Enter" }] as const) + assert.deepEqual(toPhysicalTouches(streamMessageSchema.parse(message)), []); +}); diff --git a/packages/ui/test/signing-team-ui.test.ts b/packages/ui/test/signing-team-ui.test.ts new file mode 100644 index 00000000..22b7de83 --- /dev/null +++ b/packages/ui/test/signing-team-ui.test.ts @@ -0,0 +1,91 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { build } from "esbuild"; +import { JSDOM } from "jsdom"; + +const TEAMS = [{ id: "ABCDE12345", name: "Hur Ali" }, { id: "FGHIJ67890", name: "Callstack" }]; + +async function mountSigning(scenario: { signing: Record; device?: Record; matrixDevices?: unknown[] }) { + const built = await build({ + stdin: { contents: ` + import { createRoot } from "react-dom/client"; + import { flushSync } from "react-dom"; + import { TestingPanel } from "./packages/ui/src/testing-panel.ts"; + import { SigningTeam } from "./packages/ui/src/components/testing-matrix.tsx"; + export function mount(scenario) { + const calls = []; + const host = { async callServerTool({ name, arguments: input }) { + calls.push({ name, input }); + if (name === "mobile_testing_ios_signing") return { content: [], structuredContent: scenario.signing }; + if (name === "mobile_testing_ios_signing_team") return { content: [], structuredContent: { ...scenario.signing, saved: input.teamId } }; + return { content: [], structuredContent: {} }; + }, getHostCapabilities() { return undefined; } }; + const state = { device: scenario.device, apps: [], ready: true }; + const deviceApps = { subscribe: () => () => undefined, getSnapshot: () => state }; + const panel = new TestingPanel(host, deviceApps, { heartbeatMs: 1e9 }); + panel.update({ available: true, matrixDevices: scenario.matrixDevices ?? [] }); + const root = createRoot(document.getElementById("root")); + flushSync(() => root.render()); + return { panel, calls, close: () => { root.unmount(); panel.dispose?.(); } }; + }`, resolveDir: process.cwd(), loader: "tsx" }, + bundle: true, write: false, format: "iife", globalName: "RenderTest", platform: "browser", jsx: "automatic", + define: { "process.env.NODE_ENV": '"production"' }, logLevel: "silent", + }); + const dom = new JSDOM('
', { pretendToBeVisual: true, runScripts: "outside-only", url: "https://mobile-dev.test/" }); + const window = dom.window as unknown as Record; + window.ResizeObserver = class { observe() {} disconnect() {} unobserve() {} }; + window.eval(built.outputFiles[0]!.text); + const mounted = window.RenderTest.mount(scenario); + await new Promise(resolve => setTimeout(resolve, 50)); + return { dom, mounted, root: dom.window.document.getElementById("root")! }; +} + +test("an env-pinned team is read-only and says how to change it; any other source is a dropdown", async t => { + const pinned = await mountSigning({ signing: { teams: TEAMS, resolved: { id: "ABCDE12345", name: "Hur Ali", source: "env", envVar: "AGENT_DEVICE_IOS_TEAM_ID" } } }); + t.after(() => pinned.mounted.close()); + assert.equal(pinned.root.querySelector("[role=combobox]"), null); + assert.match(pinned.root.textContent ?? "", /set by AGENT_DEVICE_IOS_TEAM_ID/); + assert.match(pinned.root.textContent ?? "", /unset AGENT_DEVICE_IOS_TEAM_ID and restart/); + + const chosen = await mountSigning({ signing: { teams: TEAMS, saved: "ABCDE12345", resolved: { id: "ABCDE12345", name: "Hur Ali", source: "user" } } }); + t.after(() => chosen.mounted.close()); + const trigger = chosen.root.querySelector("[role=combobox]") as HTMLElement | null; + assert.ok(trigger, "the dropdown renders for a saved choice"); + assert.match(trigger!.textContent ?? "", /Hur Ali \(ABCDE12345\)/); + assert.equal(chosen.root.querySelector("[data-ios-signing]")?.getAttribute("data-ios-signing"), "user"); +}); + +test("choosing Automatic clears the saved team and another team switches it", async t => { + const view = await mountSigning({ signing: { teams: TEAMS, saved: "ABCDE12345", resolved: { id: "ABCDE12345", source: "user" } } }); + t.after(() => view.mounted.close()); + await view.mounted.panel.chooseIosTeam("FGHIJ67890"); + await view.mounted.panel.chooseIosTeam(undefined); + const saves = view.mounted.calls.filter((call: { name: string }) => call.name === "mobile_testing_ios_signing_team"); + assert.deepEqual(Array.from(saves, (call: { input: { teamId?: string } }) => call.input.teamId), ["FGHIJ67890", undefined]); + // The control offers every keychain team and an Automatic row, however it is opened. + const trigger = view.root.querySelector("[role=combobox]") as HTMLElement; + const window = view.dom.window; + trigger.dispatchEvent(new window.MouseEvent("pointerdown", { bubbles: true, button: 0 })); + trigger.dispatchEvent(new window.MouseEvent("mousedown", { bubbles: true, button: 0 })); + trigger.dispatchEvent(new window.MouseEvent("click", { bubbles: true, button: 0 })); + await new Promise(resolve => setTimeout(resolve, 100)); + const options = [...window.document.querySelectorAll("[role=option]")].map(option => option.textContent); + assert.deepEqual(options, ["Automatic", "Hur Ali (ABCDE12345)", "Callstack (FGHIJ67890)"]); +}); + +test("the signing team shows only for a connected iPhone", async t => { + const phone = { deviceId: "p", name: "iPhone", platform: "ios", kind: "physical", runtime: "iOS", booted: false }; + const cases: [string, { device?: Record; matrixDevices?: unknown[] }, boolean][] = [ + ["a paired but unplugged iPhone in the matrix", { matrixDevices: [phone] }, false], + ["a connected, paired iPhone in the matrix", { matrixDevices: [{ ...phone, booted: true }] }, true], + ["an Android phone", { matrixDevices: [{ ...phone, platform: "android", booted: true }] }, false], + ["a simulator", { matrixDevices: [{ ...phone, kind: "simulator", booted: true }] }, false], + ["a disconnected mirrored iPhone", { device: { udid: "p", name: "iPhone", state: "disconnected", platform: "ios", kind: "physical" } }, false], + ["a connected mirrored iPhone", { device: { udid: "p", name: "iPhone", state: "connected", platform: "ios", kind: "physical" } }, true], + ]; + for (const [label, scenario, expected] of cases) { + const view = await mountSigning({ signing: { teams: TEAMS }, ...scenario }); + t.after(() => view.mounted.close()); + assert.equal(view.mounted.panel.showsSigningTeam, expected, label); + } +}); diff --git a/packages/ui/test/test-recorder.test.ts b/packages/ui/test/test-recorder.test.ts index c1593ceb..057b0d4a 100644 --- a/packages/ui/test/test-recorder.test.ts +++ b/packages/ui/test/test-recorder.test.ts @@ -833,3 +833,12 @@ test("only the mirror of the platform being recorded or picked draws the recorde assert.equal(recorderShowsOn("ios", "android"), false); assert.equal(recorderShowsOn("", "ios"), true, "nothing recording: nothing to hide"); }); + +test("a failed first screen read after Record says why instead of silently dropping the overlay", async () => { + const recorder = new TestRecorder(); + recorder.attach(UDID, "ios", { readComponents: async () => { throw new Error("Choose your signing team in E2E setup → Devices"); }, screen: () => SCREEN, release() {} }); + recorder.start(UDID, "ios"); + await new Promise(resolve => setTimeout(resolve, 20)); + assert.equal(recorder.getSnapshot().preparing, false); + assert.match(recorder.getSnapshot().error, /signing team/); +}); diff --git a/packages/ui/test/testing-matrix.test.ts b/packages/ui/test/testing-matrix.test.ts index 93f95efa..c7e40677 100644 --- a/packages/ui/test/testing-matrix.test.ts +++ b/packages/ui/test/testing-matrix.test.ts @@ -51,6 +51,16 @@ test("the checklist reads simulators and emulators and skips physical iPhones", assert.deepEqual(android.map(device => [device.deviceId, device.booted]), [["emulator-5554", true], ["avd:Old", false]]); }); +test("the Android checklist keeps authorized phones as physical rows and marks unauthorized ones unavailable", () => { + const android = parseMatrixDevices("android", { devices: [ + { udid: "emulator-5554", name: "Pixel", state: "Booted", kind: "emulator" }, + { udid: "R5CT1", name: "Galaxy", state: "Booted", kind: "physical" }, + { udid: "R5CT2", name: "Other", state: "unauthorized", kind: "physical" }, + ] }); + assert.deepEqual(android.map(device => [device.deviceId, device.kind, device.booted, device.connectionState]), [ + ["emulator-5554", "emulator", true, undefined], ["R5CT1", "physical", true, undefined], ["R5CT2", "physical", false, "Authorize USB debugging"]]); +}); + test("physical iOS checklist distinguishes connected, unpaired and disconnected devices", () => { const devices = parsePhysicalIosMatrixDevices({ physicalDevices: [ { udid: "P", name: "Phone", state: "connected", pairingState: "paired", runtime: "iOS 27" }, diff --git a/packages/ui/test/testing-panel-project-state.test.ts b/packages/ui/test/testing-panel-project-state.test.ts index 422e0f24..0c8bee3a 100644 --- a/packages/ui/test/testing-panel-project-state.test.ts +++ b/packages/ui/test/testing-panel-project-state.test.ts @@ -99,3 +99,81 @@ test("clicking a lane switches the layout and mirror to it, and a poll does not" await internals.readMatrix("m").catch(() => undefined); assert.equal(focused.length, before); }); + +test("the iPhone signing team is read, then saved or cleared through the server", async t => { + storage(); + const calls: { name: string; input: Record }[] = []; + const status = { teams: [{ id: "ABCDE12345", name: "Acme" }, { id: "FGHIJ67890" }], resolved: { id: "ABCDE12345", name: "Acme", source: "keychain" } }; + const bridge = { async callServerTool({ name, arguments: input }: { name: string; arguments: Record }) { + calls.push({ name, input }); + if (name === "mobile_testing_ios_signing") return { content: [], structuredContent: status }; + if (name === "mobile_testing_ios_signing_team") return { content: [], structuredContent: input.teamId ? { ...status, saved: input.teamId, resolved: { id: input.teamId, source: "user" } } : status }; + return { content: [], structuredContent: {} }; + } } as unknown as HostBridge; + const panel = new TestingPanel(bridge, deviceApps, { heartbeatMs: 1e9 }); + t.after(() => panel.dispose?.()); + panel.setAvailable(true); + await panel.loadIosSigning(); + assert.deepEqual(panel.getSnapshot().iosSigning?.resolved, { id: "ABCDE12345", name: "Acme", source: "keychain" }); + assert.equal(panel.getSnapshot().iosSigning?.teams.length, 2); + await panel.chooseIosTeam("FGHIJ67890"); + assert.equal(panel.getSnapshot().iosSigning?.resolved?.envVar, undefined); + assert.equal(panel.getSnapshot().iosSigning?.saved, "FGHIJ67890"); + assert.equal(panel.getSnapshot().iosSigning?.resolved?.source, "user"); + assert.equal(calls.filter(call => call.name === "mobile_testing_ios_signing_team").at(-1)?.input.teamId, "FGHIJ67890"); + await panel.chooseIosTeam(undefined); + assert.equal(calls.filter(call => call.name === "mobile_testing_ios_signing_team").at(-1)?.input.teamId, undefined); + assert.equal(panel.getSnapshot().iosSigning?.saved, undefined); +}); + +test("the signing view keeps which environment variable pinned the team, and drops an unknown one", async t => { + storage(); + let resolved: Record = { id: "ENVTEAM123", source: "env", envVar: "AGENT_DEVICE_IOS_TEAM_ID" }; + const bridge = { async callServerTool() { return { content: [], structuredContent: { teams: [], resolved } }; } } as unknown as HostBridge; + const panel = new TestingPanel(bridge, deviceApps, { heartbeatMs: 1e9 }); + t.after(() => panel.dispose?.()); + panel.setAvailable(true); + await panel.loadIosSigning(); + assert.equal(panel.getSnapshot().iosSigning?.resolved?.envVar, "AGENT_DEVICE_IOS_TEAM_ID"); + resolved = { id: "ENVTEAM123", source: "env", envVar: "SOMETHING_ELSE" }; + await panel.loadIosSigning(); + assert.equal(panel.getSnapshot().iosSigning?.resolved?.envVar, undefined); +}); + +test("with no signing team, a physical iPhone recording asks first and continues after the user picks", async t => { + storage(); + const phone = { udid: "phone-1", name: "iPhone", state: "connected", runtime: "iOS", platform: "ios", kind: "physical" }; + const phoneApps = { subscribe: () => () => undefined, getSnapshot: () => ({ device: phone }) } as unknown as DeviceAppsStore; + const teams = [{ id: "ABCDE12345", name: "Hur Ali" }, { id: "FGHIJ67890", name: "Callstack" }]; + const calls: string[] = []; + let saved: string | undefined; + const bridge = { async callServerTool({ name, arguments: input }: { name: string; arguments: Record }) { + calls.push(name); + if (name === "mobile_testing_ios_signing") return { content: [], structuredContent: { teams, error: "two teams" } }; + if (name === "mobile_testing_ios_signing_team") { saved = String(input.teamId); return { content: [], structuredContent: { teams, saved, resolved: { id: saved, source: "user" } } }; } + return { content: [], structuredContent: {} }; + } } as unknown as HostBridge; + const panel = new TestingPanel(bridge, phoneApps, { heartbeatMs: 1e9 }); + t.after(() => panel.dispose?.()); + panel.setAvailable(true); + let continued = false; + const waiting = panel.ensureIosTeam().then(chosen => { continued = chosen; }); + await new Promise(resolve => setTimeout(resolve, 20)); + assert.deepEqual(panel.getSnapshot().signingPrompt?.teams, teams); + assert.equal(continued, false); + await panel.chooseIosTeam("FGHIJ67890"); + await waiting; + assert.equal(continued, true); + assert.equal(saved, "FGHIJ67890"); + assert.equal(panel.getSnapshot().signingPrompt, undefined); + // Declining cancels the action. + const again = new TestingPanel({ async callServerTool() { return { content: [], structuredContent: { teams, error: "x" } }; } } as unknown as HostBridge, phoneApps, { heartbeatMs: 1e9 }); + t.after(() => again.dispose?.()); + again.setAvailable(true); + const declined = again.ensureIosTeam(); + await new Promise(resolve => setTimeout(resolve, 20)); + again.dismissSigningPrompt(); + assert.equal(await declined, false); + // No iPhone, no question. + assert.equal(await panel.ensureIosTeam(false), true); +}); diff --git a/website/src/content/docs/docs/testing.md b/website/src/content/docs/docs/testing.md index 40056ecc..63721f18 100644 --- a/website/src/content/docs/docs/testing.md +++ b/website/src/content/docs/docs/testing.md @@ -5,7 +5,7 @@ description: Record, edit, and run deterministic e2e tests from an iOS simulator Open **Testing Studio** to turn interactions with a running app into an editable e2e test. The mirror, generated TypeScript, and ordered step list share one workspace, so you can drive the app and review the test at the same time. -Testing Studio supports iOS simulators, connected and paired iPhones and iPads, and Android emulators. Physical Android devices and Maestro output are not supported. +Testing Studio supports iOS simulators, connected and paired iPhones and iPads, and Android emulators. Android phones over USB or wireless adb work too; Maestro output is not supported. ## No project, or your own project @@ -75,7 +75,7 @@ Open **E2E setup → Devices** to pick where a test runs. The list shows iOS sim - Tick one device that isn't the mirrored one and the test runs there (**Run on iPhone Air**). - **Run up to N at once** sets how many devices work at the same time, from 1 to 8. The rest wait in a queue. - A simulator or emulator that is off is booted first. -- A simulator or emulator without the app gets it copied from another booted device of the same platform that has it, even one you didn't tick. Install the physical iOS build on a phone or tablet before running; Testing Studio does not copy simulator apps to it. +- A simulator or emulator without the app gets it copied from another booted device of the same platform that has it, even one you didn't tick. On a phone or tablet, Testing Studio never copies a simulator app. If the app is missing it installs a matching `Debug-iphoneos` build it finds on this Mac (your project's `ios/build` or Xcode's DerivedData), and otherwise asks you to run `npx expo run:ios --device` first. - iOS and Android devices can run in the same batch. In a project, each device runs the config's target for its platform. Click a lane to see that device's steps on the preview. A failure on one device doesn't stop the others. Each `agent.*` step calls the model once per device. @@ -103,3 +103,21 @@ In a project, the recording stays unsaved for you to review, adjust and save. ## Data and telemetry Test source, step contents, element names, labels, typed values, project paths, bundle IDs, and device identifiers are excluded from Mobile Dev telemetry. Aggregate timings and counts cover recorder preparation, element-tree reads, editing, runs, and agent-recording handoff. See [Privacy](/docs/privacy) for collection and opt-out details. + +## Physical iPhone and iPad setup + +Recording and replay on hardware run an XCTest runner on the device, which has to be code signed. + +- **Developer Mode** must be on (Settings → Privacy & Security → Developer Mode), and the phone unlocked and trusted. Testing Studio checks Developer Mode before a run and says what to turn on. +- **Signing team.** Mobile Dev picks your Apple Developer Team ID in this order: `MOBILE_DEV_IOS_TEAM_ID` (or `AGENT_DEVICE_IOS_TEAM_ID`) in Mobile Dev's environment, then the project's `DEVELOPMENT_TEAM`, then the single team behind your Apple Development certificates. With none or several it stops and asks you to set `MOBILE_DEV_IOS_TEAM_ID`. Find the ID with `security find-identity -v -p codesigning`. +- The runner is built as `com.mobiledev.agentdevice.` so it is unique to your team. Set `AGENT_DEVICE_IOS_BUNDLE_ID` to use your own, and `AGENT_DEVICE_IOS_PROVISIONING_PROFILE` when Xcode cannot pick a profile. +- A failure carries the fix agent-device reports, such as the signing or Developer Mode hint, without local paths. +- One runner per phone: a device that is already running a test is refused until it finishes. + +## Physical Android setup + +- Turn on **USB debugging** (Developer options), connect the phone and accept the "Allow USB debugging" prompt for this Mac. An unauthorized or offline phone can't be selected. +- Keep the screen awake and unlocked (Developer options → Stay awake). Testing Studio refuses a sleeping or locked phone. +- Some vendors block installs over USB, which also blocks the helper apps the runner installs: turn on **Install via USB** (Xiaomi) or turn off **Auto Blocker** (Samsung), or accept the prompt on the phone. +- **Install the app first.** If it is missing, Testing Studio copies it from another connected Android device when its CPU ABIs include the phone's, preferring a phone. Otherwise build it for the phone (for an Expo app, `npx expo run:android --device`). +- A wireless phone gets a new address when it reconnects; if a run says the device is no longer connected, refresh Devices and pick it again.