litmus-cli 1.5.1 → 1.5.2-beta.10

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 (76) hide show
  1. package/dist/commands/connect.d.ts.map +1 -1
  2. package/dist/commands/connect.js +233 -109
  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 +7 -2
  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 +4 -1
  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 +19 -10
  12. package/dist/lib/ai-tracking.d.ts +2 -1
  13. package/dist/lib/ai-tracking.d.ts.map +1 -1
  14. package/dist/lib/ai-tracking.js +26 -8
  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 +6 -0
  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 +3 -0
  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 +3 -0
  28. package/dist/lib/backlog-flush.js.map +1 -1
  29. package/dist/lib/capture-selftest.d.ts +9 -0
  30. package/dist/lib/capture-selftest.d.ts.map +1 -1
  31. package/dist/lib/capture-selftest.js +4 -2
  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 +48 -38
  35. package/dist/lib/connect-skills.js.map +1 -1
  36. package/dist/lib/cursor-session.d.ts +1 -0
  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 +16 -0
  41. package/dist/lib/hosted-capture.d.ts.map +1 -1
  42. package/dist/lib/hosted-capture.js +14 -1
  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 +4 -0
  46. package/dist/lib/hosted-transcripts.js.map +1 -1
  47. package/dist/lib/hosted-watcher.js +5 -0
  48. package/dist/lib/hosted-watcher.js.map +1 -1
  49. package/dist/lib/isolated-host-policy.d.ts +4 -0
  50. package/dist/lib/isolated-host-policy.d.ts.map +1 -0
  51. package/dist/lib/isolated-host-policy.js +17 -0
  52. package/dist/lib/isolated-host-policy.js.map +1 -0
  53. package/dist/lib/launcher-cleanup-journal.d.ts +34 -0
  54. package/dist/lib/launcher-cleanup-journal.d.ts.map +1 -1
  55. package/dist/lib/launcher-cleanup-journal.js +75 -1
  56. package/dist/lib/launcher-cleanup-journal.js.map +1 -1
  57. package/dist/lib/portal-launcher.d.ts +46 -3
  58. package/dist/lib/portal-launcher.d.ts.map +1 -1
  59. package/dist/lib/portal-launcher.js +465 -42
  60. package/dist/lib/portal-launcher.js.map +1 -1
  61. package/dist/lib/schemas.d.ts +1 -0
  62. package/dist/lib/schemas.d.ts.map +1 -1
  63. package/dist/lib/schemas.js +1 -0
  64. package/dist/lib/schemas.js.map +1 -1
  65. package/dist/lib/skill-import.d.ts +4 -4
  66. package/dist/lib/skill-import.js +4 -4
  67. package/dist/lib/ssh-config-file.d.ts +1 -1
  68. package/dist/lib/ssh-config-file.d.ts.map +1 -1
  69. package/dist/lib/ssh-config-file.js +37 -3
  70. package/dist/lib/ssh-config-file.js.map +1 -1
  71. package/dist/lib/watcher.js +5 -0
  72. package/dist/lib/watcher.js.map +1 -1
  73. package/dist/lib/zip.d.ts.map +1 -1
  74. package/dist/lib/zip.js +2 -1
  75. package/dist/lib/zip.js.map +1 -1
  76. package/package.json +1 -1
@@ -36,13 +36,14 @@ 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),
39
+ stage, source: "cli", elapsed_ms: Math.min(elapsedMs, 3600001), event_at_ms: Date.now(),
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 } : {}),
46
47
  }),
47
48
  }).catch(() => { });
48
49
  }
@@ -131,6 +132,255 @@ const closeTerminalScript = `on run argv
131
132
  return "not_found"
132
133
  end tell
133
134
  end run`;
