@slack/radar-mcp 1.21.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +114 -18
  2. package/dist/mcp/api-paths.d.ts +2 -2
  3. package/dist/mcp/api-paths.js +4 -19
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +210 -145
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/radar-export-get.d.ts +30 -0
  10. package/dist/mcp/radar-export-get.js +49 -0
  11. package/dist/mcp/radar-http.d.ts +22 -0
  12. package/dist/mcp/radar-http.js +61 -0
  13. package/dist/mcp/radar-response.d.ts +5 -1
  14. package/dist/mcp/radar-response.js +8 -3
  15. package/dist/mcp/session-backfill.js +3 -4
  16. package/dist/mcp/session-enable.d.ts +15 -0
  17. package/dist/mcp/session-enable.js +268 -19
  18. package/dist/mcp/snapshot.js +42 -26
  19. package/dist/mcp/sources-gate.js +6 -0
  20. package/dist/mcp/stale-dashboard.d.ts +23 -0
  21. package/dist/mcp/stale-dashboard.js +122 -0
  22. package/dist/mcp/switchboard-spool.d.ts +12 -0
  23. package/dist/mcp/switchboard-spool.js +107 -0
  24. package/dist/mcp/switchboard-tools.d.ts +9 -0
  25. package/dist/mcp/switchboard-tools.js +144 -6
  26. package/dist/mcp/test-cases.d.ts +14 -0
  27. package/dist/mcp/test-cases.js +77 -0
  28. package/dist/mcp/test-runs-tools.d.ts +8 -0
  29. package/dist/mcp/test-runs-tools.js +95 -0
  30. package/dist/mcp/tools.d.ts +4 -1
  31. package/dist/mcp/tools.js +101 -21
  32. package/dist/mcp/web-child-env.d.ts +4 -1
  33. package/dist/mcp/web-child-env.js +4 -1
  34. package/dist/shared/android.d.ts +44 -0
  35. package/dist/shared/android.js +234 -24
  36. package/dist/shared/constants.d.ts +9 -4
  37. package/dist/shared/constants.js +9 -4
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/ios-logs.d.ts +10 -0
  41. package/dist/shared/ios-logs.js +91 -0
  42. package/dist/shared/ios.d.ts +25 -2
  43. package/dist/shared/ios.js +157 -3
  44. package/dist/{web → shared}/log-session.d.ts +45 -31
  45. package/dist/shared/log-session.js +300 -0
  46. package/dist/shared/logcat-capture.js +17 -1
  47. package/dist/shared/radar-request-raw.d.ts +7 -0
  48. package/dist/shared/radar-request-raw.js +89 -0
  49. package/dist/shared/radar-token.d.ts +25 -0
  50. package/dist/shared/radar-token.js +164 -0
  51. package/dist/shared/stream.d.ts +3 -0
  52. package/dist/shared/stream.js +107 -15
  53. package/dist/shared/switchboard-host-store.d.ts +21 -0
  54. package/dist/shared/switchboard-host-store.js +166 -0
  55. package/dist/shared/switchboard-note.d.ts +15 -0
  56. package/dist/shared/switchboard-note.js +92 -0
  57. package/dist/shared/switchboard-report-file.d.ts +5 -0
  58. package/dist/shared/switchboard-report-file.js +26 -0
  59. package/dist/shared/switchboard-report.d.ts +20 -0
  60. package/dist/shared/switchboard-report.js +406 -0
  61. package/dist/shared/switchboard.d.ts +111 -2
  62. package/dist/shared/switchboard.js +436 -3
  63. package/dist/shared/transport.d.ts +49 -3
  64. package/dist/shared/version.d.ts +2 -0
  65. package/dist/shared/version.js +18 -0
  66. package/dist/shared/wire.d.ts +14 -1
  67. package/dist/web/install-app.d.ts +75 -8
  68. package/dist/web/install-app.js +330 -67
  69. package/dist/web/macapp/RadarApp.swift +487 -23
  70. package/dist/web/public/index.html +51 -9
  71. package/dist/web/public/next/app.js +33 -18
  72. package/dist/web/public/next/feed.js +102 -15
  73. package/dist/web/public/next/flags.js +3 -0
  74. package/dist/web/public/next/inspector.js +69 -3
  75. package/dist/web/public/next/prefs.js +5 -2
  76. package/dist/web/public/next/registry.js +18 -5
  77. package/dist/web/public/next/store.js +455 -29
  78. package/dist/web/public/next/switchboard-note.js +93 -0
  79. package/dist/web/public/next/toast.js +9 -5
  80. package/dist/web/public/next/voice-model.js +215 -35
  81. package/dist/web/public/next/voice.js +173 -18
  82. package/dist/web/server.d.ts +15 -11
  83. package/dist/web/server.js +690 -168
  84. package/dist/web/spec.d.ts +2 -1
  85. package/dist/web/spec.js +2 -1
  86. package/package.json +2 -2
  87. package/dist/web/log-session.js +0 -166
@@ -2,8 +2,8 @@
2
2
  //
