@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
@@ -5,13 +5,16 @@
5
5
  * mid-flight, poll its findings, list targets, end it. Holds the cwd-keyed
6
6
  * {@link SessionManager} (the one-run-per-project gate) and the resolved config,
7
7
  * and delegates the heavy session assembly to an injected {@link SessionBuilder}
8
- * seam — so the orchestration here unit-tests with no browser or network. The MCP
9
- * handlers stay thin: validate input, call straight through to a method here.
8
+ * seam — so the orchestration here unit-tests with no browser or network.
10
9
  *
11
10
  * One run per project holds *across processes* too: the manager only knows this
12
11
  * server's memory, so `start` also consults the `state.json` breadcrumb and
13
12
  * refuses when another live server already owns a run here (a dead owner's stale
14
- * breadcrumb never blocks).
13
+ * breadcrumb never blocks). That read is the FRIENDLY early refusal; the
14
+ * AUTHORITY is the workspace's exclusive ownership claim, taken atomically by
15
+ * {@link FileStatePort.record} — two servers starting in the same window both
16
+ * read "no foreign run", and only the claim admits one of them
17
+ * ({@link SessionBusyError}, before a browser is launched).
15
18
  *
16
19
  * Sessions are keyed by cwd, but the tools speak `session_id`. Every id-bearing
17
20
  * call resolves the active session for the cwd and fails loud
@@ -22,29 +25,22 @@
22
25
  * MCP client dying) leaves the manager, but its findings must not vanish with it:
23
26
  * the settled session is retained so `get_findings` keeps serving its terminal
24
27
  * snapshot. `end_session` is the explicit forget; the next `start_debug`
25
- * supersedes it. The retained snapshot holds no target resources (the adapter is
26
- * already closed) and never participates in the one-run gate.
28
+ * supersedes it. The snapshot holds no target resources and never gates a start.
29
+ *
30
+ * The pieces around this orchestration live in their own modules: the contract
31
+ * types in `debug-api.ts` (re-exported here, so no importer changes), the catalog
32
+ * projection in `catalog.ts`, the retained snapshot in `retained-snapshot.ts`
33
+ * and the start-time refusals in `start-guards.ts`.
27
34
  */
28
- import { CONFIG_FILENAME } from '../config/load.js';
29
- import { ConfigError, SessionBusyError, SessionNotFoundError, SessionSettledError, TargetNotFoundError, } from '../errors.js';
30
- import { FindingsSchema } from '../findings/schema.js';
35
+ import { SessionBusyError, SessionNotFoundError, SessionSettledError } from '../errors.js';
31
36
  import { noopStatePort } from '../session/state-file.js';
32
- import { generateSessionId, workspacePaths } from '../session/workspace.js';
37
+ import { allocateSessionId, workspacePaths } from '../session/workspace.js';
38
+ import { selectTargets } from './catalog.js';
39
+ import { foreignSnapshot, projectFindings } from './foreign-findings.js';
40
+ import { RetainedSnapshot } from './retained-snapshot.js';
41
+ import { assertConfigFresh, assertNoForeignRun, assertStartNotAborted } from './start-guards.js';
33
42
  /** Default wall-clock cap on a debug run before it auto-ends (overridable per run). */
34
43
  export const DEFAULT_SESSION_TIMEOUT_MS = 300_000;