135
+ const closeEditorWindowScript = `on run argv
136
+ set assessmentAlias to item 1 of argv
137
+ set closedCount to 0
138
+ set inspectionFailed to false
139
+ tell application "System Events"
140
+ repeat with processName in {"Code", "Cursor"}
141
+ if exists process processName then
142
+ tell process processName
143
+ repeat with candidateWindow in windows
144
+ set ownedWindow to false
145
+ try
146
+ if my editorTextOwnsAlias(name of candidateWindow as text, assessmentAlias) then set ownedWindow to true
147
+ end try
148
+ if not ownedWindow then
149
+ try
150
+ repeat with candidateElement in entire contents of candidateWindow
151
+ set labels to {}
152
+ try
153
+ set end of labels to value of candidateElement as text
154
+ end try
155
+ try
156
+ set end of labels to description of candidateElement as text
157
+ end try
158
+ try
159
+ set end of labels to name of candidateElement as text
160
+ end try
161
+ repeat with candidateLabel in labels
162
+ if my editorTextOwnsAlias(candidateLabel as text, assessmentAlias) then
163
+ set ownedWindow to true
164
+ exit repeat
165
+ end if
166
+ end repeat
167
+ if ownedWindow then exit repeat
168
+ end repeat
169
+ on error
170
+ set inspectionFailed to true
171
+ end try
172
+ end if
173
+ if ownedWindow then
174
+ -- A disconnected VS Code-family window can cover itself with a
175
+ -- modal alert. Dismiss only the alert that belongs to this exact
176
+ -- assessment alias before closing the same native window.
177
+ try
178
+ repeat with candidateElement in entire contents of candidateWindow
179
+ if role of candidateElement is "AXButton" then
180
+ set buttonLabel to ""
181
+ try
182
+ set buttonLabel to name of candidateElement as text
183
+ end try
184
+ if buttonLabel is "Close Remote" then
185
+ perform action "AXPress" of candidateElement
186
+ delay 0.2
187
+ exit repeat
188
+ end if
189
+ end if
190
+ end repeat
191
+ end try
192
+ try
193
+ perform action "AXClose" of candidateWindow
194
+ on error
195
+ return "retry"
196
+ end try
197
+ delay 0.2
198
+ try
199
+ if visible of candidateWindow then return "retry"
200
+ end try
201
+ set closedCount to closedCount + 1
202
+ end if
203
+ end repeat
204
+ end tell
205
+ end if
206
+ end repeat
207
+ end tell
208
+ if closedCount > 0 then return "closed"
209
+ if inspectionFailed then return "retry"
210
+ return "not_found"
211
+ end run
212
+
213
+ on editorTextOwnsAlias(candidateText, assessmentAlias)
214
+ set remoteMarker to "SSH: " & assessmentAlias
215
+ if candidateText is remoteMarker then return true
216
+ if candidateText ends with remoteMarker then return true
217
+ if candidateText contains (remoteMarker & "]") then return true
218
+ if candidateText contains (remoteMarker & " —") then return true
219
+ if candidateText contains ("connection to \\"" & assessmentAlias & "\\"") then return true
220
+ return false
221
+ end editorTextOwnsAlias`;
222
+ const closeClaudeWindowScript = `on run argv
223
+ set assessmentAlias to item 1 of argv
224
+ set assessmentWorkspace to "workspace · " & assessmentAlias
225
+ set closedCount to 0
226
+ tell application "System Events"
227
+ if not (exists process "Claude") then return "not_found"
228
+ tell process "Claude"
229
+ repeat 20 times
230
+ set inspectedWindow to false
231
+ set matchingWindow to missing value
232
+ set sessionMenuButton to missing value
233
+ set pendingConfirmationCancel to missing value
234
+ repeat with candidateWindow in windows
235
+ set inAssessmentWorkspace to false
236
+ set hasPendingConfirmationHeading to false
237
+ set hasPendingConfirmationAlias to false
238
+ try
239
+ set windowContents to entire contents of candidateWindow
240
+ set inspectedWindow to true
241
+ repeat with candidateElement in windowContents
242
+ try
243
+ set candidateRole to role of candidateElement as text
244
+ set candidateValue to ""
245
+ set candidateDescription to ""
246
+ set candidateName to ""
247
+ try
248
+ set candidateValue to value of candidateElement as text
249
+ end try
250
+ try
251
+ set candidateDescription to description of candidateElement as text
252
+ end try
253
+ try
254
+ set candidateName to name of candidateElement as text
255
+ end try
256
+ if candidateRole is "AXHeading" then
257
+ 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
258
+ set hasPendingConfirmationHeading to true
259
+ end if
260
+ 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
261
+ set inAssessmentWorkspace to true
262
+ set matchingWindow to candidateWindow
263
+ else if inAssessmentWorkspace then
264
+ exit repeat
265
+ end if
266
+ else if inAssessmentWorkspace and candidateRole is "AXPopUpButton" then
267
+ if candidateDescription starts with "More options for " or candidateName starts with "More options for " then
268
+ set sessionMenuButton to candidateElement
269
+ exit repeat
270
+ end if
271
+ end if
272
+ -- Claude can leave its assessment-scoped SSH confirmation over
273
+ -- an otherwise unrelated main window. Dismiss only a dialog
274
+ -- that exposes this exact alias; never close the whole window
275
+ -- merely because the pending handoff is visible.
276
+ if candidateValue is assessmentAlias or candidateValue is "on " & assessmentAlias or candidateValue is "on " & assessmentAlias then
277
+ set hasPendingConfirmationAlias to true
278
+ else if hasPendingConfirmationHeading and hasPendingConfirmationAlias and candidateRole is "AXButton" then
279
+ if candidateValue is "Cancel" or candidateDescription is "Cancel" or candidateName is "Cancel" then
280
+ set pendingConfirmationCancel to candidateElement
281
+ exit repeat
282
+ end if
283
+ end if
284
+ -- Older Claude builds exposed the alias as a bare value rather
285
+ -- than a workspace heading. Preserve that exact-match fallback.
286
+ if matchingWindow is missing value and candidateValue is assessmentAlias then
287
+ set matchingWindow to candidateWindow
288
+ end if
289
+ end try
290
+ end repeat
291
+ end try
292
+ if pendingConfirmationCancel is not missing value then exit repeat
293
+ if sessionMenuButton is not missing value then exit repeat
294
+ end repeat
295
+ if pendingConfirmationCancel is not missing value then
296
+ try
297
+ perform action "AXPress" of pendingConfirmationCancel
298
+ delay 0.25
299
+ set closedCount to closedCount + 1
300
+ -- Re-scan until the exact alias is gone. A duplicate handoff can
301
+ -- stack more than one confirmation dialog for the same workspace.
302
+ on error
303
+ return "retry"
304
+ end try
305
+ else if matchingWindow is missing value then
306
+ if closedCount > 0 then return "closed"
307
+ if (count of windows) is 0 then return "not_found"
308
+ if not inspectedWindow then return "retry"
309
+ return "not_found"
310
+ else if sessionMenuButton is not missing value then
311
+ try
312
+ perform action "AXPress" of sessionMenuButton
313
+ delay 0.1
314
+ set archiveItem to missing value
315
+ repeat with menuElement in entire contents of matchingWindow
316
+ try
317
+ set menuValue to value of menuElement as text
318
+ set menuDescription to ""
319
+ set menuName to ""
320
+ try
321
+ set menuDescription to description of menuElement as text
322
+ end try
323
+ try
324
+ set menuName to name of menuElement as text
325
+ end try
326
+ if menuValue is "Archive" or menuDescription is "Archive" or menuName is "Archive" then
327
+ set archiveItem to menuElement
328
+ exit repeat
329
+ end if
330
+ end try
331
+ end repeat
332
+ if archiveItem is missing value then return "retry"
333
+ perform action "AXPress" of archiveItem
334
+ delay 0.25
335
+ set closedCount to closedCount + 1
336
+ -- Keep archiving until the exact assessment workspace contains no
337
+ -- sessions. Other workspace groups and chats are never inspected.
338
+ on error
339
+ return "retry"
340
+ end try
341
+ else
342
+ try
343
+ perform action "AXClose" of matchingWindow
344
+ on error
345
+ return "retry"
346
+ end try
347
+ delay 0.25
348
+ set closedCount to closedCount + 1
349
+ end if
350
+ end repeat
351
+ -- A close request that leaves the exact alias visible is not verified.
352
+ return "retry"
353
+ end tell
354
+ end tell
355
+ end run`;
356
+ /**
357
+ * Testable semantic model of the ownership gate used by the native Claude
358
+ * cleanup script. The runtime still uses System Events, but both paths require
359
+ * the confirmation heading, exact assessment alias and Cancel button to occur
360
+ * in the same window and in that order.
361
+ */
362
+ export function ownedClaudePendingDialogCancel(alias, windows) {
363
+ if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
364
+ return null;
365
+ const headings = new Set(["Use this SSH connection?", "Trust this workspace?"]);
366
+ const aliases = new Set([alias, `on ${alias}`, `on ${alias}`]);
367
+ for (let window = 0; window < windows.length; window++) {
368
+ let heading = false;
369
+ let exactAlias = false;
370
+ for (let element = 0; element < windows[window].length; element++) {
371
+ const candidate = windows[window][element];
372
+ const labels = [candidate.value, candidate.description, candidate.name];
373
+ if (candidate.role === "AXHeading" && labels.some(label => label && headings.has(label)))
374
+ heading = true;
375
+ if (labels.some(label => label && aliases.has(label)))
376
+ exactAlias = true;
377
+ if (heading && exactAlias && candidate.role === "AXButton" && labels.includes("Cancel")) {
378
+ return { window, element };
379
+ }
380
+ }
381
+ }
382
+ return null;
383
+ }
134
384
  /** Foreground the live, assessment-scoped Terminal session before opening another shell. */