3
3
  // WHY A NATIVE WRAPPER AND NOT JUST THE PWA. Installing the dashboard through Chrome or Safari
4
4
  // already gives you a dock icon and a standalone window, and that is genuinely enough IF the
5
- // server happens to be running. It usually is not: the dashboard auto-closes 5 minutes after its
6
- // last tab goes away (AUTO_CLOSE_GRACE_MS), so a dock click on a cold Mac lands on a dead port and
5
+ // server happens to be running. It usually is not: the dashboard auto-closes about 6 minutes after
6
+ // its last tab goes away (the 75 s tab liveness, then AUTO_CLOSE_GRACE_MS, then the sweep), so a dock click on a cold Mac lands on a dead port and
7
7
  // the window shows a browser connection error. A web app cannot start a local server, so no amount
8
8
  // of manifest work fixes that. This wrapper is the missing half: it ensures the server is up, THEN
9
9
  // shows the window.
@@ -25,9 +25,11 @@ import https from "https";
25
25
  import os from "os";
26
26
  import path from "path";
27
27
  import { fileURLToPath } from "url";
28
- import { WEB_PORT } from "./server.js";
29
- import { RADAR_VERSION } from "../shared/constants.js";
28
+ import { RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
29
+ import { compareVersions, parseVersion } from "../shared/version.js";
30
30
  const APP_NAME = "Slack Radar";
31
+ /** The Info.plist key recording the port an install baked in, so a later rebuild can keep it. */
32
+ const PORT_PLIST_KEY = "SlackRadarWebPort";
31
33
  /**
32
34
  * Quote a string as a single literal bash word, POSIX single-quote style: wrap in `'...'` and
33
35
  * turn any embedded `'` into `'\''` (close the quote, an escaped literal quote, reopen).
@@ -185,7 +187,24 @@ function selfHealStatePath() {
185
187
  function writeSelfHealState(state) {
186
188
  const file = selfHealStatePath();
187
189
  fs.mkdirSync(path.dirname(file), { recursive: true });
188
- fs.writeFileSync(file, JSON.stringify(state));
190
+ // Rename, so a reader in another launch never sees a half-written file.
191
+ const tmp = `${file}.${process.pid}.tmp`;
192
+ try {
193
+ fs.writeFileSync(tmp, JSON.stringify(state));
194
+ fs.renameSync(tmp, file);
195
+ }
196
+ catch (e) {
197
+ fs.rmSync(tmp, { force: true });
198
+ throw e;
199
+ }
200
+ }
201
+ function readSelfHealState() {
202
+ try {
203
+ return JSON.parse(fs.readFileSync(selfHealStatePath(), "utf8"));
204
+ }
205
+ catch {
206
+ return null;
207
+ }
189
208
  }
190
209
  /**
191
210
  * The launcher script that becomes the .app's executable. Written as text (not compiled) so it
@@ -247,10 +266,11 @@ npx -y @slack/radar-mcp@latest install-app"
247
266
  # SLACK_RADAR_NO_OPEN stops the server from racing us to open a BROWSER TAB: this app wants the
248
267
  # standalone window it opens below, not a tab. Fully detached (setsid-style via nohup + &, stdio
249
268
  # to a log) so the server outlives this launcher script -- otherwise the app "quitting" would
250
- # take the dashboard with it.
269
+ # take the dashboard with it. SLACK_RADAR_WEB_PORT because a Finder launch inherits none, and the
270
+ # server would bind the default port while this script waits on the one it was installed against.
251
271
  LOG="$HOME/Library/Logs/slack-radar-dashboard.log"
252
272
  mkdir -p "$(dirname "$LOG")"
253
- SLACK_RADAR_NO_OPEN=1 nohup "$NODE" "$WEB_BIN" >>"$LOG" 2>&1 &
273
+ SLACK_RADAR_WEB_PORT="$PORT" SLACK_RADAR_NO_OPEN=1 nohup "$NODE" "$WEB_BIN" >>"$LOG" 2>&1 &
254
274
 
255
275
  # Wait for the port instead of sleeping a fixed guess: a cold node start is ~300ms on a fast
256
276
  # Mac and multiple seconds on a loaded one, and opening the window early shows a connection
@@ -315,6 +335,76 @@ export function swiftInstallConfig(radarUrl, node, webBin, mcpBin) {
315
335
  "// --- END INSTALL CONFIG ---",
316
336
  ].join("\n");
317
337
  }
338
+ /** A TCP port written as plain digits in 1 to 65535, or null for anything else. */
339
+ function validPort(text) {
340
+ if (!/^\d{1,5}$/.test(text))
341
+ return null;
342
+ const port = Number(text);
343
+ return port >= 1 && port <= 65535 ? port : null;
344
+ }
345
+ /**
346
+ * The port the installed app was built against, or null when there is no app or the port cannot be
347
+ * read. Info.plist records it from this version on. An app installed before that records it only in
348
+ * its executable: the native binary holds the baked RADAR_URL as a plain string, and the shell
349
+ * launcher has its PORT= line. A key that is present decides on its own, so an unreadable one falls
350
+ * back to the default rather than to whatever the executable happens to contain.
351
+ *
352
+ * Exported for testing.
353
+ */
354
+ export function readInstalledPort(app = path.join(appDir(), `${APP_NAME}.app`)) {
355
+ let plist;
356
+ try {
357
+ plist = fs.readFileSync(path.join(app, "Contents", "Info.plist"), "utf8");
358
+ }
359
+ catch {
360
+ return null; // no app, so no port to keep
361
+ }
362
+ // Matched on the key alone, so a value of any other type, a <string> say, is an unreadable port
363
+ // rather than a missing key.
364
+ const key = plist.indexOf(`<key>${PORT_PLIST_KEY}</key>`);
365
+ if (key !== -1) {
366
+ const recorded = plist.slice(key).match(/^<key>[^<]*<\/key>\s*<integer>([^<]*)<\/integer>/);
367
+ return recorded ? validPort(recorded[1].trim()) : null;
368
+ }
369
+ const executable = plist.match(/<key>CFBundleExecutable<\/key>\s*<string>([^</]+)<\/string>/);
370
+ if (!executable)
371
+ return null;
372
+ let body;
373
+ try {
374
+ // latin1 maps every byte to one character, so a binary reads without decoding errors and an
375
+ // ASCII literal inside it still matches.
376
+ body = fs.readFileSync(path.join(app, "Contents", "MacOS", executable[1]), "latin1");
377
+ }
378
+ catch {
379
+ return null;
380
+ }
381
+ const baked = body.match(/http:\/\/localhost:(\d+)/) ?? body.match(/^PORT=(\d+)$/m);
382
+ return baked ? validPort(baked[1]) : null;
383
+ }
384
+ /**
385
+ * The port this install bakes in. An explicit SLACK_RADAR_WEB_PORT wins, and has to be a real port:
386
+ * anything else would bake a URL the app cannot parse, and the app would crash on every launch until
387
+ * a reinstall, so the install throws instead. Without one, a
388
+ * rebuild keeps the port the installed app already has: the self-heal rebuild of an app installed
389
+ * before the port was passed on runs with no port in its environment, and baking the default there
390
+ * would move a user on 8101 to 8100 while their MCP config still names 8101. The default comes last,
391
+ * and is also what a rebuild bakes when the installed app's port cannot be read or is not a port.
392
+ * The installed app is read only when the environment names no port, since its answer is unused
393
+ * otherwise. `installed` is for tests: a value, including null, stands in for that read.
394
+ *
395
+ * Exported for testing.
396
+ */
397
+ export function installPort(env = process.env, installed) {
398
+ const explicit = env.SLACK_RADAR_WEB_PORT;
399
+ if (explicit !== undefined) {
400
+ const port = validPort(explicit);
401
+ if (port === null) {
402
+ throw new Error(`SLACK_RADAR_WEB_PORT must be a port number from 1 to 65535, got ${JSON.stringify(explicit)}.`);
403
+ }
404
+ return port;
405
+ }
406
+ return (installed === undefined ? readInstalledPort() : installed) ?? WEB_PORT_DEFAULT;
407
+ }
318
408
  /**
319
409
  * Everything the app needs to know about THIS machine.
320
410
  *
@@ -328,6 +418,7 @@ export function installConfigValues(execPath, candidates) {
328
418
  node: stableNodePath(execPath ?? process.execPath, candidates ?? stableNodeCandidates()),
329
419
  webBin: webBinPath(),
330
420
  mcpBin: mcpBinPath(),
421
+ port: installPort(),
331
422
  };
332
423
  }
333
424
  /**
@@ -341,7 +432,7 @@ export function installConfigValues(execPath, candidates) {
341
432
  * a synthetic machine layout, and nothing here executes an interpreter.
342
433
  */
343
434
  export function patchedSwiftSource(source, values) {
344
- const config = swiftInstallConfig(`http://localhost:${WEB_PORT}`, values.node, values.webBin, values.mcpBin);
435
+ const config = swiftInstallConfig(`http://localhost:${values.port}`, values.node, values.webBin, values.mcpBin);
345
436
  const patched = source.replace(/\/\/ --- BEGIN INSTALL CONFIG ---[\s\S]*?\/\/ --- END INSTALL CONFIG ---/, config);
346
437
  return patched === source ? null : patched;
347
438
  }
@@ -398,7 +489,7 @@ function buildSwiftApp(dest, values) {
398
489
  }
399
490
  }
