@slack/radar-mcp 1.14.0 → 1.17.1

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 (49) hide show
  1. package/README.md +15 -3
  2. package/dist/mcp/db-tools.js +23 -0
  3. package/dist/mcp/dispatch.d.ts +4 -0
  4. package/dist/mcp/dispatch.js +26 -0
  5. package/dist/mcp/index.js +105 -37
  6. package/dist/mcp/platform-detect.d.ts +110 -0
  7. package/dist/mcp/platform-detect.js +246 -0
  8. package/dist/mcp/prefs-tools.d.ts +4 -3
  9. package/dist/mcp/prefs-tools.js +26 -3
  10. package/dist/mcp/session-enable.js +19 -1
  11. package/dist/mcp/snapshot.js +4 -1
  12. package/dist/mcp/sources-gate.js +6 -3
  13. package/dist/mcp/tools.d.ts +11 -0
  14. package/dist/mcp/tools.js +38 -0
  15. package/dist/mcp/web-child-env.d.ts +1 -0
  16. package/dist/mcp/web-child-env.js +32 -0
  17. package/dist/shared/android.d.ts +89 -1
  18. package/dist/shared/android.js +352 -78
  19. package/dist/shared/constants.d.ts +25 -1
  20. package/dist/shared/constants.js +27 -1
  21. package/dist/shared/db.js +11 -2
  22. package/dist/shared/debug-log.js +6 -1
  23. package/dist/shared/enable-diagnosis.d.ts +28 -0
  24. package/dist/shared/enable-diagnosis.js +41 -0
  25. package/dist/shared/prefs.d.ts +0 -5
  26. package/dist/shared/prefs.js +6 -2
  27. package/dist/shared/screen.d.ts +46 -9
  28. package/dist/shared/screen.js +74 -11
  29. package/dist/shared/transport.d.ts +62 -5
  30. package/dist/shared/webapp.d.ts +50 -0
  31. package/dist/shared/webapp.js +65 -0
  32. package/dist/web/bin.js +5 -1
  33. package/dist/web/install-app.d.ts +87 -0
  34. package/dist/web/install-app.js +703 -0
  35. package/dist/web/macapp/RadarApp.swift +466 -0
  36. package/dist/web/public/icons/radar-1024.png +0 -0
  37. package/dist/web/public/icons/radar.svg +40 -0
  38. package/dist/web/public/index.html +41 -1
  39. package/dist/web/public/next/app.js +19 -4
  40. package/dist/web/public/next/db.js +145 -5
  41. package/dist/web/public/next/feed.js +18 -0
  42. package/dist/web/public/next/hooks.js +10 -1
  43. package/dist/web/public/next/registry.js +18 -10
  44. package/dist/web/public/next/screen.js +147 -43
  45. package/dist/web/public/next/store.js +393 -51
  46. package/dist/web/public/next/toast.js +134 -0
  47. package/dist/web/server.d.ts +26 -1
  48. package/dist/web/server.js +341 -113
  49. package/package.json +2 -2
