@developerz.ai/ui-debugger-mcp 1.10.0 → 1.11.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 (178) hide show
  1. package/README.md +9 -5
  2. package/dist/adapters/android/abortable.d.ts +6 -0
  3. package/dist/adapters/android/abortable.js +22 -0
  4. package/dist/adapters/android/abortable.js.map +1 -0
  5. package/dist/adapters/android/android-adapter.d.ts +7 -39
  6. package/dist/adapters/android/android-adapter.js +54 -436
  7. package/dist/adapters/android/android-adapter.js.map +1 -1
  8. package/dist/adapters/android/commands.d.ts +10 -0
  9. package/dist/adapters/android/commands.js +22 -0
  10. package/dist/adapters/android/commands.js.map +1 -1
  11. package/dist/adapters/android/emulator.d.ts +41 -0
  12. package/dist/adapters/android/emulator.js +115 -0
  13. package/dist/adapters/android/emulator.js.map +1 -0
  14. package/dist/adapters/android/logcat.d.ts +87 -0
  15. package/dist/adapters/android/logcat.js +352 -0
  16. package/dist/adapters/android/logcat.js.map +1 -0
  17. package/dist/adapters/browser/browser-adapter.js +30 -42
  18. package/dist/adapters/browser/browser-adapter.js.map +1 -1
  19. package/dist/adapters/browser/cdp.d.ts +7 -10
  20. package/dist/adapters/browser/cdp.js +93 -69
  21. package/dist/adapters/browser/cdp.js.map +1 -1
  22. package/dist/adapters/browser/exchange-read.d.ts +39 -0
  23. package/dist/adapters/browser/exchange-read.js +102 -0
  24. package/dist/adapters/browser/exchange-read.js.map +1 -0
  25. package/dist/adapters/browser/extractor.js +9 -2
  26. package/dist/adapters/browser/extractor.js.map +1 -1
  27. package/dist/adapters/browser/lifecycle.d.ts +33 -0
  28. package/dist/adapters/browser/lifecycle.js +47 -4
  29. package/dist/adapters/browser/lifecycle.js.map +1 -1
  30. package/dist/adapters/browser/locate.d.ts +18 -2
  31. package/dist/adapters/browser/locate.js +48 -3
  32. package/dist/adapters/browser/locate.js.map +1 -1
  33. package/dist/adapters/browser/log-filters.d.ts +1 -1
  34. package/dist/adapters/browser/log-filters.js +15 -4
  35. package/dist/adapters/browser/log-filters.js.map +1 -1
  36. package/dist/adapters/browser/log-format.d.ts +12 -0
  37. package/dist/adapters/browser/log-format.js +123 -7
  38. package/dist/adapters/browser/log-format.js.map +1 -1
  39. package/dist/adapters/contract.d.ts +22 -5
  40. package/dist/adapters/desktop/atspi-busctl.js +3 -1
  41. package/dist/adapters/desktop/atspi-busctl.js.map +1 -1
  42. package/dist/adapters/desktop/atspi.d.ts +6 -0
  43. package/dist/adapters/desktop/atspi.js.map +1 -1
  44. package/dist/adapters/desktop/desktop-adapter.d.ts +2 -0
  45. package/dist/adapters/desktop/desktop-adapter.js +132 -98
  46. package/dist/adapters/desktop/desktop-adapter.js.map +1 -1
  47. package/dist/adapters/desktop/input.d.ts +1 -1
  48. package/dist/adapters/desktop/input.js +14 -3
  49. package/dist/adapters/desktop/input.js.map +1 -1
  50. package/dist/adapters/desktop/managed-app.d.ts +43 -0
  51. package/dist/adapters/desktop/managed-app.js +114 -0
  52. package/dist/adapters/desktop/managed-app.js.map +1 -0
  53. package/dist/adapters/desktop/proc.d.ts +2 -0
  54. package/dist/adapters/desktop/proc.js +4 -0
  55. package/dist/adapters/desktop/proc.js.map +1 -1
  56. package/dist/adapters/desktop/wait-poll.d.ts +17 -0
  57. package/dist/adapters/desktop/wait-poll.js +38 -0
  58. package/dist/adapters/desktop/wait-poll.js.map +1 -0
  59. package/dist/adapters/factory.d.ts +1 -1
  60. package/dist/adapters/factory.js +1 -1
  61. package/dist/adapters/log-format.d.ts +6 -0
  62. package/dist/adapters/log-format.js +10 -2
  63. package/dist/adapters/log-format.js.map +1 -1
  64. package/dist/agent/belt/act.d.ts +6 -3
  65. package/dist/agent/belt/act.js +40 -60
  66. package/dist/agent/belt/act.js.map +1 -1
  67. package/dist/agent/belt/look.d.ts +9 -3
  68. package/dist/agent/belt/look.js +21 -5
  69. package/dist/agent/belt/look.js.map +1 -1
  70. package/dist/agent/belt/observe.d.ts +9 -43
  71. package/dist/agent/belt/observe.js +66 -242
  72. package/dist/agent/belt/observe.js.map +1 -1
  73. package/dist/agent/belt/redact-output.d.ts +20 -0
  74. package/dist/agent/belt/redact-output.js +70 -0
  75. package/dist/agent/belt/redact-output.js.map +1 -0
  76. package/dist/agent/belt/same-origin.d.ts +21 -0
  77. package/dist/agent/belt/same-origin.js +38 -0
  78. package/dist/agent/belt/same-origin.js.map +1 -0
  79. package/dist/agent/belt/target-refs.d.ts +39 -0
  80. package/dist/agent/belt/target-refs.js +60 -0
  81. package/dist/agent/belt/target-refs.js.map +1 -0
  82. package/dist/agent/belt/tree-targets.d.ts +79 -0
  83. package/dist/agent/belt/tree-targets.js +242 -0
  84. package/dist/agent/belt/tree-targets.js.map +1 -0
  85. package/dist/agent/loop-frames.d.ts +26 -0
  86. package/dist/agent/loop-frames.js +106 -0
  87. package/dist/agent/loop-frames.js.map +1 -0
  88. package/dist/agent/loop.d.ts +13 -24
  89. package/dist/agent/loop.js +40 -104
  90. package/dist/agent/loop.js.map +1 -1
  91. package/dist/agent/prompts/debug-agent.js +3 -2
  92. package/dist/agent/prompts/debug-agent.js.map +1 -1
  93. package/dist/agent/prompts/web-addendum.d.ts +2 -2
  94. package/dist/agent/prompts/web-addendum.js +21 -32
  95. package/dist/agent/prompts/web-addendum.js.map +1 -1
  96. package/dist/agent/provider.d.ts +3 -1
  97. package/dist/agent/provider.js +4 -2
  98. package/dist/agent/provider.js.map +1 -1
  99. package/dist/boot.js +3 -1
  100. package/dist/boot.js.map +1 -1
  101. package/dist/cli/chromium-libs.d.ts +6 -1
  102. package/dist/cli/chromium-libs.js +27 -3
  103. package/dist/cli/chromium-libs.js.map +1 -1
  104. package/dist/cli/control.js +30 -5
  105. package/dist/cli/control.js.map +1 -1
  106. package/dist/config/load.js +10 -0
  107. package/dist/config/load.js.map +1 -1
  108. package/dist/config/schema.js +12 -10
  109. package/dist/config/schema.js.map +1 -1
  110. package/dist/errors.d.ts +17 -16
  111. package/dist/errors.js +33 -32
  112. package/dist/errors.js.map +1 -1
  113. package/dist/index.d.ts +1 -1
  114. package/dist/index.js +1 -1
  115. package/dist/mcp/server.js +10 -1
  116. package/dist/mcp/server.js.map +1 -1
  117. package/dist/mcp/tools/end-session.js +2 -1
  118. package/dist/mcp/tools/end-session.js.map +1 -1
  119. package/dist/mcp/tools/output.d.ts +7 -0
  120. package/dist/mcp/tools/output.js +5 -0
  121. package/dist/mcp/tools/output.js.map +1 -1
  122. package/dist/mcp/tools/result.js +4 -1
  123. package/dist/mcp/tools/result.js.map +1 -1
  124. package/dist/redact.d.ts +20 -4
  125. package/dist/redact.js +134 -19
  126. package/dist/redact.js.map +1 -1
  127. package/dist/services/auth-persona.d.ts +19 -0
  128. package/dist/services/auth-persona.js +32 -0
  129. package/dist/services/auth-persona.js.map +1 -0
  130. package/dist/services/debug-api.d.ts +7 -0
  131. package/dist/services/debug-service.d.ts +1 -1
  132. package/dist/services/debug-service.js +64 -65
  133. package/dist/services/debug-service.js.map +1 -1
  134. package/dist/services/foreign-findings.d.ts +22 -0
  135. package/dist/services/foreign-findings.js +38 -0
  136. package/dist/services/foreign-findings.js.map +1 -0
  137. package/dist/services/login-failure.d.ts +10 -0
  138. package/dist/services/login-failure.js +24 -0
  139. package/dist/services/login-failure.js.map +1 -0
  140. package/dist/services/login-selectors.d.ts +18 -0
  141. package/dist/services/login-selectors.js +44 -0
  142. package/dist/services/login-selectors.js.map +1 -0
  143. package/dist/services/login-session.d.ts +25 -0
  144. package/dist/services/login-session.js +59 -0
  145. package/dist/services/login-session.js.map +1 -0
  146. package/dist/services/login.d.ts +9 -27
  147. package/dist/services/login.js +78 -80
  148. package/dist/services/login.js.map +1 -1
  149. package/dist/services/replay.js +15 -3
  150. package/dist/services/replay.js.map +1 -1
  151. package/dist/services/session-builder.js +19 -4
  152. package/dist/services/session-builder.js.map +1 -1
  153. package/dist/services/shutdown.d.ts +8 -4
  154. package/dist/services/shutdown.js +21 -8
  155. package/dist/services/shutdown.js.map +1 -1
  156. package/dist/services/start-guards.d.ts +6 -1
  157. package/dist/services/start-guards.js +13 -2
  158. package/dist/services/start-guards.js.map +1 -1
  159. package/dist/session/cleanup.d.ts +3 -2
  160. package/dist/session/cleanup.js +6 -2
  161. package/dist/session/cleanup.js.map +1 -1
  162. package/dist/session/finalize.d.ts +45 -0
  163. package/dist/session/finalize.js +150 -0
  164. package/dist/session/finalize.js.map +1 -0
  165. package/dist/session/flock-backend.d.ts +117 -0
  166. package/dist/session/flock-backend.js +293 -0
  167. package/dist/session/flock-backend.js.map +1 -0
  168. package/dist/session/owner-lock.d.ts +4 -95
  169. package/dist/session/owner-lock.js +7 -288
  170. package/dist/session/owner-lock.js.map +1 -1
  171. package/dist/session/session.js +11 -134
  172. package/dist/session/session.js.map +1 -1
  173. package/dist/session/state-file.js +9 -1
  174. package/dist/session/state-file.js.map +1 -1
  175. package/dist/session/workspace.d.ts +32 -2
  176. package/dist/session/workspace.js +65 -4
  177. package/dist/session/workspace.js.map +1 -1
  178. package/package.json +8 -8
