@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
@@ -1,4 +1,4 @@
1
- import { STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource } from "./registry.js";
1
+ import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource } from "./registry.js";
2
2
  // Logcat-scale retention. At the live firehose (~400+ events/sec on the unified Live tab) a
3
3
  // small ring recycles in seconds, so a rare signal (a once-per-5s heartbeat) gets evicted
4
4
  // before you can filter for it. Android Studio / Flipper keep the whole session and filter
@@ -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,9 @@ 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;
93
99
  // Set true once the kill button has shut the server down. The header swaps to a "dashboard
94
100
  // stopped" state, and the poll loops are torn down so a now-dead server does not spam the
95
101
  // console with failed fetches. Emitted as "stopped".
@@ -106,12 +112,76 @@ class Store {
106
112
  // (adb not on PATH, server down), which is distinct from "zero devices attached". The header
107
113
  // chip renders this differently so the user knows to check adb, not plug in a phone.
108
114
  devicesError = false;
109
- // Last device-select failure text (an /enable 409 or error), or null when the pick succeeded.
110
- // Distinct from devicesError (adb itself failed) and from conn: a device-select failure used to
111
- // ride conn via setConn("waiting", …), but any healthy pollHealth flips conn back to connected
112
- // within 2s and the message vanished before the user read it. This field is owned by
113
- // selectDevice, survives the health poll, and clears only on a successful pick.
115
+ // Why the last device PICK failed, or null when it succeeded. Owned by selectDevice alone.
116
+ // Distinct from devicesError (adb itself failed) and from conn: a pick failure used to ride conn
117
+ // via setConn("waiting", …), but any pollHealth flips conn within 2s and the message vanished
118
+ // before the user read it. A failed pick is an unfulfilled request for a SPECIFIC device, so it
119
+ // is invalidated by one thing only, a later pick that works, and nothing about device health
120
+ // refutes it. It therefore renders whether or not the dashboard is connected.
114
121
  deviceError = null;
122
+ // Why the last Reconnect press did not arm the device, or null when it did. Owned by reconnect().
123
+ //
124
+ // KEPT SEPARATE FROM deviceError on purpose: a pick failure is about a device the user named,
125
+ // this one is about getting connected at all, and they are invalidated by different events.
126
+ //
127
+ // NOT cleared by any POLL trying to decide whether the reason is still TRUE, deliberately. Five
128
+ // such rules were tried and each lost information or lied, because inference cannot answer that:
129
+ // "connected" only means a device frame arrived within 6 seconds, which refutes "no debug build is
130
+ // running" while refuting nothing at all about "adb: device offline" or an ambiguous pick, and this
131
+ // same field carries all of them.
132
+ //
133
+ // The answerable question is WHICH OUTAGE the reason belongs to, so it is stamped with the outage
134
+ // epoch it was produced in and `visibleEnableError` shows it only during that same epoch. A reason
135
+ // therefore cannot surface in a later outage it does not explain, while a diagnostic still relevant
136
+ // to the CURRENT outage keeps showing for as long as that outage lasts.
137
+ //
138
+ // Four things DO clear it outright, via clearEnableError. Two are not truth judgements: a press
139
+ // whose request never completed has no answer to report, and a REAL change of bound device, one
140
+ // non-null serial to a different one, retires a reason that described different hardware (the
141
+ // observed serial edge and the pick path both perform that clear). Two ARE truth judgements,
142
+ // allowed because they come from a completed action's own answer rather than inference: a
143
+ // successful arm refutes the reason, reconnect and pick alike, whatever the serial did; and a
144
+ // later failed pick supersedes it, because the newest action owns the header. First sight of a
145
+ // serial is not a change of device and keeps the reason. A press does not erase its own answer:
146
+ // the /enable reply echoes the pinned serial, and reconnect() advances the baseline from the
147
+ // reply before the reason is written, so the follow-up poll observes no edge.
148
+ enableError = null;
149
+ _enableErrorEpoch = -1;
150
+ // Counts outages: bumped by setConn when the connection leaves a CONFIRMED connected state.
151
+ _outageEpoch = 0;
152
+ // Pieces of positive evidence that the current connected state is real, at most one per
153
+ // proofSpacingMs. Reset the moment the connection drops. Two are required before leaving "connected"
154
+ // counts as the end of an outage, so neither one flaky success nor one burst of frames can split a
155
+ // continuing outage in two.
156
+ _connProof = 0;
157
+ _lastProofTs = 0;
158
+ // Minimum gap between two pieces of evidence, matching the health poll cadence so the two-proof
159
+ // rule really is the mirror of the two-miss rule. Read-only: tests exercise the floor by driving
160
+ // connClock, never by retuning or disabling the floor itself.
161
+ proofSpacingMs = POLL_HEALTH_MS;
162
+ // The clock the CONNECTION logic reads: stream freshness and the proof spacing floor. Injectable so
163
+ // a test can represent observations that are genuinely seconds apart without sleeping, which is the
164
+ // only way to exercise the spacing floor rather than switching it off. Deliberately NOT used by the
165
+ // cache and rate windows further down: those have unrelated timings, and overriding one clock must
166
+ // not silently retune them.
167
+ connClock = () => Date.now();
168
+ // The reconnect reason the header may actually show: only while disconnected, and only for the
169
+ // outage that produced it. Both conditions in one place so the component cannot get it half right.
170
+ get visibleEnableError() {
171
+ if (this.conn.state === "connected")
172
+ return null;
173
+ return this._enableErrorEpoch === this._outageEpoch ? this.enableError : null;
174
+ }
175
+ // Drop the reason outright. Used where the reason is not merely from another outage but describes a
176
+ // question that was never answered, or a device we are no longer bound to. The epoch stamp handles
177
+ // "belongs to a different outage"; this handles "belongs to nothing".
178
+ clearEnableError() {
179
+ if (this.enableError === null && this._enableErrorEpoch === -1)
180
+ return;
181
+ this.enableError = null;
182
+ this._enableErrorEpoch = -1;
183
+ this.emit("enable-error", this.visibleEnableError);
184
+ }
115
185
  // Capture-source names the device declares on ping (seam builds). null = old build with no
116
186
  // discovery, in which case every tab shows (today's behavior). Emitted as "sources" on change.
117
187
  deviceSources = null;
@@ -159,6 +229,10 @@ class Store {
159
229
  // first non-null serial just records it and does NOT clear (nothing stale to drop yet).
160
230
  _lastSerial = null;
161
231
  _rafPending = false;
232
+ // The pending rAF's id, so a clear can cancel a feed emit queued by a frame that arrived just
233
+ // before the clear. Left uncancelled, it fires after clearRecords() with the now-empty state
234
+ // and reads as a genuine new frame to a paused/frozen feed subscriber.
235
+ _rafHandle = null;
162
236
  _intervals = [];
163
237
  // Per-tab presence id, generated once when this Store is constructed. Rides pollProfile's 5s
164
238
  // /health fetch (below) so the server can tell how many tabs are live and auto-close when the
@@ -240,11 +314,14 @@ class Store {
240
314
  subscriberCount(evt) {
241
315
  return this._subs[evt]?.size ?? 0;
242
316
  }
243
- // Test-only: reset all mutable state to construction defaults. Centralized so the reset list
244
- // cannot drift from the fields (a hand-maintained reset in the test omitted half of them).
317
+ // Test-only: reset data and connection state to construction defaults. Centralized so the
318
+ // reset list cannot drift from the fields (a hand-maintained reset in the test omitted half of
319
+ // them). Deliberately NOT reset: subscribers, live timers and stream handles (start() and
320
+ // openStream() own those lifecycles), and _tabId, which identifies the page for its whole life.
245
321
  _resetForTest() {
246
322
  this.spec = { blank: true, viz: [] };
247
323
  this.conn = { state: "waiting", msg: "connecting…" };
324
+ this.selfHeal = null;
248
325
  this.stopped = false;
249
326
  this.profileLabel = "detecting…";
250
327
  this.serverVersion = "";
@@ -253,6 +330,12 @@ class Store {
253
330
  this.selectedDevice = null;
254
331
  this.devicesError = false;
255
332
  this.deviceError = null;
333
+ this.enableError = null;
334
+ this._enableErrorEpoch = -1;
335
+ this._outageEpoch = 0;
336
+ this._connProof = 0;
337
+ this._lastProofTs = 0;
338
+ this.connClock = () => Date.now();
256
339
  this.deviceSources = null;
257
340
  this.cache = [];
258
341
  this.cacheKeys = new Set();
@@ -279,7 +362,12 @@ class Store {
279
362
  this._backfillToken = 0;
280
363
  this._dropped = false;
281
364
  this._lastSerial = null;
365
+ // Cancel rather than just forget: a rAF queued before the reset would otherwise fire after
366
+ // it and bump feedVersion on the supposedly fresh store (mirrors clearRecords).
367
+ if (this._rafHandle != null)
368
+ cancelAnimationFrame(this._rafHandle);
282
369
  this._rafPending = false;
370
+ this._rafHandle = null;
283
371
  }
284
372
  // Build the graph aggregate structure for the current spec: one zero-filled series per
285
373
  // spec.series entry, or null when the spec has no graph. Shared by applySpec (fresh spec) and
@@ -290,16 +378,32 @@ class Store {
290
378
  }
291
379
  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) })) };
