@developerz.ai/ui-debugger-mcp 1.9.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 (274) hide show
  1. package/README.md +63 -47
  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/adb.d.ts +19 -7
  6. package/dist/adapters/android/adb.js +50 -13
  7. package/dist/adapters/android/adb.js.map +1 -1
  8. package/dist/adapters/android/android-adapter.d.ts +20 -12
  9. package/dist/adapters/android/android-adapter.js +113 -165
  10. package/dist/adapters/android/android-adapter.js.map +1 -1
  11. package/dist/adapters/android/commands.d.ts +10 -0
  12. package/dist/adapters/android/commands.js +22 -0
  13. package/dist/adapters/android/commands.js.map +1 -1
  14. package/dist/adapters/android/emulator.d.ts +41 -0
  15. package/dist/adapters/android/emulator.js +115 -0
  16. package/dist/adapters/android/emulator.js.map +1 -0
  17. package/dist/adapters/android/logcat.d.ts +87 -0
  18. package/dist/adapters/android/logcat.js +352 -0
  19. package/dist/adapters/android/logcat.js.map +1 -0
  20. package/dist/adapters/android/ports.js.map +1 -1
  21. package/dist/adapters/android/sdk.d.ts +65 -0
  22. package/dist/adapters/android/sdk.js +107 -0
  23. package/dist/adapters/android/sdk.js.map +1 -0
  24. package/dist/adapters/android/uiautomator.d.ts +23 -7
  25. package/dist/adapters/android/uiautomator.js +31 -7
  26. package/dist/adapters/android/uiautomator.js.map +1 -1
  27. package/dist/adapters/availability.d.ts +39 -0
  28. package/dist/adapters/availability.js +62 -0
  29. package/dist/adapters/availability.js.map +1 -0
  30. package/dist/adapters/browser/browser-adapter.d.ts +11 -22
  31. package/dist/adapters/browser/browser-adapter.js +90 -71
  32. package/dist/adapters/browser/browser-adapter.js.map +1 -1
  33. package/dist/adapters/browser/cdp.d.ts +22 -17
  34. package/dist/adapters/browser/cdp.js +118 -72
  35. package/dist/adapters/browser/cdp.js.map +1 -1
  36. package/dist/adapters/browser/exchange-read.d.ts +39 -0
  37. package/dist/adapters/browser/exchange-read.js +102 -0
  38. package/dist/adapters/browser/exchange-read.js.map +1 -0
  39. package/dist/adapters/browser/extractor.js +9 -2
  40. package/dist/adapters/browser/extractor.js.map +1 -1
  41. package/dist/adapters/browser/filters.d.ts +1 -1
  42. package/dist/adapters/browser/filters.js.map +1 -1
  43. package/dist/adapters/browser/geometry.js.map +1 -1
  44. package/dist/adapters/browser/launch.d.ts +14 -5
  45. package/dist/adapters/browser/launch.js +14 -5
  46. package/dist/adapters/browser/launch.js.map +1 -1
  47. package/dist/adapters/browser/lifecycle.d.ts +91 -0
  48. package/dist/adapters/browser/lifecycle.js +141 -0
  49. package/dist/adapters/browser/lifecycle.js.map +1 -0
  50. package/dist/adapters/browser/locate.d.ts +18 -2
  51. package/dist/adapters/browser/locate.js +48 -3
  52. package/dist/adapters/browser/locate.js.map +1 -1
  53. package/dist/adapters/browser/log-filters.d.ts +2 -2
  54. package/dist/adapters/browser/log-filters.js +15 -4
  55. package/dist/adapters/browser/log-filters.js.map +1 -1
  56. package/dist/adapters/browser/log-format.d.ts +23 -20
  57. package/dist/adapters/browser/log-format.js +133 -56
  58. package/dist/adapters/browser/log-format.js.map +1 -1
  59. package/dist/adapters/browser/tab-context.d.ts +30 -0
  60. package/dist/adapters/browser/tab-context.js +41 -0
  61. package/dist/adapters/browser/tab-context.js.map +1 -0
  62. package/dist/adapters/contract.d.ts +113 -10
  63. package/dist/adapters/contract.js +7 -2
  64. package/dist/adapters/contract.js.map +1 -1
  65. package/dist/adapters/desktop/atspi-busctl.d.ts +26 -0
  66. package/dist/adapters/desktop/atspi-busctl.js +332 -0
  67. package/dist/adapters/desktop/atspi-busctl.js.map +1 -0
  68. package/dist/adapters/desktop/atspi-parse.d.ts +39 -0
  69. package/dist/adapters/desktop/atspi-parse.js +155 -0
  70. package/dist/adapters/desktop/atspi-parse.js.map +1 -0
  71. package/dist/adapters/desktop/atspi.d.ts +81 -50
  72. package/dist/adapters/desktop/atspi.js +64 -285
  73. package/dist/adapters/desktop/atspi.js.map +1 -1
  74. package/dist/adapters/desktop/capture.d.ts +11 -20
  75. package/dist/adapters/desktop/capture.js +68 -37
  76. package/dist/adapters/desktop/capture.js.map +1 -1
  77. package/dist/adapters/desktop/desktop-adapter.d.ts +22 -2
  78. package/dist/adapters/desktop/desktop-adapter.js +202 -86
  79. package/dist/adapters/desktop/desktop-adapter.js.map +1 -1
  80. package/dist/adapters/desktop/input.d.ts +19 -5
  81. package/dist/adapters/desktop/input.js +29 -13
  82. package/dist/adapters/desktop/input.js.map +1 -1
  83. package/dist/adapters/desktop/managed-app.d.ts +43 -0
  84. package/dist/adapters/desktop/managed-app.js +114 -0
  85. package/dist/adapters/desktop/managed-app.js.map +1 -0
  86. package/dist/adapters/desktop/proc.d.ts +34 -4
  87. package/dist/adapters/desktop/proc.js +37 -6
  88. package/dist/adapters/desktop/proc.js.map +1 -1
  89. package/dist/adapters/desktop/wait-poll.d.ts +17 -0
  90. package/dist/adapters/desktop/wait-poll.js +38 -0
  91. package/dist/adapters/desktop/wait-poll.js.map +1 -0
  92. package/dist/adapters/factory.d.ts +13 -6
  93. package/dist/adapters/factory.js +30 -4
  94. package/dist/adapters/factory.js.map +1 -1
  95. package/dist/adapters/log-format.d.ts +38 -0
  96. package/dist/adapters/log-format.js +47 -0
  97. package/dist/adapters/log-format.js.map +1 -0
  98. package/dist/agent/belt/act.d.ts +426 -23
  99. package/dist/agent/belt/act.js +44 -64
  100. package/dist/agent/belt/act.js.map +1 -1
  101. package/dist/agent/belt/look.d.ts +479 -16
  102. package/dist/agent/belt/look.js +94 -16
  103. package/dist/agent/belt/look.js.map +1 -1
  104. package/dist/agent/belt/observe.d.ts +652 -65
  105. package/dist/agent/belt/observe.js +119 -231
  106. package/dist/agent/belt/observe.js.map +1 -1
  107. package/dist/agent/belt/redact-output.d.ts +20 -0
  108. package/dist/agent/belt/redact-output.js +70 -0
  109. package/dist/agent/belt/redact-output.js.map +1 -0
  110. package/dist/agent/belt/report.d.ts +754 -48
  111. package/dist/agent/belt/report.js +121 -38
  112. package/dist/agent/belt/report.js.map +1 -1
  113. package/dist/agent/belt/same-origin.d.ts +21 -0
  114. package/dist/agent/belt/same-origin.js +38 -0
  115. package/dist/agent/belt/same-origin.js.map +1 -0
  116. package/dist/agent/belt/target-refs.d.ts +39 -0
  117. package/dist/agent/belt/target-refs.js +60 -0
  118. package/dist/agent/belt/target-refs.js.map +1 -0
  119. package/dist/agent/belt/trail.d.ts +44 -16
  120. package/dist/agent/belt/trail.js +46 -11
  121. package/dist/agent/belt/trail.js.map +1 -1
  122. package/dist/agent/belt/tree-targets.d.ts +79 -0
  123. package/dist/agent/belt/tree-targets.js +242 -0
  124. package/dist/agent/belt/tree-targets.js.map +1 -0
  125. package/dist/agent/capabilities.js.map +1 -1
  126. package/dist/agent/fallback.d.ts +33 -0
  127. package/dist/agent/fallback.js +84 -0
  128. package/dist/agent/fallback.js.map +1 -0
  129. package/dist/agent/loop-frames.d.ts +26 -0
  130. package/dist/agent/loop-frames.js +106 -0
  131. package/dist/agent/loop-frames.js.map +1 -0
  132. package/dist/agent/loop.d.ts +56 -65
  133. package/dist/agent/loop.js +122 -189
  134. package/dist/agent/loop.js.map +1 -1
  135. package/dist/agent/models.d.ts +10 -6
  136. package/dist/agent/models.js +15 -9
  137. package/dist/agent/models.js.map +1 -1
  138. package/dist/agent/prompts/compose.d.ts +1 -1
  139. package/dist/agent/prompts/debug-agent.js +48 -10
  140. package/dist/agent/prompts/debug-agent.js.map +1 -1
  141. package/dist/agent/prompts/web-addendum.d.ts +2 -2
  142. package/dist/agent/prompts/web-addendum.js +26 -25
  143. package/dist/agent/prompts/web-addendum.js.map +1 -1
  144. package/dist/agent/provider.d.ts +41 -1
  145. package/dist/agent/provider.js +59 -5
  146. package/dist/agent/provider.js.map +1 -1
  147. package/dist/boot.d.ts +64 -0
  148. package/dist/boot.js +147 -0
  149. package/dist/boot.js.map +1 -0
  150. package/dist/cli/chromium-libs.d.ts +267 -0
  151. package/dist/cli/chromium-libs.js +546 -0
  152. package/dist/cli/chromium-libs.js.map +1 -0
  153. package/dist/cli/control.js +79 -12
  154. package/dist/cli/control.js.map +1 -1
  155. package/dist/cli/init.d.ts +52 -3
  156. package/dist/cli/init.js +62 -10
  157. package/dist/cli/init.js.map +1 -1
  158. package/dist/config/load.d.ts +25 -8
  159. package/dist/config/load.js +50 -13
  160. package/dist/config/load.js.map +1 -1
  161. package/dist/config/schema.d.ts +18 -6
  162. package/dist/config/schema.js +34 -17
  163. package/dist/config/schema.js.map +1 -1
  164. package/dist/errors.d.ts +30 -15
  165. package/dist/errors.js +49 -30
  166. package/dist/errors.js.map +1 -1
  167. package/dist/findings/schema.d.ts +44 -6
  168. package/dist/findings/schema.js +39 -3
  169. package/dist/findings/schema.js.map +1 -1
  170. package/dist/index.d.ts +1 -1
  171. package/dist/index.js +1 -1
  172. package/dist/index.js.map +1 -1
  173. package/dist/main.js +4 -82
  174. package/dist/main.js.map +1 -1
  175. package/dist/mcp/server.js +10 -1
  176. package/dist/mcp/server.js.map +1 -1
  177. package/dist/mcp/tools/describe.d.ts +5 -4
  178. package/dist/mcp/tools/describe.js +14 -10
  179. package/dist/mcp/tools/describe.js.map +1 -1
  180. package/dist/mcp/tools/end-session.d.ts +3 -1
  181. package/dist/mcp/tools/end-session.js +8 -3
  182. package/dist/mcp/tools/end-session.js.map +1 -1
  183. package/dist/mcp/tools/output.d.ts +12 -4
  184. package/dist/mcp/tools/output.js +15 -2
  185. package/dist/mcp/tools/output.js.map +1 -1
  186. package/dist/mcp/tools/result.d.ts +10 -1
  187. package/dist/mcp/tools/result.js +12 -7
  188. package/dist/mcp/tools/result.js.map +1 -1
  189. package/dist/mcp/tools/start-debug.js +7 -5
  190. package/dist/mcp/tools/start-debug.js.map +1 -1
  191. package/dist/redact.d.ts +44 -0
  192. package/dist/redact.js +166 -0
  193. package/dist/redact.js.map +1 -0
  194. package/dist/services/auth-persona.d.ts +19 -0
  195. package/dist/services/auth-persona.js +32 -0
  196. package/dist/services/auth-persona.js.map +1 -0
  197. package/dist/services/catalog.d.ts +28 -0
  198. package/dist/services/catalog.js +65 -0
  199. package/dist/services/catalog.js.map +1 -0
  200. package/dist/services/debug-api.d.ts +179 -0
  201. package/dist/services/debug-api.js +9 -0
  202. package/dist/services/debug-api.js.map +1 -0
  203. package/dist/services/debug-service.d.ts +26 -174
  204. package/dist/services/debug-service.js +159 -227
  205. package/dist/services/debug-service.js.map +1 -1
  206. package/dist/services/foreign-findings.d.ts +22 -0
  207. package/dist/services/foreign-findings.js +38 -0
  208. package/dist/services/foreign-findings.js.map +1 -0
  209. package/dist/services/login-failure.d.ts +10 -0
  210. package/dist/services/login-failure.js +24 -0
  211. package/dist/services/login-failure.js.map +1 -0
  212. package/dist/services/login-selectors.d.ts +18 -0
  213. package/dist/services/login-selectors.js +44 -0
  214. package/dist/services/login-selectors.js.map +1 -0
  215. package/dist/services/login-session.d.ts +25 -0
  216. package/dist/services/login-session.js +59 -0
  217. package/dist/services/login-session.js.map +1 -0
  218. package/dist/services/login.d.ts +16 -29
  219. package/dist/services/login.js +269 -97
  220. package/dist/services/login.js.map +1 -1
  221. package/dist/services/replay.js +15 -3
  222. package/dist/services/replay.js.map +1 -1
  223. package/dist/services/retained-snapshot.d.ts +36 -0
  224. package/dist/services/retained-snapshot.js +63 -0
  225. package/dist/services/retained-snapshot.js.map +1 -0
  226. package/dist/services/session-builder.d.ts +26 -0
  227. package/dist/services/session-builder.js +63 -21
  228. package/dist/services/session-builder.js.map +1 -1
  229. package/dist/services/shutdown.d.ts +8 -4
  230. package/dist/services/shutdown.js +21 -8
  231. package/dist/services/shutdown.js.map +1 -1
  232. package/dist/services/start-guards.d.ts +37 -0
  233. package/dist/services/start-guards.js +61 -0
  234. package/dist/services/start-guards.js.map +1 -0
  235. package/dist/services/summarize.d.ts +12 -3
  236. package/dist/services/summarize.js +13 -5
  237. package/dist/services/summarize.js.map +1 -1
  238. package/dist/session/cleanup.d.ts +3 -2
  239. package/dist/session/cleanup.js +6 -2
  240. package/dist/session/cleanup.js.map +1 -1
  241. package/dist/session/finalize.d.ts +45 -0
  242. package/dist/session/finalize.js +150 -0
  243. package/dist/session/finalize.js.map +1 -0
  244. package/dist/session/findings-store.d.ts +2 -1
  245. package/dist/session/findings-store.js +30 -2
  246. package/dist/session/findings-store.js.map +1 -1
  247. package/dist/session/flock-backend.d.ts +117 -0
  248. package/dist/session/flock-backend.js +293 -0
  249. package/dist/session/flock-backend.js.map +1 -0
  250. package/dist/session/live-pointer.d.ts +19 -0
  251. package/dist/session/live-pointer.js +41 -0
  252. package/dist/session/live-pointer.js.map +1 -0
  253. package/dist/session/manager.d.ts +11 -1
  254. package/dist/session/manager.js +46 -2
  255. package/dist/session/manager.js.map +1 -1
  256. package/dist/session/owner-lock.d.ts +117 -0
  257. package/dist/session/owner-lock.js +218 -0
  258. package/dist/session/owner-lock.js.map +1 -0
  259. package/dist/session/process-identity.js.map +1 -1
  260. package/dist/session/session.js +40 -109
  261. package/dist/session/session.js.map +1 -1
  262. package/dist/session/state-file.d.ts +74 -14
  263. package/dist/session/state-file.js +211 -21
  264. package/dist/session/state-file.js.map +1 -1
  265. package/dist/session/workspace.d.ts +32 -2
  266. package/dist/session/workspace.js +65 -4
  267. package/dist/session/workspace.js.map +1 -1
  268. package/package.json +11 -11
  269. package/dist/adapters/android/android-adapter.test-helpers.d.ts +0 -52
  270. package/dist/adapters/android/android-adapter.test-helpers.js +0 -115
  271. package/dist/adapters/android/android-adapter.test-helpers.js.map +0 -1
  272. package/dist/mcp/server.test-helpers.d.ts +0 -23
  273. package/dist/mcp/server.test-helpers.js +0 -49
  274. package/dist/mcp/server.test-helpers.js.map +0 -1
