@developerz.ai/ui-debugger-mcp 1.1.0 → 1.3.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 (163) hide show
  1. package/README.md +45 -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 +16 -13
  21. package/dist/adapters/browser/browser-adapter.js +196 -313
  22. package/dist/adapters/browser/browser-adapter.js.map +1 -1
  23. package/dist/adapters/browser/cdp.d.ts +40 -2
  24. package/dist/adapters/browser/cdp.js +223 -19
  25. package/dist/adapters/browser/cdp.js.map +1 -1
  26. package/dist/adapters/browser/extractor.d.ts +53 -0
  27. package/dist/adapters/browser/extractor.js +224 -0
  28. package/dist/adapters/browser/extractor.js.map +1 -0
  29. package/dist/adapters/browser/filters.d.ts +15 -0
  30. package/dist/adapters/browser/filters.js +93 -0
  31. package/dist/adapters/browser/filters.js.map +1 -0
  32. package/dist/adapters/browser/launch.d.ts +41 -0
  33. package/dist/adapters/browser/launch.js +61 -0
  34. package/dist/adapters/browser/launch.js.map +1 -0
  35. package/dist/adapters/budget.d.ts +16 -0
  36. package/dist/adapters/budget.js +25 -0
  37. package/dist/adapters/budget.js.map +1 -0
  38. package/dist/adapters/contract.d.ts +82 -6
  39. package/dist/adapters/desktop/atspi.d.ts +15 -0
  40. package/dist/adapters/desktop/atspi.js +37 -17
  41. package/dist/adapters/desktop/atspi.js.map +1 -1
  42. package/dist/adapters/desktop/capture.js +8 -1
  43. package/dist/adapters/desktop/capture.js.map +1 -1
  44. package/dist/adapters/desktop/desktop-adapter.d.ts +9 -2
  45. package/dist/adapters/desktop/desktop-adapter.js +84 -32
  46. package/dist/adapters/desktop/desktop-adapter.js.map +1 -1
  47. package/dist/adapters/desktop/input.d.ts +16 -1
  48. package/dist/adapters/desktop/input.js +30 -0
  49. package/dist/adapters/desktop/input.js.map +1 -1
  50. package/dist/adapters/desktop/proc.d.ts +18 -3
  51. package/dist/adapters/desktop/proc.js +48 -5
  52. package/dist/adapters/desktop/proc.js.map +1 -1
  53. package/dist/adapters/factory.d.ts +3 -1
  54. package/dist/adapters/factory.js +6 -2
  55. package/dist/adapters/factory.js.map +1 -1
  56. package/dist/adapters/limit.d.ts +10 -0
  57. package/dist/adapters/limit.js +19 -0
  58. package/dist/adapters/limit.js.map +1 -0
  59. package/dist/agent/belt/act.d.ts +44 -9
  60. package/dist/agent/belt/act.js +176 -21
  61. package/dist/agent/belt/act.js.map +1 -1
  62. package/dist/agent/belt/look.d.ts +1 -1
  63. package/dist/agent/belt/look.js +31 -2
  64. package/dist/agent/belt/look.js.map +1 -1
  65. package/dist/agent/belt/observe.d.ts +42 -16
  66. package/dist/agent/belt/observe.js +134 -22
  67. package/dist/agent/belt/observe.js.map +1 -1
  68. package/dist/agent/belt/report.d.ts +29 -9
  69. package/dist/agent/belt/report.js +77 -10
  70. package/dist/agent/belt/report.js.map +1 -1
  71. package/dist/agent/belt/trail.d.ts +34 -0
  72. package/dist/agent/belt/trail.js +64 -0
  73. package/dist/agent/belt/trail.js.map +1 -0
  74. package/dist/agent/capabilities.d.ts +4 -4
  75. package/dist/agent/capabilities.js +41 -13
  76. package/dist/agent/capabilities.js.map +1 -1
  77. package/dist/agent/loop.d.ts +70 -21
  78. package/dist/agent/loop.js +146 -48
  79. package/dist/agent/loop.js.map +1 -1
  80. package/dist/agent/prompts/compose.d.ts +9 -1
  81. package/dist/agent/prompts/compose.js +5 -4
  82. package/dist/agent/prompts/compose.js.map +1 -1
  83. package/dist/agent/prompts/debug-agent.d.ts +13 -1
  84. package/dist/agent/prompts/debug-agent.js +98 -14
  85. package/dist/agent/prompts/debug-agent.js.map +1 -1
  86. package/dist/agent/prompts/desktop-addendum.d.ts +1 -1
  87. package/dist/agent/prompts/desktop-addendum.js +1 -1
  88. package/dist/agent/prompts/web-addendum.d.ts +1 -1
  89. package/dist/agent/prompts/web-addendum.js +84 -16
  90. package/dist/agent/prompts/web-addendum.js.map +1 -1
  91. package/dist/cli/control.d.ts +3 -1
  92. package/dist/cli/control.js +26 -40
  93. package/dist/cli/control.js.map +1 -1
  94. package/dist/cli/help.d.ts +3 -1
  95. package/dist/cli/help.js +6 -2
  96. package/dist/cli/help.js.map +1 -1
  97. package/dist/cli/init.d.ts +3 -6
  98. package/dist/cli/init.js +64 -16
  99. package/dist/cli/init.js.map +1 -1
  100. package/dist/config/fingerprint.d.ts +32 -0
  101. package/dist/config/fingerprint.js +47 -0
  102. package/dist/config/fingerprint.js.map +1 -0
  103. package/dist/config/load.d.ts +7 -1
  104. package/dist/config/load.js +17 -4
  105. package/dist/config/load.js.map +1 -1
  106. package/dist/config/schema.d.ts +12 -5
  107. package/dist/config/schema.js +17 -7
  108. package/dist/config/schema.js.map +1 -1
  109. package/dist/errors.d.ts +14 -2
  110. package/dist/errors.js +24 -4
  111. package/dist/errors.js.map +1 -1
  112. package/dist/index.d.ts +1 -1
  113. package/dist/index.js +1 -1
  114. package/dist/main.js +26 -8
  115. package/dist/main.js.map +1 -1
  116. package/dist/mcp/server.d.ts +16 -1
  117. package/dist/mcp/server.js +23 -2
  118. package/dist/mcp/server.js.map +1 -1
  119. package/dist/mcp/server.test-helpers.d.ts +23 -0
  120. package/dist/mcp/server.test-helpers.js +49 -0
  121. package/dist/mcp/server.test-helpers.js.map +1 -0
  122. package/dist/mcp/tools/describe.js +5 -0
  123. package/dist/mcp/tools/describe.js.map +1 -1
  124. package/dist/mcp/tools/end-session.js +5 -0
  125. package/dist/mcp/tools/end-session.js.map +1 -1
  126. package/dist/mcp/tools/get-findings.js +23 -3
  127. package/dist/mcp/tools/get-findings.js.map +1 -1
  128. package/dist/mcp/tools/output.d.ts +50 -0
  129. package/dist/mcp/tools/output.js +55 -0
  130. package/dist/mcp/tools/output.js.map +1 -0
  131. package/dist/mcp/tools/result.d.ts +24 -1
  132. package/dist/mcp/tools/result.js +106 -5
  133. package/dist/mcp/tools/result.js.map +1 -1
  134. package/dist/mcp/tools/send-message.js +5 -0
  135. package/dist/mcp/tools/send-message.js.map +1 -1
  136. package/dist/mcp/tools/start-debug.js +7 -1
  137. package/dist/mcp/tools/start-debug.js.map +1 -1
  138. package/dist/services/debug-service.d.ts +47 -8
  139. package/dist/services/debug-service.js +185 -14
  140. package/dist/services/debug-service.js.map +1 -1
  141. package/dist/services/session-builder.d.ts +20 -3
  142. package/dist/services/session-builder.js +43 -13
  143. package/dist/services/session-builder.js.map +1 -1
  144. package/dist/services/summarize.d.ts +1 -1
  145. package/dist/services/summarize.js +8 -1
  146. package/dist/services/summarize.js.map +1 -1
  147. package/dist/session/atomic-write.d.ts +24 -0
  148. package/dist/session/atomic-write.js +39 -0
  149. package/dist/session/atomic-write.js.map +1 -0
  150. package/dist/session/findings-store.js +3 -4
  151. package/dist/session/findings-store.js.map +1 -1
  152. package/dist/session/process-identity.d.ts +16 -0
  153. package/dist/session/process-identity.js +29 -0
  154. package/dist/session/process-identity.js.map +1 -1
  155. package/dist/session/session.js +36 -4
  156. package/dist/session/session.js.map +1 -1
  157. package/dist/session/state-file.d.ts +64 -5
  158. package/dist/session/state-file.js +76 -9
  159. package/dist/session/state-file.js.map +1 -1
  160. package/dist/session/workspace.d.ts +11 -0
  161. package/dist/session/workspace.js +14 -1
  162. package/dist/session/workspace.js.map +1 -1
  163. package/package.json +4 -1