292
380
  }
293
- // Drop every device-scoped cache when the dashboard switches to different hardware. The old
294
- // device's records, dedup keys, learned field values, and detail bodies belong to the wrong
295
- // phone. The live aggregates (counter, rate, graph) reset too: backfill re-ACCUMULATES into
296
- // them rather than rebuilding them, so leaving them would layer the new device's counts on
297
- // top of the old device's totals. The graph is REBUILT zero-filled (not nulled): nothing else
298
- // reconstructs it after a switch, so nulling it would blank the Network/Trace charts until the
299
- // next tab change. Timers and spec are left running.
300
- clearDeviceCaches() {
301
- this.cache = [];
302
- this.cacheKeys = new Set();
381
+ // Wipe locally held records and the aggregates derived from them. Shared by the device switch
382
+ // (clearDeviceCaches) and the feed's clear button (clearView) so the two cannot drift: both mean
383
+ // "forget the records we are holding", and a field added to the store belongs here once rather
384
+ // than in two hand-maintained lists.
385
+ //
386
+ // scopeToSource: undefined wipes the entire shared cache (device switch -- every record belongs
387
+ // to the wrong phone). A source string keeps every OTHER source's cache entries: the raw cache
388
+ // is shared across every tab (applySpec deliberately leaves it intact on a tab switch), so a
389
+ // button scoped to "the view you are looking at" must only drop that source's entries, not the
390
+ // history other tabs are still holding.
391
+ //
392
+ // The live aggregates (counter, rate, graph) always reset in full regardless of scope: they
393
+ // already track only the CURRENT tab's matches (applySpec zeroes them on every tab switch), so
394
+ // there is nothing of another tab's to preserve here. Backfill re-ACCUMULATES into them rather
395
+ // than rebuilding them, so leaving them would layer new counts on top of totals whose records
396
+ // are gone. The graph is REBUILT zero-filled (not nulled): nothing else reconstructs it, so
397
+ // nulling it would blank the Network/Trace charts until the next tab change.
398
+ clearRecords(scopeToSource) {
399
+ if (scopeToSource !== undefined && scopeToSource !== "all") {
400
+ this.cache = this.cache.filter((c) => c.type !== scopeToSource);
401
+ this.cacheKeys = new Set(this.cache.map((c) => this.frameKey(c.type, c.ev)));
402
+ }
403
+ else {
404
+ this.cache = [];
405
+ this.cacheKeys = new Set();
406
+ }
303
407
  this.seen = {};
304
408
  this.detailCache = new Map();
305
409
  this._capSeen = new Set();
@@ -309,15 +413,65 @@ class Store {
309
413
  this.times = [];
310
414
  this.perSec = new Array(PERSEC_N).fill(0);
311
415
  this.graph = this.buildGraph();
416
+ // A frame that arrived just before this clear may have already queued a rAF-batched "feed"
417
+ // emit (bumpFeed). Left to fire, it lands after the records are gone and reads to a paused
418
+ // feed subscriber as a genuine new row -- cancel it, the clear's own synchronous emit below
419
+ // (or the device switch's next real frame) is what should drive the next render instead.
420
+ if (this._rafHandle != null) {
421
+ cancelAnimationFrame(this._rafHandle);
422
+ this._rafHandle = null;
423
+ this._rafPending = false;
424
+ }
425
+ }
426
+ // Drop every device-scoped cache when the dashboard switches to different hardware. The old
427
+ // device's records, dedup keys, learned field values, and detail bodies belong to the wrong
428
+ // phone. Timers and spec are left running.
429
+ clearDeviceCaches() {
430
+ this.clearRecords();
312
431
  // The old device's declared sources do not describe the new one; null until its next poll.
313
432
  this.updateSources(null);
314
433
  // Best-effort latency win: age the fresh-frame stamp so the next pollHealth really fetches.
315
434
  // Backfill frames can re-freshen it within ms; pollProfile's 5s read is the backstop.
316
435
  this._lastEventTs = 0;
317
436
  }
437
+ /**
438
+ * Empty the dashboard's own view: the records this tab is holding and the aggregates over them.
439
+ * Backs the feed's clear button.
440
+ *
441
+ * SCOPED to the active source: other tabs' already-buffered records survive (see clearRecords).
442
+ * The "all" tab has no other scope to preserve, so it still empties the whole shared cache.
443
+ *
444
+ * LOCAL ONLY, on purpose. The device keeps its ring buffers, so a reconnect or a source switch
445
+ * backfills up to 200 records straight back into an emptied feed. The alternative (GET
446
+ * /api/clear) is not scoped to the visible source either: the device's handleClear loops EVERY
447
+ * plugin, so clearing the Network feed would also wipe clogs, traces, RTM, and flags. A button
448
+ * that discards unrelated capture is the worse surprise, and the device buffers stay reachable
449
+ * via the clear_buffers MCP tool for anyone who does want them gone.
450
+ *
451
+ * Deliberately does NOT touch the stream, timers, spec, or device identity: this is a view
452
+ * reset, not a disconnect, so the next frame arrives normally.
453
+ *
454
+ * Emits "feed" synchronously rather than through bumpFeed's rAF batch. A clear is a direct
455
+ * response to a click and must land on THIS frame; the batch exists to coalesce stream floods.
456
+ * Note the feed's own "feed" handler is incremental (it diffs against store.cache.length, which
457
+ * does not necessarily shrink to 0 -- other tabs' entries can remain) -- the caller re-snapshots
458
+ * its view via viewFrames(), which filters by source and is what actually guarantees zero rows.
459
+ */
460
+ clearView() {
461
+ this.clearRecords(this.spec.source || "all");
462
+ this.feedVersion++;
463
+ this.emit("feed", this.feedVersion);
464
+ }
318
465
  // ---- start everything ----
319
- start() {
320
- this.bootDefault();
466
+ async start() {
467
+ // Awaited so the first pollSpec() below always runs AFTER bootDefault's own POST (when it
468
+ // fires one) has landed server-side. Firing both at once used to race: pollSpec's GET is a
469
+ // single fast round trip against bootDefault's slower GET-then-POST, so it almost always won
470
+ // and applied the still-blank spec bootDefault was in the middle of replacing, undoing the
471
+ // local default bootDefault had just set and stranding the page on the blank placeholder
472
+ // until the next 700ms tick happened to read the corrected value.
473
+ await this.bootDefault();
474
+ this.fetchSelfHeal();
321
475
  this.pollSpec();
322
476
  this._intervals.push(setInterval(() => this.pollSpec(), POLL_SPEC_MS));
323
477
  this.pollHealth();
@@ -337,6 +491,32 @@ class Store {
337
491
  }
338
492
  this.closeStream();
339
493
  }
494
+ // Record one piece of positive evidence that the device is really there, at most one per
495
+ // proofSpacingMs. Two of these are what let a reconnection count as having ENDED an outage.
496
+ //
497
+ // Called ONLY from the two places that actually OBSERVE the device: a device-kind stream frame, and
498
+ // a /health reply saying device true. Not from setConn, and specifically not from pollHealth's
499
+ // fresh-frame fast path, which re-asserts a single stale frame every 2s and could therefore bank
500
+ // both proofs from ONE frame, ending an outage on evidence that never repeated. A busy device still
501
+ // earns its proofs from the real frames themselves, so restricting counting to observation costs it
502
+ // nothing.
503
+ //
504
+ // Spacing matters as much as the count: two consecutive health MISSES are poll-cadence apart by
505
+ // construction, while two SSE frames can land in the same tick, and an EventSource flushing a
506
+ // backlog on reconnect does exactly that. Without the floor a burst passes for a recovery.
507
+ //
508
+ // Skipped while an ambiguous multi-device pick is outstanding, for the same reason setConn refuses
509
+ // to call that state connected: frames can ride a stale forward from a prior pin, so they are not
510
+ // evidence about the device the user has not chosen yet.
511
+ noteDeviceProof() {
512
+ if (this.needsDevicePick)
513
+ return;
514
+ const now = this.connClock();
515
+ if (now - this._lastProofTs < this.proofSpacingMs)
516
+ return;
517
+ this._connProof++;
518
+ this._lastProofTs = now;
519
+ }
340
520
  setConn(state, msg) {
341
521
  // Unpinned multi-device is never "connected": frames can ride a stale forward from a prior
342
522
  // pin and flip the dot green while the per-device surfaces (DB run-as) are broken by the
@@ -348,7 +528,29 @@ class Store {
348
528
  }
349
529
  if (this.conn.state === state && this.conn.msg === (msg || ""))
350
530
  return;
531
+ const wasConnected = this.conn.state === "connected";
351
532
  this.conn = { state, msg: msg || "" };
533
+ // An outage ENDS here, and only a CONFIRMED connection counts as having ended one: two pieces of
534
+ // evidence, each at least proofSpacingMs apart. Both halves matter. The COUNT alone was not
535
+ // enough, because two frames can arrive in one tick and a reconnect backlog burst does exactly
536
+ // that, so a burst passed for a recovery. The SPACING is what makes this a real mirror of the two
537
+ // consecutive misses required before the UI says "device offline", which are poll-cadence apart by
538
+ // construction. Without both, a blip inside a continuing outage splits it in two and permanently
539
+ // orphans the reason the user was just given, for the rest of the outage they are still in.
540
+ if (wasConnected && state !== "connected") {
541
+ if (this._connProof >= 2)
542
+ this._outageEpoch++;
543
+ this._connProof = 0;
544
+ // Restart the spacing clock at the drop, so the first proof of the NEXT recovery has to be
545
+ // earned after it rather than qualifying instantly off a gap that is really the outage itself.
546
+ this._lastProofTs = this.connClock();
547
+ }
548
+ // visibleEnableError is derived from conn, so a conn change can change what the header should
549
+ // show without anything touching enableError itself. Subscribers re-read only on their OWN
550
+ // event (see useStoreValue), so this emit is what keeps the rendered reason honest; without it
551
+ // the message stayed on screen after the dashboard reconnected. Conn changes are already
552
+ // deduped by the early return above, so this is at most one extra emit per real change.
553
+ this.emit("enable-error", this.visibleEnableError);
352
554
  this.emit("conn", this.conn);
353
555
  }
354
556
  async pollSpec() {
@@ -385,6 +587,13 @@ class Store {
385
587
  try {
386
588
  const cur = await (await fetch("/spec")).json();
387
589
  if (!cur || cur.blank) {
590
+ // Apply the default locally right away, rather than waiting on the POST plus a
591
+ // future pollSpec tick to notice it landed. Without this, a fresh page load flashes
592
+ // "pick a dashboard above" with no tab highlighted for however long that round trip
593
+ // takes, even though the intent is always to land on Live. start() awaits this method
594
+ // before its own first pollSpec() runs, so that later read confirms the same spec
595
+ // rather than racing this one and overwriting it back to blank.
596
+ this.applySpec(MODES[0].spec);
388
597
  await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json", "X-Radar-Dashboard": "1" }, body: JSON.stringify(MODES[0].spec) }).catch(() => { });
389
598
  }
390
599
  }
@@ -392,6 +601,18 @@ class Store {
392
601
  /* ignore */
393
602
  }
394
603
  }
604
+ // Fetch-once: the last self-heal check only changes once per app launch (the dock launcher
605
+ // runs it in the background on startup), so this is not folded into any polling loop.
606
+ async fetchSelfHeal() {
607
+ try {
608
+ const state = await (await fetch("/self-heal")).json();
609
+ this.selfHeal = state;
610
+ this.emit("self-heal", state);
611
+ }
612
+ catch {
613
+ /* leave selfHeal null; the header just renders nothing */
614
+ }
615
+ }
395
616
  markLocalPush(spec) {
396
617
  this._localPushKey = JSON.stringify(spec);
397
618
  }
@@ -480,12 +701,25 @@ class Store {
480
701
  live = false; // server-replayed history: never alerts/counts twice
481
702
  if (!STREAM_KINDS.includes(f.type))
482
703
  return;
483
- this._lastEventTs = Date.now();
484
- // A live frame proves the stream healed itself (the browser EventSource auto-reconnects on a
485
- // transient blip). Clear _dropped here so recovered() does NOT later tear down this healthy
486
- // stream and re-open it: recovered() should only fire when the stream did NOT self-heal.
487
- this._dropped = false;
488
- this.setConn("connected", "");
704
+ // Only a frame FROM THE DEVICE is evidence the device is connected. Logs are host-side: an
705
+ // `adb logcat` child of the dashboard keeps printing other packages' lines with Radar dead and
706
+ // the Slack app not even running, and each one used to stamp the freshness clock and assert
707
+ // "connected". That parked pollHealth on its <6s fast path forever, so the header read "● live"
708
+ // against a device whose Radar server was gone, and the Reconnect Radar button -- which renders
709
+ // only while NOT connected -- never appeared, leaving no way to re-arm from the dashboard.
710
+ // Frames still reach the cache and the feed below either way; this only governs what the
711
+ // connection state is allowed to claim.
712
+ if (DEVICE_STREAM_KINDS.includes(f.type)) {
713
+ this._lastEventTs = this.connClock();
714
+ // A frame from the device IS an observation of it, so it is where a busy device earns the
715
+ // evidence that lets a recovery end an outage.
716
+ this.noteDeviceProof();
717
+ // A live frame proves the stream healed itself (the browser EventSource auto-reconnects on a
718
+ // transient blip). Clear _dropped here so recovered() does NOT later tear down this healthy
719
+ // stream and re-open it: recovered() should only fire when the stream did NOT self-heal.
720
+ this._dropped = false;
721
+ this.setConn("connected", "");
722
+ }
489
723
  const ev = f.event || {};
490
724
  ev._type = f.type;
491
725
  const isNew = this.cacheFrame(f.type, ev);
@@ -652,8 +886,9 @@ class Store {
652
886
  if (this._rafPending)
653
887
  return;
654
888
  this._rafPending = true;
655
- requestAnimationFrame(() => {
889
+ this._rafHandle = requestAnimationFrame(() => {
656
890
  this._rafPending = false;
891
+ this._rafHandle = null;
657
892
  this.feedVersion++;
658
893
  this.emit("feed", this.feedVersion);
659
894
  });
@@ -744,11 +979,20 @@ class Store {
744
979
  checkSerialEdge(serial) {
745
980
  if (serial == null || serial === this._lastSerial)
746
981
  return;
747
- // Feed clear + stream resync only on a REAL switch (serial -> other serial): a null->serial
748
- // FIRST pin has no stale feed to drop, it just records the baseline.
982
+ // Feed clear + stream resync + reason retirement only on a REAL switch (serial -> other
983
+ // serial): a null->serial FIRST pin has no stale feed to drop, it just records the baseline.
984
+ // The reason survives the first pin because a failing press is itself what produces a pin.
985
+ // Presses also cover their own re-pins: the /enable reply echoes the pinned serial and
986
+ // reconnect() advances the baseline through this method BEFORE writing the reason, so the
987
+ // clear below can only retire a reason that predates the edge -- one describing the
988
+ // previously bound device -- never the answer a press is about to put on screen.
749
989
  if (this._lastSerial !== null) {
750
990
  this.clearDeviceCaches();
751
991
  this.resyncStream();
992
+ // A reconnect reason is about the device that was bound when it was produced, so a change of
993
+ // bound device retires it. Without this, device A's "no debug build is running" explains
994
+ // device B's outage, because the epoch counts outages and a switch is not one.
995
+ this.clearEnableError();
752
996
  }
753
997
  this._lastSerial = serial;
754
998
  // The DB tab, unlike the feed, DOES carry stale state across a first pin: it loaded unpinned
@@ -778,9 +1022,13 @@ class Store {
778
1022
  this.emit("sources", names);
779
1023
  }
780
1024
  async pollHealth() {
781
- if (Date.now() - this._lastEventTs < 6000) {
1025
+ if (this.connClock() - this._lastEventTs < 6000) {
782
1026
  this._healthMisses = 0;
783
1027
  this.recovered();
1028
+ // Deliberately does NOT count connection proof. This path re-reads the SAME _lastEventTs every
1029
+ // 2s, so a single frame would otherwise bank both proofs and end an outage on evidence that
1030
+ // never repeated. The frame that set _lastEventTs already counted itself, in onFrame, which is
1031
+ // what keeps a busy device able to confirm a recovery.
784
1032
  this.setConn("connected", "");
785
1033
  return;
786
1034
  }
@@ -798,6 +1046,9 @@ class Store {
798
1046
  this.updateSources(Array.isArray(h.sources) ? h.sources : null);
799
1047
  this._healthMisses = 0;
800
1048
  this.recovered();
1049
+ // A real device:true reply is the other genuine observation, and the one a QUIET device
1050
+ // recovers on.
1051
+ this.noteDeviceProof();
801
1052
  this.setConn("connected", "");
802
1053
  }
803
1054
  else if (++this._healthMisses >= 2) {
@@ -880,34 +1131,85 @@ class Store {
880
1131
  /* transient; next poll retries */
881
1132
  }
882
1133
  }
1134
+ // Read an /enable reply into "did Radar arm, and if not, why". The STATUS CODE cannot be the
1135
+ // test: only an ambiguous device is a 409, while every other failure the route reports -- a dead
1136
+ // adb forward, a broadcast adb refused, a broadcast that landed on a device whose server never
1137
+ // answered the ping -- arrives as a 200 whose body says enabled:false and carries the reason. So
1138
+ // the body is the test. Anything that is not an explicit enabled:true counts as not armed,
1139
+ // because the one thing worse than a vague reason is a UI reporting success on an enable that
1140
+ // did nothing.
1141
+ //
1142
+ // A reply that will not PARSE is a third case, and it must not be worded like the second. Not
1143
+ // being able to read the answer says nothing about the device, so it does not get to blame one.
1144
+ // That is the repo's stated convention, in CLAUDE.md under the inconclusive-probe section: "A
1145
+ // probe that cannot always tell must say so in its return type. Never collapse 'could not tell'
1146
+ // into 'no'." So this reports the read failure, and the caller's device-blaming fallback is
1147
+ // reserved for a reply that parsed and simply carried no reason of its own.
1148
+ async readEnableResult(r, fallback) {
1149
+ const body = (await r.json().catch(() => null));
1150
+ if (body === null) {
1151
+ return {
1152
+ enabled: false,
1153
+ error: "Could not read the dashboard reply to this request. Try again.",
1154
+ serial: null,
1155
+ };
1156
+ }
1157
+ const error = typeof body.error === "string" && body.error ? body.error : fallback;
1158
+ const serial = typeof body.device_serial === "string" && body.device_serial ? body.device_serial : null;
1159
+ return { enabled: body.enabled === true, error, serial };
1160
+ }
883
1161
  // Pin a specific device for the session. POSTs the same /enable the reconnect button uses,
884
1162
  // with the chosen serial; on success it runs the same post-enable refresh as reconnect() so
885
1163
  // the UI does not wait for the next poll. On a REAL switch (target serial differs from the one
886
1164
  // last seen) it clears the old device's caches and resyncs HERE, deterministically, rather than
887
1165
  // leaning on pollHealth's serial edge: that edge is starved by the <6s fresh-frame fast path
888
1166
  // while the new stream is already delivering frames, so it may never fire. Same-serial reselect
889
- // skips the clear (nothing stale). A 409/error is surfaced on deviceError (the device chip shows
890
- // it) rather than via conn, which a healthy health poll would overwrite within 2s; the device
891
- // list is refreshed so the dropdown is current and the user can pick a valid device.
1167
+ // skips the clear (nothing stale). A failed pick is surfaced on deviceError (the device chip
1168
+ // shows it) rather than via conn, which a healthy health poll would overwrite within 2s; the
1169
+ // device list is refreshed so the dropdown is current and the user can pick a valid device.
892
1170
  async selectDevice(serial) {
893
1171
  try {
894
1172
  const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
895
- if (!r.ok && r.status === 409) {
896
- const body = await r.json().catch(() => null);
1173
+ // Any reply that did not arm the device takes the failure path, not just the 409. A 200 whose
1174
+ // body says enabled:false used to fall through here as a success: it cleared deviceError,
1175
+ // recorded the serial as switched-to, and resynced a stream against a device holding no
1176
+ // Radar server, so a pick that plainly failed rendered as a pick that worked.
1177
+ const { enabled, error, serial: confirmed } = await this.readEnableResult(r, "Selecting that device did not arm Radar on it.");
1178
+ if (!enabled) {
897
1179
  // Surface the failure on the device chip itself, not via conn: a healthy pollHealth flips
898
1180
  // conn back to connected within 2s and would erase a setConn("waiting", …) message before
899
1181
  // the user reads it. deviceError is owned here and survives the health poll.
900
- this.deviceError = (body && body.error) ? String(body.error) : "device select failed";
1182
+ //
1183
+ // _lastSerial is deliberately NOT advanced HERE, and the two halves of that split matter.
1184
+ // The route pins the device before it forwards or broadcasts, so a failed enable divides in
1185
+ // two: if the pin never landed, nothing switched and a later successful pick of the same
1186
+ // serial must still count as a switch and clear the old device's caches. If the pin DID land
1187
+ // and only the arming failed, the fetchDevices() below reads the server's pinned serial and
1188
+ // checkSerialEdge advances the baseline and clears the caches from there. So the baseline
1189
+ // tracks what the SERVER confirmed, never what this click hoped for.
1190
+ //
1191
+ // The pick is the user's LATEST action, so its answer wins the header: retire any standing
1192
+ // reconnect reason, or the chip suppression in the header would hide this click's feedback
1193
+ // behind the older message.
1194
+ this.clearEnableError();
1195
+ this.deviceError = error;
901
1196
  this.emit("devices", this.devices);
902
1197
  this.fetchDevices();
903
1198
  return;
904
1199
  }
905
- // A successful pick clears any prior select failure.
1200
+ // A successful pick clears any prior enable failure.
906
1201
  this.deviceError = null;
907
1202
  this.emit("devices", this.devices);
908
- if (serial !== this._lastSerial) {
1203
+ // The pick ARMED the device, which refutes any standing reconnect reason whatever the serial
1204
+ // did -- the same rule as a successful reconnect. Cleared here, inline, because advancing the
1205
+ // baseline below means checkSerialEdge sees no change and can never fire for this switch.
1206
+ this.clearEnableError();
1207
+ // The baseline tracks what the SERVER confirmed: the reply echo when present, the requested
1208
+ // serial only as the fallback for a reply without one. Same policy as reconnect's advance.
1209
+ const bound = confirmed ?? serial;
1210
+ if (bound !== this._lastSerial) {
909
1211
  this.clearDeviceCaches();
910
- this._lastSerial = serial;
1212
+ this._lastSerial = bound;
911
1213
  // Resync the DB tab too: a first pick (null->serial) leaves it holding the failed
912
1214
  // ambiguous /dbs; a real switch leaves it on the old device's databases.
913
1215
  this.bumpDbSerial();
@@ -941,25 +1243,65 @@ class Store {
941
1243
  this.openStream();
942
1244
  this.backfill();
943
1245
  }
1246
+ // The Reconnect Radar button. Re-arms the device through the same /enable the picker uses, and
1247
+ // reports what came back: the route already words every failure it can hit, down to naming a
1248
+ // missing debug build, and a user who just pressed a button is owed that answer instead of a
1249
+ // dashboard that keeps saying "waiting for device…" whether the press worked or not.
944
1250
  async reconnect() {
1251
+ // Read the epoch BEFORE the request, because the reply describes the outage the user pressed
1252
+ // during, not whatever is true when it lands. The failure path is slow (rebuild the forward,
1253
+ // broadcast, a ping with its own multi-second ceiling, then a process probe), which is easily long
1254
+ // enough for a boundary to pass, and stamping the later epoch would file this reason against an
1255
+ // outage it says nothing about.
1256
+ const epoch = this._outageEpoch;
1257
+ // Whether THIS press's reply advance performed the real-switch resync. Captured at the
1258
+ // advance itself, not before the fetch: a poll can observe an unrelated switch during the
1259
+ // multi-second /enable flight, and deciding from a pre-fetch baseline would count that
1260
+ // poll's resync as this press's and skip a resync nobody performed for it. Same
1261
+ // before-and-after-an-await hazard the epoch capture above avoids.
1262
+ let replySwitched = false;
945
1263
  try {
946
1264
  const r = await fetch("/enable", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
947
- // 409 = ambiguous device (multiple attached, none picked). Surface the server's
948
- // reason through the existing connection-status line so the user sees why enable
949
- // did not connect, instead of a silent stall on "reconnecting…".
950
- if (!r.ok && r.status === 409) {
951
- const body = await r.json().catch(() => null);
952
- if (body && body.error)
953
- this.setConn("waiting", String(body.error));
1265
+ const { enabled, error, serial } = await this.readEnableResult(r, "Reconnect failed. Is a device attached with a debug build of the Slack app running?");
1266
+ // The reply names the device this press pinned, and the route pins before it arms, so a
1267
+ // failing press can itself move the pin (first sight, or a switch to freshly attached
1268
+ // hardware). Advance the baseline from the reply BEFORE the reason is written: the later
1269
+ // poll then observes no edge, so it cannot retire the very reason this reply carries. A
1270
+ // real switch still gets the full retirement of the OLD device's state via checkSerialEdge.
1271
+ const beforeAdvance = this._lastSerial;
1272
+ if (serial !== null)
1273
+ this.checkSerialEdge(serial);
1274
+ replySwitched = serial !== null && beforeAdvance !== null && serial !== beforeAdvance;
1275
+ if (enabled) {
1276
+ this.clearEnableError();
1277
+ }
1278
+ else {
1279
+ // Its own field, not conn.msg: pollHealth runs every 2s and its own "device offline"
1280
+ // message would erase the specific reason within seconds of the press that asked for it.
1281
+ //
1282
+ // Stamped with the outage it belongs to, and stored even if the dashboard has since gone
1283
+ // connected: a reply saying "adb: device offline" is not refuted by a 6-second-old stream
1284
+ // frame that arrived while this request was in flight, so it is kept rather than thrown
1285
+ // away. The epoch stamp is what stops it being shown for some later outage instead.
1286
+ this.enableError = error;
1287
+ this._enableErrorEpoch = epoch;
1288
+ this.emit("enable-error", this.visibleEnableError);
954
1289
  }
955
1290
  }
956
1291
  catch {
957
- /* ignore */
1292
+ // The dashboard's own port is unreachable, so this press produced no answer about the device.
1293
+ // conn reports the dashboard being unreachable, but the reason line is a separate field and
1294
+ // would otherwise keep showing the PREVIOUS press's answer, presenting it as this press's, and
1295
+ // blaming the device for a request that never reached it.
1296
+ this.clearEnableError();
958
1297
  }
959
1298
  this.pollHealth();
960
1299
  this.pollProfile();
961
1300
  this.pollSpec();
962
- this.resyncStream();
1301
+ // checkSerialEdge already resynced the stream if THIS press's reply advanced the baseline
1302
+ // across a real switch; a second open/close/open here would only churn the backfill.
1303
+ if (!replySwitched)
1304
+ this.resyncStream();
963
1305
  }
964
1306
  // Kill the dashboard server from the header button. The X-Radar-Dashboard header is the
965
1307
  // CSRF guard the /shutdown route requires (a foreign origin's fetch cannot set it without a