@@ -21,188 +21,46 @@
21
21
  import { spawn } from 'node:child_process';
22
22
  import { AdapterError, UiDebuggerError } from '../../errors.js';
23
23
  import { capWait } from '../budget.js';
24
+ import { abortable } from './abortable.js';
24
25
  // Both managed adapters kill a detached group the same way — one implementation, in the
25
26
  // subprocess plumbing module.
26
- import { terminateGroup } from '../desktop/proc.js';
27
- import { formatConsoleLine } from '../log-format.js';
28
- import { AdbCli, pendingStateOrThrow } from './adb.js';
29
- import { expectOnScreen, keyArgs, parseScreenSize, scrollSwipe, splitTextForInput, splitTextLines, startArgs, swipeArgs, tapArgs, tapPointOf, textArgs, } from './commands.js';
27
+ import { AdbCli } from './adb.js';
28
+ import { assertPng, expectOnScreen, keyArgs, parseScreenSize, scrollSwipe, splitTextForInput, splitTextLines, startArgs, swipeArgs, tapArgs, tapPointOf, textArgs, } from './commands.js';
29
+ import { awaitBooted, delay, ManagedEmulator, POLL_MS } from './emulator.js';
30
30
  import { emulatorLaunchArgs } from './launch.js';
31
+ import { applyLogFilters, LogcatCoverage, parseRawLogcat, toConsoleEntry } from './logcat.js';
31
32
  import { emulatorSerial, pickEmulatorPort } from './ports.js';