@@ -18,11 +18,25 @@
18
18
  import { existsSync } from 'node:fs';
19
19
  import { URL } from 'node:url';
20
20
  import { chromium } from 'playwright-core';
21
- import { AdapterError } from '../../errors.js';
21
+ import { AdapterError, UiDebuggerError } from '../../errors.js';
22
+ import { capWait } from '../budget.js';
23
+ import { capToLimit } from '../limit.js';
22
24
  import { CdpCapture } from './cdp.js';
25
+ import { NODE_EXTRACTOR } from './extractor.js';
26
+ import { applyNodeFilters, centerWithin } from './filters.js';
27
+ import { closeOnFailure, createFailure } from './launch.js';
23
28
  import { normalizeQuery } from './query.js';
29
+ export { applyNodeFilters, NODE_FILTER_KEYS } from './filters.js';
24
30
  /** System Chrome channel used as the last resort when no binary can be resolved. */
25
31
  const DEFAULT_CHANNEL = 'chrome';
32
+ /**
33
+ * Playwright's own defaults for launching/connecting and for a navigation, restated
34
+ * so the run budget can only SHORTEN them (`capWait`). Left implicit, these two sit
35
+ * OUTSIDE the caller's cap and a `start_debug` with `timeout: 10` could still burn a
36
+ * minute before the driver takes its first step.
37
+ */
38
+ const LAUNCH_TIMEOUT_MS = 30_000;
39
+ const NAV_TIMEOUT_MS = 30_000;
26
40
  /** Detect the Playwright-managed Chromium binary; null if it isn't installed. */
