@slack/radar-mcp 1.13.0 → 1.17.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 (46) hide show
  1. package/README.md +31 -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 +112 -33
  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/shared/android.d.ts +40 -1
  16. package/dist/shared/android.js +114 -51
  17. package/dist/shared/constants.d.ts +25 -1
  18. package/dist/shared/constants.js +27 -1
  19. package/dist/shared/db.js +11 -2
  20. package/dist/shared/debug-log.js +6 -1
  21. package/dist/shared/enable-diagnosis.d.ts +28 -0
  22. package/dist/shared/enable-diagnosis.js +41 -0
  23. package/dist/shared/prefs.d.ts +0 -5
  24. package/dist/shared/prefs.js +6 -2
  25. package/dist/shared/screen.d.ts +46 -9
  26. package/dist/shared/screen.js +74 -11
  27. package/dist/shared/transport.d.ts +62 -5
  28. package/dist/shared/webapp.d.ts +50 -0
  29. package/dist/shared/webapp.js +65 -0
  30. package/dist/web/bin.js +16 -6
  31. package/dist/web/install-app.d.ts +87 -0
  32. package/dist/web/install-app.js +703 -0
  33. package/dist/web/macapp/RadarApp.swift +466 -0
  34. package/dist/web/public/icons/radar-1024.png +0 -0
  35. package/dist/web/public/icons/radar.svg +40 -0
  36. package/dist/web/public/index.html +42 -1
  37. package/dist/web/public/next/app.js +42 -1
  38. package/dist/web/public/next/db.js +153 -7
  39. package/dist/web/public/next/feed.js +18 -0
  40. package/dist/web/public/next/hooks.js +10 -1
  41. package/dist/web/public/next/screen.js +156 -46
  42. package/dist/web/public/next/store.js +164 -21
  43. package/dist/web/public/next/toast.js +134 -0
  44. package/dist/web/server.d.ts +151 -1
  45. package/dist/web/server.js +579 -22
  46. package/package.json +2 -2
@@ -36,10 +36,13 @@ export const MODES = [
36
36
  { key: "flags", label: "Feature Flags", spec: { title: "Feature Flags", summary: "Every feature flag the Slack app knows about, with its current effective value and whether it is locally overridden. Live-updates as flags change on the device. Filter by name.", source: "flags" } },
37
37
  ];
38
38
  // Dashboard mode key -> the ping `sources` name that must be present for the tab to work. Only
39
- // sources the device ships as plugins are gateable; the rest (network/rtm/clog/db/prefs/...)
40
- // always show, and each joins this map when its device-side migration lands. Lives here next to
41
- // MODES (the thing it keys off) so the two cannot drift apart in separate files.
39
+ // sources the device ships as plugins are gateable; the rest (network/db/prefs/...) always show,
40
+ // and each joins this map when its device-side migration lands. Note the mode key is singular
41
+ // while the plugin's source name is plural (clog -> "clogs", trace -> "traces"); the value must
42
+ // be the device's name or the tab hides forever. Lives here next to MODES (the thing it keys
43
+ // off) so the two cannot drift apart in separate files.
42
44
  export const MODE_SOURCE = {
45
+ clog: "clogs",
43
46
  trace: "traces",
44
47
  flags: "feature_flags",
45
48
  };