32
33
  import { resolveEmulatorBin } from './sdk.js';
33
34
  import { AdbUiAutomator, shapeNodes } from './uiautomator.js';
34
35
  /** Default cap on `readState` so the tree stays small (overridable via `limit`). */
35
36
  const DEFAULT_LIMIT = 200;
36
- /** `waitFor` defaults — poll the hierarchy for a query until it appears or times out. */
37
37
  const DEFAULT_WAIT_MS = 5000;
38
- const POLL_MS = 300;
39
38
  /** How long managed boot waits for `sys.boot_completed` before failing loud. */
40
39
  const BOOT_WAIT_MS = 120_000;
41
40
  /** Default logcat window (lines) read per `console` call — reading never clears the log. */
42
41
  const LOGCAT_TAIL = 500;
43
- /**
44
- * Cap on the retained console-coverage keys — the raw keys of the covered rows
45
- * still remembered individually. Bounded no matter how long the run or how wide
46
- * a one-off `limit` was. Trimming a span's oldest keys does NOT forget their
47
- * coverage: the rows stay covered as the span's `below` count, anchored by the
48
- * span's first retained key (a drain reaching them still contains that key —
49
- * the logcat buffer drops rows oldest first, and the anchor is newer).
50
- */
51
- const MAX_COVERED_KEYS = 4096;
52
- const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
53
- /** Android logcat priority letter → normalized console {@link ConsoleEntry} level. */
54
- const LOGCAT_LEVEL = {
55
- V: 'log',
56
- D: 'debug',
57
- I: 'info',
58
- W: 'warn',
59
- E: 'error',
60
- F: 'error',
61
- };
62
- /** The occurrence identity of a raw row: the whole record, at full precision. */
63
- function rawRowKey(row) {
64
- return `${row.time}|${row.pid}|${row.tid}|${row.priority}|${row.tag}|${row.text}`;
65
- }
66
- /** True when `needle` appears in `hay` contiguously starting at `start`. */
67
- function matchesAt(hay, start, needle) {
68
- for (let i = 0; i < needle.length; i++) {
69
- if (hay[start + i] !== needle[i])
70
- return false;
71
- }
72
- return true;
73
- }
74
- /** True when the last `r` entries of `covered` equal the first `r` of `keys`. */
75
- function overlapAtHead(covered, keys, r) {
76
- for (let i = 0; i < r; i++) {
77
- if (covered[covered.length - r + i] !== keys[i])
78
- return false;
79
- }
80
- return true;
81
- }
82
- /** The raw epoch time a row key starts with — `1546300800.000|1000|…` → 1546300800. */
83
- function keyTime(key) {
84
- return Number(key.slice(0, key.indexOf('|')));
85
- }
86
- /** Merge the hits' covered ranges into one sorted, disjoint union (overlaps fold). */
87
- function unionOfRanges(hits) {
88
- const sorted = [...hits].sort((a, b) => a.from - b.from || a.to - b.to);
89
- const out = [];
90
- for (const hit of sorted) {
91
- const last = out[out.length - 1];
92
- if (last !== undefined && hit.from <= last.to + 1) {
93
- last.to = Math.max(last.to, hit.to);
94
- }
95
- else {
96
- out.push({ from: hit.from, to: hit.to });
97
- }
98
- }
99
- return out;
100
- }
101
- /** `1546300800.000 1000 1000 I Tag: message` — unmatched lines are skipped. */
102
- const LOGCAT_ROW = /^\s*(\d+)\.(\d+)\s+(\d+)\s+(\d+)\s+([VDIWEF])\s+([^:]*):\s?(.*)$/;
103
- /** Parse `logcat -v epoch` output into raw rows (oldest first, as emitted). */
104
- export function parseRawLogcat(raw) {
105
- const out = [];
106
- for (const line of raw.split('\n')) {
107
- const match = LOGCAT_ROW.exec(line);
108
- if (!match)
109
- continue;
110
- const [, sec, frac, pid, tid, priority, tag, text] = match;
111
- if (sec === undefined ||
112
- frac === undefined ||
113
- pid === undefined ||
114
- tid === undefined ||
115
- priority === undefined ||
116
- text === undefined) {
117
- continue;
118
- }
119
- out.push({ time: `${sec}.${frac}`, pid, tid, priority, tag: (tag ?? '').trim(), text });
120
- }
121
- return out;
122
- }
123
- /** Normalize a raw row onto the adapter-agnostic {@link ConsoleEntry} shape. */
124
- function toConsoleEntry(row) {
125
- return {
126
- level: LOGCAT_LEVEL[row.priority] ?? 'log',
127
- text: row.text,
128
- location: row.tag === '' ? undefined : row.tag,
129
- timestamp: Math.round(Number(row.time) * 1000),
130
- };
131
- }
132
- /**
133
- * Parse `logcat -v epoch` output into {@link ConsoleEntry}s (oldest first, as emitted).
134
- * Line shape: `1546300800.000 1000 1000 I Tag: message` — unmatched lines are skipped.
135
- */
136
- export function parseLogcat(raw) {
137
- return parseRawLogcat(raw).map(toConsoleEntry);
138
- }
139
- /** Apply the whitelisted console `filters` (logcat). Loud on an unknown key or wrong type. */
140
- export function applyLogFilters(entries, filters) {
141
- if (!filters)
142
- return entries;
143
- let out = entries;
144
- for (const [key, value] of Object.entries(filters)) {
145
- switch (key) {
146
- case 'level_eq': {
147
- if (typeof value !== 'string')
148
- throw new AdapterError('filter `level_eq` expects a string');
149
- out = out.filter((e) => e.level === value);
150
- break;
151
- }
152
- case 'level_in': {
153
- if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {
154
- throw new AdapterError('filter `level_in` expects a string[]');
155
- }
156
- out = out.filter((e) => value.includes(e.level));
157
- break;
158
- }
159
- case 'text_contains': {
160
- if (typeof value !== 'string') {
161
- throw new AdapterError('filter `text_contains` expects a string');
162
- }
163
- const needle = value.toLowerCase();
164
- out = out.filter((e) => e.text.toLowerCase().includes(needle));
165
- break;
166
- }
167
- default:
168
- throw new AdapterError(`unknown filter \`${key}\` for android console (allowed: level_eq, level_in, text_contains)`);
169
- }
170
- }
171
- return out;
172
- }
42
+ // Public path stays stable: the logcat helpers and the spawn seam type moved to siblings.
43
+ export { applyLogFilters, parseLogcat, parseRawLogcat } from './logcat.js';
173
44
  /**
174
45
  * The android {@link Adapter}: an ADB + uiautomator pair behind one contract.
175
46
  * Construct via {@link AndroidAdapter.create}.
176
47
  */
