@developerz.ai/ui-debugger-mcp 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +22 -10
  2. package/dist/adapters/android/adb.d.ts +34 -5
  3. package/dist/adapters/android/adb.js +74 -20
  4. package/dist/adapters/android/adb.js.map +1 -1
  5. package/dist/adapters/android/android-adapter.d.ts +23 -7
  6. package/dist/adapters/android/android-adapter.js +106 -36
  7. package/dist/adapters/android/android-adapter.js.map +1 -1
  8. package/dist/adapters/android/android-adapter.test-helpers.d.ts +52 -0
  9. package/dist/adapters/android/android-adapter.test-helpers.js +115 -0
  10. package/dist/adapters/android/android-adapter.test-helpers.js.map +1 -0
  11. package/dist/adapters/android/commands.d.ts +27 -4
  12. package/dist/adapters/android/commands.js +66 -4
  13. package/dist/adapters/android/commands.js.map +1 -1
  14. package/dist/adapters/android/ports.d.ts +32 -0
  15. package/dist/adapters/android/ports.js +47 -0
  16. package/dist/adapters/android/ports.js.map +1 -0
  17. package/dist/adapters/android/uiautomator.d.ts +10 -2
  18. package/dist/adapters/android/uiautomator.js +36 -4
  19. package/dist/adapters/android/uiautomator.js.map +1 -1
  20. package/dist/adapters/browser/browser-adapter.d.ts +14 -13
  21. package/dist/adapters/browser/browser-adapter.js +69 -306
  22. package/dist/adapters/browser/browser-adapter.js.map +1 -1
  23. package/dist/adapters/browser/cdp.js +18 -11
  24. package/dist/adapters/browser/cdp.js.map +1 -1
  25. package/dist/adapters/browser/extractor.d.ts +49 -0
  26. package/dist/adapters/browser/extractor.js +208 -0
  27. package/dist/adapters/browser/extractor.js.map +1 -0
  28. package/dist/adapters/browser/filters.d.ts +15 -0
  29. package/dist/adapters/browser/filters.js +93 -0
  30. package/dist/adapters/browser/filters.js.map +1 -0
  31. package/dist/adapters/browser/launch.d.ts +41 -0
  32. package/dist/adapters/browser/launch.js +61 -0
  33. package/dist/adapters/browser/launch.js.map +1 -0
  34. package/dist/adapters/budget.d.ts +16 -0
  35. package/dist/adapters/budget.js +25 -0
  36. package/dist/adapters/budget.js.map +1 -0
  37. package/dist/adapters/contract.d.ts +13 -6
  38. package/dist/adapters/desktop/atspi.d.ts +15 -0
  39. package/dist/adapters/desktop/atspi.js +37 -17
  40. package/dist/adapters/desktop/atspi.js.map +1 -1
  41. package/dist/adapters/desktop/capture.js +8 -1
  42. package/dist/adapters/desktop/capture.js.map +1 -1
  43. package/dist/adapters/desktop/desktop-adapter.d.ts +9 -2
  44. package/dist/adapters/desktop/desktop-adapter.js +84 -32
  45. package/dist/adapters/desktop/desktop-adapter.js.map +1 -1
  46. package/dist/adapters/desktop/input.d.ts +16 -1
  47. package/dist/adapters/desktop/input.js +30 -0
  48. package/dist/adapters/desktop/input.js.map +1 -1
  49. package/dist/adapters/desktop/proc.d.ts +18 -3
  50. package/dist/adapters/desktop/proc.js +48 -5
  51. package/dist/adapters/desktop/proc.js.map +1 -1
  52. package/dist/adapters/factory.d.ts +3 -1
  53. package/dist/adapters/factory.js +6 -2
  54. package/dist/adapters/factory.js.map +1 -1
  55. package/dist/adapters/limit.d.ts +10 -0
  56. package/dist/adapters/limit.js +19 -0
  57. package/dist/adapters/limit.js.map +1 -0
  58. package/dist/agent/belt/act.d.ts +27 -5
  59. package/dist/agent/belt/act.js +75 -17
  60. package/dist/agent/belt/act.js.map +1 -1
  61. package/dist/agent/belt/observe.d.ts +29 -15
  62. package/dist/agent/belt/observe.js +74 -19
  63. package/dist/agent/belt/observe.js.map +1 -1
  64. package/dist/agent/belt/report.d.ts +29 -9
  65. package/dist/agent/belt/report.js +77 -10
  66. package/dist/agent/belt/report.js.map +1 -1
  67. package/dist/agent/belt/trail.d.ts +34 -0
  68. package/dist/agent/belt/trail.js +64 -0
  69. package/dist/agent/belt/trail.js.map +1 -0
  70. package/dist/agent/capabilities.d.ts +4 -4
  71. package/dist/agent/capabilities.js +38 -13
  72. package/dist/agent/capabilities.js.map +1 -1
  73. package/dist/agent/loop.d.ts +58 -19
  74. package/dist/agent/loop.js +134 -46
  75. package/dist/agent/loop.js.map +1 -1
  76. package/dist/agent/prompts/compose.d.ts +9 -1
  77. package/dist/agent/prompts/compose.js +5 -4
  78. package/dist/agent/prompts/compose.js.map +1 -1
  79. package/dist/agent/prompts/debug-agent.d.ts +13 -1
  80. package/dist/agent/prompts/debug-agent.js +45 -11
  81. package/dist/agent/prompts/debug-agent.js.map +1 -1
  82. package/dist/agent/prompts/desktop-addendum.d.ts +1 -1
  83. package/dist/agent/prompts/desktop-addendum.js +1 -1
  84. package/dist/agent/prompts/web-addendum.d.ts +1 -1
  85. package/dist/agent/prompts/web-addendum.js +16 -18
  86. package/dist/agent/prompts/web-addendum.js.map +1 -1
  87. package/dist/cli/control.d.ts +3 -1
  88. package/dist/cli/control.js +26 -40
  89. package/dist/cli/control.js.map +1 -1
  90. package/dist/cli/help.d.ts +3 -1
  91. package/dist/cli/help.js +6 -2
  92. package/dist/cli/help.js.map +1 -1
  93. package/dist/cli/init.d.ts +3 -6
  94. package/dist/cli/init.js +64 -16
  95. package/dist/cli/init.js.map +1 -1
  96. package/dist/config/load.js +8 -1
  97. package/dist/config/load.js.map +1 -1
  98. package/dist/config/schema.d.ts +12 -5
  99. package/dist/config/schema.js +17 -7
  100. package/dist/config/schema.js.map +1 -1
  101. package/dist/errors.d.ts +14 -2
  102. package/dist/errors.js +24 -4
  103. package/dist/errors.js.map +1 -1
  104. package/dist/index.d.ts +1 -1
  105. package/dist/index.js +1 -1
  106. package/dist/main.js +22 -8
  107. package/dist/main.js.map +1 -1
  108. package/dist/mcp/server.d.ts +16 -1
  109. package/dist/mcp/server.js +23 -2
  110. package/dist/mcp/server.js.map +1 -1
  111. package/dist/mcp/server.test-helpers.d.ts +23 -0
  112. package/dist/mcp/server.test-helpers.js +49 -0
  113. package/dist/mcp/server.test-helpers.js.map +1 -0
  114. package/dist/mcp/tools/describe.js +5 -0
  115. package/dist/mcp/tools/describe.js.map +1 -1
  116. package/dist/mcp/tools/end-session.js +5 -0
  117. package/dist/mcp/tools/end-session.js.map +1 -1
  118. package/dist/mcp/tools/get-findings.js +23 -3
  119. package/dist/mcp/tools/get-findings.js.map +1 -1
  120. package/dist/mcp/tools/output.d.ts +50 -0
  121. package/dist/mcp/tools/output.js +55 -0
  122. package/dist/mcp/tools/output.js.map +1 -0
  123. package/dist/mcp/tools/result.d.ts +24 -1
  124. package/dist/mcp/tools/result.js +106 -5
  125. package/dist/mcp/tools/result.js.map +1 -1
  126. package/dist/mcp/tools/send-message.js +5 -0
  127. package/dist/mcp/tools/send-message.js.map +1 -1
  128. package/dist/mcp/tools/start-debug.js +7 -1
  129. package/dist/mcp/tools/start-debug.js.map +1 -1
  130. package/dist/services/debug-service.d.ts +38 -6
  131. package/dist/services/debug-service.js +122 -13
  132. package/dist/services/debug-service.js.map +1 -1
  133. package/dist/services/session-builder.d.ts +20 -3
  134. package/dist/services/session-builder.js +43 -13
  135. package/dist/services/session-builder.js.map +1 -1
  136. package/dist/session/atomic-write.d.ts +24 -0
  137. package/dist/session/atomic-write.js +39 -0
  138. package/dist/session/atomic-write.js.map +1 -0
  139. package/dist/session/findings-store.js +3 -4
  140. package/dist/session/findings-store.js.map +1 -1
  141. package/dist/session/process-identity.d.ts +16 -0
  142. package/dist/session/process-identity.js +29 -0
  143. package/dist/session/process-identity.js.map +1 -1
  144. package/dist/session/session.js +10 -2
  145. package/dist/session/session.js.map +1 -1
  146. package/dist/session/state-file.d.ts +51 -5
  147. package/dist/session/state-file.js +60 -8
  148. package/dist/session/state-file.js.map +1 -1
  149. package/dist/session/workspace.d.ts +11 -0
  150. package/dist/session/workspace.js +14 -1
  151. package/dist/session/workspace.js.map +1 -1
  152. package/package.json +4 -1
