litmus-cli 1.5.2-beta.8 → 1.5.2

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 (88) hide show
  1. package/dist/commands/connect.d.ts.map +1 -1
  2. package/dist/commands/connect.js +109 -229
  3. package/dist/commands/connect.js.map +1 -1
  4. package/dist/commands/doctor.d.ts.map +1 -1
  5. package/dist/commands/doctor.js +2 -7
  6. package/dist/commands/doctor.js.map +1 -1
  7. package/dist/commands/submit.d.ts.map +1 -1
  8. package/dist/commands/submit.js +1 -4
  9. package/dist/commands/submit.js.map +1 -1
  10. package/dist/cursor-session/package.json +1 -1
  11. package/dist/cursor-session/session.cjs +12 -12
  12. package/dist/lib/ai-tracking.d.ts +1 -2
  13. package/dist/lib/ai-tracking.d.ts.map +1 -1
  14. package/dist/lib/ai-tracking.js +8 -26
  15. package/dist/lib/ai-tracking.js.map +1 -1
  16. package/dist/lib/api.d.ts +1 -1
  17. package/dist/lib/api.d.ts.map +1 -1
  18. package/dist/lib/api.js +2 -2
  19. package/dist/lib/api.js.map +1 -1
  20. package/dist/lib/backfill-tools.d.ts.map +1 -1
  21. package/dist/lib/backfill-tools.js +0 -6
  22. package/dist/lib/backfill-tools.js.map +1 -1
  23. package/dist/lib/backfill.d.ts.map +1 -1
  24. package/dist/lib/backfill.js +0 -3
  25. package/dist/lib/backfill.js.map +1 -1
  26. package/dist/lib/backlog-flush.d.ts.map +1 -1
  27. package/dist/lib/backlog-flush.js +0 -3
  28. package/dist/lib/backlog-flush.js.map +1 -1
  29. package/dist/lib/capture-selftest.d.ts +0 -9
  30. package/dist/lib/capture-selftest.d.ts.map +1 -1
  31. package/dist/lib/capture-selftest.js +2 -4
  32. package/dist/lib/capture-selftest.js.map +1 -1
  33. package/dist/lib/connect-skills.d.ts.map +1 -1
  34. package/dist/lib/connect-skills.js +38 -48
  35. package/dist/lib/connect-skills.js.map +1 -1
  36. package/dist/lib/cursor-session.d.ts +0 -1
  37. package/dist/lib/cursor-session.d.ts.map +1 -1
  38. package/dist/lib/cursor-session.js +1 -1
  39. package/dist/lib/cursor-session.js.map +1 -1
  40. package/dist/lib/hook-logger.cjs +0 -16
  41. package/dist/lib/hosted-capture.d.ts.map +1 -1
  42. package/dist/lib/hosted-capture.js +1 -14
  43. package/dist/lib/hosted-capture.js.map +1 -1
  44. package/dist/lib/hosted-transcripts.d.ts.map +1 -1
  45. package/dist/lib/hosted-transcripts.js +0 -4
  46. package/dist/lib/hosted-transcripts.js.map +1 -1
  47. package/dist/lib/hosted-watcher.js +0 -5
  48. package/dist/lib/hosted-watcher.js.map +1 -1
  49. package/dist/lib/launcher-cleanup-journal.d.ts +0 -34
  50. package/dist/lib/launcher-cleanup-journal.d.ts.map +1 -1
  51. package/dist/lib/launcher-cleanup-journal.js +1 -75
  52. package/dist/lib/launcher-cleanup-journal.js.map +1 -1
  53. package/dist/lib/portal-launcher.d.ts +3 -44
  54. package/dist/lib/portal-launcher.d.ts.map +1 -1
  55. package/dist/lib/portal-launcher.js +42 -361
  56. package/dist/lib/portal-launcher.js.map +1 -1
  57. package/dist/lib/schemas.d.ts +0 -1
  58. package/dist/lib/schemas.d.ts.map +1 -1
  59. package/dist/lib/schemas.js +0 -1
  60. package/dist/lib/schemas.js.map +1 -1
  61. package/dist/lib/skill-import.d.ts +4 -4
  62. package/dist/lib/skill-import.js +4 -4
  63. package/dist/lib/snapshot-capture.d.ts +24 -0
  64. package/dist/lib/snapshot-capture.d.ts.map +1 -0
  65. package/dist/lib/snapshot-capture.js +90 -0
  66. package/dist/lib/snapshot-capture.js.map +1 -0
  67. package/dist/lib/snapshot-guardian.d.ts +2 -0
  68. package/dist/lib/snapshot-guardian.d.ts.map +1 -0
  69. package/dist/lib/snapshot-guardian.js +31 -0
  70. package/dist/lib/snapshot-guardian.js.map +1 -0
  71. package/dist/lib/snapshot-worker.d.ts +2 -0
  72. package/dist/lib/snapshot-worker.d.ts.map +1 -0
  73. package/dist/lib/snapshot-worker.js +98 -0
  74. package/dist/lib/snapshot-worker.js.map +1 -0
  75. package/dist/lib/ssh-config-file.d.ts +1 -1
  76. package/dist/lib/ssh-config-file.d.ts.map +1 -1
  77. package/dist/lib/ssh-config-file.js +3 -37
  78. package/dist/lib/ssh-config-file.js.map +1 -1
  79. package/dist/lib/watcher.js +78 -139
  80. package/dist/lib/watcher.js.map +1 -1
  81. package/dist/lib/zip.d.ts.map +1 -1
  82. package/dist/lib/zip.js +1 -2
  83. package/dist/lib/zip.js.map +1 -1
  84. package/package.json +1 -1
  85. package/dist/lib/isolated-host-policy.d.ts +0 -4
  86. package/dist/lib/isolated-host-policy.d.ts.map +0 -1
  87. package/dist/lib/isolated-host-policy.js +0 -17
  88. package/dist/lib/isolated-host-policy.js.map +0 -1
