agent-device
Version:
Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.
1,150 lines • 146 kB
JavaScript
import{r as e}from"./rolldown-runtime.js";import{Jr as t}from"./sdk-batch.js";import{i as n}from"./catalog.js";import{D as r,E as i,R as a}from"./src3.js";import{n as o}from"./flag-registry.js";import{n as s,r as c}from"./command-schema.js";import{a as l}from"./version.js";import{n as u}from"./cli-command-aliases.js";import{n as d}from"./provider-plugin-catalog.js";const f=[`Flows: launchApp (with clearState, permissions, and Apple-only launch arguments; permissions apply after state clearing but before launch, and a launchApp without permissions touches nothing — there is no silent all: allow default); setPermissions (mid-flow permission grants, denials, and resets; all resolves in the backend — each simctl privacy service on iOS, the declared permissions on Android — with specific entries overriding after it); runFlow file/inline; runFlow.when and repeat.while conditions (platform, visible, notVisible, and true, all re-evaluated before every repeat iteration); onFlowStart/onFlowComplete; repeat with times, while, or both; and retry.`,`Interactions: tapOn, doubleTapOn, longPressOn, inputText on the focused element, eraseText (up to 10000 characters), openLink, hideKeyboard, basic pressKey, and back; selector targets poll until available and support recursive index, childOf, above, below, leftOf, rightOf, containsChild, containsDescendants, points, and optional; outer command labels are metadata, not target selectors.`,'Assertions and navigation: assertVisible, assertNotVisible, assertTrue (literal values and ${VAR} lookups only; "", "false", "0", "null", and "undefined" are falsy, everything else is truthy), extendedWaitUntil, scroll, scrollUntilVisible, absolute/percentage/target swipe, takeScreenshot, waitForAnimationToEnd, clearState, stopApp, and killApp (system-initiated process death: am kill on ADB-backed Android devices, which refuse a foreground target with android-kill-requires-background-app — background the app first, for example pressKey: Home — and fail a target whose process survives with android-kill-process-survived; iOS, Limrun, and WebDriver-provider backends run it as stopApp).',`Scripts: ordered runScript file/env scripts with http.post, json, and output variables; evalScript inline expressions run flow-scoped JavaScript and write output.* leaves for later steps.`],p=[`On the native iOS runner, use tapOn on a visible dismissal control. If the app supports drag dismissal, use a swipe that stays above the keyboard.`,`Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict: current runtimes refuse a targeted notifications change and leave notifications untouched under all.`,`Runtime: iOS and Android only; launchApp.clearState and standalone clearState support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading - unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported.`,"Expressions: evalScript and condition true: fields (runFlow.when and repeat.while share one evaluator) are evaluated as JavaScript (flow env and prior output leaves are string-typed); a true: field that is a boolean, a maestro.platform comparison, or plain literal text after ${VAR} lookups is decided without JavaScript, with the assertTrue falsy table for literal text. Other fields stay literal or ${VAR} lookup-only — assertTrue supports literals and bare lookups, and other expression-shaped payloads fail loud.",`Environment: flow env is the default, AD_VAR_* overrides it, and CLI -e KEY=VALUE wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and AD_* stays reserved.`,`Failure diagnostics: resolved targets and runFlow paths are rendered, while inputText payloads remain hidden; do not place secrets in diagnostic identifiers.`,`Trust: runScript, evalScript, and JavaScript condition true: fields execute flow scripts via node:vm, which is not a security sandbox. runScript runs in a daemon child process with a 30 s script budget. It may make http.post network requests (30 s each, response bodies up to 8 MiB), and its output keys cannot contain a dot. Remote flows refuse runScript before reading its file, including files supplied in the replay bundle, and refuse evalScript and true: fields that need JavaScript. Run these scripts only in trusted local flows. Local runScript paths refer to the daemon filesystem: relative paths resolve from the containing flow, and absolute paths and symlinks are allowed.`,`Remote screenshots: takeScreenshot uses a daemon-generated path and reports that path in artifactPaths. The flow cannot choose a file destination on the daemon host. Animation waits and tap retry comparisons use temporary screenshots that are removed after comparison.`,`Errors and tracking: unsupported commands and fields fail with source context when available; open a focused issue only when implementation work is planned.`];function m(){return[`Supported subset:`,...f.map(e=>` - ${e}`),``,`Boundaries:`,...p.map(e=>` - ${e}`)].join(`
`)}const h={summary:`Full multi-touch gesture shapes and platform quirks`,body:`agent-device help gestures
Full command shapes and platform quirks for touch/pointer gestures beyond scroll/swipe. Read this when a task needs multi-touch, a repeated gesture series, or exact per-platform verification.
Shapes:
agent-device longpress 300 500 800
agent-device longpress @e12 800
agent-device swipe 320 500 40 500 --count 8 --pause-ms 30 --pattern ping-pong
agent-device gesture pan 200 420 0 -80 500
agent-device gesture pan 200 420 80 -40 700 --pointer-count 2
agent-device scroll down --until 'id=submit'
agent-device gesture fling right 200 420 180
agent-device gesture pinch 0.5 200 400
agent-device gesture rotate 35 200 420
agent-device gesture transform 200 420 80 -40 2 35 700
agent-device gesture tap 80 300 200 450 310 600 --count 20 --pause-ms 100
scroll <dir> --until <selector> repeats scroll-and-check passes until that element is on screen, then stops: one request instead of a scroll-then-snapshot loop, and it stops on the target rather than overshooting it. It reports the passes it spent; vertical searches compare repeated captures of descendants in the selected scroll container and fail when those captures show no progress. If no container is found, they compare the visible tree. It is refused on top/bottom, which already stop themselves. The default limit is 12 gestures. For a longer list, add --max-passes <n> (1–200); it requires --until. Large pass budgets can hit the 90-second request timeout; inspect the current screen and continue with another search if that happens.
longpress accepts coordinates, @refs, or selectors; prefer @ref/selector, coordinates only as a fallback. Duration and gesture scale/center are positional. gesture pan is one finger by default; add --pointer-count 2 for a parallel two-finger pan. Keep count/pause/pattern on one swipe: --count (cap 200), --pause-ms (cap 10000ms), --pattern ping-pong; the combined swipe/pause schedule is capped at 60000ms.
For repeated iOS smoke checks: press <x> <y> --count <n> --jitter-px <n> for tap series, swipe <x1> <y1> <x2> <y2> --count <n> for drag series. gesture tap touches 2 to 5 distinct points and holds them for --hold-ms (default 50, min 16); --count repeats the same contacts (cap 200) with --pause-ms between, the series must fit 60000ms counting about 500ms per repetition, and a repetition costs about 450ms on a physical iPhone. Use press for one finger. For repeated keys (PIN pad), enter the plan in one command: press @e13,@e14,@e15,@e16 (2 to 16 refs, one press per key, a repeated ref presses the same key twice, click takes the same form); the whole plan resolves and admits against the current frame before the first press, key 1 expires the frame, later keys tap where the snapshot showed them, so re-snapshot and rebuild the plan when the screen can move between keys; a later key that refuses carries details.dispatchedSteps counting the keys already sent, --interval-ms sets the key delay, and --count/--hold-ms/--jitter-px/--double-tap apply to every key.
Platform quirks:
If rotation stops repeated iOS presses, inspect the screen before continuing with the remaining presses.
Cancelled gesture and swipe requests return COMMAND_FAILED with details.reason=request_canceled and record no action. Repetition pauses are interruptible.
iOS transform/pinch/rotate use private XCTest synthesis for a continuous two-finger pan/scale/rotation path; verify app metrics instead of assuming requested values map exactly to recognizer output. A gesture tap of three or more fingers can trigger iOS system gestures (undo/redo, the edit menu) and fast repeats can trigger double-tap recognizers, so verify app state; iOS touches the contacts down and lifts them together; Android touches them down up to 8ms apart and lifts them 8ms apart in reverse order.
Android transform injects a geometric two-finger path; app recognizers may report non-exact pan/scale/rotation -- verify semantic app state or coarse per-component effects instead of exact numeric deltas unless the app exposes stable metrics. If Android needs exact values, prefer isolated gesture pan --pointer-count 2, gesture pinch, or gesture rotate over one combined transform:
agent-device gesture transform 200 420 80 -40 2 35 700 --platform android
agent-device wait text "pan changed yes" 3000 --platform android
tvOS coordinate pan and fling preserve only the dominant direction as a remote swipe; authored endpoints and duration are not preserved.
Gesture planning prefers the active-app frame; a backend without a gesture viewport resolver falls back to the visible snapshot union, which can be less accurate near edges.
Rare iOS accessibility gap: a row shown disabled/hittable:false where press reports success but no UI change, or a collapsed composite control with no child refs -- run snapshot -i --json, compute the target center from rects, press x y, then diff snapshot -i. Coordinates are fallback-only; document why you used them.
Drag to reorder or drop: gesture drag @e12 @e40 holds the source (800 ms by default; positional sourceHoldMs overrides it), moves, and releases on the destination. swipe and fling never hold, so they do not start a reorder.
On mobile, after scroll, swipe, or gesture swipe, the next read waits for two captures to agree; web and desktop targets do not wait. A caller whose own polling verifies the screen adds --no-post-gesture-stabilization to skip that wait; a directional scroll then also skips its movement check.
macOS:
Context menus are secondary clicks, not long presses: agent-device click @e66 --button secondary --platform macos, then snapshot -i.
For fast desktop list traversal, prefer fixed pixel wheel steps and batch them when no snapshot is needed between passes:
agent-device scroll down --pixels 200 --duration-ms 50 --platform macos
agent-device batch --steps '[{"command":"scroll","input":{"direction":"down","pixels":200,"durationMs":50}},{"command":"scroll","input":{"direction":"down","pixels":200,"durationMs":50}}]' --platform macos`},g={maestro:{id:`maestro`,help:{summary:`Supported Maestro YAML commands, grammar, and runtime boundaries`,body:`agent-device help maestro
Run Maestro compatibility flows with replay <flow.yaml> --maestro or test <path> --maestro. Bind an iOS or Android target with --platform or an existing session.
${m()}
Unsupported syntax fails loudly rather than being skipped. Architecture, performance tradeoffs, and declared conformance divergences: https://github.com/callstack/agent-device/blob/main/docs/adr/0015-direct-maestro-engine.md
Focused compatibility request: https://github.com/callstack/agent-device/issues/new`}}};function _(e){return g[e]}function v(e){let t=e.endsWith(`?`),n=t?e.slice(0,-1):e;return t?`[${n}]`:`<${n}>`}function y(e){return o().filter(t=>t.key===e)}function b(e){if(!e.usageHidden)return e.usageLabel??e.names[0]}function x(e){return(e??[]).flatMap(e=>y(e).map(b).filter(e=>e!==void 0).map(e=>`[${e}]`))}function S(e,t){return[t.usageOverride??[e,...(t.positionalArgs??[]).map(v)].join(` `),...x(t.usageFlags??t.allowedFlags)].join(` `)}const C=`Wait failure contract:
Read --json error.details.reason.
wait_target_absent: readable capture, no match.
wait_target_present: absence timeout; details.matches/firstMatch.
predicate_failed: no valid absence capture; observation/diagnostic kept.
wait_capture_stalled: no readable capture by deadline -- retriable.
wait_deadline_exceeded: later capture exhausted budget after a readable one.
wait_readiness_exhausted: readiness deadline; details.readinessPhase -- retriable.
wait_runner_restart_exhausted: restart deadline -- retriable.
wait_landmark_identity_mismatch: replay guard: selector matched, recorded identity differed.
wait_stable_timeout: no stable UI -- not absence.
`,w={"manual-qa":{summary:`Follow manual test scripts with exact interactions and verification`,body:`agent-device help manual-qa
Use this when asked to follow a manual QA script, test case, checklist, acceptance flow, or user-provided instructions.
Contract:
Execute the script. Do not explore unrelated screens, read app source, invent missing requirements, or broaden scope.
Stop and report ambiguity when a required target or expected result is not visible after the documented recovery steps.
Loop:
1. Open the requested app; use --relaunch only when the script needs fresh state.
2. Run snapshot -i to get current refs for the next step.
3. Run press/fill/click/longpress <ref-or-selector> --settle for each mutating step.
4. Treat a settled:true diff as the next observation. Do not add wait stable or another snapshot when the diff already shows the next target or expected result.
5. If --settle prints not settled, follow its hint before the next ref-based action.
6. Verify named expectations with wait text/selector/absent, get, is, find text "..." exists, or the settled diff. Bare find clicks. A bare screenshot/snapshot is not verification for a named expectation.
7. Close the session when the script ends. If your session booted a local simulator or emulator, use close --shutdown, unless the user asks to keep it running.
Command shapes:
agent-device open com.example.app --relaunch
agent-device open https://example.com/deep-link
agent-device snapshot -i
agent-device press @e12 --settle
agent-device press 'label="Follow"' --settle
agent-device fill @e13 "qa@example.com" --settle
agent-device wait text "Order placed" 3000
agent-device wait absent 'label="Loading..."' 3000
agent-device close
--relaunch forces fresh app state; a deep link/URL open does not need it. Labels with an apostrophe or quote (label="Don't leave") are shell-quoting hazards: prefer the @ref from the latest snapshot/settle output over quoting the literal label.
Targets:
Prefer refs from the latest snapshot -i or settled diff. Use durable selectors when the label/id is known: label="Search", id="submit", role=button label="Follow". If label text matches both a field and its caption, target the field with label="Email" editable=true.
For text fields, use fill <target> <text> --settle to replace the field value; use type only to append to an already-focused field.
Do not use placeholders such as @ref, @eN, <button>, or <selector> in a final command plan. If the ref is unknown, first run snapshot -i.
Coordinates are fallback-only after refs/selectors fail or accessibility omits the target; use screenshot or snapshot -i --json to choose a visible center point.
Recovery:
Network/typeahead result missing: wait text "Expected result" or wait <selector>.
A target that should be gone/disappear: use wait absent <selector>; wait exists ... is rejected in favor of the plain selector wait.
Keyboard visible over the next target: a tap point under a measured keyboard frame returns tap_keyboard_occludes_target. Press a visible Hide Keyboard key or the app's dismissal control. In apps that support drag dismissal, use gesture pan from inside the scrollable content. Use keyboard enter only to send Return. Missing keyboard nodes never prove absence. A raw coordinate behind the keys taps anyway and reports a warning.
Target covered by other visible UI: refused with target_covered. When the occlusion scan identified the covering element, error.details.coveredBy and the hint name it (role, label, rect); the cover is diagnosis only -- never target its ref. Follow the hint's recovery: dismiss or close the cover only when it is dismissible (sheet, dialog, alert); under a persistent bar (tab bar, toolbar, navigation bar, bottom navigation) use a different visible target or inspect with snapshot/screenshot before retrying.
Sparse or recovered accessibility snapshot: use screenshot as visual truth, leave the bad screen if needed, then retry snapshot -i.
Non-hittable success hint: verify with the settled diff or snapshot; retarget by a better ref/selector if the UI did not change.
${C}`}},T={debugging:{summary:`Targeted failure evidence without dumping stale context`,body:`agent-device help debugging
Use this when behavior fails, hangs, times out, throws alerts, or needs runtime evidence.
Logs:
Keep log windows small. Prefer clear, mark, reproduce, then path.
agent-device logs clear --restart
agent-device logs mark "before diagnostics retry"
agent-device press 'id="load-diagnostics"'
agent-device logs path
Do not cat a full stale log into agent context. Open or grep only the relevant window when needed.
logs clear --restart is the compact command to clear old logs and start a fresh capture; do not split it into logs stop, logs clear, logs start.
On iOS simulators, logs scope by bundle id and resolved app executable, so use this instead of raw simctl log stream predicates.
On iOS physical devices, logs start and logs clear --restart relaunch the session app through devicectl process launch --console so stdout/stderr can be captured; logs start reports relaunched: true. logs stop ends the app.
For iOS simulator launch-time stdout/stderr, use --launch-console on the direct app launch:
agent-device open MyApp --platform ios --relaunch --launch-console ./artifacts/app.console.log
--launch-console is only for local or Limrun iOS simulator app launches, not URL opens.
Network:
Use network dump for recent session HTTP traffic parsed from app logs.
agent-device network dump --include headers
agent-device network dump 20 --include all
Use this instead of logs path when the question is request/response metadata.
network log is a supported alias, but network dump --include headers is the clearest plan form. Do not write network log headers.
Events:
Use events for a compact session timeline without dumping full app logs.
agent-device events
agent-device events 50 100
Events preserve command names, status, durations, bounded device/app inventory previews, lifecycle outcomes, artifact basenames, and structural action details such as scroll distance/direction, safe refs, and coordinates. User-entered text, clipboard contents, push/event payloads, selector values, free-form flags/messages/paths, and raw unknown command arguments are omitted or replaced with content-free placeholders. --no-record suppresses action.recorded entries, but request start/finish entries still record command, status, and timing.
Events are best effort: an event over the file cap (AGENT_DEVICE_EVENT_LOG_MAX_BYTES, default 5 MiB) or 16 MiB is dropped. Pending writes are capped per session at 128 events and 16 MiB.
Drops and write failures emit session_event_log_write_failed without failing the command. Failed entries are not replayed.
Audio:
Use audio probe when the question is whether a browser page, macOS session, iOS simulator, or Android emulator produced audible output during a short observation window.
agent-device audio probe start 10 1000 --platform web
agent-device audio probe status --platform web
agent-device audio probe stop --platform web
agent-device audio probe start 10 1000 --platform macos
agent-device audio probe start 10 1000 --platform ios
agent-device audio probe start 10 1000 --platform android
audio probe start uses duration seconds first, then bucket milliseconds. Results are compact rmsDbfs and peakDbfs arrays so agents can correlate audible moments with screenshots, actions, network entries, or frame samples.
On web, audio probe samples HTML media elements and URL-backed media may be routed through the probe AudioContext while observed.
On macOS hosts, audio probe samples host system audio through ScreenCaptureKit for macOS sessions, iOS simulators, and Android emulators. It requires Screen Recording permission and is system-audio evidence, not app-instrumented audio. Physical iOS and Android devices are not supported.
Crash symbolication:
Crash routing:
Use logs when you need the lead-up timeline before a failure.
Use debug symbols when you have crash.ips/crash.log plus a matching dSYM/build directory and need the failing frame.
Use Xcode/LLDB when you need live state, breakpoints, variables, memory, or stepping.
Use debug symbols when you already have an Apple crash artifact and local dSYMs and need the failing code path, not a full log dump:
agent-device debug symbols --artifact crash.log --dsym MyApp.dSYM --out crash-symbolicated.log
agent-device debug symbols --artifact crash.ips --search-path ./build --out crash-symbolicated.ips
debug is intentionally narrow. Do not use it for logs, network/audio evidence, performance samples, recordings, traces, or React Native internals.
Apple support matches crash Binary Images / IPS usedImages UUIDs against dwarfdump --uuid output from .dSYM bundles, then writes a symbolicated artifact path and compact crash report: app/thread, exception or termination, top symbolicated frames, and first-frame finding. This is better than pasting crash logs because it keeps agent context small while preserving the artifact on disk for inspection.
Android Java/R8 mapping.txt and native ndk-stack/addr2line symbolication are not in this first debug symbols workflow; capture crash evidence with logs and use the Android toolchain externally for now.
Alerts:
Native and platform dialogs:
agent-device alert wait 3000
agent-device alert accept
agent-device alert dismiss
Android support is snapshot-derived for runtime permission prompts and native app dialogs. iOS support is runner-derived for XCTest alerts, app-owned modal popups with native blocking markers, Safari page prompts such as "Open this page in …?", and blocking system dialogs. Use cheap alert get for an immediate check; use alert wait <short-ms> only when a prompt may appear after async work.
If alert reports no alert but a sheet is visible, alert did not recognize it. Press the button by the ref snapshot -i prints (@e3 is an example):
agent-device snapshot -i
agent-device press @e3
ALERT_UNRESOLVED means alert could not finish reading the prompt state or found an app alert, Safari dialog, or dismiss-popup window without actionable controls. Inspect it with screenshot, then snapshot -i.
Do not use settings permission to answer a dialog already on screen. Reserve settings permission for setup/resetting permission state before a flow.
Diagnostics and traces:
A failed command prints one summary line first and again last on stderr: Error (CODE), the message, whether the action reached the device when that is known, and a Next step. Follow the Next step. Live progress and --debug output can print before the first copy; the last line is always the summary.
"May have reached the device" means the action can already have run. Run snapshot to check the screen before you retry it. "Not dispatched" means a retry is safe. A summary with neither does not prove the action did not run; check the screen before you retry an action.
The Log line between the two summary lines names the failing request's diagnostics file. Use --json to read hint, logPath, and details.dispatched.
Use --debug for the raw error details and the daemon log tail.
Use AGENT_DEVICE_EXEC_TRACE=1 when you need host-tool spawn timing without full debug streaming; it flushes the full request diagnostics file on successful requests that spawn host tools.
Open output includes Session state; JSON also includes runnerLogPath and requestLogPath.
For open timing under --debug, run open --debug --json and inspect requestLogPath for the open_timing event.
Session requests/<request-id>.ndjson holds daemon request diagnostics; session runner.log holds Apple runner/xcodebuild output.
Against a remote daemon the Log path is always local: the failing request's record is fetched to <state-dir>/remote-diagnostics/, and if it cannot be fetched the line reads "Log: unavailable" with the reason instead of a daemon-host path.
daemon.log is global daemon lifecycle evidence, not the primary per-run log.
Use trace for low-level session diagnostics around one repro:
agent-device trace start ./traces/diagnostics.trace
agent-device press 'id="load-diagnostics"'
agent-device trace stop ./traces/diagnostics.trace
The trace path is positional. Do not use --path for trace start or trace stop.
Use perf xctrace only for Apple native CPU/profile or Animation Hitches artifacts:
agent-device perf cpu profile start --kind xctrace --template "Time Profiler" --out ./artifacts/app.trace
agent-device perf cpu profile stop --kind xctrace --out ./artifacts/app.trace
agent-device perf cpu profile report --kind xctrace --out ./artifacts/app-profile.json
agent-device perf trace start --kind xctrace --template "Animation Hitches" --out ./artifacts/hitches.trace
agent-device perf trace stop --kind xctrace --out ./artifacts/hitches.trace
perf xctrace keeps the .trace artifact on disk; CPU report returns a bounded weighted top-function summary. Do not dump .trace contents into context.
For Android native CPU/trace evidence, use perf artifacts instead of raw adb/simpleperf/perfetto output:
agent-device perf cpu profile start --kind simpleperf --out /tmp/cpu.perf.data
agent-device perf cpu profile stop --kind simpleperf
agent-device perf cpu profile report --kind simpleperf --out /tmp/cpu-report.json
agent-device perf trace start --kind perfetto --out /tmp/app.perfetto-trace
agent-device perf trace stop --kind perfetto
Treat native perf output as the agent evidence: for example, state=stopped, outPath=/tmp/app.perfetto-trace, sizeBytes=5392410, method=adb-shell-perfetto. The 5.3 MB raw trace stays in the artifact.
CPU reports return at most ten top functions in structured data and print five in default CLI output.
Use explicit perf frames, perf memory, perf cpu, or perf trace forms. Aggregate perf was removed in 0.21: bare perf, perf sample, perf metrics, and metrics fail with exact replacements.
Startup duration belongs to the open command's startup result; read it there.
Memory diagnostics:
Use perf memory when the symptom is leak/growth/OOM suspicion and you need agent-readable evidence.
agent-device perf memory sample --json
agent-device perf memory snapshot --kind android-hprof --out ./artifacts/app.hprof
agent-device perf memory snapshot --kind memgraph --out ./artifacts/app.memgraph
Example sample shape:
{"metrics":{"memory":{"available":true,"totalPssKb":562958,"totalRssKb":570304,"topConsumers":[{"name":"Dalvik Heap","pssKb":213456}]}}}
Example default snapshot output:
Memory artifact (android-hprof): /tmp/app.hprof (42MB)
Prefer perf memory sample over raw dumpsys/leaks output for first-pass agent diagnosis: it keeps arrays bounded and returns only relevant memory evidence.
Prefer perf memory snapshot over printing heap/memgraph data: snapshots return path, size, kind, method, and support metadata while the large artifact stays on disk for external inspection.
Unsupported platforms return artifact.available=false with reason/hint; do not pretend a heap or memgraph was captured.
Stabilizers:
Android animation-sensitive flows:
agent-device settings animations off
agent-device snapshot
agent-device settings animations on
Re-enable settings you changed before finishing.
Text-entry quirks:
Local iOS fill reuses focus when the current command identifies the target input and reads its keyboard focus. Readable focused inputs use select-all/delete with read-back before any fallback caret tap. Masked inputs, such as secure fields, that show nothing or a placeholder that is not a mask are not cleared; other masked inputs get deletes with read-back before any fallback caret tap. Masked text the deletes can't reach that shows as many bullets as the placeholder reads as cleared, so the new text is typed next to it.
iOS Allow Paste cannot be exercised under XCUITest; prefill with clipboard write "some text" instead and test the system prompt manually.
Android Gboard handwriting/stylus UI can capture text in an IME-owned input instead of the app field. If fill reports that input was captured by the keyboard/IME, use the diagnostic targetInput/actualInput details, inspect keyboard status/get if needed, and switch or disable handwriting outside the command plan before retrying. Do not keep retrying fill/type against the same field while the IME owns focus. If the exact target changes but app-owned formatting prevents raw equality, fill succeeds with verification: "unconfirmed" plus target-bound requested/before/after evidence; inspect that evidence instead of retrying the same mutation.
iOS accessibility-driven fill types the replacement once and never clears and retypes a read-back mismatch. Exact settled text confirms the entry. Nonempty replacements wait until the confirmation deadline before reporting TEXT_ENTRY_MISMATCH. A value containing only characters in order from the post-clear value plus the request fails with TEXT_ENTRY_MISMATCH, including plain dropped characters and unchanged values; legitimate trimming or masks can also hit this limit ("5" into "$0.00" displaying "$0.05"). Other settled values return verification: "unconfirmed" with requested/before/after/target evidence, including grouping ("00 062 91 77" for "000629177"), currency ("$10.00" for "1000"), and OTP summaries. Missing, reordered, duplicated or stale text can also be unconfirmed, so assert the expected value with a value selector, get/is, or the resulting screen before continuing. For single-line fills ending in a submit key, any non-matching value observed on the same target succeeds unverified, including partial or cleared text; this exception skips dropped-character checks because the submit may change the field. Assert the resulting screen. Multiline fields compare newlines as content. Unreadable or removed fields remain unverified. The coordinate-driven fill route still requires an exact match. After TEXT_ENTRY_MISMATCH, inspect the field and retry fill only if it needs correction, using the --delay-ms value from the error hint.
React Native internals:
If the question is about React component props, state, hooks, the component tree, performance, render causes, slow components, or rerenders, use help react-devtools instead of inferring from screenshots or logs.`}},E={accessibility:{summary:`Whole-app accessibility review with audit and device-setting checks`,body:`agent-device help accessibility
Use this when asked for an accessibility review, a11y audit, or a screen-reader or touch-target check of an app.
Scope:
Audit findings are advisory heuristics. Audit checks touch-target size, missing accessible names, and covered controls.
This tool does not measure color contrast or focus order, and does not give a compliance verdict. Do not claim compliance.
Loop for each screen:
1. Open the app: agent-device open <app>. Run mkdir -p ./a11y-output once.
2. Run agent-device audit, then agent-device snapshot -i. Audit captures the screen itself, so it goes first.
3. Record each finding with its kind, role, element name, and size. Audit's pinned refs (@eN~sG) stay valid only until the next snapshot.
To act on a finding, use the ref from that snapshot -i. The ref numbers can differ, so do not match by ref number.
Use the element name or identifier that audit prints only when it matches exactly one element in the snapshot. Snapshot -i text prints an identifier only for an element with no label or value, so read identifiers from agent-device snapshot -i --json.
When the name matches more than one element, or the finding line shows only a role, match by role and by the rect from agent-device audit --json and agent-device snapshot -i --json.
Act only on a unique element. If no element is unique, report the finding and do not act.
4. Capture evidence: agent-device screenshot ./a11y-output/<screen>.png --overlay-refs
Coverage:
Visit every tab, pushed screen, sheet, dialog, and empty, error, and loading state.
Audit covers the visible screen only. On a long list, run agent-device scroll down 0.8, then run audit again.
Checks audit cannot do:
Large text: first run agent-device settings text-size to record the current size. Then run agent-device settings text-size accessibility-extra-extra-extra-large, then agent-device open <app> --relaunch. The app adopts the size only after a relaunch.
Then run audit and screenshot each key screen. Look for clipped, truncated, or overlapping text.
At the end, set the recorded size again. For example, if the recorded size was large, run agent-device settings text-size large.
Dark mode: first note the current mode from a screenshot. Then run agent-device settings appearance dark, then screenshot each key screen. Look for low-contrast text and icons by eye.
At the end, set the noted mode again. For example, if the noted mode was light, run agent-device settings appearance light.
If settings refuses on this device, such as a physical iPhone, list large text and dark mode as not done.
Screen reader order and labels: read agent-device snapshot (without -i) from top to bottom. The order must match the visual order.
A label must be specific and unique: "Save Lemon Herb Rice", not "Save". A control must expose its state (selected, checked, disabled).
Gesture-only actions: every swipe or long-press action needs another way to reach it, such as a visible control or an accessibility action.
On the iOS simulator, agent-device snapshot -i --actions names the custom actions that a merged element hides.
Fix loop (only when the user asks to fix):
Change the app source, then reload (Fast Refresh, or agent-device open <app> --relaunch).
Run audit again on the same screen and confirm the finding is gone. Report the before and after audit output.
Report:
Group findings by screen. For each finding, give the kind, element name or identifier when shown, ref, screenshot path, and suggested fix.
List the checks you could not do. Include audit's limitation lines in that list.`},dogfood:{summary:`Exploratory QA workflow with reproducible evidence`,body:`agent-device help dogfood
Use this when asked to dogfood, exploratory test, bug hunt, QA, or find issues in an app.
Goal:
Find user-visible issues from runtime behavior. Do not read app source or invent findings from code.
Produce a concise report with severity, repro commands, expected/actual behavior, and evidence paths.
Loop:
1. Identify target app/platform; ask only if missing.
2. Create output dirs and open the app. If auth or OTP is required, sign in or ask the user for the code.
3. Capture baseline snapshot -i and screenshot.
4. Map top-level navigation, then exercise primary flows and edge states.
5. For each issue, capture evidence and write the finding immediately, then continue.
6. Close the session and reconcile the report summary.
Keep stateful commands serial within the same session. Parallel runs can pollute text fields, focus, alerts, and navigation state.
Platform checks:
On the first screen, and after a screen changes meaningfully, run audit, then snapshot -i. Audit captures the screen itself, so it goes first. Audit's pinned refs (@eN~sG) stay valid only until the next snapshot. To act on a finding, use the ref from that snapshot -i. Match the finding by the element name or identifier that audit prints, only when it matches exactly one snapshot element, not by ref number. Otherwise use role and rect from the JSON output. Act only on a unique element. Report audit's findings as accessibility findings.
For a whole-app accessibility review, read help accessibility.
On iOS, test Back and the edge-back swipe where a screen was pushed. On Android, test system Back and applicable sheet dismissal.
Where a sheet is dismissible, swipe it down with no edits and expect dismiss. Dismiss it after an edit and expect confirm or save. Then press explicit Cancel.
When the app autosaves, discards explicitly, requires the flow, or presents the surface as nondismissible, skip that probe.
Check that each destructive action confirms or offers undo, and that every swipe action is reachable another way.
To check a field's return key, focus the field, then run keyboard status. Compare returnKey with the field's task. Exercise each control once with press <ref-or-selector> --settle, using reversible test data.
Follow Apple (https://developer.apple.com/design/human-interface-guidelines/) and Material (https://m3.material.io/foundations/designing/structure) guidance for further platform conventions.
Coverage:
Navigation, forms, empty/error/loading states, offline or retry behavior, permissions, settings, accessibility labels, orientation/keyboard, and obvious performance stalls.
React Native warning/error overlays can be real findings or test blockers. Capture them, use react-native dismiss-overlay if unrelated, re-snapshot, and report them.
Expo Go/dev-client shells: use the provided exp:// or dev-client URL and record whether the shell, project load, or app UI is being tested. On iOS dogfood, prefer agent-device open "Expo Go" <url> when Expo Go is the known shell, then snapshot -i to confirm the project UI rather than the runner splash.
Android RN/Expo/Re.Pack dev server: direct Android localhost URL opens with a port auto-configure host reachability.
Categories: visual, functional, UX, content, performance, diagnostics, permissions, accessibility.
Severity: critical blocks a core flow/data/crashes; high breaks a major feature; medium has friction or workaround; low is polish.
Evidence commands:
mkdir -p ./dogfood-output/screenshots ./dogfood-output/videos ./dogfood-output/traces
agent-device open <app> --platform ios
agent-device snapshot -i
agent-device screenshot ./dogfood-output/screenshots/initial.png
agent-device screenshot ./dogfood-output/screenshots/issue-001.png --overlay-refs
agent-device logs clear --restart
agent-device logs mark "issue-001 repro"
agent-device logs path
agent-device record start ./dogfood-output/videos/issue-001.mp4
agent-device record start ./dogfood-output/videos/benchmark.mp4 --hide-touches
agent-device record stop
agent-device close
Evidence rules:
Interactive/behavioral issues need step screenshots and usually a repro video.
Static/on-load issues can use one screenshot; set repro video to N/A.
Use screenshot --overlay-refs when showing the tappable target or broken state helps repro.
Report shape:
./dogfood-output/report.md
Include date, platform, target app, session, scope, severity counts, and issues.
For each finding: ID, severity, category, title, affected flow/screen, repro commands, expected, actual, evidence files, notes.
Target 5-10 well-evidenced issues when available. If no issues are found, report coverage completed and residual risk instead of claiming the app is bug-free.
Rules:
Findings must come from observed runtime behavior, not source reads.
After each mutation, use the --settle diff as evidence when available; otherwise re-snapshot.
Wait timeouts are integer milliseconds in the trailing positional: agent-device wait 'role=tab' 10000. Do not write duration suffixes such as 10s.
scroll takes a selector-less direction+amount form: agent-device scroll down 0.8. One gesture cannot travel further than 0.8 of the viewport axis, so a larger amount saturates rather than covering more ground; to cross several screens use agent-device scroll down --until <selector> or scroll bottom. Use --settle to wait for the UI to go quiet and get the settled diff.
Keep commands in the report reproducible; use selectors or refs from fresh snapshots, not guessed coordinates.
Prefer refs for exploration and selectors for deterministic replay.
Use logs, network, screenshot --overlay-refs, trace, perf frames, perf memory, native profiles, or react-devtools only when they add evidence to a specific issue.
Never delete screenshots, videos, traces, or report artifacts during a session.
Escalate to help debugging or help react-devtools when runtime symptoms require those tools.`},validate:{summary:`Engineering self-validation with device evidence and cleanup`,body:`agent-device help validate
Use this when validating a code change, release candidate, performance fix, visual behavior, logging path, replay, or device-facing regression.
Contract:
Prove the changed behavior through public agent-device surfaces. Do not validate against stale dist output, a retained stale daemon, or a runner built before the change.
Keep evidence reproducible: exact commands, target device/app, observed output, artifact paths, and cleanup status.
Required freshness gate before device verification:
For a TypeScript runtime or CLI output change, start with pnpm build. For non-Android device verification, run pnpm clean:daemon next.
Before local Android verification, run pnpm build:android before pnpm clean:daemon so the bundled helpers match current source.
For an Apple runner change, run pnpm build:xcuitest and avoid inherited retained runners from older source. Do not build the Apple runner for TypeScript-only changes.
Use open --relaunch when startup state matters. Use a purpose-specific --session for multi-step validation.
CI may cache ~/.agent-device/apple-runner/derived with an exact key that includes the agent-device package and Xcode version. Runner reuse is authorized only by the cache metadata's content manifest, so a restore that fails validation rebuilds; prepare ios-runner already recovers one retryable non-connecting runner launch.
Loop:
1. Build or prepare the changed surface with the repo command that owns it.
2. Open the target app/device state explicitly.
3. Use snapshot -i and press/fill/click/longpress --settle for UI-driving steps.
4. Use the settled diff as evidence when it shows the changed behavior; otherwise verify with wait/get/is, find text "..." exists, screenshot, logs, network, perf, or trace based on the claim.
5. Record timings, token/output size, screenshots/videos, logs, or perf artifacts only when they answer the validation question.
6. Close sessions and release leases before finishing. If your session booted a local simulator or emulator, use close --shutdown, unless the user asks to keep it running.
Evidence:
CLI/runtime freshness: pnpm build, pnpm clean:daemon, then agent-device --version or the command under test.
Apple runner freshness: pnpm build:xcuitest, then a live agent-device command on the target simulator/device.
Visual claim: screenshot, optionally screenshot --overlay-refs when target mapping matters.
Runtime/logging claim: logs clear --restart, logs mark, reproduce, logs path.
Network claim: network dump --include headers when headers are relevant.
Performance claim: perf frames, perf memory sample, native profile reports, or trace artifacts with bounded output.
Replay/regression claim: replay or test through the public command path.
Report:
Summarize what changed, exact validation commands, pass/fail observations, artifact paths, and residual risk.
If live validation is blocked, state the blocker, device/session, and exact next command needed.`}};function D(){return`agent-device <command> [args] [--json]
Automates iOS, Android, macOS, TV, and web apps for AI agents.
All ${n().length} commands: agent-device help commands
Start:
When starting a task with a known app, first run:
agent-device open <app> --foreground
It starts the session and returns the initial interactive snapshot with @refs.
Do not probe first with devices, apps, appstate, snapshot, or screenshot.
Unknown app id: devices, then apps, then open <discovered-id>. Never invent ids.
Resuming an existing session: continue from its current state; do not reopen it.
Loop:
press|click|fill|longpress <target> ... --settle
hover <target> --settle (web only; reveals hover-gated UI)
scroll <direction|top|bottom> [amount] --settle; back --settle
acts, waits for quiet, and prints the UI diff. Continue from that diff.
Run snapshot -i only when the diff lacks the next target or did not settle.
Verify a named expectation with the diff, wait text "...", wait <selector>, wait absent <selector>,
is, or get. A bare screenshot is not verification.
find acts: it clicks by default. To check only, use find text "..." exists.
End with: agent-device close
Targets:
Copy refs exactly: @e12, @e12~s4. Keep @ and any ~sN pin; refs go stale
after mutations. A literal @handle is label="@handle", not a bare ref.
Prefer refs, then id/label/role selectors. Selector keys: ${t.join(` `)}.
Coordinates are last resort: after snapshot -i shows no semantic target, or a
sparse/AX-unavailable warning says its refs and selectors are invalid.
Then screenshot, press <x> <y>, and re-snapshot on the changed screen.
Rules:
--settle is only for press/click/fill/longpress/hover/scroll/back; never open,
snapshot, or close. type never accepts --settle.
fill <target> <text> --settle replaces; type <text> appends after focus.
Late network/debounce result: wait text "Expected", not snapshot polling.
Output full agent-device commands; no pipes, grep, jq, or pseudo-commands.
Stop when the requested end state is visible. Mutations run serially.
More commands (exact shapes: agent-device help <command>):
open install devices apps boot close app and device lifecycle
screenshot record logs network perf trace evidence and diagnostics
replay test batch session scripted flows
alert keyboard clipboard settings gesture system and input
Guides (agent-device help <topic>):
workflow full refs, selectors, waits, recovery, and platform limits
manual-qa / dogfood / accessibility / validate / debugging / scripting / gestures
react-native / react-devtools / cdp / tv / web / macos / remote
physical-device / ios-system-ui / maestro
foldable iPhone Duo panels, the fold command, and why refs die on a pose change
`}const O={summary:`Foldable devices: panels, pose, and which screen you are on`,body:`agent-device help foldable
A foldable Apple device (iPhone Duo) carries two integrated panels, which Apple calls the outer display and the inner display. Only one is lit at a time; the lit panel distinguishes closed from non-closed, but not open from half-open. Use UIHinge.status for the exact pose.
Screens are handled for you:
Each iOS simulator capture resolves the panel table, selects the sole lit panel when power identifies it. The simctl path normalizes density with that panel's point scale; runner fallback uses the display's reported pixels-per-point. The table comes from CoreDevice in the default simulator set and from a helper inside the simulator in a scoped set (--ios-simulator-device-set), which CoreDevice cannot reach. There is no screen flag. When panel power names no single lit panel, the capture names the table's primary panel, which may be dark and yield an all-black PNG. Check the pose with UIHinge.status before trusting that capture. With no primary panel either, capture fails with COMMAND_FAILED and reason capture-panel-unidentified rather than pick a panel by list order.
The two panels are different sizes (iPhone Duo: 466x678 points closed on the outer panel, 669x951 open on the inner). A pose change therefore invalidates every ref and coordinate. Re-snapshot after any pose change and never carry coordinates or refs across one.
Check which panel is lit before trusting a geometry claim: use the fold response's screen.widthPt and screen.heightPt; 466x678 versus 669x951 identifies the panel.
Changing the pose:
agent-device fold closed | half-open | open
fold sends a private HID hinge event inside the selected simulator and then reads the hinge angle back until it agrees, each read a separate in-simulator CoreMotion sample: closed is 0 degrees, open is 180, and half-open is any angle between them. An angle in that interval only proves the category, so half-open is reported once consecutive readings both fall inside it and agree. The response reports the verified pose, the hinge angle, and the panel the device now lights with its native panel point size, marked coordinateSpace "native-panel". That point size is the panel's own geometry, not the next snapshot's viewport, so it cannot place a tap: the active app window can differ (a 669x951 inner panel hosts a 951x669 window). A hinge whose last reading is some other pose fails with COMMAND_FAILED and reason fold-pose-unverified, naming the angle the simulator still reports; a hinge seen half-open but never at rest fails with reason fold-pose-unsettled, naming the observed and previous angles; a first hinge-angle read that returns no sample (for example a simulator runtime without CoreMotion hinge support) fails with reason fold-pose-dispatched-unverified, meaning the pose was sent but cannot be confirmed; hingeReadFailure holds the read's own failure details, and screen holds the lit panel's size when panel power decides one panel, so take a screenshot or snapshot to check. A single-panel simulator fails with UNSUPPORTED_OPERATION. A simulator in a scoped set selected with --ios-simulator-device-set folds the same way: the HID send, the hinge reads, and the panel reads all run through simctl --set.
Expect a fold to take 2-4 seconds, longer for the first fold after a boot while the hinge settles; half-open waits for agreeing hinge reads. Re-snapshot after every fold; refs and coordinates from before it are stale, and the command's message says so.
Timed motion: fold --keyframes '[{"atMs":0,"angle":0},{"atMs":5000,"angle":180}]'. Use 2–64 frames starting at 0ms, increasing integer timestamps up to 60000ms, and angles from 0 to 180. The last timestamp sets motion duration, excluding setup and verification. Equal angles hold; cancellation stops motion. See the fold examples in the command and Node API documentation for trajectories.
Requirements: an iOS simulator session on a foldable device and an Xcode toolchain with the iOS simulator SDK and foldable HID support (verified on Xcode 27.1). Device Hub and host Accessibility permission are not required. The command runs a small helper through simctl spawn for the session UDID; the helper is built once per Fold.m source hash and Xcode toolchain, cached under ~/.agent-device/fold-helper, and rebuilt only when the source or the toolchain changes. The same helper reads the hinge and the panels in either simulator set. Build or dispatch failures are reported without a UI fallback. The app under test reads the resulting pose as UIHinge.status.
Android emulators: fold sets the posture through the emulator console (adb emu posture 1|2|3), then reads adb shell cmd device_state print-state until the guest commits CLOSED, HALF_OPENED, or OPENED, and reports the angle read from the hinge sensor. It can differ from the AVD profile's per-posture angles: 0, 90 and 180 degrees on the Pixel folds, 15, 90 and 165 on the generic 7.6in Foldable. Folding to the cover display can raise Android's "Swipe up to continue" lock screen; fold dismisses it so the app stays reachable. An emulator profile without those device states (a phone) fails with UNSUPPORTED_OPERATION and reason single-panel-device, and a physical device is refused. Keyframes are not supported on Android, and the response carries no panel geometry: re-snapshot after every fold.
If a task asserts behavior for more than one pose, fold to each pose and re-snapshot, and report which poses the run covered.`},k={summary:`React Native app automation hazards and routing`,body:`agent-device help react-native
Use this when the target app is React Native, Expo, or a React Native dev client.
This topic covers React Native-specific automation hazards and routes deeper
questions to the owning help topic.
Choose the next help topic:
Routine QA/dogfood/manual-test flow (open, snapshot -i, press/fill --settle, verify, close): help manual-qa; it has the concrete command shapes, so you should not need generic navigation help for a normal pass.
Deep exploration of navigation/selector/ref edge cases, or a serial-command question manual-qa does not answer: help workflow (full reference, larger read).
Logs, network, diagnostics, traces, permission dialogs, or runtime failures: help debugging.
Component tree, props/state/hooks, slow renders, rerenders, render causes, or dropped frames in React: help react-devtools.
JS heap growth, heap snapshots, allocation hotspots, or retained-object leaks: help cdp.
A wrong or stale value that may come from app state or storage (AsyncStorage, MMKV, a feature flag): see Stale state below.
Remote/cloud config, leases, and local service tunnels: help remote.
React Native dev loop:
Do not run doctor as routine QA/dogfood prep. Use doctor only when the user asks for setup diagnostics or a command failure points to an unhealthy device, runner, dev-server, or remote environment.
For "start from screen X" flows, prefer open --relaunch before the first snapshot so the app does not reuse a prior in-progress navigation state.
JS-only change with Metro or Re.Pack connected:
agent-device metro reload
agent-device wait text "Home"
Do not use agent-device reload. Use open --relaunch for native startup reset.
Android RN/Expo/Re.Pack dev server: direct Android localhost URL opens with a port auto-configure host reachability. For app/package launches, run metro prepare when the app cannot reach the local dev server.
Verify Metro/Re.Pack from the same host context that owns the dev server. If a sandboxed shell cannot curl localhost:8081/status but an unrestricted host shell can, the dev server is running and the sandbox probe is not authoritative.
adb reverse only affects Android device-to-host traffic. It does not prove host-to-dev-server reachability, and it does not fix a redbox caused by a stale or wrong bundle/app state.
Multiple local worktrees can reuse one native iOS simulator build by running each worktree's dev server on a different port and opening the same installed app on different simulators with explicit runtime hints:
agent-device open "React Navigation Example" --platform ios --device "iPhone 17" --session rn-a --metro-host 127.0.0.1 --metro-port 8081 --relaunch
agent-device open "React Navigation Example" --platform ios --device "iPhone 17 Pro" --session rn-b --metro-host 127.0.0.1 --metro-port 8082 --relaunch
iOS simulator opens write bare React Native's per-simulator debug server settings before launch. Detected Expo development clients receive their server URL through a launch link instead. Use separate sessions/devices, close both sessions when done, and rebuild only for native changes or dependency changes that affect the binary. One simulator cannot run two copies of the same bundle id.
Expo Go/dev clients are host shells. Use provided project URLs, verify with snapshot -i after opening, and ask instead of inventing app ids or URLs. Help workflow owns the full Expo URL command shapes.
Overlays and busy RN UIs:
If snapshot reports a React Native warning/error overlay, handle it before interacting with the app: run agent-device react-native dismiss-overlay. The command sends the safe LogBox/RedBox action and verifies the overlay is gone with a fresh post-dismiss snapshot -i.
If the command reports the overlay is still visible, use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing warning/error text manually.
Do not manually press warning/error text bodies, collapsed banner bodies, full-screen warning parents, or broad LogBox/RedBox refs. The dismiss-overlay command owns the narrow LogBox/RedBox targeting policy.
Report the overlay in the final summary. Use screenshot --overlay-refs before dismissing only if visual evidence is required.
Minimal overlay continuation:
agent-device snapshot -i
agent-device react-native dismiss-overlay
agent-device snapshot -i
agent-device press 'id="submit-order"'
Do not use a plain snapshot after dismiss-overlay when the next step needs current refs; use snapshot -i.
When overlay evidence is required before continuing, keep the sequence explicit:
agent-device snapshot -i
agent-device screenshot --overlay-refs
agent-device react-native dismiss-overlay
agent-device snapshot -i
agent-device press 'id="submit-order"'
If snapshot times out because the UI never becomes idle, Android accessibility may be blocked by busy or continuously changing app UI. After that timeout, use screenshot as visual truth instead of repeatedly retrying snapshots.
If iOS snapshot reports AX unavailable or returns only a sparse root, the current screen's accessibility state is invalid. Use plain screenshot as visual truth, coordinate navigation to leave the bad screen, then take a fresh snapshot -i before returning to selector/@ref commands.
agent-device screenshot
agent-device press 124 817
agent-device snapshot -i
Android runtime permission dialogs and native alerts are handled by alert wait/accept/dismiss. If alert reports no alert but a sheet is visible, alert did not recognize it: use snapshot -i and press @ref on the visible button.
React DevTools routing:
Keep the agent-device react-devtools prefix on every React DevTools command.
Use help react-devtools for component trees, props/state/hooks, render profiles, slow renders, rerenders, and their causes.
If React DevTools cannot attach, report the error and continue with logs, network, perf frames, perf memory, screenshot, and trace evidence instead of blocking the whole flow.
CDP memory routing:
Keep the agent-device cdp prefix on every CDP command.
Use help cdp for JS heap usage samples, heap snapshots, snapshot diffs, leak-triplet analysis, allocation hotspots, and retained-object paths.
Use perf memory sample or perf memory snapshot for native/process memory; use cdp only for JavaScript heap evidence.
Stale state:
If a wrong or stale value may come from app state or storage, read the value. Do not navigate the UI to infer it. Read JS values with help cdp (runtime eval).
Fallback for debuggable builds on a local simulator or emulator, not a remote lease: read the AsyncStorage 1.x/2.x files.
iOS: Library/Application Support/<bundle-id>/RCTAsyncLocalStorage_V1 in xcrun simctl get_app_container <udid> <bundle-id> data
Android: databases/RKStorage through adb shell run-as <package>
Missing files can mean a newer store (AsyncStorage 3.x). Do not conclude that the value is absent.
Slow-flow investigation:
Keep one session, open the app first, and snapshot -i before interacting.
Start React Native slow-flow plans with this ordered scaffold:
agent-device open "Agent Device Tester" --platform android
agent-device snapshot -i
If the task says to open the app, include the open command even when it also describes the current screen.
Use help react-devtools for the narrow React profile window: react-devtools profile start right before the interaction and react-devtools profile stop after it.
Use help debugging for logs clear --restart, logs mark, network dump --include headers, perf frames, perf memory, native profiles, traces, and runtime failure evidence.
For 15-20s async work, use wait with the exact expected text or selector instead of repeated snapshots.
Report React render offenders separately from network/backend waits and device frame/CPU/memory findings.`};var A=e({buildCommandSynopsis:()=>q,buildCommandUsageText:()=>K,buildUsageText:()=>z,helpTopicIds:()=>Y,resolveHelpTargetUsageText:()=>J});const j=[`Default config files: ~/.agent-device/config.json (or <AGENT_DEVICE_HOME>/config.json), ./agent-device.json (project-safe defaults only).`,`Use --config <path> or AGENT_DEVICE_CONFIG for explicit connection/provider defaults; project config cannot select endpoints or credentials.`,`Pin device selection with { "devicePin": { "platform": "ios", "device": "iPad Pro" } } in config. Conflicts name the config file. Edit or remove the pin there to target another device.`],M=[{label:`AGENT_DEVICE_SESSION`,description:`Explicit session name`},{label:`AGENT_DEVICE_PLATFORM`,description:`Default platform binding`},{label:`AGENT_DEVICE_SCREENSHOT_SCALE`,description:`Default screenshot scale factor`},{label:`AGENT_DEVICE_SESSION_LOCK`,description:`Bound-session conflict mode`},{label:`AGENT_DEVICE_DAEMON_BASE_URL`,description:`Connect to remote daemon`},{label:`AGENT_DEVICE_DAEMON_AUTH_TOKEN`,description:`Remote daemon service/API token`},{label:`AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS`,description:`Local daemon startup ceiling (default 120000)`},{label:`AGENT_DEVICE_CLOUD_BASE_URL`,description:`Bridge/control-plane API origin for cloud auth and /api-keys`}],N=[`agent-device open Settings --platform ios`,`agent-device open https://example.com --platform web`,`agent-device snapshot -i`,`agent-device fill @e3 "test@example.com"`,`agent-device replay ./session.ad`,`agent-device wait absent 'label="Loading..."' 3000`,`agent-device test ./suite --platform android`],P={commands:{summary:`Full command catalog, global flags, configuration, and environment`,body:`agent-device help commands`},...w,maestro:_(`maestro`).help,workflow:{summary:`Normal agent-device bootstrap, exploration, and validation loop`,body:`agent-device help workflow
Command shapes, refs, selectors, waits, recovery, and platform limits for open -> snapshot -i -> settle -> verify -> close loop.
Command shape:
Command lines only -- no prose, numbering, fences, pipes, or grep/head/tail/jq; raw output carries refs/hints for the next step. Order: subcommand, positionals, flags: agent-device open com.example.app --session checkout --platform android --relaunch
Chain confident consecutive steps with &&: press 'label="Search"' --settle && fill 'label="Search"' "query" --settle. Fall back to one command at a time when a step is uncertain (ambiguous match, network-backed result, unseen screen).
Refs look like @e12; use the exact ref from the latest snapshot -i, never a placeholder (@ref, @eN, @Label_Name). Pin with ~s<n> (press @e12~s4); every platform rejects a stale pinned ref -- refresh with snapshot -i or use a selector.
close = agent-device close. App back is back; system back is back --system. Single taps are press/click; gesture tap touches 2 to 5 points at once. type never takes --settle: run type, then diff snapshot to verify. Known flow: batch --steps-file ./steps.json (help batch).
Gestures: scroll/swipe for lists/flicks; gesture pan|fling|pinch|rotate|transform|tap|drag for multi-touch. Shapes and platform quirks: help gestures.
Bootstrap:
open --foreground -> snapshot. Selection: explicit --device/--udid/--serial, then session, booted/bootable local, or provider; --platform/--target only filter. Ambiguous/empty fails with bounded retry selectors; no provider fallback.
Install arguments are app/package id then artifact path: agent-device install com.example.app ./dist/app.apk --platform android, then open <id> --relaunch for fresh state. Use reinstall only when explicitly requested.
Unknown app id: devices, then apps, then open <discovered-app-id>. Never open artifact paths or invent package ids; ask if lookup misses the target.
Apple CI: prepare ios-runner after boot/install, before replay/test (help prepare). Remote/cloud: connect -> open -> commands -> close -> disconnect (help remote). Reusable scripts, secret-safe fills, replay repair: help scripting.
Snapshots and refs:
snapshot reads visible state; snapshot -i gets current interactive refs only -- fast path before interaction. Default text is token-efficient; --raw/--json for full provider tree.
Legend: @e12 [button] label="Add to cart" enabled hittable -> press @e12. [off-screen below] -> scroll down --until (a hint, not a ref).
Refs stay valid until you press/click/fill/type/scroll/back/wait-for-async-UI, change app state, or find/diff print refs; open/--relaunch clears the stored snapshot outright.
Prefer --settle and its diff when it shows next target; refresh with snapshot -i only when you did not settle, it reported not settled, or output lacks what you need. A known selector/label after a mutation is often enough, since interaction commands refresh state internally.
Truncated preview: snapshot -s @e12 (the current concrete ref), not get text. Missing target: scroll <dir> --until <selector>. TV/D-pad focus: help tv.
Selectors:
id="field-email", label="Allow", role=button label="Search" -- not bare role keys (button="Search"); no CSS selectors/--selector/--text/raw x-y when refs/selectors exist.
Mutating selector ambiguity: press/click/fill/longpress collapse duplicate accessibility wrappers only when every match is one ancestor-descendant chain resolving to the same actionable node. Matches in distinct subtrees fail with AMBIGUOUS_MATCH and a bounded candidate list; geometry never chooses a winner. Retry one printed candidate ref (pinned to refsGeneration) or narrow the selector with role/id/longer text. Uniqueness-based reads (is except exists/absent, get attrs) share that failure shape.
hittable: false on a resolved element does not block dispatch (iOS AX flags are unreliable on deep RN trees); press/fill/click return targetHittable: false plus a hint -- verify or re-target, not a failure.
Text entry:
fill replaces; type appends to an already-focused field: fill 'id="field-email"' "qa@example.com"; type "Handle with care" --delay-ms 80
fill <target> "" clears the field (replace with nothing); the empty argument must be present -- fill <target> alone is a missing argument.
For dropped iOS text, retry with --delay-ms before clipboard paste (also Limrun iOS).
Keyboard covers the target (tap_keyboard_occludes_target): on iOS, press a visible Hide Keyboard key or app dismissal control. In apps with drag dismissal, use gesture pan. Android: keyboard dismiss. Use keyboard enter to send Return.
iOS paste-prompt limits and Android IME/handwriting capture quirks: help debugging.
Session ordering:
Stateful commands (open/press/fill/type/scroll/back/alert/replay/batch/close) run serially within one session. Parallelize only read-only commands, or separate sessions/devices.
Read-only and waits:
${C}
snapshot/get/is answer read-only questions; snapshot -i is for refs. --settle confirms local UI quieted; delayed results use wait text "Expected result" or wait <selector> instead of polling; strict disappearance uses wait absent <selector>.
wait stable [quietMs] [timeoutMs] (defaults 500/10000) is the fallback for open/relaunch/navigation, or an intentionally-unsettled mutation -- not after a --settle whose diff already shows the change. Ambiguous find: add --first or --last.
Navigation:
Pick a coordinate gesture point near the target's center, away from edges/tab bars/nav bars/the home indicator (they trigger system navigation instead); macOS context menus are secondary clicks (help macos). Action sheets/menus/camera screens are normal UI: snapshot -i, press by label/ref, handle permission sheets via UI/alert. If back is ambiguous, prefer a nav/back ref, tab-bar ref, or deep link over repeating it.
Validation and evidence:
Nearby mutation diff: diff snapshot -i; with no prior snapshot it initializes the baseline (zero changes) instead of failing.
Named expectations need the exact text/selector via wait/is/get -- a bare screenshot/snapshot is not verification. Before declaring a task done, confirm the requested end state is actually visible on the current screen, scrolling it into view if needed; get text alone, or stopping one screen early, is not enough.
When an action only reveals or reaches a target, verify the exact target named, not just the action. Prefer testIDs/ids/selectors over visible text. Icon/tappable proof: screenshot --overlay-refs; if snapshot is sparse/AX-unavailable, use plain screenshot and coordinates, then retry snapshot -i on another screen.
iOS merged: child ref => press it; else press parent @ref --settle. Names are not selectors.
Perf/memory/log/network/trace/crash: help debugging. Recording, save-script, batch, replay repair: help scripting.
React Native: help react-native for Metro/Re.Pack reload, DevTools, RN overlays. JS-only change: metro reload, wait text "Home"; open --relaunch for native reset.
Lifecycle facts (trust these instead of probing): open without --relaunch is idempotent-foreground except native macOS app opens (background); --relaunch restarts it. close keeps a healthy iOS runner warm by default; runners/daemons self-idle after 5 minutes; stale leases self-reclaim. open device claims reclaim other worktrees' warm runners; "already owned by another agent-device daemon" = owner outside claim arbitration. Env vars: help physical-device.
Escalate:
help manual-qa scripted manual QA
help dogfood exploratory QA report
help validate engineering self-validation
help debugging logs, network, alerts, traces, text-entry
help scripting recording, save-script, batch, replay repair
help gestures multi-touch gesture shapes/quirks
help tv Android TV, tvOS, Vega VVD remote
help react-devtools RN components, props/state/hooks, render profiling
help react-native RN hazards, Metro/Re.Pack, routing
help remote remote/cloud config, lease, tunnels
help macos desktop, frontmost-app, menu bar
help web minimal browser loop
help ios-system-ui SpringBoard, widget, system-UI`},scripting:{summary:`Reusable scripts, secret-safe fills, batch JSON, and replay repair`,body:`agent-device help scripting
Use this for reusable .ad script authoring (save-script), scripted destination guards, secret-safe fills, batch multi-step JSON, replay divergence/repair, and evidence recording.
Script paths are the caller's:
replay <path> and test <path-or-glob> resolve and read on the machine running the command, then send the script content (Maestro runFlow includes too) with the request. The same flows therefore run against a local daemon and against a remote one (AGENT_DEVICE_DAEMON_BASE_URL) with no copy step, and a missing script fails immediately, naming the path you typed. Against a remote daemon, outside a macOS app lease, open --save-script=<path> names a caller file: after each recorded action the client refreshes it with the recording so far, and close writes the final script there, as a local close does. While the client holds the recording's active record, a version it already saved, or an older one, is not written again: the result names the stored destination with a warning, and the file is not checked. If that file is missing while the session is still recording, the next recorded action writes it again; after close, reuse your original open command with --save-script=<path> --force to record again to the original destination. An existing file is refused unless you pass --force. A session that another process closes keeps the version from the last recorded action. Remote session save-script, replay/close --save-script, and --save-script in batch steps are refused. A daemon without the script-artifacts capability is refused before the open.
test --json marks a failed test with infrastructure: true only when the owning runtime classified a device, runner, boot, or transport failure. It remains a failed test; consumers may use the tag to distinguish "the oracle did not run" from a behavioral replay divergence without weakening either gate.
Script line grammar:
A .ad line is <command> [positional...] [flag...]. Whitespace splits tokens; a token quoted with " or ' is one argument, and single quotes keep a double quote literal, exactly as at the shell (press 'id="far"' is one selector). Values in double quotes are JSON strings (escape \\\\, \\", \\t, \\n). Values in single quotes are literal, as at the shell: a backslash keeps its own character and the only escape is \\' for an apostrophe. A script carries only the flags declared for that command and marked recorded, so the script form of a step matches the CLI form: scroll down --until 'id="x"', wait 'label="Sign in"' --raw. CLI-only spellings and per-request options are not part of a step: --settle, --verify, scroll --pixels/--duration-ms, and the device-selection flags (--platform, --serial, --device) are the common ones a script does not carry.
Reaching an off-screen target is viewport-independent in a script the same way it is at the CLI: write scroll down --until <selector>, not a fixed scroll amount that passes on one screen size and fails on another.
A recorded element step writes its target as a selector. An id unique on the recorded screen is written alone (press 'id="submit"'); otherwise it writes alternatives such as role+label and label, joined with || (press 'role="button" label="Submit" || label="Submit"').
press/click/longpress resolve their target once. Before interacting with a loading screen, add an explicit landmark wait: wait 'label="Continue"' 5000, then press 'label="Continue"'.
Reusable open-to-destination scripts:
Arm recording on the first open, perform the full journey, verify the destination with a selector-targeted wait, then publish without closing:
agent-device open com.example.app --relaunch --save-script=screen-x.ad
agent-device press 'id="continue"' --settle
agent-device wait 'role="heading" label="Screen X"'
agent-device session save-script
session save-script [path] [--force] publishes the sole recorded open through the destination guard, omits close, and leaves the session active. The guard is a selector wait on a labeled/id-bearing landmark: its identity is captured while armed and re-verified after the wait resolves at replay time, so a reshuffled screen with the same label elsewhere fails closed instead of false-passing. A duration wait, wait stable, wait absent, wait @ref, or a selector wait on an unlabeled element is not a destination guard. A second successful open aborts publication; start a fresh session to author again.
Unparameterized fill/type inputs are literal .ad script content. For a sensitive fill, arm recording first, keep the live value in an env var, and name its replay placeholder explicitly:
export AD_VAR_PASSWORD='<secret>'
agent-device fill 'id="password"' "$AD_VAR_PASSWORD" --record-as PASSWORD
The live app receives the value; recording state and the published script contain only \${PASSWORD}. Reuse the same name for repeated values; --record-as is fill-only, requires an armed recording, and is mutually exclusive with --no-record. Replay with AD_VAR_PASSWORD still set, or pass --env PASSWORD=<value>. Do not record passwords/tokens without --record-as; their literal text is written to the .ad target.
To keep the value out of the CLI's argv as well, pipe it in with --text-stdin instead of a text argument:
printf %s "$AD_VAR_PASSWORD" | agent-device fill 'id="password"' --text-stdin --record-as PASSWORD
--text-stdin reads at most 64 KiB, removes exactly one trailing newline, and refuses a terminal, empty input, invalid UTF-8, or an extra text argument. While recording is armed, --record-as publishes \${VAR} and --no-record leaves the step out; passing neither is an error. Output shows the value as \${VAR} with --record-as and as [REDACTED] otherwise, including in error messages and in the requested, before and after read-back of an unconfirmed fill, which can hold a reformatted form of the value. With --settle, the diff line text and tail labels are replaced whole; refs and counts stay. Without an armed recording the step is not recorded. It is not available inside batch steps.
The privacy controls for typed input (--text-stdin and --record-as) keep the literal out of agent-device's own responses, diagnostics, and recorded scripts. They do not rewrite what the platform records: on iOS, XCTest writes its own diagnostic logs and its .xcresult bundle, and typed text can appear in both, on a simulator or a physical device. Treat those as sensitive, and use test-only credentials when they may be kept or shared.
Replay divergence and repair:
A failing replay/test step returns REPLAY_DIVERGENCE with a bounded report (screen digest, ranked selector suggestions, resume). Fix app state, then resume with replay --from <n> --plan-digest <sha256> (both from the report's resume field) to continue without re-running earlier steps; resume never re-executes skipped steps, so app state there is the caller's responsibility. --from is replay-only; test rejects it. The digest binds the script, includes, effective --platform/--target, and per-action runtime/identity; native .ad interpolation is late-bound so changing only its values keeps the digest, while Maestro environment substitution can change it.
A resource step that cannot run in bounded batch/replay returns details.reason bounded_composite_resource_unsupported, details.shape, and dispatched: no for that step. Affected commands include perf, audio, record, trace, some logs operations, close when it would dispose an owned capture or release a provider lease, and acquisition that would recover another session's durable resources. Existing-session open preserves its owned resource handles. An Android test IME alone is restored by ordinary close, including a bounded step; restoration may settle after the remaining composite time. If restore fails, close retires the session but retains its device claim: inspect the device and claim before recovery, rather than retrying close on the retired session. details.standaloneCommandName names the public command when known; it is not a complete command. Run the original refused step separately with its original arguments and options, the same --session value, and the same private CLI context. For replay, inspect the failed source line. After completing the step directly, use resume.alternateFrom with planDigest if offered and steps remain; resume.from retries the same bounded step and refuses it again. An authored .ad command without a resource classification fails closed with shape <command>:unclassified. Inspect completed steps before retrying the composite; earlier steps may have changed the app. A nested test with an attempt timeout or --record-video is refused before its first attempt; direct test keeps its own timeout behavior.
Native .ad session takeover: replay <file>.ad --keep-session suppresses exactly an authored terminal close and returns the surviving session for continued commands. --update/-u is a no-op (ADR 0012); every divergence already carries the same ranked suggestions.
Agent-supervised repair: arm replay <file>.ad --save-script[=<out>] before step 1 (armed once; --from continuations do not need it again). Every divergence carries a repairHint: record-and-heal means press the correct control via a blessed @ref from the divergence's screen.refs, recorded, then replay --from <n+1> --plan-digest <sha256>; state-repair means the script is correct but app state is not -- fix state with --no-record actions, then replay --from <n> to re-run the unchanged step; caution means a blind re-press may repeat the mistake; manual means no safe automated repair could be proven. Read-only inspection you run to locate the repair target (snapshot -i, get attrs, find, is) is excluded from the healed script by default; pass --record on a read step you want kept. End the repair with close --save-script[=<out>] (default <stem>.healed.ad); review its diff before promoting it over the original. Running close --save-script before a required resume aborts the repair with no script written.
Batch:
agent-device batch --steps '[{"command":"open","input":{"app":"settings"}},{"command":"wait","input":{"kind":"duration","durationMs":100}}]'
agent-device batch --steps-file ./steps.json --json
Step keys are command, input, and optional runtime -- that is the whole accepted shape. input holds the command's structured fields, not its terminal spelling: a CLI positional becomes a named field (target, text, direction) and a flag becomes a camelCase key (--settle -> "settle":true). Accepted commands, that mapping, and runnable press/fill/snapshot steps: help batch.
Maestro full-suite validation on connected devices uses one test command with a comma-separated --device list and --shard-all (--shard-split only to split suite entries across devices):
agent-device test ./e2e/maestro --maestro --device udid1,emulator-5554 --shard-all 2
Recording:
record start/stop. Default scope is app (needs an active open session); use --scope device/system for whole-screen capture spanning multiple apps/home/settings. --quality medium|high on Android and Apple targets. stop burns touch overlays into the video by default; --hide-touches skips that for the fastest raw recording, and is recommended for gesture-heavy iOS simulator proof videos since overlay timing depends on a stable runner session. Android adb screenrecord has a 180s limit, so long Android recordings return as multiple MP4 chunks while the daemon stays alive; after a daemon restart, record stop recovers only manifest-owned chunks. record stop is safe to repeat: if its request window ended while the daemon was still exporting, running it again in that session returns the completed recording instead of starting a second one. If a leased remote session ends while a recording runs (lease expiry, release, or close), the daemon finishes it and keeps the video and telemetry downloadable by the tenant for 15 minutes; GET /artifacts lists them with the sessionName.
record contact-sheet <video.mp4> [--out <sheet.png>] reads an exported MP4 back and writes one PNG holding the frames where the screen visibly changed, each labeled with its elapsed time. It is how you read a recording you cannot play, and it needs no session or device; the frames come out of that file, so the sheet cannot describe a screen the video does not contain. The sample grid is bounded and spread over the whole clip, so it reports coverage, not a review: a flash that opens and closes between two sample times is not in it. Needs a macOS host and an MP4 (a WebM recording is refused).
Tracing: trace start ./trace.log, trace stop ./trace.log (path is positional, not --path).`},gestures:h,tv:{summary:`Android TV (incl. Fire TV on Fire OS), tvOS, and Vega VVD focus-first remote navigation`,body:`agent-device help tv
Use this when the target is Android TV (including Fire TV devices on Fire OS over ADB), Apple TV/tvOS, or an Amazon Vega OS TV app running in the Vega Virtual Device (VVD). TV surfaces are focus-first: move focus with remote/D-pad buttons, then activate the focused control.
Core loop:
agent-device open Settings --platform android --target tv --session tv
agent-device snapshot -i --platform android --target tv --session tv
agent-device tv-remote press down --platform android --target tv --session tv
agent-device is focused 'label="Profiles"' --platform android --target tv --session tv
agent-device tv-remote press select --platform android --target tv --session tv
agent-device screenshot ./tv-focus.png --overlay-refs --platform android --target tv --session tv
Vega OS:
Vega OS is driven through the SDK-matched Vega CLI and VDA, not ADB.
Initial support is VVD-only. Physical devices that run Vega OS remain unsupported until their discovery, lifecycle, and remote controls have durable hardware evidence.
Use --platform vega --target tv for the running Vega Virtual Device.
vega virtual-device start
agent-device devices --platform vega --target tv
agent-device open <component-id> --platform vega --target tv --session vega-tv
agent-device tv-remote press down --platform vega --target tv --session vega-tv
agent-device tv-remote press select --platform vega --target tv --session vega-tv
agent-device close <component-id> --session vega-tv
vega virtual-device stop
Use a component ID from the app package or Vega SDK tooling; agent-device app inventory is not yet supported.
Use --serial VirtualDevice for explicit VVD selection.
The VVD is never booted implicitly; start it with vega virtual-device start.
Snapshot, screenshot, selectors, install, touch/text/gesture, logs, and performance commands remain unsupported until their Vega backends are implemented.
Buttons:
Examples: tv-remote longpress select; tv-remote press select --duration-ms 500. Syntax: tv-remote [press|longpress] <button> [--duration-ms <ms>]
Android TV, tvOS, and Vega OS: up, down, left, right, select, menu, home, back.
Android TV also accepts volume-up, volume-down, mute, power, sleep, wake, media-play-pause, media-play, media-pause, media-stop, media-next, media-previous, media-rewind, media-fast-forward, channel-up, channel-down, last-channel, guide, info, captions, tv-input, color-red, color-green, color-yellow, and color-blue.
android-keycode:<n> sends a raw Android TV keycode from 1 to 2147483647. tvOS and Vega OS refuse these additional buttons. Phones and WebDriver sessions refuse tv-remote. Power and sleep can turn the screen off; success confirms dispatch without waiting for an app or screen change.
The LG webOS and Samsung Tizen plugins accept up, down, left, right, select, back, media-play, media-pause, media-stop, media-rewind, and media-fast-forward; Tizen also accepts media-play-pause, media-next, and media-previous. They refuse every other button.
ok, center, and enter are input aliases for select; command output still reports button: "select".
longpress is CLI sugar for --duration-ms 500. --duration-ms overrides that preset.
--duration-ms holds a tvOS or Vega OS remote button for that exact duration. On Android TV, any positive duration maps to the ADB longpress form because Android input keyevent has no exact hold duration.
Vega OS uses the exact hold duration through inputd-cli in the VVD.
Android TV:
Android TV uses ADB keyevents behind agent-device tv-remote. Keep command plans on agent-device; do not switch to raw adb keyevent.
Use --target tv when a host has both phone/tablet and TV emulators/devices.
Fire TV devices and emulators running Fire OS (Android-based) connect as Android TV devices over ADB: enable ADB debugging, run adb connect <ip>:5555, and use --platform android --target tv. Discovery reads the amazon.hardware.fire_tv system feature, so a Fire TV that declares no leanback feature is still a tv target.
tvOS:
tvOS is driven by the Siri Remote focus engine, not coordinate taps.
back maps to the Menu remote button; home maps to the Home remote button.
Use --platform ios --target tv for Apple TV simulators and devices.
Focus and visual truth:
On Android TV and tvOS, if snapshot -i exposes a focused node, verify it with is focused <selector>.
On tvOS, snapshot -i can report focus on the outer tile when duplicate accessibility wrappers collapse.
Use wait focused=true only when repeated snapshots preserve focus metadata for the app.
If the app exposes only a surface view, or focus metadata is transient, use screenshot --overlay-refs, screenshot, or diff snapshot as visual truth and keep moving focus with tv-remote. On Vega OS, use the VVD display as visual truth until capture support lands.
Do not assume press/click @ref works on Android TV, tvOS, or Vega OS until the desired element is focused.`},...T,"react-devtools":{summary:`React Native components, props/state/hooks, and render profiling`,body:`agent-device help react-devtools
Use this for React Native internals the accessibility tree cannot show: the component tree, a component's props, state, hooks, and owners, errors and warnings components logged while rendering, and render performance (slow renders, rerenders and their causes, commits over a 16 ms frame).
Components:
agent-device react-devtools tree [@ref|Name] [--depth 8] [--limit 60]
agent-device react-devtools find <Name> [--exact]
agent-device react-devtools inspect <@ref|Name>
agent-device react-devtools errors
Render profiling:
agent-device react-devtools profile start
agent-device react-devtools profile stop
agent-device react-devtools profile report [Component]
agent-device react-devtools profile commit [N]
Connection:
Every command except profile report and profile commit, which read the saved profile, attaches to the app's JavaScript runtime through its Metro dev server: a development build on React Native 0.74 or newer, with no app, Metro, or Babel changes and no start or connect step. It is verified on Android emulators and iOS simulators, through agent-device proxy, and on remote bridge sessions, where it uses the Metro server next to the agent: the session's binding from metro prepare, or --metro-host/--metro-port. A device-facing Metro URL, such as the bridge's, refuses the debugger connection.
Add --app <bundle-id> when several apps share the dev server, --metro-device <name> when one app runs on several devices connected to it, and --metro-port/--metro-host (or --bundle-url) when the dev server is neither the session's nor localhost:8081.
Component inspection:
Start with find <part of a name> or tree; both print @c refs. Wrapper chains such as providers collapse onto one line, and three or more consecutive siblings with identical subtrees, such as list rows, collapse into one line with a count; run tree @ref to open a branch.
inspect takes an @c ref, or a name only one mounted component has. It prints the owners that rendered it, its props, state, hooks (custom hooks list the hooks they call), and what it logged while rendering. Deep values print as short previews.
errors lists the mounted components that logged console errors or warnings while rendering, with the messages. When the app's React DevTools backend does not attribute every log to a component, as on React Native 0.74 and 0.76, errors says its list can be incomplete; check logs as well.
Refs are DevTools element ids: they change when a component remounts or the app reloads, so find again after either.
With a React DevTools window connected to the app, tree, find, errors, and inspect by name fail with tree-unavailable; close it and reload the app.
Profiling loop:
1. Run profile start immediately before the interaction; keep the window narrow.
2. Drive the interaction with normal agent-device commands. When correlating with logs, run logs clear --restart before the first logs mark.
3. Run profile stop. It saves the recording, then prints the commit count, render time, commits over the 16 ms frame budget, and ranked findings, each naming a component, its evidence, and a fix. If changed-prop inspection is interrupted after collection, profile report and profile commit can still read the saved recording.
4. Drill into one finding with profile report <Component> or profile commit <N>. Without an argument, report lists components by self time with why they rendered, and commit lists commits in order (the slowest when capped).
5. After a fix, repeat the same start, interaction, and stop, and compare the findings.
Findings:
slow-render: the component's own render is expensive. memo-defeated: a memoized component often re-renders because props change identity. parent-cascade: the component often re-renders with unchanged props, state, and context when its owner renders. context-cascade: most of the component's renders come from context changes. effect-chain: the component triggers a follow-up commit right after rendering, likely state set in an effect. render-storm: one component commits many times per second. eager-mount: hundreds of instances mount in one commit. slow-commit: a commit of three frames or more that other findings leave mostly unexplained.
Timings come from development builds and run slower than release builds; compare runs instead of reading absolute numbers.
Rules:
Every command is an agent-device subcommand: agent-device react-devtools ...
Do not repeatedly raise table limits such as --limit 50 or --limit 200; drill into one component with profile report instead.
For network evidence, use agent-device network dump --include headers; headers is not a positional argument.
Example:
agent-device logs clear --restart
agent-device logs mark "before catalog search"
agent-device react-devtools profile start
agent-device fill 'id="catalog-search"' "tart" --delay-ms 80
agent-device logs mark "after catalog search"
agent-device react-devtools profile stop
agent-device react-devtools profile report CatalogScreen
agent-device network dump --include headers
Device busy and ownership:
DEVICE_IN_USE has two flavors. "already in use by session X" is this daemon's session table: reuse it with --session X, or run close --session X first. "owned by session X in workspace Y" is the host-global device claim another session — from this daemon or another worktree's daemon — or an in-flight command holds; there may be no session to close, and it is never retriable, so run the error's exact recovery command instead of retrying.
Inspect ownership without any daemon: agent-device device status (add --stale to list the claims it hides: dead, PID-reused, missing-state-directory, and daemon-replaced owners, some of which may still run; agent-device device release --stale settles and releases only owners proven unable to release). Its devices list inspects whether a new session can take each claimed device: acquirable true means no claim blocks it, false names the reason in blockedBy (live-owner, owner-pid-reused, owner-process-still-running, owner-liveness-unknown, claim-record-inconsistent, or a resource such as screen-recording-cleanup-pending that still waits for disposal). owner names the claim's owner when its record decodes: the holder that blocks the device, or, when acquirable, the reclaimable dead owner open would settle. It is an inspection, not a promise: status cannot see a reboot and runs no recovery, so open may decide differently, and a daemon's own abandoned claim, which status reports as blocked by that live owner, open through that same daemon may still take. A dead or replaced owner that retains nothing does not block by itself. hiddenStaleClaims counts the claim records this view hides and is not an availability signal, so read acquirable: a hidden owner whose PID was reused or whose state directory is gone, and pending resource cleanup, each still block the device. devices marks rows that are claimed, so pick an unclaimed device instead of contending.
A live foreign owner is released by closing its session from its own workspace or stopping its daemon: agent-device daemon stop --state-dir <owner state dir> (the error names the state dir). The device itself can settle a claim: when it rebooted after that claim was taken, its app, runner, and accessibility session were destroyed, so open reconciles the owner's resources, takes the claim, and reports the release in warnings. Never recover by hunting PIDs with ps/kill. boot/install/shutdown take the same claims as open and refuse foreign-claimed devices identically; they do not ask the device about its boot.
Use snapshot, screenshot, logs, network, perf frames, and perf memory for device/app runtime evidence. Use react-devtools when component internals or React rendering performance matter.`},cdp:{summary:`React Native CDP targets, JS heap snapshots, and leak triage`,body:`agent-device help cdp
Use this when a React Native or Expo app exposes a CDP target through Metro and
the task needs JavaScript heap growth checks, heap snapshot diffs, allocation
hotspots, retained-object leak evidence, or a small runtime eval to confirm JS
state. Do not use this as the default React Native profiler.
Setup:
Start Metro and open the app first. For Android devices/emulators, make sure Metro is reachable from the app, typically with adb reverse tcp:8081 tcp:8081.
In remote bridge sessions, omit --url for target list/select after connect; agent-device derives the Metro CDP URL from the prepared remote runtime.
agent-device cdp target list --url http://127.0.0.1:8081
agent-device cdp target select <target-id>
Quick JS heap signal:
agent-device cdp memory usage sample --label baseline --gc
# perform the suspected leaking action with agent-device commands
agent-device cdp memory usage sample --label after-action --gc
agent-device cdp memory usage diff --base jm_1 --compare jm_2
agent-device cdp memory usage leak-signal --since jm_1
Retained-object proof:
agent-device cdp memory snapshot capture --name baseline --gc
# perform the suspected leaking action
agent-device cdp memory snapshot capture --name after-action --gc
# perform cleanup/navigation that should release the objects
agent-device cdp memory snapshot capture --name cleanup --gc
agent-device cdp memory snapshot diff --base ms_1 --compare ms_2 --limit 10
agent-device cdp memory snapshot leak-triplet --baseline ms_1 --action ms_2 --cleanup ms_3 --limit 10
agent-device cdp memory snapshot retainers --snapshot ms_3 --id <node-id> --depth 8 --limit 10
Allocation pressure:
Use allocation sampling to find where allocations were created, not to prove a leak:
agent-device cdp memory allocation start --name suspected-flow --interval 32768 --stack-depth 32
# perform the flow once
agent-device cdp memory allocation stop
agent-device cdp memory allocation hotspots --limit 10
agent-device cdp memory allocation source-maps
Recommended subset:
cdp dynamically runs a pinned CDP helper through npm; the first run may download the pinned package, and later runs can reuse the npm cache.
Every argument after cdp is passed to the CDP helper. Put agent-device global flags before cdp when you need the outer CLI to consume them.
Use cdp memory usage, memory snapshot, memory allocation, and targeted runtime eval.
Avoid cdp profile cpu, trace, network, and console by default because agent-device already has perf cpu, trace, network, logs, and react-devtools guidance for those areas.
Runtime eval:
After cdp target select, read a JS value: agent-device cdp runtime eval --expr '<expression>' --await
--expr reaches only globals the app exposes. Module imports, such as AsyncStorage, are not globals. If it cannot reach the value, report that. Do not guess.
Output contract:
Until cdp has a compact leak report command, synthesize one from memory usage diff, snapshot diff, leak-triplet, and retainers. Report heap deltas, top retained classes/shapes, leak-triplet rows that stayed high after cleanup, and the shortest useful retaining paths. Do not paste raw heap snapshots or large allocation profiles into the response; use exported artifacts only when the user asks for raw data.
Target caveats:
React Native/Hermes implements a subset of browser CDP. If a command reports an unsupported method, keep the target selected and switch to heap usage samples plus heap snapshots. Prefer react-devtools profile for render causes; prefer perf memory sample or perf memory snapshot for native/process memory.`},"react-native":k,"physical-device":{summary:`Connected phone/tablet setup and iOS signing prerequisites`,body:`agent-device help physical-device
Use this when the target is connected hardware instead of a simulator/emulator.
For simulator/emulator flows, use help manual-qa for routine QA or help workflow for the full reference.
Discovery:
agent-device devices --platform ios
agent-device devices --platform android
With multiple devices present, select one: --device <name>, or --udid <udid> (iOS) / --serial <serial> (Android) when names collide.
iOS physical-device prerequisites:
Xcode, xcrun xcdevice, and xcrun xctrace must be available from the selected Xcode.
The device must be paired/trusted, connected, unlocked when needed, and have Developer Mode enabled. A paired device that CoreDevice cannot reach (devicectl tunnelState unavailable: unplugged or off the network) is listed with booted: false, and commands refuse it with details.kind not_ready and details.tunnelState unavailable.
Modern devices visible to devicectl use CoreDevice. Older devices visible only to xctrace use the XCTest backend automatically.
XCTest-backed devices must already have the target app installed and should be opened by bundle ID; app inventory, install/reinstall, logs, performance sampling, recording, deep links, and launch arguments require CoreDevice.
XCTest-backed runner commands travel through macOS usbmuxd; keep the trusted device connected by cable.
The AgentDeviceRunner XCTest host must be signed before commands can run on a physical device.
Start with Automatic Signing and only these env vars:
AGENT_DEVICE_IOS_TEAM_ID=ABCDE12345
AGENT_DEVICE_IOS_BUNDLE_ID=com.yourname.agentdevice.runner
Find team ids and Apple Development signing certificates with:
security find-identity -v -p codesigning
If Xcode cannot choose a profile, set AGENT_DEVICE_IOS_PROVISIONING_PROFILE to the profile name/specifier, not a file path.
AGENT_DEVICE_IOS_SIGNING_IDENTITY is optional; omit it unless xcodebuild asks for a specific identity.
The profile/team must allow AGENT_DEVICE_IOS_BUNDLE_ID and <id>.uitests.
A runner startup failure names its class in error details.reason rather than only in prose: signing_no_development_team, signing_provisioning_profile_missing, bundle_identifier_already_registered, signing_unspecified, devtools_security_developer_mode_disabled (the Mac's DevToolsSecurity setting, which says nothing about the device's Developer Mode toggle), simulator_service_hub_unavailable (an Xcode too old for the host macOS: macOS refuses to load its DTServiceHub, so every runner launch fails; the command stops as soon as the refusal reaches runner.log, and selecting an Xcode that supports this macOS on the daemon host is the fix), simulator_set_destination_not_found (a --ios-simulator-device-set simulator the selected Xcode cannot resolve; names the set), device_developer_mode_disabled (read from an iPhone's own report before the runner builds, and the only device state that stops a run up front), device_developer_disk_image_unavailable (also read from the device, and published on a startup failure that named no cause of its own, since iOS 17+ mounts the developer disk image on demand during build and launch rather than gating the build), or build_failed_unclassified when nothing proved a cause. The two device reasons are never inferred from tool output or from each other. Branch on details.reason and follow hint; the message is for humans.
First-run XCTest setup/build can take longer than normal commands; keep the device connected and use --debug to inspect signing/build diagnostics if setup times out.
Android physical-device prerequisites:
Enable USB debugging and confirm the device appears in agent-device devices --platform android.
Android does not need the iOS runner signing setup. For React Native/Expo Metro reachability, read help react-native.
Runner and daemon lifecycle (applies to simulators too):
open without --relaunch is idempotent-foreground for an already-running app, except native macOS app opens keep it in the background (help macos); neither restarts the process. open --relaunch restarts the app; on iOS simulators this collapses to one simctl launch --terminate-running-process call instead of a separate terminate-then-launch.
If a relaunch leaves an existing session's device effects unconfirmed, close can release its claim; idle shutdown retries cleanup and leaves an unconfirmed claim stale, while embedded runtimes and AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0 require close because they do not shut down for idleness.
No runner read launches a session app that is not running: snapshot, wait, is, get, a reading find, and an interaction's leading reads (a gesture's viewport read, the capture that resolves a selector click/fill) answer the retriable APP_NOT_RUNNING instead of bare-launching over a launch SpringBoard still holds behind its deep-link confirmation. Only open, activate, and a command that mutates without a leading read bring a stopped app up.
close keeps a healthy iOS simulator XCTest runner warm by default so the next open on that simulator (same udid in the same simulator set) skips the runner build, unless --shutdown was requested, the session was recording, or its device lease ends on close. A lease allocated with retainOnClose can keep the runner between sessions; releasing or expiring that lease stops its runner unless a session outside the lease has taken over the device. A retained runner auto-stops after an idle window (default 5 minutes); set AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS to override, or 0 to disable idle stopping. Lease release, expiry, and graceful daemon shutdown still clean up runners they own. Only a ready runner with an observed listener is retained; close retires unfinished prewarm recovery. Losing the retained listener stops that generation, and graceful daemon shutdown stops idle retained runners rather than handing them off without supervision.
Each AGENT_DEVICE_STATE_DIR runs its own daemon. It self-exits after an idle window (default 5 minutes, matching the runner idle-stop default) once it has no open sessions, no in-flight requests, and no active recording; set AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS to override, or 0 to disable idle reap.
A client starting a local daemon waits while the daemon process stays alive and keeps publishing startup progress, so an overloaded host makes startup slower, not failed. It stops at a ceiling (default 120 s; set AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS to a positive integer number of milliseconds to override) and names the outcome in error details.reason: startup-exited (the process ended before registering), startup-stalled (alive, no startup progress for a fixed 60 s window the ceiling variable does not change), or startup-ceiling (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the 60 s stall window, so a ceiling set below 60 s also ends a silent own launch this way). details.phases carries the startup phase timings it observed and details.startupTimeoutMs the effective ceiling. Branch on details.reason, never on the message. The variable is read only when a client must start a daemon: a value that is not a positive integer fails with INVALID_ARGS before the daemon spawns, and a client that only attaches to or reuses a running daemon never reads it.
On iOS simulators, open prepares app accessibility before launching an app or URL. If a running app has an empty accessibility tree after an earlier XCTest session, use open <app> --relaunch, then snapshot -i. A preparation failure is logged and does not block launch.
A command that needs the shared local daemon starts it for its state dir when none runs (device status and device release --stale never contact one). When the running daemon comes from another version or build, the command replaces it only if the daemon reports no work: no in-flight request, session, repair session, or live lease (a streaming resumable upload and a host human-control hold that names no lease are not counted); otherwise it fails with details.reason daemon-busy and leaves the daemon alone. A daemon that agreed to leave is waited for up to 60 s and never signaled while it drains; one still running then fails with details.reason daemon-drain-timeout unless it answers nothing and is provably a daemon process, which is force-retired. A daemon from a release that predates this check is never replaced and fails with daemon-incompatible. End a busy or older daemon deliberately with agent-device daemon stop --state-dir <path>. Node clients pick daemonLifecycle 'attach' (never starts or replaces a daemon; fails with daemon-not-running or daemon-incompatible) or 'managed' (the default until 0.22), and ensureDaemon() starts or replaces one explicitly.
daemon stop --state-dir <path> stops a detached daemon with process signals after verifying its identity. For a live embedded runtime, stop refuses with details.reason daemon-owner-embedded and a hint naming the host PID. Close that runtime in its host process with the handle returned by startAgentDevice(). Stop refuses live unrecognized ownership with daemon-owner-unrecognized and sends no request or signal. Stop retires an embedded or unrecognized registration when its recorded host lifetime has provably exited. Without --clean, an unreadable daemon.json fails with daemon-record-unreadable. daemon status shows host-owned or owner-not-recognized. Managed clients reuse a matching embedded runtime. Takeover, drain, and timeout recovery refuse a live embedded or unrecognized owner without a signal; a provably exited owner is retired so the state directory stays usable. Detached stop and cleanup use the lifetime and ownership from one registration read. --clean requires proven detached ownership; embedded, unrecognized and unreadable records fail with daemon-clean-not-detached because that cleanup walks the owner's whole process tree.
On a machine shared by several agents, set AGENT_DEVICE_SESSION_IDLE_TIMEOUT_MS to also expire an individual session that has taken a host-global device claim and then received no commands for that long; the claim is released and the next command on that session answers SESSION_NOT_FOUND with details.reason SESSION_IDLE_EXPIRED naming the window and the device. Off by default, because on a shared host "idle" and "thinking" are indistinguishable: only set it where an abandoned claim blocking every other agent is the worse failure. Sessions holding a remote lease or any active capture (recording, logs, audio, performance, or trace) are never expired this way.
A stale iOS runner lease — its owner process dead, or its AGENT_DEVICE_STATE_DIR deleted — is reclaimed automatically instead of failing with "is already owned by another agent-device daemon". A live owner's runner is also reclaimed when the requesting daemon holds the host-global device claim for that device: claims are exclusive, so holding one proves the runner's owner released the device and merely kept the runner warm. The error remains only for owners outside claim arbitration (a pre-claims build, or daemons pointed at different claim stores).
For iOS SpringBoard, widget, or other system-UI surfaces, read agent-device help ios-system-ui.`},"ios-system-ui":{summary:`iOS SpringBoard, widget, and system-surface workflow`,body:`agent-device help ios-system-ui
Use this when a task needs iOS SpringBoard (home screen), widget add/edit/remove, or other system-UI surfaces instead of the app under test.
This works today by opening SpringBoard as the session app; there is no separate widget/system command. System labels vary by iOS version and locale, so discover them from the current snapshot instead of relying on the literal strings shown below. This workflow is verified on iOS simulator. On a physical iPhone, opening SpringBoard, snapshot -i, and selector presses on visible home-screen icons are verified; the widget add/edit/remove steps are not yet verified on a physical iPhone.
Core loop:
1. Reach the app state you want to prepare (for example, arrange the widget/Live Activity data the app should show) with normal app automation, then agent-device open com.apple.springboard --platform ios. From an existing app session, agent-device home first also lands on the home screen, but open com.apple.springboard is what actually binds the session to SpringBoard for selector-driven commands.
2. agent-device snapshot -i to read the current localized SpringBoard controls.
3. agent-device longpress <x> <y> on an empty area of the home screen to enter edit mode. This is the one deliberate coordinate step; there is no reliable non-coordinate way to trigger it.
4. Re-snapshot and use selectors from the fresh tree to drive the Edit menu -> widget gallery -> search -> size picker -> Add Widget, for example:
agent-device snapshot -i
agent-device press 'label="Add Widget"'
agent-device fill 'label="Search"' "Calendar"
5. The widget-gallery search-result rows currently fall back to unlabeled nodes (a known capture gap), so tap the result by coordinates read from a screenshot until that is fixed:
agent-device screenshot
agent-device press <x> <y>
6. Continue with the semantic size picker and agent-device press 'label="Add Widget"' to place it.
7. To edit or remove an installed widget, longpress it, then re-snapshot and use the fresh context-menu selectors (Edit Widget / Remove Widget).
8. Use screenshots for visual assertions, and as the fallback wherever a system surface exposes sparse accessibility, not only in the gallery step.
9. Reopen the app bundle under test (agent-device open <app-id> --platform ios) to return to normal app automation; leaving SpringBoard bound does not resume the app session on its own.
Rules:
Do not hard-code Edit/Done/Add Widget or other SpringBoard label text into a plan as a fixed assumption; take them from the latest snapshot -i so the plan survives iOS version/locale differences.
A real system permission alert can appear mid-flow; it composes with this workflow normally, so handle it with alert wait/accept/dismiss or by pressing the visible label like any other step.
Prefer refs/selectors from the fresh snapshot for every step except the two documented coordinate fallbacks (empty-space long-press to enter edit mode, and the gallery search-result tap).
This topic covers what already works by opening SpringBoard as the session app. It does not yet cover keeping an app session open while alternating individual commands against SpringBoard, or Live Activity/Dynamic Island semantics; those land separately.`},foldable:O,remote:{summary:`Direct proxy, cloud profiles, and remote config`,body:`agent-device help remote
Remote connection providers use the same lifecycle:
connect -> install/open -> commands -> close -> disconnect
Providers:
Cloud: agent-device connect or agent-device connect cloud discovers the agent-device cloud profile.
Remote config: agent-device connect --remote-config ./remote-config.json uses a local profile.
Direct proxy: agent-device connect proxy --daemon-base-url <proxy-agent-device-url> stores the shared proxy profile and client identity.
BrowserStack: agent-device connect browserstack verifies credentials, the exact device, and a bs:// app reference, then stores a local provider profile. It does not create an App Automate session.
AWS Device Farm: agent-device connect aws-device-farm verifies credentials and the exact project, device, and optional app upload, then stores a local provider profile. It does not create a remote access session.
TestMu AI (plugin, install separately): agent-device connect testmu verifies credentials and the exact virtual device (emulator or simulator) or, with --provider-device-type real, real device and OS version, then stores a local provider profile. --provider-app takes an lt:// app reference, an https URL, or a local path: connect looks an lt:// id up among your uploads for that device pool, while URL and local sources are uploaded and validated when open creates the session. It does not create a hub session.
Limrun: agent-device connect limrun verifies access to the selected iOS or Android instance service, then stores a local provider profile. It does not create an instance.
Revyl (plugin, install separately): agent-device connect revyl verifies credentials against the Revyl backend, then stores a local provider profile with the platform, optional --device model and --provider-os-version, and a required --provider-app https URL: Revyl downloads and installs that build when it starts the device. It does not rent a device.
Plugin installation: the lines below name the plugin each provider needs, and plugin help is available before installation. plugins list --json reports your installed plugins. A missing plugin returns reason plugin-not-installed with its installation command; a selected plugin that cannot supply the provider returns plugin-unavailable instead. After changing plugins, close sessions and stop an existing local daemon with the same --state-dir before the next device command.
${d()}
After direct-provider connect:
Read the printed Device, App, Next, and workflow-note lines. They are also available as verification/device/app/liveSession/nextSteps/notes in --json output.
BrowserStack, AWS Device Farm, and TestMu AI create the hosted session on open. open needs the installed package or bundle identifier, not the app artifact name, ARN, or lt:// id.
Before provider allocation, apps lists compatible uploaded app assets without creating an instance when the selected provider exposes a catalog. open <exact-asset-name> creates the instance with that asset, resolves its installed app id, and launches it. install remains available when the app comes from a fresh local path or URL.
AWS Device Farm cannot install after allocation. If connect reports no attached app, run its printed reconnect command, which includes --session <name> --force, before open.
Do not run devices as a pre-open catalog probe for direct providers; it can allocate the deferred provider session. Limrun is the exception for apps: before allocation it lists uploaded assets for the selected platform.
Device cloud interfaces:
CLI is the canonical bootstrap path: connect limrun/browserstack/aws-device-farm/testmu/revyl, then use normal open/snapshot/click/close/disconnect commands; artifacts are provider-dependent.
JavaScript can skip persisted connect state by passing leaseProvider plus provider fields to createAgentDeviceClient or per-command options.
MCP exposes operational tools such as open, snapshot, click, close, and artifacts. It does not expose connect/disconnect; run CLI connect first in the same state dir before relying on MCP tools.
Direct proxy flow for a remote Mac/simulator:
On the Mac with simulator/device access:
cloudflared tunnel --url http://127.0.0.1:4310
# In a second terminal, after the tunnel reports its public name:
agent-device proxy --port 4310 --public-origin https://example.trycloudflare.com
Forwarding headers do not set upload ticket origins. For an ephemeral tunnel, obtain its public name, then configure and restart the proxy.
On the remote client:
export AGENT_DEVICE_SESSION=checkout-agent
agent-device connect proxy --daemon-base-url https://example.trycloudflare.com/agent-device --daemon-auth-token <token>
agent-device devices --platform ios
agent-device open Maps --platform ios --device "iPhone 17 Pro"
agent-device snapshot -i --platform ios --device "iPhone 17 Pro"
agent-device artifacts --json
agent-device close
agent-device disconnect
Leased sessions: a connection from connect proxy, connect (cloud), another connect provider, or a remote config that sets leaseProvider leases its device for one agent. Every command on it, from connect to disconnect, names its session with --session <name>, AGENT_DEVICE_SESSION, or a config session. Without one, it fails with INVALID_ARGS, reason REMOTE_SESSION_REQUIRED, before anything is leased, and never falls back to the connection another agent on the machine saved last. Set AGENT_DEVICE_SESSION once per agent or CI job before connect.
Proxy lease by device spec:
Without --udid or --serial, open, install, reinstall, and uninstall through connect proxy send --platform, --target, and --device on the lease allocate, and the backend in front of the daemon picks the device. --os <version|range>, --image-tag <tag>, --device-mode <slim|full>, --device-baseline <name>, and --physical add a device spec to that request. A non-blank osVersion, imageTag, deviceMode or deviceBaseline and physical: true name a spec key, sent as given; the backend validates its value (for example, Android --os is an API level, --device-mode full asks for an unslimmed iOS simulator, and --device-baseline names a saved device state the backend restores; it is unrelated to diff screenshot --baseline <path>). A blank string and physical: false name nothing, from the CLI, the SDK, or MCP. A value of another type fails with INVALID_ARGS, reason device-spec-invalid. connect proxy stores the spec keys it names as defaults like --platform and --device.
agent-device open MyApp --platform ios --device "iPhone 17 Pro" --os ">=26"
agent-device open MyApp --platform android --os 34 --image-tag google_apis_playstore
A backend that honours the spec returns the granted device as lease.device (model, osVersion, imageTag, physical, deviceMode when it reports one, and baseline {name, version} when one was restored); open --json prints it. A lease that reports no deviceMode is accepted without confirming the mode. A daemon, local or behind agent-device proxy, refuses a request that names a spec key with UNSUPPORTED_OPERATION, reason device-spec-unsupported, and details.keys, and records no lease. When the backend returns a lease without lease.device, with deviceMode slim for a full request, or without baseline.name equal to the requested --device-baseline, the CLI releases that lease, unless the allocation explicitly reports reuse (created: false). The command then fails with UNSUPPORTED_OPERATION, reason device-spec-unsupported, and details.released reports whether a release it attempted succeeded. A live lease serves a later command only when every spec key the command names equals the one the lease was allocated by; otherwise the command fails with reason CONNECTION_DEVICE_CONFLICT. Run connect --force to lease by another spec.
Human takeover of a leased remote device:
Run agent-device takeover using the active remote connection and session. It pauses state-changing agent commands until Ctrl+C while snapshots and other read-only diagnostics remain available. Tenant requests can control only their admitted lease device. Local takeover without a remote device lease is not supported.
agent-device takeover --session remote-session
agent-device takeover status
agent-device takeover release <hold-id>
An HTTP-mode daemon also accepts authenticated GET/PUT/DELETE requests at /admin/human-control/holds on its loopback listener. Host administrators supply the exact lease backend/provider/device key and use the local daemon token, not a tenant credential. This host-admin route is intentionally not forwarded by agent-device proxy. Holds do not survive daemon restart; re-establish them after reconnecting. The same listener and token serve GET/PUT/DELETE /admin/leases, where a host allocates a macos-app lease confining a client to one app (<bundleId> or <bundleId>@<pid>); tenants cannot allocate one.
Cloud profile flow:
export AGENT_DEVICE_SESSION=checkout-ios
agent-device connect
agent-device open com.example.app
agent-device snapshot
agent-device disconnect
TestMu AI virtual-device flow (emulators and simulators):
agent-device plugins add @agent-device/testmu
export LT_USERNAME=... LT_ACCESS_KEY=... AGENT_DEVICE_SESSION=checkout-ios
agent-device connect testmu --platform ios --device "iPhone 16" --provider-os-version 18.0 --provider-app lt://APP-id
agent-device open com.example.app
agent-device snapshot -i
agent-device close
agent-device artifacts --json
agent-device disconnect
TestMu AI real-device flow:
agent-device connect testmu --provider-device-type real --platform ios --device "iPhone 16" --provider-os-version 18 --provider-app ./MyApp.ipa --session checkout-real
Real iOS devices are listed by major OS version (18, not 18.0) and install a signed .ipa. Real and virtual devices have separate upload APIs, so pass an lt:// id uploaded for the pool you connect to.
LG webOS and Samsung Tizen TV flows (web apps, TV in Developer Mode):
export AGENT_DEVICE_SESSION=checkout-tv
agent-device connect webos --device living-room
agent-device open com.example.app
Add the plugin with plugins add @agent-device/webos. After open, drive the app with tv-remote, snapshot, close and disconnect. Prerequisites: the webOS CLI (npm install -g @webos-tools/cli) and the TV in Developer Mode, registered with ares-setup-device. --device names an ares-setup-device entry; connect does not contact the TV, open reads it. The TV enters as an Android TV device with id webos:<TV ip>:<port> from that entry, or webos:<ares device> for a USB entry. The page is driven over the Chrome DevTools Protocol through the ares-inspect tunnel.
Samsung Tizen: agent-device connect tizen --device 192.0.2.10, with the plugin from plugins add @agent-device/tizen, then the same commands. Prerequisites: sdb from the VS Code Tizen extension's SDK, the TV in Developer Mode with this host as its developer IP, and the app installed from a debug-enabled package. --device takes the TV IP or an sdb serial; connect does not contact the TV, open runs sdb connect when needed. The TV enters as an Android TV device with id tizen:<sdb serial>. open kills the app and debug-launches it, then drives the page over the Chrome DevTools Protocol through an sdb forward.
BrowserStack hosted-device flow:
export BROWSERSTACK_USERNAME=... BROWSERSTACK_ACCESS_KEY=... AGENT_DEVICE_SESSION=checkout-android
agent-device connect browserstack --platform android --device "Google Pixel 8" --provider-os-version 14.0 --provider-app bs://app-id
agent-device open com.example.app
agent-device snapshot -i
agent-device close
agent-device artifacts --json
agent-device disconnect
AWS Device Farm hosted-device flow:
export AWS_REGION=us-west-2 AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... AWS_SESSION_TOKEN=... AGENT_DEVICE_SESSION=checkout-android
agent-device connect aws-device-farm --platform android --aws-project-arn <arn> --aws-device-arn <arn> --aws-app-arn <arn>
agent-device open com.example.app
agent-device snapshot -i
agent-device close
agent-device artifacts --json
agent-device disconnect
AWS Device Farm currently supports Android and iOS WebDriver sessions only; Vega OS and Vega Fire TV ARNs are not routed.
Limrun direct-device flow:
export LIMRUN_API_KEY=... AGENT_DEVICE_SESSION=checkout-android
agent-device connect limrun --platform android
Limrun creates remote iOS simulators and Android emulators only. Do not pass local device selectors such as --udid, --serial, or --device.
To drive an existing instance without the API key, set LIM_IOS_INSTANCE_URL and LIM_IOS_INSTANCE_TOKEN, or LIM_ANDROID_INSTANCE_URL, LIM_ANDROID_INSTANCE_TOKEN, and LIM_ANDROID_INSTANCE_ADB_URL, from the instance status before connect. agent-device then never creates or deletes that instance; install and reinstall sync local app files without LIMRUN_API_KEY. Android still needs its ADB URL to connect. The apps command before the first open requires LIMRUN_API_KEY to list stored assets.
Set LIMRUN_KEEP_ALIVE=1 to ping the instance every 30 seconds while a session is open, so an idle session does not hit the Limrun inactivity timeout. It is off by default.
To capture network traffic, connect with --provider-network-logs --provider-network-hosts <app API hosts>. artifacts and close write the HAR and print its path and any capture failures; the HAR holds raw headers and bodies, and captured traffic exits through the daemon host.
agent-device apps
agent-device open Example.apk
agent-device snapshot -i
agent-device close
agent-device disconnect
Revyl cloud-device flow (plugin, install separately):
agent-device plugins add @agent-device/revyl
export REVYL_API_KEY=... AGENT_DEVICE_SESSION=checkout-ios
agent-device connect revyl --platform ios --provider-app https://downloads.example.test/app.zip
agent-device open com.example.app
agent-device snapshot -i
agent-device close
agent-device disconnect
Revyl starts a device from its own pool, so --device and --provider-os-version are preferences it picks from rather than a catalog lookup; leave them unset to get a simulator that is already warm. --provider-app must be an https URL it can download. connect verifies the key without renting a device; the device is rented on the first command that needs it and released on close or disconnect.
Local profile flow:
agent-device connect --remote-config ./remote-config.json
agent-device open com.example.app
agent-device snapshot
agent-device disconnect
Script flow, per-command config:
agent-device open com.example.app --remote-config ./remote-config.json
agent-device snapshot --remote-config ./remote-config.json
agent-device disconnect --remote-config ./remote-config.json
Rules:
connect and disconnect are top-level commands. Do not write agent-device remote connect or agent-device remote disconnect.
Use connect without --remote-config when the cloud control plane owns the connection profile.
Prefer connect --remote-config over --daemon-base-url, --tenant, --run-id, and --lease-id when using a local profile.
Use agent-device proxy for direct tunnel access to a Mac you control. Expose the proxy through cloudflared/ngrok, configure --public-origin with the public tunnel origin, then run agent-device connect proxy with the tunnel URL and printed token before normal commands.
Use Limrun, BrowserStack, AWS Device Farm, TestMu AI, and Revyl through local provider profiles; they do not accept a remote agent-device daemon URL.
Device cloud credentials must be available before the command starts. Limrun uses LIMRUN_API_KEY, or the LIM_*_INSTANCE_* variables for an existing instance. BrowserStack uses BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY. TestMu AI uses LT_USERNAME and LT_ACCESS_KEY. Revyl uses REVYL_API_KEY, with REVYL_API_URL to point at another Revyl backend. AWS Device Farm uses the AWS CLI credential chain, including CI-provided AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_SESSION_TOKEN, AWS profiles, or web identity role variables.
A local daemon keeps the Limrun, BrowserStack, TestMu AI, and Revyl credentials it started with. When the shell holds different ones, the first command that allocates a lease refuses with reason provider-credentials-changed; run agent-device daemon stop with the same --state-dir, then rerun the command. A shell that sets none of them uses the daemon's. A daemon with an HTTP auth hook serves remote callers and does not compare.
A lease for a provider the daemon has no runtime for refuses with UNSUPPORTED_OPERATION, reason provider-not-registered, and lists the registered providers, plus the plugins that failed to register as failedPlugins; no lease is recorded. Restart the daemon with the provider configured. Provider-less leases, proxy, and cloud need no provider runtime.
Direct-provider connect performs read-only provider calls and saves active connection state only after verification succeeds. It never creates a device, instance, App Automate session, or AWS remote access session.
connect without --session always creates a fresh remote session and prints that session in its next-step commands. Concurrent callers must pass the returned --session on every command; the ambient active connection is only a single-workflow convenience.
To replace an existing connection, pass its returned session explicitly with --session <name> --force. --force without --session creates another fresh session and does not release or overwrite an unrelated active connection.
Prefer short-lived AWS role credentials in CI. Generated connection profiles store app/device selectors and ARNs, not Limrun API keys or instance tokens, BrowserStack or TestMu AI access keys, or AWS credentials.
Limrun Android supports direct ADB port reverse for local Metro. Limrun iOS requires a public Metro URL because it cannot reach local host ports directly.
After closing a device cloud session, run agent-device artifacts --json to retrieve provider video/log/dashboard URLs when the provider has made them available.
connect proxy stores the connection profile and client identity. Proxy device leases are acquired on open and expire after five minutes without commands; when a lease expires or is released, the daemon ends the session opened under it and frees its device; devices may inspect proxy inventory without allocating.
Multiple agents can share one proxy when each uses connect proxy, open, commands, close, and disconnect.
disconnect releases local connection state; close releases the active session and device lease.
A busy direct-proxy device error means another agent owns the device until it closes or its inactivity lease expires.
Keep the proxy token secret. Anyone with the token can control the proxied daemon.
A daemon with AGENT_DEVICE_HTTP_AUTH_HOOK configured treats HTTP requests as remote: host-path install sources are rejected, as are install and reinstall binary paths, push payload files, and xctrace template files; uploaded artifacts remain supported, inline push JSON remains supported, and Maestro runScript, evalScript, and JavaScript conditions are rejected. No-hook local HTTP and socket flows retain their local behavior.
A daemon started with AGENT_DEVICE_DAEMON_POLICY=<policy.json> enforces that policy for every request, including batch steps and replay actions: it can limit which devices are visible and bindable, allow or deny commands (Maestro flows reach the daemon as the runtime command), and deny device-shutdown. A denial is UNAUTHORIZED with details.reason DAEMON_POLICY_DENIED; do not retry it. Use an allowed command or device, or ask the daemon operator to change the policy; a denied capability such as device-shutdown has no allowed alternative.
If local/proxy iOS reports that the runner is already owned by another agent-device daemon after lease admission, retry after the owning session closes or after lease expiry. If the conflict repeats, clean stale daemon state on the machine with simulator access.
Do not use --config as a remote profile flag. --config loads CLI defaults; --remote-config selects remote daemon/profile settings.
For self-contained scripts, pass the same --remote-config to every operational command, including disconnect; a preceding connect is optional but not required.
For remote artifact installs, use install-from-source <url> or install-from-source --github-actions-artifact org/repo:artifact; do not download CI artifacts locally first.
After connect, let the active remote connection supply runtime hints.
For connected phone/tablet setup and iOS signing prerequisites, read agent-device help physical-device.
Use --debug when remote connection or transport errors need diagnostic ids and remote log hints.`},macos:{summary:`macOS desktop, frontmost-app, and menu bar surfaces`,body:`agent-device help macos
Use macOS only when the task targets desktop apps, desktop surfaces, or menu bar extras.
Open and inspect:
agent-device open TextEdit --platform macos
agent-device snapshot -i --platform macos
Surfaces:
--surface is an open flag; the session keeps it, so later commands do not repeat it.
--surface app normal app session
--surface frontmost-app inspect whichever app is frontmost
--surface desktop desktop-wide surface
--surface menubar menu bar extras and menu bar-only apps
Menu bar app example:
agent-device open "Agent Device Tester Menu" --platform macos --surface menubar
agent-device snapshot -i --platform macos
Context menu example:
agent-device click @e66 --button secondary --platform macos
agent-device snapshot -i --platform macos
Rules:
Use open and snapshot -i for menu bar inspection. Do not output inspect as a command.
Context menus are not ambient UI: secondary-click a visible target, then re-snapshot and use the new menu-item refs.
Do not let iOS simulator-set scoping hide macOS desktop targets.
Prefer refs/selectors over raw coordinates.
macOS snapshot rects are window-space; use current refs or overlay refs instead of guessing coordinates.
On the default XCTest backend a read (snapshot, get, find) of a session app that sits behind other windows is answered from where it sits, without raising the app; interactions and a window-level screenshot of that app still bring it forward.
With AGENT_DEVICE_MACOS_APP_BACKEND=native, each app opened on the app surface is its own device: sessions on different apps run in parallel; a same-app or whole-Mac (desktop, menubar, frontmost-app) session conflicts.
An app session opens its app in the background and opens or closes only that app (open <url> goes to it). It refuses clipboard, settings, and audio probe; use a --surface desktop session for those, or a new --session for another app.`},web:{summary:`Minimal browser workflow with the managed web backend`,body:`agent-device help web
Use --platform web only for the minimal browser command loop exposed through agent-device.
Dependency:
Browser mechanics come from a managed, pinned agent-browser backend. agent-device owns command/session/replay integration, selectors/refs at the command surface, and artifact routing; agent-browser owns browser launch, page control, screenshots, and browser-specific behavior.
Use --platform web when a browser step belongs inside an agent-device session, replay, batch, MCP, or typed-client flow. Use agent-browser directly for standalone web automation.
Before first use, set up and verify the managed backend:
agent-device web setup
agent-device web doctor
Web automation requires Node 24+.
Planning rule:
For web command plans, output only agent-device command lines. Do not add prose, numbering, Markdown fences, shell pipes, or agent-browser commands unless the task is explicitly standalone browser automation outside agent-device.
First-slice loop:
Audio probe start uses duration seconds first, then bucket milliseconds.
agent-device web setup
agent-device web doctor
agent-device open https://example.com --platform web
agent-device snapshot -i --platform web
agent-device get text @e2 --platform web
agent-device is visible 'label="Welcome"' --platform web
agent-device find text "Welcome" exists --platform web
agent-device click @e12 --platform web
agent-device hover @e14 --settle --platform web
agent-device fill @e13 "qa@example.com" --platform web
agent-device wait text "Welcome" 3000 --platform web
agent-device record start ./artifacts/web-flow.webm --platform web
agent-device network dump 25 --include headers --platform web
agent-device audio probe start 10 1000 --platform web
agent-device screenshot ./artifacts/web-home.png --platform web
agent-device screenshot ./artifacts/web-full.png --platform web --fullscreen
agent-device viewport 1280 900 --platform web
agent-device record stop --platform web
agent-device close --platform web
Supported in agent-device web sessions:
open <url>, snapshot -i, get text/attrs, is visible/hidden/exists/absent/focused/text, find text/selector, click/press @ref or selector, hover @ref or selector, fill/type @ref or selector, wait text/selector/absent, network dump, audio probe, screenshot, record start/stop with WebM output, close, and replay scripts made from those commands.
hover moves the pointer without pressing so hover-gated UI (row toolbars, menus) appears; use --settle to read what it revealed, then act on the fresh refs. hover @ref hovers the browser element handle directly; pair --settle with a selector or coordinates (web refs carry no geometry, as with click @ref --settle). Web only: touch platforms have no hover state, so hover-gated flows there need a different entry point.
Out of scope for agent-device web support:
Browser runtime debugging, tabs/windows/devtools control, network routing/interception/HAR, storage/cookie management, arbitrary page scripting, downloads/uploads, multi-page orchestration, and agent-browser-specific diagnostics. Use agent-browser directly for those browser-specific workflows.
Rules:
Do not claim web e2e CI exists unless a project workflow explicitly provides it.
Do not use native mobile or desktop setup commands such as boot, apps, install, settings, alert, keyboard, perf, logs, or react-devtools for --platform web.
Keep browser plans session-scoped: open a URL, inspect refs, act on refs/selectors, verify with wait/get/is/snapshot, capture screenshot only when visual evidence is needed, then close. Each --session name is its own browser (cookies and storage) and its own device (agent-browser-chrome:session:p_<name>, or t_<tenant hash>_<name> under tenant isolation so tenants never share a browser): web sessions with different names run in parallel, and the same name in the same tenant conflicts while different tenants may reuse a name. Without --session under local workspace scoping, each workspace uses its own browser and device (agent-browser-chrome:session:w_<workspace scope>); different workspaces can run in parallel, while the same workspace conflicts across daemons sharing a claims directory. A request without a workspace scope (no cwd) uses the default session's browser and device (p_default, or t_<tenant hash>_default under tenant isolation). A name matches case-insensitively and must be 1 to 30 characters of letters, digits, "_" and "-" (1 to 17 under tenant isolation); anything else, including surrounding whitespace or an empty --session "", is refused with web_session_name_invalid.`},...E};function F(e,t,n){let r=n.endsWith(`?`),i=r?n.slice(0,-1):n,a=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(i),o=a||t.usageOverride!==void 0&&t.usageOverride.startsWith(`${e} ${i}`);return r?a?`[${i}]`:o?i:`[${i}]`:o?i:`<${i}>`}function I(e,t){return t.listUsageOverride?t.listUsageOverride:[e,...(t.positionalArgs??[]).map(n=>F(e,t,n))].join(` `)}function L(){return D()}function R(){return`agent-device help commands
Full command catalog. Use agent-device help <command> for exact flags and behavior.
${G(n().map(e=>{let t=s(e);return{name:e,schema:t,usage:I(e,t)}}))}
${H(`Device Selection (shared by device commands; help <command> lists each command's flags):`,B(i))}
${H(`Global Flags:`,B(r))}
${W(`Configuration:`,j)}
${U(`Environment:`,M)}
${W(`Examples:`,N)}
`}function z(){return L()}function B(e){return o().filter(t=>e.has(t.key)&&t.usageLabel!==void 0&&t.usageDescription!==void 0)}function V(e,t){return t?e.map(e=>{let n=t[e.key];return n===void 0?e:{...e,usageDescription:n}}):e}function H(e,t){return U(e,t.map(e=>({label:e.usageLabel??``,description:e.usageDescription??``})))}function U(e,t){if(t.length===0)return`${e}\n (none)`;let n=Math.max(...t.map(e=>Math.min(e.label.length,26)))+2,r=[e];for(let e of t){let t=e.label.length<=26?e.label.padEnd(n):`${e.label} `;r.push(` ${t}${e.description}`)}return r.join(`
`)}function W(e,t){return t.length===0?`${e}\n (none)`:[e,...t.map(e=>` ${e}`)].join(`
`)}function G(e){return U(`Commands:`,e.map(e=>({label:e.usage,description:e.schema.text.summary})))}function K(e){let t=X(e);if(t)return t;let n=c(e);if(!n)return null;let r=S(e,n),i=V(B(new Set(n.allowedFlags??[])),n.flagDescriptionOverrides),o=[];e===`connect`&&o.push(`Optional provider plugins:\n${d()}`),i.length>0&&o.push(H(`Command flags:`,i));let s=o.length>0?`\n\n${o.join(`
`)}`:``;return`Usage:
agent-device ${r}
${a(n.text)}${s}
`}function q(e){let t=c(e);return t?`agent-device ${S(e,t)}`:null}function J(e){return K(u(e))}function Y(){return Object.keys(P)}function X(e){let t=P[e];if(!t)return null;let n=e===`commands`?R():t.body,r=Z.filter(t=>t.topic!==e).map(e=>` ${e.line}\n`).join(``);return`${Q(e,n)}
Related:
${r}`}const Z=[{topic:null,line:`agent-device help <command> command-specific flags`},{topic:`manual-qa`,line:`agent-device help manual-qa routine QA loop`},{topic:`workflow`,line:`agent-device help workflow full automation reference`}];function Q(e,t){let n=`agent-device help ${e}`;return t.startsWith(n)?`agent-device ${l()} — ${e}${t.slice(n.length)}`:t}export{J as i,A as n,Y as r,z as t};