35
- /**
36
- * Narrow a findings object to the requested keys — the `fields` projection for a
37
- * snapshot read off disk (a live {@link Session} projects its own).
38
- */
39
- function projectFindings(findings, fields) {
40
- const out = {};
41
- for (const field of fields) {
42
- // Assigning key-by-key off a validated object; the index signature is what
43
- // makes this need the cast, not any doubt about the value's type.
44
- out[field] = findings[field];
45
- }
46
- return out;
47
- }
48
44
  export class DebugService {
49
45
  #manager;
50
46
  #config;
@@ -53,16 +49,15 @@ export class DebugService {
53
49
  #state;
54
50
  #defaultTimeoutMs;
55
51
  #now;
52
+ #platform;
56
53
  #configChanged;
57
54
  /** Live wall-clock timer for the active run; cleared when the run ends. */
58
55
  #timer;
59
56
  /**
60
57
  * The last run that auto-ended (timeout / SIGTERM / client death), kept settled
61
- * and closed so `get_findings` can still read its partial findings + evidence.
62
- * Dropped by `end_session` (the explicit forget) and superseded by the next run.
63
- * Never consulted by the one-run gate — a retained snapshot cannot block a start.
58
+ * and closed so `get_findings` can still read its findings. Never a gate.
64
59
  */
65
- #retained;
60
+ #retained = new RetainedSnapshot();
66
61
  /**
67
62
  * The `start()` currently in flight (building/launching, slot not yet in the
68
63
  * manager), or `undefined`. Set synchronously before the first await so a
@@ -70,11 +65,17 @@ export class DebugService {
70
65
  * racing a second browser onto the same profile.
71
66
  *
72
67
  * `controller` cancels it at the next checkpoint and `settled` resolves once it
73
- * has finished tearing down (it never rejects) — so {@link endActive} can abort a
74
- * launch *and wait for it*, instead of finding an empty manager and letting the
75
- * process exit with a half-launched Chrome still holding the profile lock.
68
+ * has torn down (it never rejects) — so {@link endActive} can abort a launch
69
+ * *and wait for it*, instead of exiting with a half-launched Chrome on the lock.
76
70
  */
77
71
  #starting;
72
+ /**
73
+ * The run the last `end_session` closed, with its teardown — what makes a REPEAT
74
+ * of that call a no-op that still waits for (and fails with) the first one.
75
+ */
76
+ #ended;
77
+ /** The teardown in flight (or the last one, settled) — a barrier, so it never rejects. */
78
+ #tearing = Promise.resolve();
78
79
  constructor(deps) {
79
80
  this.#manager = deps.manager;
80
81
  this.#config = deps.config;
@@ -83,6 +84,7 @@ export class DebugService {
83
84
  this.#state = deps.state ?? noopStatePort;
84
85
  this.#defaultTimeoutMs = deps.defaultTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;
85
86
  this.#now = deps.now ?? (() => Date.now());
87
+ this.#platform = deps.platform ?? process.platform;
86
88
  this.#configChanged = deps.configChanged ?? (() => false);
87
89
  }
88
90
  /**
@@ -90,26 +92,24 @@ export class DebugService {
90
92
  * the target, and kick the loop off in the background. Fails loud if a run is
91
93
  * already active for this cwd ({@link SessionBusyError}) — whether it belongs to
92
94
  * this server (the manager / in-flight guard) or to another live one (the
93
- * `state.json` breadcrumb); never leaks a launched browser — a lost lock race or
94
- * a failed `open` tears the session back down.
95
+ * `state.json` breadcrumb read, and then the workspace's ownership claim);
96
+ * never leaks a launched browser — a lost lock race or a failed `open` tears
97
+ * the session back down.
95
98
  *
96
99
  * `timeout` is wall-clock from HERE: the deadline is fixed on entry and the
97
100
  * remaining budget is threaded into the build and the first navigation, so a slow
98
101
  * Chrome launch spends the caller's cap instead of sitting outside it.
99
102
  *
100
- * The refusal is the default and stays the default; `replace: true` is the
101
- * caller's explicit takeover. Either way the caller ends up with a way forward:
102
- * the refusal names the active id and the exact calls that read, close or
103
- * replace it, and `describe` reports that id at any time — so a lost session id
104
- * is a detour, not the dead end that used to need the out-of-band CLI.
103
+ * The refusal is the default; `replace: true` is the caller's explicit takeover.
104
+ * Either way the caller has a way forward: the refusal names the active id and
105
+ * the calls that read, close or replace it, and `describe` reports that id.
105
106
  */
106
107
  async start(input) {
107
108
  const cwd = this.#cwd;
108
109
  // Checked first, and synchronously (no await before `#starting` is set) — a
109
110
  // concurrent start must fail here, not launch a second browser on the same
110
- // profile. Ahead of `replace` on purpose: a run that is still opening owns no
111
- // manager slot to hand over, and racing its teardown is how a half-launched
112
- // Chrome gets orphaned on the profile lock.
111
+ // profile. Ahead of `replace` on purpose: a run still opening owns no manager
112
+ // slot to hand over, and racing its teardown orphans a half-launched Chrome.
113
113
  if (this.#starting !== undefined) {
114
114
  throw new SessionBusyError(`A debug session is already starting for '${cwd}' — one run per project at a time. ` +
115
115
  'Wait a moment for it to open, then describe() names it, ' +
@@ -123,9 +123,18 @@ export class DebugService {
123
123
  'start_debug({…, replace:true}), which ends that run first. describe() reports this id ' +
124
124
  'at any time, so a lost session id never wedges the project.');
125
125
  }
126
+ // The previous run's teardown is still in flight: the manager freed its slot,
127
+ // but its close has not settled, so the profile/browser it held is mid-release.
128
+ // Launching now would race the ending run for those resources — refuse until
129
+ // the gate lifts, naming what the caller waits on.
130
+ const closing = this.#manager.closingId(cwd);
131
+ if (closing !== undefined) {
132
+ throw new SessionBusyError(`The previous debug session ('${closing}') for '${cwd}' is still closing — its ` +
133
+ 'teardown is releasing the profile lock. Wait a moment, then retry.');
134
+ }
126
135
  // Before anything is launched: a run built from config the caller has already
127
136
  // replaced is worse than no run — it reproduces the very failure they just fixed.
128
- this.#assertConfigFresh();
137
+ assertConfigFresh(this.#configChanged);
129
138
  const deadline = this.#now() + (input.timeoutMs ?? this.#defaultTimeoutMs);
130
139
  const controller = new AbortController();
131
140
  const attempt = this.#launch(input, deadline, controller.signal);
@@ -145,29 +154,37 @@ export class DebugService {
145
154
  /**
146
155
  * The launch itself: breadcrumb, build, lock, open, arm. Every await is a
147
156
  * cancellation checkpoint — `signal` is the shutdown path asking this start to
148
- * stop — and every failure (including a cancellation) tears down whatever
149
- * already came up and drops the breadcrumb, so nothing is left holding the
150
- * project's profile lock.
157
+ * stop — and every failure tears down whatever came up and drops the
158
+ * breadcrumb, so nothing is left holding the project's profile lock.
151
159
  */
152
160
  async #launch({ target, goal, criteria, url, as, replace }, deadline, signal) {
153
161
  const cwd = this.#cwd;
154
162
  /** Budget left on the caller's cap; never negative — a blown budget is simply spent. */
155
163
  const remaining = () => Math.max(0, deadline - this.#now());
156
- await this.#assertNoForeignRun(cwd);
164
+ // The friendly early refusal: another live server's breadcrumb already names a
165
+ // run here. It is a READ, so two servers in the same window can both see "no
166
+ // foreign run" — the AUTHORITATIVE admission is the claim `state.record()` takes.
167
+ await assertNoForeignRun(this.#state, cwd);
157
168
  // The caller asked to take the project over. Before the breadcrumb, so the
158
169
  // takeover's `clear()` cannot wipe the record of the run replacing it.
159
170
  if (replace === true)
160
171
  await this.#takeOverActive();
161
- const id = generateSessionId(this.#now());
162
- // The breadcrumb goes down BEFORE the launch, not after it: a cold Chrome start
163
- // takes 5-20s, and until `state.json` exists the run is invisible out-of-band —
164
- // `status` prints "no debug run recorded" and `stop` never signals, while a real
165
- // browser already holds the profile lock. It fails loud (a run the CLI cannot
166
- // see is a run nobody can stop) — and here that costs nothing, since not one
167
- // process has been launched yet.
172
+ // Skips an id whose session dir already exists: a server restarted within the
173
+ // same second restarts its counter too, and the session create is exclusive.
174
+ const workspace = workspacePaths(cwd, this.#config.workspace);
175
+ const id = await allocateSessionId(workspace, this.#now());
176
+ // The breadcrumb goes down BEFORE the launch: a cold Chrome start takes 5-20s,
177
+ // and until `state.json` exists the run is invisible out-of-band — `status`
178
+ // prints "no debug run recorded" and `stop` never signals, while a real browser
179
+ // already holds the profile lock. It fails loud (a run the CLI cannot see is a
180
+ // run nobody can stop) — and here that costs nothing: nothing is launched yet.
181
+ //
182
+ // Writing it also TAKES the workspace's ownership claim, the real gate: a live
183
+ // foreign owner refuses this write with {@link SessionBusyError} (naming its
184
+ // pid and session), so the loser never hides the winner's live run.
168
185
  await this.#state.record({ sessionId: id, target, goal });
169
186
  try {
170
- this.#assertStartNotAborted(signal, id);
187
+ assertStartNotAborted(signal, id);
171
188
  const built = await this.#build({
172
189
  id,
173
190
  target,
@@ -178,7 +195,7 @@ export class DebugService {
178
195
  timeoutMs: remaining(),
179
196
  });
180
197
  try {
181
- this.#assertStartNotAborted(signal, id);
198
+ assertStartNotAborted(signal, id);
182
199
  this.#manager.start(cwd, built.session);
183
200
  }
184
201
  catch (err) {
@@ -187,10 +204,10 @@ export class DebugService {
187
204
  }
188
205
  // This run owns the slot now — the previous run's retained snapshot is
189
206
  // superseded (its findings.json stays on disk for the CLI / a human).
190
- this.#retained = undefined;
207
+ this.#retained.clear();
191
208
  try {
192
209
  await built.open(remaining());
193
- this.#assertStartNotAborted(signal, id);
210
+ assertStartNotAborted(signal, id);
194
211
  built.session.start(built.run);
195
212
  }
196
213
  catch (err) {
@@ -204,34 +221,21 @@ export class DebugService {
204
221
  }
205
222
  catch (err) {
206
223
  // Nobody holds this id, so nothing could ever end the run — leave no
207
- // `running` breadcrumb pointing the CLI at a run that is already gone.
208
- await this.#state.clear().catch(() => undefined);
224
+ // `running` breadcrumb pointing the CLI at a gone run. Scoped to THIS
225
+ // attempt's id: a successor that recorded itself meanwhile keeps its own.
226
+ await this.#state.clear(id).catch(() => undefined);
209
227
  throw err;
210
228
  }
211
229
  }
212
230
  /**
213
- * Stop a start that the shutdown path has cancelled (SIGTERM, a CLI `stop`, the
214
- * MCP client dying). The caller tears down whatever it had already built —
215
- * teardown is exactly what the abort is for.
216
- */
217
- #assertStartNotAborted(signal, id) {
218
- if (!signal.aborted)
219
- return;
220
- throw new SessionSettledError(`Debug run '${id}' was torn down while it was still starting — this ui-debugger-mcp server ` +
221
- 'is shutting down (SIGTERM, `ui-debugger-mcp stop`, or the MCP client disconnected). ' +
222
- 'Nothing was left running; start again once the server is back.');
223
- }
224
- /**
225
- * `replace: true` — end the run this server holds for the project so the new one
226
- * can have it. No-op when nothing is active: replacing nothing is just a start.
231
+ * `replace: true` — end the run this server holds so the new one can have it.
232
+ * No-op when nothing is active: replacing nothing is just a start.
227
233
  *
228
- * Deliberately routed through {@link end}, the very method `end_session` calls,
229
- * rather than a private teardown: releasing a target correctly means the managed
230
- * browser is STOPPED while an attached one is only DISCONNECTED, the wall-clock
231
- * timer is cleared and the breadcrumb dropped — a second implementation of that
232
- * would drift, and the drift would show up as a leaked Chrome sitting on the
233
- * profile lock. A teardown that throws fails the start, loudly; the manager frees
234
- * the slot before closing, so the project is not wedged either way.
234
+ * Deliberately routed through {@link end}, the very method `end_session` calls:
235
+ * releasing a target correctly means the managed browser is STOPPED while an
236
+ * attached one is only DISCONNECTED, the timer is cleared and the breadcrumb
237
+ * dropped — a second implementation of that would drift, and the drift would
238
+ * show up as a leaked Chrome on the profile lock.
235
239
  */
236
240
  async #takeOverActive() {
237
241
  if (!this.#manager.has(this.#cwd))
@@ -239,48 +243,17 @@ export class DebugService {
239
243
  await this.end({ session_id: this.#manager.get(this.#cwd).id });
240
244
  }
241
245
  /**
242
- * Refuse to start on config this server can no longer honour.
243
- *
244
- * The message names the one action that works. Without it the caller edits the
245
- * file, sees the identical failure, and has no way to tell a bad fix from an
246
- * unread one — which is exactly how a real session burned two runs.
247
- */
248
- #assertConfigFresh() {
249
- if (!this.#configChanged())
250
- return;
251
- throw new ConfigError(`${CONFIG_FILENAME} changed on disk after this ui-debugger-mcp server started, so a run now ` +
252
- 'would still use the OLD settings (models, targets, urls are read once at boot). ' +
253
- 'Restart the MCP server to pick the new config up — in Claude Code, /mcp → reconnect ' +
254
- 'ui-debugger, or restart the session.');
255
- }
256
- /**
257
- * The other half of the one-run gate: another *live* server process holding a
258
- * run on this project. The manager only sees this process's memory, so without
259
- * this a second MCP client on the same cwd would launch a second run onto the
260
- * same profile/emulator and overwrite the live breadcrumb (leaving the CLI
261
- * pointing at the wrong pid). A dead or PID-recycled owner does not count — a
262
- * crashed server's stale `running` file must never wedge the project shut.
263
- */
264
- async #assertNoForeignRun(cwd) {
265
- const foreign = await this.#state.foreignRun();
266
- if (foreign === null)
267
- return;
268
- throw new SessionBusyError(`Another ui-debugger-mcp server (pid ${foreign.pid}) already has a debug session ` +
269
- `('${foreign.sessionId}') active for '${cwd}'. One run per project at a time. ` +
270
- `Read what it is doing with get_findings({session_id:'${foreign.sessionId}'}) — a run ` +
271
- 'that has already settled is just waiting to be closed by its own client. To take the ' +
272
- "project over, run 'ui-debugger-mcp stop' in this directory, then start again.");
273
- }
274
- /**
275
- * Arm the wall-clock cap on what is LEFT of the run's budget: auto-end the run when
276
- * it fires (replaces any prior timer). `0` — the launch outlived the whole cap —
277
- * ends the run on the next tick rather than granting it a fresh one.
246
+ * Arm the wall-clock cap on what is LEFT of the run's budget: auto-end the run
247
+ * when it fires (replacing any prior timer). `0` — the launch outlived the whole
248
+ * cap — ends the run on the next tick, not with a fresh one.
278
249
  */
279
250
  #armTimeout(ms) {
280
251
  this.#clearTimeout();
281
252
  this.#timer = setTimeout(() => {
282
253
  this.#timer = undefined;
283
- void this.endActive().catch(() => undefined);
254
+ // Ends the run it was armed for, and ONLY that: `endActive` would also abort
255
+ // a `replace:true` start in flight, failing it as "server is shutting down".
256
+ void this.#endRetaining().catch(() => undefined);
284
257
  }, ms);
285
258
  }
286
259
  /** Cancel the active run's wall-clock timer, if any. */
@@ -293,10 +266,11 @@ export class DebugService {
293
266
  /**
294
267
  * Queue a mid-run instruction for the active run's driver. Fails loud
295
268
  * ({@link SessionSettledError}) once the run has settled — the loop no longer
296
- * drains the inbox, so an ack then would silently drop the message.
269
+ * drains the inbox, so an ack then would drop the message.
297
270
  */
298
271
  send({ session_id, message }) {
299
- const session = this.#require(session_id);
272
+ // Readable, not just active: an auto-ended run answers "settled", not "no such session".
273
+ const session = this.#requireReadable(session_id);
300
274
  if (session.status !== 'running') {
301
275
  throw new SessionSettledError(`Debug run '${session_id}' has already settled ('${session.status}') — the driver is no ` +
302
276
  'longer listening. Read its results with get_findings, or start a new run with start_debug.');
@@ -307,8 +281,7 @@ export class DebugService {
307
281
  /**
308
282
  * Snapshot the run's findings — optionally long-poll (`wait`) and/or project a
309
283
  * subset (`fields`). Serves the retained terminal snapshot once the run has
310
- * auto-ended, so a timed-out run's partial findings stay reachable (the
311
- * long-poll returns at once: a settled run has nothing left to wait for).
284
+ * auto-ended, so a timed-out run's findings stay reachable.
312
285
  */
313
286
  async getFindings({ session_id, wait, fields, }) {
314
287
  let session;
@@ -318,143 +291,135 @@ export class DebugService {
318
291
  catch (error) {
319
292
  // Our own memory has no such run — but another live server on this project
320
293
  // might, and `start_debug` has already named that session to this caller.
321
- // Answering "no such session" there is a contradiction that sends the
322
- // caller into a retry loop; serve what that run has flushed instead.
323
- const foreign = await this.#foreignSnapshot(session_id);
294
+ // Answering "no such session" there is a contradiction; serve what it flushed.
295
+ const foreign = await foreignSnapshot(this.#state, session_id, error);
324
296
  if (foreign)
325
297
  return fields ? projectFindings(foreign, fields) : foreign;
326
298
  throw error;
327
299
  }
328
300
  return fields ? session.snapshot(fields, wait) : session.snapshot(undefined, wait);
329
301
  }
330
- /**
331
- * A foreign run's findings as last flushed to disk, or `null` if this id names
332
- * no such run. Read-only and point-in-time: we do not own that run, so there is
333
- * nothing to long-poll — the owning server is the one advancing it.
334
- */
335
- async #foreignSnapshot(session_id) {
336
- const raw = await this.#state.foreignFindings(session_id);
337
- if (raw === null)
338
- return null;
339
- const parsed = FindingsSchema.safeParse(raw);
340
- return parsed.success ? parsed.data : null;
341
- }
342
302
  /** List configured targets (the whole catalog, or one when named) plus resolved models/workspace. */
343
303
  describe({ target }) {
344
- const entries = Object.entries(this.#config.targets);
345
- const selected = target === undefined ? entries : entries.filter(([name]) => name === target);
346
- if (target !== undefined && selected.length === 0) {
347
- throw new TargetNotFoundError(`target '${target}' not found in config.targets`);
348
- }
304
+ const targets = selectTargets(this.#config.targets, target, this.#platform);
349
305
  const session = this.#currentRun();
350
306
  return {
351
- targets: selected.map(([name, config]) => describeTarget(name, config)),
307
+ targets,
352
308
  models: this.#config.models,
353
- // The RESOLVED per-project root, not the raw config string: the caller joins
354
- // this to the relative evidence paths it gets back, and `./tmp/ui-debugger-mcp`
355
- // would send it looking one directory short of where anything lands.
309
+ // The RESOLVED per-project root, not the raw config string (a directory short).
356
310
  workspace: workspacePaths(this.#cwd, this.#config.workspace).root,
357
311
  ...(session && { session }),
358
312
  };
359
313
  }
360
314
  /**
361
315
  * The run this server holds for the project — the active one, or the retained
362
- * snapshot of the last run that auto-ended (both are readable and both are
363
- * `end_session`-able by their id). `undefined` when there is none.
316
+ * snapshot of the last run that auto-ended (both readable, both `end_session`-able
317
+ * by their id). `undefined` when there is none.
364
318
  *
365
- * This is the in-band answer to a lost `session_id`: without it, a caller whose
366
- * context was compacted mid-conversation could neither read the run nor close
367
- * it, and the only recovery left was `ui-debugger-mcp stop` in a shell the
368
- * caller may not have. A start still in flight is deliberately not reported —
369
- * it has no id to hand out yet, and the busy error says to wait for it.
319
+ * The in-band answer to a lost `session_id`: without it a compacted caller could
320
+ * neither read the run nor close it, and the only recovery left was the out-of-band
321
+ * CLI. A start still in flight is not reported — it has no id yet.
370
322
  */
371
323
  #currentRun() {
372
- const session = this.#manager.has(this.#cwd) ? this.#manager.get(this.#cwd) : this.#retained;
324
+ const session = this.#manager.has(this.#cwd)
325
+ ? this.#manager.get(this.#cwd)
326
+ : this.#retained.peek();
373
327
  if (session === undefined)
374
328
  return undefined;
375
329
  return { id: session.id, status: session.status, goal: session.story };
376
330
  }
377
331
  /**
378
332
  * End the active run: abort the loop, close the adapter, free the profile lock.
379
- * Ending a run that already auto-ended (timeout / client death) is not an error
380
- * — it just forgets the retained snapshot, so `end_session` reads the same
381
- * either way and stays the one explicit forget.
333
+ * Ending a run that already auto-ended is not an error — it just forgets the
334
+ * retained snapshot, so `end_session` stays the one explicit forget.
382
335
  */
383
336
  async end({ session_id }) {
384
- if (this.#forgetRetained(session_id))
337
+ const retained = this.#retained.peek();
338
+ if (retained !== undefined && this.#forgetRetained(session_id)) {
339
+ this.#ended = { session: retained, done: Promise.resolve() };
385
340
  return { ok: true, session_id };
386
- this.#require(session_id);
387
- this.#clearTimeout();
388
- // Clear the breadcrumb even when the close throws: the manager frees the slot
389
- // before closing, so a stale `running` state.json would make a later CLI
390
- // `stop` SIGTERM a healthy server. The close error still propagates.
391
- try {
392
- await this.#manager.end(this.#cwd);
393
341
  }
394
- finally {
395
- await this.#state.clear();
342
+ // Idempotent: a repeat for the run it just ended succeeds and says so — once that
343
+ // teardown SETTLED (final status; its close error too). Other unknown ids fail loud.
344
+ const ended = this.#ended;
345
+ if (ended?.session.id === session_id) {
346
+ await ended.done;
347
+ return { ok: true, session_id, already_ended: { status: ended.session.status } };
396
348
  }
349
+ const session = this.#require(session_id);
350
+ this.#clearTimeout();
351
+ const done = this.#teardown(session_id);
352
+ this.#ended = { session, done };
353
+ await done;
397
354
  return { ok: true, session_id };
398
355
  }
356
+ /**
357
+ * Close the active run, then drop its breadcrumb — even when the close throws.
358
+ * The ONE teardown, for every way a run ends, so {@link endActive} can wait on it.
359
+ */
360
+ #teardown(session_id) {
361
+ const done = (async () => {
362
+ try {
363
+ await this.#manager.end(this.#cwd);
364
+ }
365
+ finally {
366
+ // The manager frees the slot before closing, so a stale `running` state.json
367
+ // would make a later CLI `stop` SIGTERM a healthy server. Scoped to
368
+ // `session_id`: a successor recording itself mid-teardown is untouched.
369
+ await this.#state.clear(session_id);
370
+ }
371
+ })();
372
+ this.#tearing = done.catch(() => undefined);
373
+ return done;
374
+ }
399
375
  /**
400
376
  * End whatever run is active for this cwd, if any — the graceful-shutdown path
401
- * for a SIGTERM/SIGINT, a CLI `stop`, or the wall-clock timeout firing. No-op
402
- * when nothing is running.
377
+ * for a SIGTERM/SIGINT, a CLI `stop`, or the wall-clock timeout firing.
403
378
  */
404
379
  async endActive() {
405
380
  this.#clearTimeout();
406
381
  // A start still in flight owns no manager slot yet, so the check below would
407
382
  // sail straight past a Chrome that is mid-launch: cancel it and WAIT for its
408
- // teardown, or the process exits with a browser still holding the profile lock
409
- // and every later run fails with "Chrome profile ... is locked".
383
+ // teardown, or the process exits with a browser on the profile lock.
410
384
  const starting = this.#starting;
411
385
  if (starting !== undefined) {
412
386
  starting.controller.abort();
413
387
  await starting.settled;
414
388
  }
389
+ // Slot-free is not torn-down: a timeout or `end_session` teardown in flight has
390
+ // emptied the manager, and shutdown must not exit before that close has settled.
391
+ await this.#tearing;
392
+ await this.#endRetaining();
393
+ }
394
+ /** End the active run (if any) nobody asked to end, keeping it readable. */
395
+ async #endRetaining() {
415
396
  if (!this.#manager.has(this.#cwd))
416
397
  return;
417
398
  // Nobody asked for this end, so nobody has read the results yet: retain the
418
399
  // session (settled + closed) so `get_findings` still serves them. Captured
419
- // before the close, so even a failing teardown leaves the findings reachable.
420
- this.#retained = this.#manager.get(this.#cwd);
421
- // Same contract as `end()`: the breadcrumb clears even when the close throws.
422
- try {
423
- await this.#manager.end(this.#cwd);
424
- }
425
- finally {
426
- await this.#state.clear();
427
- }
400
+ // before the close, so a failing teardown leaves them reachable anyway.
401
+ const ending = this.#manager.get(this.#cwd);
402
+ this.#retained.retain(ending);
403
+ await this.#teardown(ending.id);
428
404
  }
429
405
  /**
430
406
  * Resolve the session a read names: the active run, or — once the manager is
431
- * empty — the retained snapshot of the last auto-ended run, so a timed-out run's
432
- * partial findings stay readable by their id until `end_session` or the next
433
- * `start_debug`. A different id still fails loud.
407
+ * empty — the retained snapshot of the last auto-ended run. A different id fails loud.
434
408
  */
435
409
  #requireReadable(session_id) {
436
- const retained = this.#retained;
437
- if (retained === undefined || this.#manager.has(this.#cwd)) {
410
+ if (this.#manager.has(this.#cwd) || this.#retained.peek() === undefined) {
438
411
  return this.#require(session_id);
439
412
  }
440
- if (retained.id !== session_id) {
441
- throw new SessionNotFoundError(`No active debug session '${session_id}' for '${this.#cwd}' (the last run '${retained.id}' ` +
442
- 'has ended; its findings are still readable under that id).');
443
- }
444
- return retained;
413
+ return this.#retained.requireRetained(session_id, this.#cwd);
445
414
  }
446
415
  /**
447
- * Forget the retained snapshot when the caller's `end_session` names it — the
448
- * run is already torn down, so there is nothing left to close. Returns whether
449
- * the id was the retained one (and it is now forgotten).
416
+ * Forget the retained snapshot when the caller's `end_session` names it — the run
417
+ * is already torn down. Returns whether the id was the retained one.
450
418
  */
451
419
  #forgetRetained(session_id) {
452
420
  if (this.#manager.has(this.#cwd))
453
421
  return false;
454
- if (this.#retained?.id !== session_id)
455
- return false;
456
- this.#retained = undefined;
457
- return true;
422
+ return this.#retained.forget(session_id);
458
423
  }
459
424
  /** Resolve the active session for this cwd, asserting its id matches the caller's. */
460
425
  #require(session_id) {
@@ -465,37 +430,4 @@ export class DebugService {
465
430
  return session;
466
431
  }
467
432
  }
468
- /** Whether a target is in attach mode (connects to a running instance, never start/stop). */
469
- function isAttach(target) {
470
- if (target.adapter === 'browser')
471
- return target.cdpUrl != null;
472
- if (target.adapter === 'android')
473
- return target.adbSerial != null;
474
- return false;
475
- }
476
- /** Project one configured target onto its public {@link TargetInfo} (no secrets). */
477
- function describeTarget(name, target) {
478
- const base = {
479
- name,
480
- adapter: target.adapter,
481
- mode: isAttach(target) ? 'attach' : 'managed',
482
- operational: true,
483
- // What the project declares is EXPECTED of this app — the driver already gets
484
- // it in its prompt; the caller sees it here so "the table is empty" coming back
485
- // as a non-finding is explainable without opening the config file.
486
- ...(target.notes !== undefined && { notes: target.notes }),
487
- };
488
- if (target.adapter === 'browser') {
489
- // Persona NAMES are the discoverable half — a caller can pick a valid `as`
490
- // without opening the config file, and never sees the values.
491
- const personas = Object.keys(target.auth ?? {});
492
- return {
493
- ...base,
494
- url: target.url,
495
- headless: target.headless,
496
- ...(personas.length > 0 && { personas }),
497
- };
498
- }
499
- return base;
500
- }
501
433
  //# sourceMappingURL=debug-service.js.map