Files
software-mansion__argent/packages/tool-server/test/keyboard-error-taxonomy.test.ts
Sebastian Flajszer 1e69c90981 feat(ios-device): add physical iOS support (#944)
# Physical iOS device support

Try it now (cabled iPhone, unlocked, Developer Mode on):

```bash
argent run list-devices                                            # copy the 25-char UDID
argent run launch-app --udid <UDID> --bundleId com.apple.Preferences
```

First launch builds and signs the on-device runner: 3 to 5 minutes, keep
the phone unlocked. Every later start: seconds, from cache. No signing
setup needed if an Apple ID is signed into Xcode; the team is detected
from the keychain.

## What this adds

- Physical iPhone support, on by default: a cabled iPhone simply appears
in `list-devices`. iPhone-only: physical iPads are skipped at discovery.
- 15 tools ported to hardware. Flows replay on device.
- Zero-config signing from the keychain; `ARGENT_IOS_TEAM_ID` is an
override, nothing is persisted.
- Self-contained npm install: the runner's Swift sources ship in the
package. New package `@argent/ios-device-runner` (an XCUITest bundle
hosting an HTTP command server on the device), new tool-server backend
under `src/utils/ios-device/`.
- The one always-on cost: `list-devices` on macOS now runs physical
discovery in parallel with the other platform probes, under the existing
8s devicectl timeout; off-macOS it early-returns.

## Suggested review order

Rough estimate: half a day for the full pass.

1. `packages/ios-device-runner/PROTOCOL.md`, then `README.md` (wire
contract and reliability model, ~15 min)
2. `packages/tool-server/src/utils/ios-device/` (devicectl, usbmux,
team-detect, runner-build, runner-commands: the core)
3. `packages/tool-server/src/blueprints/ios-device-runner.ts` (service
lifecycle, crash recovery)
4. Per-tool device arms and the capability gates
(`ios-physical-device-classification.test.ts` is the ratchet)
5. Docs page, the two new skills, the Swift runner sources

## Requirements

1. macOS host with full Xcode (iOS platform installed); uses `xcrun
devicectl` and `xcodebuild`.
2. An Apple ID signed into Xcode; automatic signing mints the runner's
provisioning profile.
3. USB cable only. Wi-Fi is deliberately unsupported: the transport is
usbmux, and a Wi-Fi-only device lists as `paired`, not `connected`.
4. iPhone paired with and trusting the Mac, Developer Mode on, A12/2018
or newer (modern 8+16-hex UDID, the CoreDevice floor). Legacy 40-hex
UDIDs are not classified as iOS.
5. Signing resolves as: `ARGENT_IOS_TEAM_ID` in the tool-server's
environment (explicit override, CI) -> keychain detection (newest
identity first, memoized per server run, never persisted). One
certificate: nothing to do. Several teams: newest wins; the first tool
result names the pick, the runner-ups, and the override. No certificate:
the error walks through Xcode > Settings > Accounts and Manage
Certificates > + > Apple Development, then retry; it never names the env
var, since a team id alone cannot sign. Bundle ids derive per team
(`com.argent.runner.t<teamid>`). `ARGENT_IOS_RUNNER_PROJECT` overrides
the project path for unusual layouts.

Build artifacts cache under `~/.argent/ios-device-runner`, keyed by
runner sources, Xcode/SDK version, and signing. A team with no
registered devices self-heals: the failed generic build retries against
the connected phone, which registers it.

## How it works

1. `xcrun devicectl` (CoreDevice) is the control plane: discovery,
readiness, app lifecycle. Readiness gates on the wired transport, so an
unplugged phone is refused before any build starts.
2. A signed XCUITest runner is built lazily with the resolved team,
started via `xcodebuild test-without-building`, and parks as an HTTP
command server for 24h. On an npm install the Xcode project is the copy
shipped inside the package.
3. The listener binds to the device's loopback interface; the host
reaches it over usbmuxd with a dependency-free `node:net` client.
4. Mutating commands are journaled by `commandId`; a lost reply is
resolved by asking `status` for the journaled fate, never by replay
(at-most-once delivery).
5. Routing hangs off `resolveDevice` UDID-shape classification plus a
per-tool capability allowlist. CLI and MCP layers are untouched; outside
tool-server, docs, and the runner package the diff is failure-code
constants (registry), two agent skills plus rule updates (skills), the
pack step (packages/argent), and the e2e smoke script.

## Supported tools

| Tool | Status | Notes |
| ----------------- | --------- |
------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| launch-app | Supported | Plain `devicectl` launch. System UI
(SpringBoard/Spotlight) registers a session only; no launch attempt.
Carries a note when signing is not resolvable yet. |
| restart-app | Supported | System UI bundle ids rejected before any
device contact. |
| reinstall-app | Supported | Same system UI pre-flight. |
| screenshot | Supported | Served through the runner; device-wide, needs
no registered app. (No host-side devicectl screenshot exists on any
toolchain; that dead route was removed.) |
| describe | Supported | AX tree snapshot via the runner. Snapshots the
session app's process, so another process's dialogs are not in the tree.
A backgrounded session app fails with an actionable error instead of
being silently re-fronted. Focus polling is off for this source; typing
uses a fixed settle. |
| keyboard | Supported | Types into the focused element; typing with
nothing focused is refused with "tap the text field first". `enter` and
`backspace` are the named keys (both exist as software-keyboard
characters; there is no per-keycode HID surface on hardware).
Whitespace-only keys rejected, not silently "typed". |
| gesture-tap | Supported | `clickCount > 1` dispatches as one native
multi-tap gesture, not separate taps. |
| gesture-swipe | Supported | Single-finger drag between two points. |
| gesture-custom | Supported | Two shapes only: press-hold and straight
single-finger drag. Second finger or `Move` waypoints rejected with
authoring guidance, before any runner starts. |
| button | Supported | `home`, `volumeUp`, `volumeDown`, `actionButton`
(volume buttons are simulator-unavailable in the SDK, not
device-unavailable). `power`/`appSwitch` have no public XCUIDevice API
and reject before device contact; a button the model lacks gets a typed
refusal via `hasHardwareButton`. |
| await-ui-element | Supported | Polls the same runner snapshot describe
returns; waits and taps see identical frames. Degrades to `cause:
"unreadable"` with a note on a backgrounded app, never a raw throw. |
| await-screen-idle | Supported | Same describe path; resolves
not-settled instead of throwing, so a follow-up screenshot still runs. |
| run-sequence | Supported | Outer gate only; each step pre-flights its
own capability. |
| open-url | Supported | devicectl launches the receiving app with the
URL as its launch payload. http(s) defaults to Safari; any other scheme
needs the new optional `bundleId` param (hardware cannot resolve a
scheme's handler system-wide). |
| screenshot-diff | Supported | Live captures through the runner
(full-resolution, device-wide, no registered app needed); the diff
itself runs on the host. Baselines are per device model/resolution;
`rotation` is ignored on hardware. |

Flows run through these tools; the device flow tree gets the same
`subtreeText` hoisting as every other platform, so container-scoped
`text` asserts work.

## Not supported (400 at the capability gate)

1. gesture-pinch, gesture-rotate: no two-finger coordinate API on
hardware. Pinch/rotate flow directives also fail upfront with a clear
error.
2. screen-recording-start/stop (video): simulator-only capture pipeline.
3. rotate, paste, shake, settings-permissions: simulator-only backends,
not ported (paste also hits the iOS 16+ cross-app paste permission
prompt).
4. native-devtools, debugger, profiler families: simulator-side
instrumentation (DYLD injection does not exist on hardware).
5. Physical iPads: filtered at discovery for now.

A test ratchet (`ios-physical-device-classification.test.ts`) keeps
`apple.device` declarations in sync with the ported list.

## Core contracts

1. Observation never mutates the screen: a backgrounded session app
makes `describe`/`await-*` fail with an error naming the three ways out
(screenshot, launch-app, or launch-app com.apple.springboard). Mutating
commands do re-front, and their result carries `reactivated: true`.
2. The runner listener is unauthenticated; mitigation is the
loopback-only bind.
3. `list-devices` states: `connected` (cabled now, usable) vs `paired`
(unreachable, never auto-bound). Wired transport alone decides; a
Wi-Fi-migrated CoreDevice tunnel does not count.
4. The multi-team signing pick rides the first affected tool result as a
one-shot note (the pre-existing notes channel). The `list-devices`
result shape is unchanged from main: devices and avds, nothing else.
5. Rejections are typed 400 validation errors end to end, so a batch
flow run skips one failing flow instead of aborting.

Also: the runner is a first-class device-owned service
(`stop-simulator-server` and `stop-all-simulator-servers` reap it,
detached xcodebuild child included; a crashed runner respawns on the
next call). A passcode-locked phone refuses launches; the devicectl
10002 hint also covers a pending system prompt on an unlocked phone.
Build failures surface xcodebuild's own `error:` lines with signing
hints (no registered devices, free-team app-id cap, missing
provisioning, the `errSecInternalComponent` partition-list fix). An app
XCTest reports as `.unknown` (a swipe-killed foreign app) is refused
with launch-app guidance. Status-bar pinning is skipped on hardware;
pixel-settle masks the top band.

## Testing

- Unit coverage, hardware-independent: UDID classification and
capability routing; usbmux framing and transport; devicectl list/hints
parsing incl. the silent iPhone-only filter; keychain detection against
real certificate fixtures; runner build/cache self-heals (poisoned
cache, concurrent checkout, fresh-team retry); crash/journal recovery;
the backgrounded-observation and reactivated contracts; keyboard guards
incl. the not-focused refusal; system-UI pre-flight; per-tool device
arms.
- Manual smoke on a real device: `scripts/e2e-ios-physical-device.mjs`.

## Docs and skills

1. `features/physical-ios-devices.mdx`: the user-facing walkthrough
(zero-config signing with the sign-in fallback, prerequisites,
app-scoped model, troubleshooting).
2. `fundamentals/supported-platforms.mdx`: physical iPhones in the
platform matrix (iPads not supported yet).
3. `reference/tools.mdx` and `reference/configuration.mdx`: list-devices
states and the `ARGENT_IOS_TEAM_ID` override.
4. Two skills ship with the package via `argent init`:
`argent-ios-device-setup` (setup ladder plus a troubleshooting table
keyed to real error texts) and `argent-ios-device-interact` (the
app-scoped hardware contract, supported subset with alternatives,
gesture recipes, pitfalls). The agent rule and sibling skills route to
them.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
  * Added experimental USB-connected physical iPhone support.
* Physical iPhones now support discovery, app lifecycle actions, URL
opening, accessibility snapshots, screenshots, taps, swipes, custom
gestures, keyboard input, waits, flows, and screenshot comparisons.
* Added automatic signing-team detection with optional
`ARGENT_IOS_TEAM_ID` configuration.
* Added clear handling for paired or unavailable devices and unsupported
hardware actions.

* **Documentation**
* Added setup, troubleshooting, capability, and physical-device usage
guidance.
* Clarified that physical iPads and several simulator-only tools and
gestures remain unsupported.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-09-03 14:33:11 +02:00

290 lines
12 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { Registry, FAILURE_CODES, getFailureSignal, type DeviceInfo } from "@argent/registry";
import { InvalidToolInputError } from "../src/utils/capability";
import { typeSimulatorServer } from "../src/tools/keyboard/simulator-server-keys";
import { makeChromiumImpl } from "../src/tools/keyboard/platforms/chromium";
import { makeIosDeviceImpl } from "../src/tools/keyboard/platforms/ios-device";
import { RunnerCommandError } from "../src/utils/ios-device/runner-client";
import {
clearCurrentIosDeviceApp,
setCurrentIosDeviceApp,
} from "../src/utils/ios-device/app-session";
import { injectVegaNamedKey, injectVegaText } from "../src/utils/vega-input";
import { injectAndroidNamedKey, injectAndroidText } from "../src/utils/android-input";
// The `keyboard` tool's `key` is a free `z.string()` and its `text` is a free
// string, so an unknown named key or an un-typeable character passes zod
// validation but is a *caller* mistake, not an internal fault. The HTTP layer
// maps InvalidToolInputError → 400 and anything else → 500. Before this, the
// non-Android backends threw a plain `Error` (pre-#420) / a `FailureError`
// (post-#420) — both surfaced as 500, so `key: "pageup"` returned 400 on Android
// but 500 on iOS / chromium / vega (hubgan review). These pins keep every
// keyboard backend's input-rejection uniform: a 400-mapping InvalidToolInputError
// that STILL carries #420's granular telemetry code (the 400 mapping keys off the
// error class, not the code — see InvalidToolInputError in utils/capability.ts).
async function expectInvalidInput(p: Promise<unknown>, code: string): Promise<void> {
const err = await p.then(
() => {
throw new Error("expected the call to reject, but it resolved");
},
(e: unknown) => e
);
expect(err).toBeInstanceOf(InvalidToolInputError);
expect(getFailureSignal(err)?.error_code).toBe(code);
}
function iosRegistry(): Registry {
const registry = new Registry();
vi.spyOn(registry, "resolveService").mockResolvedValue({ pressKey: vi.fn() } as never);
return registry;
}
function chromiumRegistry(): Registry {
const registry = new Registry();
vi.spyOn(registry, "resolveService").mockResolvedValue({
dispatchKeyEvent: vi.fn(async () => {}),
} as never);
return registry;
}
const iosDevice = { id: "AAAA", platform: "ios", kind: "simulator" } as unknown as DeviceInfo;
const chromiumDevice = {
id: "chromium-cdp-9222",
platform: "chromium",
kind: "app",
} as unknown as DeviceInfo;
const iosPhysicalDevice = {
id: "00008030-000A1B2C3D4E5F60",
platform: "ios",
kind: "device",
} as unknown as DeviceInfo;
describe("keyboard backends — input rejection is a 400 with a uniform telemetry taxonomy", () => {
it("iOS: unknown key → 400 + KEYBOARD_KEY_UNSUPPORTED", async () => {
await expectInvalidInput(
typeSimulatorServer(iosRegistry(), iosDevice, { udid: iosDevice.id, key: "pageup" }),
FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED
);
});
it("iOS: un-typeable character → 400 + KEYBOARD_CHARACTER_UNSUPPORTED", async () => {
await expectInvalidInput(
typeSimulatorServer(iosRegistry(), iosDevice, { udid: iosDevice.id, text: "😀" }),
FAILURE_CODES.KEYBOARD_CHARACTER_UNSUPPORTED
);
});
it("chromium: unknown key → 400 + KEYBOARD_KEY_UNSUPPORTED", async () => {
const impl = makeChromiumImpl(chromiumRegistry());
await expectInvalidInput(
impl.handler({}, { udid: chromiumDevice.id, key: "pageup" }, chromiumDevice),
FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED
);
});
it("chromium: un-typeable character → 400 + KEYBOARD_CHARACTER_UNSUPPORTED", async () => {
const impl = makeChromiumImpl(chromiumRegistry());
await expectInvalidInput(
impl.handler({}, { udid: chromiumDevice.id, text: "😀" }, chromiumDevice),
FAILURE_CODES.KEYBOARD_CHARACTER_UNSUPPORTED
);
});
it("vega: unknown key → 400 + KEYBOARD_KEY_UNSUPPORTED", async () => {
await expectInvalidInput(injectVegaNamedKey("pageup"), FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED);
});
it("vega: newline in text → 400 + VEGA_TEXT_INVALID", async () => {
await expectInvalidInput(injectVegaText("a\nb"), FAILURE_CODES.VEGA_TEXT_INVALID);
});
it("android: unknown key → 400 + KEYBOARD_KEY_UNSUPPORTED", async () => {
// adbShell is never reached — the unknown key is rejected before injection.
await expectInvalidInput(
injectAndroidNamedKey("emulator-5554", "pageup"),
FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED
);
});
it("android: un-typeable character → 400 + KEYBOARD_CHARACTER_UNSUPPORTED", async () => {
// Same granular bucket as the iOS/chromium un-typeable-character
// rejections above — not the generic TOOL_INPUT_INVALID (hubgan review).
// adbShell is never reached: the guard rejects before injection.
await expectInvalidInput(
injectAndroidText("emulator-5554", "café"),
FAILURE_CODES.KEYBOARD_CHARACTER_UNSUPPORTED
);
});
it("android: newline in text → 400 + KEYBOARD_CHARACTER_UNSUPPORTED", async () => {
// A newline is a character this backend can't type, so it buckets with the
// un-typeable-character rejections.
await expectInvalidInput(
injectAndroidText("emulator-5554", "a\nb"),
FAILURE_CODES.KEYBOARD_CHARACTER_UNSUPPORTED
);
});
// `key` is a free string, so a prototype-chain name ("constructor",
// "__proto__", …) must be rejected as an unknown key on every backend rather
// than slipping through an object lookup with a garbage value and going over
// the wire as a broken press. Pin the 400 + KEYBOARD_KEY_UNSUPPORTED bucket
// for a representative prototype key on each backend.
it("iOS: prototype-chain key name → 400 + KEYBOARD_KEY_UNSUPPORTED", async () => {
await expectInvalidInput(
typeSimulatorServer(iosRegistry(), iosDevice, { udid: iosDevice.id, key: "constructor" }),
FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED
);
});
it("chromium: prototype-chain key name → 400 + KEYBOARD_KEY_UNSUPPORTED", async () => {
const impl = makeChromiumImpl(chromiumRegistry());
await expectInvalidInput(
impl.handler({}, { udid: chromiumDevice.id, key: "constructor" }, chromiumDevice),
FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED
);
});
it("vega: prototype-chain key name → 400 + KEYBOARD_KEY_UNSUPPORTED", async () => {
await expectInvalidInput(
injectVegaNamedKey("constructor"),
FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED
);
});
// android's prototype-chain guard is pinned in keyboard-android.test.ts,
// which additionally asserts adb is never reached.
// The physical-iOS backend normalizes `key` through a trim(), so a
// whitespace-only name collapsed to "" and slipped past its named-key guard
// into the empty-request no-op below it: a 200 { typed: "", keys: 0 } with no
// device contact, which the caller cannot tell apart from a real press (the
// very outcome ../src/tools/keyboard/index.ts's empty-key guard exists to
// prevent). It rejects like every sibling instead.
it("iOS device: whitespace-only key -> 400 + KEYBOARD_KEY_UNSUPPORTED", async () => {
const impl = makeIosDeviceImpl(new Registry());
await expectInvalidInput(
impl.handler({}, { udid: iosPhysicalDevice.id, key: " " }, iosPhysicalDevice),
FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED
);
});
it("iOS device: unknown key -> 400 rejection naming both supported keys", async () => {
const impl = makeIosDeviceImpl(new Registry());
const err = await impl
.handler({}, { udid: iosPhysicalDevice.id, key: "pageup" }, iosPhysicalDevice)
.then(
() => {
throw new Error("expected the call to reject, but it resolved");
},
(e: unknown) => e
);
expect(err).toBeInstanceOf(InvalidToolInputError);
expect(getFailureSignal(err)?.error_code).toBe(FAILURE_CODES.KEYBOARD_KEY_UNSUPPORTED);
// The message is the caller's whole named-key contract on hardware, so it
// must list both keys the backend accepts.
expect((err as Error).message).toContain("only 'enter' and 'backspace'");
});
});
describe("keyboard (ios-device): named-key routing", () => {
beforeEach(() => {
setCurrentIosDeviceApp(iosPhysicalDevice.id, "com.example.app");
});
afterEach(() => {
clearCurrentIosDeviceApp(iosPhysicalDevice.id);
});
// Positive control for the rejection above, pinned at the api.run seam: the
// key that was asked for is the runner command that goes over the wire.
it.each([
{ key: "enter", command: "keyboardReturn" },
{ key: "backspace", command: "keyboardDelete" },
])("routes key '$key' to the runner's $command command", async ({ key, command }) => {
const run = vi.fn().mockResolvedValue({ message: "ok" });
const registry = new Registry();
vi.spyOn(registry, "resolveService").mockResolvedValue({
udid: iosPhysicalDevice.id,
run,
} as never);
const impl = makeIosDeviceImpl(registry);
const result = await impl.handler({}, { udid: iosPhysicalDevice.id, key }, iosPhysicalDevice);
expect(result).toEqual({ typed: key, keys: 1 });
expect(run).toHaveBeenCalledWith({ command, appBundleId: "com.example.app" });
});
});
describe("keyboard (ios-device): typing with nothing focused", () => {
// The runner probes keyboard focus before typing and answers
// TEXT_INPUT_NOT_FOCUSED; audited on an iPhone 15, the pre-probe behavior
// was the generic "XCTest recorded a failure while executing type", which
// named neither the cause nor the fix.
function notFocusedRegistry(): Registry {
const registry = new Registry();
vi.spyOn(registry, "resolveService").mockResolvedValue({
udid: iosPhysicalDevice.id,
run: vi.fn().mockRejectedValue(
new RunnerCommandError("no text input has keyboard focus", {
code: "TEXT_INPUT_NOT_FOCUSED",
})
),
} as never);
return registry;
}
beforeEach(() => {
setCurrentIosDeviceApp(iosPhysicalDevice.id, "com.example.app");
});
afterEach(() => {
clearCurrentIosDeviceApp(iosPhysicalDevice.id);
});
it.each([{ text: "hello" }, { key: "enter" }, { key: "backspace" }])(
"maps TEXT_INPUT_NOT_FOCUSED to the retype instruction for %j",
async (input) => {
const impl = makeIosDeviceImpl(notFocusedRegistry());
const err = await impl
.handler({}, { udid: iosPhysicalDevice.id, ...input }, iosPhysicalDevice)
.then(
() => {
throw new Error("expected the call to reject, but it resolved");
},
(e: unknown) => e
);
expect(err).toBeInstanceOf(InvalidToolInputError);
expect((err as Error).message).toBe(
"Nothing on screen has keyboard focus. Tap the text field first, then retype."
);
expect(getFailureSignal(err)?.error_code).toBe(FAILURE_CODES.KEYBOARD_INPUT_NOT_FOCUSED);
}
);
it("passes other runner failures through untouched", async () => {
const registry = new Registry();
const original = new RunnerCommandError("app 'com.example.app' is not running", {
code: "APP_NOT_AVAILABLE",
});
vi.spyOn(registry, "resolveService").mockResolvedValue({
udid: iosPhysicalDevice.id,
run: vi.fn().mockRejectedValue(original),
} as never);
const impl = makeIosDeviceImpl(registry);
const err = await impl
.handler({}, { udid: iosPhysicalDevice.id, text: "hello" }, iosPhysicalDevice)
.then(
() => {
throw new Error("expected the call to reject, but it resolved");
},
(e: unknown) => e
);
expect(err).toBe(original);
});
});