package/README.md CHANGED
@@ -106,6 +106,10 @@ Install like any local MCP server — one entry in your `.mcp.json`:
106
106
  }
107
107
  ```
108
108
 
109
+ It's also published in the official [MCP Registry](https://modelcontextprotocol.io/registry) as
110
+ `io.github.developerz-ai/ui-debugger-mcp` — any client that browses the registry (instead of a
111
+ hand-written `.mcp.json` entry) can find and install it by that name.
112
+
109
113
  Then add a per-project `.ui-debugger-mcp.json` describing the app to debug
110
114
  (models, targets, urls). The fastest way is the `init` command:
111
115
 
@@ -167,10 +171,10 @@ and prints the `.mcp.json` snippet to paste.
167
171
 
168
172
  ```text
169
173
  // 4. In Claude Code (or any MCP client):
170
- start_debug { target: "web", goal: "log in and add item 3 to the cart" }
174
+ start_debug { target: "web", goal: "log in and add item 3 to the cart", url: "http://localhost:3000" }
171
175
 
172
176
  // 5. Poll until done:
173
- get_findings { session_id: "...", wait: true }
177
+ get_findings { session_id: "...", wait: 30000 }
174
178
 
175
179
  // 6. Read bugs[] + visual[] + summary. Fix code, repeat.