400
491
  /** Minimal Info.plist. LSUIElement is NOT set: this app SHOULD show in the dock, that is the ask. */
401
- function infoPlist(executable) {
492
+ function infoPlist(executable, port) {
402
493
  return `<?xml version="1.0" encoding="UTF-8"?>
403
494
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
404
495
  <plist version="1.0">
@@ -412,6 +503,8 @@ function infoPlist(executable) {
412
503
  <key>CFBundleExecutable</key><string>${executable}</string>
413
504
  <key>CFBundleIconFile</key><string>radar</string>
414
505
  <key>LSMinimumSystemVersion</key><string>11.0</string>
506
+ <!-- The dashboard port baked into the executable, read back by the next rebuild so it keeps it. -->
507
+ <key>${PORT_PLIST_KEY}</key><integer>${port}</integer>
415
508
  <!-- The window follows the dashboard's own light/dark theme via its stylesheet, so the app must
416
509
  NOT be forced into one appearance. -->
417
510
  <key>NSRequiresAquaSystemAppearance</key><false/>
@@ -478,6 +571,13 @@ function buildIcns(resourcesDir) {
478
571
  fs.rmSync(iconset, { recursive: true, force: true });
479
572
  }
480
573
  }
574
+ // buildSwiftApp()'s compile is the one step in here that can be slow for a structural reason, and it
575
+ // is bounded at 60s by its own execFileSync timeout, which leaves about 60s of slack against this
576
+ // threshold. The rest is unbounded but local and sub-second in practice (sips, iconutil, lsregister).
577
+ // A lock older than this can only be a crash leftover, the process that made it died before reaching
578
+ // the finally below. Without this, one crashed install would wedge every self-heal check forever,
579
+ // since nothing else ever removes the lock file.
580
+ const STALE_LOCK_MS = 2 * 60 * 1000;
481
581
  /**
482
582
  * Create (or replace) the launcher app. Returns its path.
483
583
  *
@@ -503,13 +603,6 @@ export function installMacApp() {
503
603
  // staging path -- for the self-heal caller that just means trying again next launch.
504
604
  fs.mkdirSync(dir, { recursive: true });
505
605
  const lockPath = path.join(dir, ".install.lock");
506
- // buildSwiftApp()'s compile is the one step in here that can be slow for a structural reason, and it
507
- // is bounded at 60s by its own execFileSync timeout, which leaves about 60s of slack against this
508
- // threshold. The rest is unbounded but local and sub-second in practice (sips, iconutil, lsregister).
509
- // A lock older than this can only be a crash leftover, the process that made it died before reaching
510
- // the finally below. Without this, one crashed install would wedge every self-heal check forever,
511
- // since nothing else ever removes the lock file.
512
- const STALE_LOCK_MS = 2 * 60 * 1000;
513
606
  let lockFd;
514
607
  try {
515
608
  lockFd = fs.openSync(lockPath, "wx");
@@ -548,11 +641,11 @@ export function installMacApp() {
548
641
  // The node running THIS install, under its most stable name, is the one known-good
549
642
  // interpreter on the machine. Under npx that is the same node the dashboard would run under
550
643
  // anyway. See stableNodePath() for why the name matters more than the exact path.
551
- fs.writeFileSync(path.join(macos, "radar-launcher"), launcherScript(values.node, webBin, WEB_PORT), {
644
+ fs.writeFileSync(path.join(macos, "radar-launcher"), launcherScript(values.node, webBin, values.port), {
552
645
  mode: 0o755,
553
646
  });
554
647
  }
555
- fs.writeFileSync(path.join(staging, "Contents", "Info.plist"), infoPlist(native ? "SlackRadar" : "radar-launcher"));
648
+ fs.writeFileSync(path.join(staging, "Contents", "Info.plist"), infoPlist(native ? "SlackRadar" : "radar-launcher", values.port));
556
649
  const icon = buildIcns(resources);
557
650
  // Each rename is one atomic filesystem op, so `app` is never half-old-half-new WITHIN either
558
651
  // step. The pair is not one atomic transaction though: a crash between the two renames leaves
@@ -584,27 +677,49 @@ export function installMacApp() {
584
677
  if (!icon) {
585
678
  console.log("Note: could not build the app icon, so macOS will show a generic one.");
586
679
  }
587
- return { app, native, node: values.node };
680
+ return { app, native, node: values.node, port: values.port };
588
681
  }
589
682
  finally {
590
683
  fs.closeSync(lockFd);
591
684
  fs.rmSync(lockPath, { force: true });
592
685
  }
593
686
  }
594
- /** Entry point for the `install-app` subcommand. Prints what to do next, then reveals the app. */
595
- export function runInstallApp() {
687
+ /** Open the folder holding the app, so the user can drag it to the dock without hunting for it. */
688
+ function revealAppDir() {
689
+ try {
690
+ spawn("open", [appDir()], { detached: true, stdio: "ignore" }).unref();
691
+ }
692
+ catch {
693
+ // Best effort.
694
+ }
695
+ }
696
+ /**
697
+ * Entry point for the `install-app` subcommand. Prints what to do next, then reveals the app.
698
+ * `install` and `reveal` are for tests, so the printed message can be checked without building an
699
+ * app or opening a Finder window.
700
+ */
701
+ export function runInstallApp(install = installMacApp, reveal = revealAppDir) {
596
702
  if (process.platform !== "darwin") {
597
703
  console.error(`install-app builds a macOS .app bundle; this platform is ${process.platform}.`);
598
704
  process.exit(1);
599
705
  }
600
706
  let result;
601
707
  try {
602
- result = installMacApp();
708
+ result = install();
603
709
  }
604
710
  catch (e) {
605
711
  console.error(`install-app failed: ${e.message}`);
606
712
  process.exit(1);
607
713
  }
714
+ console.log(installAppMessage(result));
715
+ reveal();
716
+ }
717
+ /**
718
+ * What install-app prints once the bundle is in place.
719
+ *
720
+ * Exported for testing.
721
+ */
722
+ export function installAppMessage(result) {
608
723
  // Name which of the two builds landed. They behave differently in the one way the user cares
609
724
  // about (own window vs a browser tab), so a single generic success message would mislead.
610
725
  const how = result.native
@@ -612,8 +727,16 @@ export function runInstallApp() {
612
727
  : "No Swift toolchain was found, so it opens in your default browser instead of a native\n" +
613
728
  "window. Install Xcode Command Line Tools (xcode-select --install) and re-run this for\n" +
614
729
  "a real app window.";
615
- console.log(`Installed ${result.app}\n\n` +
616
- `Dashboard interpreter: ${result.node}\n\n` +
730
+ // Named because the MCP server reads its own SLACK_RADAR_WEB_PORT, and the two have to match. Only
731
+ // a port other than the default needs anything set there.
732
+ const mcpPort = result.port === WEB_PORT_DEFAULT
733
+ ? ""
734
+ : `Your MCP server config needs SLACK_RADAR_WEB_PORT=${result.port} in its env too, or the tools\n` +
735
+ `will look for the dashboard on ${WEB_PORT_DEFAULT}.\n`;
736
+ return (`Installed ${result.app}\n\n` +
737
+ `Dashboard interpreter: ${result.node}\n` +
738
+ `Dashboard port: ${result.port}\n` +
739
+ `${mcpPort}\n` +
617
740
  `${how}\n\n` +
618
741
  `To keep it in your dock: open it once, then right-click its dock icon and choose\n` +
619
742
  `Options > Keep in Dock.\n\n` +
@@ -624,13 +747,6 @@ export function runInstallApp() {
624
747
  // the whole reported failure, and one sentence closes it.
625
748
  `If Radar is already running, quit it and open it again. Clicking a running app only brings\n` +
626
749
  `its window forward, so it would keep serving the version you just replaced.`);
627
- // Open the containing folder so the user can drag it to the dock without hunting for it.
628
- try {
629
- spawn("open", [appDir()], { detached: true, stdio: "ignore" }).unref();
630
- }
631
- catch {
632
- // Best effort.
633
- }
634
750
  }
635
751
  /** Single source of truth for "what version is currently installed" -- reads the installed
636
752
  * app's Info.plist, shared by runSelfHealCheck() and runSelfHealPrecheck() so the two never
@@ -643,7 +759,10 @@ function readInstalledVersion() {
643
759
  const match = plist.match(/<key>CFBundleShortVersionString<\/key><string>(.*?)<\/string>/);
644
760
  if (!match)
645
761
  return { found: false, reason: "unreadable" };
646
- return { found: true, version: match[1] };
762
+ const plain = match[1].split(/[-+]/, 1)[0];
763
+ if (parseVersion(plain) === null)
764
+ return { found: false, reason: "unreadable" };
765
+ return { found: true, version: match[1], plain };
647
766
  }
648
767
  /** Logs and records the no-installed-app / unreadable-version early return, the same for
649
768
  * runSelfHealCheck() and runSelfHealPrecheck() -- neither has anything to compare against. */
@@ -660,8 +779,9 @@ function logNoInstalledVersion(checkedAt, reason) {
660
779
  * pointed at a stale, orphaned npx cache path with no signal to the user. This rebuilds it in
661
780
  * place when this process's own version (itself just resolved via the same `@latest` npx call)
662
781
  * differs from what is installed, so the fix lands invisibly and takes effect on the NEXT
663
- * launch. Never throws out of this function: a launcher-triggered background process failing
664
- * loudly would look like a crash, which is exactly what staying invisible rules out.
782
+ * launch. Never throws out of this function, except when the final state write itself fails: a
783
+ * launcher-triggered background process failing loudly would look like a crash, which is exactly
784
+ * what staying invisible rules out. That one throw exits non-zero, which the precheck counts as a failure.
665
785
  */
666
786
  export function runSelfHealCheck() {
667
787
  const checkedAt = new Date().toISOString();
@@ -671,12 +791,27 @@ export function runSelfHealCheck() {
671
791
  logNoInstalledVersion(checkedAt, read.reason);
672
792
  return;
673
793
  }
794
+ // The plist match cannot span a newline, so installed is safe to log as is.
674
795
  const installed = read.version;
675
- if (installed === RADAR_VERSION) {
676
- logSelfHeal(`self-heal: already current (${RADAR_VERSION})`);
796
+ const comparison = compareVersions(RADAR_VERSION, read.plain);
797
+ if (comparison === null) {
798
+ const message = `npm resolved ${RADAR_VERSION}, which is not a plain x.y.z, so nothing was rebuilt.`;
799
+ logSelfHeal(`self-heal: ${message}`);
800
+ writeSelfHealState({ checkedAt, outcome: "error", fromVersion: installed, toVersion: RADAR_VERSION, error: message });
801
+ return;
802
+ }
803
+ if (comparison === 0) {
804
+ logSelfHeal(`self-heal: already current (${installed})`);
677
805
  writeSelfHealState({ checkedAt, outcome: "current", toVersion: RADAR_VERSION });
678
806
  return;
679
807
  }
808
+ // npm config such as min-release-age can hand us a version older than the installed one.
809
+ if (comparison < 0) {
810
+ const message = `npm resolved ${RADAR_VERSION}, older than the installed ${installed}, so nothing was rebuilt.`;
811
+ logSelfHeal(`self-heal: ${message}`);
812
+ writeSelfHealState({ checkedAt, outcome: "error", fromVersion: installed, toVersion: RADAR_VERSION, error: message });
813
+ return;
814
+ }
680
815
  try {
681
816
  installMacApp();
682
817
  logSelfHeal(`self-heal: rebuilt ${installed} -> ${RADAR_VERSION}`);
@@ -749,19 +884,6 @@ export function checkLatestPublishedVersion() {
749
884
  });
750
885
  });
751
886
  }
752
- /** [major,minor,patch] numeric comparison -- this project's versions are always plain `npm
753
- * version`-produced semver, so no semver dependency is needed. */
754
- function isNewerVersion(candidate, installed) {
755
- const c = candidate.split(".").map(Number);
756
- const i = installed.split(".").map(Number);
757
- for (let idx = 0; idx < 3; idx++) {
758
- const cPart = c[idx] ?? 0;
759
- const iPart = i[idx] ?? 0;
760
- if (cPart !== iPart)
761
- return cPart > iPart;
762
- }
763
- return false;
764
- }
765
887
  // Real spawn by default; a test swaps this so it can assert on the npx rebuild call without
766
888
  // letting a real `npx @latest` reach the network.
767
889
  let selfHealSpawn = spawn;
@@ -770,6 +892,11 @@ let selfHealSpawn = spawn;
770
892
  export function _setSelfHealSpawnForTest(fn) {
771
893
  selfHealSpawn = fn;
772
894
  }
895
+ // A stalled npx download would otherwise keep this process around until reboot.
896
+ let selfHealRebuildTimeoutMs = 10 * 60 * 1000;
897
+ export function _setSelfHealRebuildTimeoutForTest(ms) {
898
+ selfHealRebuildTimeoutMs = ms;
899
+ }
773
900
  /**
774
901
  * Entry point for `install-app --self-heal-precheck`. RadarApp.swift now spawns THIS (the
775
902
  * already-installed, guaranteed self-heal-aware mcp/index.js) instead of going straight to `npx
@@ -780,14 +907,41 @@ export function _setSelfHealSpawnForTest(fn) {
780
907
  * the normal state, not an edge case, for a locally-built dock app ahead of what is published.
781
908
  *
782
909
  * This checks the registry's plain version metadata first (no package code ever executes) and
783
- * only spawns the npx follow-up once that confirms a real, strictly-newer version exists. At that
784
- * point whatever `npx @latest` resolves to is guaranteed to postdate this build and understand
785
- * `--self-heal-check`, because versions only move forward under this project's manual, sequential
786
- * publish model -- so the old-dispatch bug cannot trigger here.
910
+ * only spawns the npx follow-up once that confirms a real, strictly-newer version exists. Versions
911
+ * only move forward under this project's manual, sequential publish model, so `npx @latest` lands
912
+ * on this build or newer, unless npm config (min-release-age, a lagging mirror) holds it back. The
913
+ * precheck logs that skew. A held-back child from this release on refuses to downgrade, but an older
914
+ * one does not have that check.
787
915
  */
788
916
  export function runSelfHealPrecheck() {
789
917
  void runSelfHealPrecheckAsync();
790
918
  }
919
+ function formatDuration(ms) {
920
+ if (ms >= 60_000) {
921
+ const minutes = Math.round(ms / 60_000);
922
+ return `${minutes} minute${minutes === 1 ? "" : "s"}`;
923
+ }
924
+ const seconds = Math.max(1, Math.round(ms / 1000));
925
+ return `${seconds} second${seconds === 1 ? "" : "s"}`;
926
+ }
927
+ /** A failed spawn can fire 'exit' right after 'error', so only the first one counts. */
928
+ function waitForExit(child) {
929
+ return new Promise((resolve, reject) => {
930
+ let settled = false;
931
+ child.on("error", (err) => {
932
+ if (settled)
933
+ return;
934
+ settled = true;
935
+ reject(err);
936
+ });
937
+ child.on("exit", (code, signal) => {
938
+ if (settled)
939
+ return;
940
+ settled = true;
941
+ resolve({ code, signal });
942
+ });
943
+ });
944
+ }
791
945
  /** The awaitable core of runSelfHealPrecheck(), exported so a test can await its outcome
792
946
  * directly instead of polling for the fire-and-forget wrapper to finish. */
793
947
  export async function runSelfHealPrecheckAsync() {
@@ -811,7 +965,18 @@ export async function runSelfHealPrecheckAsync() {
811
965
  });
812
966
  return;
813
967
  }
814
- if (!isNewerVersion(latest, installed)) {
968
+ const comparison = compareVersions(latest, read.plain);
969
+ if (comparison === null) {
970
+ logSelfHeal(`self-heal: registry version ${latest.replace(/[\r\n]/g, " ")} is not a plain x.y.z, so nothing was rebuilt.`);
971
+ writeSelfHealState({ checkedAt, outcome: "current", toVersion: installed });
972
+ return;
973
+ }
974
+ if (comparison < 0) {
975
+ logSelfHeal(`self-heal: installed ${installed} is ahead of the registry (${latest}), nothing to do`);
976
+ writeSelfHealState({ checkedAt, outcome: "current", toVersion: installed });
977
+ return;
978
+ }
979
+ if (comparison === 0) {
815
980
  logSelfHeal(`self-heal: already current (${installed})`);
816
981
  writeSelfHealState({ checkedAt, outcome: "current", toVersion: installed });
817
982
  return;
@@ -828,26 +993,124 @@ export async function runSelfHealPrecheckAsync() {
828
993
  });
829
994
  return;
830
995
  }
831
- logSelfHeal(`self-heal: newer version ${latest} published (installed ${installed}), triggering rebuild`);
996
+ // A Finder launch has a bare PATH and npx cannot find node, so hand it the node we run under.
997
+ const nodeDir = path.dirname(process.execPath);
998
+ const npxDir = path.dirname(path.resolve(npx));
999
+ const dirs = npxDir === nodeDir ? [nodeDir] : [nodeDir, npxDir];
1000
+ // An empty segment would mean the current directory, so drop it when PATH is unset.
1001
+ const spawnPath = [...dirs, process.env.PATH].filter(Boolean).join(path.delimiter);
1002
+ const spawnEnv = { ...process.env, PATH: spawnPath };
1003
+ logSelfHeal(`self-heal: newer version ${latest} published (installed ${installed}), triggering rebuild with ${npx} and node from ${nodeDir}`);
1004
+ const spawnedAt = new Date().toISOString();
1005
+ let exit;
1006
+ let timedOut = false;
832
1007
  try {
833
- selfHealSpawn(npx, ["-y", "@slack/radar-mcp@latest", "install-app", "--self-heal-check"], {
834
- detached: true,
835
- stdio: "ignore",
836
- }).unref();
1008
+ // Swift already points our stdout and stderr at the dashboard log, so the child inherits that.
1009
+ const child = selfHealSpawn(npx, ["-y", "@slack/radar-mcp@latest", "install-app", "--self-heal-check"], {
1010
+ stdio: ["ignore", "inherit", "inherit"],
1011
+ env: spawnEnv,
1012
+ });
1013
+ // Our own timer rather than spawn's timeout option, so the message can tell our kill from anyone else's.
1014
+ const timer = setTimeout(() => {
1015
+ timedOut = true;
1016
+ child.kill("SIGTERM");
1017
+ // npx may not pass SIGTERM on, and a child that never exits would hang this process too.
1018
+ setTimeout(() => child.kill("SIGKILL"), 10_000).unref();
1019
+ }, selfHealRebuildTimeoutMs);
1020
+ try {
1021
+ exit = await waitForExit(child);
1022
+ }
1023
+ finally {
1024
+ clearTimeout(timer);
1025
+ }
837
1026
  }
838
1027
  catch (e) {
839
- logSelfHeal(`self-heal: could not spawn the rebuild: ${e.message}`);
840
- writeSelfHealState({
841
- checkedAt,
842
- outcome: "error",
843
- fromVersion: installed,
844
- toVersion: latest,
845
- error: e.message,
846
- });
1028
+ // A missing or non-executable npx shows up here, through the 'error' event.
1029
+ const message = `could not start the rebuild to ${latest}: ${e.message}`;
1030
+ logSelfHeal(`self-heal: ${message}`);
1031
+ writeSelfHealState({ checkedAt: new Date().toISOString(), outcome: "error", fromVersion: installed, toVersion: latest, error: message });
1032
+ return;
847
1033
  }
1034
+ // runSelfHealCheck writes a report on every path, and a failed write exits non-zero, so a clean
1035
+ // exit means the child reported. Our timeout still wins, since npm can swallow the SIGTERM and exit 0.
1036
+ if (!timedOut && exit.signal === null && exit.code === 0) {
1037
+ // Best effort: only an entry written since the spawn counts, and it may be another launch's.
1038
+ const after = readSelfHealState();
1039
+ const resolved = typeof after?.toVersion === "string" ? after.toVersion.replace(/[\r\n]/g, " ") : null;
1040
+ if (after && resolved && after.checkedAt >= spawnedAt) {
1041
+ if (parseVersion(resolved) === null) {
1042
+ logSelfHeal(`self-heal: npx resolved ${resolved} while the registry says ${latest}; the resolved version is not a plain x.y.z`);
1043
+ }
1044
+ else if (compareVersions(latest, resolved) > 0) {
1045
+ logSelfHeal(`self-heal: npx resolved ${resolved} while the registry says ${latest}, npm config may be holding it back`);
1046
+ }
1047
+ }
1048
+ return;
1049
+ }
1050
+ const reason = timedOut
1051
+ ? `took longer than ${formatDuration(selfHealRebuildTimeoutMs)} and was stopped`
1052
+ : exit.signal
1053
+ ? `was killed by ${exit.signal}`
1054
+ : `exited with code ${exit.code}`;
1055
+ const message = `the rebuild to ${latest} ${reason}`;
1056
+ logSelfHeal(`self-heal: ${message}`);
1057
+ writeSelfHealState({ checkedAt: new Date().toISOString(), outcome: "error", fromVersion: installed, toVersion: latest, error: message });
848
1058
  }
849
1059
  catch (e) {
850
1060
  logSelfHeal(`self-heal: unexpected error: ${e.message}`);
851
1061
  writeSelfHealState({ checkedAt, outcome: "error", toVersion: RADAR_VERSION, error: e.message });
852
1062
  }
853
1063
  }