27
41
  function detectManagedChromium() {
28
42
  try {
@@ -56,203 +70,6 @@ const DEFAULT_LIMIT = 200;
56
70
  const DEFAULT_SCROLL_STEP = 600;
57
71
  /** Interactive + semantic elements `readState` surfaces when no `query` is given. */
58
72
  const DEFAULT_SELECTOR = 'a[href], button, input, select, textarea, [role], [tabindex], [onclick], [contenteditable="true"], summary, label, h1, h2, h3, h4, h5, h6, [data-testid], p, img';
59
- /** Whitelisted `filters` keys for this adapter — anything else is rejected, not ignored. */
60
- export const NODE_FILTER_KEYS = [
61
- 'visible_eq',
62
- 'enabled_eq',
63
- 'role_in',
64
- 'name_contains',
65
- 'contrast_lt',
66
- ];
67
- /**
68
- * Browser-side element → {@link RawNode} extractor. Playwright serializes this and
69
- * runs it in the page, so it MUST stay self-contained: no module references, only
70
- * its params and nested locals. One batched call powers both `find` and
71
- * `readState`.
72
- */
73
- const NODE_EXTRACTOR = (elements) => {
74
- const clean = (s) => (s ?? '').replace(/\s+/g, ' ').trim();
75
- const parseColor = (value) => {
76
- const m = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)$/.exec(value ?? '');
77
- if (!m?.[1] || !m[2] || !m[3])
78
- return null;
79
- const rawAlpha = m[4];
80
- const a = rawAlpha === undefined
81
- ? 1
82
- : rawAlpha.endsWith('%')
83
- ? Number.parseFloat(rawAlpha) / 100
84
- : Number.parseFloat(rawAlpha);
85
- return {
86
- r: Number.parseFloat(m[1]),
87
- g: Number.parseFloat(m[2]),
88
- b: Number.parseFloat(m[3]),
89
- a,
90
- };
91
- };
92
- // The viewport canvas ("backplate") — the fallback background when no opaque
93
- // ancestor paints one. Browsers DARKEN this backplate for pages that opt into
94
- // `color-scheme: dark`, so hard-coding white would mis-judge contrast there.
95
- // Resolve the CSS system `Canvas` color under the root's used color scheme via
96
- // a throwaway probe (appended + removed in the same synchronous turn — never
97
- // painted), degrading to white when `Canvas` is unsupported. Cached: one probe
98
- // per extraction, not per node.
99
- let canvasFallback;
100
- const canvasBackground = (doc) => {
101
- if (canvasFallback)
102
- return canvasFallback;
103
- const probe = doc.createElement('div');
104
- probe.style.backgroundColor = 'Canvas';
105
- doc.documentElement.appendChild(probe);
106
- const resolved = parseColor(getComputedStyle(probe).backgroundColor);
107
- doc.documentElement.removeChild(probe);
108
- canvasFallback = resolved && resolved.a >= 0.99 ? resolved : { r: 255, g: 255, b: 255, a: 1 };
109
- return canvasFallback;
110
- };
111
- // Nearest opaque ancestor background; else the actual viewport canvas color.
112
- const effectiveBackground = (el) => {
113
- let node = el;
114
- while (node) {
115
- const bg = parseColor(getComputedStyle(node).backgroundColor);
116
- if (bg && bg.a >= 0.99)
117
- return bg;
118
- node = node.parentElement;
119
- }
120
- return canvasBackground(el.ownerDocument);
121
- };
122
- const luminance = (c) => {
123
- const chan = (v) => {
124
- const s = v / 255;
125
- return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
126
- };
127
- return 0.2126 * chan(c.r) + 0.7152 * chan(c.g) + 0.0722 * chan(c.b);
128
- };
129
- // WCAG ratio (1–21), with a translucent foreground blended over the background.
130
- const contrastRatio = (fg, bg) => {
131
- const blended = fg.a >= 1
132
- ? fg
133
- : {
134
- r: fg.r * fg.a + bg.r * (1 - fg.a),
135
- g: fg.g * fg.a + bg.g * (1 - fg.a),
136
- b: fg.b * fg.a + bg.b * (1 - fg.a),
137
- a: 1,
138
- };
139
- const l1 = luminance(blended);
140
- const l2 = luminance(bg);
141
- const hi = Math.max(l1, l2);
142
- const lo = Math.min(l1, l2);
143
- return Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100;
144
- };
145
- const implicitRole = (el) => {
146
- const tag = el.tagName.toLowerCase();
147
- if (tag === 'a')
148
- return el.hasAttribute('href') ? 'link' : 'generic';
149
- if (tag === 'select')
150
- return 'combobox';
151
- if (tag === 'textarea')
152
- return 'textbox';
153
- if (tag === 'input') {
154
- const type = (el.getAttribute('type') ?? 'text').toLowerCase();
155
- if (type === 'checkbox' || type === 'radio')
156
- return type;
157
- if (type === 'range')
158
- return 'slider';
159
- if (type === 'button' || type === 'submit' || type === 'reset' || type === 'image') {
160
- return 'button';
161
- }
162
- return 'textbox';
163
- }
164
- if (tag === 'button')
165
- return 'button';
166
- if (tag === 'img')
167
- return 'img';
168
- if (tag === 'nav')
169
- return 'navigation';
170
- if (tag === 'main')
171
- return 'main';
172
- if (tag === 'form')
173
- return 'form';
174
- if (tag === 'h1' ||
175
- tag === 'h2' ||
176
- tag === 'h3' ||
177
- tag === 'h4' ||
178
- tag === 'h5' ||
179
- tag === 'h6') {
180
- return 'heading';
181
- }
182
- return tag;
183
- };
184
- const accessibleName = (el) => {
185
- const label = clean(el.getAttribute('aria-label'));
186
- if (label)
187
- return label;
188
- const labelledby = el.getAttribute('aria-labelledby');
189
- if (labelledby) {
190
- const text = clean(labelledby
191
- .split(/\s+/)
192
- .map((id) => el.ownerDocument.getElementById(id)?.textContent ?? '')
193
- .join(' '));
194
- if (text)
195
- return text;
196
- }
197
- if (el.labels && el.labels.length > 0) {
198
- const text = clean(Array.from(el.labels)
199
- .map((l) => l.textContent ?? '')
200
- .join(' '));
201
- if (text)
202
- return text;
203
- }
204
- const placeholder = clean(el.getAttribute('placeholder'));
205
- if (placeholder)
206
- return placeholder;
207
- const alt = clean(el.getAttribute('alt'));
208
- if (alt)
209
- return alt;
210
- const text = clean(el.textContent);
211
- if (text)
212
- return text;
213
- const value = clean(el.getAttribute('value'));
214
- if (value)
215
- return value;
216
- return clean(el.getAttribute('title'));
217
- };
218
- return elements.map((el) => {
219
- const r = el.getBoundingClientRect();
220
- const style = getComputedStyle(el);
221
- const testid = clean(el.getAttribute('data-testid'));
222
- const text = clean(el.textContent);
223
- const node = {
224
- role: clean(el.getAttribute('role')) || implicitRole(el),
225
- name: accessibleName(el),
226
- bounds: {
227
- x: Math.round(r.x),
228
- y: Math.round(r.y),
229
- width: Math.round(r.width),
230
- height: Math.round(r.height),
231
- },
232
- enabled: el.disabled !== true && el.getAttribute('aria-disabled') !== 'true',
233
- visible: r.width > 0 &&
234
- r.height > 0 &&
235
- style.display !== 'none' &&
236
- style.visibility !== 'hidden' &&
237
- !el.hasAttribute('hidden') &&
238
- el.getAttribute('aria-hidden') !== 'true',
239
- };
240
- if (testid)
241
- node.testid = testid;
242
- if (text) {
243
- const fg = parseColor(style.color);
244
- if (fg) {
245
- const bg = effectiveBackground(el);
246
- node.style = {
247
- color: style.color,
248
- backgroundColor: `rgb(${bg.r}, ${bg.g}, ${bg.b})`,
249
- contrast: contrastRatio(fg, bg),
250
- };
251
- }
252
- }
253
- return node;
254
- });
255
- };
256
73
  /**
257
74
  * Resolve a navigate target against the configured base URL. Drivers often pass
258
75
  * a relative path (`/`, `/login`) — `page.goto` rejects those as "invalid URL",
@@ -328,85 +145,6 @@ export function scrollDelta(direction, amount) {
328
145
  }
329
146
  }
330
147
  }
331
- function expectBoolean(key, value) {
332
- if (typeof value !== 'boolean') {
333
- throw new AdapterError(`filter \`${key}\` expects a boolean`);
334
- }
335
- return value;
336
- }
337
- function expectString(key, value) {
338
- if (typeof value !== 'string') {
339
- throw new AdapterError(`filter \`${key}\` expects a string`);
340
- }
341
- return value;
342
- }
343
- function expectNumber(key, value) {
344
- if (typeof value !== 'number') {
345
- throw new AdapterError(`filter \`${key}\` expects a number`);
346
- }
347
- return value;
348
- }
349
- function expectStringArray(key, value) {
350
- if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {
351
- throw new AdapterError(`filter \`${key}\` expects a string[]`);
352
- }
353
- return value;
354
- }
355
- /**
356
- * Apply the whitelisted node `filters` in JS. Throws {@link AdapterError} on an
357
- * unknown key (no silent injection surface) or a wrong value type.
358
- */
359
- export function applyNodeFilters(nodes, filters) {
360
- if (!filters)
361
- return nodes;
362
- let out = nodes;
363
- for (const [key, value] of Object.entries(filters)) {
364
- switch (key) {
365
- case 'visible_eq': {
366
- const want = expectBoolean(key, value);
367
- out = out.filter((n) => n.visible === want);
368
- break;
369
- }
370
- case 'enabled_eq': {
371
- const want = expectBoolean(key, value);
372
- out = out.filter((n) => n.enabled === want);
373
- break;
374
- }
375
- case 'role_in': {
376
- const roles = expectStringArray(key, value);
377
- out = out.filter((n) => roles.includes(n.role));
378
- break;
379
- }
380
- case 'name_contains': {
381
- const needle = expectString(key, value).toLowerCase();
382
- out = out.filter((n) => n.name.toLowerCase().includes(needle));
383
- break;
384
- }
385
- case 'contrast_lt': {
386
- // Keep only VISIBLE text nodes whose contrast is BELOW the threshold —
387
- // the one-call "find unreadable text" sweep runs without `visible_eq`,
388
- // so hidden nodes with coincidentally low contrast must drop out here or
389
- // they surface as false "hard-to-read text" findings (nodes without
390
- // style drop out too).
391
- const threshold = expectNumber(key, value);
392
- out = out.filter((n) => n.visible && n.style?.contrast !== undefined && n.style.contrast < threshold);
393
- break;
394
- }
395
- default:
396
- throw new AdapterError(`unknown filter \`${key}\` for browser adapter (allowed: ${NODE_FILTER_KEYS.join(', ')})`);
397
- }
398
- }
399
- return out;
400
- }
401
- /** True when a node's center sits inside `region` — used to scope by a {@link Node} `within`. */
402
- function centerWithin(node, region) {
403
- const cx = node.bounds.x + node.bounds.width / 2;
404
- const cy = node.bounds.y + node.bounds.height / 2;
405
- return (cx >= region.x &&
406
- cx <= region.x + region.width &&
407
- cy >= region.y &&
408
- cy <= region.y + region.height);
409
- }
410
148
  /** Drop the internal `visible` flag — the public contract returns plain {@link Node}s. */
411
149
  function toNode(node) {
412
150
  const out = {
@@ -419,8 +157,54 @@ function toNode(node) {
419
157
  out.testid = node.testid;
420
158
  if (node.style)
421
159
  out.style = node.style;
160
+ if (node.frame)
161
+ out.frame = node.frame;
162
+ // Empty string and `false` are real answers here ("the field is empty", "the box
163
+ // is unchecked") — test for presence, never truthiness.
164
+ if (node.value !== undefined)
165
+ out.value = node.value;
166
+ if (node.checked !== undefined)
167
+ out.checked = node.checked;
422
168
  return out;
423
169
  }
170
+ /**
171
+ * Where a frame's viewport sits in page coordinates: `{x:0,y:0}` for the main
172
+ * document, the iframe element's position for a child, `null` when the frame is
173
+ * gone or not rendered (detached, `display:none`) and must be skipped.
174
+ */
175
+ async function frameOffset(frame) {
176
+ if (frame.parentFrame() === null)
177
+ return { x: 0, y: 0 };
178
+ try {
179
+ const element = await frame.frameElement();
180
+ const box = await element.boundingBox();
181
+ return box ? { x: box.x, y: box.y } : null;
182
+ }
183
+ catch {
184
+ return null; // detached between listing and reading
185
+ }
186
+ }
187
+ /**
188
+ * Translate a node read inside a frame into page coordinates and stamp which
189
+ * frame it came from.
190
+ *
191
+ * Bounds arrive relative to the frame's own viewport; clicks dispatch against
192
+ * the page. Without the shift, every click on embedded content would land at the
193
+ * wrong place on the page — silently, since the coordinates stay plausible.
194
+ */
195
+ function placeInPage(node, offset, frame) {
196
+ if (frame.parentFrame() === null)
197
+ return node;
198
+ return {
199
+ ...node,
200
+ bounds: {
201
+ ...node.bounds,
202
+ x: node.bounds.x + offset.x,
203
+ y: node.bounds.y + offset.y,
204
+ },
205
+ frame: frame.url(),
206
+ };
207
+ }
424
208
  /**
425
209
  * The web {@link Adapter}: a Playwright-driven Chrome page. Construct via
426
210
  * {@link BrowserAdapter.create} (async launch/connect can't live in a constructor).
@@ -428,6 +212,7 @@ function toNode(node) {
428
212
  export class BrowserAdapter {
429
213
  #config;
430
214
  #context;
215
+ /** The tab currently driven — reassigned by {@link BrowserAdapter.selectTab}. */
431
216
  #page;
432
217
  #browser;
433
218
  #mode;
@@ -442,32 +227,51 @@ export class BrowserAdapter {
442
227
  }
443
228
  /** Open the adapter: attach over `cdpUrl` when set, else launch a managed persistent context. */
444
229
  static async create(init) {
445
- return init.config.cdpUrl
446
- ? BrowserAdapter.#attach(init.config, init.onLog)
447
- : BrowserAdapter.#launch(init.config, init.profileDir, init.onLog);
230
+ const { cdpUrl } = init.config;
231
+ const launcher = init.chromium ?? chromium;
232
+ // Nothing raw escapes: launch, connect and post-connect wiring all leave here as
233
+ // AdapterError (header contract). Cleanup of a half-built adapter happens below.
234
+ const wait = capWait(LAUNCH_TIMEOUT_MS, init.timeoutMs);
235
+ try {
236
+ return cdpUrl
237
+ ? await BrowserAdapter.#attach(init.config, launcher, wait, init.onLog)
238
+ : await BrowserAdapter.#launch(init.config, init.profileDir, launcher, wait, init.onLog);
239
+ }
240
+ catch (error) {
241
+ throw createFailure(error, cdpUrl ? { mode: 'attach', cdpUrl } : { mode: 'managed', profileDir: init.profileDir });
242
+ }
448
243
  }
449
- static async #launch(config, profileDir, onLog) {
244
+ static async #launch(config, profileDir, launcher, timeout, onLog) {
450
245
  // Still CDP: Playwright drives Chromium exclusively over the DevTools Protocol
451
246
  // (here a CDP pipe; `#attach` uses a CDP WebSocket). A persistent context is the
452
247
  // supported way to own a Chrome process WITH the per-project profile — both
453
248
  // managed and attach speak the same protocol, only the transport differs.
454
- const context = await chromium.launchPersistentContext(profileDir, {
249
+ const context = await launcher.launchPersistentContext(profileDir, {
455
250
  headless: config.headless,
251
+ timeout,
456
252
  ...resolveLaunchBinary(config),
457
253
  });
458
- const page = context.pages()[0] ?? (await context.newPage());
459
- const capture = BrowserAdapter.#startCapture(page, onLog);
460
- return new BrowserAdapter({ config, context, page, browser: null, mode: 'managed', capture });
254
+ // Chrome is LIVE from here on and holds the profile lock — a throw past this point
255
+ // must close it, or every later run of this project fails to launch.
256
+ return closeOnFailure(context, async () => {
257
+ const page = context.pages()[0] ?? (await context.newPage());
258
+ const capture = BrowserAdapter.#startCapture(page, onLog);
259
+ return new BrowserAdapter({ config, context, page, browser: null, mode: 'managed', capture });
260
+ });
461
261
  }
462
- static async #attach(config, onLog) {
262
+ static async #attach(config, launcher, timeout, onLog) {
463
263
  if (!config.cdpUrl) {
464
264
  throw new AdapterError('attach mode requires `cdpUrl`');
465
265
  }
466
- const browser = await chromium.connectOverCDP(config.cdpUrl);
467
- const context = browser.contexts()[0] ?? (await browser.newContext());
468
- const page = context.pages()[0] ?? (await context.newPage());
469
- const capture = BrowserAdapter.#startCapture(page, onLog);
470
- return new BrowserAdapter({ config, context, page, browser, mode: 'attach', capture });
266
+ const browser = await launcher.connectOverCDP(config.cdpUrl, { timeout });
267
+ // Cleanup here drops the CONNECTION only — same disconnect semantics `close()`
268
+ // relies on, so a failed attach never stops a browser we did not start.
269
+ return closeOnFailure(browser, async () => {
270
+ const context = browser.contexts()[0] ?? (await browser.newContext());
271
+ const page = context.pages()[0] ?? (await context.newPage());
272
+ const capture = BrowserAdapter.#startCapture(page, onLog);
273
+ return new BrowserAdapter({ config, context, page, browser, mode: 'attach', capture });
274
+ });
471
275
  }
472
276
  /** Wire console/network capture onto the live page before the first navigation. */
473
277
  static #startCapture(page, onLog) {
@@ -475,12 +279,13 @@ export class BrowserAdapter {
475
279
  capture.start();
476
280
  return capture;
477
281
  }
478
- async open(target) {
282
+ async open(target, timeoutMs) {
479
283
  // Resolution lives inside `#run` so URL failures surface as AdapterError too.
480
284
  await this.#run('open', async () => {
481
285
  const resolved = resolveTargetUrl(target, this.#config.url);
482
286
  const url = appendDebugLogin(resolved, this.#config.debugLogin);
483
- await this.#page.goto(url);
287
+ // The first navigation spends the run's budget, not a fresh 30s of its own.
288
+ await this.#page.goto(url, { timeout: capWait(NAV_TIMEOUT_MS, timeoutMs) });
484
289
  });
485
290
  }
486
291
  async find(opts) {
@@ -492,7 +297,7 @@ export class BrowserAdapter {
492
297
  async click(target) {
493
298
  await this.#run('click', async () => {
494
299
  if (typeof target === 'string') {
495
- await this.#page.locator(normalizeQuery(target)).first().click();
300
+ await (await this.#locate(target)).click();
496
301
  return;
497
302
  }
498
303
  await this.#clickBoundsCenter(target);
@@ -504,7 +309,7 @@ export class BrowserAdapter {
504
309
  // than `fill()` so it appends like the coordinate path instead of replacing.
505
310
  await this.#run('type', async () => {
506
311
  if (typeof target === 'string') {
507
- await this.#page.locator(normalizeQuery(target)).first().click();
312
+ await (await this.#locate(target)).click();
508
313
  }
509
314
  else {
510
315
  await this.#clickBoundsCenter(target);
@@ -513,16 +318,20 @@ export class BrowserAdapter {
513
318
  });
514
319
  }
515
320
  /**
516
- * Coordinate click at a {@link Node}'s bounds center, shared by `click` and
517
- * `type`. Bounds are viewport-relative, so an off-screen center would make CDP
518
- * click nothing — fail loud instead so the agent knows to scroll first.
321
+ * Center of `bounds`, asserted on-screen. Bounds are viewport-relative, so CDP
322
+ * mouse events at an off-screen center land on nothing — silently. Fail loud
323
+ * instead so the agent knows to scroll it into view first.
519
324
  */
520
- async #clickBoundsCenter(node) {
521
- const { x, y, width, height } = node.bounds;
522
- const center = { x: x + width / 2, y: y + height / 2 };
325
+ #centerInViewport(bounds) {
326
+ const center = { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
523
327
  if (isOutsideViewport(center, this.#page.viewportSize())) {
524
328
  throw new AdapterError(`element center (${Math.round(center.x)}, ${Math.round(center.y)}) is outside the viewport — scroll it into view first, then re-read its bounds`);
525
329
  }
330
+ return center;
331
+ }
332
+ /** Coordinate click at a {@link Node}'s bounds center, shared by `click` and `type`. */
333
+ async #clickBoundsCenter(node) {
334
+ const center = this.#centerInViewport(node.bounds);
526
335
  await this.#page.mouse.click(center.x, center.y);
527
336
  }
528
337
  async pressKey(key) {
@@ -542,9 +351,11 @@ export class BrowserAdapter {
542
351
  // Scope: park the cursor over the region first, so the wheel event targets the
543
352
  // scrollable element under it instead of the viewport. No scope → wheel where
544
353
  // the mouse already is (`Input.dispatchMouseEvent` of type `mouseWheel`).
354
+ // Same viewport guard as the coordinate click: an off-screen region would
355
+ // move the cursor nowhere and scroll the viewport instead — silently wrong.
545
356
  if (opts.within !== undefined) {
546
- const { x, y, width, height } = await this.#regionBox(opts.within);
547
- await this.#page.mouse.move(x + width / 2, y + height / 2);
357
+ const center = this.#centerInViewport(await this.#regionBox(opts.within));
358
+ await this.#page.mouse.move(center.x, center.y);
548
359
  }
549
360
  await this.#page.mouse.wheel(dx, dy);
550
361
  });
@@ -597,24 +408,94 @@ export class BrowserAdapter {
597
408
  await this.#context.close();
598
409
  });
599
410
  }
600
- /** Build, scope, filter, and cap the normalized node list shared by `find`/`readState`. */
411
+ /**
412
+ * Build, scope, filter, and cap the normalized node list shared by `find`/`readState`.
413
+ *
414
+ * Reads EVERY frame of the page, not just the main document: a page-level
415
+ * locator stops at an iframe boundary, so anything embedded (payment fields,
416
+ * editors, consent screens) was previously invisible — the agent saw an empty
417
+ * region and had no way to learn why. Child-frame bounds are translated into
418
+ * page coordinates, so a coordinate click needs no frame awareness at all.
419
+ */
601
420
  async #collect(opts, defaultLimit) {
602
421
  // Agent queries are role+name / plain text (what the tree shows), not raw CSS —
603
422
  // normalize them onto a Playwright engine; an absent query reads the default set.
604
423
  const selector = opts.query ? normalizeQuery(opts.query) : DEFAULT_SELECTOR;
605
- const scope = typeof opts.within === 'string'
606
- ? this.#page.locator(normalizeQuery(opts.within))
607
- : this.#page;
608
- let nodes = await scope.locator(selector).evaluateAll(NODE_EXTRACTOR);
424
+ const within = typeof opts.within === 'string' ? normalizeQuery(opts.within) : undefined;
425
+ let nodes = [];
426
+ for (const frame of this.#page.frames()) {
427
+ const offset = await frameOffset(frame);
428
+ // A frame that detached mid-read (navigation, ad slot recycling) is not an
429
+ // error — it is one document out of many, and the rest still answer.
430
+ if (offset === null)
431
+ continue;
432
+ const scope = within ? frame.locator(within) : frame;
433
+ let found;
434
+ try {
435
+ found = await scope.locator(selector).evaluateAll(NODE_EXTRACTOR);
436
+ }
437
+ catch {
438
+ continue;
439
+ }
440
+ nodes.push(...found.map((node) => placeInPage(node, offset, frame)));
441
+ }
609
442
  if (opts.within && typeof opts.within !== 'string') {
610
443
  const region = opts.within.bounds;
611
444
  nodes = nodes.filter((n) => centerWithin(n, region));
612
445
  }
613
446
  nodes = applyNodeFilters(nodes, opts.filters);
614
- const limit = opts.limit ?? defaultLimit;
615
- if (limit !== undefined)
616
- nodes = nodes.slice(0, limit);
617
- return nodes.map(toNode);
447
+ return capToLimit(nodes, opts.limit ?? defaultLimit).map(toNode);
448
+ }
449
+ /**
450
+ * A locator for `selector` in whichever frame actually contains it — the main
451
+ * document first, then every child frame.
452
+ *
453
+ * `page.locator()` never crosses into an iframe, so a selector copied straight
454
+ * off an embedded node would simply fail to resolve. Falling back through the
455
+ * frames keeps `act` working on a target the agent can plainly see in the tree.
456
+ */
457
+ async #locate(selector) {
458
+ const normalized = normalizeQuery(selector);
459
+ const frames = this.#page.frames();
460
+ for (const frame of frames) {
461
+ const locator = frame.locator(normalized).first();
462
+ try {
463
+ if ((await locator.count()) > 0)
464
+ return locator;
465
+ }
466
+ catch {
467
+ // Detached frame — try the next one.
468
+ }
469
+ }
470
+ // Nothing matched anywhere: hand back the main-frame locator so the caller's
471
+ // own action reports the miss with Playwright's message, as it always did.
472
+ return this.#page.locator(normalized).first();
473
+ }
474
+ async tabs() {
475
+ return this.#run('tabs', async () => {
476
+ const pages = this.#context.pages();
477
+ return Promise.all(pages.map(async (page, index) => ({
478
+ index,
479
+ url: page.url(),
480
+ // A tab opened a moment ago may not have a document yet.
481
+ title: await page.title().catch(() => ''),
482
+ active: page === this.#page,
483
+ })));
484
+ });
485
+ }
486
+ async selectTab(index) {
487
+ await this.#run('selectTab', async () => {
488
+ const pages = this.#context.pages();
489
+ const page = pages[index];
490
+ if (!page) {
491
+ throw new AdapterError(`no tab at index ${index} — ${pages.length} open (0…${Math.max(0, pages.length - 1)})`);
492
+ }
493
+ this.#page = page;
494
+ // Capture is page-scoped: without this the new tab records no console or
495
+ // network activity at all, while the old one keeps recording unseen.
496
+ this.#capture.rebind(page);
497
+ await page.bringToFront();
498
+ });
618
499
  }
619
500
  /** Resolve a scroll `within` scope to an on-screen rectangle (Node bounds, or a located selector). */
620
501
  async #regionBox(within) {
@@ -632,7 +513,9 @@ export class BrowserAdapter {
632
513
  return await fn();
633
514
  }
634
515
  catch (error) {
635
- throw new AdapterError(`browser.${op} failed: ${error instanceof Error ? error.message : String(error)}`);
516
+ if (error instanceof UiDebuggerError)
517
+ throw error;
518
+ throw new AdapterError(`browser.${op} failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
636
519
  }
637
520
  }
638
521
  }