177
48
  export class AndroidAdapter {
178
- /**
179
- * The native selector grammar — the uiautomator parser this adapter's
180
- * `find`/`click`/`type` accept: `role "name"` or a bare `resource-id`/name
181
- * substring, and nothing else. Declared here, not derived from the absence of
182
- * `tabs`: the dialect is the grammar, and the grammar is the adapter's own.
183
- */
49
+ /** The native grammar `find`/`click`/`type` accept: `role "name"` or a bare id/name substring. */
184
50
  selectorDialect = 'native';
185
51
  #config;
186
52
  #bind;
187
53
  #attach;
188
- #spawn;
189
54
  #bootWaitMs;
190
55
  #pickPort;
191
56
  #resolveBin;
192
57
  #onLog;
193
- /**
194
- * The covered runs: disjoint spans of raw keys — every row the durable trail
195
- * already holds, oldest first, capped at {@linkcode MAX_COVERED_KEYS} retained
196
- * keys (see {@linkcode AndroidAdapter.streamRows} and
197
- * {@linkcode AndroidAdapter.capCoverage}).
198
- */
199
- #covered = [];
58
+ /** Durable-trail dedup state — which logcat rows the capture sink already holds. */
59
+ #coverage = new LogcatCoverage();
200
60
  #transport;
201
61
  /** The device every call is bound to (`emulator-<port>` once managed boot picks one). */
202
62
  #serial;
203
- #emulator = null;
204
- /** Why the managed emulator process is unusable (launch failure / early exit), or null. */
205
- #emulatorDown = null;
63
+ #emulator;
206
64
  #booted;
207
65
  #screen = null;
208
66
  constructor(handles) {
@@ -211,7 +69,7 @@ export class AndroidAdapter {
211
69
  this.#bind = handles.bind;
212
70
  this.#attach = handles.attach;
213
71
  this.#serial = handles.serial;
214
- this.#spawn = handles.spawn;
72
+ this.#emulator = new ManagedEmulator(handles.spawn);
215
73
  this.#bootWaitMs = handles.bootWaitMs;
216
74
  this.#pickPort = handles.pickPort;
217
75
  this.#resolveBin = handles.resolveBin;
@@ -273,7 +131,15 @@ export class AndroidAdapter {
273
131
  // One absolute deadline for the whole open: the managed boot poll AND the
274
132
  // post-boot activity start share it, so neither can outlive the caller's budget.
275
133
  const deadline = Date.now() + capWait(this.#bootWaitMs, timeoutMs);
276
- await this.#ensureBooted(deadline);
134
+ try {
135
+ await this.#ensureBooted(deadline);
136
+ }
137
+ catch (error) {
138
+ // A boot that failed (timeout, early exit, bad adb) must not leave the emulator
139
+ // we spawned running with nothing owning it: release it on this path too.
140
+ await this.#teardown().catch(() => undefined);
141
+ throw error;
142
+ }
277
143
  if (target.trim() !== '') {
278
144
  await this.#adb.shell(startArgs(target), deadline);
279
145
  this.#assertBefore(deadline, 'android: activity start');
@@ -334,7 +200,7 @@ export class AndroidAdapter {
334
200
  });
335
201
  }
336
202
  async screenshot() {
337
- return this.#run('screenshot', () => this.#adb.execOut(['screencap', '-p']));
203
+ return this.#run('screenshot', async () => assertPng(await this.#adb.execOut(['screencap', '-p'])));
338
204
  }
339
205
  async waitFor(opts) {
340
206
  if (opts.networkIdle) {
@@ -345,9 +211,13 @@ export class AndroidAdapter {
345
211
  throw new AdapterError('waitFor requires `query` (android has no networkIdle)');
346
212
  }
347
213
  const timeout = opts.timeout ?? DEFAULT_WAIT_MS;
348
- await this.#run('waitFor', async () => {
214
+ const { signal } = opts;
215
+ // Raised outside `#run`, which would re-wrap an abort and lose its `AbortError` name.
216
+ await abortable(signal, `android: waitFor aborted (${query})`, () => this.#run('waitFor', async () => {
349
217
  const deadline = Date.now() + timeout;
350
- for (;;) {
218
+ // An in-flight dump can't be cancelled (no transport cancel) but is capped by
219
+ // `deadline`; the loop stops right after it.
220
+ while (signal?.aborted !== true) {
351
221
  if (await this.#present(query, deadline)) {
352
222
  // A node that only appeared AFTER the deadline is a timeout, not a success:
353
223
  // the wait's promise is "the node is there NOW", and by then it is not.
@@ -359,7 +229,7 @@ export class AndroidAdapter {
359
229
  }
360
230
  await delay(POLL_MS);
361
231
  }
362
- });
232
+ }));
363
233
  }
364
234
  /**
365
235
  * One deadline-bounded poll for `query`. The wait's deadline goes **into** the dump:
@@ -390,213 +260,11 @@ export class AndroidAdapter {
390
260
  // The durable trail is the RAW record: every drained row is streamed before
391
261
  // filters/limit narrow the returned view — the browser's capture-then-filter
392
262
  // posture, on the same sink.
393
- this.#streamRows(rows);
263
+ this.#coverage.stream(rows, this.#onLog);
394
264
  const entries = applyLogFilters(rows.map(toConsoleEntry).reverse(), opts.filters);
395
265
  return opts.limit !== undefined ? entries.slice(0, opts.limit) : entries;
396
266
  });
397
267
  }
398
- /**
399
- * Stream the drained logcat rows to the capture sink — one formatted line per row.
400
- *
401
- * The sink is the run's redacting durable writer (the session layer binds it);
402
- * the adapter itself never writes to disk. `logcat -t N` re-dumps the same tail
403
- * on every read, so the durable trail would otherwise repeat it — coverage
404
- * prevents that without an ever-growing row set:
405
- *
406
- * Drains are chronological tails of one append-only log: each is a contiguous
407
- * run of rows, and the log's newest row only moves forward. What the trail
408
- * already holds is therefore a set of DISJOINT covered runs —
409
- * {@linkcode CoveredSpan}, oldest first — and this drain decides each of its
410
- * rows by locating every span inside it ({@linkcode AndroidAdapter.spanHit}):
411
- *
412
- * - the span's retained keys found as one contiguous block of the drain →
413
- * the block and the span's rows directly below it are covered → skipped;
414
- * rows above the block sit below the earlier tail's cutoff, never drained
415
- * → streamed now (a wider `limit` back-fills them, once);
416
- * - the drain found inside a span's retained keys (a narrower read of an
417
- * already-covered stretch) → the whole drain is covered → skipped;
418
- * - only the span's key suffix found at the drain's head (the span
419
- * straddles the drain's cutoff — a narrower drain, the span's oldest rows
420
- * slid out of the buffer, or fresh rows arrived past it) → that overlap
421
- * is skipped, everything after it streams;
422
- * - no span located → the drain's rows are all fresh → they stream.
423
- *
424
- * Everything outside the covered ranges streams — the fresh suffix, back-fill
425
- * below an earlier cutoff, AND the unseen middle of a drain that bridged two
426
- * disjoint spans. Matching whole key SEQUENCES — never a boundary key — keeps
427
- * byte-identical records honest: a drain holding two copies of one record ends
428
- * on the second copy, and only a sequence match finds it; a first-key
429
- * `findIndex` would stop at the first copy and re-stream the rest. Under a
430
- * fully periodic drain an overlap is genuinely ambiguous; the earliest
431
- * (largest-skip) match wins, which never duplicates: two rows sharing a raw
432
- * key format to the same trail line, so a skipped twin loses no content.
433
- *
434
- * After the drain its whole extent is covered (every row streamed or
435
- * skipped), so it merges into one span — absorbing the spans it bridged,
436
- * keeping a straddling span's retained rows on either side of the drain, and
437
- * filing spans wholly below or above it where they were — and
438
- * {@linkcode AndroidAdapter.capCoverage} bounds the retained keys, folding
439
- * the oldest into the span's `below` count without forgetting their coverage.
440
- *
441
- * A failing sink never fails the read.
442
- */
443
- #streamRows(rows) {
444
- const sink = this.#onLog;
445
- const oldest = rows[0];
446
- if (sink === undefined || oldest === undefined)
447
- return;
448
- const keys = rows.map(rawRowKey);
449
- // Locate every covered span inside this drain, and file the spans it does
450
- // not touch: disjoint from the drain, a span sits wholly below it (older
451
- // than the drain's oldest row) or wholly above (newer than its newest).
452
- const hits = [];
453
- const below = [];
454
- const above = [];
455
- const drainStart = keyTime(rawRowKey(oldest));
456
- for (const span of this.#covered) {
457
- const hit = this.#spanHit(span, keys);
458
- if (hit !== null) {
459
- hits.push(hit);
460
- continue;
461
- }
462
- const newest = span.keys[span.keys.length - 1];
463
- if (newest !== undefined && keyTime(newest) < drainStart)
464
- below.push(span);
465
- else
466
- above.push(span);
467
- }
468
- // Stream every row outside the union of the covered ranges.
469
- const ranges = unionOfRanges(hits);
470
- let cursor = 0;
471
- for (const [index, row] of rows.entries()) {
472
- let range = ranges[cursor];
473
- while (range !== undefined && range.to < index) {
474
- cursor++;
475
- range = ranges[cursor];
476
- }
477
- if (range !== undefined && index >= range.from)
478
- continue;
479
- try {
480
- sink('console', formatConsoleLine(toConsoleEntry(row)));
481
- }
482
- catch (error) {
483
- // A sink failure must not crash the read — the entries still come back.
484
- console.error(`android capture sink failed: ${error instanceof Error ? error.message : String(error)}`);
485
- }
486
- }
487
- // The drain's whole extent is covered now — every row streamed or skipped —
488
- // so it becomes one span. A straddling span's retained rows stay remembered
489
- // on either side of the drain; when several spans straddle (fully periodic
490
- // content), the most coverage kept wins, which never duplicates.
491
- let belowAnchored = 0;
492
- let headKeys = [];
493
- let tailKeys = [];
494
- for (const hit of hits) {
495
- if (hit.belowAnchored + hit.headKeys.length > belowAnchored + headKeys.length) {
496
- belowAnchored = hit.belowAnchored;
497
- headKeys = hit.headKeys;
498
- }
499
- if (hit.tailKeys.length > tailKeys.length)
500
- tailKeys = hit.tailKeys;
501
- }
502
- this.#covered = [
503
- ...below,
504
- { below: belowAnchored, keys: [...headKeys, ...keys, ...tailKeys] },
505
- ...above,
506
- ];
507
- this.#capCoverage();
508
- }
509
- /**
510
- * Locate one covered span inside this drain's keys (both oldest first).
511
- * Returns where the span's covered rows sit inside the drain — inclusive
512
- * `[from, to]` indexes plus the span's covered rows outside the drain — or
513
- * null when none of the span appears in it.
514
- */
515
- #spanHit(span, keys) {
516
- const m = span.keys.length;
517
- const n = keys.length;
518
- if (m === 0 || n === 0)
519
- return null;
520
- // The span's retained keys as one contiguous block of the drain — a drain
521
- // at least as wide as the span's retained window. Earliest alignment wins
522
- // (see the streamRows note). The span's rows below the block are covered
523
- // too: the retained ones are anchored by the block, the trimmed ones by the
524
- // span's `below` count.
525
- if (n >= m) {
526
- for (let i = 0; i + m <= n; i++) {
527
- if (matchesAt(keys, i, span.keys)) {
528
- return {
529
- from: Math.max(0, i - span.below),
530
- to: i + m - 1,
531
- belowAnchored: span.below - Math.min(span.below, i),
532
- headKeys: [],
533
- tailKeys: [],
534
- };
535
- }
536
- }
537
- }
538
- // The drain as one contiguous block of the span's retained keys — a
539
- // narrower read of an already-covered stretch. The whole drain is covered,
540
- // and the span's retained rows on either side of it stay covered.
541
- if (m >= n) {
542
- for (let q = 0; q + n <= m; q++) {
543
- if (matchesAt(span.keys, q, keys)) {
544
- return {
545
- from: 0,
546
- to: n - 1,
547
- belowAnchored: span.below,
548
- headKeys: span.keys.slice(0, q),
549
- tailKeys: span.keys.slice(q + n),
550
- };
551
- }
552
- }
553
- }
554
- // Otherwise the drain's head sits inside the span: its longest suffix that
555
- // matches the drain's prefix is the overlap (the span straddles the drain's
556
- // cutoff, or its oldest rows slid out of the buffer).
557
- for (let r = Math.min(m, n); r >= 1; r--) {
558
- if (overlapAtHead(span.keys, keys, r)) {
559
- return {
560
- from: 0,
561
- to: r - 1,
562
- belowAnchored: span.below,
563
- headKeys: span.keys.slice(0, m - r),
564
- tailKeys: [],
565
- };
566
- }
567
- }
568
- return null;
569
- }
570
- /**
571
- * Bound the retained coverage keys at {@linkcode MAX_COVERED_KEYS}, oldest
572
- * first. A span's trimmed keys stay covered as its `below` count — the rows
573
- * sit directly below the span's new first key, contiguous with it and
574
- * anchored by it, so a later drain reaching them still skips them. A span
575
- * always keeps one anchor key; when every span is down to its anchor and the
576
- * cap still bites, the oldest spans drop whole — by then their rows left the
577
- * logcat buffer long before (the anchor is newer, and the buffer drops rows
578
- * oldest first).
579
- */
580
- #capCoverage() {
581
- let total = this.#covered.reduce((sum, span) => sum + span.keys.length, 0);
582
- for (const span of this.#covered) {
583
- if (total <= MAX_COVERED_KEYS)
584
- break;
585
- const droppable = span.keys.length - 1;
586
- if (droppable <= 0)
587
- continue;
588
- const drop = Math.min(droppable, total - MAX_COVERED_KEYS);
589
- span.below += drop;
590
- span.keys.splice(0, drop);
591
- total -= drop;
592
- }
593
- while (total > MAX_COVERED_KEYS && this.#covered.length > 1) {
594
- const dropped = this.#covered.shift();
595
- if (dropped === undefined)
596
- break;
597
- total -= dropped.keys.length;
598
- }
599
- }
600
268
  /** Android exposes no network channel over ADB — unsupported, surfaced loud. */