@@ -36,14 +36,13 @@ export function reportLauncherTiming(backendUrl, token, stage, elapsedMs, extra
36
36
  method: "POST", redirect: "error", signal: AbortSignal.timeout(3000),
37
37
  headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
38
38
  body: JSON.stringify({
39
- stage, source: "cli", elapsed_ms: Math.min(elapsedMs, 3600001), event_at_ms: Date.now(),
39
+ stage, source: "cli", elapsed_ms: Math.min(elapsedMs, 3600001),
40
40
  temperature: extra.temperature ?? "unknown",
41
41
  os: process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "windows" : process.platform === "linux" ? "linux" : "unknown",
42
42
  app_version: CLI_VERSION,
43
43
  ...(extra.tool ? { tool: extra.tool } : {}), ...(extra.outcome ? { outcome: extra.outcome } : {}),
44
44
  ...(extra.sessionId ? { session_id: extra.sessionId } : {}), ...(extra.requestId ? { request_id: extra.requestId } : {}),
45
45
  ...(extra.readinessPath ? { readiness_path: extra.readinessPath } : {}),
46
- ...(extra.cleanupTarget ? { cleanup_target: extra.cleanupTarget } : {}),
47
46
  }),
48
47
  }).catch(() => { });
49
48
  }
@@ -132,168 +131,6 @@ const closeTerminalScript = `on run argv
132
131
  return "not_found"
133
132
  end tell
134
133
  end run`;