176
180
  ```
@@ -181,7 +185,7 @@ It's a **conversation**, not a remote control — five fat tools, not one-per-cl
181
185
 
182
186
  | Tool | What it does |
183
187
  |------|--------------|
184
- | `start_debug` | Open a run: `{ target, goal, criteria?, timeout? }`. The small agent drives autonomously. Returns `{ session_id }`. |
188
+ | `start_debug` | Open a run: `{ target, goal, url?, criteria?, timeout? }`. `url` is required when the target has no configured url. The small agent drives autonomously. Returns `{ session_id }`. |
185
189
  | `get_findings` | Poll status + structured findings (functional bugs + visual issues) + evidence. Long-poll with `wait`. |
186
190
  | `send_message` | Talk to the running agent mid-flight — add work, redirect, or answer a question. |
187
191
  | `describe` | List the configured targets + models for this project. |
@@ -191,6 +195,14 @@ A run is **always time-capped**: `start_debug`'s `timeout` (seconds) overrides t
191
195
  default 300s, so a session can never hang forever — it auto-ends and frees the
192
196
  profile lock when the cap fires.
193
197
 
198
+ Every tool result carries **both** a pretty-printed text block and a typed
199
+ `structuredContent` payload validated against a declared `outputSchema` — parse
200
+ the structured half, don't scrape the text. Tools also declare MCP annotations
201
+ (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) so clients
202
+ can render/gate them correctly, and evidence paths (screenshots, `replay.mp4`,
203
+ logs) ride as `resource_link` content items, not inline strings. Full shapes in
204
+ [`docs/reference.md`](docs/reference.md).
205
+
194
206
  Typical loop from a smart agent:
195
207
 
196
208
  ```text
@@ -227,7 +239,7 @@ One Chrome profile = one run. If a previous run crashed without cleaning up:
227
239
  ```bash
228
240
  npx @developerz.ai/ui-debugger-mcp stop # graceful teardown
229
241
  ```
230
- Or delete `./tmp/ui-debugger-mcp/state.json` and restart the MCP server.
242
+ Or delete `./tmp/ui-debugger-mcp/<project>/state.json` and restart the MCP server.
231
243
 
232
244
  **Run times out with no findings**
233
245
  Default cap is 300 s. Raise it per-call:
@@ -239,11 +251,11 @@ If the agent is stuck at login, add `?debug-ai=true` to your app's login route
239
251
  pattern.
240
252
 
241
253
  **`get_findings` returns empty `bugs[]` / `visual[]`**
242
- The run may still be in progress — use `wait: true`:
254
+ The run may still be in progress — use `wait` (ms) to long-poll:
243
255
  ```text
244
- get_findings { session_id: "...", wait: true }
256
+ get_findings { session_id: "...", wait: 30000 }
245
257
  ```
246
- Check `./tmp/ui-debugger-mcp/<project>/logs/agent.log` for the agent's trace.
258
+ Check `./tmp/ui-debugger-mcp/<project>/sessions/<id>/logs/agent.log` for the agent's trace.
247
259
 
248
260
  **`replay.mp4` not generated**
249
261
  ffmpeg is optional. Install it and retry, or ignore — findings and screenshots
@@ -289,7 +301,7 @@ See [`docs/idea/`](docs/idea/) for design notes.
289
301
 
290
302
  ## Credits / influences
291
303
 