@@ -90,6 +93,13 @@ export function specMatchesMode(spec) {
90
93
  class Store {
91
94
  spec = { blank: true, viz: [] };
92
95
  conn = { state: "waiting", msg: "connecting…" };
96
+ // Last self-heal check's outcome, fetched once at boot (see fetchSelfHeal). null until that
97
+ // fetch resolves. Drives the header's passive "self-healed to a newer version" indicator.
98
+ selfHeal = null;
99
+ // Set true once the kill button has shut the server down. The header swaps to a "dashboard
100
+ // stopped" state, and the poll loops are torn down so a now-dead server does not spam the
101
+ // console with failed fetches. Emitted as "stopped".
102
+ stopped = false;
93
103
  profileLabel = "detecting…";
94
104
  serverVersion = "";
95
105
  profiles = [];
@@ -155,7 +165,18 @@ class Store {
155
165
  // first non-null serial just records it and does NOT clear (nothing stale to drop yet).
156
166
  _lastSerial = null;
157
167
  _rafPending = false;
168
+ // The pending rAF's id, so a clear can cancel a feed emit queued by a frame that arrived just
169
+ // before the clear. Left uncancelled, it fires after clearRecords() with the now-empty state
170
+ // and reads as a genuine new frame to a paused/frozen feed subscriber.
171
+ _rafHandle = null;
158
172
  _intervals = [];
173
+ // Per-tab presence id, generated once when this Store is constructed. Rides pollProfile's 5s
174
+ // /health fetch (below) so the server can tell how many tabs are live and auto-close when the
175
+ // last one is gone. In-memory only, never persisted: a page reload naturally gets a fresh id,
176
+ // which is fine — the old id ages out of the server's presence map. Rides pollProfile, NOT
177
+ // pollHealth: pollHealth early-returns without fetching while a stream is busy (<6s since the
178
+ // last event), so a user actively watching a chatty stream would send zero presence signals.
179
+ _tabId = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2);
159
180
  // ---- shared detail cache (bounded FIFO) ----
160
181
  cacheDetail(kind, id, detail) {
161
182
  const key = kind + ":" + id;
@@ -234,6 +255,8 @@ class Store {
234
255
  _resetForTest() {
235
256
  this.spec = { blank: true, viz: [] };
236
257
  this.conn = { state: "waiting", msg: "connecting…" };
258
+ this.selfHeal = null;
259
+ this.stopped = false;
237
260
  this.profileLabel = "detecting…";
238
261
  this.serverVersion = "";
239
262
  this.profiles = [];
@@ -268,6 +291,7 @@ class Store {
268
291
  this._dropped = false;
269
292
  this._lastSerial = null;
270
293
  this._rafPending = false;
294
+ this._rafHandle = null;
271
295
  }
272
296
  // Build the graph aggregate structure for the current spec: one zero-filled series per
273
297
  // spec.series entry, or null when the spec has no graph. Shared by applySpec (fresh spec) and
@@ -278,16 +302,32 @@ class Store {
278
302
  }
279
303
  return { N: GRAPH_N, series: this.spec.series.map((s) => ({ def: s, buckets: new Array(GRAPH_N).fill(0), counts: new Array(GRAPH_N).fill(0) })) };
280
304
  }
281
- // Drop every device-scoped cache when the dashboard switches to different hardware. The old
282
- // device's records, dedup keys, learned field values, and detail bodies belong to the wrong
283
- // phone. The live aggregates (counter, rate, graph) reset too: backfill re-ACCUMULATES into
284
- // them rather than rebuilding them, so leaving them would layer the new device's counts on
285
- // top of the old device's totals. The graph is REBUILT zero-filled (not nulled): nothing else
286
- // reconstructs it after a switch, so nulling it would blank the Network/Trace charts until the
287
- // next tab change. Timers and spec are left running.
288
- clearDeviceCaches() {
289
- this.cache = [];
290
- this.cacheKeys = new Set();
305
+ // Wipe locally held records and the aggregates derived from them. Shared by the device switch
306
+ // (clearDeviceCaches) and the feed's clear button (clearView) so the two cannot drift: both mean
307
+ // "forget the records we are holding", and a field added to the store belongs here once rather
308
+ // than in two hand-maintained lists.
309
+ //
310
+ // scopeToSource: undefined wipes the entire shared cache (device switch -- every record belongs
311
+ // to the wrong phone). A source string keeps every OTHER source's cache entries: the raw cache
312
+ // is shared across every tab (applySpec deliberately leaves it intact on a tab switch), so a
313
+ // button scoped to "the view you are looking at" must only drop that source's entries, not the
314
+ // history other tabs are still holding.
315
+ //
316
+ // The live aggregates (counter, rate, graph) always reset in full regardless of scope: they
317
+ // already track only the CURRENT tab's matches (applySpec zeroes them on every tab switch), so
318
+ // there is nothing of another tab's to preserve here. Backfill re-ACCUMULATES into them rather
319
+ // than rebuilding them, so leaving them would layer new counts on top of totals whose records
320
+ // are gone. The graph is REBUILT zero-filled (not nulled): nothing else reconstructs it, so
321
+ // nulling it would blank the Network/Trace charts until the next tab change.
322
+ clearRecords(scopeToSource) {
323
+ if (scopeToSource !== undefined && scopeToSource !== "all") {
324
+ this.cache = this.cache.filter((c) => c.type !== scopeToSource);
325
+ this.cacheKeys = new Set(this.cache.map((c) => this.frameKey(c.type, c.ev)));
326
+ }
327
+ else {
328
+ this.cache = [];
329
+ this.cacheKeys = new Set();
330
+ }
291
331
  this.seen = {};
292
332
  this.detailCache = new Map();
293
333
  this._capSeen = new Set();
@@ -297,15 +337,65 @@ class Store {
297
337
  this.times = [];
298
338
  this.perSec = new Array(PERSEC_N).fill(0);
299
339
  this.graph = this.buildGraph();
340
+ // A frame that arrived just before this clear may have already queued a rAF-batched "feed"
341
+ // emit (bumpFeed). Left to fire, it lands after the records are gone and reads to a paused
342
+ // feed subscriber as a genuine new row -- cancel it, the clear's own synchronous emit below
343
+ // (or the device switch's next real frame) is what should drive the next render instead.
344
+ if (this._rafHandle != null) {
345
+ cancelAnimationFrame(this._rafHandle);
346
+ this._rafHandle = null;
347
+ this._rafPending = false;
348
+ }
349
+ }
350
+ // Drop every device-scoped cache when the dashboard switches to different hardware. The old
351
+ // device's records, dedup keys, learned field values, and detail bodies belong to the wrong
352
+ // phone. Timers and spec are left running.
353
+ clearDeviceCaches() {
354
+ this.clearRecords();
300
355
  // The old device's declared sources do not describe the new one; null until its next poll.
301
356
  this.updateSources(null);
302
357
  // Best-effort latency win: age the fresh-frame stamp so the next pollHealth really fetches.
303
358
  // Backfill frames can re-freshen it within ms; pollProfile's 5s read is the backstop.
304
359
  this._lastEventTs = 0;
305
360
  }
361
+ /**
362
+ * Empty the dashboard's own view: the records this tab is holding and the aggregates over them.
363
+ * Backs the feed's clear button.
364
+ *
365
+ * SCOPED to the active source: other tabs' already-buffered records survive (see clearRecords).
366
+ * The "all" tab has no other scope to preserve, so it still empties the whole shared cache.
367
+ *
368
+ * LOCAL ONLY, on purpose. The device keeps its ring buffers, so a reconnect or a source switch
369
+ * backfills up to 200 records straight back into an emptied feed. The alternative (GET
370
+ * /api/clear) is not scoped to the visible source either: the device's handleClear loops EVERY
371
+ * plugin, so clearing the Network feed would also wipe clogs, traces, RTM, and flags. A button
372
+ * that discards unrelated capture is the worse surprise, and the device buffers stay reachable
373
+ * via the clear_buffers MCP tool for anyone who does want them gone.
374
+ *
375
+ * Deliberately does NOT touch the stream, timers, spec, or device identity: this is a view
376
+ * reset, not a disconnect, so the next frame arrives normally.
377
+ *
378
+ * Emits "feed" synchronously rather than through bumpFeed's rAF batch. A clear is a direct
379
+ * response to a click and must land on THIS frame; the batch exists to coalesce stream floods.
380
+ * Note the feed's own "feed" handler is incremental (it diffs against store.cache.length, which
381
+ * does not necessarily shrink to 0 -- other tabs' entries can remain) -- the caller re-snapshots
382
+ * its view via viewFrames(), which filters by source and is what actually guarantees zero rows.
383
+ */
384
+ clearView() {
385
+ this.clearRecords(this.spec.source || "all");
386
+ this.feedVersion++;
387
+ this.emit("feed", this.feedVersion);
388
+ }
306
389
  // ---- start everything ----
307
- start() {
308
- this.bootDefault();
390
+ async start() {
391
+ // Awaited so the first pollSpec() below always runs AFTER bootDefault's own POST (when it
392
+ // fires one) has landed server-side. Firing both at once used to race: pollSpec's GET is a
393
+ // single fast round trip against bootDefault's slower GET-then-POST, so it almost always won
394
+ // and applied the still-blank spec bootDefault was in the middle of replacing, undoing the
395
+ // local default bootDefault had just set and stranding the page on the blank placeholder
396
+ // until the next 700ms tick happened to read the corrected value.
397
+ await this.bootDefault();
398
+ this.fetchSelfHeal();
309
399
  this.pollSpec();
310
400
  this._intervals.push(setInterval(() => this.pollSpec(), POLL_SPEC_MS));
311
401
  this.pollHealth();
@@ -373,13 +463,32 @@ class Store {
373
463
  try {
374
464
  const cur = await (await fetch("/spec")).json();
375
465
  if (!cur || cur.blank) {
376
- await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(MODES[0].spec) }).catch(() => { });
466
+ // Apply the default locally right away, rather than waiting on the POST plus a
467
+ // future pollSpec tick to notice it landed. Without this, a fresh page load flashes
468
+ // "pick a dashboard above" with no tab highlighted for however long that round trip
469
+ // takes, even though the intent is always to land on Live. start() awaits this method
470
+ // before its own first pollSpec() runs, so that later read confirms the same spec
471
+ // rather than racing this one and overwriting it back to blank.
472
+ this.applySpec(MODES[0].spec);
473
+ await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json", "X-Radar-Dashboard": "1" }, body: JSON.stringify(MODES[0].spec) }).catch(() => { });
377
474
  }
378
475
  }
379
476
  catch {
380
477
  /* ignore */
381
478
  }
382
479
  }
480
+ // Fetch-once: the last self-heal check only changes once per app launch (the dock launcher
481
+ // runs it in the background on startup), so this is not folded into any polling loop.
482
+ async fetchSelfHeal() {
483
+ try {
484
+ const state = await (await fetch("/self-heal")).json();
485
+ this.selfHeal = state;
486
+ this.emit("self-heal", state);
487
+ }
488
+ catch {
489
+ /* leave selfHeal null; the header just renders nothing */
490
+ }
491
+ }
383
492
  markLocalPush(spec) {
384
493
  this._localPushKey = JSON.stringify(spec);
385
494
  }
@@ -387,7 +496,9 @@ class Store {
387
496
  if (opts.local)
388
497
  this.markLocalPush(spec);
389
498
  try {
390
- return await (await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(spec) })).json();
499
+ // X-Radar-Dashboard marks this as an authored write (see the server's handleSetSpec): it is
500
+ // what lets the write count as a keep-alive, and a foreign origin cannot forge it.
501
+ return await (await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json", "X-Radar-Dashboard": "1" }, body: JSON.stringify(spec) })).json();
391
502
  }
392
503
  catch {
393
504
  return { ok: false, error: "request failed" };
@@ -638,8 +749,9 @@ class Store {
638
749
  if (this._rafPending)
639
750
  return;
640
751
  this._rafPending = true;
641
- requestAnimationFrame(() => {
752
+ this._rafHandle = requestAnimationFrame(() => {
642
753
  this._rafPending = false;
754
+ this._rafHandle = null;
643
755
  this.feedVersion++;
644
756
  this.emit("feed", this.feedVersion);
645
757
  });
@@ -813,7 +925,16 @@ class Store {
813
925
  try {
814
926
  const [profilesR, healthR] = await Promise.all([
815
927
  fetch("/_control/profiles").then((r) => r.json()).catch(() => null),
816
- fetch("/health").then((r) => r.json()).catch(() => null),
928
+ // Tab id rides THIS fetch (not pollHealth's) as the poll-only presence signal the
929
+ // server counts for auto-close. pollProfile fires unconditionally every 5s, so a busy
930
+ // stream cannot starve it the way it starves pollHealth's fresh-frame fast path. The
931
+ // X-Radar-Dashboard header is the same CSRF guard /shutdown requires: without it, a
932
+ // foreign origin's plain GET could forge presence (fake a tab open forever, or arm
933
+ // everSeen on an MCP-only session it should never touch). A cross-origin request cannot
934
+ // set a custom header without a CORS preflight it will fail.
935
+ fetch("/health?tab=" + encodeURIComponent(this._tabId), {
936
+ headers: { "X-Radar-Dashboard": "1" },
937
+ }).then((r) => r.json()).catch(() => null),
817
938
  ]);
818
939
  const uid = healthR && healthR.boundUserId;
819
940
  // pollHealth's fresh-frame fast path can skip its /health fetch indefinitely on a chatty
@@ -868,7 +989,7 @@ class Store {
868
989
  // list is refreshed so the dropdown is current and the user can pick a valid device.
869
990
  async selectDevice(serial) {
870
991
  try {
871
- const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST" });
992
+ const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
872
993
  if (!r.ok && r.status === 409) {
873
994
  const body = await r.json().catch(() => null);
874
995
  // Surface the failure on the device chip itself, not via conn: a healthy pollHealth flips
@@ -920,7 +1041,7 @@ class Store {
920
1041
  }
921
1042
  async reconnect() {
922
1043
  try {
923
- const r = await fetch("/enable", { method: "POST" });
1044
+ const r = await fetch("/enable", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
924
1045
  // 409 = ambiguous device (multiple attached, none picked). Surface the server's
925
1046
  // reason through the existing connection-status line so the user sees why enable
926
1047
  // did not connect, instead of a silent stall on "reconnecting…".
@@ -938,6 +1059,28 @@ class Store {
938
1059
  this.pollSpec();
939
1060
  this.resyncStream();
940
1061
  }
1062
+ // Kill the dashboard server from the header button. The X-Radar-Dashboard header is the
1063
+ // CSRF guard the /shutdown route requires (a foreign origin's fetch cannot set it without a
1064
+ // preflight it will fail). On success the server is going away, so tear down every poll
1065
+ // loop + the stream: any further fetch would just fail against a dead port and spam the
1066
+ // console. Flip `stopped` so the header renders the terminal "dashboard stopped" state.
1067
+ async kill() {
1068
+ try {
1069
+ const r = await fetch("/shutdown", {
1070
+ method: "POST",
1071
+ headers: { "X-Radar-Dashboard": "1" },
1072
+ });
1073
+ if (!r.ok)
1074
+ return false;
1075
+ }
1076
+ catch {
1077
+ return false;
1078
+ }
1079
+ this.stop();
1080
+ this.stopped = true;
1081
+ this.emit("stopped", true);
1082
+ return true;
1083
+ }
941
1084
  }
942
1085
  // ---- aggregate math (moved here from widgets per the plan: it belongs WITH the aggregate
943
1086
  // engine, not the renderer). seriesValues turns a graph series' raw buckets into plotted
@@ -0,0 +1,134 @@
1
+ // A small floating confirmation, shown for anything the user needs a moment to notice and then
2
+ // forget (a save, e.g.). Deliberately plain DOM, not a Preact component: the whole point is that
3
+ // it survives regardless of what any particular panel is doing, including a panel that unmounts
4
+ // itself right after triggering the action (the screen overlay returns null when closed, so a
5
+ // confirmation living inside it can never render at the one moment auto-save needs it most).
6
+ const finishListeners = new Set();
7
+ /**
8
+ * Called from the packaged dock app's native side (RadarApp.swift) once a WKDownload actually
9
+ * finishes, with the REAL on-disk path. The filename Radar guesses client-side before the
10
+ * download even starts is not necessarily final -- the app uniquifies a colliding name -- so
11
+ * "where did it save" can only be answered after the fact, from the native side that chose the
12
+ * destination. Never invoked in a plain browser tab: there is no bridge there, so this global is
13
+ * simply never called, and every listener below just never fires, which is correct -- a web page
14
+ * cannot reveal a file in Finder no matter what UI it draws.
15
+ *
16
+ * Uses globalThis, not the bare `window` identifier: this line runs at module load, and Node's
17
+ * test harness for this file installs a stand-in `window` by CALLING a setup function after
18
+ * imports resolve, not before -- referencing `window` directly here would throw before that
19
+ * setup ever runs. globalThis always exists in both Node and a real browser, and in a real
20
+ * browser globalThis IS window, so Swift's `window.__radarDownloadFinished(...)` call still
21
+ * finds this unchanged.
22
+ */
23
+ globalThis.__radarDownloadFinished = (path) => {
24
+ finishListeners.forEach((cb) => cb(path));
25
+ };
26
+ /** Subscribe to native download-finished notifications. Returns an unsubscribe function. */
27
+ export function onDownloadFinished(cb) {
28
+ finishListeners.add(cb);
29
+ return () => finishListeners.delete(cb);
30
+ }
31
+ export function revealInFinder(path) {
32
+ const w = globalThis;
33
+ w.webkit?.messageHandlers?.radarReveal?.postMessage(path);
34
+ }
35
+ /**
36
+ * Does `downloadedPath` hold the capture the server named as `expectedFile`?
37
+ *
38
+ * The two names are usually equal -- /screen/download sends the capture's own basename as its
39
+ * Content-Disposition filename, and that is what the native side receives as the suggested name.
40
+ * They differ when ~/Downloads already holds that name: decideDestinationUsing in RadarApp.swift
41
+ * uniquifies as "<stem>-N.<ext>" rather than overwriting. So exact equality alone would drop the
42
+ * reveal offer on exactly the re-download it was added for, and a bare "any path will do" accepts
43
+ * an earlier save's file. Accepting the name plus its uniquified forms is the narrow middle.
44
+ *
45
+ * Capture names are `radar_screen_<ISO timestamp>.<ext>` with a fixed-width timestamp, so no
46
+ * capture's stem can be another's stem followed by "-N": the suffix cannot collide with a real
47
+ * name.
48
+ */
49
+ export function isCaptureDownloadMatch(downloadedPath, expectedFile) {
50
+ const base = downloadedPath.split("/").pop() ?? "";
51
+ if (!base || !expectedFile)
52
+ return false;
53
+ if (base === expectedFile)
54
+ return true;
55
+ const dot = expectedFile.lastIndexOf(".");
56
+ if (dot <= 0)
57
+ return false;
58
+ const stem = expectedFile.slice(0, dot);
59
+ const ext = expectedFile.slice(dot);
60
+ if (!base.startsWith(stem) || !base.endsWith(ext))
61
+ return false;
62
+ const middle = base.slice(stem.length, base.length - ext.length);
63
+ return /^-\d+$/.test(middle);
64
+ }
65
+ let toastTimer = null;
66
+ // The capture the toast on screen is waiting on, or null when it is not waiting on one. Holding
67
+ // the FILE rather than a boolean is what lets the listener below tell "this save's download
68
+ // landed" from "some earlier save's download landed while this toast happens to be up".
69
+ let awaitedFile = null;
70
+ /**
71
+ * Show a confirmation with no file behind it: a failure, or any plain status line. Leaves the
72
+ * toast unclickable and shuts the reveal gate, so a late download-finished path from an earlier
73
+ * save cannot attach itself to this message.
74
+ */
75
+ export function showToast(message) {
76
+ paint(message);
77
+ awaitedFile = null;
78
+ }
79
+ /**
80
+ * Show a save confirmation and accept a reveal offer for `file` specifically -- the name the
81
+ * server reported for THIS save.
82
+ */
83
+ export function showSaveToast(message, file) {
84
+ paint(message);
85
+ awaitedFile = file;
86
+ }
87
+ function paint(message) {
88
+ let el = document.getElementById("radartoast");
89
+ if (!el) {
90
+ el = document.createElement("div");
91
+ el.id = "radartoast";
92
+ document.body.appendChild(el);
93
+ }
94
+ el.textContent = message;
95
+ // "clickable" is dropped along with the reveal wiring: this toast has no file yet, and the
96
+ // class is what lets it take clicks at all (the base rule is pointer-events:none so a toast
97
+ // never swallows a click meant for a row underneath it).
98
+ el.className = "on";
99
+ // Clear any reveal wiring from a PREVIOUS save so this toast cannot end up pointing at the
100
+ // wrong file if this save's own confirmation is still in flight.
101
+ el.onclick = null;
102
+ el.title = "";
103
+ if (toastTimer)
104
+ clearTimeout(toastTimer);
105
+ const target = el;
106
+ toastTimer = setTimeout(() => {
107
+ target.className = "";
108
+ // A toast that has faded is no longer waiting on anything, so a path arriving after it must
109
+ // not re-arm a toast a later message has since taken over.
110
+ awaitedFile = null;
111
+ }, 4000);
112
+ }
113
+ // Single persistent listener: the toast on screen becomes clickable once the download IT is
114
+ // waiting on actually finishes. Registered once at module load rather than per paint() call, since
115
+ // a toast's own lifetime (4s) can easily be shorter than the round trip to the native side and
116
+ // back for a real recording.
117
+ //
118
+ // Both guards are load-bearing. Without the awaitedFile check this wired reveal onto whichever
119
+ // toast merely had class "on", so a failure toast could offer to reveal an earlier capture; the
120
+ // base rule's pointer-events:none hid that until the clickable state made the handler reachable.
121
+ // Matching the path as well as checking for one keeps a slow first download from attaching itself
122
+ // to the second save's confirmation.
123
+ onDownloadFinished((path) => {
124
+ const el = document.getElementById("radartoast");
125
+ if (!el || !el.classList.contains("on"))
126
+ return;
127
+ if (!awaitedFile || !isCaptureDownloadMatch(path, awaitedFile))
128
+ return;
129
+ // Adding the class is what makes the handler reachable. Setting onclick alone did nothing:
130
+ // the base rule's pointer-events:none meant the element never received the click.
131
+ el.classList.add("clickable");
132
+ el.title = "Click to show in Finder";
133
+ el.onclick = () => revealInFinder(path);
134
+ });
@@ -1,5 +1,7 @@
1
1
  import http from "http";
2
+ import type { ProcessState } from "../shared/transport.js";
2
3
  import { type LogFrame } from "./log-session.js";
4
+ import { stopRecording, getLive } from "../shared/screen.js";
3
5
  declare const WEB_PORT: number;
4
6
  /**
5
7
  * Decide whether to drop a log frame under backpressure. LIVE frames are dropped
@@ -29,7 +31,155 @@ export declare function seedInitialSpec(): void;
29
31
  * Same post-bind discipline as seedInitialSpec: the port owner is the sole legitimate writer.
30
32
  */
31
33
  export declare function cleanupOnBind(): void;
32
- export declare function createServer(): http.Server;
34
+ export declare const TAB_LIVENESS_MS = 75000;
35
+ export declare const AUTO_CLOSE_GRACE_MS: number;
36
+ /**
37
+ * Pure auto-close decision, mirroring screen.ts's nextViewerAction/shouldRelaunch precedent:
38
+ * the sweep owns the timestamp bookkeeping, this owns only the yes/no. Close only when there
39
+ * are no live tabs, at least one tab has EVER been seen (an MCP-spawned dashboard nobody has
40
+ * opened must never self-destruct), and the empty period has outlived the grace window.
41
+ * Exported for unit testing without a clock or a socket.
42
+ */
43
+ export declare function shouldAutoClose(liveTabs: number, everSeen: boolean, msSinceEmpty: number | null): boolean;
44
+ export declare function touchTab(id: string, now?: number): void;
45
+ /**
46
+ * Treat an authored MCP write (a /setspec, a successful /enable) as a keep-alive equivalent to
47
+ * a tab being present: clear the empty marker so the idle timer never fires mid-session. NOT
48
+ * gated on any tab being tracked — an hour-long MCP debugging session with zero open tabs is a
49
+ * legitimate reason to stay up, and losing it would drop the session logcat ring, the device
50
+ * pin, and the pulled-DB cache. Deliberately does NOT set everSeen: an MCP-only dashboard that
51
+ * nobody ever opened stays protected by the everSeen guard even after the MCP goes quiet.
52
+ */
53
+ export declare function markKeepAlive(): void;
54
+ /**
55
+ * Whether a request may buy the process more life. True for our own client and the MCP, false
56
+ * for anything else, so a foreign page cannot postpone auto-close forever.
57
+ *
58
+ * Two accepted proofs, both unforgeable cross-origin without a CORS preflight the foreign
59
+ * origin cannot satisfy: the `X-Radar-Dashboard` header `/shutdown` already requires, or an
60
+ * `application/json` content-type. JSON counts because every MCP version ever published sends
61
+ * it on `/setspec`; requiring only the header would silently strip the keep-alive from an older
62
+ * globally-installed MCP talking to a newer dashboard.
63
+ *
64
+ * The content-type test compares the MIME ESSENCE, never a substring. CORS safelists a
65
+ * content-type by its essence and ignores parameters, so `text/plain; charset=application/json`
66
+ * is a SIMPLE request that any page can send with no preflight while still containing the
67
+ * string "application/json". A substring match there would reopen the exact hole this closes.
68
+ *
69
+ * Exported so the route wiring is directly testable: the decision, not just its effect.
70
+ */
71
+ export declare function isAuthoredRequest(headers: {
72
+ "x-radar-dashboard"?: string | string[];
73
+ "content-type"?: string | string[];
74
+ }): boolean;
75
+ /**
76
+ * One sweep tick: prune stale tab ids, maintain the emptySince marker across the 1->0 / 0->1
77
+ * transitions, and return whether the dashboard should auto-close now. Owns all timestamp
78
+ * bookkeeping and delegates the decision to shouldAutoClose. `now` is injectable so the
79
+ * transition logic is unit-testable with a fake clock. Returns true only on the tick where the
80
+ * grace window has elapsed with no live tabs.
81
+ */
82
+ export declare function sweepPresence(now?: number): boolean;
83
+ /** Presence snapshot for tests. */
84
+ export declare function getPresenceState(): {
85
+ liveTabs: number;
86
+ everSeen: boolean;
87
+ emptySince: number | null;
88
+ };
89
+ /** Reset presence between tests (module state is a process singleton). */
90
+ export declare function resetPresenceForTest(): void;
91
+ interface ShutdownDeps {
92
+ getLive?: typeof getLive;
93
+ stopRecording?: typeof stopRecording;
94
+ exit?: (code: number) => void;
95
+ log?: (msg: string) => void;
96
+ }
97
+ /**
98
+ * Gracefully shut the dashboard down. Reached by the manual /shutdown route and the auto-close
99
+ * sweep, so the server.close + timeout-fallback exit logic lives in exactly one place. Before
100
+ * tearing down, if a screen recording is live, finalize it: bin.ts's exit-time cleanup SIGKILLs
101
+ * the cast's ffmpeg child, and an ffmpeg killed mid-write leaves an mp4 with no moov atom
102
+ * (unplayable). Awaiting stopRecording writes the moov and closes the file first.
103
+ *
104
+ * That mp4 safety covers THOSE TWO PATHS ONLY. bin.ts also registers this on SIGINT/SIGTERM,
105
+ * but screen.ts's own signal handlers exit synchronously and are registered first, so Ctrl-C
106
+ * never reaches here and a recording killed that way can still be corrupt. Pre-existing gap;
107
+ * see the bin.ts comment at the SIGINT registration for why fixing it means touching screen.ts.
108
+ *
109
+ * A second call for the same server is a no-op: the sweep tick and a manual /shutdown can both
110
+ * fire, and awaiting stopRecording gives the next tick a window to land mid-flight.
111
+ * Deps are injectable so the recording-safety path is testable without spawning ffmpeg or
112
+ * actually exiting the process.
113
+ */
114
+ export declare function shutdownDashboard(server: {
115
+ close(cb?: () => void): void;
116
+ }, deps?: ShutdownDeps): Promise<void>;
117
+ /**
118
+ * Start the periodic auto-close sweep. Called once by bin.ts AFTER a successful listen bind, not
119
+ * from createServer, so importing this module (or spinning a throwaway server in a test) never
120
+ * arms a timer that could process.exit the test runner. The interval is unref'd so it never
121
+ * keeps the process alive on its own.
122
+ */
123
+ export declare function startAutoCloseSweep(server: http.Server): ReturnType<typeof setInterval> | null;
124
+ /**
125
+ * Build the dashboard HTTP server. `onShutdown` is the hook the manual /shutdown route fires
126
+ * after answering; it defaults to the real graceful shutdown and is injectable so a test can
127
+ * exercise the route without exiting the process. bin.ts calls createServer() with no args.
128
+ */
129
+ export declare function createServer(onShutdown?: (server: http.Server) => void): http.Server;
130
+ /**
131
+ * The /enable response body for a completed device probe, plus its one side effect: a
132
+ * successful re-arm keeps the dashboard alive (an MCP-driven session can re-enable with no tab
133
+ * open, and that must not let the idle timer fire out from under it).
134
+ *
135
+ * `onEnabled` fires only on a successful probe. The route passes `markKeepAlive` when the
136
+ * request was authored (see isAuthoredRequest) and OMITS it otherwise, so an unauthored caller
137
+ * gets the same body but buys no extra process life. Injected rather than called directly so
138
+ * the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
139
+ * a real socket to RADAR_HOST:RADAR_PORT, which this function does not touch at all).
140
+ *
141
+ * A failed probe gets guidance, not a bare false: the broadcast landed (or exited 0 with no
142
+ * receiver), so the likely causes are a build without the slack-radar modules or the wrong
143
+ * profile. Mirrors the MCP enable message. Exported for unit testing.
144
+ */
145
+ /**
146
+ * Which keep-alive hook /enable hands to enableResultBody: the real one for an authored request,
147
+ * none otherwise. Its own function purely so a test can assert the CHOICE. Asserting the effect
148
+ * through the route cannot cover this — handleEnable's device probe fails with no hardware, which
149
+ * short-circuits before the hook is ever consulted, so a route-level test passes either way (a
150
+ * mutation deleting the gate survived the whole suite before this existed).
151
+ */
152
+ export declare function keepAliveHookFor(authored: boolean): (() => void) | undefined;
153
+ /**
154
+ * Whether the dashboard serves this request without proof of origin. Everything else is refused
155
+ * unless authored. Exported so a test can drive the decision directly, and so the open surface is
156
+ * reviewable in one place instead of inferred from twenty route branches.
157
+ *
158
+ * Reads are open by path. Writes are closed with exactly two named exceptions, both justified
159
+ * below. A POST to a read path is NOT open: only GET and HEAD can ever be reads.
160
+ */
161
+ export declare function isOpenToAnyCaller(urlPath: string, method: string | undefined): boolean;
162
+ /**
163
+ * Whether a request's Host names this loopback dashboard. The listener is bound to 127.0.0.1, but
164
+ * that only limits which interface accepts the TCP connection: a browser resolving an attacker's
165
+ * domain to 127.0.0.1 (DNS rebinding) connects locally and arrives with that domain in Host. The
166
+ * page is then same-origin by the browser's reckoning, so it can set any header it likes and the
167
+ * X-Radar-Dashboard guard buys nothing against it. Checking Host is what makes the loopback bind
168
+ * an actual boundary, and it matters most for /shutdown, which kills the process.
169
+ *
170
+ * Accepts localhost / 127.0.0.1 / [::1] / ::1 / 0.0.0.0, with or without a port, and a missing
171
+ * Host (HTTP/1.0 and a bare socket client send none; those cannot be a rebound browser).
172
+ *
173
+ * SLACK_RADAR_ALLOWED_HOSTS adds names for the setups that reach the dashboard by something other
174
+ * than localhost -- a /etc/hosts alias, a container or Codespaces forwarded URL, a LAN hostname.
175
+ * Comma-separated, `host` or `host:port`; a bare name matches on any port. Without it those users
176
+ * would just get a 403 with nothing to do about it.
177
+ */
178
+ export declare function isLocalHostHeader(host: string | string[] | undefined, allowedHosts?: string | undefined): boolean;
179
+ export declare function enableResultBody(enabled: boolean, onEnabled?: () => void, processState?: ProcessState): {
180
+ enabled: boolean;
181
+ error?: string;
182
+ };
33
183
  export declare const DEVICE_SOURCES: Record<string, {
34
184
  segment: string;
35
185
  arrayKey: string;