135
- const closeClaudeWindowScript = `on run argv
136
- set assessmentAlias to item 1 of argv
137
- set assessmentWorkspace to "workspace · " & assessmentAlias
138
- set closedCount to 0
139
- tell application "System Events"
140
- if not (exists process "Claude") then return "not_found"
141
- tell process "Claude"
142
- repeat 20 times
143
- set inspectedWindow to false
144
- set matchingWindow to missing value
145
- set sessionMenuButton to missing value
146
- set pendingConfirmationCancel to missing value
147
- repeat with candidateWindow in windows
148
- set inAssessmentWorkspace to false
149
- set hasPendingConfirmationHeading to false
150
- set hasPendingConfirmationAlias to false
151
- try
152
- set windowContents to entire contents of candidateWindow
153
- set inspectedWindow to true
154
- repeat with candidateElement in windowContents
155
- try
156
- set candidateRole to role of candidateElement as text
157
- set candidateValue to ""
158
- set candidateDescription to ""
159
- set candidateName to ""
160
- try
161
- set candidateValue to value of candidateElement as text
162
- end try
163
- try
164
- set candidateDescription to description of candidateElement as text
165
- end try
166
- try
167
- set candidateName to name of candidateElement as text
168
- end try
169
- if candidateRole is "AXHeading" then
170
- if candidateValue is "Use this SSH connection?" or candidateValue is "Trust this workspace?" or candidateDescription is "Use this SSH connection?" or candidateDescription is "Trust this workspace?" or candidateName is "Use this SSH connection?" or candidateName is "Trust this workspace?" then
171
- set hasPendingConfirmationHeading to true
172
- end if
173
- if candidateValue is assessmentAlias or candidateValue is assessmentWorkspace or candidateDescription is assessmentAlias or candidateDescription is assessmentWorkspace or candidateName is assessmentAlias or candidateName is assessmentWorkspace then
174
- set inAssessmentWorkspace to true
175
- set matchingWindow to candidateWindow
176
- else if inAssessmentWorkspace then
177
- exit repeat
178
- end if
179
- else if inAssessmentWorkspace and candidateRole is "AXPopUpButton" then
180
- if candidateDescription starts with "More options for " or candidateName starts with "More options for " then
181
- set sessionMenuButton to candidateElement
182
- exit repeat
183
- end if
184
- end if
185
- -- Claude can leave its assessment-scoped SSH confirmation over
186
- -- an otherwise unrelated main window. Dismiss only a dialog
187
- -- that exposes this exact alias; never close the whole window
188
- -- merely because the pending handoff is visible.
189
- if candidateValue is assessmentAlias or candidateValue is "on " & assessmentAlias or candidateValue is "on " & assessmentAlias then
190
- set hasPendingConfirmationAlias to true
191
- else if hasPendingConfirmationHeading and hasPendingConfirmationAlias and candidateRole is "AXButton" then
192
- if candidateValue is "Cancel" or candidateDescription is "Cancel" or candidateName is "Cancel" then
193
- set pendingConfirmationCancel to candidateElement
194
- exit repeat
195
- end if
196
- end if
197
- -- Older Claude builds exposed the alias as a bare value rather
198
- -- than a workspace heading. Preserve that exact-match fallback.
199
- if matchingWindow is missing value and candidateValue is assessmentAlias then
200
- set matchingWindow to candidateWindow
201
- end if
202
- end try
203
- end repeat
204
- end try
205
- if pendingConfirmationCancel is not missing value then exit repeat
206
- if sessionMenuButton is not missing value then exit repeat
207
- end repeat
208
- if pendingConfirmationCancel is not missing value then
209
- try
210
- perform action "AXPress" of pendingConfirmationCancel
211
- delay 0.25
212
- set closedCount to closedCount + 1
213
- -- Re-scan until the exact alias is gone. A duplicate handoff can
214
- -- stack more than one confirmation dialog for the same workspace.
215
- on error
216
- return "retry"
217
- end try
218
- else if matchingWindow is missing value then
219
- if closedCount > 0 then return "closed"
220
- if (count of windows) is 0 then return "not_found"
221
- if not inspectedWindow then return "retry"
222
- return "not_found"
223
- else if sessionMenuButton is not missing value then
224
- try
225
- perform action "AXPress" of sessionMenuButton
226
- delay 0.1
227
- set archiveItem to missing value
228
- repeat with menuElement in entire contents of matchingWindow
229
- try
230
- set menuValue to value of menuElement as text
231
- set menuDescription to ""
232
- set menuName to ""
233
- try
234
- set menuDescription to description of menuElement as text
235
- end try
236
- try
237
- set menuName to name of menuElement as text
238
- end try
239
- if menuValue is "Archive" or menuDescription is "Archive" or menuName is "Archive" then
240
- set archiveItem to menuElement
241
- exit repeat
242
- end if
243
- end try
244
- end repeat
245
- if archiveItem is missing value then return "retry"
246
- perform action "AXPress" of archiveItem
247
- delay 0.25
248
- set closedCount to closedCount + 1
249
- -- Keep archiving until the exact assessment workspace contains no
250
- -- sessions. Other workspace groups and chats are never inspected.
251
- on error
252
- return "retry"
253
- end try
254
- else
255
- try
256
- perform action "AXClose" of matchingWindow
257
- on error
258
- return "retry"
259
- end try
260
- delay 0.25
261
- set closedCount to closedCount + 1
262
- end if
263
- end repeat
264
- -- A close request that leaves the exact alias visible is not verified.
265
- return "retry"
266
- end tell
267
- end tell
268
- end run`;
269
- /**
270
- * Testable semantic model of the ownership gate used by the native Claude
271
- * cleanup script. The runtime still uses System Events, but both paths require
272
- * the confirmation heading, exact assessment alias and Cancel button to occur
273
- * in the same window and in that order.
274
- */
275
- export function ownedClaudePendingDialogCancel(alias, windows) {
276
- if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
277
- return null;
278
- const headings = new Set(["Use this SSH connection?", "Trust this workspace?"]);
279
- const aliases = new Set([alias, `on ${alias}`, `on ${alias}`]);
280
- for (let window = 0; window < windows.length; window++) {
281
- let heading = false;
282
- let exactAlias = false;
283
- for (let element = 0; element < windows[window].length; element++) {
284
- const candidate = windows[window][element];
285
- const labels = [candidate.value, candidate.description, candidate.name];
286
- if (candidate.role === "AXHeading" && labels.some(label => label && headings.has(label)))
287
- heading = true;
288
- if (labels.some(label => label && aliases.has(label)))
289
- exactAlias = true;
290
- if (heading && exactAlias && candidate.role === "AXButton" && labels.includes("Cancel")) {
291
- return { window, element };
292
- }
293
- }
294
- }
295
- return null;
296
- }
297
134
  /** Foreground the live, assessment-scoped Terminal session before opening another shell. */