601
269
  async network() {
602
270
  throw new AdapterError('android target has no network channel over ADB (use a proxy; unsupported)');
@@ -609,27 +277,21 @@ export class AndroidAdapter {
609
277
  async close() {
610
278
  if (this.#attach)
611
279
  return;
612
- await this.#run('close', async () => {
613
- if (this.#booted && this.#transport) {
614
- // Best-effort console kill; the SIGTERM below is the hard backstop.
615
- await this.#transport.adb.adb(['emu', 'kill']).catch(() => undefined);
616
- }
617
- const pid = this.#emulator?.pid;
618
- this.#booted = false;
619
- this.#serial = null;
620
- this.#screen = null;
621
- // Drop the binding so a re-`open` binds to the next emulator, not the dead one.
622
- if (this.#bind)
623
- this.#transport = null;
624
- if (pid === undefined) {
625
- this.#emulator = null;
626
- return;
627
- }
628
- // SIGTERM the group, escalate to SIGKILL, and keep the handle until death is
629
- // confirmed — a dropped handle leaves a SIGTERM-ignoring emulator orphaned for good.
630
- await terminateGroup(pid);
631
- this.#emulator = null;
632
- });
280
+ await this.#run('close', () => this.#teardown());
281
+ }
282
+ /** Stop the emulator we started (console kill, then the process group) and unbind. */
283
+ async #teardown() {
284
+ if (this.#booted && this.#transport) {
285
+ // Best-effort console kill; the SIGTERM below is the hard backstop.
286
+ await this.#transport.adb.adb(['emu', 'kill']).catch(() => undefined);
287
+ }
288
+ this.#booted = false;
289
+ this.#serial = null;
290
+ this.#screen = null;
291
+ // Drop the binding so a re-`open` binds to the next emulator, not the dead one.
292
+ if (this.#bind)
293
+ this.#transport = null;
294
+ await this.#emulator.terminate();
633
295
  }
634
296
  /**
635
297
  * Managed boot: resolve the emulator binary first (`emulatorPath`, else SDK/PATH
@@ -637,13 +299,13 @@ export class AndroidAdapter {
637
299
  * launch `emulator @avd -port <p>` (once) and poll `sys.boot_completed`. The port
638
300
  * is picked free and bound **before** the spawn, so every later call (and the `close` kill)
639
301
  * targets the emulator we started, never a pre-existing one. No-op when attached; `deadline`
640
- * (the absolute instant the open's budget runs out) bounds both the device poll and the
641
- * `getprop` poll — a slow `adb` call can never push the boot past it.
302
+ * (the absolute instant the open's budget runs out) bounds the whole poll — a slow `adb`
303
+ * call can never push the boot past it.
642
304
  */
643
305
  async #ensureBooted(deadline) {
644
306
  if (this.#booted)
645
307
  return;
646
- if (!this.#emulator) {
308
+ if (!this.#emulator.running) {
647
309
  // Only managed mode needs an AVD — attach never reads it (hence optional in config).
648
310
  const avd = this.#config.avd;
649
311
  if (avd === undefined) {
@@ -658,68 +320,24 @@ export class AndroidAdapter {
658
320
  throw new AdapterError('android: no emulator binary found for managed boot — set `emulatorPath` on the ' +
659
321
  `target; searched: ${(resolved.searched ?? []).join(', ')}`);
660
322
  }
661
- const bin = resolved.bin;
662
323
  const port = await this.#pickPort();
663
324
  this.#serial = emulatorSerial(port);
664
325
  if (this.#bind)
665
326
  this.#transport = this.#bind(this.#serial);
666
- const child = this.#spawn(bin, emulatorLaunchArgs({
327
+ this.#emulator.start(resolved.bin, emulatorLaunchArgs({
667
328
  avd,
668
329
  port,
669
330
  headless: this.#config.headless,
670
331
  ...(this.#config.emulatorArgs ? { extraArgs: this.#config.emulatorArgs } : {}),
671
332
  }));
672
- this.#emulatorDown = null;
673
- // Both fire async (later tick): without a listener a bad `emulatorPath` would
674
- // crash the whole server via an unhandled 'error' event. Capture the failure
675
- // and let the boot poll below surface it as a loud AdapterError.
676
- child.on('error', (err) => {
677
- this.#emulatorDown = `emulator ('${bin}') failed to launch: ${err.message}`;
678
- this.#emulator = null;
679
- });
680
- child.on('exit', (code, signal) => {
681
- this.#emulatorDown ??= `emulator ('${bin}') exited before boot (${signal ?? code ?? 'unknown'})`;
682
- this.#emulator = null;
683
- });
684
- this.#emulator = child;
685
- }
686
- await this.#awaitDevice(deadline);
687
- for (;;) {
688
- const out = (await this.#adb.shell(['getprop', 'sys.boot_completed'], deadline)).trim();
689
- if (Date.now() >= deadline) {
690
- throw new AdapterError(`android: emulator @${this.#config.avd} (${this.#serial}) did not boot within ${this.#bootWaitMs}ms`);
691
- }
692
- if (out === '1')
693
- break;
694
- await delay(POLL_MS);
695
333
  }
334
+ await awaitBooted(this.#adb, this.#emulator, deadline, {
335
+ avd: this.#config.avd,
336
+ serial: this.#serial,
337
+ bootWaitMs: this.#bootWaitMs,
338
+ });
696
339
  this.#booted = true;
697
340
  }
698
- /**
699
- * Bounded replacement for the unbounded `adb wait-for-device`: poll `get-state` until
700
- * a device answers, failing loud when the emulator died, the poll hit a real error
701
- * ({@link pendingStateOrThrow}) or the deadline passed — never hang `open` forever.
702
- *
703
- * The `get-state` call carries the deadline: its own 30 s transport cap is shortened to
704
- * the time left, so a wedged `adb` cannot hold the boot past the caller's budget.
705
- */
706
- async #awaitDevice(deadline) {
707
- for (;;) {
708
- if (this.#emulatorDown !== null) {
709
- throw new AdapterError(`android: ${this.#emulatorDown}`);
710
- }
711
- // `get-state` exits non-zero while no device is connected — that alone is "keep
712
- // waiting"; a missing `adb`, an ambiguous target or a wedged call surfaces now.
713
- const state = await this.#adb.adb(['get-state'], deadline).catch(pendingStateOrThrow);
714
- if (Date.now() >= deadline) {
715
- throw new AdapterError(`android: no device appeared within ${this.#bootWaitMs}ms ` +
716
- `(emulator @${this.#config.avd} on ${this.#serial})`);
717
- }
718
- if (state.trim() === 'device')
719
- return;
720
- await delay(POLL_MS);
721
- }
722
- }
723
341
  /** Read (and cache) the device screen size for viewport scrolls. */
724
342
  async #screenSize() {
725
343
  if (this.#screen)