1064
+ /** Whether the registry has a newer Radar than the installed app, or the installed app is already
1065
+ * ahead of `runningVersion` and just needs a restart. Never throws; failures land in `error`. */
1066
+ export async function checkForUpdate(runningVersion = "unknown") {
1067
+ const read = readInstalledVersion();
1068
+ if (!read.found) {
1069
+ return { installed: null, latest: null, updateAvailable: false, error: "Slack Radar.app is not installed" };
1070
+ }
1071
+ if ((compareVersions(read.plain, runningVersion.split(/[-+]/, 1)[0]) ?? 0) > 0) {
1072
+ return { installed: read.version, latest: null, updateAvailable: false, restartAvailable: true };
1073
+ }
1074
+ const latest = await checkLatestPublishedVersion();
1075
+ if (latest === null) {
1076
+ return { installed: read.version, latest: null, updateAvailable: false, error: "could not reach the npm registry" };
1077
+ }
1078
+ const comparison = compareVersions(latest, read.plain);
1079
+ return { installed: read.version, latest, updateAvailable: comparison !== null && comparison > 0 };
1080
+ }
1081
+ /** Entry point for `install-app --update-now`. Reuses the self-heal rebuild, so an explicit update
1082
+ * stays subject to the same npm config as the background one. */
1083
+ export async function runUpdateNow() {
1084
+ const startedAt = new Date().toISOString();
1085
+ const before = readInstalledVersion();
1086
+ const running = (process.env.RADAR_APP_VERSION ?? "").split(/[-+]/, 1)[0];
1087
+ // Updated means newer than the running app, or than the copy before the install when no version was baked in.
1088
+ const base = parseVersion(running) ? running : before.found ? before.plain : null;
1089
+ const isUpdated = (r) => r.found && base !== null && (compareVersions(r.plain, base) ?? 0) > 0;
1090
+ await runSelfHealPrecheckAsync();
1091
+ let after = readInstalledVersion();
1092
+ // A fresh lock means the launch self-heal beat our rebuild to it, so wait for it to finish.
1093
+ const lock = path.join(appDir(), ".install.lock");
1094
+ while (!isUpdated(after) && Date.now() - (fs.statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? 0) < STALE_LOCK_MS) {
1095
+ await new Promise((resolve) => setTimeout(resolve, 250));
1096
+ after = readInstalledVersion();
1097
+ }
1098
+ const result = { updated: isUpdated(after) };
1099
+ if (!result.updated) {
1100
+ const state = readSelfHealState();
1101
+ const recorded = state && state.checkedAt >= startedAt && state.outcome === "error" ? state.error : undefined;
1102
+ if (recorded !== undefined) {
1103
+ result.error = recorded;
1104
+ }
1105
+ else {
1106
+ // No recorded error: the rebuild resolved a version equal to what's already installed, the
1107
+ // signature of an npm min-release-age hold. Confirm against the registry before naming it.
1108
+ const latest = after.found ? await checkLatestPublishedVersion() : null;
1109
+ result.error =
1110
+ after.found && latest !== null && (compareVersions(latest, after.plain) ?? 0) > 0
1111
+ ? `Your npm config may be holding Radar back on ${after.version}. The published version is ${latest}.`
1112
+ : "The app was not updated. See ~/Library/Logs/slack-radar-dashboard.log for the log.";
1113
+ }
1114
+ }
1115
+ console.log(JSON.stringify(result));
1116
+ }