298
135
  export function focusExistingMacTerminal(alias, execFileFn = execFile) {
299
136
  if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
@@ -321,127 +158,6 @@ export function closeOwnedMacTerminal(alias, platform = process.platform, execFi
321
158
  });
322
159
  });
323
160
  }
324
- /** Close only a Claude window whose accessibility tree still names this assessment alias. */
325
- export function closeOwnedMacClaudeWindow(alias, platform = process.platform, execFileFn = execFile) {
326
- if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias) || platform !== "darwin")
327
- return Promise.resolve("unsupported");
328
- return new Promise((resolve, reject) => {
329
- execFileFn("/usr/bin/osascript", ["-e", closeClaudeWindowScript, alias], { timeout: 10000 }, (error, stdout) => {
330
- if (error)
331
- return reject(error);
332
- const outcome = String(stdout).trim();
333
- if (outcome === "closed" || outcome === "not_found")
334
- return resolve(outcome);
335
- if (outcome === "retry")
336
- return reject(new Error("The owned Claude assessment window could not be closed safely"));
337
- reject(new Error("Claude returned an unknown cleanup result"));
338
- });
339
- });
340
- }
341
- function execFileOutput(command, args, execFileFn) {
342
- return new Promise((resolve, reject) => {
343
- execFileFn(command, args, { timeout: 2500 }, (error, stdout) => error ? reject(error) : resolve(String(stdout).trim()));
344
- });
345
- }
346
- /** Identify Claude's main process strongly enough to reject PID reuse. */
347
- export async function macClaudeProcess(platform = process.platform, execFileFn = execFile) {
348
- if (platform !== "darwin")
349
- return null;
350
- let rawPid;
351
- try {
352
- rawPid = await execFileOutput("/usr/bin/pgrep", ["-x", "Claude"], execFileFn);
353
- }
354
- catch (error) {
355
- // pgrep 1 means no matching process. Any other failure is unknown, and
356
- // must not be mistaken for permission to take ownership of Claude.
357
- if (typeof error === "object" && error && "code" in error && error.code === 1)
358
- return null;
359
- throw error;
360
- }
361
- const pid = Number(rawPid.split(/\s+/)[0]);
362
- if (!Number.isSafeInteger(pid) || pid <= 1)
363
- throw new Error("Claude returned an invalid process identity");
364
- const startedAt = await execFileOutput("/bin/ps", ["-p", String(pid), "-o", "lstart="], execFileFn);
365
- if (!startedAt)
366
- throw new Error("Claude process start time is unavailable");
367
- return { pid, startedAt };
368
- }
369
- /** Identify ChatGPT App's main process strongly enough to reject PID reuse. */
370
- export async function macCodexProcess(appCommand, platform = process.platform, execFileFn = execFile) {
371
- if (platform !== "darwin")
372
- return null;
373
- const application = /(?:^|\/)Codex(?:\.app(?:\/Contents\/MacOS\/Codex)?)?$/.test(appCommand ?? "") ? "Codex" : "ChatGPT";
374
- const executable = application === "Codex"
375
- ? /\/Codex\.app\/Contents\/MacOS\/Codex$/
376
- : /\/ChatGPT\.app\/Contents\/MacOS\/ChatGPT$/;
377
- // macOS truncates this Electron process's comm value for pgrep. Read the
378
- // executable column and accept only the app bundle's main executable.
379
- const processes = await execFileOutput("/bin/ps", ["-axo", "pid=,comm="], execFileFn);
380
- const match = processes.split("\n").map(line => /^\s*(\d+)\s+(.+)$/.exec(line))
381
- .find(row => row && executable.test(row[2]));
382
- if (!match)
383
- return null;
384
- const pid = Number(match[1]);
385
- if (!Number.isSafeInteger(pid) || pid <= 1)
386
- throw new Error(`${application} App returned an invalid process identity`);
387
- const startedAt = await execFileOutput("/bin/ps", ["-p", String(pid), "-o", "lstart="], execFileFn);
388
- if (!startedAt)
389
- throw new Error(`${application} App process start time is unavailable`);
390
- return { pid, startedAt, application };
391
- }
392
- /** Quit Claude only when the still-running process is exactly the one Litmus launched. */
393
- export async function closeOwnedMacClaudeProcess(expected, platform = process.platform, execFileFn = execFile, wait = ms => new Promise(resolve => setTimeout(resolve, ms))) {
394
- if (platform !== "darwin" || !Number.isSafeInteger(expected.pid) || expected.pid <= 1 || !expected.startedAt)
395
- return "unsupported";
396
- const current = await macClaudeProcess(platform, execFileFn);
397
- if (!current)
398
- return "not_found";
399
- if (current.pid !== expected.pid || current.startedAt !== expected.startedAt)
400
- return "ownership_changed";
401
- await execFileOutput("/usr/bin/osascript", ["-e", 'tell application "Claude" to quit'], execFileFn);
402
- for (let attempt = 0; attempt < 20; attempt++) {
403
- const remaining = await macClaudeProcess(platform, execFileFn);
404
- if (!remaining || remaining.pid !== expected.pid || remaining.startedAt !== expected.startedAt)
405
- return "closed";
406
- await wait(100);
407
- }
408
- throw new Error("The Litmus-launched Claude process did not quit");
409
- }
410
- /** Close the assessment-owned Claude process, or its exact alias window after a restart. */
411
- export async function closeOwnedMacClaudeSession(alias, expected, windowLaunched, platform = process.platform, execFileFn = execFile, wait = ms => new Promise(resolve => setTimeout(resolve, ms))) {
412
- // Archive the exact assessment workspace first. Quitting a process that
413
- // Litmus launched closes its native window but leaves Claude's persisted
414
- // sessions behind, so they reappear the next time Claude opens.
415
- const windowOutcome = windowLaunched
416
- ? await closeOwnedMacClaudeWindow(alias, platform, execFileFn)
417
- : "not_found";
418
- if (expected) {
419
- const outcome = await closeOwnedMacClaudeProcess(expected, platform, execFileFn, wait);
420
- if (outcome !== "ownership_changed")
421
- return outcome;
422
- }
423
- return windowOutcome;
424
- }
425
- /** Quit ChatGPT App only when the running process is exactly the one Litmus launched. */
426
- export async function closeOwnedMacCodexProcess(expected, platform = process.platform, execFileFn = execFile, wait = ms => new Promise(resolve => setTimeout(resolve, ms))) {
427
- if (platform !== "darwin" || !Number.isSafeInteger(expected.pid) || expected.pid <= 1 || !expected.startedAt)
428
- return "unsupported";
429
- if (expected.application !== "ChatGPT" && expected.application !== "Codex")
430
- return "unsupported";
431
- const current = await macCodexProcess(expected.application, platform, execFileFn);
432
- if (!current)
433
- return "not_found";
434
- if (current.pid !== expected.pid || current.startedAt !== expected.startedAt)
435
- return "ownership_changed";
436
- await execFileOutput("/usr/bin/osascript", ["-e", `tell application "${expected.application}" to quit`], execFileFn);
437
- for (let attempt = 0; attempt < 20; attempt++) {
438
- const remaining = await macCodexProcess(expected.application, platform, execFileFn);
439
- if (!remaining || remaining.pid !== expected.pid || remaining.startedAt !== expected.startedAt)
440
- return "closed";
441
- await wait(100);
442
- }
443
- throw new Error("The Litmus-launched ChatGPT App process did not quit");
444
- }
445
161
  export async function openTerminal(alias, terminal, requestId) {
446
162
  if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
447
163
  return false;
@@ -470,7 +186,7 @@ export function removeTerminalLauncher(alias, home = os.homedir()) {
470
186
  rmSync(path.join(home, ".litmus", "launchers", `${alias}.command`), { force: true });
471
187
  }
472
188
  /** Isolate existing fatal/exit paths and synchronous probes from the heartbeat process. */
473
- export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation, remoteReady, onRemoteReady, onLocalOpened) {
189
+ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation, remoteReady, onRemoteReady) {
474
190
  return new Promise(resolve => {
475
191
  let result = "action_required";
476
192
  let prepared = null;
@@ -495,9 +211,6 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
495
211
  execArgv: [], env,
496
212
  stdio: ["ignore", "inherit", "inherit", "ipc"],
497
213
  });
498
- // This is the local process boundary. Remote attachment is deliberately
499
- // measured later by the managed readiness event/probe.
500
- child.once("spawn", () => onLocalOpened?.("ok"));
501
214
  child.on("message", message => {
502
215
  if (!message || typeof message !== "object")
503
216
  return;
@@ -535,7 +248,7 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
535
248
  });
536
249
  const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", stop); };
537
250
  const timer = setTimeout(() => { child.kill(); resolve("action_required"); }, 240000);
538
- child.once("error", () => { onLocalOpened?.("failed"); cleanup(); resolve("action_required"); });
251
+ child.once("error", () => { cleanup(); resolve("action_required"); });
539
252
  child.once("exit", code => {
540
253
  cleanup();
541
254
  if (!remembered && code === 0 && result === "dispatched" && prepared?.tool === tool)
@@ -602,8 +315,6 @@ export async function runPortalLauncher(options) {
602
315
  const launcherStarted = performance.now();
603
316
  const timing = options.reportTiming ?? (() => { });
604
317
  timing("cli_started", Math.max(0, Date.now() - (options.connectStartedAt ?? Date.now())));
605
- timing("connect_started", Math.max(0, Date.now() - (options.connectStartedAt ?? Date.now())));
606
- timing("detection_started", 0);
607
318
  const abort = new AbortController();
608
319
  const stop = () => abort.abort();
609
320
  options.signal?.addEventListener("abort", stop, { once: true });
@@ -660,7 +371,6 @@ export async function runPortalLauncher(options) {
660
371
  }, abort.signal);
661
372
  let seenCommandId = null;
662
373
  const seenCommands = new Set();
663
- const pendingLaunches = new Set();
664
374
  let longPoll = false;
665
375
  let readinessSupported = false;
666
376
  let preparationInventorySupported = false;
@@ -778,47 +488,28 @@ export async function runPortalLauncher(options) {
778
488
  const inventoryElapsed = performance.now() - launcherStarted;
779
489
  timing("tool_inventory_revalidated", inventoryElapsed, { sessionId: registered.session_id });
780
490
  timing("tool_inventory_complete", inventoryElapsed, { sessionId: registered.session_id });
781
- timing("detection_completed", inventoryElapsed, { sessionId: registered.session_id });
782
491
  options.onInventoryRevalidated?.(discovered, registered.workspace_generation);
783
492
  const dispatchCommand = (command) => {
784
493
  if (seenCommands.has(command.id))
785
494
  return;
786
495
  const commandReceived = performance.now();
787
496
  timing("command_received", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
788
- timing("launch_requested", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
789
497
  // A poll can redeliver an opening command after its response was lost.
790
498
  // Record before launching, including while result delivery retries.
791
499
  seenCommands.add(command.id);
792
500
  seenCommandId = command.id;
793
- const launchTask = (async () => {
501
+ void (async () => {
794
502
  let outcome = { status: "failed" };
795
503
  if (toolIds().includes(command.tool)) {
796
504
  timing("os_open_started", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
797
505
  const remoteReady = waitForEditorReadiness(command.tool);
798
506
  try {
799
- let localOpenedReported = false;
800
- const onLocalOpened = (localOutcome = "ok") => {
801
- if (localOpenedReported)
802
- return;
803
- localOpenedReported = true;
804
- timing("local_process_opened", performance.now() - commandReceived, {
805
- tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: localOutcome,
806
- });
807
- };
808
- const launched = await options.launch(command.tool, installed, abort.signal, {
809
- requestId: command.id,
810
- ...(command.generation ? { generation: command.generation } : {}),
811
- ...(remoteReady ? { remoteReady } : {}),
812
- onLocalOpened,
813
- });
507
+ const launched = await options.launch(command.tool, installed, abort.signal, { requestId: command.id, ...(command.generation ? { generation: command.generation } : {}), ...(remoteReady ? { remoteReady } : {}) });
814
508
  outcome = typeof launched === "string" ? { status: launched } : launched;
815
- if (!localOpenedReported && outcome.status === "failed")
816
- onLocalOpened("failed");
817
509
  }
818
510
  catch { /* fixed failure */ }
819
511
  const openElapsed = performance.now() - commandReceived;
820
- const osOpened = outcome.status === "dispatched" || outcome.reason === "confirmation_required";
821
- timing("os_open_finished", openElapsed, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: osOpened ? "ok" : "failed" });
512
+ timing("os_open_finished", openElapsed, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: outcome.status === "dispatched" ? "ok" : "failed" });
822
513
  }
823
514
  if (abort.signal.aborted)
824
515
  return;
@@ -847,8 +538,6 @@ export async function runPortalLauncher(options) {
847
538
  }
848
539
  }
849
540
  })();
850
- pendingLaunches.add(launchTask);
851
- void launchTask.then(() => pendingLaunches.delete(launchTask), () => pendingLaunches.delete(launchTask));
852
541
  };
853
542
  const preparationReport = (preparingTools, readyTools = []) => preparationInventorySupported ? {
854
543
  tools: [...new Set([...readyTools, ...preparingTools.filter(i => !i.unavailable).map(i => i.tool)])],
@@ -860,53 +549,48 @@ export async function runPortalLauncher(options) {
860
549
  const prepareInstalledTools = async (preparingTools, readyTools = []) => {
861
550
  if (!options.prepareTools)
862
551
  return;
863
- const preparationPreference = { tool: null };
864
552
  const pendingTools = new Set(preparingTools.filter(tool => !tool.unavailable).map(tool => tool.tool));
865
553
  const ready = new Set(readyTools);
554
+ let reportInFlight;
555
+ let reportRequested = false;
866
556
  let preparationEnded = false;
867
557
  const currentPreparing = () => installed.filter(tool => pendingTools.has(tool.tool));
868
- const pollPreparation = async (waitSeconds) => {
558
+ const publishPreparation = () => {
869
559
  if (!registered.progress_updates || preparationEnded)
870
- return true;
871
- const query = new URLSearchParams({ wait_seconds: String(waitSeconds) });
872
- if (seenCommandId)
873
- query.set("seen_command_id", seenCommandId);
874
- const reply = await call(`/sessions/${session.session_id}/poll?${query}`, preparationReport(currentPreparing(), [...ready])).catch(() => null);
875
- if (!reply)
876
- return false;
877
- acceptEditorReadiness(reply?.ready_tools);
878
- if (reply?.preferred_tool && pendingTools.has(reply.preferred_tool))
879
- preparationPreference.tool = reply.preferred_tool;
880
- if (reply?.command)
881
- dispatchCommand(reply.command);
882
- return true;
560
+ return reportInFlight ?? Promise.resolve();
561
+ reportRequested = true;
562
+ if (!reportInFlight)
563
+ reportInFlight = (async () => {
564
+ while (reportRequested && !preparationEnded) {
565
+ reportRequested = false;
566
+ const query = seenCommandId ? `?seen_command_id=${encodeURIComponent(seenCommandId)}` : "";
567
+ const reply = await call(`/sessions/${session.session_id}/poll${query}`, preparationReport(currentPreparing(), [...ready])).catch(() => null);
568
+ acceptEditorReadiness(reply?.ready_tools);
569
+ if (reply?.command) {
570
+ dispatchCommand(reply.command);
571
+ // Acknowledge receipt promptly; otherwise a slow opener blocks
572
+ // delivery of another ready tool until the lease renewal.
573
+ reportRequested = true;
574
+ }
575
+ }
576
+ })().finally(() => { reportInFlight = undefined; });
577
+ return reportInFlight;
883
578
  };
884
- await pollPreparation(0);
885
- let preferencePoll;
886
- let preferencePollTimer;
887
- const armPreferencePoll = () => {
888
- if (!registered.progress_updates || preparationEnded || abort.signal.aborted)
579
+ await publishPreparation();
580
+ // Preparing a matching editor server may outlast the initial mailbox
581
+ // lease. Renew as connecting, without claiming readiness or starting time.
582
+ // Drain any in-flight renewal before the first ready poll, so a delayed
583
+ // response cannot put a connected laptop back into preparation.
584
+ let renewalTimer;
585
+ const renewPreparation = () => {
586
+ if (preparationEnded || abort.signal.aborted)
889
587
  return;
890
- preferencePoll = pollPreparation(3);
891
- void preferencePoll.then(succeeded => {
892
- preferencePoll = undefined;
893
- // A legacy backend may ignore wait_seconds and answer immediately.
894
- // Keep that path under the server's 30/minute limit, and back off
895
- // further after a refusal or transport failure.
588
+ void publishPreparation().finally(() => {
896
589
  if (!preparationEnded && !abort.signal.aborted)
897
- preferencePollTimer = setTimeout(armPreferencePoll, succeeded ? 100 : 2000);
590
+ renewalTimer = setTimeout(renewPreparation, 15000);
898
591
  });
899
592
  };
900
- armPreferencePoll();
901
- preparationPreference.refresh = async () => {
902
- if (!registered.progress_updates || preparationEnded || abort.signal.aborted)
903
- return;
904
- const activePoll = preferencePoll;
905
- if (activePoll)
906
- await activePoll;
907
- else
908
- await pollPreparation(0);
909
- };
593
+ renewalTimer = setTimeout(renewPreparation, 15000);
910
594
  try {
911
595
  const preparesEntireInventory = preparingTools.length === installed.length
912
596
  && preparingTools.every(tool => installed.some(candidate => candidate.tool === tool.tool));
@@ -917,7 +601,8 @@ export async function runPortalLauncher(options) {
917
601
  ready.delete(prepared.tool);
918
602
  else
919
603
  ready.add(prepared.tool);
920
- }, registered.workspace_generation, preparationPreference);
604
+ void publishPreparation();
605
+ }, registered.workspace_generation);
921
606
  if (preparesEntireInventory)
922
607
  installed = preparedTools;
923
608
  else {
@@ -926,10 +611,9 @@ export async function runPortalLauncher(options) {
926
611
  }
927
612
  }
928
613
  finally {
614
+ clearTimeout(renewalTimer);
615
+ await reportInFlight;
929
616
  preparationEnded = true;
930
- if (preferencePollTimer)
931
- clearTimeout(preferencePollTimer);
932
- await preferencePoll;
933
617
  }
934
618
  };
935
619
  await prepareInstalledTools(installed);
@@ -1034,9 +718,6 @@ export async function runPortalLauncher(options) {
1034
718
  completeLauncher("cancelled");
1035
719
  stopInstallationWatch();
1036
720
  abort.abort();
1037
- // A launch may still be recording the exact app process that Litmus owns.
1038
- // Do not let confirmed-submission cleanup read and delete the journal first.
1039
- await Promise.allSettled([...pendingLaunches]);
1040
721
  if (session)
1041
722
  await call(`/sessions/${session.session_id}`, undefined, "DELETE").catch(() => { });
1042
723
  options.signal?.removeEventListener("abort", stop);