From 15c4a6c072c541a5cf6c62a2e30976018f6de951 Mon Sep 17 00:00:00 2001 From: Hur Ali Date: Thu, 26 Nov 2026 16:28:32 +0500 Subject: [PATCH 1/7] fix(testing-studio): no project mode recording --- packages/core/test/testing-panel-ui.test.ts | 19 +++++++++++++++++++ packages/ui/src/components/testing-view.tsx | 11 +++++++---- packages/ui/src/test-recorder.ts | 5 +++-- packages/ui/test/test-recorder.test.ts | 5 +++++ 4 files changed, 34 insertions(+), 6 deletions(-) diff --git a/packages/core/test/testing-panel-ui.test.ts b/packages/core/test/testing-panel-ui.test.ts index 50ba4b44c..58bbb5a22 100644 --- a/packages/core/test/testing-panel-ui.test.ts +++ b/packages/core/test/testing-panel-ui.test.ts @@ -846,6 +846,25 @@ test("with no project open the picker says so and setup offers no project files" onTeardown(async () => { await act(async () => { root.unmount(); }); }); }); +test("Record waits for the foreground app target in No project mode", async t => { + const { module: { TestingView }, dom, onTeardown } = await renderEnvironment(t, { + exports: 'export { TestingView } from "./packages/ui/src/components/testing-view.tsx";', slug: "testing-no-project-record-target", + }); + const { act, createElement } = await import("react"); + const { createRoot } = await import("react-dom/client"); + const root = createRoot(dom.window.document.getElementById("root")!); + const deviceApps = { subscribe: () => () => undefined, getSnapshot: () => DEVICE_SNAPSHOT }; + const panel = panelStub({ projectPath: "/studio", studioPath: "/studio", runtimeMode: "bundled", targets: [], targetName: "", targetSource: "none" }); + await act(async () => { root.render(createElement(TestingView, { panel, deviceApps })); }); + assert.equal((dom.window.document.querySelector("[data-testing-record]") as HTMLButtonElement).disabled, true); + assert.match(dom.window.document.querySelector("[data-testing-blocker]")?.textContent ?? "", /Open the app you want to record/); + const ready = panelStub({ projectPath: "/studio", studioPath: "/studio", runtimeMode: "bundled", + targets: [{ name: "ios", platform: "ios", bundleId: "com.app" }], targetName: "ios", targetSource: "foreground" }); + await act(async () => { root.render(createElement(TestingView, { panel: ready, deviceApps })); }); + assert.equal((dom.window.document.querySelector("[data-testing-record]") as HTMLButtonElement).disabled, false); + onTeardown(async () => { await act(async () => { root.unmount(); }); }); +}); + test("a stored Testing Studio test shows its pinned app and offers to re-pin it to the app in front", async t => { const { module: { TestingView }, dom, onTeardown } = await renderEnvironment(t, { exports: 'export { TestingView } from "./packages/ui/src/components/testing-view.tsx";', slug: "testing-pinned-app", diff --git a/packages/ui/src/components/testing-view.tsx b/packages/ui/src/components/testing-view.tsx index 80bcb9556..6acef620b 100644 --- a/packages/ui/src/components/testing-view.tsx +++ b/packages/ui/src/components/testing-view.tsx @@ -278,7 +278,11 @@ export function TestingView({ panel, deviceApps }: { panel: TestingPanel; device const booted = device?.state === "Booted" || device?.state === "connected"; const target = state.targets.find(entry => entry.name === state.targetName) ?? state.targets[0]; const mismatch = panel.targetMismatch; - const recordable = isRecordableDevice(device) && !mismatch; + // Record needs a target as well as a mirror. In No project mode the foreground app can arrive + // after the device stream; without a target the recorder has no tree source and an empty fallback + // looks like an app with no accessible elements. + const recordable = Boolean(state.projectPath && !state.loadingProject && target?.bundleId + && booted && isRecordableDevice(device) && !mismatch); const deviceId = device?.udid ?? ""; const platform = device ? recordablePlatform(device) : "ios"; // Why the recorder cannot start yet, in the order the user has to fix them. @@ -326,7 +330,7 @@ export function TestingView({ panel, deviceApps }: { panel: TestingPanel; device - + ; } @@ -893,7 +897,7 @@ function StoredTestPreview({ panel, source, path, loading }: { panel: TestingPan * the mirror canvas by the simulator panel, which holds the device connection; this is the readout * and the controls. */ -function TestingRecorder({ panel, recordable, deviceId }: { panel: TestingPanel; recordable: boolean; deviceId: string; platform: DevicePlatform }) { +function TestingRecorder({ panel, deviceId }: { panel: TestingPanel; deviceId: string }) { const state = useSyncExternalStore(testRecorder.subscribe, testRecorder.getSnapshot); const panelState = useSyncExternalStore(panel.subscribe, panel.getSnapshot); const recording = state.recordingDeviceId === deviceId && deviceId !== ""; @@ -952,7 +956,6 @@ function TestingRecorder({ panel, recordable, deviceId }: { panel: TestingPanel; if (panelState.selectedTestPath) return ; return
- {!recordable && !recording && !panelState.agent?.active &&

Recording needs a booted iOS simulator or Android emulator in the mirror. If one is already running, choose it from Add device.

} {panelState.agent?.active &&

The mirror is the agent's while it records, so clicking it does nothing. Press Stop to take it back.

} diff --git a/packages/ui/src/test-recorder.ts b/packages/ui/src/test-recorder.ts index 52c7c7f4b..7736bdf4e 100644 --- a/packages/ui/src/test-recorder.ts +++ b/packages/ui/src/test-recorder.ts @@ -299,9 +299,10 @@ export class TestRecorder { this.invalidate(); } - /** What a panel's `readComponents` forwards to. Without a source there is nothing to record from. */ + /** What a panel's `readComponents` forwards to. Missing setup is not an empty app tree. */ readTree(deviceId: string, platform: DevicePlatform): Promise<{ tree: ScreenComponent[]; screen?: ScreenSize }> { - return this.treeSource ? this.treeSource.read(deviceId, platform) : Promise.resolve({ tree: [] }); + return this.treeSource ? this.treeSource.read(deviceId, platform) + : Promise.reject(new Error("Testing Studio has no app target to read. Wait for the foreground app to appear in Testing Studio, then record again.")); } releaseTree() { this.treeSource?.release(); } diff --git a/packages/ui/test/test-recorder.test.ts b/packages/ui/test/test-recorder.test.ts index 222d4f638..d236630eb 100644 --- a/packages/ui/test/test-recorder.test.ts +++ b/packages/ui/test/test-recorder.test.ts @@ -812,6 +812,11 @@ test("recording an Android emulator reads the tree with its serial and platform" recorder.stop(); }); +test("a missing app target is reported separately from an empty accessibility tree", async () => { + const recorder = new TestRecorder(); + await assert.rejects(recorder.readTree("sim", "ios"), /no app target to read/); +}); + test("only the mirror of the platform being recorded or picked draws the recorder's overlay", () => { assert.equal(recorderShowsOn("android", "android"), true); assert.equal(recorderShowsOn("android", "ios"), false, "a re-record on Android must not paint the iOS mirror"); From 783975265fe1a6c90bb476e0e4912dee809e69db Mon Sep 17 00:00:00 2001 From: Hur Ali Date: Thu, 26 Nov 2026 16:55:23 +0500 Subject: [PATCH 2/7] feat: add open in browser --- CONTRIBUTING.md | 4 +- .../test/display-mode-control.test.ts | 1 + apps/codex-plugin/ui/main.tsx | 2 +- docs/architecture.md | 4 +- docs/devices.md | 2 +- docs/mcp-tools.md | 1 + docs/telemetry.md | 8 ++- packages/core/src/browser-panel.ts | 45 ++++++++++++++--- packages/core/test/browser-panel.test.ts | 49 +++++++++++++++++++ packages/mcp-app/src/browser-panel.ts | 8 ++- .../src/components/open-in-browser-button.tsx | 38 ++++++++++++++ packages/mcp-app/src/components/workspace.tsx | 21 +++++++- packages/mcp-app/src/workspace-app.tsx | 3 +- packages/mcp-app/src/workspace-extension.ts | 5 ++ packages/shared/src/panel-target.ts | 6 +++ 15 files changed, 182 insertions(+), 15 deletions(-) create mode 100644 packages/mcp-app/src/components/open-in-browser-button.tsx diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7dc80f4a3..0953f56e3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -469,7 +469,9 @@ npm run cursor:config global file rather than a project's `.cursor/mcp.json`: the snippet uses absolute paths to this checkout and the Node executable running the generator. 2. Reload Cursor, check that `mobile-dev` is enabled in the MCP section of Cursor Settings, and - ask **“Open Mobile Dev”** in a new agent chat. + ask **“Open Mobile Dev”** in a new agent chat. Cursor's Agent window cannot grow the in-chat + iframe; **Open in browser** on the panel toolbar loads the same panel on a loopback page + the host can show in its own window. After UI or server edits, run `npm run build` and reload Cursor. Regenerate the config if the checkout or Node path changes. diff --git a/apps/codex-plugin/test/display-mode-control.test.ts b/apps/codex-plugin/test/display-mode-control.test.ts index ef4e52386..4df1e2cf8 100644 --- a/apps/codex-plugin/test/display-mode-control.test.ts +++ b/apps/codex-plugin/test/display-mode-control.test.ts @@ -54,4 +54,5 @@ for (const [host, entry, shown] of [ await setTimeout(20); const buttons = [...window.document.querySelectorAll(".workspace-toolbar button")].map(button => button.textContent); assert.equal(buttons.includes("Back to chat"), shown, buttons.join(", ")); + assert.equal(buttons.some(text => text?.includes("Open in browser")) === true, host === "shared MCP Apps panel", buttons.join(", ")); }); diff --git a/apps/codex-plugin/ui/main.tsx b/apps/codex-plugin/ui/main.tsx index 8cd22ae21..8d80043e0 100644 --- a/apps/codex-plugin/ui/main.tsx +++ b/apps/codex-plugin/ui/main.tsx @@ -1,4 +1,4 @@ import { startMcpApp } from "@mobile-dev/mcp-app/app.tsx"; import { codexWorkspace } from "./codex-workspace.tsx"; -startMcpApp({ workspace: { extension: codexWorkspace, displayModeControl: false } }); +startMcpApp({ workspace: { extension: codexWorkspace, displayModeControl: false, openInBrowserControl: false } }); diff --git a/docs/architecture.md b/docs/architecture.md index aad7b08a8..b4fab49a5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -39,7 +39,9 @@ A host adds to the shared pieces without changing them: a separate module, so esbuild splits it into chunks beside `server.mjs`, keeping every file under the Claude plugin directory's 5 MiB limit. - **Panel:** a host's page entry calls `startMcpApp` with its chrome. Codex adds the - update banner; Claude uses the shared entry, for its cards. + update banner and leaves out Open in browser (its host blocks localhost). The shared + Cursor entry keeps that control, which starts the loopback page and asks the host to + open the link; Claude uses the shared entry, for its cards. - **Views:** shared views depend only on `HostBridge`, the subset of `App` they use, plus optional host context attachments. `DeviceWorkspace` keeps the iOS and Android panels, their selection and layout identical in every host. diff --git a/docs/devices.md b/docs/devices.md index 5ca40499e..0b1d15175 100644 --- a/docs/devices.md +++ b/docs/devices.md @@ -16,7 +16,7 @@ Android tools look for the SDK in `ANDROID_HOME`, `ANDROID_SDK_ROOT`, and the de ## Device panel -Open a new chat after installing. Open Mobile Dev in the sidebar or call `mobile_open_workspace` for the fullscreen view. Call `mobile_open_simulator` for the panel beside a chat. Both opening tools accept optional `platform`, `kind`, and discovered `deviceId` arguments. For example, `{ platform: "android", kind: "emulator" }` opens Android and selects an emulator before connecting; `kind: "physical"` selects a connected phone. An unavailable requested target stays unselected, with a message and the device picker available. Opening never boots a device. Without targeting, iOS opens when both platforms have running devices; Android opens when it has the only running device. Later manual device selections replace the opening choice. +Open a new chat after installing. Open Mobile Dev in the sidebar or call `mobile_open_workspace` for the fullscreen view. Call `mobile_open_simulator` for the panel beside a chat. In Cursor, **Open in browser** on the panel toolbar opens the same view in a loopback page the host can show in its own window, which is the way to get a larger canvas in the Agent window. Both opening tools accept optional `platform`, `kind`, and discovered `deviceId` arguments. For example, `{ platform: "android", kind: "emulator" }` opens Android and selects an emulator before connecting; `kind: "physical"` selects a connected phone. An unavailable requested target stays unselected, with a message and the device picker available. Opening never boots a device. Without targeting, iOS opens when both platforms have running devices; Android opens when it has the only running device. Later manual device selections replace the opening choice. Choose **+ Add device** in a tab strip and select the screens to display. The menu groups devices into iOS and Android columns. Choosing a device closes the menu. Open **+ Add device** again to choose another. Selecting a stopped simulator or emulator starts it. Each screen has its own Home, App Switcher, Screenshot, and Select controls. Each new device opens in a split to the right of that group. Drag a tab to the left, right, top, or bottom edge of a view to split it. Drop it in the center to join that group or on the tab strip to reorder it. Drag a divider to resize the views. Drag the empty part of a tab strip to move the whole group. Each group streams its selected tab. Deselecting a device closes its screen and leaves the device running. The panel uses Apple’s device bezel and screen mask from the installed DeviceKit assets, with a simple frame as a fallback when assets are unavailable. Use the settings button at the bottom right for appearance, text size, location, and the device frame. iOS also offers contrast; Android offers rotation. The menu shows only settings supported by the bundled backend. Click the screen to type or drag. Closing the panel closes its stream. diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index f1fdab697..59640e6a6 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -6,6 +6,7 @@ | --- | --- | | `mobile_open_simulator` | Open the native panel, optionally targeting a platform, device kind, or discovered device ID | | `mobile_open_workspace` | Open fullscreen with the same optional device targeting | +| `mobile_open_browser_panel` | Start the loopback panel page and return its URL, app-only | | `mobile_open_app_intel` | Open App Intelligence, optionally focused on an exact screen ID from `mobile_app_intel` | | `mobile_list_simulators` | Start the bundled backend if needed and list devices | | `mobile_choose_devices` | Ask the user to choose task targets in the host's native form; listed only for hosts with one (Codex, Claude Code) | diff --git a/docs/telemetry.md b/docs/telemetry.md index 58ee4dfeb..a14c05954 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -34,7 +34,13 @@ Behavior never depends on this value; it only attributes measurements and errors and honors telemetry opt-out. `browser_panel.context_update` counts the page's model context updates by `outcome` (`stored`, `invalid` or `too_large`), and `browser_panel.context_bytes` records the size of stored updates in bytes; the - context's text and images are never sent. + context's text and images are never sent. Since 0.1.197, the in-chat **Open in + browser** control counts `ui.workspace.open_in_browser` when the host opens the + returned loopback URL. Failures of that round trip or of `openLink` are handled + as `workspace.open_in_browser`. The URL, token and query are never sent. The + loopback page still hides the control by advertising `dev.mobile/browserPanel`. + Unexpected page-start failures besides a host with no shared transport are + captured as `browser_panel.open`. - Codex measures its Testing Studio runtime download. Claude measures its combined device and Testing Studio runtime download. `panel_runtime.ready` records, in milliseconds, how long the runtime took to be ready on its first use in a server, by `outcome`: `cached` when a diff --git a/packages/core/src/browser-panel.ts b/packages/core/src/browser-panel.ts index 753c28381..ead0dac80 100644 --- a/packages/core/src/browser-panel.ts +++ b/packages/core/src/browser-panel.ts @@ -2,17 +2,19 @@ import { randomBytes, randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import type { AddressInfo } from "node:net"; -import { getUiCapability } from "@modelcontextprotocol/ext-apps/server"; +import { getUiCapability, registerAppTool } from "@modelcontextprotocol/ext-apps/server"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import type { ImageContent, TextContent } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; -import type { PanelTarget } from "@mobile-dev/shared/panel-target.ts"; +import { deviceIdSchema, panelTargetSchema, type PanelTarget } from "@mobile-dev/shared/panel-target.ts"; import { telemetryHost, type TelemetryHost } from "@mobile-dev/shared/telemetry.ts"; import type { ServerFeature } from "./server-feature.ts"; import type { SharedTransport } from "./shared-transport.ts"; import { captureServerError, recordBrowserPanelContext, recordBrowserPanelSessions } from "./telemetry.ts"; const PAGE = new URL("./browser-panel.html", import.meta.url); +const openingToolName = z.enum(["mobile_open_simulator", "mobile_open_workspace", "mobile_open_app_intel"]); +const NO_BROWSER = "This host cannot open Mobile Dev in a browser."; export const BROWSER_SESSION_IDLE_MS = 5 * 60_000; // Screenshots the user adds to chat travel as base64 images. export const BROWSER_CONTEXT_MAX_BYTES = 16 * 1024 * 1024; @@ -48,17 +50,48 @@ export type BrowserPanelOptions = { export function browserPanel({ template = PAGE, always = false }: BrowserPanelOptions = {}): ServerFeature { return (server, { connections, onPanelOpen }) => { let page: Promise | undefined; - onPanelOpen(async ({ tool, target }) => { - const capabilities = server.server.getClientCapabilities(); - if (connections === undefined || (always === false && getUiCapability(capabilities))) return; + function ensurePage() { + if (connections === undefined) throw new Error(NO_BROWSER); const clientInfo = server.server.getClientVersion(); const host = telemetryHost(clientInfo?.name); page ??= startPanelPage(connections, host, template); - const opened = await page; + return page; + } + onPanelOpen(async ({ tool, target }) => { + const capabilities = server.server.getClientCapabilities(); + if (connections === undefined || (always === false && getUiCapability(capabilities))) return; + const opened = await ensurePage(); const url = opened.url(tool, target); const instructions = openingInstructions(url, opened.connected()); return { url, instructions }; }); + registerAppTool(server, "mobile_open_browser_panel", { + title: "Open Mobile Dev in a browser", + description: "Start the loopback panel page and return its URL so the in-chat panel can open it in a window. App-only: the in-chat Open in browser control calls this; the model never does.", + inputSchema: { + tool: openingToolName, + platform: z.enum(["ios", "android"]).optional(), + kind: z.enum(["simulator", "emulator", "physical"]).optional(), + deviceId: deviceIdSchema.optional(), + workspaceTool: z.enum(["logs", "performance", "storage", "app-intel", "tracesift", "testing"]).optional(), + appIntelScreen: z.string().min(1).max(512).optional(), + }, + outputSchema: { url: z.string() }, + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + _meta: { ui: { visibility: ["app"] } }, + }, async (input) => { + try { + const { tool, ...rest } = input; + const target = panelTargetSchema.parse(rest); + const opened = await ensurePage(); + const url = opened.url(tool, target); + return { content: [{ type: "text", text: url }], structuredContent: { url } }; + } catch (error) { + const text = error instanceof Error ? error.message : NO_BROWSER; + if (text !== NO_BROWSER) captureServerError(error, "browser_panel.open"); + return { isError: true, content: [{ type: "text", text }] }; + } + }); // A browser has no model context of its own, so the agent asks the server for it. server.registerTool("mobile_read_panel_context", { title: "Read Mobile Dev panel context", diff --git a/packages/core/test/browser-panel.test.ts b/packages/core/test/browser-panel.test.ts index 0edc8cf7b..76c3f794c 100644 --- a/packages/core/test/browser-panel.test.ts +++ b/packages/core/test/browser-panel.test.ts @@ -160,6 +160,55 @@ test("opening the panel links the browser page only for hosts without MCP Apps", } }); +test("an in-chat panel can open the loopback page without the agent receiving a link", async t => { + const directory = await mkdtemp(join(tmpdir(), "browser-panel-")); + const page = join(directory, "browser-panel.html"); + await writeFile(page, ""); + t.after(() => rm(directory, { recursive: true, force: true })); + const fake = await fakeBaguette(); + t.after(() => fake.close()); + const [hostSide, serverSide] = InMemoryTransport.createLinkedPair(); + const shared = new SharedTransport(serverSide); + const plugin = await createTestPlugin("", { + panel: createPanel({ baguette: new Baguette(fake.url), simulatorInput: fakeSimulatorInput() }), + features: [browserPanel({ template: pathToFileURL(page) })], + connections: shared, + }); + const host = new Client({ name: "cursor", version: "1" }, { capabilities: { extensions: { [EXTENSION_ID]: { mimeTypes: [RESOURCE_MIME_TYPE] } } } }); + await plugin.server.connect(shared); + await host.connect(hostSide); + t.after(async () => { await host.close(); await plugin.close(); }); + const { tools } = await host.listTools(); + const openInBrowser = tools.find(tool => tool.name === "mobile_open_browser_panel"); + assert.deepEqual(openInBrowser?._meta?.ui, { visibility: ["app"] }); + const opened = await host.callTool({ name: "mobile_open_simulator", arguments: { platform: "ios" } }); + assert.equal((opened.structuredContent as { browserPanel?: unknown }).browserPanel, undefined); + const result = await host.callTool({ + name: "mobile_open_browser_panel", + arguments: { tool: "mobile_open_simulator", platform: "ios", workspaceTool: "testing" }, + }); + assert.equal(result.isError, undefined); + const url = (result.structuredContent as { url: string }).url; + const link = new URL(url); + assert.equal(link.hostname, "127.0.0.1"); + assert.equal(link.searchParams.get("tool"), "mobile_open_simulator"); + assert.equal(link.searchParams.get("platform"), "ios"); + assert.equal(link.searchParams.get("workspaceTool"), "testing"); + assert.equal((await fetch(link)).status, 200); +}); + +test("opening in a browser without a shared transport is refused", async t => { + const plugin = await createTestPlugin("", { panel: createPanel(), features: [browserPanel()] }); + const [hostSide, serverSide] = InMemoryTransport.createLinkedPair(); + const host = new Client({ name: "cursor", version: "1" }); + await plugin.server.connect(serverSide); + await host.connect(hostSide); + t.after(async () => { await host.close(); await plugin.close(); }); + const result = await host.callTool({ name: "mobile_open_browser_panel", arguments: { tool: "mobile_open_simulator" } }); + assert.equal(result.isError, true); + assert.match((result.content as Array<{ text: string }>)[0].text, /cannot open Mobile Dev in a browser/); +}); + test("a panel that never renders inline links the browser page for MCP Apps hosts too", async t => { const directory = await mkdtemp(join(tmpdir(), "browser-panel-")); const page = join(directory, "browser-panel.html"); diff --git a/packages/mcp-app/src/browser-panel.ts b/packages/mcp-app/src/browser-panel.ts index 73a55e8d7..52878bfc8 100644 --- a/packages/mcp-app/src/browser-panel.ts +++ b/packages/mcp-app/src/browser-panel.ts @@ -3,7 +3,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { PLUGIN_VERSION } from "@mobile-dev/shared/version.ts"; -import { PANEL_PAGE_META } from "@mobile-dev/shared/panel-target.ts"; +import { BROWSER_PANEL_CAPABILITY, PANEL_PAGE_META } from "@mobile-dev/shared/panel-target.ts"; const dark = matchMedia("(prefers-color-scheme: dark)"); const DISCONNECTED = "Mobile Dev disconnected from its chat session. Ask the agent to open Mobile Dev again."; @@ -102,7 +102,11 @@ async function open() { // Advertise only capabilities this browser can fulfill. Chat messages need a // host-owned bridge; model context goes to the server, where the agent reads it. const hostContext = context(); - const capabilities = { serverTools: {}, serverResources: {}, openLinks: {}, updateModelContext: { text: {}, image: {} } }; + const capabilities = { + serverTools: {}, serverResources: {}, openLinks: {}, + updateModelContext: { text: {}, image: {} }, + experimental: { [BROWSER_PANEL_CAPABILITY]: {} }, + }; bridge = new AppBridge(client, { name: host, version: PLUGIN_VERSION }, capabilities, { hostContext }); bridge.onupdatemodelcontext = async ({ content }) => { const sessionId = transport.sessionId; diff --git a/packages/mcp-app/src/components/open-in-browser-button.tsx b/packages/mcp-app/src/components/open-in-browser-button.tsx new file mode 100644 index 000000000..9cb6a94d7 --- /dev/null +++ b/packages/mcp-app/src/components/open-in-browser-button.tsx @@ -0,0 +1,38 @@ +import type { App } from "@modelcontextprotocol/ext-apps"; +import { BROWSER_PANEL_CAPABILITY } from "@mobile-dev/shared/panel-target.ts"; +import type { PanelTarget } from "@mobile-dev/shared/panel-target.ts"; +import { Button } from "@mobile-dev/ui/components/ui/button.tsx"; +import { captureUiError, countUiEvent } from "@mobile-dev/ui/telemetry.ts"; +import { ExternalLinkIcon } from "lucide-react"; +import { useCallback, useState, useSyncExternalStore } from "react"; + +export type BrowserPanelOpen = PanelTarget & { tool: "mobile_open_simulator" | "mobile_open_workspace" | "mobile_open_app_intel" }; + +export function OpenInBrowserButton({ app, target, onError }: { app: App; target: () => BrowserPanelOpen; onError?: (message: string) => void }) { + const subscribe = useCallback((onChange: () => void) => { + app.addEventListener("hostcontextchanged", onChange); + return () => app.removeEventListener("hostcontextchanged", onChange); + }, [app]); + const shown = useSyncExternalStore(subscribe, () => { + const capabilities = app.getHostCapabilities(); + if (!capabilities?.serverTools) return false; + return capabilities.experimental?.[BROWSER_PANEL_CAPABILITY] === undefined; + }); + const [busy, setBusy] = useState(false); + if (!shown) return null; + return ; +} diff --git a/packages/mcp-app/src/components/workspace.tsx b/packages/mcp-app/src/components/workspace.tsx index 87ecb1cba..2029807d7 100644 --- a/packages/mcp-app/src/components/workspace.tsx +++ b/packages/mcp-app/src/components/workspace.tsx @@ -11,6 +11,8 @@ import { TraceSiftView } from "@mobile-dev/ui/components/tracesift-view.tsx"; import { AppIntelligenceView } from "@mobile-dev/ui/components/app-intelligence-view.tsx"; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@mobile-dev/ui/components/ui/base-select.tsx"; import { Button } from "@mobile-dev/ui/components/ui/button.tsx"; +import type { App } from "@modelcontextprotocol/ext-apps"; +import { OpenInBrowserButton, type BrowserPanelOpen } from "./open-in-browser-button"; import { usePanelRef, useGroupRef, type Layout } from "react-resizable-panels"; import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@mobile-dev/ui/components/ui/resizable.tsx"; @@ -36,7 +38,7 @@ const tools = { type Tool = keyof typeof tools; const isTool = (value: string): value is Tool => value in tools; -export function Workspace({ panels, recordingController, banner, displayModeControl, contextControl, automaticTool, automaticToolRevision = 0, devices }: { panels: WorkspaceTools; recordingController: RecordingController; banner?: ReactNode; displayModeControl?: ReactNode; contextControl?: ReactNode; automaticTool?: ToolName; automaticToolRevision?: number; devices: DeviceWorkspace }) { +export function Workspace({ panels, recordingController, banner, displayModeControl, openInBrowserControl, app, contextControl, automaticTool, automaticToolRevision = 0, devices }: { panels: WorkspaceTools; recordingController: RecordingController; banner?: ReactNode; displayModeControl?: ReactNode; openInBrowserControl?: boolean; app?: App; contextControl?: ReactNode; automaticTool?: ToolName; automaticToolRevision?: number; devices: DeviceWorkspace }) { const { logs, performance, storage, tracesift } = panels; const appIntel = panels["app-intel"]; const appFlow = panels["app-flow"]; @@ -143,6 +145,7 @@ export function Workspace({ panels, recordingController, banner, displayModeCont const ToolIcon = tools[tool].icon; const toolbar =
)} {only && This test was recorded on {platformLabel(only)} and doesn't have an {platformLabel(only === "ios" ? "android" : "ios")} target. To add one, open the app on an {platformLabel(only === "ios" ? "android" : "ios")} device in the mirror and choose Add {platformLabel(only === "ios" ? "android" : "ios")} app.} - {state.matrixDevices.length === 0 &&

{state.matrixLoading ? "Looking for simulators and emulators…" : "No simulators or emulators found."}

} + {state.matrixDevices.length === 0 &&

{state.matrixLoading ? "Looking for devices…" : "No devices found."}

}
at once
- {count > state.matrixLimit ? `${count - state.matrixLimit} will queue until a slot frees. ` : ""}{state.runtimeMode === "project" ? "Devices that are off are booted, and a missing app is copied from another booted device that has it. Each device runs the config's target for its platform." : "Devices that are off are booted, and a missing app is copied from another booted device that has it."} Agent steps call the model once per device. + {count > state.matrixLimit ? `${count - state.matrixLimit} will queue until a slot frees. ` : ""}Simulators and emulators are booted when needed. A connected iPhone or iPad needs the app installed on the device before a run. Each device runs its platform's app; agent steps call the model once per device. ; } @@ -82,6 +83,7 @@ function LaneRow({ panel, lane, selected, mirrored, totalSteps }: { panel: Testi title="Show this device's steps and mirror it." onClick={() => panel.openLane(lane.runId)}> {lane.deviceName} + {lane.kind === "physical" && Device} {active && lane.state !== "queued" && }{laneLabel(lane, totalSteps)} {duration === undefined ? "" : formatRunDuration(duration)} diff --git a/packages/ui/src/components/testing-view.tsx b/packages/ui/src/components/testing-view.tsx index 6acef620b..5bac8e578 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 or emulator in the mirror. If one is already running, choose it from Add device." - : !isRecordableDevice(device) ? "Recording works on an iOS simulator or an Android emulator, not a physical device." + : !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." : mismatch; return
diff --git a/packages/ui/src/simulator-panel.ts b/packages/ui/src/simulator-panel.ts index 8f06f433b..44d14ca45 100644 --- a/packages/ui/src/simulator-panel.ts +++ b/packages/ui/src/simulator-panel.ts @@ -276,12 +276,13 @@ export function createSimulatorPanel( * the inspection path the annotation overlay uses, but the e2e runner's own element tree, so a * recorded selector resolves to the same element when the test runs. The Testing Studio panel installs * that source — it knows the project and the target — and this supplies the device and the - * screen. Only iOS simulators and Android emulators are wired up; a physical device has no tree here at all. + * screen. On physical iOS the runner tree is scaled into the mirror's pixel space. */ const recorderReader = { + get fillOnly() { return selected?.kind === "physical" && selected.platform === "ios"; }, readComponents: async () => { if (!selected) return []; - const { tree, screen } = await testRecorder.readTree(selected.udid, recordablePlatform(selected)); + const { tree, screen } = await testRecorder.readTree(selected.udid, recordablePlatform(selected), selected.kind === "physical" ? "physical" : undefined); // `screen` is the space the runner measured in; `points` is the space the mirror maps // pointer events into. They agree on an iOS simulator and do not on Android, where scrcpy // caps the stream's longest edge while the tree stays in device pixels. @@ -294,7 +295,7 @@ export function createSimulatorPanel( // the screen the test will be on. perform: (action: | { kind: "tap"; point: { x: number; y: number } } - | { kind: "type"; text: string } + | { kind: "type"; text: string; nodeId?: string } | { kind: "swipe"; from: { x: number; y: number }; to: { x: number; y: number } }) => { if (action.kind === "tap") send({ type: "tap", x: action.point.x, y: action.point.y, ...points }); // The stream carries a swipe of its own, so a recorded `swipe` is taken as the gesture it @@ -308,6 +309,10 @@ 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") { + 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))); + } else if (action.text) send({ type: "type", text: action.text }); }, }; diff --git a/packages/ui/src/test-recorder.ts b/packages/ui/src/test-recorder.ts index 7736bdf4e..cf73a887d 100644 --- a/packages/ui/src/test-recorder.ts +++ b/packages/ui/src/test-recorder.ts @@ -8,6 +8,8 @@ import { countUiEvent, recordUiTiming, setUiGauge } from "./telemetry.ts"; * connection, so it supplies this; the recorder never talks to the host itself. */ export type RecorderReader = { + /** Filling through agent-device focuses the field itself, without a preceding mirror tap. */ + fillOnly?: boolean; /** The runner's element tree as flat components, in the same coordinate space as `screen`. */ readComponents: () => Promise; /** The screen size the mirror maps pointer events into. */ @@ -21,7 +23,7 @@ export type RecorderReader = { */ perform?: (action: | { kind: "tap"; point: ScreenPoint } - | { kind: "type"; text: string } + | { kind: "type"; text: string; nodeId?: string } // Start and end in screen space, as every other point here is; the panel's own stream carries // a swipe, so the gesture a recorded step emits is one the mirror can also take. | { kind: "swipe"; from: ScreenPoint; to: ScreenPoint }) => void; @@ -53,7 +55,8 @@ export type RecorderTreeSource = { * The screen is the runner's, not the mirror's: on Android the two differ, and the panel that * owns the mirror converts between them. See `scaledComponents`. */ - read: (deviceId: string, platform: DevicePlatform) => Promise<{ tree: ScreenComponent[]; screen?: ScreenSize }>; + read: (deviceId: string, platform: DevicePlatform, kind?: "physical") => Promise<{ tree: ScreenComponent[]; screen?: ScreenSize }>; + fill?: (deviceId: string, nodeId: string, text: string) => Promise; release: () => void; }; @@ -277,6 +280,7 @@ export class TestRecorder { private menuToken = 0; /** The centre of the element the last step named, which is where its action lands. */ private lastTarget?: ScreenPoint; + private lastNodeId?: string; /** That element's rectangle, which is the box a scoped swipe is drawn inside. */ private lastBounds?: ScreenBounds; private snapshot: TestRecorderSnapshot = { @@ -300,11 +304,15 @@ export class TestRecorder { } /** What a panel's `readComponents` forwards to. Missing setup is not an empty app tree. */ - readTree(deviceId: string, platform: DevicePlatform): Promise<{ tree: ScreenComponent[]; screen?: ScreenSize }> { - return this.treeSource ? this.treeSource.read(deviceId, platform) + readTree(deviceId: string, platform: DevicePlatform, kind?: "physical"): Promise<{ tree: ScreenComponent[]; screen?: ScreenSize }> { + return this.treeSource ? this.treeSource.read(deviceId, platform, kind) : Promise.reject(new Error("Testing Studio has no app target to read. Wait for the foreground app to appear in Testing Studio, then record again.")); } + fillTree(deviceId: string, nodeId: string, text: string): Promise { + return this.treeSource?.fill?.(deviceId, nodeId, text) ?? Promise.reject(new Error("Testing Studio cannot enter text on this device.")); + } + releaseTree() { this.treeSource?.release(); } private update(fields: Partial) { @@ -765,6 +773,7 @@ export class TestRecorder { this.lastTarget = owner ? { x: owner.bounds.x + owner.bounds.width / 2, y: owner.bounds.y + owner.bounds.height / 2 } : point; + this.lastNodeId = owner?.nodeId; this.update({ steps: [...this.snapshot.steps, step] }); countUiEvent(kind === "tap" ? "ui.testing.step_tap" : stepIsAssertion(kind) ? "ui.testing.step_assert" : "ui.testing.step_action"); if (selector.kind === "point") countUiEvent("ui.testing.step_unresolved"); @@ -905,8 +914,8 @@ export class TestRecorder { this.reader?.perform?.({ kind: "swipe", ...swipePath(span ?? { x: 0, y: 0, ...(this.reader?.screen() ?? { width: 0, height: 0 }) }, swipeDirection(value)) }); } else if (effect === "type") { - this.reader?.perform?.({ kind: "tap", point: where }); - this.reader?.perform?.({ kind: "type", text: value ?? "" }); + if (!this.reader?.fillOnly) this.reader?.perform?.({ kind: "tap", point: where }); + this.reader?.perform?.({ kind: "type", text: value ?? "", ...(this.lastNodeId ? { nodeId: this.lastNodeId } : {}) }); } // Anything that touched the app leaves a screen the cached tree no longer describes. if (effect !== "none") this.invalidate(); diff --git a/packages/ui/src/testing-matrix.ts b/packages/ui/src/testing-matrix.ts index 0ae767b3a..c5e24c165 100644 --- a/packages/ui/src/testing-matrix.ts +++ b/packages/ui/src/testing-matrix.ts @@ -13,14 +13,14 @@ export const MAX_MATRIX_LIMIT = 8; export type LaneProgress = { stepIndex: number; phase: "start" | "end"; status?: string; error?: string }; export type LaneResult = { status: string; steps: { line: number; status: string; error?: string }[]; error?: string; output?: string; durationMs?: number }; export type MatrixLane = { - runId: string; deviceId: string; deviceName: string; platform: MatrixPlatform; state: LaneState; + runId: string; deviceId: string; deviceName: string; platform: MatrixPlatform; kind?: "simulator" | "emulator" | "physical"; state: LaneState; resolvedDeviceId?: string; progress: LaneProgress[]; result?: LaneResult; error?: string; startedAt?: number; finishedAt?: number; }; export type MatrixView = { matrixId: string; /** The test the lanes run, relative to the project. */ testPath?: string; lanes: MatrixLane[]; limit: number; startedAt: number; finishedAt?: number }; /** One device in the checklist. `installed` is unknown (undefined) for a device that is off. */ export type MatrixDeviceOption = { - deviceId: string; name: string; platform: MatrixPlatform; runtime: string; booted: boolean; installed?: boolean; + deviceId: string; name: string; platform: MatrixPlatform; kind?: "simulator" | "emulator" | "physical"; runtime: string; booted: boolean; installed?: boolean; connectionState?: string; }; const TERMINAL: ReadonlySet = new Set(["passed", "failed", "cancelled", "error"]); @@ -75,6 +75,7 @@ export function parseMatrix(value: unknown): MatrixView | null { const result = record(lane.result); lanes.push({ runId: str(lane.runId), deviceId: str(lane.deviceId), deviceName: str(lane.deviceName) || str(lane.deviceId), platform: lane.platform, + ...(lane.kind === "physical" || lane.kind === "simulator" || lane.kind === "emulator" ? { kind: lane.kind } : {}), state: str(lane.state) as LaneState, ...(str(lane.resolvedDeviceId) ? { resolvedDeviceId: str(lane.resolvedDeviceId) } : {}), progress: (Array.isArray(lane.progress) ? lane.progress : []).map(record).filter((entry): entry is Record => entry !== null @@ -100,19 +101,27 @@ export function parseMatrix(value: unknown): MatrixView | null { }; } -/** Reads the checklist's devices out of the two device-list tools' payloads. Physical iOS devices are not listed. */ +/** Reads the checklist's devices out of the simulator and Android device-list tools. */ export function parseMatrixDevices(platform: MatrixPlatform, value: unknown): MatrixDeviceOption[] { 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))) - // A physical iPhone cannot take a simulator build, and a physical Android is not booted by us. - .filter(device => platform === "android" || str(device.kind) !== "physical") + .filter(device => str(device.kind) !== "physical") .map(device => ({ - deviceId: str(device.udid), name: str(device.name) || str(device.udid), platform, runtime: str(device.runtime), + 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", })); } +export function parsePhysicalIosMatrixDevices(value: unknown): MatrixDeviceOption[] { + const devices = record(value)?.physicalDevices; + if (!Array.isArray(devices)) return []; + return devices.map(record).filter((device): device is Record => device !== null && Boolean(str(device.udid))) + .map(device => ({ deviceId: str(device.udid), name: str(device.name) || str(device.udid), platform: "ios", kind: "physical", runtime: str(device.runtime), + booted: str(device.state) === "connected" && str(device.pairingState) === "paired", + connectionState: str(device.state) !== "connected" ? "Disconnected" : str(device.pairingState) !== "paired" ? "Pair this device" : "Connected" })); +} + export type MatrixPreferences = { limit: number }; const STORAGE_PREFIX = "mobile-dev.testing.matrix:"; diff --git a/packages/ui/src/testing-panel.ts b/packages/ui/src/testing-panel.ts index 899d23de6..b2bf89365 100644 --- a/packages/ui/src/testing-panel.ts +++ b/packages/ui/src/testing-panel.ts @@ -1,6 +1,7 @@ import type { TestingRuntimeProgress } from "@mobile-dev/shared/testing-runtime.ts"; import type { HostBridge } from "./host-bridge.ts"; 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 { RecorderTreeSource } from "./test-recorder.ts"; @@ -11,7 +12,7 @@ import { testFileSlug } from "@mobile-dev/shared/test-recording.ts"; import { branchStoredStepLocator, storedTestCallLines, storedTestUntilSource } from "@mobile-dev/shared/stored-test-steps.ts"; import type { RecordedStep } from "@mobile-dev/shared/test-recording.ts"; import type { TestDraftSummary } from "@mobile-dev/shared/test-drafts.ts"; -import { DEFAULT_MATRIX_LIMIT, clampLimit, isTerminalLane, matrixFinished, parseMatrix, parseMatrixDevices, readMatrixPreferences, writeMatrixPreferences } from "./testing-matrix.ts"; +import { DEFAULT_MATRIX_LIMIT, clampLimit, isTerminalLane, matrixFinished, parseMatrix, parseMatrixDevices, parsePhysicalIosMatrixDevices, readMatrixPreferences, writeMatrixPreferences } from "./testing-matrix.ts"; import type { MatrixDeviceOption, MatrixLane, MatrixView } from "./testing-matrix.ts"; /** @@ -194,10 +195,11 @@ export function platformLabel(platform: "ios" | "android"): string { return plat * Launch app opens an app that is already installed; it never builds one, since a build is the * project's own (Expo, EAS, Gradle, Xcode) and takes minutes. A missing app says so, with the way to fix it. */ -export function launchErrorMessage(message: string, bundleId: string, platform: "ios" | "android"): string { +export function launchErrorMessage(message: string, bundleId: string, platform: "ios" | "android", kind?: "physical"): string { if (!/is not installed|Unable to find package|Unknown package/i.test(message)) return message; - const where = platform === "ios" ? "this simulator" : "this emulator"; - return `${bundleId} is not installed on ${where}. Build and install it (for an Expo app, \`npx expo run:${platform}\`), then launch again.`; + const where = kind === "physical" ? "this iPhone or iPad" : platform === "ios" ? "this simulator" : "this emulator"; + const command = kind === "physical" ? "npx expo run:ios --device" : `npx expo run:${platform}`; + return `${bundleId} is not installed on ${where}. Build and install it (for an Expo app, \`${command}\`), then launch again.`; } function projectName(projectPath: string): string { return projectPath.split("/").filter(Boolean).at(-1) ?? projectPath; } @@ -223,6 +225,11 @@ function parseTargets(data: Record): TestingTargetOption[] { */ export class TestingPanel { + private launchOnDevice(device: SimulatorDevice, bundleId: string) { + const physicalIos = device.kind === "physical" && device.platform === "ios"; + return this.call(physicalIos ? "mobile_testing_physical_launch" : "mobile_launch_app", + { deviceId: device.udid, bundleId, ...(physicalIos ? {} : { platform: recordablePlatform(device) }) }, 120_000); + } private readonly app: HostBridge; private readonly deviceApps: DeviceAppsStore; private readonly listeners = new Set<() => void>(); @@ -359,8 +366,8 @@ export class TestingPanel { private treeSource(projectPath: string, bundleId: string): RecorderTreeSource { return { - read: async (deviceId, platform) => { - const result = await this.call("mobile_testing_read_tree", { deviceId, platform, projectPath, bundleId }, 20000); + read: async (deviceId, platform, kind) => { + const result = await this.call("mobile_testing_read_tree", { deviceId, platform, ...(kind ? { kind } : {}), projectPath, bundleId }, 20000); const content = object(result.structuredContent); const tree = content?.tree; // The screen the runner measured against. Android's is device pixels and the mirror's is @@ -368,6 +375,9 @@ export class TestingPanel { const screen = screenSize(content?.screen); return { tree: Array.isArray(tree) ? tree as ScreenComponent[] : [], ...(screen ? { screen } : {}) }; }, + fill: async (deviceId, nodeId, value) => { + await this.call("mobile_testing_fill", { deviceId, projectPath, bundleId, nodeId, text: value }, 30_000); + }, // Fire and forget: giving the device back must never hold up stopping a recording, and a // release that fails leaves the session for the next `read` to take over. release: () => { void this.call("mobile_testing_release_device", {}, 10000).catch(() => undefined); }, @@ -739,15 +749,11 @@ export class TestingPanel { this.update({ launching: true, error: null }); const startedAt = performance.now(), telemetryContext = getUiTelemetryAttributes(); try { - await this.call("mobile_launch_app", { - platform: recordablePlatform(device), - deviceId: device.udid, - bundleId, - }, 120_000); + await this.launchOnDevice(device, bundleId); this.update({ appLaunched: true }); countUiEvent("ui.testing.launch"); } catch (error) { - this.update({ error: launchErrorMessage(error instanceof Error ? error.message : String(error), bundleId, recordablePlatform(device)) }); + this.update({ error: launchErrorMessage(error instanceof Error ? error.message : String(error), bundleId, recordablePlatform(device), device.kind === "physical" ? "physical" : undefined) }); captureUiError(error, "testing.launch", telemetryContext); } finally { if (getUiTelemetryAttributes() === telemetryContext) recordUiTiming("ui.testing.launch", performance.now() - startedAt); @@ -957,7 +963,7 @@ export class TestingPanel { if (!mirrored || mirrored !== platform || !app || !device) return; // The element tree is read from the app in front, so it has to be this platform's app. if (this.deviceApps.getSnapshot().foregroundApp?.bundleId !== app.bundleId) { - try { await this.call("mobile_launch_app", { platform: app.platform, deviceId: device.udid, bundleId: app.bundleId }, 120_000); } + try { await this.launchOnDevice(device, app.bundleId); } catch (error) { this.update({ error: `Could not open ${app.bundleId}: ${error instanceof Error ? error.message : String(error)}` }); return; } } const relativePath = this.snapshot.selectedTestPath; @@ -1306,16 +1312,15 @@ export class TestingPanel { const projectPath = this.snapshot.projectPath; const bundleId = this.target?.bundleId ?? ""; const device = this.deviceApps.getSnapshot().device; - // Only a booted iOS simulator or Android emulator can be recorded against; anything else is - // reported as no device. const recordable = device !== undefined && isRecordableDevice(device); const deviceId = recordable ? device.udid : ""; const platform = recordable ? recordablePlatform(device) : undefined; - const key = `${projectPath}\u0000${platform ?? ""}\u0000${deviceId}\u0000${bundleId}`; + const kind = recordable && device.kind === "physical" ? "physical" : undefined; + const key = `${projectPath}\u0000${platform ?? ""}\u0000${kind ?? ""}\u0000${deviceId}\u0000${bundleId}`; if (key === this.reportedContext && !force) return; this.reportedContext = key; try { - await this.call("mobile_testing_set_context", { projectPath, deviceId, ...(platform ? { platform } : {}), bundleId }, 10_000); + await this.call("mobile_testing_set_context", { projectPath, deviceId, ...(platform ? { platform } : {}), ...(kind ? { kind } : {}), bundleId }, 10_000); } catch { // The next change reports again; a selection the server missed only means an agent is told // to ask the user, which is the refusal it would have given anyway. @@ -1661,7 +1666,7 @@ export class TestingPanel { if (pinned && this.deviceApps.getSnapshot().foregroundApp?.bundleId !== pinned.bundleId) { try { const device = this.deviceApps.getSnapshot().device; - if (device) await this.call("mobile_launch_app", { platform: pinned.platform, deviceId: device.udid, bundleId: pinned.bundleId }, 120_000); + if (device) await this.launchOnDevice(device, pinned.bundleId); } catch (error) { this.update({ running: false, error: `Could not open ${pinned.bundleId}: ${error instanceof Error ? error.message : String(error)}` }); return; @@ -1787,7 +1792,12 @@ export class TestingPanel { if (!this.matrixEnabled) return []; const only = this.matrixPlatform; const known = new Map(this.snapshot.matrixDevices.filter(device => !only || device.platform === only).map(device => [device.deviceId, device])); - return this.snapshot.matrixSelected.flatMap(id => known.get(id) ?? []); + const selected = this.snapshot.matrixSelected.flatMap(id => known.get(id) ?? []); + if (selected.length || this.snapshot.matrixSelected.length || only === "android") return selected; + const mirror = this.deviceApps.getSnapshot().device; + if (mirror?.kind !== "physical" || mirror.platform !== "ios") return selected; + return [known.get(mirror.udid) ?? { deviceId: mirror.udid, name: mirror.name, platform: "ios", kind: "physical", runtime: mirror.runtime, + booted: mirror.state === "connected" && mirror.pairingState === "paired" }]; } /** @@ -1810,6 +1820,7 @@ export class TestingPanel { get runsOnMatrix(): boolean { const selection = this.matrixSelection; if (selection.length !== 1) return selection.length > 1; + if (selection[0]!.kind === "physical") return true; return selection[0]!.deviceId !== this.deviceApps.getSnapshot().device?.udid; } @@ -1861,23 +1872,31 @@ export class TestingPanel { writeMatrixPreferences(this.snapshot.projectPath, { limit: next }); } - /** Lists the simulators and emulators, and for each booted one whether the app is on it. */ + /** Lists simulators, emulators and connected iOS hardware, then checks the selected app. */ async loadMatrixDevices() { if (!this.snapshot.available || this.snapshot.matrixLoading) return; this.update({ matrixLoading: true }); try { const read = (name: string) => this.call(name, {}, 20_000).then(result => result.structuredContent, () => undefined); - const [simulators, emulators] = await Promise.all([read("mobile_list_simulators"), read("mobile_list_android_devices")]); - const devices = [...parseMatrixDevices("ios", simulators), ...parseMatrixDevices("android", emulators)]; + const [simulators, emulators, physicalIos] = await Promise.all([read("mobile_list_simulators"), read("mobile_list_android_devices"), + this.call("mobile_list_ios_devices", {}, 20_000).then(result => result.structuredContent, error => { + this.update({ error: `Could not discover connected iOS devices: ${error instanceof Error ? error.message : String(error)}` }); + return undefined; + })]); + const devices = [...parseMatrixDevices("ios", simulators), ...parsePhysicalIosMatrixDevices(physicalIos), ...parseMatrixDevices("android", emulators)]; const apps = this.matrixApps(); const checked = await Promise.all(devices.map(async device => { const appId = apps[device.platform]; if (!device.booted || !appId) return device; try { - const result = await this.call("mobile_list_apps", { platform: device.platform, deviceId: device.deviceId }, 20_000); + const result = await this.call(device.kind === "physical" ? "mobile_testing_physical_app" : "mobile_list_apps", { platform: device.platform, deviceId: device.deviceId, bundleId: appId }, 20_000); + if (device.kind === "physical") return { ...device, installed: object(result.structuredContent)?.installed === true }; const list = object(result.structuredContent)?.apps; return { ...device, installed: Array.isArray(list) && list.some(entry => object(entry)?.bundleId === appId) }; - } catch { return device; } + } catch (error) { + if (device.kind === "physical") this.update({ error: `Could not check the app on ${device.name}: ${error instanceof Error ? error.message : String(error)}` }); + return device; + } })); if (!this.disposed) this.update({ matrixDevices: checked }); } finally { @@ -1960,7 +1979,7 @@ export class TestingPanel { await this.stageWrite; const response = await this.call("mobile_testing_run_matrix", { projectPath: this.snapshot.projectPath, relativePath: input.relativePath, untilSource: input.source, - devices: selection.map(device => ({ deviceId: device.deviceId, platform: device.platform, name: device.name })), + devices: selection.map(device => ({ deviceId: device.deviceId, platform: device.platform, kind: device.kind ?? (device.platform === "ios" ? "simulator" : "emulator"), name: device.name })), apps, limit: this.snapshot.matrixLimit, ...(this.snapshot.runtimeMode === "project" ? { targets: this.matrixProjectTargets() } : {}), ...(this.snapshot.modelPreference ? { model: this.snapshot.modelPreference } : {}), diff --git a/packages/ui/test/test-recorder.test.ts b/packages/ui/test/test-recorder.test.ts index d236630eb..c1593ceb8 100644 --- a/packages/ui/test/test-recorder.test.ts +++ b/packages/ui/test/test-recorder.test.ts @@ -47,6 +47,16 @@ test("a tap row records the step and takes it on the device", async () => { assert.deepEqual(done, [{ kind: "tap", point: { x: 50, y: 820 } }]); }); +test("physical iOS text entry uses the runner field ref without a mirror tap", async () => { + const recorder = new TestRecorder(); + const done: unknown[] = []; + const field: ScreenComponent = { ...tab("Search", 300), role: "textbox", value: "Paris" }; + recorder.attach(UDID, "ios", { ...reader([field], { count: 0 }), fillOnly: true, perform: action => { done.push(action); } }); + recorder.start(UDID, "ios"); + await pick(recorder, { x: 50, y: 320 }, "fill", "Berlin"); + assert.deepEqual(done, [{ kind: "type", text: "Berlin", nodeId: "Search" }]); +}); + test("picking an element offers its locator to insert, hands it back on Insert, and records nothing", async () => { const reads = { count: 0 }; const recorder = new TestRecorder(); diff --git a/packages/ui/test/testing-matrix.test.ts b/packages/ui/test/testing-matrix.test.ts index 680b682c0..93f95efad 100644 --- a/packages/ui/test/testing-matrix.test.ts +++ b/packages/ui/test/testing-matrix.test.ts @@ -4,7 +4,7 @@ import type { HostBridge } from "../src/host-bridge.ts"; import type { DeviceAppsStore } from "../src/device-apps.ts"; import { TestingPanel } from "../src/testing-panel.ts"; import { testRecorder } from "../src/test-recorder.ts"; -import { clampLimit, laneLabel, matrixFinished, matrixSummary, parseMatrix, parseMatrixDevices } from "../src/testing-matrix.ts"; +import { clampLimit, laneLabel, matrixFinished, matrixSummary, parseMatrix, parseMatrixDevices, parsePhysicalIosMatrixDevices } from "../src/testing-matrix.ts"; import type { MatrixLane, MatrixView } from "../src/testing-matrix.ts"; const PROJECT = "/Users/someone/app"; @@ -51,6 +51,17 @@ 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("physical iOS checklist distinguishes connected, unpaired and disconnected devices", () => { + const devices = parsePhysicalIosMatrixDevices({ physicalDevices: [ + { udid: "P", name: "Phone", state: "connected", pairingState: "paired", runtime: "iOS 27" }, + { udid: "U", name: "Unpaired", state: "connected", pairingState: "unpaired" }, + { udid: "D", name: "Disconnected", state: "disconnected", pairingState: "paired" }, + ] }); + assert.deepEqual(devices.map(device => [device.kind, device.booted, device.connectionState]), [ + ["physical", true, "Connected"], ["physical", false, "Pair this device"], ["physical", false, "Disconnected"], + ]); +}); + /** A host that plays a matrix: the first poll shows two lanes running and a third queued, the next ends them. */ function matrixHost(calls: { name: string; arguments: Record }[]) { let polls = 0; @@ -117,6 +128,21 @@ test("one selected device runs as a lane unless it is the mirrored device, and a panel.dispose(); }); +test("a mirrored physical iPhone is pinned to a physical matrix lane", async () => { + const calls: { name: string; arguments: Record }[] = []; + const mirrored = { subscribe: () => () => undefined, getSnapshot: () => ({ device: { udid: "phone", name: "Phone", platform: "ios", kind: "physical", state: "connected", pairingState: "paired", runtime: "iOS 27" } }) } as unknown as DeviceAppsStore; + const panel = new TestingPanel(matrixHost(calls), mirrored); + const set = (fields: Record) => (panel as unknown as { update(fields: Record): void }).update(fields); + panel.setAvailable(true); + set({ projectPath: PROJECT, runtimeMode: "bundled", targets: [{ name: "ios", platform: "ios", bundleId: "com.example.app" }], selectedTestPath: "tests/a.e2e.ts", selectedTestSource: 'test("x", async () => {});\n', tests: [{ relativePath: "tests/a.e2e.ts", name: "a", updatedAt: "", sizeBytes: 1, target: { platform: "ios", bundleId: "com.example.app" } }] }); + assert.equal(panel.runsOnMatrix, true); + assert.equal(panel.matrixRunCount, 1); + await panel.runStoredTest(); + const start = calls.find(call => call.name === "mobile_testing_run_matrix"); + assert.deepEqual(start?.arguments.devices, [{ deviceId: "phone", platform: "ios", kind: "physical", name: "Phone" }]); + panel.dispose(); +}); + test("the concurrency limit is saved per project but device choices are not", () => { const store = new Map(); (globalThis as { localStorage?: unknown }).localStorage = { getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => { store.set(key, value); } }; diff --git a/website/src/content/docs/docs/testing.md b/website/src/content/docs/docs/testing.md index cfa84ad57..40056ecc2 100644 --- a/website/src/content/docs/docs/testing.md +++ b/website/src/content/docs/docs/testing.md @@ -1,11 +1,11 @@ --- title: Testing Studio -description: Record, edit, and run deterministic e2e tests from an iOS simulator or Android emulator beside your conversation, on one device or several at once. +description: Record, edit, and run deterministic e2e tests from an iOS simulator, connected iPhone or iPad, or Android emulator beside your conversation. --- 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 and Android emulators. Physical devices and Maestro output are not supported. +Testing Studio supports iOS simulators, connected and paired iPhones and iPads, and Android emulators. Physical Android devices and Maestro output are not supported. ## No project, or your own project @@ -26,12 +26,12 @@ The **E2E setup** popover lists the project, mobile apps, devices and agent mode ## Prepare a device -1. Boot an iOS simulator or Android emulator and select it in Mobile Dev. +1. Boot an iOS simulator or Android emulator, or connect and pair an iPhone or iPad, then select it in Mobile Dev. 2. Open **Testing Studio**. Choose a project folder from the picker, or stay on **No project**. 3. In a project, choose a target whose platform matches the mirrored device. 4. Select **Launch app**. -**Launch app** opens an app that is already installed; it doesn't build one. If the app is missing, Testing Studio says so and names the build to run, for example `npx expo run:android` for an Expo app. +**Launch app** opens an app that is already installed; it doesn't build one. If the app is missing, build and install it for the selected device. For an Expo app, use `npx expo run:android` for an emulator or `npx expo run:ios --device` for a connected iPhone or iPad. A simulator build cannot be copied to physical hardware. ## Record a test @@ -69,13 +69,13 @@ Saved tests are listed under **In the project** or **In Testing Studio**. Open o ## Run on several devices -Open **E2E setup → Devices** to pick where a test runs. The list shows every iOS simulator and Android emulator, whether it is booted, and whether it has the app. +Open **E2E setup → Devices** to pick where a test runs. The list shows iOS simulators, connected or remembered iPhones and iPads, and Android emulators. Physical iOS rows show connection and app installation status; disconnected or unpaired hardware cannot be selected. - Tick two or more devices and **Run test** becomes **Run on N devices**. Each device runs the same test in its own lane, with its own steps, verdict and **Cancel**. - 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 device that is off is booted first. -- A device without the app gets it copied from another booted device of the same platform that has it, even one you didn't tick. +- 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. - 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. From 5f17330907b329d8b56703845aea1d9d07697645 Mon Sep 17 00:00:00 2001 From: Hur Ali Date: Fri, 27 Nov 2026 14:11:09 +0500 Subject: [PATCH 4/7] fix(cursor): bugs for tools not shown on first render and maximize button if available (#153) --- CONTRIBUTING.md | 6 +-- .../test/display-mode-control.test.ts | 1 - apps/codex-plugin/ui/main.tsx | 2 +- docs/architecture.md | 4 +- docs/devices.md | 2 +- docs/mcp-tools.md | 1 - docs/telemetry.md | 8 +-- packages/core/src/browser-panel.ts | 45 +++-------------- packages/core/test/browser-panel.test.ts | 49 ------------------- packages/mcp-app/src/browser-panel.ts | 8 +-- .../src/components/open-in-browser-button.tsx | 38 -------------- packages/mcp-app/src/components/workspace.tsx | 23 +-------- packages/mcp-app/src/workspace-app.tsx | 3 +- packages/mcp-app/src/workspace-extension.ts | 5 -- packages/shared/src/panel-target.ts | 6 --- 15 files changed, 18 insertions(+), 183 deletions(-) delete mode 100644 packages/mcp-app/src/components/open-in-browser-button.tsx diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0953f56e3..21da20476 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -469,9 +469,9 @@ npm run cursor:config global file rather than a project's `.cursor/mcp.json`: the snippet uses absolute paths to this checkout and the Node executable running the generator. 2. Reload Cursor, check that `mobile-dev` is enabled in the MCP section of Cursor Settings, and - ask **“Open Mobile Dev”** in a new agent chat. Cursor's Agent window cannot grow the in-chat - iframe; **Open in browser** on the panel toolbar loads the same panel on a loopback page - the host can show in its own window. + ask **“Open Mobile Dev”** in a new agent chat. The panel shows **Expand** only when the host advertises `fullscreen` in + `availableDisplayModes`. Cursor documents no MCP Apps display modes, and its Agent window + has not advertised one, so the panel keeps the iframe size the host gives it there. After UI or server edits, run `npm run build` and reload Cursor. Regenerate the config if the checkout or Node path changes. diff --git a/apps/codex-plugin/test/display-mode-control.test.ts b/apps/codex-plugin/test/display-mode-control.test.ts index 4df1e2cf8..ef4e52386 100644 --- a/apps/codex-plugin/test/display-mode-control.test.ts +++ b/apps/codex-plugin/test/display-mode-control.test.ts @@ -54,5 +54,4 @@ for (const [host, entry, shown] of [ await setTimeout(20); const buttons = [...window.document.querySelectorAll(".workspace-toolbar button")].map(button => button.textContent); assert.equal(buttons.includes("Back to chat"), shown, buttons.join(", ")); - assert.equal(buttons.some(text => text?.includes("Open in browser")) === true, host === "shared MCP Apps panel", buttons.join(", ")); }); diff --git a/apps/codex-plugin/ui/main.tsx b/apps/codex-plugin/ui/main.tsx index 8d80043e0..8cd22ae21 100644 --- a/apps/codex-plugin/ui/main.tsx +++ b/apps/codex-plugin/ui/main.tsx @@ -1,4 +1,4 @@ import { startMcpApp } from "@mobile-dev/mcp-app/app.tsx"; import { codexWorkspace } from "./codex-workspace.tsx"; -startMcpApp({ workspace: { extension: codexWorkspace, displayModeControl: false, openInBrowserControl: false } }); +startMcpApp({ workspace: { extension: codexWorkspace, displayModeControl: false } }); diff --git a/docs/architecture.md b/docs/architecture.md index b4fab49a5..aad7b08a8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -39,9 +39,7 @@ A host adds to the shared pieces without changing them: a separate module, so esbuild splits it into chunks beside `server.mjs`, keeping every file under the Claude plugin directory's 5 MiB limit. - **Panel:** a host's page entry calls `startMcpApp` with its chrome. Codex adds the - update banner and leaves out Open in browser (its host blocks localhost). The shared - Cursor entry keeps that control, which starts the loopback page and asks the host to - open the link; Claude uses the shared entry, for its cards. + update banner; Claude uses the shared entry, for its cards. - **Views:** shared views depend only on `HostBridge`, the subset of `App` they use, plus optional host context attachments. `DeviceWorkspace` keeps the iOS and Android panels, their selection and layout identical in every host. diff --git a/docs/devices.md b/docs/devices.md index 0b1d15175..5ca40499e 100644 --- a/docs/devices.md +++ b/docs/devices.md @@ -16,7 +16,7 @@ Android tools look for the SDK in `ANDROID_HOME`, `ANDROID_SDK_ROOT`, and the de ## Device panel -Open a new chat after installing. Open Mobile Dev in the sidebar or call `mobile_open_workspace` for the fullscreen view. Call `mobile_open_simulator` for the panel beside a chat. In Cursor, **Open in browser** on the panel toolbar opens the same view in a loopback page the host can show in its own window, which is the way to get a larger canvas in the Agent window. Both opening tools accept optional `platform`, `kind`, and discovered `deviceId` arguments. For example, `{ platform: "android", kind: "emulator" }` opens Android and selects an emulator before connecting; `kind: "physical"` selects a connected phone. An unavailable requested target stays unselected, with a message and the device picker available. Opening never boots a device. Without targeting, iOS opens when both platforms have running devices; Android opens when it has the only running device. Later manual device selections replace the opening choice. +Open a new chat after installing. Open Mobile Dev in the sidebar or call `mobile_open_workspace` for the fullscreen view. Call `mobile_open_simulator` for the panel beside a chat. Both opening tools accept optional `platform`, `kind`, and discovered `deviceId` arguments. For example, `{ platform: "android", kind: "emulator" }` opens Android and selects an emulator before connecting; `kind: "physical"` selects a connected phone. An unavailable requested target stays unselected, with a message and the device picker available. Opening never boots a device. Without targeting, iOS opens when both platforms have running devices; Android opens when it has the only running device. Later manual device selections replace the opening choice. Choose **+ Add device** in a tab strip and select the screens to display. The menu groups devices into iOS and Android columns. Choosing a device closes the menu. Open **+ Add device** again to choose another. Selecting a stopped simulator or emulator starts it. Each screen has its own Home, App Switcher, Screenshot, and Select controls. Each new device opens in a split to the right of that group. Drag a tab to the left, right, top, or bottom edge of a view to split it. Drop it in the center to join that group or on the tab strip to reorder it. Drag a divider to resize the views. Drag the empty part of a tab strip to move the whole group. Each group streams its selected tab. Deselecting a device closes its screen and leaves the device running. The panel uses Apple’s device bezel and screen mask from the installed DeviceKit assets, with a simple frame as a fallback when assets are unavailable. Use the settings button at the bottom right for appearance, text size, location, and the device frame. iOS also offers contrast; Android offers rotation. The menu shows only settings supported by the bundled backend. Click the screen to type or drag. Closing the panel closes its stream. diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index 59640e6a6..f1fdab697 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -6,7 +6,6 @@ | --- | --- | | `mobile_open_simulator` | Open the native panel, optionally targeting a platform, device kind, or discovered device ID | | `mobile_open_workspace` | Open fullscreen with the same optional device targeting | -| `mobile_open_browser_panel` | Start the loopback panel page and return its URL, app-only | | `mobile_open_app_intel` | Open App Intelligence, optionally focused on an exact screen ID from `mobile_app_intel` | | `mobile_list_simulators` | Start the bundled backend if needed and list devices | | `mobile_choose_devices` | Ask the user to choose task targets in the host's native form; listed only for hosts with one (Codex, Claude Code) | diff --git a/docs/telemetry.md b/docs/telemetry.md index a14c05954..58ee4dfeb 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -34,13 +34,7 @@ Behavior never depends on this value; it only attributes measurements and errors and honors telemetry opt-out. `browser_panel.context_update` counts the page's model context updates by `outcome` (`stored`, `invalid` or `too_large`), and `browser_panel.context_bytes` records the size of stored updates in bytes; the - context's text and images are never sent. Since 0.1.197, the in-chat **Open in - browser** control counts `ui.workspace.open_in_browser` when the host opens the - returned loopback URL. Failures of that round trip or of `openLink` are handled - as `workspace.open_in_browser`. The URL, token and query are never sent. The - loopback page still hides the control by advertising `dev.mobile/browserPanel`. - Unexpected page-start failures besides a host with no shared transport are - captured as `browser_panel.open`. + context's text and images are never sent. - Codex measures its Testing Studio runtime download. Claude measures its combined device and Testing Studio runtime download. `panel_runtime.ready` records, in milliseconds, how long the runtime took to be ready on its first use in a server, by `outcome`: `cached` when a diff --git a/packages/core/src/browser-panel.ts b/packages/core/src/browser-panel.ts index ead0dac80..753c28381 100644 --- a/packages/core/src/browser-panel.ts +++ b/packages/core/src/browser-panel.ts @@ -2,19 +2,17 @@ import { randomBytes, randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import type { AddressInfo } from "node:net"; -import { getUiCapability, registerAppTool } from "@modelcontextprotocol/ext-apps/server"; +import { getUiCapability } from "@modelcontextprotocol/ext-apps/server"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import type { ImageContent, TextContent } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; -import { deviceIdSchema, panelTargetSchema, type PanelTarget } from "@mobile-dev/shared/panel-target.ts"; +import type { PanelTarget } from "@mobile-dev/shared/panel-target.ts"; import { telemetryHost, type TelemetryHost } from "@mobile-dev/shared/telemetry.ts"; import type { ServerFeature } from "./server-feature.ts"; import type { SharedTransport } from "./shared-transport.ts"; import { captureServerError, recordBrowserPanelContext, recordBrowserPanelSessions } from "./telemetry.ts"; const PAGE = new URL("./browser-panel.html", import.meta.url); -const openingToolName = z.enum(["mobile_open_simulator", "mobile_open_workspace", "mobile_open_app_intel"]); -const NO_BROWSER = "This host cannot open Mobile Dev in a browser."; export const BROWSER_SESSION_IDLE_MS = 5 * 60_000; // Screenshots the user adds to chat travel as base64 images. export const BROWSER_CONTEXT_MAX_BYTES = 16 * 1024 * 1024; @@ -50,48 +48,17 @@ export type BrowserPanelOptions = { export function browserPanel({ template = PAGE, always = false }: BrowserPanelOptions = {}): ServerFeature { return (server, { connections, onPanelOpen }) => { let page: Promise | undefined; - function ensurePage() { - if (connections === undefined) throw new Error(NO_BROWSER); - const clientInfo = server.server.getClientVersion(); - const host = telemetryHost(clientInfo?.name); - page ??= startPanelPage(connections, host, template); - return page; - } onPanelOpen(async ({ tool, target }) => { const capabilities = server.server.getClientCapabilities(); if (connections === undefined || (always === false && getUiCapability(capabilities))) return; - const opened = await ensurePage(); + const clientInfo = server.server.getClientVersion(); + const host = telemetryHost(clientInfo?.name); + page ??= startPanelPage(connections, host, template); + const opened = await page; const url = opened.url(tool, target); const instructions = openingInstructions(url, opened.connected()); return { url, instructions }; }); - registerAppTool(server, "mobile_open_browser_panel", { - title: "Open Mobile Dev in a browser", - description: "Start the loopback panel page and return its URL so the in-chat panel can open it in a window. App-only: the in-chat Open in browser control calls this; the model never does.", - inputSchema: { - tool: openingToolName, - platform: z.enum(["ios", "android"]).optional(), - kind: z.enum(["simulator", "emulator", "physical"]).optional(), - deviceId: deviceIdSchema.optional(), - workspaceTool: z.enum(["logs", "performance", "storage", "app-intel", "tracesift", "testing"]).optional(), - appIntelScreen: z.string().min(1).max(512).optional(), - }, - outputSchema: { url: z.string() }, - annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, - _meta: { ui: { visibility: ["app"] } }, - }, async (input) => { - try { - const { tool, ...rest } = input; - const target = panelTargetSchema.parse(rest); - const opened = await ensurePage(); - const url = opened.url(tool, target); - return { content: [{ type: "text", text: url }], structuredContent: { url } }; - } catch (error) { - const text = error instanceof Error ? error.message : NO_BROWSER; - if (text !== NO_BROWSER) captureServerError(error, "browser_panel.open"); - return { isError: true, content: [{ type: "text", text }] }; - } - }); // A browser has no model context of its own, so the agent asks the server for it. server.registerTool("mobile_read_panel_context", { title: "Read Mobile Dev panel context", diff --git a/packages/core/test/browser-panel.test.ts b/packages/core/test/browser-panel.test.ts index 76c3f794c..0edc8cf7b 100644 --- a/packages/core/test/browser-panel.test.ts +++ b/packages/core/test/browser-panel.test.ts @@ -160,55 +160,6 @@ test("opening the panel links the browser page only for hosts without MCP Apps", } }); -test("an in-chat panel can open the loopback page without the agent receiving a link", async t => { - const directory = await mkdtemp(join(tmpdir(), "browser-panel-")); - const page = join(directory, "browser-panel.html"); - await writeFile(page, ""); - t.after(() => rm(directory, { recursive: true, force: true })); - const fake = await fakeBaguette(); - t.after(() => fake.close()); - const [hostSide, serverSide] = InMemoryTransport.createLinkedPair(); - const shared = new SharedTransport(serverSide); - const plugin = await createTestPlugin("", { - panel: createPanel({ baguette: new Baguette(fake.url), simulatorInput: fakeSimulatorInput() }), - features: [browserPanel({ template: pathToFileURL(page) })], - connections: shared, - }); - const host = new Client({ name: "cursor", version: "1" }, { capabilities: { extensions: { [EXTENSION_ID]: { mimeTypes: [RESOURCE_MIME_TYPE] } } } }); - await plugin.server.connect(shared); - await host.connect(hostSide); - t.after(async () => { await host.close(); await plugin.close(); }); - const { tools } = await host.listTools(); - const openInBrowser = tools.find(tool => tool.name === "mobile_open_browser_panel"); - assert.deepEqual(openInBrowser?._meta?.ui, { visibility: ["app"] }); - const opened = await host.callTool({ name: "mobile_open_simulator", arguments: { platform: "ios" } }); - assert.equal((opened.structuredContent as { browserPanel?: unknown }).browserPanel, undefined); - const result = await host.callTool({ - name: "mobile_open_browser_panel", - arguments: { tool: "mobile_open_simulator", platform: "ios", workspaceTool: "testing" }, - }); - assert.equal(result.isError, undefined); - const url = (result.structuredContent as { url: string }).url; - const link = new URL(url); - assert.equal(link.hostname, "127.0.0.1"); - assert.equal(link.searchParams.get("tool"), "mobile_open_simulator"); - assert.equal(link.searchParams.get("platform"), "ios"); - assert.equal(link.searchParams.get("workspaceTool"), "testing"); - assert.equal((await fetch(link)).status, 200); -}); - -test("opening in a browser without a shared transport is refused", async t => { - const plugin = await createTestPlugin("", { panel: createPanel(), features: [browserPanel()] }); - const [hostSide, serverSide] = InMemoryTransport.createLinkedPair(); - const host = new Client({ name: "cursor", version: "1" }); - await plugin.server.connect(serverSide); - await host.connect(hostSide); - t.after(async () => { await host.close(); await plugin.close(); }); - const result = await host.callTool({ name: "mobile_open_browser_panel", arguments: { tool: "mobile_open_simulator" } }); - assert.equal(result.isError, true); - assert.match((result.content as Array<{ text: string }>)[0].text, /cannot open Mobile Dev in a browser/); -}); - test("a panel that never renders inline links the browser page for MCP Apps hosts too", async t => { const directory = await mkdtemp(join(tmpdir(), "browser-panel-")); const page = join(directory, "browser-panel.html"); diff --git a/packages/mcp-app/src/browser-panel.ts b/packages/mcp-app/src/browser-panel.ts index 52878bfc8..73a55e8d7 100644 --- a/packages/mcp-app/src/browser-panel.ts +++ b/packages/mcp-app/src/browser-panel.ts @@ -3,7 +3,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { PLUGIN_VERSION } from "@mobile-dev/shared/version.ts"; -import { BROWSER_PANEL_CAPABILITY, PANEL_PAGE_META } from "@mobile-dev/shared/panel-target.ts"; +import { PANEL_PAGE_META } from "@mobile-dev/shared/panel-target.ts"; const dark = matchMedia("(prefers-color-scheme: dark)"); const DISCONNECTED = "Mobile Dev disconnected from its chat session. Ask the agent to open Mobile Dev again."; @@ -102,11 +102,7 @@ async function open() { // Advertise only capabilities this browser can fulfill. Chat messages need a // host-owned bridge; model context goes to the server, where the agent reads it. const hostContext = context(); - const capabilities = { - serverTools: {}, serverResources: {}, openLinks: {}, - updateModelContext: { text: {}, image: {} }, - experimental: { [BROWSER_PANEL_CAPABILITY]: {} }, - }; + const capabilities = { serverTools: {}, serverResources: {}, openLinks: {}, updateModelContext: { text: {}, image: {} } }; bridge = new AppBridge(client, { name: host, version: PLUGIN_VERSION }, capabilities, { hostContext }); bridge.onupdatemodelcontext = async ({ content }) => { const sessionId = transport.sessionId; diff --git a/packages/mcp-app/src/components/open-in-browser-button.tsx b/packages/mcp-app/src/components/open-in-browser-button.tsx deleted file mode 100644 index 9cb6a94d7..000000000 --- a/packages/mcp-app/src/components/open-in-browser-button.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import type { App } from "@modelcontextprotocol/ext-apps"; -import { BROWSER_PANEL_CAPABILITY } from "@mobile-dev/shared/panel-target.ts"; -import type { PanelTarget } from "@mobile-dev/shared/panel-target.ts"; -import { Button } from "@mobile-dev/ui/components/ui/button.tsx"; -import { captureUiError, countUiEvent } from "@mobile-dev/ui/telemetry.ts"; -import { ExternalLinkIcon } from "lucide-react"; -import { useCallback, useState, useSyncExternalStore } from "react"; - -export type BrowserPanelOpen = PanelTarget & { tool: "mobile_open_simulator" | "mobile_open_workspace" | "mobile_open_app_intel" }; - -export function OpenInBrowserButton({ app, target, onError }: { app: App; target: () => BrowserPanelOpen; onError?: (message: string) => void }) { - const subscribe = useCallback((onChange: () => void) => { - app.addEventListener("hostcontextchanged", onChange); - return () => app.removeEventListener("hostcontextchanged", onChange); - }, [app]); - const shown = useSyncExternalStore(subscribe, () => { - const capabilities = app.getHostCapabilities(); - if (!capabilities?.serverTools) return false; - return capabilities.experimental?.[BROWSER_PANEL_CAPABILITY] === undefined; - }); - const [busy, setBusy] = useState(false); - if (!shown) return null; - return ; -} diff --git a/packages/mcp-app/src/components/workspace.tsx b/packages/mcp-app/src/components/workspace.tsx index 2029807d7..7f99703fc 100644 --- a/packages/mcp-app/src/components/workspace.tsx +++ b/packages/mcp-app/src/components/workspace.tsx @@ -11,8 +11,6 @@ import { TraceSiftView } from "@mobile-dev/ui/components/tracesift-view.tsx"; import { AppIntelligenceView } from "@mobile-dev/ui/components/app-intelligence-view.tsx"; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@mobile-dev/ui/components/ui/base-select.tsx"; import { Button } from "@mobile-dev/ui/components/ui/button.tsx"; -import type { App } from "@modelcontextprotocol/ext-apps"; -import { OpenInBrowserButton, type BrowserPanelOpen } from "./open-in-browser-button"; import { usePanelRef, useGroupRef, type Layout } from "react-resizable-panels"; import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@mobile-dev/ui/components/ui/resizable.tsx"; @@ -38,7 +36,7 @@ const tools = { type Tool = keyof typeof tools; const isTool = (value: string): value is Tool => value in tools; -export function Workspace({ panels, recordingController, banner, displayModeControl, openInBrowserControl, app, contextControl, automaticTool, automaticToolRevision = 0, devices }: { panels: WorkspaceTools; recordingController: RecordingController; banner?: ReactNode; displayModeControl?: ReactNode; openInBrowserControl?: boolean; app?: App; contextControl?: ReactNode; automaticTool?: ToolName; automaticToolRevision?: number; devices: DeviceWorkspace }) { +export function Workspace({ panels, recordingController, banner, displayModeControl, contextControl, automaticTool, automaticToolRevision = 0, devices }: { panels: WorkspaceTools; recordingController: RecordingController; banner?: ReactNode; displayModeControl?: ReactNode; contextControl?: ReactNode; automaticTool?: ToolName; automaticToolRevision?: number; devices: DeviceWorkspace }) { const { logs, performance, storage, tracesift } = panels; const appIntel = panels["app-intel"]; const appFlow = panels["app-flow"]; @@ -144,8 +142,6 @@ export function Workspace({ panels, recordingController, banner, displayModeCont const menuSide = bottomToolbar ? "top" : "bottom"; const ToolIcon = tools[tool].icon; const toolbar = ; const simulatorPanel = setSimulatorsCollapsed(size.inPixels < 1)}> @@ -179,19 +176,3 @@ export function Workspace({ panels, recordingController, banner, displayModeCont ; } - -function browserPanelOpen(tool: Tool, toolOpen: boolean, devices: ReturnType, selectedScreen: string | null): BrowserPanelOpen { - const view = document.documentElement.dataset.view; - const opening: BrowserPanelOpen["tool"] = tool === "app-intel" && toolOpen ? "mobile_open_app_intel" : view === "workspace" ? "mobile_open_workspace" : "mobile_open_simulator"; - const target: BrowserPanelOpen = { tool: opening }; - if (toolOpen && tool !== "app-flow") target.workspaceTool = tool; - if (tool === "app-intel" && selectedScreen) target.appIntelScreen = selectedScreen; - const pane = devices.panes.find(item => item.key === devices.active); - const device = pane?.device; - if (device && pane) { - target.platform = pane.platform; - target.deviceId = device.udid; - if (device.kind === "simulator" || device.kind === "emulator" || device.kind === "physical") target.kind = device.kind; - } - return target; -} diff --git a/packages/mcp-app/src/workspace-app.tsx b/packages/mcp-app/src/workspace-app.tsx index 2e2f9602d..5c21890ed 100644 --- a/packages/mcp-app/src/workspace-app.tsx +++ b/packages/mcp-app/src/workspace-app.tsx @@ -38,7 +38,7 @@ export function startWorkspaceApp(options: WorkspaceOptions = {}) { const devices = new DeviceWorkspace(app, panels); function renderWorkspace() { const workspace = Mobile Dev could not render. Reopen the panel to try again.

}> - } openInBrowserControl={options.openInBrowserControl} app={app} contextControl={} devices={devices} automaticTool={automaticTool} automaticToolRevision={automaticToolRevision} /> + } contextControl={} devices={devices} automaticTool={automaticTool} automaticToolRevision={automaticToolRevision} />
; reactRoot.render(workspace); } @@ -145,7 +145,6 @@ export function startWorkspaceApp(options: WorkspaceOptions = {}) { if (disposingUI) return; attributeHost(app); hostContext(); - renderWorkspace(); const capabilities = app.getHostCapabilities(); const available = !!capabilities?.serverTools && !!capabilities?.serverResources; panels.setAvailable(available); diff --git a/packages/mcp-app/src/workspace-extension.ts b/packages/mcp-app/src/workspace-extension.ts index 8ab91d7f8..27acc2762 100644 --- a/packages/mcp-app/src/workspace-extension.ts +++ b/packages/mcp-app/src/workspace-extension.ts @@ -15,9 +15,4 @@ export type WorkspaceOptions = { extension?: (app: App) => WorkspaceExtension; /** Show Expand / Back to chat. Hosts with their own fullscreen controls (Codex) turn it off; advertised display modes cannot tell. */ displayModeControl?: boolean; - /** - * Show Open in browser, which loads the loopback page in a host window. Codex - * turns it off: its host blocks localhost, and it already has fullscreen. - */ - openInBrowserControl?: boolean; }; diff --git a/packages/shared/src/panel-target.ts b/packages/shared/src/panel-target.ts index 41d734d68..93ec492ca 100644 --- a/packages/shared/src/panel-target.ts +++ b/packages/shared/src/panel-target.ts @@ -41,11 +41,5 @@ export function panelTargetPlatform(target: PanelTarget): "ios" | "android" | un */ export const PANEL_PAGE_META = "mobile-dev/panel"; -/** - * Host capability the loopback browser page advertises so the in-chat panel can - * hide Open in browser when it is already that page. - */ -export const BROWSER_PANEL_CAPABILITY = "dev.mobile/browserPanel"; - /** How often the open Testing Studio tab re-sends its selection, so the server can tell a closed tab from an idle one. */ export const PANEL_HEARTBEAT_MS = 5_000; From 1956eb89720ee865b230f61e9b3b2aa80d50732b Mon Sep 17 00:00:00 2001 From: Hur Ali Date: Fri, 27 Nov 2026 15:20:04 +0500 Subject: [PATCH 5/7] feat(testing-studio): physical iPhone and Android support with signing team picker (#154) * feat(testing-studio): iOS physical device * feat(testing-studio): add android device * fix: ios signing * feat: signing picker * fix: device signing and errors --- docs/telemetry.md | 2 + packages/core/src/agent-device-runtime.ts | 4 +- packages/core/src/ios-device-build.ts | 49 +++ packages/core/src/ios-signing.ts | 313 ++++++++++++++++++ packages/core/src/telemetry.ts | 2 +- packages/core/src/testing-agent.ts | 7 +- packages/core/src/testing-device.ts | 41 ++- packages/core/src/testing-prepare.ts | 238 ++++++++++++- packages/core/src/testing-run.ts | 27 +- packages/core/src/testing-tools.ts | 71 +++- packages/core/test/ios-signing.test.ts | 214 ++++++++++++ packages/core/test/testing-agent.test.ts | 4 +- packages/core/test/testing-device.test.ts | 21 ++ packages/core/test/testing-matrix.test.ts | 8 + .../core/test/testing-physical-app.test.ts | 33 ++ packages/core/test/testing-prepare.test.ts | 129 +++++++- packages/core/test/testing-run.test.ts | 73 ++-- packages/shared/src/panel-target.ts | 6 +- packages/shared/src/protocol.ts | 20 +- packages/skills/mobile-dev-testing/SKILL.md | 2 +- packages/ui/src/components/testing-matrix.tsx | 30 +- packages/ui/src/components/testing-setup.tsx | 5 +- packages/ui/src/components/testing-view.tsx | 32 +- packages/ui/src/physical-touch.ts | 32 ++ packages/ui/src/simulator-panel.ts | 9 +- packages/ui/src/stream-input.ts | 12 + packages/ui/src/test-recorder.ts | 8 +- packages/ui/src/testing-matrix.ts | 16 +- packages/ui/src/testing-panel.ts | 110 ++++++ packages/ui/test/physical-touch.test.ts | 30 ++ packages/ui/test/signing-team-ui.test.ts | 91 +++++ packages/ui/test/test-recorder.test.ts | 9 + packages/ui/test/testing-matrix.test.ts | 10 + .../test/testing-panel-project-state.test.ts | 78 +++++ website/src/content/docs/docs/testing.md | 22 +- 35 files changed, 1671 insertions(+), 87 deletions(-) create mode 100644 packages/core/src/ios-device-build.ts create mode 100644 packages/core/src/ios-signing.ts create mode 100644 packages/core/test/ios-signing.test.ts create mode 100644 packages/core/test/testing-physical-app.test.ts create mode 100644 packages/ui/src/physical-touch.ts create mode 100644 packages/ui/test/physical-touch.test.ts create mode 100644 packages/ui/test/signing-team-ui.test.ts diff --git a/docs/telemetry.md b/docs/telemetry.md index 58ee4dfeb..1f958f7fc 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -930,3 +930,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 c3ddf4b57..2efb546cf 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 000000000..a288b4149 --- /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 000000000..03128b1c1 --- /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 7353d72f5..72edec986 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 ecc44db77..01199b887 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 443d3fe0a..5e90dcbe9 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 f035349ec..861d47b30 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 692cff320..6a22773cd 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 b51b14299..853da9ba1 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 000000000..f8c696f50 --- /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 6aadd0702..165e69f1c 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 a5eed1ca0..5dcecf7d7 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 f5b35bbd6..ba1550ed7 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 000000000..1c7cccaae --- /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 0566862d4..f0d3ac3a3 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 7657e40e3..a702c5617 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 93ec492ca..62e5315d4 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 ac6d5271e..1a2bbcbd7 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 efe5a0556..d5fc5c2a1 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 461903440..7dff09333 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 c33476b75..8a25a725a 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 5bac8e578..5738d5701 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 000000000..88d91ce06 --- /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 44d14ca45..fe501d92a 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 4cc80f388..bd735fa68 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 cf73a887d..a15715a8c 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 c5e24c165..7e244e524 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 b2bf89365..5ed06b76d 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 000000000..9c484c809 --- /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 000000000..22b7de834 --- /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 c1593ceb8..057b0d4a1 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 93f95efad..c7e406775 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 422e0f242..0c8bee3aa 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 40056ecc2..63721f18a 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. From 05cadebed473cf514bac7818076a5ec4d5ec414e Mon Sep 17 00:00:00 2001 From: Hur Ali Date: Fri, 27 Nov 2026 15:53:29 +0500 Subject: [PATCH 6/7] fix: code reviews --- packages/core/src/testing-run.ts | 8 +++++- packages/core/test/mobile-dev-skill.test.ts | 2 +- packages/core/test/testing-run.test.ts | 8 ++++++ packages/ui/test/testing-matrix.test.ts | 20 +++++++------ packages/ui/test/testing-panel.test.ts | 32 ++++++++++++--------- 5 files changed, 47 insertions(+), 23 deletions(-) diff --git a/packages/core/src/testing-run.ts b/packages/core/src/testing-run.ts index 6a22773cd..65fc3c945 100644 --- a/packages/core/src/testing-run.ts +++ b/packages/core/src/testing-run.ts @@ -496,7 +496,13 @@ async function runProjectPreview(request: TestRunRequest, deps: TestRunDeps): Pr } } -function quoted(value: string): string { return JSON.stringify(value); } +function quoted(value: string): string { + // These strings become JavaScript source in generated e2e configs. Keep HTML and line separators + // escaped as well as quotes and backslashes so the source is safe in every embedding context. + return JSON.stringify(value).replace(/[<>\u2028\u2029]/g, char => ({ + "<": "\\u003c", ">": "\\u003e", "\u2028": "\\u2028", "\u2029": "\\u2029", + })[char]!); +} /** 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; diff --git a/packages/core/test/mobile-dev-skill.test.ts b/packages/core/test/mobile-dev-skill.test.ts index 804b89c54..6b965dfec 100644 --- a/packages/core/test/mobile-dev-skill.test.ts +++ b/packages/core/test/mobile-dev-skill.test.ts @@ -87,7 +87,7 @@ test("the testing skill teaches Testing Studio mode: record saves, run, add the assert.match(skill, /`mobile_testing_agent_finish` \*\*writes the test\*\*.*`relativePath`/s); // Run: one device or several, and devices that are off are the matrix's to boot. assert.match(skill, /`mobile_testing_run_matrix/); - assert.match(skill, /\*\*Devices that are off are booted by the matrix\*\*/); + assert.match(skill, /\*\*Simulators and emulators that are off are booted by the matrix\*\*/); // A platform with no app: ask, wait, add without asking, report the id, run again. assert.match(skill, /mobile_testing_wait_for_app.*mobile_testing_set_target.*mode: "add".*\*\*without asking\*\*.*which id you added/s); // Failure: branch that platform's line only, two tries, then report; never touch an assertion. diff --git a/packages/core/test/testing-run.test.ts b/packages/core/test/testing-run.test.ts index a702c5617..a0706cd59 100644 --- a/packages/core/test/testing-run.test.ts +++ b/packages/core/test/testing-run.test.ts @@ -544,6 +544,14 @@ test("a hardware UDID or phone serial is pinned through a provider the runner re assert.equal(devicePinSource("emulator-5554"), '"emulator-5554"'); }); +test("generated device pins escape HTML delimiters and JavaScript line separators", () => { + const pin = devicePinSource('phone"\u2028\u2029'); + assert.ok(pin.includes('phone\\u003c/script\\u003e\\"\\u2028\\u2029')); + assert.ok(!pin.includes("")); + assert.ok(!pin.includes("\u2028")); + assert.ok(!pin.includes("\u2029")); +}); + 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; diff --git a/packages/ui/test/testing-matrix.test.ts b/packages/ui/test/testing-matrix.test.ts index c7e406775..1e458adc4 100644 --- a/packages/ui/test/testing-matrix.test.ts +++ b/packages/ui/test/testing-matrix.test.ts @@ -82,6 +82,7 @@ function matrixHost(calls: { name: string; arguments: Record }[ const structuredContent = name === "mobile_testing_run_matrix" ? { matrixId: "m1", limit: 2, startedAt: 1, lanes: lanes(["queued", "queued", "queued"]) } : name === "mobile_testing_run_progress" ? { matrixId: "m1", limit: 2, startedAt: 1, lanes: lanes(++polls < 2 ? ["running", "running", "queued"] : ["passed", "passed", "passed"]) } : name === "mobile_list_simulators" ? { devices: [0, 1, 2].map(i => ({ udid: `d${i}`, name: `Phone ${i}`, state: "Booted", runtime: "iOS 26" })) } + : name === "mobile_testing_ios_signing" ? { resolved: { id: "TEAM123", source: "user" }, teams: [{ id: "TEAM123" }] } : name === "mobile_list_apps" ? { apps: [{ bundleId: "com.example.app", name: "App" }] } : {}; return { content: [], structuredContent }; } } as unknown as HostBridge; @@ -143,14 +144,17 @@ test("a mirrored physical iPhone is pinned to a physical matrix lane", async () const mirrored = { subscribe: () => () => undefined, getSnapshot: () => ({ device: { udid: "phone", name: "Phone", platform: "ios", kind: "physical", state: "connected", pairingState: "paired", runtime: "iOS 27" } }) } as unknown as DeviceAppsStore; const panel = new TestingPanel(matrixHost(calls), mirrored); const set = (fields: Record) => (panel as unknown as { update(fields: Record): void }).update(fields); - panel.setAvailable(true); - set({ projectPath: PROJECT, runtimeMode: "bundled", targets: [{ name: "ios", platform: "ios", bundleId: "com.example.app" }], selectedTestPath: "tests/a.e2e.ts", selectedTestSource: 'test("x", async () => {});\n', tests: [{ relativePath: "tests/a.e2e.ts", name: "a", updatedAt: "", sizeBytes: 1, target: { platform: "ios", bundleId: "com.example.app" } }] }); - assert.equal(panel.runsOnMatrix, true); - assert.equal(panel.matrixRunCount, 1); - await panel.runStoredTest(); - const start = calls.find(call => call.name === "mobile_testing_run_matrix"); - assert.deepEqual(start?.arguments.devices, [{ deviceId: "phone", platform: "ios", kind: "physical", name: "Phone" }]); - panel.dispose(); + try { + panel.setAvailable(true); + set({ projectPath: PROJECT, runtimeMode: "bundled", targets: [{ name: "ios", platform: "ios", bundleId: "com.example.app" }], selectedTestPath: "tests/a.e2e.ts", selectedTestSource: 'test("x", async () => {});\n', tests: [{ relativePath: "tests/a.e2e.ts", name: "a", updatedAt: "", sizeBytes: 1, target: { platform: "ios", bundleId: "com.example.app" } }] }); + assert.equal(panel.runsOnMatrix, true); + assert.equal(panel.matrixRunCount, 1); + await panel.runStoredTest(); + const start = calls.find(call => call.name === "mobile_testing_run_matrix"); + assert.deepEqual(start?.arguments.devices, [{ deviceId: "phone", platform: "ios", kind: "physical", name: "Phone" }]); + } finally { + panel.dispose(); + } }); test("the concurrency limit is saved per project but device choices are not", () => { diff --git a/packages/ui/test/testing-panel.test.ts b/packages/ui/test/testing-panel.test.ts index 9dfed6495..c81d943f0 100644 --- a/packages/ui/test/testing-panel.test.ts +++ b/packages/ui/test/testing-panel.test.ts @@ -357,19 +357,25 @@ test("Testing Studio does not flash a mirror mismatch while the switched device' test("a Testing Studio test with no app pins the one in front on its first run, then runs against the pin", async () => { const calls: { name: string; arguments: Record }[] = []; const source = 'test("stored", async ({ app }) => {\n await app.open();\n});\n'; - const panel = new TestingPanel(host({ mobile_testing_run_test: { status: "passed", exitCode: 0, steps: [] } }, calls), frontApps); - panel.setAvailable(true); - (panel as unknown as { update(fields: Record): void }).update({ projectPath: PROJECT, runtimeMode: "bundled", selectedTestPath: "tests/stored.e2e.ts", selectedTestSource: source, tests: [{ relativePath: "tests/stored.e2e.ts", name: "stored.e2e.ts", updatedAt: "", sizeBytes: 1 }] }); - await panel.runStoredTest(); - const first = calls.find(call => call.name === "mobile_testing_run_test")!; - assert.deepEqual([first.arguments.platform, first.arguments.bundleId, first.arguments.pin], ["ios", "com.example.app", true]); - calls.length = 0; - (panel as unknown as { update(fields: Record): void }).update({ tests: [{ relativePath: "tests/stored.e2e.ts", name: "stored.e2e.ts", updatedAt: "", sizeBytes: 1, target: { platform: "ios", bundleId: "com.pinned.app" } }] }); - await panel.runStoredTest(); - assert.ok(calls.some(call => call.name === "mobile_launch_app" && call.arguments.bundleId === "com.pinned.app"), "the pinned app is opened when it is not in front"); - const second = calls.find(call => call.name === "mobile_testing_run_test")!; - assert.deepEqual([second.arguments.bundleId, second.arguments.pin], ["com.pinned.app", undefined]); - panel.dispose(); + let foregroundBundleId = "com.example.app"; + const apps = { subscribe: () => () => undefined, getSnapshot: () => ({ ...frontApps.getSnapshot(), foregroundApp: { bundleId: foregroundBundleId, pid: 1 } }) } as unknown as DeviceAppsStore; + const panel = new TestingPanel(host({ mobile_testing_run_test: { status: "passed", exitCode: 0, steps: [] }, + mobile_testing_tests: { tests: [{ relativePath: "tests/stored.e2e.ts", name: "stored.e2e.ts", updatedAt: "", sizeBytes: 1 }] } }, calls), apps); + try { + panel.setAvailable(true); + (panel as unknown as { update(fields: Record): void }).update({ projectPath: PROJECT, runtimeMode: "bundled", selectedTestPath: "tests/stored.e2e.ts", selectedTestSource: source, tests: [{ relativePath: "tests/stored.e2e.ts", name: "stored.e2e.ts", updatedAt: "", sizeBytes: 1 }] }); + await panel.runStoredTest(); + const first = calls.find(call => call.name === "mobile_testing_run_test")!; + assert.deepEqual([first.arguments.platform, first.arguments.bundleId, first.arguments.pin], ["ios", "com.example.app", true]); + calls.length = 0; + foregroundBundleId = "com.other.app"; + await panel.runStoredTest(); + assert.ok(calls.some(call => call.name === "mobile_launch_app" && call.arguments.bundleId === "com.example.app"), "the pinned app is opened when it is not in front"); + const second = calls.find(call => call.name === "mobile_testing_run_test")!; + assert.deepEqual([second.arguments.bundleId, second.arguments.pin], ["com.example.app", undefined]); + } finally { + panel.dispose(); + } }); test("a Testing Studio save pins the app in front, not a stale target from an earlier app", async () => { From bb615436878211bee76302554482a3638ad7d63a Mon Sep 17 00:00:00 2001 From: Hur Ali Date: Fri, 27 Nov 2026 16:37:36 +0500 Subject: [PATCH 7/7] fix: failing ci --- packages/core/test/serve-emu-boot-wait.test.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/core/test/serve-emu-boot-wait.test.ts b/packages/core/test/serve-emu-boot-wait.test.ts index 85957306e..712f1c2bf 100644 --- a/packages/core/test/serve-emu-boot-wait.test.ts +++ b/packages/core/test/serve-emu-boot-wait.test.ts @@ -53,7 +53,21 @@ else { } else if (command[0] === 'forward' && command[1] === 'tcp:0') process.stdout.write('28000'); else if (command.includes('app_process')) setInterval(() => {}, 1000); - else if (command[1] === 'cat') { process.stderr.write('device booting-device not found'); process.exitCode = 1; } + else if (command[1] === 'cat') { + // spawnAdb starts app_process before polling the socket, but the two adb + // processes can reach this fake in either order on a busy CI runner. + const deadline = Date.now() + 5000; + const checkLaunch = () => { + if (fs.readFileSync(${JSON.stringify(calls)}, 'utf8').includes('app_process')) { + process.stderr.write('device booting-device not found'); + process.exitCode = 1; + } else if (Date.now() >= deadline) { + process.stderr.write('scrcpy app_process did not launch'); + process.exitCode = 1; + } else setTimeout(checkLaunch, 10); + }; + checkLaunch(); + } } `; await writeFile(join(platformTools, "adb"), program, { mode: 0o755 });