@@ -1,38 +1,42 @@
1
1
  /**
2
- * Desktop screenshots — compositor-aware capture to PNG bytes.
3
- *
4
- * There is no universal Linux screen-capture API: naive X11 grabbers return BLACK
5
- * on Wayland (`idea/desktop-control.md`). So detect the session and dispatch —
6
- * **grim** on wlroots/Wayland, **scrot** on X11. Both write a temp PNG we read and
7
- * delete, keeping one uniform path. GNOME/KDE D-Bus + portal routes are future work.
8
- *
9
- * The picker + arg builders are pure and unit-tested; {@link Screenshot} is the
10
- * thin runner that shells out and fails loud as an {@link AdapterError}.
2
+ * Desktop screenshots — try X11, then Wayland when available. Environment hints
3
+ * do not prove compositor protocol support: only a successful capture does.
4
+ * Both routes write temporary PNGs; portal/D-Bus capture remains unimplemented.
11
5
  */
12
6
  import { mkdtemp, readFile, rm } from 'node:fs/promises';
13
7
  import { tmpdir } from 'node:os';
14
8
  import { join } from 'node:path';
15
- import { AdapterError } from '../../errors.js';
9
+ import { AdapterError, ExecTimeoutError } from '../../errors.js';
16
10
  import { desktopEnv, errMessage, makeExec } from './proc.js';