135
385
  export function focusExistingMacTerminal(alias, execFileFn = execFile) {
136
386
  if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
@@ -158,6 +408,144 @@ export function closeOwnedMacTerminal(alias, platform = process.platform, execFi
158
408
  });
159
409
  });
160
410
  }
411
+ /** Close only VS Code-family windows whose accessibility tree names this assessment alias. */
412
+ export function closeOwnedMacEditorWindows(alias, platform = process.platform, execFileFn = execFile) {
413
+ if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias) || platform !== "darwin")
414
+ return Promise.resolve("unsupported");
415
+ return new Promise((resolve, reject) => {
416
+ execFileFn("/usr/bin/osascript", ["-e", closeEditorWindowScript, alias], { timeout: 5000 }, (error, stdout) => {
417
+ if (error)
418
+ return reject(error);
419
+ const outcome = String(stdout).trim();
420
+ if (outcome === "closed" || outcome === "not_found")
421
+ return resolve(outcome);
422
+ if (outcome === "retry")
423
+ return reject(new Error("The owned assessment editor window could not be closed safely"));
424
+ reject(new Error("The editor returned an unknown cleanup result"));
425
+ });
426
+ });
427
+ }
428
+ /** Close only a Claude window whose accessibility tree still names this assessment alias. */
429
+ export function closeOwnedMacClaudeWindow(alias, platform = process.platform, execFileFn = execFile) {
430
+ if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias) || platform !== "darwin")
431
+ return Promise.resolve("unsupported");
432
+ return new Promise((resolve, reject) => {
433
+ execFileFn("/usr/bin/osascript", ["-e", closeClaudeWindowScript, alias], { timeout: 10000 }, (error, stdout) => {
434
+ if (error)
435
+ return reject(error);
436
+ const outcome = String(stdout).trim();
437
+ if (outcome === "closed" || outcome === "not_found")
438
+ return resolve(outcome);
439
+ if (outcome === "retry")
440
+ return reject(new Error("The owned Claude assessment window could not be closed safely"));
441
+ reject(new Error("Claude returned an unknown cleanup result"));
442
+ });
443
+ });
444
+ }
445
+ function execFileOutput(command, args, execFileFn) {
446
+ return new Promise((resolve, reject) => {
447
+ execFileFn(command, args, { timeout: 2500 }, (error, stdout) => error ? reject(error) : resolve(String(stdout).trim()));
448
+ });
449
+ }
450
+ /** Identify Claude's main process strongly enough to reject PID reuse. */
451
+ export async function macClaudeProcess(platform = process.platform, execFileFn = execFile) {
452
+ if (platform !== "darwin")
453
+ return null;
454
+ let rawPid;
455
+ try {
456
+ rawPid = await execFileOutput("/usr/bin/pgrep", ["-x", "Claude"], execFileFn);
457
+ }
458
+ catch (error) {
459
+ // pgrep 1 means no matching process. Any other failure is unknown, and
460
+ // must not be mistaken for permission to take ownership of Claude.
461
+ if (typeof error === "object" && error && "code" in error && error.code === 1)
462
+ return null;
463
+ throw error;
464
+ }
465
+ const pid = Number(rawPid.split(/\s+/)[0]);
466
+ if (!Number.isSafeInteger(pid) || pid <= 1)
467
+ throw new Error("Claude returned an invalid process identity");
468
+ const startedAt = await execFileOutput("/bin/ps", ["-p", String(pid), "-o", "lstart="], execFileFn);
469
+ if (!startedAt)
470
+ throw new Error("Claude process start time is unavailable");
471
+ return { pid, startedAt };
472
+ }
473
+ /** Identify ChatGPT App's main process strongly enough to reject PID reuse. */
474
+ export async function macCodexProcess(appCommand, platform = process.platform, execFileFn = execFile) {
475
+ if (platform !== "darwin")
476
+ return null;
477
+ const application = /(?:^|\/)Codex(?:\.app(?:\/Contents\/MacOS\/Codex)?)?$/.test(appCommand ?? "") ? "Codex" : "ChatGPT";
478
+ const executable = application === "Codex"
479
+ ? /\/Codex\.app\/Contents\/MacOS\/Codex$/
480
+ : /\/ChatGPT\.app\/Contents\/MacOS\/ChatGPT$/;
481
+ // macOS truncates this Electron process's comm value for pgrep. Read the
482
+ // executable column and accept only the app bundle's main executable.
483
+ const processes = await execFileOutput("/bin/ps", ["-axo", "pid=,comm="], execFileFn);
484
+ const match = processes.split("\n").map(line => /^\s*(\d+)\s+(.+)$/.exec(line))
485
+ .find(row => row && executable.test(row[2]));
486
+ if (!match)
487
+ return null;
488
+ const pid = Number(match[1]);
489
+ if (!Number.isSafeInteger(pid) || pid <= 1)
490
+ throw new Error(`${application} App returned an invalid process identity`);
491
+ const startedAt = await execFileOutput("/bin/ps", ["-p", String(pid), "-o", "lstart="], execFileFn);
492
+ if (!startedAt)
493
+ throw new Error(`${application} App process start time is unavailable`);
494
+ return { pid, startedAt, application };
495
+ }
496
+ /** Quit Claude only when the still-running process is exactly the one Litmus launched. */
497
+ export async function closeOwnedMacClaudeProcess(expected, platform = process.platform, execFileFn = execFile, wait = ms => new Promise(resolve => setTimeout(resolve, ms))) {
498
+ if (platform !== "darwin" || !Number.isSafeInteger(expected.pid) || expected.pid <= 1 || !expected.startedAt)
499
+ return "unsupported";
500
+ const current = await macClaudeProcess(platform, execFileFn);
501
+ if (!current)
502
+ return "not_found";
503
+ if (current.pid !== expected.pid || current.startedAt !== expected.startedAt)
504
+ return "ownership_changed";
505
+ await execFileOutput("/usr/bin/osascript", ["-e", 'tell application "Claude" to quit'], execFileFn);
506
+ for (let attempt = 0; attempt < 20; attempt++) {
507
+ const remaining = await macClaudeProcess(platform, execFileFn);
508
+ if (!remaining || remaining.pid !== expected.pid || remaining.startedAt !== expected.startedAt)
509
+ return "closed";
510
+ await wait(100);
511
+ }
512
+ throw new Error("The Litmus-launched Claude process did not quit");
513
+ }
514
+ /** Close the assessment-owned Claude process, or its exact alias window after a restart. */
515
+ export async function closeOwnedMacClaudeSession(alias, expected, windowLaunched, platform = process.platform, execFileFn = execFile, wait = ms => new Promise(resolve => setTimeout(resolve, ms))) {
516
+ // Archive the exact assessment workspace first. Quitting a process that
517
+ // Litmus launched closes its native window but leaves Claude's persisted
518
+ // sessions behind, so they reappear the next time Claude opens.
519
+ const windowOutcome = windowLaunched
520
+ ? await closeOwnedMacClaudeWindow(alias, platform, execFileFn)
521
+ : "not_found";
522
+ if (expected) {
523
+ const outcome = await closeOwnedMacClaudeProcess(expected, platform, execFileFn, wait);
524
+ if (outcome !== "ownership_changed")
525
+ return outcome;
526
+ }
527
+ return windowOutcome;
528
+ }
529
+ /** Quit ChatGPT App only when the running process is exactly the one Litmus launched. */
530
+ export async function closeOwnedMacCodexProcess(expected, platform = process.platform, execFileFn = execFile, wait = ms => new Promise(resolve => setTimeout(resolve, ms))) {
531
+ if (platform !== "darwin" || !Number.isSafeInteger(expected.pid) || expected.pid <= 1 || !expected.startedAt)
532
+ return "unsupported";
533
+ if (expected.application !== "ChatGPT" && expected.application !== "Codex")
534
+ return "unsupported";
535
+ const current = await macCodexProcess(expected.application, platform, execFileFn);
536
+ if (!current)
537
+ return "not_found";
538
+ if (current.pid !== expected.pid || current.startedAt !== expected.startedAt)
539
+ return "ownership_changed";
540
+ await execFileOutput("/usr/bin/osascript", ["-e", `tell application "${expected.application}" to quit`], execFileFn);
541
+ for (let attempt = 0; attempt < 20; attempt++) {
542
+ const remaining = await macCodexProcess(expected.application, platform, execFileFn);
543
+ if (!remaining || remaining.pid !== expected.pid || remaining.startedAt !== expected.startedAt)
544
+ return "closed";
545
+ await wait(100);
546
+ }
547
+ throw new Error("The Litmus-launched ChatGPT App process did not quit");
548
+ }
161
549
  export async function openTerminal(alias, terminal, requestId) {
162
550
  if (!/^litmus-[a-zA-Z0-9-]+$/.test(alias))
163
551
  return false;
@@ -186,7 +574,7 @@ export function removeTerminalLauncher(alias, home = os.homedir()) {
186
574
  rmSync(path.join(home, ".litmus", "launchers", `${alias}.command`), { force: true });
187
575
  }
188
576
  /** Isolate existing fatal/exit paths and synchronous probes from the heartbeat process. */
189
- export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation, remoteReady, onRemoteReady) {
577
+ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared, generation, remoteReady, onRemoteReady, onLocalOpened) {
190
578
  return new Promise(resolve => {
191
579
  let result = "action_required";
192
580
  let prepared = null;
@@ -211,6 +599,9 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
211
599
  execArgv: [], env,
212
600
  stdio: ["ignore", "inherit", "inherit", "ipc"],
213
601
  });
602
+ // This is the local process boundary. Remote attachment is deliberately
603
+ // measured later by the managed readiness event/probe.
604
+ child.once("spawn", () => onLocalOpened?.("ok"));
214
605
  child.on("message", message => {
215
606
  if (!message || typeof message !== "object")
216
607
  return;
@@ -248,7 +639,7 @@ export function openNativeEditor(tool, token, signal, forkFn = fork, onPrepared,
248
639
  });
249
640
  const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", stop); };
250
641
  const timer = setTimeout(() => { child.kill(); resolve("action_required"); }, 240000);
251
- child.once("error", () => { cleanup(); resolve("action_required"); });
642
+ child.once("error", () => { onLocalOpened?.("failed"); cleanup(); resolve("action_required"); });
252
643
  child.once("exit", code => {
253
644
  cleanup();
254
645
  if (!remembered && code === 0 && result === "dispatched" && prepared?.tool === tool)
@@ -315,6 +706,8 @@ export async function runPortalLauncher(options) {
315
706
  const launcherStarted = performance.now();
316
707
  const timing = options.reportTiming ?? (() => { });
317
708
  timing("cli_started", Math.max(0, Date.now() - (options.connectStartedAt ?? Date.now())));
709
+ timing("connect_started", Math.max(0, Date.now() - (options.connectStartedAt ?? Date.now())));
710
+ timing("detection_started", 0);
318
711
  const abort = new AbortController();
319
712
  const stop = () => abort.abort();
320
713
  options.signal?.addEventListener("abort", stop, { once: true });
@@ -371,6 +764,7 @@ export async function runPortalLauncher(options) {
371
764
  }, abort.signal);
372
765
  let seenCommandId = null;
373
766
  const seenCommands = new Set();
767
+ const pendingLaunches = new Set();
374
768
  let longPoll = false;
375
769
  let readinessSupported = false;
376
770
  let preparationInventorySupported = false;
@@ -488,28 +882,47 @@ export async function runPortalLauncher(options) {
488
882
  const inventoryElapsed = performance.now() - launcherStarted;
489
883
  timing("tool_inventory_revalidated", inventoryElapsed, { sessionId: registered.session_id });
490
884
  timing("tool_inventory_complete", inventoryElapsed, { sessionId: registered.session_id });
885
+ timing("detection_completed", inventoryElapsed, { sessionId: registered.session_id });
491
886
  options.onInventoryRevalidated?.(discovered, registered.workspace_generation);
492
887
  const dispatchCommand = (command) => {
493
888
  if (seenCommands.has(command.id))
494
889
  return;
495
890
  const commandReceived = performance.now();
496
891
  timing("command_received", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
892
+ timing("launch_requested", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
497
893
  // A poll can redeliver an opening command after its response was lost.
498
894
  // Record before launching, including while result delivery retries.
499
895
  seenCommands.add(command.id);
500
896
  seenCommandId = command.id;
501
- void (async () => {
897
+ const launchTask = (async () => {
502
898
  let outcome = { status: "failed" };
503
899
  if (toolIds().includes(command.tool)) {
504
900
  timing("os_open_started", 0, { tool: command.tool, sessionId: registered.session_id, requestId: command.id });
505
901
  const remoteReady = waitForEditorReadiness(command.tool);
506
902
  try {
507
- const launched = await options.launch(command.tool, installed, abort.signal, { requestId: command.id, ...(command.generation ? { generation: command.generation } : {}), ...(remoteReady ? { remoteReady } : {}) });
903
+ let localOpenedReported = false;
904
+ const onLocalOpened = (localOutcome = "ok") => {
905
+ if (localOpenedReported)
906
+ return;
907
+ localOpenedReported = true;
908
+ timing("local_process_opened", performance.now() - commandReceived, {
909
+ tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: localOutcome,
910
+ });
911
+ };
912
+ const launched = await options.launch(command.tool, installed, abort.signal, {
913
+ requestId: command.id,
914
+ ...(command.generation ? { generation: command.generation } : {}),
915
+ ...(remoteReady ? { remoteReady } : {}),
916
+ onLocalOpened,
917
+ });
508
918
  outcome = typeof launched === "string" ? { status: launched } : launched;
919
+ if (!localOpenedReported && outcome.status === "failed")
920
+ onLocalOpened("failed");
509
921
  }
510
922
  catch { /* fixed failure */ }
511
923
  const openElapsed = performance.now() - commandReceived;
512
- timing("os_open_finished", openElapsed, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: outcome.status === "dispatched" ? "ok" : "failed" });
924
+ const osOpened = outcome.status === "dispatched" || outcome.reason === "confirmation_required";
925
+ timing("os_open_finished", openElapsed, { tool: command.tool, sessionId: registered.session_id, requestId: command.id, outcome: osOpened ? "ok" : "failed" });
513
926
  }
514
927
  if (abort.signal.aborted)
515
928
  return;
@@ -538,6 +951,8 @@ export async function runPortalLauncher(options) {
538
951
  }
539
952
  }
540
953
  })();
954
+ pendingLaunches.add(launchTask);
955
+ void launchTask.then(() => pendingLaunches.delete(launchTask), () => pendingLaunches.delete(launchTask));
541
956
  };
542
957
  const preparationReport = (preparingTools, readyTools = []) => preparationInventorySupported ? {
543
958
  tools: [...new Set([...readyTools, ...preparingTools.filter(i => !i.unavailable).map(i => i.tool)])],
@@ -549,48 +964,53 @@ export async function runPortalLauncher(options) {
549
964
  const prepareInstalledTools = async (preparingTools, readyTools = []) => {
550
965
  if (!options.prepareTools)
551
966
  return;
967
+ const preparationPreference = { tool: null };
552
968
  const pendingTools = new Set(preparingTools.filter(tool => !tool.unavailable).map(tool => tool.tool));
553
969
  const ready = new Set(readyTools);
554
- let reportInFlight;
555
- let reportRequested = false;
556
970
  let preparationEnded = false;
557
971
  const currentPreparing = () => installed.filter(tool => pendingTools.has(tool.tool));
558
- const publishPreparation = () => {
972
+ const pollPreparation = async (waitSeconds) => {
559
973
  if (!registered.progress_updates || preparationEnded)
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;
974
+ return true;
975
+ const query = new URLSearchParams({ wait_seconds: String(waitSeconds) });
976
+ if (seenCommandId)
977
+ query.set("seen_command_id", seenCommandId);
978
+ const reply = await call(`/sessions/${session.session_id}/poll?${query}`, preparationReport(currentPreparing(), [...ready])).catch(() => null);
979
+ if (!reply)
980
+ return false;
981
+ acceptEditorReadiness(reply?.ready_tools);
982
+ if (reply?.preferred_tool && pendingTools.has(reply.preferred_tool))
983
+ preparationPreference.tool = reply.preferred_tool;
984
+ if (reply?.command)
985
+ dispatchCommand(reply.command);
986
+ return true;
578
987
  };
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)
988
+ await pollPreparation(0);
989
+ let preferencePoll;
990
+ let preferencePollTimer;
991
+ const armPreferencePoll = () => {
992
+ if (!registered.progress_updates || preparationEnded || abort.signal.aborted)
587
993
  return;
588
- void publishPreparation().finally(() => {
994
+ preferencePoll = pollPreparation(3);
995
+ void preferencePoll.then(succeeded => {
996
+ preferencePoll = undefined;
997
+ // A legacy backend may ignore wait_seconds and answer immediately.
998
+ // Keep that path under the server's 30/minute limit, and back off
999
+ // further after a refusal or transport failure.
589
1000
  if (!preparationEnded && !abort.signal.aborted)
590
- renewalTimer = setTimeout(renewPreparation, 15000);
1001
+ preferencePollTimer = setTimeout(armPreferencePoll, succeeded ? 100 : 2000);
591
1002
  });
592
1003
  };
593
- renewalTimer = setTimeout(renewPreparation, 15000);
1004
+ armPreferencePoll();
1005
+ preparationPreference.refresh = async () => {
1006
+ if (!registered.progress_updates || preparationEnded || abort.signal.aborted)
1007
+ return;
1008
+ const activePoll = preferencePoll;
1009
+ if (activePoll)
1010
+ await activePoll;
1011
+ else
1012
+ await pollPreparation(0);
1013
+ };
594
1014
  try {
595
1015
  const preparesEntireInventory = preparingTools.length === installed.length
596
1016
  && preparingTools.every(tool => installed.some(candidate => candidate.tool === tool.tool));
@@ -601,8 +1021,7 @@ export async function runPortalLauncher(options) {
601
1021
  ready.delete(prepared.tool);
602
1022
  else
603
1023
  ready.add(prepared.tool);
604
- void publishPreparation();
605
- }, registered.workspace_generation);
1024
+ }, registered.workspace_generation, preparationPreference);
606
1025
  if (preparesEntireInventory)
607
1026
  installed = preparedTools;
608
1027
  else {
@@ -611,9 +1030,10 @@ export async function runPortalLauncher(options) {
611
1030
  }
612
1031
  }
613
1032
  finally {
614
- clearTimeout(renewalTimer);
615
- await reportInFlight;
616
1033
  preparationEnded = true;
1034
+ if (preferencePollTimer)
1035
+ clearTimeout(preferencePollTimer);
1036
+ await preferencePoll;
617
1037
  }
618
1038
  };
619
1039
  await prepareInstalledTools(installed);
@@ -718,6 +1138,9 @@ export async function runPortalLauncher(options) {
718
1138
  completeLauncher("cancelled");
719
1139
  stopInstallationWatch();
720
1140
  abort.abort();
1141
+ // A launch may still be recording the exact app process that Litmus owns.
1142
+ // Do not let confirmed-submission cleanup read and delete the journal first.
1143
+ await Promise.allSettled([...pendingLaunches]);
721
1144
  if (session)
722
1145
  await call(`/sessions/${session.session_id}`, undefined, "DELETE").catch(() => { });
723
1146
  options.signal?.removeEventListener("abort", stop);