@slack/radar-mcp 1.18.1 → 1.20.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.
@@ -1,4 +1,4 @@
1
- import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource } from "./registry.js";
1
+ import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource, levelRank, FIELD_VALUES } 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
@@ -16,6 +16,22 @@ const CAPTURE_CONCURRENCY = 3; // max parallel background /detail fetches
16
16
  const CAP_SEEN_CAP = 4000; // bound on the dedup set for eager capture
17
17
  const POLL_SPEC_MS = 700;
18
18
  const POLL_HEALTH_MS = 2000;
19
+ // Auto-re-arm pacing (see maybeAutoRearm): one attempt per minute at most, and after three
20
+ // failed broadcasts in one outage the human owns the next press. An /enable flight is
21
+ // multi-second (forward rebuild + broadcast + ping), so a tighter floor would mostly find
22
+ // the in-flight latch still held and burn attempts against it.
23
+ const AUTO_REARM_SPACING_MS = 60_000;
24
+ export const AUTO_REARM_MAX_FAILS = 3;
25
+ // The human's "stop re-enabling" choice, persisted alongside the theme and setup-hint keys.
26
+ const AUTO_REARM_OFF_KEY = "radar-auto-rearm-off";
27
+ function readAutoRearmSuppressed() {
28
+ try {
29
+ return localStorage.getItem(AUTO_REARM_OFF_KEY) === "1";
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
19
35
  const POLL_PROFILE_MS = 5000;
20
36
  const GRAPH_N = 60;
21
37
  const PERSEC_N = 30;
@@ -80,16 +96,54 @@ function canonicalSpecKey(spec) {
80
96
  const cleaned = { ...spec };
81
97
  delete cleaned.title;
82
98
  delete cleaned.summary;
99
+ // A level floor is a way of looking at the same tab, not a different tab: the Logs button
100
+ // stays lit at "level ≥ WARN". `match.package` is deliberately still part of the key, so the app
101
+ // selector next to it does move you off the preset; the two controls are not meant to agree.
102
+ delete cleaned.minLevel;
83
103
  if (Array.isArray(cleaned.viz))
84
104
  cleaned.viz = cleaned.viz.filter((x) => x !== "counter");
85
105
  return JSON.stringify(norm(cleaned));
86
106
  }
107
+ // The spec a PRESET tab pushes. The level floor follows the person between the two tabs that
108
+ // have log rows, and waits out a visit to any other tab (`remembered` is the store's last level
109
+ // on a log-carrying tab), the way the text filter survives every tab switch. It never overrides
110
+ // a level the target already carries, so an agent-authored view keeps its own; the Custom button
111
+ // does not come through here at all.
112
+ export function specForTab(next, current, remembered = "") {
113
+ const logish = (s) => s === "log" || s === "all";
114
+ if (!logish(next.source) || next.minLevel !== undefined)
115
+ return next;
116
+ const min = current && logish(current.source)
117
+ ? (typeof current.minLevel === "string" ? current.minLevel : "")
118
+ : remembered;
119
+ return min ? { ...next, minLevel: min } : next;
120
+ }
87
121
  export function specMatchesMode(spec) {
88
122
  if (!spec || spec.blank)
89
123
  return null;
90
124
  const key = canonicalSpecKey(spec);
91
125
  return MODES.find((m) => canonicalSpecKey(m.spec) === key)?.key ?? null;
92
126
  }
127
+ /**
128
+ * This page's presence id, taken from the URL when whoever opened the page supplied one.
129
+ *
130
+ * The dock app supplies one. It has to know this page's id before the page exists, because the
131
+ * question it asks the server is "is anyone other than my own window using this dashboard", and a page
132
+ * that mints its own id in here leaves the app no way to name it. A plain browser tab arrives with no
133
+ * parameter and mints its own, exactly as every tab did before.
134
+ *
135
+ * `presence`, not `tab`, because the dashboard's own tabs (Live, Network, Clogs) are the other thing
136
+ * `?tab=` would read as, and this is not one of those.
137
+ *
138
+ * Exported so a test can drive the URL branch without a browser.
139
+ */
140
+ export function pageTabId(search) {
141
+ const query = search ?? (typeof location !== "undefined" ? location.search : "");
142
+ const supplied = new URLSearchParams(query).get("presence");
143
+ if (supplied)
144
+ return supplied;
145
+ return typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2);
146
+ }
93
147
  class Store {
94
148
  spec = { blank: true, viz: [] };
95
149
  conn = { state: "waiting", msg: "connecting…" };
@@ -122,6 +176,8 @@ class Store {
122
176
  // is invalidated by one thing only, a later pick that works, and nothing about device health
123
177
  // refutes it. It therefore renders whether or not the dashboard is connected.
124
178
  deviceError = null;
179
+ // Same flag for the pick error (see enableInstructs).
180
+ deviceErrorInstructs = false;
125
181
  // Why the last Reconnect press did not arm the device, or null when it did. Owned by reconnect().
126
182
  //
127
183
  // KEPT SEPARATE FROM deviceError on purpose: a pick failure is about a device the user named,
@@ -149,7 +205,164 @@ class Store {
149
205
  // the /enable reply echoes the pinned serial, and reconnect() advances the baseline from the
150
206
  // reply before the reason is written, so the follow-up poll observes no edge.
151
207
  enableError = null;
208
+ // Whether enableError's wording tells the user what to do (the reply's own `instructs` flag,
209
+ // set where the wording is written). The header reads this instead of guessing from the prose.
210
+ enableInstructs = false;
152
211
  _enableErrorEpoch = -1;
212
+ // The stream proxy diagnosed the current outage as "the device-side radar session ENDED"
213
+ // (idle watchdog, app restart): the proxy's own retries can never fix that — only a
214
+ // re-enable can — so this flag is what authorizes the auto-re-arm below. Set from a _status
215
+ // frame carrying reason "no_session"; cleared by an OBSERVED connected report — a device
216
+ // frame, the proxy's own connect, a device:true health reply, or an /enable that came back
217
+ // armed — and specifically NOT by pollHealth's fresh-frame fast path, which re-reads
218
+ // pre-outage evidence (see setConn's `observed` parameter). Deliberately NOT epoch-stamped
219
+ // like enableError: staleness is
220
+ // handled at the SOURCE — the server discards a diagnosis that resolves after its stream
221
+ // reconnected — and the guards in maybeAutoRearm (spacing, cap, in-flight latch) bound
222
+ // whatever slips through. It also DRIVES the header wording: while latched, the conn span
223
+ // renders the session-ended state instead of conn.msg, because pollHealth's generic
224
+ // "device offline, retrying…" overwrites the msg within one 2s tick and is factually wrong
225
+ // for this outage mode (the device is fine; the session inside the app ended).
226
+ sessionEnded = false;
227
+ // True while ANY /enable flight is in progress — manual press or auto-re-arm — set by
228
+ // reconnect() itself so one latch covers both initiators. Emitted as "enabling"; the
229
+ // header's button disables and relabels off it.
230
+ enabling = false;
231
+ // True specifically while an AUTO attempt is in flight (a subset of `enabling`), so the
232
+ // header can word the state as the machine acting rather than answering a press. Emitted
233
+ // as "auto-rearm".
234
+ autoRearming = false;
235
+ // When the last automatic attempt was made. NOT reset by a recovery: the spacing window spans
236
+ // outages, so a session that dies again right after an arm waits out the window instead of
237
+ // getting a free immediate attempt every cycle (see noteNoSession).
238
+ _autoRearmLastTs = 0;
239
+ _autoRearmFails = 0;
240
+ // When the last outage ended (an observed connected report, or an /enable that came back
241
+ // armed). Whether that recovery HELD decides the next outage's budget: held for a full spacing
242
+ // window, the next outage starts fresh; died inside it, the next outage is a flap and the drop
243
+ // counts as a failed attempt. null until the first recovery.
244
+ _recoveredAt = null;
245
+ // The latch was dropped by an "undiagnosed" frame rather than by a recovery. A retire is a
246
+ // pause, not an outage boundary: nothing came back in between, so when no_session returns there
247
+ // is nothing to judge and the count and the clock carry over (see noteNoSession).
248
+ _latchRetired = false;
249
+ // Set when the current exhausted state was reached through drops (a session that died again
250
+ // inside the spacing window of coming back) rather than three real failed attempts, so the
251
+ // header can say what actually happened instead of "after 3 tries".
252
+ _autoRearmFlapped = false;
253
+ // Set when the budget was spent at once on a reply the server will repeat for every later
254
+ // unattended attempt (not by three real failures), so the header can say "gave up" without
255
+ // naming a count of attempts that were never made. Cleared with the rest of the outage state.
256
+ _autoRearmTerminal = false;
257
+ // Counts diagnosed outages, bumped when the no-session latch is SET. An attempt records the
258
+ // generation it started under so a verdict that lands after the latch was cleared AND re-set
259
+ // by a newer outage is not charged to the newer one: the boolean latch alone cannot tell the
260
+ // two apart.
261
+ _noSessionGen = 0;
262
+ get autoRearmFlapped() {
263
+ return this._autoRearmFlapped;
264
+ }
265
+ get autoRearmTerminal() {
266
+ return this._autoRearmTerminal;
267
+ }
268
+ // The human's off switch for the automation, set from the header's "stop" control. Without
269
+ // it, a user who explicitly DISABLED radar with a dashboard tab still visible had no way to
270
+ // make the tab stop re-arming the session it keeps diagnosing as ended (the socket table
271
+ // cannot tell "died mid-use" from "idled out after a deliberate disable"). PERSISTED per
272
+ // browser origin (see the key below) and never cleared by a recovery: it records the human's
273
+ // intent, not a fact about the outage. Emitted as "auto-rearm" (the header's recovery
274
+ // wording re-reads on that event).
275
+ autoRearmSuppressed = readAutoRearmSuppressed();
276
+ // Cross-tab: the choice is stored per browser origin, so a SIBLING tab already open must
277
+ // honour it too — otherwise the tab that pressed stop renders "off" while the tab next to it
278
+ // keeps arming the device, and the control's whole purpose (make the arming stop) fails.
279
+ // `storage` fires only in the OTHER tabs, which is exactly the gap the writer cannot cover.
280
+ watchSuppressionAcrossTabs() {
281
+ try {
282
+ window.addEventListener("storage", (e) => {
283
+ if (e.key !== null && e.key !== AUTO_REARM_OFF_KEY)
284
+ return;
285
+ const next = readAutoRearmSuppressed();
286
+ if (next === this.autoRearmSuppressed)
287
+ return;
288
+ this.autoRearmSuppressed = next;
289
+ // Another tab resuming is the same fresh intent as this tab's own control.
290
+ if (!next)
291
+ this.resetRearmBudget();
292
+ this.emit("auto-rearm", this.autoRearming);
293
+ if (!next)
294
+ void this.maybeAutoRearm();
295
+ });
296
+ }
297
+ catch {
298
+ /* no window (tests, SSR): the flag still holds for this instance */
299
+ }
300
+ }
301
+ // Start the automatic re-enable over: count, marks, the spacing clock and the recovery
302
+ // baseline. For a state that is about a different intent than the one that spent them: a
303
+ // change of bound device (device A's failures say nothing about device B) or the human
304
+ // turning the automation back on (a resume is a fresh intent, and someone who just switched
305
+ // it on expects it to try, not to read "gave up" for drops that happened while it was off).
306
+ // The clock goes too, or the first attempt after the change waits out a window that belongs
307
+ // to the old intent. Republishes so the header re-reads the give-up state.
308
+ resetRearmBudget() {
309
+ const wasExhausted = this.autoRearmExhausted;
310
+ this._autoRearmFails = 0;
311
+ this._autoRearmTerminal = false;
312
+ this._autoRearmFlapped = false;
313
+ this._recoveredAt = null;
314
+ this._latchRetired = false;
315
+ this._autoRearmLastTs = 0;
316
+ if (wasExhausted)
317
+ this.emit("auto-rearm", this.autoRearming);
318
+ }
319
+ setAutoRearmSuppressed(v) {
320
+ if (this.autoRearmSuppressed === v)
321
+ return;
322
+ this.autoRearmSuppressed = v;
323
+ if (!v)
324
+ this.resetRearmBudget();
325
+ // Persisted like the theme and the setup-hint dismissal: a reload silently resuming
326
+ // automatic device arming would undo a decision the human made deliberately.
327
+ try {
328
+ if (v)
329
+ localStorage.setItem(AUTO_REARM_OFF_KEY, "1");
330
+ else
331
+ localStorage.removeItem(AUTO_REARM_OFF_KEY);
332
+ }
333
+ catch {
334
+ /* private mode: the choice lasts for this tab only */
335
+ }
336
+ this.emit("auto-rearm", this.autoRearming);
337
+ // A resume during a diagnosed outage tries now, not on the next poll tick.
338
+ if (!v)
339
+ void this.maybeAutoRearm();
340
+ }
341
+ // Set from /health's self_arm_blocked: this dashboard PROCESS may not touch the device on
342
+ // its own. Two reasons today, both server-side facts: an agent spawned it (the premise
343
+ // open_radar_dashboard's MCP-gate exemption rests on), or SLACK_RADAR_NO_ARM is set (the
344
+ // documented opt-out for device-touching behaviour, which suppressed the boot arm and must
345
+ // suppress this too). The header words a blocked tab as "Press Reconnect" (or, beside a
346
+ // reason on screen that itself instructs — see reasonInstructs in app.ts — "Auto re-enable
347
+ // is unavailable on this tab").
348
+ // Tri-state: null until a /health reply answers with an explicit boolean. A no_session frame
349
+ // can beat that reply on a fresh tab (the stream diagnoses in ~2s while /health waits on a
350
+ // device ping), and the automatic re-enable must not act on a default — so it requires an
351
+ // answered false, never the absence of a true. The header reads null as unanswered: it
352
+ // renders "Checking whether this tab may re-enable…" (unless the human's persisted stop is
353
+ // set, which outranks the unanswered question and renders its own wording) and hides the
354
+ // automation controls, so
355
+ // it neither promises a retry the store would refuse nor issues an instruction the answer
356
+ // may withdraw.
357
+ selfArmBlocked = null;
358
+ // The give-up state: this outage spent its automatic budget, the next press is the human's.
359
+ // Derived so the header can render it; flips back when a connected report resets the count.
360
+ get autoRearmExhausted() {
361
+ return this._autoRearmFails >= AUTO_REARM_MAX_FAILS;
362
+ }
363
+ // The auto-re-arm clock, injectable for the same reason as connClock: tests exercise the
364
+ // spacing floor by moving time, never by disabling the floor.
365
+ rearmClock = () => Date.now();
153
366
  // Counts outages: bumped by setConn when the connection leaves a CONFIRMED connected state.
154
367
  _outageEpoch = 0;
155
368
  // Pieces of positive evidence that the current connected state is real, at most one per
@@ -170,9 +383,19 @@ class Store {
170
383
  connClock = () => Date.now();
171
384
  // The reconnect reason the header may actually show: only while disconnected, and only for the
172
385
  // outage that produced it. Both conditions in one place so the component cannot get it half right.
386
+ // The instructs flag of the wording visibleEnableError shows, and false whenever it shows none:
387
+ // the flag is never readable apart from the wording it qualifies.
388
+ get visibleEnableInstructs() {
389
+ return this.visibleEnableError === null ? false : this.enableInstructs;
390
+ }
173
391
  get visibleEnableError() {
174
392
  if (this.conn.state === "connected")
175
393
  return null;
394
+ // A flight in progress supersedes the previous attempt's answer: rendering "Reconnect
395
+ // failed…" beside a button that simultaneously says "enabling…" is two contradictory
396
+ // messages about one flow. The reason returns (or is replaced) when the flight lands.
397
+ if (this.enabling)
398
+ return null;
176
399
  return this._enableErrorEpoch === this._outageEpoch ? this.enableError : null;
177
400
  }
178
401
  // Drop the reason outright. Used where the reason is not merely from another outage but describes a
@@ -182,6 +405,7 @@ class Store {
182
405
  if (this.enableError === null && this._enableErrorEpoch === -1)
183
406
  return;
184
407
  this.enableError = null;
408
+ this.enableInstructs = false;
185
409
  this._enableErrorEpoch = -1;
186
410
  this.emit("enable-error", this.visibleEnableError);
187
411
  }
@@ -214,6 +438,10 @@ class Store {
214
438
  dbSerialVersion = 0;
215
439
  customActive = false;
216
440
  lastCustomSpec = null;
441
+ // The level floor last seen on a log-carrying tab ("" when none), so a trip through Network
442
+ // and back to Logs lands on the same level. Read by specForTab. Any log-carrying spec counts,
443
+ // an agent-authored one included: a log view Claude pushes with no level is the last level seen.
444
+ lastLogLevel = "";
217
445
  detailCache = new Map();
218
446
  _capSeen = new Set();
219
447
  _capQueue = [];
@@ -244,13 +472,31 @@ class Store {
244
472
  // and reads as a genuine new frame to a paused/frozen feed subscriber.
245
473
  _rafHandle = null;
246
474
  _intervals = [];
247
- // Per-tab presence id, generated once when this Store is constructed. Rides pollProfile's 5s
475
+ // Per-tab presence id, settled once when this Store is constructed. Rides pollProfile's 5s
248
476
  // /health fetch (below) so the server can tell how many tabs are live and auto-close when the
249
- // last one is gone. In-memory only, never persisted: a page reload naturally gets a fresh id,
250
- // which is fine — the old id ages out of the server's presence map. Rides pollProfile, NOT
251
- // pollHealth: pollHealth early-returns without fetching while a stream is busy (<6s since the
252
- // last event), so a user actively watching a chatty stream would send zero presence signals.
253
- _tabId = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2);
477
+ // last one is gone. In-memory only, never persisted. A reload of a page the dock app opened keeps
478
+ // the same id, because it comes from the URL; a reload of a plain browser tab gets a fresh one and
479
+ // the old id ages out of the server's presence map, which is what always happened. Rides
480
+ // pollProfile, NOT pollHealth: pollHealth early-returns without fetching while a stream is busy
481
+ // (<6s since the last event), so a user actively watching a chatty stream would send zero presence
482
+ // signals.
483
+ _tabId = pageTabId();
484
+ /**
485
+ * The headers an authored write carries: the proof the server's gate wants, plus which tab is
486
+ * writing.
487
+ *
488
+ * The pair has to travel together, and a method rather than four header literals is how that stays
489
+ * true. An authored write that proves it came from a dashboard but not WHICH one is credited to an
490
+ * agent session (see the server's creditAuthoredWrite), and a session claim is the one thing the
491
+ * dock app never overrides: it would refuse to replace a stale dashboard, and refuse to stop its own
492
+ * server on quit, because this window changed a filter.
493
+ *
494
+ * Sent on the writes the server CREDITS, which is /setspec and /enable. A db query or a screen
495
+ * consent buys no keep-alive, so it needs no identity.
496
+ */
497
+ authoredHeaders(extra = {}) {
498
+ return { "X-Radar-Dashboard": "1", "X-Radar-Tab": this._tabId, ...extra };
499
+ }
254
500
  // ---- shared detail cache (bounded FIFO) ----
255
501
  cacheDetail(kind, id, detail) {
256
502
  const key = kind + ":" + id;
@@ -329,6 +575,7 @@ class Store {
329
575
  // them). Deliberately NOT reset: subscribers, live timers and stream handles (start() and
330
576
  // openStream() own those lifecycles), and _tabId, which identifies the page for its whole life.
331
577
  _resetForTest() {
578
+ this.lastLogLevel = "";
332
579
  this.spec = { blank: true, viz: [] };
333
580
  this.conn = { state: "waiting", msg: "connecting…" };
334
581
  this.selfHeal = null;
@@ -341,8 +588,23 @@ class Store {
341
588
  this.selectedDevice = null;
342
589
  this.devicesError = false;
343
590
  this.deviceError = null;
591
+ this.deviceErrorInstructs = false;
344
592
  this.enableError = null;
593
+ this.enableInstructs = false;
345
594
  this._enableErrorEpoch = -1;
595
+ this.sessionEnded = false;
596
+ this.enabling = false;
597
+ this.autoRearming = false;
598
+ this.autoRearmSuppressed = false;
599
+ this.selfArmBlocked = null;
600
+ this._autoRearmLastTs = 0;
601
+ this._autoRearmFails = 0;
602
+ this._autoRearmTerminal = false;
603
+ this._recoveredAt = null;
604
+ this._latchRetired = false;
605
+ this._autoRearmFlapped = false;
606
+ this._noSessionGen = 0;
607
+ this.rearmClock = () => Date.now();
346
608
  this._outageEpoch = 0;
347
609
  this._connProof = 0;
348
610
  this._lastProofTs = 0;
@@ -489,6 +751,7 @@ class Store {
489
751
  // local default bootDefault had just set and stranding the page on the blank placeholder
490
752
  // until the next 700ms tick happened to read the corrected value.
491
753
  await this.bootDefault();
754
+ this.watchSuppressionAcrossTabs();
492
755
  this.fetchSelfHeal();
493
756
  this.fetchSetupHint();
494
757
  this.pollSpec();
@@ -536,7 +799,21 @@ class Store {
536
799
  this._connProof++;
537
800
  this._lastProofTs = now;
538
801
  }
539
- setConn(state, msg) {
802
+ setConn(state, msg, observed = false) {
803
+ // An OBSERVED connected report refutes "no radar session" directly (a dead session
804
+ // serves no stream), so it retires the auto-re-arm authorization, its failure count, and
805
+ // its spacing clock together — the NEXT diagnosed outage deserves the same immediate
806
+ // first attempt this one got. `observed` means the report traces to a real observation
807
+ // (a device frame, the stream proxy's own connect, a device:true health reply) — and NOT
808
+ // pollHealth's fresh-frame fast path, which re-reads the same pre-outage _lastEventTs
809
+ // every tick for up to 6s and would otherwise clear the latch, budget, and spacing with
810
+ // evidence that predates the outage (the same exclusion noteDeviceProof already makes).
811
+ // Judged on the state as REPORTED, before the multi-device override below rewrites it:
812
+ // the ambiguity is about which device to pin, not about whether a session is serving
813
+ // frames, and letting the override eat the refutation would leave the header claiming
814
+ // "no radar session" about a session that just spoke.
815
+ if (state === "connected" && observed)
816
+ this.refuteSessionEnded();
540
817
  // Unpinned multi-device is never "connected": frames can ride a stale forward from a prior
541
818
  // pin and flip the dot green while the per-device surfaces (DB run-as) are broken by the
542
819
  // ambiguity. Override any connected claim to a waiting "pick one" until a device is pinned.
@@ -613,7 +890,7 @@ class Store {
613
890
  // before its own first pollSpec() runs, so that later read confirms the same spec
614
891
  // rather than racing this one and overwriting it back to blank.
615
892
  this.applySpec(MODES[0].spec);
616
- await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json", "X-Radar-Dashboard": "1" }, body: JSON.stringify(MODES[0].spec) }).catch(() => { });
893
+ await fetch("/setspec", { method: "POST", headers: this.authoredHeaders({ "Content-Type": "application/json" }), body: JSON.stringify(MODES[0].spec) }).catch(() => { });
617
894
  }
618
895
  }
619
896
  catch {
@@ -659,8 +936,9 @@ class Store {
659
936
  this.markLocalPush(spec);
660
937
  try {
661
938
  // X-Radar-Dashboard marks this as an authored write (see the server's handleSetSpec): it is
662
- // what lets the write count as a keep-alive, and a foreign origin cannot forge it.
663
- return await (await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json", "X-Radar-Dashboard": "1" }, body: JSON.stringify(spec) })).json();
939
+ // what lets the write count as a keep-alive, and a foreign origin cannot forge it. X-Radar-Tab
940
+ // says the keep-alive is THIS window's rather than an agent session's.
941
+ return await (await fetch("/setspec", { method: "POST", headers: this.authoredHeaders({ "Content-Type": "application/json" }), body: JSON.stringify(spec) })).json();
664
942
  }
665
943
  catch {
666
944
  return { ok: false, error: "request failed" };
@@ -674,6 +952,9 @@ class Store {
674
952
  // backfill the device ring. Mirrors vanilla build(spec).
675
953
  applySpec(spec) {
676
954
  this.spec = spec || { blank: true, viz: [] };
955
+ if (this.spec.source === "log" || this.spec.source === "all") {
956
+ this.lastLogLevel = typeof this.spec.minLevel === "string" ? this.spec.minLevel : "";
957
+ }
677
958
  this.total = 0;
678
959
  this.liveMatches = 0;
679
960
  this.times = [];
@@ -726,8 +1007,26 @@ class Store {
726
1007
  return;
727
1008
  }
728
1009
  if (f.type === "_status") {
1010
+ // reason is typed as a plain string on purpose: the client acts on the known value and
1011
+ // treats every other value as a retraction (see src/shared/wire.ts StatusReason), so a
1012
+ // server that adds a reason later needs no client change.
729
1013
  const e = f.event;
730
- this.setConn(e.state, e.msg);
1014
+ // conn first, reason second: a reasoned frame is itself a waiting report, and
1015
+ // noteNoSession's immediate re-arm attempt reads conn.state — handled the other way
1016
+ // around, a diagnosis arriving right after a connected blip would see the stale
1017
+ // "connected" and skip the immediate attempt it exists for. observed=true: a connected
1018
+ // _status is the proxy vouching its upstream actually answered.
1019
+ this.setConn(e.state, e.msg, true);
1020
+ // The reason is the outage's CURRENT diagnosis (see src/shared/wire.ts StatusReason): only
1021
+ // no_session latches, and any other reason, today "undiagnosed" and whatever a later server
1022
+ // adds, retires the latch. Dispatching on the retraction token itself would leave the latch
1023
+ // stuck under the next new value, the exact defect the retire exists to fix.
1024
+ if (e.reason) {
1025
+ if (e.reason === "no_session")
1026
+ this.noteNoSession();
1027
+ else
1028
+ this.retireNoSession();
1029
+ }
731
1030
  return;
732
1031
  }
733
1032
  if (f.type === "_error") {
@@ -756,7 +1055,7 @@ class Store {
756
1055
  // transient blip). Clear _dropped here so recovered() does NOT later tear down this healthy
757
1056
  // stream and re-open it: recovered() should only fire when the stream did NOT self-heal.
758
1057
  this._dropped = false;
759
- this.setConn("connected", "");
1058
+ this.setConn("connected", "", true);
760
1059
  }
761
1060
  const ev = f.event || {};
762
1061
  ev._type = f.type;
@@ -823,9 +1122,8 @@ class Store {
823
1122
  }
824
1123
  }
825
1124
  candidates(field) {
826
- const fixed = { direction: ["OUTGOING", "INCOMING"], level: ["VERBOSE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"], method: ["GET", "POST", "PUT", "DELETE", "PATCH"] };
827
- if (fixed[field])
828
- return fixed[field].slice();
1125
+ if (FIELD_VALUES[field])
1126
+ return FIELD_VALUES[field].slice();
829
1127
  const seen = this.seen[field];
830
1128
  return seen ? [...seen].sort() : [];
831
1129
  }
@@ -988,6 +1286,12 @@ class Store {
988
1286
  this.selectedDevice === null);
989
1287
  }
990
1288
  matches(ev) {
1289
+ // The lowest priority to show. Only log rows carry one, so on the "all" timeline network,
1290
+ // rtm, clog and trace rows pass untouched, the same carve-out `package` gets below. A row whose
1291
+ // priority the order does not know ranks -1 and is hidden (see levelRank).
1292
+ const min = this.spec.minLevel;
1293
+ if (typeof min === "string" && min && ev._type === "log" && levelRank(ev.level) < levelRank(min))
1294
+ return false;
991
1295
  const m = this.spec.match;
992
1296
  if (!m)
993
1297
  return true;
@@ -1027,9 +1331,18 @@ class Store {
1027
1331
  if (this._lastSerial !== null) {
1028
1332
  this.clearDeviceCaches();
1029
1333
  this.resyncStream();
1334
+ // The re-arm budget is about the device that was bound when it was spent, so a change of
1335
+ // bound device starts it over: device A's two failed arms must not leave device B one drop
1336
+ // away from "gave up" before any attempt was made against it. The device_changed refusal
1337
+ // echoes the OLD pin, so it never moves this baseline; only an adopting press or a poll that
1338
+ // sees the new pin does.
1339
+ this.resetRearmBudget();
1030
1340
  // A reconnect reason is about the device that was bound when it was produced, so a change of
1031
1341
  // bound device retires it. Without this, device A's "no debug build is running" explains
1032
- // device B's outage, because the epoch counts outages and a switch is not one.
1342
+ // device B's outage, because the epoch counts outages and a switch is not one. The pick
1343
+ // error is deliberately NOT retired here: a failed pick the server did pin moves this
1344
+ // baseline through the device-list refresh AFTER the error was written, so the error is
1345
+ // about the device just pinned and must survive the edge it caused.
1033
1346
  this.clearEnableError();
1034
1347
  }
1035
1348
  this._lastSerial = serial;
@@ -1077,6 +1390,11 @@ class Store {
1077
1390
  this.emit("screen-caps", this.screenCaps);
1078
1391
  }
1079
1392
  async pollHealth() {
1393
+ // The auto-re-arm cadence rides this existing 2s tick instead of owning a timer: every
1394
+ // guard lives inside maybeAutoRearm, so this line is a no-op except mid-outage on a
1395
+ // diagnosed dead session. Fire-and-forget so a multi-second /enable flight cannot delay
1396
+ // the health read below.
1397
+ void this.maybeAutoRearm();
1080
1398
  if (this.connClock() - this._lastEventTs < 6000) {
1081
1399
  this._healthMisses = 0;
1082
1400
  this.recovered();
@@ -1098,21 +1416,22 @@ class Store {
1098
1416
  // instead by fetchDevices, which polls /_control/devices every 5s regardless of stream
1099
1417
  // activity. Between the two, both busy and quiet observer tabs converge within 5s.
1100
1418
  this.checkSerialEdge(h.device_serial ?? null);
1101
- if (h.device) {
1102
- // Only a healthy reply updates the source list: a device:false blip must not flip
1103
- // tabs off and back on recovery. The last list stands until the serial edge clears it.
1104
- this.updateSources(Array.isArray(h.sources) ? h.sources : null);
1105
- this._healthMisses = 0;
1106
- this.recovered();
1107
- // A real device:true reply is the other genuine observation, and the one a QUIET device
1108
- // recovers on.
1109
- this.noteDeviceProof();
1110
- this.setConn("connected", "");
1419
+ if (h.device === true) {
1420
+ this.onHealthDeviceUp(h.sources);
1111
1421
  }
1112
1422
  else if (++this._healthMisses >= 2) {
1113
1423
  this._dropped = true;
1114
1424
  this.setConn("waiting", "device offline, retrying…");
1115
1425
  }
1426
+ // Whether this dashboard process may arm the device on its own. Read on every health
1427
+ // reply rather than once at boot (pollProfile's reply feeds the same note, since this
1428
+ // fetch is skipped while the stream is busy), and the field starts null so the
1429
+ // automatic re-enable cannot act before a reply answers with an explicit boolean. AFTER
1430
+ // the device verdict above on purpose: an answered "may" fires the pending first attempt,
1431
+ // and a reply saying device:true has just refuted the no-session latch that attempt
1432
+ // would act on — the same reply must not arm a session it is confirming alive (the
1433
+ // deviceAlive argument is the belt to that ordering's braces).
1434
+ this.noteSelfArmBlocked(h.self_arm_blocked, h.device === true);
1116
1435
  }
1117
1436
  catch {
1118
1437
  if (++this._healthMisses >= 2) {
@@ -1121,6 +1440,42 @@ class Store {
1121
1440
  }
1122
1441
  }
1123
1442
  }
1443
+ // What a /health reply saying device:true means, for BOTH polls that fetch /health: only a
1444
+ // healthy reply updates the source list (a device:false blip must not flip tabs off and back
1445
+ // on recovery; the last list stands until the serial edge clears it), the miss counter resets,
1446
+ // a dropped stream is re-synced, and the reply counts as a genuine observation — the one a
1447
+ // QUIET device recovers on — which setConn's observed connected report turns into the end of
1448
+ // any diagnosed outage. Shared so pollHealth and pollProfile cannot treat the same evidence
1449
+ // differently.
1450
+ onHealthDeviceUp(sources) {
1451
+ this.updateSources(Array.isArray(sources) ? sources : null);
1452
+ this._healthMisses = 0;
1453
+ this.recovered();
1454
+ this.noteDeviceProof();
1455
+ this.setConn("connected", "", true);
1456
+ }
1457
+ // Record a /health reply's answer to "may this process arm the device on its own", from
1458
+ // whichever poll carried it. Only an explicit boolean counts as an answer: a reply without
1459
+ // the field (an older server) leaves the question open, because that server still takes the
1460
+ // destructive first-enable teardown and ignores ?auto=1, so a tab must not arm it unattended
1461
+ // either. Emitted on change so the header can stop promising a retry such a tab will never
1462
+ // make — and, once the answer is "may", the first attempt follows the answer right away
1463
+ // rather than waiting for the next poll tick. Unless the SAME reply reported the device up
1464
+ // (deviceAlive): both callers run onHealthDeviceUp on a device:true reply before calling
1465
+ // this, and its observed connected report retires the no-session latch, so there is no
1466
+ // outage left for the attempt to act on; the skip here is the belt to that ordering's
1467
+ // braces, and a session that really is dead re-diagnoses on the stream with a fresh
1468
+ // generation and its own immediate attempt.
1469
+ noteSelfArmBlocked(v, deviceAlive = false) {
1470
+ if (typeof v !== "boolean")
1471
+ return;
1472
+ if (this.selfArmBlocked === v)
1473
+ return;
1474
+ this.selfArmBlocked = v;
1475
+ this.emit("self-arm-blocked", this.selfArmBlocked);
1476
+ if (!v && !deviceAlive)
1477
+ void this.maybeAutoRearm();
1478
+ }
1124
1479
  // Called when health flips back to connected. If we were in a dropped state, the EventSource
1125
1480
  // did not survive the drop and the tab has been silent, so re-open the stream + backfill the
1126
1481
  // device ring ONCE on the recovery edge. The _dropped guard makes this fire on the transition,
@@ -1149,14 +1504,24 @@ class Store {
1149
1504
  ]);
1150
1505
  const uid = healthR && healthR.boundUserId;
1151
1506
  // pollHealth's fresh-frame fast path can skip its /health fetch indefinitely on a chatty
1152
- // stream; this 5s poll already fetched /health, so read the sources off it too.
1153
- if (healthR && healthR.device) {
1154
- this.updateSources(Array.isArray(healthR.sources) ? healthR.sources : null);
1155
- }
1507
+ // stream; this 5s poll already fetched /health, so a device:true here is handled by the SAME
1508
+ // helper pollHealth uses (sources, misses, recovery, proof, connected — and through the
1509
+ // observed connected report, the no-session latch). One helper, so the two /health consumers
1510
+ // cannot drift apart again: an earlier version only retired the latch here and left conn
1511
+ // waiting for a tick, and a version before that only refreshed the sources, which let the
1512
+ // consent answer below fire an attempt at a session this very reply had reported alive.
1513
+ if (healthR && healthR.device === true)
1514
+ this.onHealthDeviceUp(healthR.sources);
1156
1515
  // Same starvation backstop for the screen caps: this reply is the /health an open
1157
1516
  // overlay actually sees while the stream is chatty.
1158
1517
  if (healthR)
1159
1518
  this.updateScreenCaps(healthR.screen);
1519
+ // And for the consent answer: on a chatty stream this poll is the only /health reply the
1520
+ // tab sees, so without it the field sits at null (unanswered) until the first outage
1521
+ // releases pollHealth's fast path — the header would hide the automation's controls and
1522
+ // the first attempt would wait for a reply instead of firing on the diagnosis.
1523
+ if (healthR)
1524
+ this.noteSelfArmBlocked(healthR.self_arm_blocked, healthR.device === true);
1160
1525
  this.profiles = (profilesR && profilesR.profiles) || [];
1161
1526
  if (uid == null) {
1162
1527
  this.profileLabel = this._lastBoundLabel ? "last seen " + this._lastBoundLabel + " — reconnecting…" : "waiting for device…";
@@ -1203,9 +1568,9 @@ class Store {
1203
1568
  //
1204
1569
  // A reply that will not PARSE is a third case, and it must not be worded like the second. Not
1205
1570
  // being able to read the answer says nothing about the device, so it does not get to blame one.
1206
- // That is the repo's stated convention, in CLAUDE.md under the inconclusive-probe section: "A
1207
- // probe that cannot always tell must say so in its return type. Never collapse 'could not tell'
1208
- // into 'no'." So this reports the read failure, and the caller's device-blaming fallback is
1571
+ // A probe that cannot always tell says so in its return type, and "could not tell" never collapses
1572
+ // into "no"; every probe in RadarApp.swift follows the same rule. So this reports the read failure,
1573
+ // and the caller's device-blaming fallback is
1209
1574
  // reserved for a reply that parsed and simply carried no reason of its own.
1210
1575
  async readEnableResult(r, fallback) {
1211
1576
  const body = (await r.json().catch(() => null));
@@ -1213,12 +1578,23 @@ class Store {
1213
1578
  return {
1214
1579
  enabled: false,
1215
1580
  error: "Could not read the dashboard reply to this request. Try again.",
1581
+ // Client-authored wording, so the client knows it instructs.
1582
+ instructs: true,
1216
1583
  serial: null,
1584
+ refusal: null,
1217
1585
  };
1218
1586
  }
1219
1587
  const error = typeof body.error === "string" && body.error ? body.error : fallback;
1220
1588
  const serial = typeof body.device_serial === "string" && body.device_serial ? body.device_serial : null;
1221
- return { enabled: body.enabled === true, error, serial };
1589
+ // The route's marker for a refusal that no later unattended attempt can change (the process
1590
+ // may not self-arm; the hardware changed under the session). Absent on failures a retry
1591
+ // might still fix.
1592
+ const refusal = typeof body.refusal === "string" && body.refusal ? body.refusal : null;
1593
+ // Only a server wording can carry the server's flag; the `fallback` is the client's own and
1594
+ // does not instruct. An older server sends no flag, and absent reads as "does not instruct",
1595
+ // so the header's tail keeps its own imperative rather than dropping it on a guess.
1596
+ const instructs = typeof body.error === "string" && body.error ? body.instructs === true : false;
1597
+ return { enabled: body.enabled === true, error, instructs, serial, refusal };
1222
1598
  }
1223
1599
  // Pin a specific device for the session. POSTs the same /enable the reconnect button uses,
1224
1600
  // with the chosen serial; on success it runs the same post-enable refresh as reconnect() so
@@ -1231,12 +1607,12 @@ class Store {
1231
1607
  // device list is refreshed so the dropdown is current and the user can pick a valid device.
1232
1608
  async selectDevice(serial) {
1233
1609
  try {
1234
- const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
1610
+ const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST", headers: this.authoredHeaders() });
1235
1611
  // Any reply that did not arm the device takes the failure path, not just the 409. A 200 whose
1236
1612
  // body says enabled:false used to fall through here as a success: it cleared deviceError,
1237
1613
  // recorded the serial as switched-to, and resynced a stream against a device holding no
1238
1614
  // Radar server, so a pick that plainly failed rendered as a pick that worked.
1239
- const { enabled, error, serial: confirmed } = await this.readEnableResult(r, "Selecting that device did not arm Radar on it.");
1615
+ const { enabled, error, instructs, serial: confirmed } = await this.readEnableResult(r, "Selecting that device did not arm Radar on it.");
1240
1616
  if (!enabled) {
1241
1617
  // Surface the failure on the device chip itself, not via conn: a healthy pollHealth flips
1242
1618
  // conn back to connected within 2s and would erase a setConn("waiting", …) message before
@@ -1255,12 +1631,16 @@ class Store {
1255
1631
  // behind the older message.
1256
1632
  this.clearEnableError();
1257
1633
  this.deviceError = error;
1634
+ this.deviceErrorInstructs = instructs;
1635
+ this.emit("device-error", this.deviceError);
1258
1636
  this.emit("devices", this.devices);
1259
1637
  this.fetchDevices();
1260
1638
  return;
1261
1639
  }
1262
1640
  // A successful pick clears any prior enable failure.
1263
1641
  this.deviceError = null;
1642
+ this.deviceErrorInstructs = false;
1643
+ this.emit("device-error", null);
1264
1644
  this.emit("devices", this.devices);
1265
1645
  // The pick ARMED the device, which refutes any standing reconnect reason whatever the serial
1266
1646
  // did -- the same rule as a successful reconnect. Cleared here, inline, because advancing the
@@ -1305,26 +1685,233 @@ class Store {
1305
1685
  this.openStream();
1306
1686
  this.backfill();
1307
1687
  }
1308
- // The Reconnect Radar button. Re-arms the device through the same /enable the picker uses, and
1309
- // reports what came back: the route already words every failure it can hit, down to naming a
1310
- // missing debug build, and a user who just pressed a button is owed that answer instead of a
1311
- // dashboard that keeps saying "waiting for device…" whether the press worked or not.
1312
- async reconnect() {
1688
+ // A "no_session" diagnosis arrived on the stream (see the _status handler). Record it and
1689
+ // try to recover right away when the spacing clock allows: the clock starts at zero, so the
1690
+ // FIRST outage's first attempt is immediate and the tab heals in seconds, and a real
1691
+ // idle-timeout outage (minutes of healthy session since the last attempt) is immediate too.
1692
+ //
1693
+ // The budget is decided here, by whether the LAST recovery held. A session that died again
1694
+ // inside one spacing window of coming back is a flap (a crash-looping app, which is close to
1695
+ // the state someone with this dashboard open is often in): the drop counts as a failed
1696
+ // attempt and the spacing clock is not reset, so a flapping session is re-armed at most once
1697
+ // a minute and reaches "gave up" after three, instead of being resurrected every few seconds
1698
+ // forever with the give-up state unreachable because every cycle was a "new outage".
1699
+ noteNoSession() {
1700
+ if (!this.sessionEnded) {
1701
+ this.sessionEnded = true;
1702
+ const now = this.rearmClock();
1703
+ const wasExhausted = this.autoRearmExhausted;
1704
+ const resuming = this._latchRetired;
1705
+ if (resuming) {
1706
+ // Re-latching after a retire: the same outage resuming, nothing to judge, and the same
1707
+ // generation, so an attempt that was in flight across the retire still charges here.
1708
+ this._latchRetired = false;
1709
+ }
1710
+ else if (this._recoveredAt === null || now - this._recoveredAt >= AUTO_REARM_SPACING_MS) {
1711
+ this._autoRearmFails = 0;
1712
+ this._autoRearmTerminal = false;
1713
+ this._autoRearmFlapped = false;
1714
+ }
1715
+ else {
1716
+ this._autoRearmFails++;
1717
+ // A count-based judgement supersedes a marked refusal from the earlier outage.
1718
+ this._autoRearmTerminal = false;
1719
+ this._autoRearmFlapped = true;
1720
+ }
1721
+ if (!resuming)
1722
+ this._noSessionGen++;
1723
+ this.emit("session-ended", true);
1724
+ // The header re-reads the give-up state only on its own event; republish only when the
1725
+ // judgement above changed it, so the flight's own open/close edges stay the only emits of
1726
+ // an ordinary outage.
1727
+ if (this.autoRearmExhausted !== wasExhausted)
1728
+ this.emit("auto-rearm", this.autoRearming);
1729
+ }
1730
+ void this.maybeAutoRearm();
1731
+ }
1732
+ // The proxy re-probed and no longer finds the session absent: the socket is present after
1733
+ // all, or the table cannot be read because the device is gone. The outage changed nature
1734
+ // under the latched reason, so drop the latch: the header stops asserting "no radar session"
1735
+ // over a reason span that says the device is unreachable, and the automation stops spending
1736
+ // attempts on hardware that is not there. Not a recovery (nothing came back), so _recoveredAt
1737
+ // stays and a later no_session on this device is judged against the real last recovery.
1738
+ retireNoSession() {
1739
+ if (!this.sessionEnded)
1740
+ return;
1741
+ this.sessionEnded = false;
1742
+ this._latchRetired = true;
1743
+ this.emit("session-ended", false);
1744
+ this.emit("auto-rearm", this.autoRearming);
1745
+ }
1746
+ // Auto-re-arm: the recovery the retry loops deliberately do not perform. The stream proxy
1747
+ // never re-enables (enabling binds an identity and mutates device state; a read loop must
1748
+ // not, and a machine consumer holding /stream must never arm a device by holding it), so a
1749
+ // dead session used to sit at "retrying…" until a human found the Reconnect button. This is
1750
+ // that button pressing itself, under conditions that keep the consent story intact:
1751
+ // - only on a diagnosed no_session (the one state a re-enable is known to fix, proven
1752
+ // safe to arm by the device's own socket table — nobody's live session gets clobbered);
1753
+ // - only from a VISIBLE tab (a human is looking; a background tab must not re-arm a device
1754
+ // someone deliberately let idle out, and an MCP-only dashboard has no tab at all);
1755
+ // - never during an ambiguous multi-device pick (that decision belongs to the human);
1756
+ // - at most once per spacing window, and it gives up for the outage after enough failed
1757
+ // broadcasts that the next one clearly needs a human (the button stays on screen).
1758
+ // Cadence comes free: noteNoSession fires the first attempt, pollHealth's 2s tick drives
1759
+ // the rest — including the catch-up attempt when a hidden tab becomes visible again.
1760
+ async maybeAutoRearm() {
1761
+ if (!this.sessionEnded || this.stopped || this.autoRearming || this.enabling)
1762
+ return;
1763
+ // Strict false, not falsy: null means no /health reply has answered yet, and an
1764
+ // unanswered consent question refuses the same as a "no" (the server refuses the
1765
+ // ?auto=1 too, but this keeps the tab from even asking).
1766
+ if (this.autoRearmSuppressed || this.selfArmBlocked !== false)
1767
+ return;
1768
+ if (this.conn.state === "connected")
1769
+ return;
1770
+ if (this.needsDevicePick)
1771
+ return;
1772
+ if (typeof document !== "undefined" && document.visibilityState !== "visible")
1773
+ return;
1774
+ if (this.autoRearmExhausted)
1775
+ return;
1776
+ const now = this.rearmClock();
1777
+ if (now - this._autoRearmLastTs < AUTO_REARM_SPACING_MS)
1778
+ return;
1779
+ this._autoRearmLastTs = now;
1780
+ this.autoRearming = true;
1781
+ // The outage this attempt belongs to (see _noSessionGen).
1782
+ const gen = this._noSessionGen;
1783
+ try {
1784
+ // Inside the try so a throwing "auto-rearm" subscriber cannot leave the latch stuck
1785
+ // true forever (the finally below always clears it).
1786
+ this.emit("auto-rearm", true);
1787
+ // Budget is spent against reconnect()'s own reported outcome. "no_answer" (the
1788
+ // dashboard's own port unreachable — reconnectInner CATCHES that fetch failure, so it
1789
+ // never surfaces as a rejection here) must count: it is the mode where every future
1790
+ // attempt is equally doomed, and without spending budget a dead dashboard would fire
1791
+ // /enable every spacing window forever under a header promising it will keep trying.
1792
+ const outcome = await this.reconnect(true);
1793
+ // An armed reply retires the no-session state inside reconnect() itself (so a manual
1794
+ // press does it too) and stamps the recovery; the budget is NOT refilled by the arm. An
1795
+ // arm that holds refills it at the next outage, an arm the session dies out of within
1796
+ // the spacing window is a flap and counts against it (see noteNoSession).
1797
+ //
1798
+ // Failures are gated on the SAME outage still standing: a refutation that landed
1799
+ // mid-flight ended the outage this attempt belonged to, and its late verdict must not
1800
+ // shrink the NEXT outage's budget — including a next outage that latched during the
1801
+ // flight, which the boolean alone would mistake for this one.
1802
+ // A retired latch is the same outage paused (see _latchRetired), so a verdict landing inside
1803
+ // that window still belongs to it; without this a repeating unplug/replug with a dead session
1804
+ // never reached the cap because every verdict landed while retired.
1805
+ if (outcome !== "armed" && outcome !== "in_flight" && (this.sessionEnded || this._latchRetired) && gen === this._noSessionGen)
1806
+ this._autoRearmFails++;
1807
+ }
1808
+ catch {
1809
+ // Defensive only: the real reconnect() resolves on every path today. A future path
1810
+ // that rejects still must not escape the fire-and-forget call sites or retry free.
1811
+ if ((this.sessionEnded || this._latchRetired) && gen === this._noSessionGen)
1812
+ this._autoRearmFails++;
1813
+ }
1814
+ finally {
1815
+ this.autoRearming = false;
1816
+ this.emit("auto-rearm", false);
1817
+ }
1818
+ }
1819
+ // The Reconnect Radar button — and the auto-re-arm, which is this button pressing itself.
1820
+ // Re-arms the device through the same /enable the picker uses, and reports what came back:
1821
+ // the route already words every failure it can hit, down to naming a missing debug build,
1822
+ // and a user who just pressed a button is owed that answer instead of a dashboard that
1823
+ // keeps saying "waiting for device…" whether the press worked or not.
1824
+ //
1825
+ // Single-flight across BOTH initiators: a manual press mid-auto-attempt (or the reverse)
1826
+ // must not launch a second concurrent /enable — two flights double-broadcast and interleave
1827
+ // their pin/resync answers. `enabling` is store state (emitted "enabling") so the header's
1828
+ // button disables and relabels off the same latch that refuses the overlap.
1829
+ // The outcome the auto-re-arm budget is spent against. "armed" is the device's own yes;
1830
+ // "refused" is a completed reply saying no (the enable flow's worded failures); "no_answer"
1831
+ // is a request that never produced a reply at all — the dashboard's own port unreachable —
1832
+ // which must still spend budget or a dead dashboard fires /enable every spacing window
1833
+ // forever. A latch-refused overlap reports "in_flight" so a caller never mistakes it for a
1834
+ // completed attempt.
1835
+ // `auto` marks an UNATTENDED attempt (the automatic recovery, not a press). The server reads
1836
+ // it to refuse the destructive screen teardown a first /enable can otherwise take — killing a
1837
+ // live cast and deleting saved recordings with nobody pressing anything.
1838
+ async reconnect(auto = false) {
1839
+ if (this.enabling)
1840
+ return "in_flight";
1841
+ this.enabling = true;
1842
+ try {
1843
+ // Emits inside the try so a throwing subscriber cannot leave the latch stuck true —
1844
+ // the finally always clears it. visibleEnableError derives from `enabling` (a flight
1845
+ // suppresses the previous attempt's answer), so the latch flip must republish it: the
1846
+ // header subscribes the reason span to "enable-error" and re-reads only on its own
1847
+ // event.
1848
+ this.emit("enabling", true);
1849
+ this.emit("enable-error", this.visibleEnableError);
1850
+ return await this.reconnectInner(auto);
1851
+ }
1852
+ finally {
1853
+ this.enabling = false;
1854
+ this.emit("enabling", false);
1855
+ this.emit("enable-error", this.visibleEnableError);
1856
+ }
1857
+ }
1858
+ // Spend the rest of this outage's automatic budget at once. Used when a reply says no future
1859
+ // unattended attempt can succeed; the "auto-rearm" emit is what re-renders the header's
1860
+ // give-up wording (that hook re-reads only on its own event).
1861
+ exhaustAutoRearm() {
1862
+ if (this.autoRearmExhausted)
1863
+ return;
1864
+ this._autoRearmFails = AUTO_REARM_MAX_FAILS;
1865
+ this._autoRearmTerminal = true;
1866
+ this.emit("auto-rearm", this.autoRearming);
1867
+ }
1868
+ // Retire the session-ended state and stamp the recovery. Called only from evidence that the
1869
+ // device is actually there — an observed connected report, or an /enable that came back
1870
+ // armed. Deliberately NOT the budget and NOT the spacing clock: whether this recovery earns
1871
+ // the next outage a fresh budget and an immediate attempt is decided when that outage
1872
+ // arrives, by whether this one held (noteNoSession). Resetting both here made the budget
1873
+ // strictly per-outage with nothing counting outages, so a session that died seconds after
1874
+ // every arm was resurrected on every cycle with no give-up reachable. The "auto-rearm" emit
1875
+ // is what lets the header's give-up wording clear (that hook re-reads only on its own event).
1876
+ refuteSessionEnded() {
1877
+ if (!this.sessionEnded) {
1878
+ // A recovery observed while the latch is RETIRED (undiagnosed, then the stream connected
1879
+ // or a press armed) is still the end of that outage: stamp it, so the next no_session is
1880
+ // judged against a real recovery instead of resuming a count from hours ago, and a session
1881
+ // that dies again within the window after it is still read as a flap. Without this the
1882
+ // retired flag outlived the recovery and a fresh outage inherited an exhausted budget.
1883
+ if (this._latchRetired) {
1884
+ this._latchRetired = false;
1885
+ this._recoveredAt = this.rearmClock();
1886
+ }
1887
+ return;
1888
+ }
1889
+ this.sessionEnded = false;
1890
+ this._recoveredAt = this.rearmClock();
1891
+ this._latchRetired = false;
1892
+ this.emit("session-ended", false);
1893
+ this.emit("auto-rearm", this.autoRearming);
1894
+ }
1895
+ async reconnectInner(auto) {
1313
1896
  // Read the epoch BEFORE the request, because the reply describes the outage the user pressed
1314
1897
  // during, not whatever is true when it lands. The failure path is slow (rebuild the forward,
1315
1898
  // broadcast, a ping with its own multi-second ceiling, then a process probe), which is easily long
1316
1899
  // enough for a boundary to pass, and stamping the later epoch would file this reason against an
1317
1900
  // outage it says nothing about.
1318
1901
  const epoch = this._outageEpoch;
1902
+ // And the diagnosed outage this attempt belongs to (see _noSessionGen), for the terminal
1903
+ // refusal below: the same "its own outage only" rule the per-unit budget follows.
1904
+ const gen = this._noSessionGen;
1319
1905
  // Whether THIS press's reply advance performed the real-switch resync. Captured at the
1320
1906
  // advance itself, not before the fetch: a poll can observe an unrelated switch during the
1321
1907
  // multi-second /enable flight, and deciding from a pre-fetch baseline would count that
1322
1908
  // poll's resync as this press's and skip a resync nobody performed for it. Same
1323
1909
  // before-and-after-an-await hazard the epoch capture above avoids.
1324
1910
  let replySwitched = false;
1911
+ let outcome;
1325
1912
  try {
1326
- const r = await fetch("/enable", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
1327
- const { enabled, error, serial } = await this.readEnableResult(r, "Reconnect failed. Is a device attached with a debug build of the Slack app running?");
1913
+ const r = await fetch(auto ? "/enable?auto=1" : "/enable", { method: "POST", headers: this.authoredHeaders() });
1914
+ const { enabled, error, instructs, serial, refusal } = await this.readEnableResult(r, "Reconnect failed. Is a device attached with a debug build of the Slack app running?");
1328
1915
  // The reply names the device this press pinned, and the route pins before it arms, so a
1329
1916
  // failing press can itself move the pin (first sight, or a switch to freshly attached
1330
1917
  // hardware). Advance the baseline from the reply BEFORE the reason is written: the later
@@ -1334,8 +1921,23 @@ class Store {
1334
1921
  if (serial !== null)
1335
1922
  this.checkSerialEdge(serial);
1336
1923
  replySwitched = serial !== null && beforeAdvance !== null && serial !== beforeAdvance;
1924
+ outcome = enabled ? "armed" : "refused";
1337
1925
  if (enabled) {
1338
1926
  this.clearEnableError();
1927
+ // An armed reply is the device itself answering (the route verifies with a ping before
1928
+ // reporting enabled), so it retires the no-session state immediately rather than
1929
+ // leaving the header promising a retry for the seconds until a poll observes the
1930
+ // recovery. Here, not in the auto-re-arm caller, so a MANUAL press retires it too.
1931
+ // Deliberately NOT setConn("connected"): the stream has its own reconnect to do, and
1932
+ // only an observation of the WIRE may claim "live".
1933
+ this.refuteSessionEnded();
1934
+ // With sessionEnded retired, the header falls back to conn.msg verbatim — which is
1935
+ // still the outage diagnosis this reply just refuted. Replace the MESSAGE only, never
1936
+ // the state: "connected" stays the wire's claim to make. Worded as the recovery step it
1937
+ // is, distinct from pollHealth's generic "reconnecting…" (the dashboard-unreachable
1938
+ // wording), so the interim frame reads as progress and not as a new problem.
1939
+ if (this.conn.state !== "connected")
1940
+ this.setConn(this.conn.state, "re-enabled, reconnecting the stream…");
1339
1941
  }
1340
1942
  else {
1341
1943
  // Its own field, not conn.msg: pollHealth runs every 2s and its own "device offline"
@@ -1346,16 +1948,32 @@ class Store {
1346
1948
  // frame that arrived while this request was in flight, so it is kept rather than thrown
1347
1949
  // away. The epoch stamp is what stops it being shown for some later outage instead.
1348
1950
  this.enableError = error;
1951
+ this.enableInstructs = instructs;
1349
1952
  this._enableErrorEpoch = epoch;
1350
1953
  this.emit("enable-error", this.visibleEnableError);
1954
+ // A marked refusal is terminal for the automation: the route refuses every later
1955
+ // unattended attempt the same way (the process may not self-arm; the pin moved to
1956
+ // different hardware and only a press may adopt it). Spending the remaining budget on
1957
+ // attempts known to fail would keep the header promising a retry for two more minutes
1958
+ // beside an error span already saying to press Reconnect — two adjacent instructions
1959
+ // pointing different ways. Exhaust the outage's budget now, so the header reads "gave
1960
+ // up" from this reply on, with the reason span saying to press Reconnect. The budget
1961
+ // still refills on recovery.
1962
+ // Gated on the latch like every other late verdict (see maybeAutoRearm): a refutation
1963
+ // that landed mid-flight ended the outage this reply belongs to, and spending the NEXT
1964
+ // outage's budget on it would render "gave up" over an outage with no attempt made.
1965
+ if (refusal !== null && (this.sessionEnded || this._latchRetired) && gen === this._noSessionGen)
1966
+ this.exhaustAutoRearm();
1351
1967
  }
1352
1968
  }
1353
1969
  catch {
1354
1970
  // The dashboard's own port is unreachable, so this press produced no answer about the device.
1355
1971
  // conn reports the dashboard being unreachable, but the reason line is a separate field and
1356
1972
  // would otherwise keep showing the PREVIOUS press's answer, presenting it as this press's, and
1357
- // blaming the device for a request that never reached it.
1973
+ // blaming the device for a request that never reached it. The caller still learns this
1974
+ // happened through the returned outcome — clearing the reason must not read as success.
1358
1975
  this.clearEnableError();
1976
+ outcome = "no_answer";
1359
1977
  }
1360
1978
  this.pollHealth();
1361
1979
  this.pollProfile();
@@ -1364,6 +1982,7 @@ class Store {
1364
1982
  // across a real switch; a second open/close/open here would only churn the backfill.
1365
1983
  if (!replySwitched)
1366
1984
  this.resyncStream();
1985
+ return outcome;
1367
1986
  }
1368
1987
  // Kill the dashboard server from the header button. The X-Radar-Dashboard header is the
1369
1988
  // CSRF guard the /shutdown route requires (a foreign origin's fetch cannot set it without a
@@ -1426,6 +2045,8 @@ export function describeConstraints(spec) {
1426
2045
  parts.push("where " + Object.entries(spec.match).map(([k, v]) => k + "=" + v).join(", "));
1427
2046
  if (spec.bodyContains)
1428
2047
  parts.push('body contains "' + spec.bodyContains + '"');
2048
+ if (typeof spec.minLevel === "string" && spec.minLevel)
2049
+ parts.push("level ≥ " + spec.minLevel);
1429
2050
  if (spec.highlight && spec.highlight.field)
1430
2051
  parts.push("flag " + spec.highlight.field + " " + (spec.highlight.op || ">") + " " + spec.highlight.value + (spec.highlight.label ? " (" + spec.highlight.label + ")" : ""));
1431
2052
  if (Array.isArray(spec.series) && spec.series.length)