292
- - [`ai-task-master`](../ai-task-master) — build template (orchestrator + subagents)
293
- - [`gold-standards-in-ai`](../gold-standards-in-ai) — MCP & code conventions
294
- - [`claude-code-bible`](../../sebyx07/claude-code-bible) — agent-first patterns
304
+ - `ai-task-master` — build template (orchestrator + subagents), reference repo, not published
305
+ - `gold-standards-in-ai` — MCP & code conventions, reference repo, not published
306
+ - `claude-code-bible` — agent-first patterns ([sebyx07/claude-code-bible](https://github.com/sebyx07/claude-code-bible))
295
307
  - [Model Context Protocol](https://modelcontextprotocol.io/docs/develop/connect-local-servers)
@@ -7,15 +7,44 @@
7
7
  * live in the pure builders beside it (`commands.ts`, `uiautomator.ts`) so they stay
8
8
  * unit-testable without spawning. {@link AdbCli} is injected as a seam in tests.
9
9
  *
10
+ * One subprocess call underneath ({@link AdbExec}, injectable) resolving raw bytes; the
11
+ * text channels decode UTF-8 on top, so `exec-out` stays binary-safe by construction.
12
+ *
10
13
  * Three channels, mirroring `adb`'s own surface:
11
14
  * - {@link Adb.shell} — `adb shell <cmd>` → text (am/input/uiautomator/getprop/logcat).
12
15
  * - {@link Adb.execOut} — `adb exec-out <cmd>` → **raw bytes** (binary-safe `screencap -p`).
13
16
  * - {@link Adb.adb} — top-level `adb <args>` (`wait-for-device`, `emu kill`).
14
17
  *
15
- * Target selection is baked into the `flags` at construction: `['-s', serial]` for an
16
- * attached device, `['-e']` for the single managed emulator. Fails loud — a non-zero
17
- * exit or a missing binary rejects as an {@link AdbError}, never a silent fallback.
18
+ * Target selection is baked into the `flags` at construction and is always an explicit
19
+ * serial — `['-s', serial]`, the configured one when attaching, `emulator-<port>` for
20
+ * the emulator a managed run started (never the ambiguous `-e`). Fails loud — a non-zero
21
+ * exit, a timeout or a missing binary rejects as an {@link AdbError}, never a silent
22
+ * fallback; {@link pendingStateOrThrow} is the one narrow exception a boot poll may retry.
23
+ */
24
+ /**
25
+ * Triage a `get-state` rejection during a boot poll: return `''` (poll again) only when
26
+ * the device is merely not up yet, otherwise rethrow. Honest failure — a missing `adb`
27
+ * or a wedged call must surface now, not 120 s later as a misleading "no device appeared".
18
28
  */
29
+ export declare function pendingStateOrThrow(error: unknown): string;
30
+ /**
31
+ * The one subprocess call the transport makes — resolves **raw stdout bytes** (text
32
+ * channels decode on top, so `exec-out` stays binary-safe). Injectable so argv-shape
33
+ * tests assert the argv they would have spawned instead of spawning: a real child's
34
+ * stdout is at the mercy of the machine, and argv ordering is a pure property.
35
+ */
36
+ export type AdbExec = (bin: string, args: string[], timeoutMs: number) => Promise<Uint8Array>;
37
+ /** The real {@link AdbExec}: `execFile`, capped, buffer-encoded (never UTF-8 mangled). */
38
+ export declare const execFileBytes: AdbExec;
39
+ /** Construction knobs for {@link AdbCli} — also the seams unit tests drive it through. */
40
+ export interface AdbCliOptions {
41
+ /** Per-call timeout in ms (default {@link DEFAULT_TIMEOUT_MS}). */
42
+ timeoutMs?: number;
43
+ /** Binary to invoke (default `adb`). */
44
+ bin?: string;
45
+ /** Subprocess runner (default {@link execFileBytes}). */
46
+ exec?: AdbExec;
47
+ }
19
48
  /** The ADB transport the adapter depends on — implemented by {@link AdbCli}, faked in tests. */
20
49
  export interface Adb {
21
50
  /** `adb <target> shell <command…>` → stdout text. */
@@ -27,11 +56,11 @@ export interface Adb {
27
56
  }
28
57
  /**
29
58
  * `execFile`-backed {@link Adb}. Construct with the device-selection `flags`
30
- * (`['-s', serial]` to attach · `['-e']` for the managed emulator).
59
+ * (`['-s', serial]` — the config serial when attaching, `emulator-<port>` when managed).
31
60
  */
32
61
  export declare class AdbCli implements Adb {
33
62
  #private;
34
- constructor(flags: string[]);
63
+ constructor(flags: string[], options?: AdbCliOptions);
35
64
  shell(command: string[]): Promise<string>;
36
65
  adb(args: string[]): Promise<string>;
37
66
  execOut(command: string[]): Promise<Uint8Array>;
@@ -7,14 +7,19 @@
7
7
  * live in the pure builders beside it (`commands.ts`, `uiautomator.ts`) so they stay
8
8
  * unit-testable without spawning. {@link AdbCli} is injected as a seam in tests.
9
9
  *
10
+ * One subprocess call underneath ({@link AdbExec}, injectable) resolving raw bytes; the
11
+ * text channels decode UTF-8 on top, so `exec-out` stays binary-safe by construction.
12
+ *
10
13
  * Three channels, mirroring `adb`'s own surface:
11
14
  * - {@link Adb.shell} — `adb shell <cmd>` → text (am/input/uiautomator/getprop/logcat).
12
15
  * - {@link Adb.execOut} — `adb exec-out <cmd>` → **raw bytes** (binary-safe `screencap -p`).
13
16
  * - {@link Adb.adb} — top-level `adb <args>` (`wait-for-device`, `emu kill`).
14
17
  *
15
- * Target selection is baked into the `flags` at construction: `['-s', serial]` for an
16
- * attached device, `['-e']` for the single managed emulator. Fails loud — a non-zero
17
- * exit or a missing binary rejects as an {@link AdbError}, never a silent fallback.
18
+ * Target selection is baked into the `flags` at construction and is always an explicit
19
+ * serial — `['-s', serial]`, the configured one when attaching, `emulator-<port>` for
20
+ * the emulator a managed run started (never the ambiguous `-e`). Fails loud — a non-zero
21
+ * exit, a timeout or a missing binary rejects as an {@link AdbError}, never a silent
22
+ * fallback; {@link pendingStateOrThrow} is the one narrow exception a boot poll may retry.
18
23
  */
19
24
  import { execFile } from 'node:child_process';
20
25
  import { promisify } from 'node:util';
@@ -23,14 +28,64 @@ const pExecFile = promisify(execFile);
23
28
  const ADB = 'adb';
24
29
  /** 64 MiB stdout cap — `screencap -p` PNGs run a few MB on hi-dpi panels; text replies are tiny. */
25
30
  const MAX_BUFFER = 64 * 1024 * 1024;
31
+ /**
32
+ * Per-invocation wall-clock cap. `adb` wedges in practice — a stuck `uiautomator dump`,
33
+ * a half-dead emulator, an adb server mid-restart — and an unbounded `execFile` would
34
+ * hang the whole run behind it. 30 s is far above any healthy call (a cold `screencap`
35
+ * or a big hierarchy dump lands in single-digit seconds).
36
+ *
37
+ * The long boot wait is *not* one call: the adapter polls `get-state`/`getprop` against
38
+ * its own 120 s deadline, so every individual call stays under this cap.
39
+ */
40
+ const DEFAULT_TIMEOUT_MS = 30_000;
41
+ /**
42
+ * Kill signal on expiry. SIGKILL, not SIGTERM: a wedged `adb` blocked on the transport
43
+ * is exactly the process that ignores a polite signal, and Node only rejects once the
44
+ * child is actually gone.
45
+ */
46
+ const KILL_SIGNAL = 'SIGKILL';
47
+ /** Decoder for the text channels — one instance, `adb` speaks UTF-8. */
48
+ const DECODER = new TextDecoder();
49
+ /**
50
+ * `adb` failure phrases that mean "the device is not up **yet**" — the only rejection a
51
+ * boot poll may retry. Deliberately narrow: a missing binary, an ambiguous target
52
+ * (`more than one device`) or a timeout are real failures, not "keep waiting".
53
+ */
54
+ const PENDING_DEVICE = /no devices\/emulators found|device offline|device '[^']*' not found|device still (connecting|authorizing)/i;
55
+ /**
56
+ * Triage a `get-state` rejection during a boot poll: return `''` (poll again) only when
57
+ * the device is merely not up yet, otherwise rethrow. Honest failure — a missing `adb`
58
+ * or a wedged call must surface now, not 120 s later as a misleading "no device appeared".
59
+ */
60
+ export function pendingStateOrThrow(error) {
61
+ if (error instanceof AdbError && PENDING_DEVICE.test(error.message))
62
+ return '';
63
+ throw error;
64
+ }
65
+ /** The real {@link AdbExec}: `execFile`, capped, buffer-encoded (never UTF-8 mangled). */
66
+ export const execFileBytes = async (bin, args, timeoutMs) => {
67
+ const { stdout } = await pExecFile(bin, args, {
68
+ encoding: 'buffer',
69
+ maxBuffer: MAX_BUFFER,
70
+ timeout: timeoutMs,
71
+ killSignal: KILL_SIGNAL,
72
+ });
73
+ return Uint8Array.from(stdout);
74
+ };
26
75
  /**
27
76
  * `execFile`-backed {@link Adb}. Construct with the device-selection `flags`
28
- * (`['-s', serial]` to attach · `['-e']` for the managed emulator).
77
+ * (`['-s', serial]` — the config serial when attaching, `emulator-<port>` when managed).
29
78
  */
30
79
  export class AdbCli {
31
80
  #flags;
32
- constructor(flags) {
81
+ #timeoutMs;
82
+ #bin;
83
+ #exec;
84
+ constructor(flags, options = {}) {
33
85
  this.#flags = flags;
86
+ this.#timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
87
+ this.#bin = options.bin ?? ADB;
88
+ this.#exec = options.exec ?? execFileBytes;
34
89
  }
35
90
  shell(command) {
36
91
  return this.#text(['shell', ...command]);
@@ -38,33 +93,32 @@ export class AdbCli {
38
93
  adb(args) {
39
94
  return this.#text(args);
40
95
  }
41
- async execOut(command) {
42
- const args = ['exec-out', ...command];
43
- try {
44
- const { stdout } = await pExecFile(ADB, [...this.#flags, ...args], {
45
- encoding: 'buffer',
46
- maxBuffer: MAX_BUFFER,
47
- });
48
- return Uint8Array.from(stdout);
49
- }
50
- catch (error) {
51
- throw this.#wrap(args, error);
52
- }
96
+ execOut(command) {
97
+ return this.#bytes(['exec-out', ...command]);
53
98
  }
99
+ /** UTF-8 view of the byte read — `adb`'s text channels (`am`, `getprop`, `logcat`) are UTF-8. */
54
100
  async #text(args) {
101
+ return DECODER.decode(await this.#bytes(args));
102
+ }
103
+ async #bytes(args) {
55
104
  try {
56
- const { stdout } = await pExecFile(ADB, [...this.#flags, ...args], { maxBuffer: MAX_BUFFER });
57
- return stdout;
105
+ return await this.#exec(this.#bin, [...this.#flags, ...args], this.#timeoutMs);
58
106
  }
59
107
  catch (error) {
60
108
  throw this.#wrap(args, error);
61
109
  }
62
110
  }
63
- /** Wrap any subprocess failure as a loud {@link AdbError} (ENOENT → a clear install hint). */
111
+ /**
112
+ * Wrap any subprocess failure as a loud {@link AdbError}: ENOENT → a clear install
113
+ * hint, expiry (the child was killed by our `timeout`) → a wedge report naming the cap.
114
+ */
64
115
  #wrap(args, error) {
65
116
  if (error instanceof Error && error.code === 'ENOENT') {
66
117
  return new AdbError('android: `adb` not found on PATH (install Android platform-tools)');
67
118
  }
119
+ if (error instanceof Error && error.killed === true) {
120
+ return new AdbError(`adb ${args[0] ?? ''} timed out after ${this.#timeoutMs}ms (${KILL_SIGNAL}ed — adb or the emulator is wedged)`);
121
+ }
68
122
  const message = error instanceof Error ? error.message : String(error);
69
123
  return new AdbError(`adb ${args[0] ?? ''} failed: ${message}`);
70
124
  }
@@ -1 +1 @@
1
- {"version":3,"file":"adb.js","sourceRoot":"","sources":["../../../src/adapters/android/adb.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,MAAM,SAAS,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAEtC,MAAM,GAAG,GAAG,KAAK,CAAC;AAElB,oGAAoG;AACpG,MAAM,UAA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disconnect-only (never stops it); otherwise it
12
- * boots the configured `emulator @avd`, waits for `sys.boot_completed`, and `close`
13
- * stops it. Android is fully framework-driven — no vision needed for actions.
12
+ * boots the configured `emulator @avd` on a free console port (`ports.ts`), waits for
13
+ * `sys.boot_completed`, and `close` stops it. Either way every call is bound to one
14
+ * explicit serial (`adb -s <serial>`), so a managed run can never drive — or kill — an
15
+ * emulator it did not start. Android is fully framework-driven — no vision for actions.
14
16
  *
15
17
  * `console` is logcat-backed (real crash/error signal); `network` has no ADB channel
16
18
  * and throws loud ({@link AdapterError}). Every backend failure surfaces as an
@@ -33,14 +35,20 @@ export type SpawnEmulator = (bin: string, args: string[]) => ChildProcess;
33
35
  export interface AndroidAdapterInit {
34
36
  /** Resolved android-target config (avd, emulatorPath, adbSerial). */
35
37
  config: AndroidTarget;
36
- /** Override the ADB transport (defaults to {@link AdbCli}); a seam for tests. */
37
- adb?: Adb;
38
+ /**
39
+ * Override the ADB transport (defaults to an {@link AdbCli} bound to the device
40
+ * serial); a seam for tests. As a function it is the transport *factory* and gets
41
+ * the serial the adapter bound to — managed mode calls it at boot.
42
+ */
43
+ adb?: Adb | ((serial: string) => Adb);
38
44
  /** Override the read source (defaults to {@link AdbUiAutomator}); a seam for tests. */
39
45
  ui?: UiAutomatorSource;
40
46
  /** Override the emulator spawn (defaults to `spawn`, detached); a seam for tests. */
41
47
  spawn?: SpawnEmulator;
42
48
  /** Override the managed-boot deadline (defaults to {@link BOOT_WAIT_MS}); a seam for tests. */
43
49
  bootWaitMs?: number;
50
+ /** Override the managed console-port pick (defaults to {@link pickEmulatorPort}); a test seam. */
51
+ pickPort?: () => Promise<number>;
44
52
  }
45
53
  /**
46
54
  * The android {@link Adapter}: an ADB + uiautomator pair behind one contract.
@@ -49,10 +57,14 @@ export interface AndroidAdapterInit {
49
57
  export declare class AndroidAdapter implements Adapter {
50
58
  #private;
51
59
  private constructor();
52
- /** Wire the adapter from config: `adbSerial` → attach (`-s serial`), else managed emulator (`-e`). */
60
+ /**
61
+ * Wire the adapter from config. Both modes talk to **one explicit serial**
62
+ * (`adb -s <serial>`): attach reads it from `adbSerial` and binds here, managed
63
+ * only learns it when it picks a console port and spawns — so it binds at boot.
64
+ */
53
65
  static create(init: AndroidAdapterInit): AndroidAdapter;
54
66
  /** Ensure the device is up (managed: boot the emulator), then start the activity/package. */
55
- open(target: string): Promise<void>;
67
+ open(target: string, timeoutMs?: number): Promise<void>;
56
68
  find(opts: Query): Promise<Node | null>;
57
69
  readState(opts?: Query): Promise<Node[]>;
58
70
  click(target: NodeRef): Promise<void>;
@@ -65,6 +77,10 @@ export declare class AndroidAdapter implements Adapter {
65
77
  console(opts?: LogQuery): Promise<ConsoleEntry[]>;
66
78
  /** Android exposes no network channel over ADB — unsupported, surfaced loud. */
67
79
  network(): Promise<NetworkEntry[]>;
68
- /** Attach: disconnect-only (never stop the device). Managed: stop the emulator. */
80
+ /**
81
+ * Attach: disconnect-only (never stop the device). Managed: stop **our** emulator —
82
+ * the kill goes to the bound serial (`adb -s emulator-<port> emu kill`), so a
83
+ * co-running emulator we never started is untouched.
84
+ */
69
85
  close(): Promise<void>;
70
86
  }
@@ -9,8 +9,10 @@
9
9
  *
10
10
  * **Managed or attach** (`idea/adapters.md`): with an `adbSerial` the adapter attaches
11
11
  * to a running device and `close` is disconnect-only (never stops it); otherwise it
12
- * boots the configured `emulator @avd`, waits for `sys.boot_completed`, and `close`
13
- * stops it. Android is fully framework-driven — no vision needed for actions.
12
+ * boots the configured `emulator @avd` on a free console port (`ports.ts`), waits for
13
+ * `sys.boot_completed`, and `close` stops it. Either way every call is bound to one
14
+ * explicit serial (`adb -s <serial>`), so a managed run can never drive — or kill — an
15
+ * emulator it did not start. Android is fully framework-driven — no vision for actions.
14
16
  *
15
17
  * `console` is logcat-backed (real crash/error signal); `network` has no ADB channel
16
18
  * and throws loud ({@link AdapterError}). Every backend failure surfaces as an
@@ -18,8 +20,10 @@
18
20
  */
19
21
  import { spawn } from 'node:child_process';
20
22
  import { AdapterError, UiDebuggerError } from '../../errors.js';
21
- import { AdbCli } from './adb.js';
22
- import { centerOf, keyArgs, parseScreenSize, scrollSwipe, splitTextForInput, startArgs, swipeArgs, tapArgs, textArgs, } from './commands.js';
23
+ import { capWait } from '../budget.js';
24
+ import { AdbCli, pendingStateOrThrow } from './adb.js';
25
+ import { keyArgs, parseScreenSize, scrollSwipe, splitTextForInput, splitTextLines, startArgs, swipeArgs, tapArgs, tapPointOf, textArgs, } from './commands.js';
26
+ import { emulatorSerial, pickEmulatorPort } from './ports.js';
23
27
  import { AdbUiAutomator, shapeNodes } from './uiautomator.js';
24
28
  /** Default cap on `readState` so the tree stays small (overridable via `limit`). */
25
29
  const DEFAULT_LIMIT = 200;
@@ -104,11 +108,14 @@ export function applyLogFilters(entries, filters) {
104
108
  */
105
109
  export class AndroidAdapter {
106
110
  #config;
107
- #adb;
108
- #ui;
111
+ #bind;
109
112
  #attach;
110
113
  #spawn;
111
114
  #bootWaitMs;
115
+ #pickPort;
116
+ #transport;
117
+ /** The device every call is bound to (`emulator-<port>` once managed boot picks one). */
118
+ #serial;
112
119
  #emulator = null;
113
120
  /** Why the managed emulator process is unusable (launch failure / early exit), or null. */
114
121
  #emulatorDown = null;
@@ -116,32 +123,66 @@ export class AndroidAdapter {
116
123
  #screen = null;
117
124
  constructor(handles) {
118
125
  this.#config = handles.config;
119
- this.#adb = handles.adb;
120
- this.#ui = handles.ui;
126
+ this.#transport = handles.transport;
127
+ this.#bind = handles.bind;
121
128
  this.#attach = handles.attach;
129
+ this.#serial = handles.serial;
122
130
  this.#spawn = handles.spawn;
123
131
  this.#bootWaitMs = handles.bootWaitMs;
132
+ this.#pickPort = handles.pickPort;
124
133
  // Attach mode targets an already-running device — treat it as booted from the start.
125
134
  this.#booted = handles.attach;
126
135
  }
127
- /** Wire the adapter from config: `adbSerial` → attach (`-s serial`), else managed emulator (`-e`). */
136
+ /**
137
+ * Wire the adapter from config. Both modes talk to **one explicit serial**
138
+ * (`adb -s <serial>`): attach reads it from `adbSerial` and binds here, managed
139
+ * only learns it when it picks a console port and spawns — so it binds at boot.
140
+ */
128
141
  static create(init) {
129
- const serial = init.config.adbSerial ?? null;
130
- const attach = serial !== null;
131
- const adb = init.adb ?? new AdbCli(serial !== null ? ['-s', serial] : ['-e']);
142
+ const attachSerial = init.config.adbSerial ?? null;
143
+ // An injected transport instance (test seam) is already bound — never rebuilt.
144
+ const seam = typeof init.adb === 'object' ? init.adb : null;
145
+ const makeAdb = typeof init.adb === 'function' ? init.adb : null;
146
+ const bind = seam === null
147
+ ? (serial) => {
148
+ const adb = makeAdb ? makeAdb(serial) : new AdbCli(['-s', serial]);
149
+ return { adb, ui: init.ui ?? new AdbUiAutomator(adb) };
150
+ }
151
+ : null;
152
+ let transport = null;
153
+ if (seam !== null)
154
+ transport = { adb: seam, ui: init.ui ?? new AdbUiAutomator(seam) };
155
+ else if (attachSerial !== null && bind !== null)
156
+ transport = bind(attachSerial);
132
157
  return new AndroidAdapter({
133
158
  config: init.config,
134
- adb,
135
- ui: init.ui ?? new AdbUiAutomator(adb),
136
- attach,
159
+ transport,
160
+ bind,
161
+ attach: attachSerial !== null,
162
+ serial: attachSerial,
137
163
  spawn: init.spawn ?? ((bin, args) => spawn(bin, args, { detached: true, stdio: 'ignore' })),
138
164
  bootWaitMs: init.bootWaitMs ?? BOOT_WAIT_MS,
165
+ pickPort: init.pickPort ?? (() => pickEmulatorPort()),
139
166
  });
140
167
  }
168
+ /** The bound ADB transport. Managed mode binds it at boot — nothing talks to a device before. */
169
+ get #adb() {
170
+ if (!this.#transport) {
171
+ throw new AdapterError('android: no device bound yet (open the target first)');
172
+ }
173
+ return this.#transport.adb;
174
+ }
175
+ /** The bound hierarchy reader — bound with {@link AndroidAdapter.#adb}. */
176
+ get #ui() {
177
+ if (!this.#transport) {
178
+ throw new AdapterError('android: no device bound yet (open the target first)');
179
+ }
180
+ return this.#transport.ui;
181
+ }
141
182
  /** Ensure the device is up (managed: boot the emulator), then start the activity/package. */
142
- async open(target) {
183
+ async open(target, timeoutMs) {
143
184
  await this.#run('open', async () => {
144
- await this.#ensureBooted();
185
+ await this.#ensureBooted(timeoutMs);
145
186
  if (target.trim() !== '')
146
187
  await this.#adb.shell(startArgs(target));
147
188
  });
@@ -161,18 +202,23 @@ export class AndroidAdapter {
161
202
  }
162
203
  async click(target) {
163
204
  await this.#run('click', async () => {
164
- const { x, y } = centerOf((await this.#resolve(target)).bounds);
205
+ const { x, y } = tapPointOf(await this.#resolve(target));
165
206
  await this.#adb.shell(tapArgs(x, y));
166
207
  });
167
208
  }
168
209
  async type(target, text) {
169
210
  // Contract: focus the target first, then type. Tap its center to focus.
170
- // Text goes out in %s-safe chunks — one `input text` per chunk (they append).
211
+ // Line breaks become ENTER presses (a raw \n would reach the device shell);
212
+ // each line goes out in %s-safe chunks — one `input text` per chunk (they append).
171
213
  await this.#run('type', async () => {
172
- const { x, y } = centerOf((await this.#resolve(target)).bounds);
214
+ const { x, y } = tapPointOf(await this.#resolve(target));
173
215
  await this.#adb.shell(tapArgs(x, y));
174
- for (const chunk of splitTextForInput(text)) {
175
- await this.#adb.shell(textArgs(chunk));
216
+ for (const [index, line] of splitTextLines(text).entries()) {
217
+ if (index > 0)
218
+ await this.#adb.shell(keyArgs('enter'));
219
+ for (const chunk of splitTextForInput(line)) {
220
+ await this.#adb.shell(textArgs(chunk));
221
+ }
176
222
  }
177
223
  });
178
224
  }
@@ -190,6 +236,8 @@ export class AndroidAdapter {
190
236
  : await this.#screenSize();
191
237
  const { x1, y1, x2, y2 } = scrollSwipe(opts.direction, area, opts.amount);
192
238
  await this.#adb.shell(swipeArgs(x1, y1, x2, y2));
239
+ // Screen size may have changed (orientation, split-screen, etc.) — invalidate cache.
240
+ this.#screen = null;
193
241
  });
194
242
  }
195
243
  async screenshot() {
@@ -232,18 +280,27 @@ export class AndroidAdapter {
232
280
  async network() {
233
281
  throw new AdapterError('android target has no network channel over ADB (use a proxy; unsupported)');
234
282
  }
235
- /** Attach: disconnect-only (never stop the device). Managed: stop the emulator. */
283
+ /**
284
+ * Attach: disconnect-only (never stop the device). Managed: stop **our** emulator —
285
+ * the kill goes to the bound serial (`adb -s emulator-<port> emu kill`), so a
286
+ * co-running emulator we never started is untouched.
287
+ */
236
288
  async close() {
237
289
  if (this.#attach)
238
290
  return;
239
291
  await this.#run('close', async () => {
240
- if (this.#booted) {
292
+ if (this.#booted && this.#transport) {
241
293
  // Best-effort console kill; the SIGTERM below is the hard backstop.
242
- await this.#adb.adb(['emu', 'kill']).catch(() => undefined);
294
+ await this.#transport.adb.adb(['emu', 'kill']).catch(() => undefined);
243
295
  }
244
296
  const pid = this.#emulator?.pid;
245
297
  this.#emulator = null;
246
298
  this.#booted = false;
299
+ this.#serial = null;
300
+ this.#screen = null;
301
+ // Drop the binding so a re-`open` binds to the next emulator, not the dead one.
302
+ if (this.#bind)
303
+ this.#transport = null;
247
304
  if (pid === undefined)
248
305
  return;
249
306
  try {
@@ -256,54 +313,67 @@ export class AndroidAdapter {
256
313
  }
257
314
  });
258
315
  }
259
- /** Managed boot: launch `emulator @avd` (once) and poll `sys.boot_completed`. No-op when attached. */
260
- async #ensureBooted() {
316
+ /**
317
+ * Managed boot: launch `emulator @avd -port <p>` (once), poll `sys.boot_completed`. The port
318
+ * is picked free and bound **before** the spawn, so every later call (and the `close` kill)
319
+ * targets the emulator we started, never a pre-existing one. No-op when attached; `timeoutMs`
320
+ * (the run's remaining cap) shortens the boot deadline when it is the tighter of the two.
321
+ */
322
+ async #ensureBooted(timeoutMs) {
261
323
  if (this.#booted)
262
324
  return;
263
325
  if (!this.#emulator) {
264
326
  const bin = this.#config.emulatorPath ?? 'emulator';
265
- const child = this.#spawn(bin, [`@${this.#config.avd}`]);
327
+ const port = await this.#pickPort();
328
+ this.#serial = emulatorSerial(port);
329
+ if (this.#bind)
330
+ this.#transport = this.#bind(this.#serial);
331
+ const child = this.#spawn(bin, [`@${this.#config.avd}`, '-port', String(port)]);
266
332
  this.#emulatorDown = null;
267
333
  // Both fire async (later tick): without a listener a bad `emulatorPath` would
268
334
  // crash the whole server via an unhandled 'error' event. Capture the failure
269
335
  // and let the boot poll below surface it as a loud AdapterError.
270
336
  child.on('error', (err) => {
271
337
  this.#emulatorDown = `emulator ('${bin}') failed to launch: ${err.message}`;
338
+ this.#emulator = null;
272
339
  });
273
340
  child.on('exit', (code, signal) => {
274
341
  this.#emulatorDown ??= `emulator ('${bin}') exited before boot (${signal ?? code ?? 'unknown'})`;
342
+ this.#emulator = null;
275
343
  });
276
344
  this.#emulator = child;
277
345
  }
278
- const deadline = Date.now() + this.#bootWaitMs;
346
+ const deadline = Date.now() + capWait(this.#bootWaitMs, timeoutMs);
279
347
  await this.#awaitDevice(deadline);
280
348
  for (;;) {
281
349
  const out = (await this.#adb.shell(['getprop', 'sys.boot_completed'])).trim();
282
350
  if (out === '1')
283
351
  break;
284
352
  if (Date.now() >= deadline) {
285
- throw new AdapterError(`android: emulator @${this.#config.avd} did not boot within ${this.#bootWaitMs}ms`);
353
+ throw new AdapterError(`android: emulator @${this.#config.avd} (${this.#serial}) did not boot within ${this.#bootWaitMs}ms`);
286
354
  }
287
355
  await delay(POLL_MS);
288
356
  }
289
357
  this.#booted = true;
290
358
  }
291
359
  /**
292
- * Bounded replacement for the unbounded `adb wait-for-device`: poll `get-state`
293
- * until a device answers, failing loud when the emulator died or the boot
294
- * deadline passed — a dead emulator must never hang `open` forever.
360
+ * Bounded replacement for the unbounded `adb wait-for-device`: poll `get-state` until
361
+ * a device answers, failing loud when the emulator died, the poll hit a real error
362
+ * ({@link pendingStateOrThrow}) or the deadline passed — never hang `open` forever.
295
363
  */
296
364
  async #awaitDevice(deadline) {
297
365
  for (;;) {
298
366
  if (this.#emulatorDown !== null) {
299
367
  throw new AdapterError(`android: ${this.#emulatorDown}`);
300
368
  }
301
- // `get-state` exits non-zero while no device is connected — that's "keep waiting".
302
- const state = await this.#adb.adb(['get-state']).catch(() => '');
369
+ // `get-state` exits non-zero while no device is connected — that alone is "keep
370
+ // waiting"; a missing `adb`, an ambiguous target or a wedged call surfaces now.
371
+ const state = await this.#adb.adb(['get-state']).catch(pendingStateOrThrow);
303
372
  if (state.trim() === 'device')
304
373
  return;
305
374
  if (Date.now() >= deadline) {
306
- throw new AdapterError(`android: no device appeared within ${this.#bootWaitMs}ms (emulator @${this.#config.avd})`);
375
+ throw new AdapterError(`android: no device appeared within ${this.#bootWaitMs}ms ` +
376
+ `(emulator @${this.#config.avd} on ${this.#serial})`);
307
377
  }
308
378
  await delay(POLL_MS);
309
379
  }