17
- /**
18
- * Capture cap — deliberately longer than `proc.ts`'s input/a11y default: a cold
19
- * grim/scrot encoding a hi-dpi PNG (plus a compositor round-trip on Wayland) is
20
- * legitimately slow, and one frame is worth waiting for. Still bounded: a wedged
21
- * capture must not park the run until the outer session timeout.
22
- */
11
+ /** One shared cap: fallback must not restart the capture budget. */
23
12
  const CAPTURE_TIMEOUT_MS = 30_000;
24
- /**
25
- * Pick the capture tool from the environment: Wayland (`WAYLAND_DISPLAY`) → grim,
26
- * X11 (`DISPLAY`) → scrot. Throws loud when neither is set — there is nothing to capture.
27
- */
28
- export function chooseCaptureTool(env) {
29
- if (env.WAYLAND_DISPLAY)
30
- return 'grim';
13
+ function captureTools(env) {
14
+ const tools = [];
31
15
  if (env.DISPLAY)
32
- return 'scrot';
33
- throw new AdapterError('desktop: cannot screenshot — neither WAYLAND_DISPLAY nor DISPLAY is set');
16
+ tools.push('scrot');
17
+ if (env.WAYLAND_DISPLAY)
18
+ tools.push('grim');
19
+ return tools;
20
+ }
21
+ function captureFailure(env, failures) {
22
+ const hints = ['XDG_CURRENT_DESKTOP', 'XDG_SESSION_DESKTOP', 'DESKTOP_SESSION']
23
+ .filter((key) => env[key])
24
+ .map((key) => `${key}=${env[key]}`)
25
+ .join(', ');
26
+ return new AdapterError(`desktop: screenshot capture infrastructure unavailable (not an application defect; ${hints || 'compositor/desktop unknown'}): ${failures.join('; ')}. ` +
27
+ 'grim requires a compositor supporting the Wayland screencopy protocol; portal/D-Bus capture is not implemented.');
34
28
  }
35
- /** Build the capture argv that writes a PNG to `file` (grim: positional · scrot: `--overwrite`). */
29
+ /** First route to try, not a claim that the display or backend is usable. */
30
+ export function chooseCaptureTool(env) {
31
+ const tool = captureTools(env)[0];
32
+ if (tool)
33
+ return tool;
34
+ throw captureFailure(env, [
35
+ 'scrot unavailable: DISPLAY is not set',
36
+ 'grim unavailable: WAYLAND_DISPLAY is not set',
37
+ ]);
38
+ }
39
+ /** Build the capture argv that writes a PNG to `file`. */
36
40
  export function captureArgs(tool, file) {
37
41
  switch (tool) {
38
42
  case 'grim':
@@ -45,26 +49,53 @@ export function captureArgs(tool, file) {
45
49
  }
46
50
  }
47
51
  }
48
- /** grim/scrot-backed {@link ScreenCapture}. Construct with a target `display` (or inject `exec`). */
52
+ /** grim/scrot-backed capture with injectable execution and clock for deterministic tests. */
49
53
  export class Screenshot {
50
54
  #env;
51
55
  #exec;
56
+ #now;
52
57
  constructor(init = {}) {
53
58
  this.#env = desktopEnv(init.display);
54
59
  this.#exec = init.exec ?? makeExec(this.#env, CAPTURE_TIMEOUT_MS);
60
+ this.#now = init.now ?? Date.now;
55
61
  }
56
- /** Capture the current frame as PNG bytes via a temp file (read then deleted). */
57
- async capture() {
58
- const tool = chooseCaptureTool(this.#env);
62
+ async capture(deadline) {
63
+ const end = Math.min(deadline ?? Infinity, this.#now() + CAPTURE_TIMEOUT_MS);
64
+ const checkDeadline = () => {
65
+ if (this.#now() >= end) {
66
+ throw new ExecTimeoutError(`desktop: screenshot capture at/after its deadline (${end})`);
67
+ }
68
+ };
69
+ const failures = [];
70
+ if (!this.#env.DISPLAY)
71
+ failures.push('scrot unavailable: DISPLAY is not set');
72
+ if (!this.#env.WAYLAND_DISPLAY)
73
+ failures.push('grim unavailable: WAYLAND_DISPLAY is not set');
74
+ const tools = captureTools(this.#env);
75
+ if (!tools.length)
76
+ throw captureFailure(this.#env, failures);
77
+ checkDeadline();
59
78
  const dir = await mkdtemp(join(tmpdir(), 'uidbg-shot-'));
60
- const file = join(dir, 'shot.png');
61
79
  try {
62
- await this.#exec(tool, captureArgs(tool, file));
63
- const buffer = await readFile(file);
64
- return new Uint8Array(buffer);
65
- }
66
- catch (error) {
67
- throw new AdapterError(`desktop.screenshot failed (${tool}): ${errMessage(error)}`);
80
+ for (const tool of tools) {
81
+ checkDeadline();
82
+ // Separate files prevent a failed route's partial output becoming fallback evidence.
83
+ const file = join(dir, `${tool}.png`);
84
+ try {
85
+ await this.#exec(tool, captureArgs(tool, file), { deadline: end });
86
+ checkDeadline();
87
+ const buffer = await readFile(file);
88
+ checkDeadline();
89
+ return new Uint8Array(buffer);
90
+ }
91
+ catch (error) {
92
+ if (error instanceof ExecTimeoutError)
93
+ throw error;
94
+ checkDeadline();
95
+ failures.push(`${tool} failed: ${errMessage(error)}`);
96
+ }
97
+ }
98
+ throw captureFailure(this.#env, failures);
68
99
  }
69
100
  finally {
70
101
  await rm(dir, { recursive: true, force: true });
@@ -1 +1 @@
1
- {"version":3,"file":"capture.js","sourceRoot":"","sources":["../../../src/adapters/desktop/capture.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAa,UAAU,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAExE;;;;;GAKG;AACH,MAAM,kBAA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AAE,CAAC;gBAChB,qFAAqF;gBACrF,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,MAAM,CAAC,CAAC;gBACtC,IAAI,CAAC;oBACH,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC,CAAC;oBACnE,aAAa,EAAE,CAAC;oBAChB,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;oBACpC,aAAa,EAAE,CAAC;oBAChB,OAAO,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;gBAChC,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,IAAI,KAAK,YAAY,gBAAgB;wBAAE,MAAM,KAAK,CAAC;oBACnD,aAAa,EAAE,CAAC;oBAChB,QAAQ,CAAC,IAAI,CAAC,GAAG,IAAI,YAAY,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACxD,CAAC;YACH,CAAC;YACD,MAAM,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC5C,CAAC;gBAAS,CAAC;YACT,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;CACF"}
@@ -9,14 +9,25 @@
9
9
  *
10
10
  * **Managed only**: the desktop target has no attach handle (unlike web `cdpUrl` /
11
11
  * android `adbSerial`), so `open` launches the configured command and `close` stops
12
- * it. Reads/clicks key off AT-SPI screen extents; vision fallback is future work.
12
+ * it. Reads/clicks/type key off the AT-SPI tree — its screen extents give the
13
+ * click coordinates. A custom-drawn surface (a canvas, a game, a custom widget)
14
+ * exposes no a11y node, so it is simply absent from the tree: `find`, `click` and
15
+ * `type` cannot reach it. There is no automatic vision/OCR fallback: this adapter
16
+ * has no OCR/pixel path, so the adapter never switches to pixels — a read yields
17
+ * tree nodes or nothing. Only the agent-level `look` can describe a frame.
18
+ *
19
+ * **Every read is scoped to one window.** The AT-SPI tree spans every application
20
+ * on the desktop, so an unscoped lookup for "Save" can resolve to another app's
21
+ * button and the click lands in the wrong window. The scope is the configured
22
+ * `window` when the target has one, else the window the last `open` selected;
23
+ * with neither, a read fails loud rather than reading the whole desktop.
13
24
  *
14
25
  * Desktop apps expose no console/network channels — those methods throw loud
15
26
  * ({@link AdapterError}), never a silent empty list. Every backend failure surfaces
16
27
  * as an {@link AdapterError}; our own loud errors pass through un-rewrapped.
17
28
  */
18
29
  import type { DesktopTarget } from '../../config/schema.js';
19
- import type { Adapter, ConsoleEntry, NetworkEntry, Node, NodeRef, Query, ScrollOptions, WaitOptions } from '../contract.js';
30
+ import type { Adapter, ConsoleEntry, NetworkEntry, Node, NodeRef, Query, ScrollOptions, SelectorDialect, WaitOptions } from '../contract.js';
20
31
  import { type AtspiSource } from './atspi.js';
21
32
  import { type ScreenCapture } from './capture.js';
22
33
  import { type PointerInput } from './input.js';
@@ -31,6 +42,8 @@ export interface DesktopAdapterInit {
31
42
  input?: PointerInput;
32
43
  /** Override the capture backend (defaults to {@link Screenshot}); a seam for tests. */
33
44
  capture?: ScreenCapture;
45
+ /** Wall-clock cap of one `readState` walk (defaults to {@link READ_WALK_MS}); a seam for tests. */
46
+ readWalkMs?: number;
34
47
  }
35
48
  /**
36
49
  * The desktop {@link Adapter}: an xdotool + AT-SPI2 + scrot/grim trio behind one
@@ -38,6 +51,13 @@ export interface DesktopAdapterInit {
38
51
  */
39
52
  export declare class DesktopAdapter implements Adapter {
40
53
  #private;
54
+ /**
55
+ * The native selector grammar — the AT-SPI parser this adapter's
56
+ * `find`/`click`/`type` accept: `role "name"` or a bare name substring, and
57
+ * nothing else. Declared here, not derived from the absence of `tabs`: the
58
+ * dialect is the grammar, and the grammar is the adapter's own.
59
+ */
60
+ readonly selectorDialect: SelectorDialect;
41
61
  private constructor();
42
62
  /** Wire the adapter from config, binding each backend to the chosen X11 display. */
43
63
  static create(init: DesktopAdapterInit): DesktopAdapter;
@@ -9,30 +9,51 @@
9
9
  *
10
10
  * **Managed only**: the desktop target has no attach handle (unlike web `cdpUrl` /
11
11
  * android `adbSerial`), so `open` launches the configured command and `close` stops
12
- * it. Reads/clicks key off AT-SPI screen extents; vision fallback is future work.
12
+ * it. Reads/clicks/type key off the AT-SPI tree — its screen extents give the
13
+ * click coordinates. A custom-drawn surface (a canvas, a game, a custom widget)
14
+ * exposes no a11y node, so it is simply absent from the tree: `find`, `click` and
15
+ * `type` cannot reach it. There is no automatic vision/OCR fallback: this adapter
16
+ * has no OCR/pixel path, so the adapter never switches to pixels — a read yields
17
+ * tree nodes or nothing. Only the agent-level `look` can describe a frame.
18
+ *
19
+ * **Every read is scoped to one window.** The AT-SPI tree spans every application
20
+ * on the desktop, so an unscoped lookup for "Save" can resolve to another app's
21
+ * button and the click lands in the wrong window. The scope is the configured
22
+ * `window` when the target has one, else the window the last `open` selected;
23
+ * with neither, a read fails loud rather than reading the whole desktop.
13
24
  *
14
25
  * Desktop apps expose no console/network channels — those methods throw loud
15
26
  * ({@link AdapterError}), never a silent empty list. Every backend failure surfaces
16
27
  * as an {@link AdapterError}; our own loud errors pass through un-rewrapped.
17
28
  */
18
- import { spawn } from 'node:child_process';
19
29
  import { AdapterError, UiDebuggerError } from '../../errors.js';
20
30
  import { capWait } from '../budget.js';
21
- import { BusctlAtspi, parseRoleNameQuery, shapeNodes } from './atspi.js';
31
+ import { BusctlAtspi, parseRoleNameQuery, shapeNodes, } from './atspi.js';
22
32
  import { Screenshot } from './capture.js';
23
33
  import { centerOf, clickPointOf, expectOnScreen, Xdotool, } from './input.js';
24
- import { desktopEnv, terminateGroup } from './proc.js';
34
+ import { ManagedApp, withWaylandHint } from './managed-app.js';
35
+ import { desktopEnv } from './proc.js';
36
+ import { abortError, pollUntilPresent } from './wait-poll.js';
25
37
  /** Default cap on `readState` so the tree stays small (overridable via `limit`). */
26
38
  const DEFAULT_LIMIT = 200;
39
+ /**
40
+ * Wall-clock cap on one `readState` walk. Every visited node costs ~4 busctl spawns, so a
41
+ * big tree (Electron with accessibility on) can run for minutes. The contract has no
42
+ * "truncated" marker on a node list, so a walk cut off by this cap fails loud rather than
43
+ * hand the driver a tree that silently stops partway.
44
+ */
45
+ const READ_WALK_MS = 30_000;
46
+ /** How many matches `find` inspects to prefer an exact name over a substring one. */
47
+ const FIND_CANDIDATES = 20;
48
+ /** Wall-clock cap on that ranking walk; on expiry `find` keeps its first (substring) hit. */
49
+ const FIND_RANK_MS = 3000;
27
50
  /** `waitFor` defaults — poll the a11y tree for a query until it appears or times out. */
28
51
  const DEFAULT_WAIT_MS = 5000;
29
- const POLL_MS = 500;
30
52
  /** How long `open` waits for the launched window to appear before failing loud. */
31
53
  const WINDOW_WAIT_MS = 10_000;
32
54
  /** Wheel-step calibration: pixels-per-click, and the default page-ish distance. */
33
55
  const SCROLL_STEP_PX = 120;
34
56
  const DEFAULT_SCROLL_AMOUNT = 360;
35
- const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
36
57
  /** Map a pixel scroll `amount` onto a positive integer count of wheel clicks. */
37
58
  export function scrollRepeat(amount) {
38
59
  return Math.max(1, Math.round((amount ?? DEFAULT_SCROLL_AMOUNT) / SCROLL_STEP_PX));
@@ -42,18 +63,45 @@ export function scrollRepeat(amount) {
42
63
  * contract. Construct via {@link DesktopAdapter.create}.
43
64
  */
44
65
  export class DesktopAdapter {
66
+ /**
67
+ * The native selector grammar — the AT-SPI parser this adapter's
68
+ * `find`/`click`/`type` accept: `role "name"` or a bare name substring, and
69
+ * nothing else. Declared here, not derived from the absence of `tabs`: the
70
+ * dialect is the grammar, and the grammar is the adapter's own.
71
+ */
72
+ selectorDialect = 'native';
45
73
  #config;
46
74
  #env;
47
75
  #atspi;
48
76
  #input;
49
77
  #capture;
50
- #child = null;
78
+ #readWalkMs;
79
+ #app;
80
+ /**
81
+ * The window identity the reads are scoped to — the app/window the AT-SPI
82
+ * walk is restricted to.
83
+ *
84
+ * The a11y tree spans EVERY application on the desktop, so an unscoped read
85
+ * returns whichever application happened to answer first: two apps with the
86
+ * same "Save" label and the click lands in the wrong one.
87
+ *
88
+ * The scope is the CONFIGURED `window` whenever the target configures one:
89
+ * that is the window xdotool activates, so it is the window the reads must
90
+ * name — and a later `open` of another window does NOT re-scope them (the
91
+ * configured window still wins the match, so the scope stays put). Only a
92
+ * target with NO configured window takes its scope from the window `open`
93
+ * last selected, and there a later `open` of another window DOES re-scope
94
+ * the reads.
95
+ */
96
+ #scope = null;
51
97
  constructor(handles) {
52
98
  this.#config = handles.config;
53
99
  this.#env = handles.env;
54
100
  this.#atspi = handles.atspi;
55
101
  this.#input = handles.input;
56
102
  this.#capture = handles.capture;
103
+ this.#readWalkMs = handles.readWalkMs;
104
+ this.#app = new ManagedApp(handles.config.launch, handles.env);
57
105
  }
58
106
  /** Wire the adapter from config, binding each backend to the chosen X11 display. */
59
107
  static create(init) {
@@ -64,6 +112,7 @@ export class DesktopAdapter {
64
112
  atspi: init.atspi ?? new BusctlAtspi({ display }),
65
113
  input: init.input ?? new Xdotool({ display }),
66
114
  capture: init.capture ?? new Screenshot({ display }),
115
+ readWalkMs: init.readWalkMs ?? READ_WALK_MS,
67
116
  });
68
117
  }
69
118
  /**
@@ -81,75 +130,91 @@ export class DesktopAdapter {
81
130
  throw new AdapterError('desktop: no window to drive — set `window.title` or `window.class` on the desktop ' +
82
131
  'target, or pass a window title as the open target');
83
132
  }
84
- const { died } = this.#launch();
133
+ await this.#app.reapLingering();
134
+ const { died } = this.#app.launch();
85
135
  // The window wait fits inside the run's remaining cap when that is the shorter one.
86
- const activated = this.#input.activateWindow(match, capWait(WINDOW_WAIT_MS, timeoutMs));
136
+ const waitMs = capWait(WINDOW_WAIT_MS, timeoutMs);
137
+ // The wait gets an ABSOLUTE deadline, not just a duration: the xdotool calls it
138
+ // makes are capped by the time left until then, so an in-flight search cannot
139
+ // outlive the budget the run has left.
140
+ const deadline = Date.now() + waitMs;
141
+ const activated = this.#input.activateWindow(match, waitMs, deadline);
87
142
  // Pre-handle the loser: when the child dies first, the window wait keeps polling
88
143
  // (bounded by the cap above) and its later rejection must not go unhandled.
89
144
  activated.catch(() => { });
90
- await Promise.race([activated, died]);
91
- });
92
- }
93
- /**
94
- * Spawn the managed app (a live child is reused) and latch its death.
95
- *
96
- * `stdio: 'ignore'` keeps the app detached from our stdio MCP channel, so the exit
97
- * code is the only signal we get — hence the latch: {@link Launched.died} carries it
98
- * to whoever is waiting in `open`.
99
- */
100
- #launch() {
101
- const running = this.#child;
102
- if (running)
103
- return running;
104
- const command = this.#config.launch;
105
- const proc = spawn('/bin/sh', ['-c', command], {
106
- env: this.#env,
107
- detached: true,
108
- stdio: 'ignore',
145
+ await Promise.race([activated, died]).catch((error) => {
146
+ throw this.#env.WAYLAND_DISPLAY ? withWaylandHint(error) : error;
147
+ });
148
+ // The window that is now up is the one every later read is scoped to — the
149
+ // a11y tree holds every application on the desktop, so the scope is what
150
+ // keeps a lookup inside this one.
151
+ this.#scope = { title: match.title, class: match.class };
109
152
  });
110
- const died = new Promise((_resolve, reject) => {
111
- const down = (reason) => {
112
- // A dead app must not pin `#child`: clear it so a later `open` relaunches
113
- // and `close` never kills a recycled process group.
114
- if (this.#child?.proc === proc)
115
- this.#child = null;
116
- reject(new AdapterError(`desktop: launch command exited (${reason}) before the window appeared: ${command}`));
117
- };
118
- proc.once('exit', (code, signal) => down(signal ? `killed by ${signal}` : `exit code ${code ?? 'unknown'}`));
119
- // 'error' fires async: unlistened, a missing `/bin/sh` would crash the server.
120
- proc.once('error', (error) => down(`spawn failed: ${error.message}`));
121
- });
122
- // The app normally outlives `open`, so its eventual exit rejects with nobody racing
123
- // it — pre-handle so a clean quit is never an unhandled rejection.
124
- died.catch(() => { });
125
- const launched = { proc, died };
126
- this.#child = launched;
127
- return launched;
128
153
  }
129
154
  async find(opts) {
130
155
  return this.#run('find', async () => {
131
- const nodes = await this.readState({ ...opts, limit: 1 });
132
- return nodes[0] ?? null;
156
+ const first = (await this.readState({ ...opts, limit: 1 }))[0];
157
+ if (!first || !opts.query)
158
+ return first ?? null;
159
+ const wanted = parseRoleNameQuery(opts.query).name;
160
+ if (wanted === undefined || first.name === wanted)
161
+ return first;
162
+ // The first hit is only a substring match ("Save As" for "Save"): look at a bounded
163
+ // set of further matches and prefer an exact name, then a case-insensitive one.
164
+ // The ranking is a refinement, not the lookup: it gets its own short cap, and when
165
+ // that expires the substring hit already in hand is the answer (a deliberate
166
+ // fallback — failing here would break every selector act on a large tree).
167
+ const rankMs = Math.min(FIND_RANK_MS, this.#readWalkMs);
168
+ const rankDeadline = Date.now() + rankMs;
169
+ let candidates;
170
+ try {
171
+ // `partial`: a walk cut off by the cap still holds the matches it reached —
172
+ // an exact hit among them must win over the earlier substring one.
173
+ candidates = await this.#readNodes({ ...opts, limit: FIND_CANDIDATES }, rankMs, true);
174
+ }
175
+ catch (error) {
176
+ if (error instanceof AdapterError && Date.now() >= rankDeadline)
177
+ return first;
178
+ throw error;
179
+ }
180
+ return (candidates.find((n) => n.name === wanted) ??
181
+ candidates.find((n) => n.name.toLowerCase() === wanted.toLowerCase()) ??
182
+ first);
133
183
  });
134
184
  }
135
185
  async readState(opts = {}) {
136
- return this.#run('readState', async () => {
137
- const region = opts.within !== undefined ? await this.#regionBounds(opts.within) : undefined;
138
- // A bounded query (role/name) + maxNodes let the AT-SPI walk skip describing
139
- // (and stop once it has found) more than the caller could ever use — `find`
140
- // (and thus `waitFor`'s poll loop) asks for `limit: 1`, so a match on the first
141
- // matching node ends the walk instead of describing the whole tree. Region
142
- // scoping (`within`) and `filters` are applied downstream in `shapeNodes`, not
143
- // visible to the walk itself, so an early match-count stop could wrongly skip a
144
- // same-query match that would have survived them (the first `Save` found is
145
- // disabled, the enabled one sits deeper) — only tighten `maxNodes` when there is
146
- // no post-walk narrowing to reconcile against.
147
- const query = opts.query ? parseRoleNameQuery(opts.query) : undefined;
148
- const narrowed = region !== undefined || opts.filters !== undefined;
149
- const maxNodes = narrowed ? DEFAULT_LIMIT : (opts.limit ?? DEFAULT_LIMIT);
150
- const nodes = await this.#atspi.readTree({ query, maxNodes });
151
- return shapeNodes(nodes, opts, DEFAULT_LIMIT, region);
152
- });
186
+ return this.#run('readState', () => this.#readNodes(opts, this.#readWalkMs));
187
+ }
188
+ /** One AT-SPI read shaped onto contract nodes, its walk capped at `walkMs` (loud on a partial tree unless `partial`). */
189
+ async #readNodes(opts, walkMs, partial = false) {
190
+ const scope = this.#readScope();
191
+ const region = opts.within !== undefined ? await this.#regionBounds(opts.within) : undefined;
192
+ // A bounded query (role/name) + maxNodes let the AT-SPI walk skip describing
193
+ // (and stop once it has found) more than the caller could ever use — `find`
194
+ // (and thus `waitFor`'s poll loop) asks for `limit: 1`, so a match on the first
195
+ // matching node ends the walk instead of describing the whole tree. Region
196
+ // scoping (`within`) and `filters` are applied downstream in `shapeNodes`, not
197
+ // visible to the walk itself, so an early match-count stop could wrongly skip a
198
+ // same-query match that would have survived them (the first `Save` found is
199
+ // disabled, the enabled one sits deeper) — only tighten `maxNodes` when there is
200
+ // no post-walk narrowing to reconcile against.
201
+ const query = opts.query ? parseRoleNameQuery(opts.query) : undefined;
202
+ // `visible_eq: true` is pushed into the walk (it then counts only showing nodes
203
+ // toward `maxNodes`, keeping the early stop); any other filter still narrows after.
204
+ const { visible_eq: visibleEq, ...otherFilters } = opts.filters ?? {};
205
+ const visibleOnly = visibleEq === true;
206
+ const narrowed = region !== undefined ||
207
+ Object.keys(otherFilters).length > 0 ||
208
+ (visibleEq !== undefined && !visibleOnly);
209
+ const maxNodes = narrowed ? DEFAULT_LIMIT : (opts.limit ?? DEFAULT_LIMIT);
210
+ const deadline = Date.now() + walkMs;
211
+ const nodes = await this.#atspi.readTree({ query, maxNodes, scope, visibleOnly, deadline });
212
+ // A walk that stopped on the clock (not on `maxNodes`) returned a partial tree.
213
+ if (!partial && Date.now() >= deadline && nodes.length < maxNodes) {
214
+ throw new AdapterError(`desktop: readState walk hit its ${walkMs}ms cap after ${nodes.length} nodes — ` +
215
+ 'the tree is too large to read whole; narrow it with `query`, `filters` or `within`');
216
+ }
217
+ return shapeNodes(nodes, opts, DEFAULT_LIMIT, region);
153
218
  }
154
219
  async click(target) {
155
220
  await this.#run('click', async () => {
@@ -174,8 +239,13 @@ export class DesktopAdapter {
174
239
  async scroll(opts) {
175
240
  await this.#run('scroll', async () => {
176
241
  // Scope: park the cursor over the region first so the wheel targets it.
177
- if (opts.within !== undefined) {
178
- const { x, y } = centerOf(await this.#regionBounds(opts.within));
242
+ // Unscoped, the wheel goes wherever the pointer last was — possibly another app.
243
+ // Park it over the target window (or the `within` region) first.
244
+ const anchor = opts.within !== undefined
245
+ ? await this.#regionBounds(opts.within)
246
+ : await this.#rootBounds();
247
+ if (anchor) {
248
+ const { x, y } = centerOf(anchor);
179
249
  await this.#input.move(x, y);
180
250
  }
181
251
  await this.#input.scroll(opts.direction, scrollRepeat(opts.amount));
@@ -193,15 +263,36 @@ export class DesktopAdapter {
193
263
  throw new AdapterError('waitFor requires `query` (desktop has no networkIdle)');
194
264
  }
195
265
  const timeout = opts.timeout ?? DEFAULT_WAIT_MS;
266
+ // NaN would make `Date.now() >= deadline` false forever — an unbounded poll.
267
+ if (!Number.isFinite(timeout) || timeout < 0) {
268
+ throw new AdapterError(`desktop: waitFor \`timeout\` must be a non-negative, finite number of ms (got ${timeout})`);
269
+ }
270
+ const signal = opts.signal;
271
+ if (signal?.aborted)
272
+ throw abortError();
196
273
  await this.#run('waitFor', async () => {
197
274
  const deadline = Date.now() + timeout;
198
- for (;;) {
199
- if (await this.#present(query, deadline))
275
+ // One abort latch for the whole wait: it cuts short both an in-flight walk and
276
+ // the poll nap, and its listener is removed on every exit path below.
277
+ let onAbort;
278
+ const aborted = new Promise((_resolve, reject) => {
279
+ if (!signal)
200
280
  return;
201
- if (Date.now() >= deadline) {
202
- throw new AdapterError(`desktop: waitFor timed out after ${timeout}ms (${query})`);
203
- }
204
- await delay(POLL_MS);
281
+ onAbort = () => reject(abortError());
282
+ signal.addEventListener('abort', onAbort, { once: true });
283
+ });
284
+ aborted.catch(() => { });
285
+ try {
286
+ await pollUntilPresent({
287
+ present: () => this.#present(query, deadline),
288
+ label: `waitFor timed out after ${timeout}ms (${query})`,
289
+ deadline,
290
+ aborted,
291
+ });
292
+ }
293
+ finally {
294
+ if (signal && onAbort)
295
+ signal.removeEventListener('abort', onAbort);
205
296
  }
206
297
  });
207
298
  }
@@ -212,10 +303,14 @@ export class DesktopAdapter {
212
303
  * checks the clock between polls — would overshoot its timeout by a whole walk.
213
304
  */
214
305
  async #present(query, deadline) {
306
+ const scope = this.#readScope();
215
307
  const nodes = await this.#atspi.readTree({
216
308
  query: parseRoleNameQuery(query),
217
309
  maxNodes: 1,
218
310
  deadline,
311
+ scope,
312
+ // "exists/becomes visible": a hidden twin (another tab's "Save") is not the thing awaited.
313
+ visibleOnly: true,
219
314
  });
220
315
  return shapeNodes(nodes, { query, limit: 1 }, DEFAULT_LIMIT).length > 0;
221
316
  }
@@ -236,28 +331,46 @@ export class DesktopAdapter {
236
331
  * left to kill it and its X/profile locks held until the user does it by hand.
237
332
  */
238
333
  async close() {
239
- const pid = this.#child?.proc.pid;
240
- if (pid === undefined) {
241
- this.#child = null;
242
- return;
243
- }
244
- await this.#run('close', async () => {
245
- await terminateGroup(pid);
246
- this.#child = null;
247
- });
334
+ await this.#run('close', () => this.#app.stop());
248
335
  }
249
336
  /** Resolve a {@link NodeRef} to a concrete {@link Node}, re-querying a selector. */
250
337
  async #resolve(target) {
251
338
  if (typeof target !== 'string')
252
339
  return target;
253
- const node = await this.find({ query: target });
340
+ // Visible only: a click on a hidden match lands on stale extents — whatever is there.
341
+ const node = await this.find({ query: target, filters: { visible_eq: true } });
254
342
  if (!node) {
255
- throw new AdapterError(`desktop: no element matched query ${JSON.stringify(target)}`);
343
+ throw new AdapterError(`desktop: no visible element matched query ${JSON.stringify(target)}`);
256
344
  }
257
345
  return node;
258
346
  }
259
347
  /**
260
- * Resolve a scope `within` (a {@link Node} or a selector) to an on-screen rectangle.
348
+ * The scope every read must carry — the window the target is bound to.
349
+ *
350
+ * The scope in force is the configured `window` when the target has one (a
351
+ * later `open` of another window does not change it — the configured window
352
+ * still wins the match), else the window the last `open` selected. With
353
+ * neither there is no window to read: an unscoped read walks EVERY
354
+ * application on the desktop, so a lookup for "Save" can resolve to another
355
+ * app's button and the click lands in the wrong window. That is the bug this
356
+ * scope exists to prevent, so the read fails loud instead of silently
357
+ * reading the whole desktop.
358
+ */
359
+ #readScope() {
360
+ const scope = this.#scope ?? this.#config.window;
361
+ if (!scope || (!scope.title && !scope.class)) {
362
+ throw new AdapterError('desktop: no window selected — set `window.title` or `window.class` on the desktop ' +
363
+ 'target, or open a window first; an unscoped read would match any application on ' +
364
+ 'the desktop');
365
+ }
366
+ return scope;
367
+ }
368
+ /** On-screen bounds of the scoped window itself, or null when AT-SPI cannot measure it. */
369
+ async #rootBounds() {
370
+ const [root] = await this.#atspi.readTree({ maxNodes: 1, scope: this.#readScope() });
371
+ return root?.measured && root.bounds.width > 0 && root.bounds.height > 0 ? root.bounds : null;
372
+ }
373
+ /** Resolve a scope `within` (a {@link Node} or a selector) to an on-screen rectangle.
261
374
  *
262
375
  * A zero-size region is rejected, not scoped to: it would park the scroll cursor at
263
376
  * the screen origin and (via `centerWithin`) read as a region nothing sits in.
@@ -285,8 +398,11 @@ export class DesktopAdapter {
285
398
  return await fn();
286
399
  }
287
400
  catch (error) {
288
- if (error instanceof UiDebuggerError)
401
+ // Aborts keep their `AbortError` name — the caller recognises them by it.
402
+ if (error instanceof UiDebuggerError ||
403
+ (error instanceof Error && error.name === 'AbortError')) {
289
404
  throw error;
405
+ }
290
406
  throw new AdapterError(`desktop.${op} failed: ${error instanceof Error ? error.message : String(error)}`);
291
407
  }
292
408
  }