@@ -0,0 +1,703 @@
1
+ // `slack-radar install-app` -- build a macOS .app that launches the Radar dashboard from the dock.
2
+ //
3
+ // WHY A NATIVE WRAPPER AND NOT JUST THE PWA. Installing the dashboard through Chrome or Safari
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
7
+ // the window shows a browser connection error. A web app cannot start a local server, so no amount
8
+ // of manifest work fixes that. This wrapper is the missing half: it ensures the server is up, THEN
9
+ // shows the window.
10
+ //
11
+ // WHY A NATIVE WINDOW AND NOT A BROWSER. The first version here opened a URL, which is not enough:
12
+ // a URL always resolves to a TAB in whatever browser is already running, so a dock click dropped
13
+ // Radar into the middle of a Safari window full of unrelated tabs. Chromium's --app flag does give a
14
+ // standalone window, but only for Chromium users, and defaulting a Safari user into Chrome launches
15
+ // a browser they do not use. So when swiftc is available the installer compiles a tiny WKWebView app
16
+ // that OWNS its window: one dock icon, no tab bar, no address bar, no browser, the same for
17
+ // everyone. The shell launcher stays as the fallback for a machine with no Swift toolchain.
18
+ //
19
+ // Either way the app holds NO dashboard logic -- it starts the server and renders localhost -- so it
20
+ // does not go stale when Radar upgrades (the SAME app keeps working against a newer dist).
21
+ import { execFileSync, spawn } from "child_process";
22
+ import fs from "fs";
23
+ import http from "http";
24
+ import https from "https";
25
+ import os from "os";
26
+ import path from "path";
27
+ import { fileURLToPath } from "url";
28
+ import { WEB_PORT } from "./server.js";
29
+ import { RADAR_VERSION } from "../shared/constants.js";
30
+ const APP_NAME = "Slack Radar";
31
+ /**
32
+ * Quote a string as a single literal bash word, POSIX single-quote style: wrap in `'...'` and
33
+ * turn any embedded `'` into `'\''` (close the quote, an escaped literal quote, reopen).
34
+ *
35
+ * JSON.stringify is NOT this: it escapes for JS/JSON syntax, not shell syntax. Inside a bash
36
+ * double-quoted string (`"..."`), `$` and a backtick are still special -- JSON.stringify leaves
37
+ * both untouched, so a path containing `$(cmd)` or a backtick runs that command instead of
38
+ * naming a file (confirmed live: install-app.ts previously wrote `NODE=${JSON.stringify(...)}`,
39
+ * a bash double-quoted assignment). Single quotes have no special characters at all except `'`
40
+ * itself, which this escapes, so every other byte -- `$`, backticks, `\`, spaces -- passes
41
+ * through as a literal.
42
+ */
43
+ function bashQuote(value) {
44
+ return `'${value.replace(/'/g, `'\\''`)}'`;
45
+ }
46
+ /** Where the .app goes. ~/Applications, not /Applications: no sudo, and it is per-user anyway. */
47
+ function appDir() {
48
+ return path.join(os.homedir(), "Applications");
49
+ }
50
+ /** The dashboard entrypoint this install will launch. Absolute, so a minimal PATH cannot break it. */
51
+ function webBinPath() {
52
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), "bin.js");
53
+ }
54
+ /** The ALREADY-INSTALLED mcp/index.js -- baked in at install time, so it is guaranteed to be
55
+ * from THIS build (and therefore self-heal-precheck-aware), the same certainty webBinPath()
56
+ * already gives the dashboard entrypoint. */
57
+ function mcpBinPath() {
58
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "mcp", "index.js");
59
+ }
60
+ /**
61
+ * Resolve npx's absolute path, same reasoning as the baked-in node path: a Finder-launched dock
62
+ * app gets a minimal PATH with no shell config, so a bare `npx` would not resolve. npm ships npx
63
+ * alongside node in most installs, so check there first; `which` covers the rest. Returns null
64
+ * (never throws) so a machine with no npx just does not get the self-heal capability.
65
+ */
66
+ export function resolveNpxPath() {
67
+ const alongsideNode = path.join(path.dirname(process.execPath), "npx");
68
+ if (fs.existsSync(alongsideNode))
69
+ return alongsideNode;
70
+ try {
71
+ return execFileSync("which", ["npx"]).toString().trim();
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ }
77
+ /** Same log file RadarApp.swift's ensureDashboardRunning() already appends to, so self-heal
78
+ * outcomes show up next to the dashboard's own launch log rather than a second file to check. */
79
+ function selfHealLogPath() {
80
+ return path.join(os.homedir(), "Library", "Logs", "slack-radar-dashboard.log");
81
+ }
82
+ /** Append-only: a truncating write would drop the dashboard's own launch history. */
83
+ function logSelfHeal(line) {
84
+ const file = selfHealLogPath();
85
+ fs.mkdirSync(path.dirname(file), { recursive: true });
86
+ fs.appendFileSync(file, `${new Date().toISOString()} ${line}\n`);
87
+ }
88
+ /** Same ~/.slack-radar convention server.ts's SPEC_DIR uses, so this state file lives next to
89
+ * the other runtime state rather than inventing a new location. */
90
+ function selfHealStatePath() {
91
+ return path.join(os.homedir(), ".slack-radar", "self-heal.json");
92
+ }
93
+ /** Overwrite, not append: only the latest check matters to the dashboard's header indicator. */
94
+ function writeSelfHealState(state) {
95
+ const file = selfHealStatePath();
96
+ fs.mkdirSync(path.dirname(file), { recursive: true });
97
+ fs.writeFileSync(file, JSON.stringify(state));
98
+ }
99
+ /**
100
+ * The launcher script that becomes the .app's executable. Written as text (not compiled) so it
101
+ * stays readable and auditable in place -- a binary blob dropped in ~/Applications by an npm
102
+ * package deserves more suspicion than a shell script anyone can cat.
103
+ *
104
+ * `nodeBin` and `webBin` are baked in as ABSOLUTE paths, resolved at install time. A dock app
105
+ * launches from Finder with a minimal PATH that usually lacks node entirely (nvm/homebrew node
106
+ * live in a shell-configured PATH), so `node` or `npx` by bare name would fail with a dialog-less
107
+ * silent exit. Baking the paths also pins the launcher to the exact install that generated it
108
+ * rather than whatever npx would resolve today.
109
+ *
110
+ * Exported for testing: a test can assert on the generated script without writing a bundle into
111
+ * the developer's ~/Applications.
112
+ */
113
+ export function launcherScript(nodeBin, webBin, port) {
114
+ return `#!/bin/bash
115
+ # Generated by \`slack-radar install-app\` (Radar ${RADAR_VERSION}). Safe to read, delete, or
116
+ # regenerate. Launches the Slack Radar dashboard and opens it in its own window.
117
+ #
118
+ # Absolute paths are baked in on purpose: a Finder-launched app gets a minimal PATH without the
119
+ # shell config that puts node on it, so bare \`node\`/\`npx\` would not resolve.
120
+ set -u
121
+
122
+ NODE=${bashQuote(nodeBin)}
123
+ WEB_BIN=${bashQuote(webBin)}
124
+ PORT=${port}
125
+ URL="http://localhost:$PORT"
126
+
127
+ # Is a dashboard already listening? /spec is instant and unique to Radar (no device round-trip),
128
+ # the same fingerprint bin.ts's adopt path uses. curl is always present on macOS.
129
+ alive() {
130
+ curl -fsS --max-time 2 "$URL/spec" >/dev/null 2>&1
131
+ }
132
+
133
+ if ! alive; then
134
+ # SLACK_RADAR_NO_OPEN stops the server from racing us to open a BROWSER TAB: this app wants the
135
+ # standalone window it opens below, not a tab. Fully detached (setsid-style via nohup + &, stdio
136
+ # to a log) so the server outlives this launcher script -- otherwise the app "quitting" would
137
+ # take the dashboard with it.
138
+ LOG="$HOME/Library/Logs/slack-radar-dashboard.log"
139
+ mkdir -p "$(dirname "$LOG")"
140
+ SLACK_RADAR_NO_OPEN=1 nohup "$NODE" "$WEB_BIN" >>"$LOG" 2>&1 &
141
+
142
+ # Wait for the port instead of sleeping a fixed guess: a cold node start is ~300ms on a fast
143
+ # Mac and multiple seconds on a loaded one, and opening the window early shows a connection
144
+ # error the user has to reload past. ~10s ceiling, then open anyway so a server that is merely
145
+ # slow still gets a window rather than silent nothing.
146
+ for _ in $(seq 1 50); do
147
+ alive && break
148
+ sleep 0.2
149
+ done
150
+ fi
151
+
152
+ # Open the dashboard in the user's DEFAULT browser. Never hardcode one: picking Chrome because it
153
+ # supports a nicer window shape means a Safari user's dock icon launches a browser they do not use,
154
+ # with none of their sessions or extensions. The default handler is the user's stated preference,
155
+ # so honor it and treat the window shape as a bonus applied only when that browser supports it.
156
+ #
157
+ # The default http handler's bundle id, read from Launch Services. An empty result (a fresh account
158
+ # that has never set one) falls through to plain \`open\`, which resolves the default itself.
159
+ DEFAULT_BROWSER=$(
160
+ defaults read com.apple.LaunchServices/com.apple.launchservices.secure 2>/dev/null \\
161
+ | awk '/LSHandlerURLScheme = https?;/ { print prev } { prev = $0 }' \\
162
+ | grep -o '"[^"]*"' | tr -d '"' | head -1
163
+ )
164
+ # Lowercased for matching below. Real bundle ids are mixed-case in ways that do not match how
165
+ # Launch Services reports them (Arc is company.thebrowser.Browser, Brave is com.brave.Browser,
166
+ # but Safari comes back as com.apple.safari), and \`case\` is case-sensitive -- so matching the raw
167
+ # value would silently miss those browsers and drop them to a plain tab.
168
+ DEFAULT_BROWSER_LC=$(printf '%s' "$DEFAULT_BROWSER" | tr '[:upper:]' '[:lower:]')
169
+
170
+ # Chromium-family browsers support --app=URL, which yields a window with no tab bar and no address
171
+ # bar: the closest thing to a native app window without an installed PWA. Safari and Firefox have
172
+ # no equivalent, so they get a normal tab, which is correct just less pretty.
173
+ case "$DEFAULT_BROWSER_LC" in
174
+ com.google.chrome*|com.microsoft.edgemac*|com.brave.browser*|company.thebrowser.browser*|com.vivaldi.vivaldi*)
175
+ # -b targets the bundle id directly, so this works wherever the app is installed rather than
176
+ # assuming /Applications. -n opens a new instance so the --app flag is honored even when the
177
+ # browser is already running.
178
+ open -nb "$DEFAULT_BROWSER" --args --app="$URL" && exit 0
179
+ ;;
180
+ esac
181
+
182
+ # Safari, Firefox, an unknown default, or a failed --app launch: hand the URL to macOS and let it
183
+ # route to whatever the user actually set.
184
+ open "$URL"
185
+ `;
186
+ }
187
+ /**
188
+ * The `--- BEGIN/END INSTALL CONFIG ---` block buildSwiftApp() substitutes into RadarApp.swift.
189
+ * Exported like launcherScript, for the same reason: a test can assert on the generated text
190
+ * without touching ~/Applications.
191
+ */
192
+ export function swiftInstallConfig(radarUrl, node, webBin, npx, mcpBin) {
193
+ return [
194
+ "// --- BEGIN INSTALL CONFIG (substituted by install-app) ---",
195
+ `let RADAR_URL = ${JSON.stringify(radarUrl)}`,
196
+ `let RADAR_NODE = ${JSON.stringify(node)}`,
197
+ `let RADAR_WEB_BIN = ${JSON.stringify(webBin)}`,
198
+ `let RADAR_NPX = ${JSON.stringify(npx)}`,
199
+ `let RADAR_MCP_BIN = ${JSON.stringify(mcpBin)}`,
200
+ "// --- END INSTALL CONFIG ---",
201
+ ].join("\n");
202
+ }
203
+ /**
204
+ * Compile the WKWebView app into `dest`. Returns false if the machine cannot build it, so install
205
+ * falls back to the shell launcher rather than failing outright.
206
+ *
207
+ * Swift is compiled AT INSTALL TIME rather than shipping a prebuilt binary in the npm tarball. A
208
+ * prebuilt would need signing and notarization to launch without Gatekeeper refusing it, would need
209
+ * two architectures, and would mean shipping an opaque executable through npm. Compiling locally
210
+ * sidesteps all three: the output is a local build, which Gatekeeper treats as such.
211
+ */
212
+ function buildSwiftApp(dest) {
213
+ const src = path.join(path.dirname(fileURLToPath(import.meta.url)), "macapp", "RadarApp.swift");
214
+ if (!fs.existsSync(src))
215
+ return false;
216
+ try {
217
+ execFileSync("swiftc", ["-version"], { stdio: "ignore", timeout: 10_000 });
218
+ }
219
+ catch {
220
+ return false; // no Swift toolchain (no Xcode or Command Line Tools)
221
+ }
222
+ const webBin = webBinPath();
223
+ // Substitute the install-time config block. Anchored to the markers so the replacement cannot
224
+ // silently miss and compile an app pointing at the defaults.
225
+ const source = fs.readFileSync(src, "utf8");
226
+ const config = swiftInstallConfig(`http://localhost:${WEB_PORT}`, process.execPath, webBin, resolveNpxPath() ?? "", mcpBinPath());
227
+ const patched = source.replace(/\/\/ --- BEGIN INSTALL CONFIG ---[\s\S]*?\/\/ --- END INSTALL CONFIG ---/, config);
228
+ if (patched === source)
229
+ return false; // markers moved; do not ship a misconfigured binary
230
+ const tmpSrc = path.join(os.tmpdir(), `radar-app-${process.pid}.swift`);
231
+ try {
232
+ fs.writeFileSync(tmpSrc, patched);
233
+ // -O for a snappier cold start (this runs before the window appears). Targeting the host arch
234
+ // only is correct: the binary never leaves this machine.
235
+ //
236
+ // A bounded timeout matters beyond "do not hang forever": installMacApp()'s stale-lock
237
+ // recovery treats any lock older than STALE_LOCK_MS as a dead crash leftover and reaps it out
238
+ // from under whatever still holds it. Without a ceiling here, a first-run Xcode license/AMFI
239
+ // prompt could block this call indefinitely (stdio: "pipe" gives it no TTY to answer the
240
+ // prompt on), and a concurrent caller's stale-lock reaper would then start a second install
241
+ // into the same staging path -- the exact concurrent-rebuild corruption the lock exists to
242
+ // prevent, just gated behind a timer instead of removed. Killing a stuck compile here keeps
243
+ // STALE_LOCK_MS an actual upper bound on install duration, not an assumption.
244
+ execFileSync("swiftc", ["-O", "-o", dest, tmpSrc], { stdio: "pipe", timeout: 60_000 });
245
+ return true;
246
+ }
247
+ catch (e) {
248
+ // Surface the compiler's own message: a Swift version mismatch is otherwise a silent downgrade
249
+ // to the browser fallback, and the user would never learn why the window looks like a tab. A
250
+ // timeout kill lands here too (execFileSync sets e.signal, no stderr) -- the generic "could not
251
+ // compile" message still applies, so no separate branch is needed.
252
+ const detail = e instanceof Error && "stderr" in e ? String(e.stderr ?? "") : "";
253
+ console.log(`Note: could not compile the native window${detail ? `:\n${detail.trim()}` : "."}`);
254
+ return false;
255
+ }
256
+ finally {
257
+ fs.rmSync(tmpSrc, { force: true });
258
+ }
259
+ }
260
+ /** Minimal Info.plist. LSUIElement is NOT set: this app SHOULD show in the dock, that is the ask. */
261
+ function infoPlist(executable) {
262
+ return `<?xml version="1.0" encoding="UTF-8"?>
263
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
264
+ <plist version="1.0">
265
+ <dict>
266
+ <key>CFBundleName</key><string>${APP_NAME}</string>
267
+ <key>CFBundleDisplayName</key><string>${APP_NAME}</string>
268
+ <key>CFBundleIdentifier</key><string>com.slack.radar.dashboard.launcher</string>
269
+ <key>CFBundleVersion</key><string>${RADAR_VERSION}</string>
270
+ <key>CFBundleShortVersionString</key><string>${RADAR_VERSION}</string>
271
+ <key>CFBundlePackageType</key><string>APPL</string>
272
+ <key>CFBundleExecutable</key><string>${executable}</string>
273
+ <key>CFBundleIconFile</key><string>radar</string>
274
+ <key>LSMinimumSystemVersion</key><string>11.0</string>
275
+ <!-- The window follows the dashboard's own light/dark theme via its stylesheet, so the app must
276
+ NOT be forced into one appearance. -->
277
+ <key>NSRequiresAquaSystemAppearance</key><false/>
278
+ <!-- The dashboard is served over plain http on loopback. App Transport Security blocks cleartext
279
+ by default, which would make every request from the WKWebView fail. Scoped to localhost
280
+ ONLY: this permits no cleartext to any other host. -->
281
+ <key>NSAppTransportSecurity</key>
282
+ <dict>
283
+ <key>NSExceptionDomains</key>
284
+ <dict>
285
+ <key>localhost</key>
286
+ <dict>
287
+ <key>NSExceptionAllowsInsecureHTTPLoads</key><true/>
288
+ </dict>
289
+ </dict>
290
+ </dict>
291
+ <key>NSHighResolutionCapable</key><true/>
292
+ </dict>
293
+ </plist>
294
+ `;
295
+ }
296
+ /**
297
+ * Build the .icns macOS needs for the dock icon. Generated from the committed 1024px PNG via
298
+ * iconutil, which ships with macOS -- so this needs no ImageMagick (unlike make-icons.mjs, which
299
+ * is a dev-only step). Returns false if anything is missing so install can proceed iconless
300
+ * rather than abort: a working launcher with a generic icon beats no launcher.
301
+ */
302
+ function buildIcns(resourcesDir) {
303
+ const here = path.dirname(fileURLToPath(import.meta.url));
304
+ const png = path.join(here, "public", "icons", "radar-1024.png");
305
+ if (!fs.existsSync(png))
306
+ return false;
307
+ const iconset = path.join(resourcesDir, "radar.iconset");
308
+ try {
309
+ fs.mkdirSync(iconset, { recursive: true });
310
+ // iconutil requires this exact filename set. sips (also built in) does the downscaling.
311
+ const variants = [
312
+ ["icon_16x16.png", 16],
313
+ ["icon_16x16@2x.png", 32],
314
+ ["icon_32x32.png", 32],
315
+ ["icon_32x32@2x.png", 64],
316
+ ["icon_128x128.png", 128],
317
+ ["icon_128x128@2x.png", 256],
318
+ ["icon_256x256.png", 256],
319
+ ["icon_256x256@2x.png", 512],
320
+ ["icon_512x512.png", 512],
321
+ ["icon_512x512@2x.png", 1024],
322
+ ];
323
+ for (const [name, size] of variants) {
324
+ execFileSync("sips", ["-z", String(size), String(size), png, "--out", path.join(iconset, name)], {
325
+ stdio: "ignore",
326
+ });
327
+ }
328
+ execFileSync("iconutil", ["-c", "icns", iconset, "-o", path.join(resourcesDir, "radar.icns")], {
329
+ stdio: "ignore",
330
+ });
331
+ return true;
332
+ }
333
+ catch {
334
+ return false;
335
+ }
336
+ finally {
337
+ // The .iconset is scratch; only the .icns ships inside the bundle.
338
+ fs.rmSync(iconset, { recursive: true, force: true });
339
+ }
340
+ }
341
+ /**
342
+ * Create (or replace) the launcher app. Returns its path.
343
+ *
344
+ * Builds the new bundle at a `.new` staging path and swaps it in only once fully written, so a
345
+ * failure partway through a rebuild leaves the previous, working bundle in place instead of
346
+ * deleted with nothing to replace it. An exclusive lock file guards the whole build+swap against
347
+ * a second concurrent install (a dock self-heal and a manual install-app overlapping, say) racing
348
+ * the same staging path.
349
+ */
350
+ export function installMacApp() {
351
+ const dir = appDir();
352
+ const app = path.join(dir, `${APP_NAME}.app`);
353
+ const staging = `${app}.new`;
354
+ const backup = `${app}.old`;
355
+ const webBin = webBinPath();
356
+ if (!fs.existsSync(webBin)) {
357
+ throw new Error(`cannot find the dashboard entrypoint at ${webBin}`);
358
+ }
359
+ // "wx" is atomic create-if-absent, so there is no check-then-create race on the lock itself.
360
+ // A second caller finding it already there fails immediately rather than racing the same
361
+ // staging path -- for the self-heal caller that just means trying again next launch.
362
+ fs.mkdirSync(dir, { recursive: true });
363
+ const lockPath = path.join(dir, ".install.lock");
364
+ // buildSwiftApp()'s compile step is bounded to 60s (see its execFileSync timeout) specifically
365
+ // so this threshold is an actual upper bound on install duration, not an assumption -- icon
366
+ // generation and everything else here is fast in comparison. A lock older than this can only be
367
+ // a crash leftover, the process that made it died before reaching the finally below. Without
368
+ // this, one crashed install would wedge every self-heal check forever, since nothing else ever
369
+ // removes the lock file.
370
+ const STALE_LOCK_MS = 2 * 60 * 1000;
371
+ let lockFd;
372
+ try {
373
+ lockFd = fs.openSync(lockPath, "wx");
374
+ }
375
+ catch (e) {
376
+ if (e.code !== "EEXIST")
377
+ throw e;
378
+ const age = Date.now() - fs.statSync(lockPath).mtimeMs;
379
+ if (age < STALE_LOCK_MS) {
380
+ throw new Error("an install is already in progress");
381
+ }
382
+ // Stale: clear it and try once more. If a second caller wins this retry, its "wx" still
383
+ // fails atomically and correctly reports "already in progress" -- this is not a re-race of
384
+ // the same lock, just a one-time recovery from an abandoned one.
385
+ fs.rmSync(lockPath, { force: true });
386
+ try {
387
+ lockFd = fs.openSync(lockPath, "wx");
388
+ }
389
+ catch (e2) {
390
+ if (e2.code === "EEXIST") {
391
+ throw new Error("an install is already in progress");
392
+ }
393
+ throw e2;
394
+ }
395
+ }
396
+ try {
397
+ const macos = path.join(staging, "Contents", "MacOS");
398
+ const resources = path.join(staging, "Contents", "Resources");
399
+ fs.rmSync(staging, { recursive: true, force: true });
400
+ fs.mkdirSync(macos, { recursive: true });
401
+ fs.mkdirSync(resources, { recursive: true });
402
+ // Prefer the native window; fall back to the shell launcher (opens a browser) if Swift is absent.
403
+ const nativeExe = path.join(macos, "SlackRadar");
404
+ const native = buildSwiftApp(nativeExe);
405
+ if (!native) {
406
+ // process.execPath is the node running THIS install, the one known-good interpreter on the
407
+ // machine. Under npx that is the same node the dashboard would run under anyway.
408
+ fs.writeFileSync(path.join(macos, "radar-launcher"), launcherScript(process.execPath, webBin, WEB_PORT), {
409
+ mode: 0o755,
410
+ });
411
+ }
412
+ fs.writeFileSync(path.join(staging, "Contents", "Info.plist"), infoPlist(native ? "SlackRadar" : "radar-launcher"));
413
+ const icon = buildIcns(resources);
414
+ // Each rename is one atomic filesystem op, so `app` is never half-old-half-new WITHIN either
415
+ // step. The pair is not one atomic transaction though: a crash between the two renames leaves
416
+ // no `app` at all (it is sitting at `backup`) until the process resumes and completes the
417
+ // second rename or a person restores it by hand -- Node's fs has no rename-exchange primitive
418
+ // to close that particular gap, so this is close to the best achievable on POSIX, not a full
419
+ // guarantee. Clear any stale `.old` first (a previous run's crash leftover) so the first
420
+ // rename cannot fail with ENOTEMPTY.
421
+ fs.rmSync(backup, { recursive: true, force: true });
422
+ if (fs.existsSync(app)) {
423
+ fs.renameSync(app, backup);
424
+ }
425
+ fs.renameSync(staging, app);
426
+ // Best-effort cleanup on success; a leftover .old must not fail an otherwise-good install.
427
+ try {
428
+ fs.rmSync(backup, { recursive: true, force: true });
429
+ }
430
+ catch {
431
+ // harmless
432
+ }
433
+ // Nudge Launch Services to notice the new bundle so it appears in Spotlight immediately
434
+ // instead of whenever the system next rescans. Best effort; the app works regardless.
435
+ try {
436
+ execFileSync("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister", ["-f", app], { stdio: "ignore" });
437
+ }
438
+ catch {
439
+ // lsregister moved or refused; harmless.
440
+ }
441
+ if (!icon) {
442
+ console.log("Note: could not build the app icon, so macOS will show a generic one.");
443
+ }
444
+ return { app, native };
445
+ }
446
+ finally {
447
+ fs.closeSync(lockFd);
448
+ fs.rmSync(lockPath, { force: true });
449
+ }
450
+ }
451
+ /** Entry point for the `install-app` subcommand. Prints what to do next, then reveals the app. */
452
+ export function runInstallApp() {
453
+ if (process.platform !== "darwin") {
454
+ console.error(`install-app builds a macOS .app bundle; this platform is ${process.platform}.`);
455
+ process.exit(1);
456
+ }
457
+ let result;
458
+ try {
459
+ result = installMacApp();
460
+ }
461
+ catch (e) {
462
+ console.error(`install-app failed: ${e.message}`);
463
+ process.exit(1);
464
+ }
465
+ // Name which of the two builds landed. They behave differently in the one way the user cares
466
+ // about (own window vs a browser tab), so a single generic success message would mislead.
467
+ const how = result.native
468
+ ? "It opens in its own window, with no browser involved."
469
+ : "No Swift toolchain was found, so it opens in your default browser instead of a native\n" +
470
+ "window. Install Xcode Command Line Tools (xcode-select --install) and re-run this for\n" +
471
+ "a real app window.";
472
+ console.log(`Installed ${result.app}\n\n` +
473
+ `${how}\n\n` +
474
+ `To keep it in your dock: open it once, then right-click its dock icon and choose\n` +
475
+ `Options > Keep in Dock.\n\n` +
476
+ `Clicking it starts the dashboard if it is not already running.`);
477
+ // Open the containing folder so the user can drag it to the dock without hunting for it.
478
+ try {
479
+ spawn("open", [appDir()], { detached: true, stdio: "ignore" }).unref();
480
+ }
481
+ catch {
482
+ // Best effort.
483
+ }
484
+ }
485
+ /** Single source of truth for "what version is currently installed" -- reads the installed
486
+ * app's Info.plist, shared by runSelfHealCheck() and runSelfHealPrecheck() so the two never
487
+ * drift on how they read it. */
488
+ function readInstalledVersion() {
489
+ const plistPath = path.join(appDir(), `${APP_NAME}.app`, "Contents", "Info.plist");
490
+ if (!fs.existsSync(plistPath))
491
+ return { found: false, reason: "no-app" };
492
+ const plist = fs.readFileSync(plistPath, "utf8");
493
+ const match = plist.match(/<key>CFBundleShortVersionString<\/key><string>(.*?)<\/string>/);
494
+ if (!match)
495
+ return { found: false, reason: "unreadable" };
496
+ return { found: true, version: match[1] };
497
+ }
498
+ /** Logs and records the no-installed-app / unreadable-version early return, the same for
499
+ * runSelfHealCheck() and runSelfHealPrecheck() -- neither has anything to compare against. */
500
+ function logNoInstalledVersion(checkedAt, reason) {
501
+ logSelfHeal(reason === "no-app"
502
+ ? "self-heal: no installed app, nothing to do"
503
+ : "self-heal: could not read the installed version, nothing to do");
504
+ writeSelfHealState({ checkedAt, outcome: "current", toVersion: RADAR_VERSION });
505
+ }
506
+ /**
507
+ * Entry point for `install-app --self-heal-check`, spawned in the background by RadarApp.swift
508
+ * on every dock launch. install-app bakes the .app's paths and version in ONCE, so a Radar
509
+ * upgrade via `npx @slack/radar-mcp@latest` (the documented setup) can leave the installed app
510
+ * pointed at a stale, orphaned npx cache path with no signal to the user. This rebuilds it in
511
+ * place when this process's own version (itself just resolved via the same `@latest` npx call)
512
+ * differs from what is installed, so the fix lands invisibly and takes effect on the NEXT
513
+ * launch. Never throws out of this function: a launcher-triggered background process failing
514
+ * loudly would look like a crash, which is exactly what staying invisible rules out.
515
+ */
516
+ export function runSelfHealCheck() {
517
+ const checkedAt = new Date().toISOString();
518
+ try {
519
+ const read = readInstalledVersion();
520
+ if (!read.found) {
521
+ logNoInstalledVersion(checkedAt, read.reason);
522
+ return;
523
+ }
524
+ const installed = read.version;
525
+ if (installed === RADAR_VERSION) {
526
+ logSelfHeal(`self-heal: already current (${RADAR_VERSION})`);
527
+ writeSelfHealState({ checkedAt, outcome: "current", toVersion: RADAR_VERSION });
528
+ return;
529
+ }
530
+ try {
531
+ installMacApp();
532
+ logSelfHeal(`self-heal: rebuilt ${installed} -> ${RADAR_VERSION}`);
533
+ writeSelfHealState({ checkedAt, outcome: "updated", fromVersion: installed, toVersion: RADAR_VERSION });
534
+ }
535
+ catch (e) {
536
+ logSelfHeal(`self-heal: rebuild failed: ${e.message}`);
537
+ writeSelfHealState({
538
+ checkedAt,
539
+ outcome: "error",
540
+ fromVersion: installed,
541
+ toVersion: RADAR_VERSION,
542
+ error: e.message,
543
+ });
544
+ }
545
+ }
546
+ catch (e) {
547
+ logSelfHeal(`self-heal: unexpected error: ${e.message}`);
548
+ writeSelfHealState({ checkedAt, outcome: "error", toVersion: RADAR_VERSION, error: e.message });
549
+ }
550
+ }
551
+ // Real npm registry by default; a test points this at a local server instead so
552
+ // checkLatestPublishedVersion() never needs a live network call to be exercised.
553
+ let registryUrl = "https://registry.npmjs.org/@slack/radar-mcp/latest";
554
+ /** Test seam: override the registry URL checkLatestPublishedVersion() reads from. */
555
+ export function _setRegistryUrlForTest(url) {
556
+ registryUrl = url;
557
+ }
558
+ /**
559
+ * Reads the latest published version from the npm registry, or null on ANY failure (non-200,
560
+ * timeout, malformed JSON, network down) -- never throws. This is a pure metadata read: it never
561
+ * executes any resolved package's code, so unlike `npx @latest install-app --self-heal-check` it
562
+ * carries none of the old-dispatch risk (an already-published old build that does not understand
563
+ * `--self-heal-check` would just run its full interactive install unconditionally).
564
+ */
565
+ export function checkLatestPublishedVersion() {
566
+ return new Promise((resolve) => {
567
+ // settled-guard: req.destroy() on the timeout path can still fire a subsequent "error"
568
+ // event, which must not resolve a second time.
569
+ let settled = false;
570
+ const done = (v) => {
571
+ if (settled)
572
+ return;
573
+ settled = true;
574
+ resolve(v);
575
+ };
576
+ const client = registryUrl.startsWith("http://") ? http : https;
577
+ const req = client.get(registryUrl, { timeout: 3000 }, (res) => {
578
+ if (res.statusCode !== 200) {
579
+ res.resume();
580
+ done(null);
581
+ return;
582
+ }
583
+ let body = "";
584
+ res.on("data", (chunk) => (body += chunk));
585
+ res.on("end", () => {
586
+ try {
587
+ const parsed = JSON.parse(body);
588
+ done(typeof parsed.version === "string" ? parsed.version : null);
589
+ }
590
+ catch {
591
+ done(null);
592
+ }
593
+ });
594
+ });
595
+ req.on("error", () => done(null));
596
+ req.on("timeout", () => {
597
+ req.destroy();
598
+ done(null);
599
+ });
600
+ });
601
+ }
602
+ /** [major,minor,patch] numeric comparison -- this project's versions are always plain `npm
603
+ * version`-produced semver, so no semver dependency is needed. */
604
+ function isNewerVersion(candidate, installed) {
605
+ const c = candidate.split(".").map(Number);
606
+ const i = installed.split(".").map(Number);
607
+ for (let idx = 0; idx < 3; idx++) {
608
+ const cPart = c[idx] ?? 0;
609
+ const iPart = i[idx] ?? 0;
610
+ if (cPart !== iPart)
611
+ return cPart > iPart;
612
+ }
613
+ return false;
614
+ }
615
+ // Real spawn by default; a test swaps this so it can assert on the npx rebuild call without
616
+ // letting a real `npx @latest` reach the network.
617
+ let selfHealSpawn = spawn;
618
+ /** Test seam: override the spawn implementation runSelfHealPrecheckAsync() uses to trigger the
619
+ * conditional npx rebuild. */
620
+ export function _setSelfHealSpawnForTest(fn) {
621
+ selfHealSpawn = fn;
622
+ }
623
+ /**
624
+ * Entry point for `install-app --self-heal-precheck`. RadarApp.swift now spawns THIS (the
625
+ * already-installed, guaranteed self-heal-aware mcp/index.js) instead of going straight to `npx
626
+ * -y @slack/radar-mcp@latest install-app --self-heal-check`. The direct-to-npx version had a real
627
+ * bug: nothing guaranteed `@latest` resolved to code that understood `--self-heal-check`, and the
628
+ * already-published old dispatch ignores unknown flags and runs the full INTERACTIVE install
629
+ * unconditionally (opens a Finder window) on every dock click until npm catches up -- which is
630
+ * the normal state, not an edge case, for a locally-built dock app ahead of what is published.
631
+ *
632
+ * This checks the registry's plain version metadata first (no package code ever executes) and
633
+ * only spawns the npx follow-up once that confirms a real, strictly-newer version exists. At that
634
+ * point whatever `npx @latest` resolves to is guaranteed to postdate this build and understand
635
+ * `--self-heal-check`, because versions only move forward under this project's manual, sequential
636
+ * publish model -- so the old-dispatch bug cannot trigger here.
637
+ */
638
+ export function runSelfHealPrecheck() {
639
+ void runSelfHealPrecheckAsync();
640
+ }
641
+ /** The awaitable core of runSelfHealPrecheck(), exported so a test can await its outcome
642
+ * directly instead of polling for the fire-and-forget wrapper to finish. */
643
+ export async function runSelfHealPrecheckAsync() {
644
+ const checkedAt = new Date().toISOString();
645
+ try {
646
+ const read = readInstalledVersion();
647
+ if (!read.found) {
648
+ logNoInstalledVersion(checkedAt, read.reason);
649
+ return;
650
+ }
651
+ const installed = read.version;
652
+ const latest = await checkLatestPublishedVersion();
653
+ if (latest === null) {
654
+ logSelfHeal("self-heal: could not reach the npm registry, nothing to do");
655
+ writeSelfHealState({
656
+ checkedAt,
657
+ outcome: "error",
658
+ fromVersion: installed,
659
+ toVersion: RADAR_VERSION,
660
+ error: "could not reach the npm registry",
661
+ });
662
+ return;
663
+ }
664
+ if (!isNewerVersion(latest, installed)) {
665
+ logSelfHeal(`self-heal: already current (${installed})`);
666
+ writeSelfHealState({ checkedAt, outcome: "current", toVersion: installed });
667
+ return;
668
+ }
669
+ const npx = resolveNpxPath();
670
+ if (!npx) {
671
+ logSelfHeal(`self-heal: newer version ${latest} is published but no npx was found, cannot rebuild`);
672
+ writeSelfHealState({
673
+ checkedAt,
674
+ outcome: "error",
675
+ fromVersion: installed,
676
+ toVersion: latest,
677
+ error: "no npx found",
678
+ });
679
+ return;
680
+ }
681
+ logSelfHeal(`self-heal: newer version ${latest} published (installed ${installed}), triggering rebuild`);
682
+ try {
683
+ selfHealSpawn(npx, ["-y", "@slack/radar-mcp@latest", "install-app", "--self-heal-check"], {
684
+ detached: true,
685
+ stdio: "ignore",
686
+ }).unref();
687
+ }
688
+ catch (e) {
689
+ logSelfHeal(`self-heal: could not spawn the rebuild: ${e.message}`);
690
+ writeSelfHealState({
691
+ checkedAt,
692
+ outcome: "error",
693
+ fromVersion: installed,
694
+ toVersion: latest,
695
+ error: e.message,
696
+ });
697
+ }
698
+ }
699
+ catch (e) {
700
+ logSelfHeal(`self-heal: unexpected error: ${e.message}`);
701
+ writeSelfHealState({ checkedAt, outcome: "error", toVersion: RADAR_VERSION, error: e.message });
702
+ }
703
+ }