litmus-cli 1.5.2 → 1.5.4

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