@slack/radar-mcp 1.18.1 → 1.19.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.
@@ -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;
@@ -122,6 +138,8 @@ class Store {
122
138
  // is invalidated by one thing only, a later pick that works, and nothing about device health
123
139
  // refutes it. It therefore renders whether or not the dashboard is connected.
124
140
  deviceError = null;
141
+ // Same flag for the pick error (see enableInstructs).
142
+ deviceErrorInstructs = false;
125
143
  // Why the last Reconnect press did not arm the device, or null when it did. Owned by reconnect().
126
144
  //
127
145
  // KEPT SEPARATE FROM deviceError on purpose: a pick failure is about a device the user named,
@@ -149,7 +167,164 @@ class Store {
149
167
  // the /enable reply echoes the pinned serial, and reconnect() advances the baseline from the
150
168
  // reply before the reason is written, so the follow-up poll observes no edge.
151
169
  enableError = null;
170
+ // Whether enableError's wording tells the user what to do (the reply's own `instructs` flag,
171
+ // set where the wording is written). The header reads this instead of guessing from the prose.
172
+ enableInstructs = false;
152
173
  _enableErrorEpoch = -1;
174
+ // The stream proxy diagnosed the current outage as "the device-side radar session ENDED"
175
+ // (idle watchdog, app restart): the proxy's own retries can never fix that — only a
176
+ // re-enable can — so this flag is what authorizes the auto-re-arm below. Set from a _status
177
+ // frame carrying reason "no_session"; cleared by an OBSERVED connected report — a device
178
+ // frame, the proxy's own connect, a device:true health reply, or an /enable that came back
179
+ // armed — and specifically NOT by pollHealth's fresh-frame fast path, which re-reads
180
+ // pre-outage evidence (see setConn's `observed` parameter). Deliberately NOT epoch-stamped
181
+ // like enableError: staleness is
182
+ // handled at the SOURCE — the server discards a diagnosis that resolves after its stream
183
+ // reconnected — and the guards in maybeAutoRearm (spacing, cap, in-flight latch) bound
184
+ // whatever slips through. It also DRIVES the header wording: while latched, the conn span
185
+ // renders the session-ended state instead of conn.msg, because pollHealth's generic
186
+ // "device offline, retrying…" overwrites the msg within one 2s tick and is factually wrong
187
+ // for this outage mode (the device is fine; the session inside the app ended).
188
+ sessionEnded = false;
189
+ // True while ANY /enable flight is in progress — manual press or auto-re-arm — set by
190
+ // reconnect() itself so one latch covers both initiators. Emitted as "enabling"; the
191
+ // header's button disables and relabels off it.
192
+ enabling = false;
193
+ // True specifically while an AUTO attempt is in flight (a subset of `enabling`), so the
194
+ // header can word the state as the machine acting rather than answering a press. Emitted
195
+ // as "auto-rearm".
196
+ autoRearming = false;
197
+ // When the last automatic attempt was made. NOT reset by a recovery: the spacing window spans
198
+ // outages, so a session that dies again right after an arm waits out the window instead of
199
+ // getting a free immediate attempt every cycle (see noteNoSession).
200
+ _autoRearmLastTs = 0;
201
+ _autoRearmFails = 0;
202
+ // When the last outage ended (an observed connected report, or an /enable that came back
203
+ // armed). Whether that recovery HELD decides the next outage's budget: held for a full spacing
204
+ // window, the next outage starts fresh; died inside it, the next outage is a flap and the drop
205
+ // counts as a failed attempt. null until the first recovery.
206
+ _recoveredAt = null;
207
+ // The latch was dropped by an "undiagnosed" frame rather than by a recovery. A retire is a
208
+ // pause, not an outage boundary: nothing came back in between, so when no_session returns there
209
+ // is nothing to judge and the count and the clock carry over (see noteNoSession).
210
+ _latchRetired = false;
211
+ // Set when the current exhausted state was reached through drops (a session that died again
212
+ // inside the spacing window of coming back) rather than three real failed attempts, so the
213
+ // header can say what actually happened instead of "after 3 tries".
214
+ _autoRearmFlapped = false;
215
+ // Set when the budget was spent at once on a reply the server will repeat for every later
216
+ // unattended attempt (not by three real failures), so the header can say "gave up" without
217
+ // naming a count of attempts that were never made. Cleared with the rest of the outage state.
218
+ _autoRearmTerminal = false;
219
+ // Counts diagnosed outages, bumped when the no-session latch is SET. An attempt records the
220
+ // generation it started under so a verdict that lands after the latch was cleared AND re-set
221
+ // by a newer outage is not charged to the newer one: the boolean latch alone cannot tell the
222
+ // two apart.
223
+ _noSessionGen = 0;
224
+ get autoRearmFlapped() {
225
+ return this._autoRearmFlapped;
226
+ }
227
+ get autoRearmTerminal() {
228
+ return this._autoRearmTerminal;
229
+ }
230
+ // The human's off switch for the automation, set from the header's "stop" control. Without
231
+ // it, a user who explicitly DISABLED radar with a dashboard tab still visible had no way to
232
+ // make the tab stop re-arming the session it keeps diagnosing as ended (the socket table
233
+ // cannot tell "died mid-use" from "idled out after a deliberate disable"). PERSISTED per
234
+ // browser origin (see the key below) and never cleared by a recovery: it records the human's
235
+ // intent, not a fact about the outage. Emitted as "auto-rearm" (the header's recovery
236
+ // wording re-reads on that event).
237
+ autoRearmSuppressed = readAutoRearmSuppressed();
238
+ // Cross-tab: the choice is stored per browser origin, so a SIBLING tab already open must
239
+ // honour it too — otherwise the tab that pressed stop renders "off" while the tab next to it
240
+ // keeps arming the device, and the control's whole purpose (make the arming stop) fails.
241
+ // `storage` fires only in the OTHER tabs, which is exactly the gap the writer cannot cover.
242
+ watchSuppressionAcrossTabs() {
243
+ try {
244
+ window.addEventListener("storage", (e) => {
245
+ if (e.key !== null && e.key !== AUTO_REARM_OFF_KEY)
246
+ return;
247
+ const next = readAutoRearmSuppressed();
248
+ if (next === this.autoRearmSuppressed)
249
+ return;
250
+ this.autoRearmSuppressed = next;
251
+ // Another tab resuming is the same fresh intent as this tab's own control.
252
+ if (!next)
253
+ this.resetRearmBudget();
254
+ this.emit("auto-rearm", this.autoRearming);
255
+ if (!next)
256
+ void this.maybeAutoRearm();
257
+ });
258
+ }
259
+ catch {
260
+ /* no window (tests, SSR): the flag still holds for this instance */
261
+ }
262
+ }
263
+ // Start the automatic re-enable over: count, marks, the spacing clock and the recovery
264
+ // baseline. For a state that is about a different intent than the one that spent them: a
265
+ // change of bound device (device A's failures say nothing about device B) or the human
266
+ // turning the automation back on (a resume is a fresh intent, and someone who just switched
267
+ // it on expects it to try, not to read "gave up" for drops that happened while it was off).
268
+ // The clock goes too, or the first attempt after the change waits out a window that belongs
269
+ // to the old intent. Republishes so the header re-reads the give-up state.
270
+ resetRearmBudget() {
271
+ const wasExhausted = this.autoRearmExhausted;
272
+ this._autoRearmFails = 0;
273
+ this._autoRearmTerminal = false;
274
+ this._autoRearmFlapped = false;
275
+ this._recoveredAt = null;
276
+ this._latchRetired = false;
277
+ this._autoRearmLastTs = 0;
278
+ if (wasExhausted)
279
+ this.emit("auto-rearm", this.autoRearming);
280
+ }
281
+ setAutoRearmSuppressed(v) {
282
+ if (this.autoRearmSuppressed === v)
283
+ return;
284
+ this.autoRearmSuppressed = v;
285
+ if (!v)
286
+ this.resetRearmBudget();
287
+ // Persisted like the theme and the setup-hint dismissal: a reload silently resuming
288
+ // automatic device arming would undo a decision the human made deliberately.
289
+ try {
290
+ if (v)
291
+ localStorage.setItem(AUTO_REARM_OFF_KEY, "1");
292
+ else
293
+ localStorage.removeItem(AUTO_REARM_OFF_KEY);
294
+ }
295
+ catch {
296
+ /* private mode: the choice lasts for this tab only */
297
+ }
298
+ this.emit("auto-rearm", this.autoRearming);
299
+ // A resume during a diagnosed outage tries now, not on the next poll tick.
300
+ if (!v)
301
+ void this.maybeAutoRearm();
302
+ }
303
+ // Set from /health's self_arm_blocked: this dashboard PROCESS may not touch the device on
304
+ // its own. Two reasons today, both server-side facts: an agent spawned it (the premise
305
+ // open_radar_dashboard's MCP-gate exemption rests on), or SLACK_RADAR_NO_ARM is set (the
306
+ // documented opt-out for device-touching behaviour, which suppressed the boot arm and must
307
+ // suppress this too). The header words a blocked tab as "Press Reconnect" (or, beside a
308
+ // reason on screen that itself instructs — see reasonInstructs in app.ts — "Auto re-enable
309
+ // is unavailable on this tab").
310
+ // Tri-state: null until a /health reply answers with an explicit boolean. A no_session frame
311
+ // can beat that reply on a fresh tab (the stream diagnoses in ~2s while /health waits on a
312
+ // device ping), and the automatic re-enable must not act on a default — so it requires an
313
+ // answered false, never the absence of a true. The header reads null as unanswered: it
314
+ // renders "Checking whether this tab may re-enable…" (unless the human's persisted stop is
315
+ // set, which outranks the unanswered question and renders its own wording) and hides the
316
+ // automation controls, so
317
+ // it neither promises a retry the store would refuse nor issues an instruction the answer
318
+ // may withdraw.
319
+ selfArmBlocked = null;
320
+ // The give-up state: this outage spent its automatic budget, the next press is the human's.
321
+ // Derived so the header can render it; flips back when a connected report resets the count.
322
+ get autoRearmExhausted() {
323
+ return this._autoRearmFails >= AUTO_REARM_MAX_FAILS;
324
+ }
325
+ // The auto-re-arm clock, injectable for the same reason as connClock: tests exercise the
326
+ // spacing floor by moving time, never by disabling the floor.
327
+ rearmClock = () => Date.now();
153
328
  // Counts outages: bumped by setConn when the connection leaves a CONFIRMED connected state.
154
329
  _outageEpoch = 0;
155
330
  // Pieces of positive evidence that the current connected state is real, at most one per
@@ -170,9 +345,19 @@ class Store {
170
345
  connClock = () => Date.now();
171
346
  // The reconnect reason the header may actually show: only while disconnected, and only for the
172
347
  // outage that produced it. Both conditions in one place so the component cannot get it half right.
348
+ // The instructs flag of the wording visibleEnableError shows, and false whenever it shows none:
349
+ // the flag is never readable apart from the wording it qualifies.
350
+ get visibleEnableInstructs() {
351
+ return this.visibleEnableError === null ? false : this.enableInstructs;
352
+ }
173
353
  get visibleEnableError() {
174
354
  if (this.conn.state === "connected")
175
355
  return null;
356
+ // A flight in progress supersedes the previous attempt's answer: rendering "Reconnect
357
+ // failed…" beside a button that simultaneously says "enabling…" is two contradictory
358
+ // messages about one flow. The reason returns (or is replaced) when the flight lands.
359
+ if (this.enabling)
360
+ return null;
176
361
  return this._enableErrorEpoch === this._outageEpoch ? this.enableError : null;
177
362
  }
178
363
  // Drop the reason outright. Used where the reason is not merely from another outage but describes a
@@ -182,6 +367,7 @@ class Store {
182
367
  if (this.enableError === null && this._enableErrorEpoch === -1)
183
368
  return;
184
369
  this.enableError = null;
370
+ this.enableInstructs = false;
185
371
  this._enableErrorEpoch = -1;
186
372
  this.emit("enable-error", this.visibleEnableError);
187
373
  }
@@ -341,8 +527,23 @@ class Store {
341
527
  this.selectedDevice = null;
342
528
  this.devicesError = false;
343
529
  this.deviceError = null;
530
+ this.deviceErrorInstructs = false;
344
531
  this.enableError = null;
532
+ this.enableInstructs = false;
345
533
  this._enableErrorEpoch = -1;
534
+ this.sessionEnded = false;
535
+ this.enabling = false;
536
+ this.autoRearming = false;
537
+ this.autoRearmSuppressed = false;
538
+ this.selfArmBlocked = null;
539
+ this._autoRearmLastTs = 0;
540
+ this._autoRearmFails = 0;
541
+ this._autoRearmTerminal = false;
542
+ this._recoveredAt = null;
543
+ this._latchRetired = false;
544
+ this._autoRearmFlapped = false;
545
+ this._noSessionGen = 0;
546
+ this.rearmClock = () => Date.now();
346
547
  this._outageEpoch = 0;
347
548
  this._connProof = 0;
348
549
  this._lastProofTs = 0;
@@ -489,6 +690,7 @@ class Store {
489
690
  // local default bootDefault had just set and stranding the page on the blank placeholder
490
691
  // until the next 700ms tick happened to read the corrected value.
491
692
  await this.bootDefault();
693
+ this.watchSuppressionAcrossTabs();
492
694
  this.fetchSelfHeal();
493
695
  this.fetchSetupHint();
494
696
  this.pollSpec();
@@ -536,7 +738,21 @@ class Store {
536
738
  this._connProof++;
537
739
  this._lastProofTs = now;
538
740
  }
539
- setConn(state, msg) {
741
+ setConn(state, msg, observed = false) {
742
+ // An OBSERVED connected report refutes "no radar session" directly (a dead session
743
+ // serves no stream), so it retires the auto-re-arm authorization, its failure count, and
744
+ // its spacing clock together — the NEXT diagnosed outage deserves the same immediate
745
+ // first attempt this one got. `observed` means the report traces to a real observation
746
+ // (a device frame, the stream proxy's own connect, a device:true health reply) — and NOT
747
+ // pollHealth's fresh-frame fast path, which re-reads the same pre-outage _lastEventTs
748
+ // every tick for up to 6s and would otherwise clear the latch, budget, and spacing with
749
+ // evidence that predates the outage (the same exclusion noteDeviceProof already makes).
750
+ // Judged on the state as REPORTED, before the multi-device override below rewrites it:
751
+ // the ambiguity is about which device to pin, not about whether a session is serving
752
+ // frames, and letting the override eat the refutation would leave the header claiming
753
+ // "no radar session" about a session that just spoke.
754
+ if (state === "connected" && observed)
755
+ this.refuteSessionEnded();
540
756
  // Unpinned multi-device is never "connected": frames can ride a stale forward from a prior
541
757
  // pin and flip the dot green while the per-device surfaces (DB run-as) are broken by the
542
758
  // ambiguity. Override any connected claim to a waiting "pick one" until a device is pinned.
@@ -726,8 +942,26 @@ class Store {
726
942
  return;
727
943
  }
728
944
  if (f.type === "_status") {
945
+ // reason is typed as a plain string on purpose: the client acts on the known value and
946
+ // treats every other value as a retraction (see src/shared/wire.ts StatusReason), so a
947
+ // server that adds a reason later needs no client change.
729
948
  const e = f.event;
730
- this.setConn(e.state, e.msg);
949
+ // conn first, reason second: a reasoned frame is itself a waiting report, and
950
+ // noteNoSession's immediate re-arm attempt reads conn.state — handled the other way
951
+ // around, a diagnosis arriving right after a connected blip would see the stale
952
+ // "connected" and skip the immediate attempt it exists for. observed=true: a connected
953
+ // _status is the proxy vouching its upstream actually answered.
954
+ this.setConn(e.state, e.msg, true);
955
+ // The reason is the outage's CURRENT diagnosis (see src/shared/wire.ts StatusReason): only
956
+ // no_session latches, and any other reason, today "undiagnosed" and whatever a later server
957
+ // adds, retires the latch. Dispatching on the retraction token itself would leave the latch
958
+ // stuck under the next new value, the exact defect the retire exists to fix.
959
+ if (e.reason) {
960
+ if (e.reason === "no_session")
961
+ this.noteNoSession();
962
+ else
963
+ this.retireNoSession();
964
+ }
731
965
  return;
732
966
  }
733
967
  if (f.type === "_error") {
@@ -756,7 +990,7 @@ class Store {
756
990
  // transient blip). Clear _dropped here so recovered() does NOT later tear down this healthy
757
991
  // stream and re-open it: recovered() should only fire when the stream did NOT self-heal.
758
992
  this._dropped = false;
759
- this.setConn("connected", "");
993
+ this.setConn("connected", "", true);
760
994
  }
761
995
  const ev = f.event || {};
762
996
  ev._type = f.type;
@@ -1027,9 +1261,18 @@ class Store {
1027
1261
  if (this._lastSerial !== null) {
1028
1262
  this.clearDeviceCaches();
1029
1263
  this.resyncStream();
1264
+ // The re-arm budget is about the device that was bound when it was spent, so a change of
1265
+ // bound device starts it over: device A's two failed arms must not leave device B one drop
1266
+ // away from "gave up" before any attempt was made against it. The device_changed refusal
1267
+ // echoes the OLD pin, so it never moves this baseline; only an adopting press or a poll that
1268
+ // sees the new pin does.
1269
+ this.resetRearmBudget();
1030
1270
  // A reconnect reason is about the device that was bound when it was produced, so a change of
1031
1271
  // 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.
1272
+ // device B's outage, because the epoch counts outages and a switch is not one. The pick
1273
+ // error is deliberately NOT retired here: a failed pick the server did pin moves this
1274
+ // baseline through the device-list refresh AFTER the error was written, so the error is
1275
+ // about the device just pinned and must survive the edge it caused.
1033
1276
  this.clearEnableError();
1034
1277
  }
1035
1278
  this._lastSerial = serial;
@@ -1077,6 +1320,11 @@ class Store {
1077
1320
  this.emit("screen-caps", this.screenCaps);
1078
1321
  }
1079
1322
  async pollHealth() {
1323
+ // The auto-re-arm cadence rides this existing 2s tick instead of owning a timer: every
1324
+ // guard lives inside maybeAutoRearm, so this line is a no-op except mid-outage on a
1325
+ // diagnosed dead session. Fire-and-forget so a multi-second /enable flight cannot delay
1326
+ // the health read below.
1327
+ void this.maybeAutoRearm();
1080
1328
  if (this.connClock() - this._lastEventTs < 6000) {
1081
1329
  this._healthMisses = 0;
1082
1330
  this.recovered();
@@ -1098,21 +1346,22 @@ class Store {
1098
1346
  // instead by fetchDevices, which polls /_control/devices every 5s regardless of stream
1099
1347
  // activity. Between the two, both busy and quiet observer tabs converge within 5s.
1100
1348
  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", "");
1349
+ if (h.device === true) {
1350
+ this.onHealthDeviceUp(h.sources);
1111
1351
  }
1112
1352
  else if (++this._healthMisses >= 2) {
1113
1353
  this._dropped = true;
1114
1354
  this.setConn("waiting", "device offline, retrying…");
1115
1355
  }
1356
+ // Whether this dashboard process may arm the device on its own. Read on every health
1357
+ // reply rather than once at boot (pollProfile's reply feeds the same note, since this
1358
+ // fetch is skipped while the stream is busy), and the field starts null so the
1359
+ // automatic re-enable cannot act before a reply answers with an explicit boolean. AFTER
1360
+ // the device verdict above on purpose: an answered "may" fires the pending first attempt,
1361
+ // and a reply saying device:true has just refuted the no-session latch that attempt
1362
+ // would act on — the same reply must not arm a session it is confirming alive (the
1363
+ // deviceAlive argument is the belt to that ordering's braces).
1364
+ this.noteSelfArmBlocked(h.self_arm_blocked, h.device === true);
1116
1365
  }
1117
1366
  catch {
1118
1367
  if (++this._healthMisses >= 2) {
@@ -1121,6 +1370,42 @@ class Store {
1121
1370
  }
1122
1371
  }
1123
1372
  }
1373
+ // What a /health reply saying device:true means, for BOTH polls that fetch /health: only a
1374
+ // healthy reply updates the source list (a device:false blip must not flip tabs off and back
1375
+ // on recovery; the last list stands until the serial edge clears it), the miss counter resets,
1376
+ // a dropped stream is re-synced, and the reply counts as a genuine observation — the one a
1377
+ // QUIET device recovers on — which setConn's observed connected report turns into the end of
1378
+ // any diagnosed outage. Shared so pollHealth and pollProfile cannot treat the same evidence
1379
+ // differently.
1380
+ onHealthDeviceUp(sources) {
1381
+ this.updateSources(Array.isArray(sources) ? sources : null);
1382
+ this._healthMisses = 0;
1383
+ this.recovered();
1384
+ this.noteDeviceProof();
1385
+ this.setConn("connected", "", true);
1386
+ }
1387
+ // Record a /health reply's answer to "may this process arm the device on its own", from
1388
+ // whichever poll carried it. Only an explicit boolean counts as an answer: a reply without
1389
+ // the field (an older server) leaves the question open, because that server still takes the
1390
+ // destructive first-enable teardown and ignores ?auto=1, so a tab must not arm it unattended
1391
+ // either. Emitted on change so the header can stop promising a retry such a tab will never
1392
+ // make — and, once the answer is "may", the first attempt follows the answer right away
1393
+ // rather than waiting for the next poll tick. Unless the SAME reply reported the device up
1394
+ // (deviceAlive): both callers run onHealthDeviceUp on a device:true reply before calling
1395
+ // this, and its observed connected report retires the no-session latch, so there is no
1396
+ // outage left for the attempt to act on; the skip here is the belt to that ordering's
1397
+ // braces, and a session that really is dead re-diagnoses on the stream with a fresh
1398
+ // generation and its own immediate attempt.
1399
+ noteSelfArmBlocked(v, deviceAlive = false) {
1400
+ if (typeof v !== "boolean")
1401
+ return;
1402
+ if (this.selfArmBlocked === v)
1403
+ return;
1404
+ this.selfArmBlocked = v;
1405
+ this.emit("self-arm-blocked", this.selfArmBlocked);
1406
+ if (!v && !deviceAlive)
1407
+ void this.maybeAutoRearm();
1408
+ }
1124
1409
  // Called when health flips back to connected. If we were in a dropped state, the EventSource
1125
1410
  // did not survive the drop and the tab has been silent, so re-open the stream + backfill the
1126
1411
  // device ring ONCE on the recovery edge. The _dropped guard makes this fire on the transition,
@@ -1149,14 +1434,24 @@ class Store {
1149
1434
  ]);
1150
1435
  const uid = healthR && healthR.boundUserId;
1151
1436
  // 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
- }
1437
+ // stream; this 5s poll already fetched /health, so a device:true here is handled by the SAME
1438
+ // helper pollHealth uses (sources, misses, recovery, proof, connected — and through the
1439
+ // observed connected report, the no-session latch). One helper, so the two /health consumers
1440
+ // cannot drift apart again: an earlier version only retired the latch here and left conn
1441
+ // waiting for a tick, and a version before that only refreshed the sources, which let the
1442
+ // consent answer below fire an attempt at a session this very reply had reported alive.
1443
+ if (healthR && healthR.device === true)
1444
+ this.onHealthDeviceUp(healthR.sources);
1156
1445
  // Same starvation backstop for the screen caps: this reply is the /health an open
1157
1446
  // overlay actually sees while the stream is chatty.
1158
1447
  if (healthR)
1159
1448
  this.updateScreenCaps(healthR.screen);
1449
+ // And for the consent answer: on a chatty stream this poll is the only /health reply the
1450
+ // tab sees, so without it the field sits at null (unanswered) until the first outage
1451
+ // releases pollHealth's fast path — the header would hide the automation's controls and
1452
+ // the first attempt would wait for a reply instead of firing on the diagnosis.
1453
+ if (healthR)
1454
+ this.noteSelfArmBlocked(healthR.self_arm_blocked, healthR.device === true);
1160
1455
  this.profiles = (profilesR && profilesR.profiles) || [];
1161
1456
  if (uid == null) {
1162
1457
  this.profileLabel = this._lastBoundLabel ? "last seen " + this._lastBoundLabel + " — reconnecting…" : "waiting for device…";
@@ -1213,12 +1508,23 @@ class Store {
1213
1508
  return {
1214
1509
  enabled: false,
1215
1510
  error: "Could not read the dashboard reply to this request. Try again.",
1511
+ // Client-authored wording, so the client knows it instructs.
1512
+ instructs: true,
1216
1513
  serial: null,
1514
+ refusal: null,
1217
1515
  };
1218
1516
  }
1219
1517
  const error = typeof body.error === "string" && body.error ? body.error : fallback;
1220
1518
  const serial = typeof body.device_serial === "string" && body.device_serial ? body.device_serial : null;
1221
- return { enabled: body.enabled === true, error, serial };
1519
+ // The route's marker for a refusal that no later unattended attempt can change (the process
1520
+ // may not self-arm; the hardware changed under the session). Absent on failures a retry
1521
+ // might still fix.
1522
+ const refusal = typeof body.refusal === "string" && body.refusal ? body.refusal : null;
1523
+ // Only a server wording can carry the server's flag; the `fallback` is the client's own and
1524
+ // does not instruct. An older server sends no flag, and absent reads as "does not instruct",
1525
+ // so the header's tail keeps its own imperative rather than dropping it on a guess.
1526
+ const instructs = typeof body.error === "string" && body.error ? body.instructs === true : false;
1527
+ return { enabled: body.enabled === true, error, instructs, serial, refusal };
1222
1528
  }
1223
1529
  // Pin a specific device for the session. POSTs the same /enable the reconnect button uses,
1224
1530
  // with the chosen serial; on success it runs the same post-enable refresh as reconnect() so
@@ -1236,7 +1542,7 @@ class Store {
1236
1542
  // body says enabled:false used to fall through here as a success: it cleared deviceError,
1237
1543
  // recorded the serial as switched-to, and resynced a stream against a device holding no
1238
1544
  // 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.");
1545
+ const { enabled, error, instructs, serial: confirmed } = await this.readEnableResult(r, "Selecting that device did not arm Radar on it.");
1240
1546
  if (!enabled) {
1241
1547
  // Surface the failure on the device chip itself, not via conn: a healthy pollHealth flips
1242
1548
  // conn back to connected within 2s and would erase a setConn("waiting", …) message before
@@ -1255,12 +1561,16 @@ class Store {
1255
1561
  // behind the older message.
1256
1562
  this.clearEnableError();
1257
1563
  this.deviceError = error;
1564
+ this.deviceErrorInstructs = instructs;
1565
+ this.emit("device-error", this.deviceError);
1258
1566
  this.emit("devices", this.devices);
1259
1567
  this.fetchDevices();
1260
1568
  return;
1261
1569
  }
1262
1570
  // A successful pick clears any prior enable failure.
1263
1571
  this.deviceError = null;
1572
+ this.deviceErrorInstructs = false;
1573
+ this.emit("device-error", null);
1264
1574
  this.emit("devices", this.devices);
1265
1575
  // The pick ARMED the device, which refutes any standing reconnect reason whatever the serial
1266
1576
  // did -- the same rule as a successful reconnect. Cleared here, inline, because advancing the
@@ -1305,26 +1615,233 @@ class Store {
1305
1615
  this.openStream();
1306
1616
  this.backfill();
1307
1617
  }
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() {
1618
+ // A "no_session" diagnosis arrived on the stream (see the _status handler). Record it and
1619
+ // try to recover right away when the spacing clock allows: the clock starts at zero, so the
1620
+ // FIRST outage's first attempt is immediate and the tab heals in seconds, and a real
1621
+ // idle-timeout outage (minutes of healthy session since the last attempt) is immediate too.
1622
+ //
1623
+ // The budget is decided here, by whether the LAST recovery held. A session that died again
1624
+ // inside one spacing window of coming back is a flap (a crash-looping app, which is close to
1625
+ // the state someone with this dashboard open is often in): the drop counts as a failed
1626
+ // attempt and the spacing clock is not reset, so a flapping session is re-armed at most once
1627
+ // a minute and reaches "gave up" after three, instead of being resurrected every few seconds
1628
+ // forever with the give-up state unreachable because every cycle was a "new outage".
1629
+ noteNoSession() {
1630
+ if (!this.sessionEnded) {
1631
+ this.sessionEnded = true;
1632
+ const now = this.rearmClock();
1633
+ const wasExhausted = this.autoRearmExhausted;
1634
+ const resuming = this._latchRetired;
1635
+ if (resuming) {
1636
+ // Re-latching after a retire: the same outage resuming, nothing to judge, and the same
1637
+ // generation, so an attempt that was in flight across the retire still charges here.
1638
+ this._latchRetired = false;
1639
+ }
1640
+ else if (this._recoveredAt === null || now - this._recoveredAt >= AUTO_REARM_SPACING_MS) {
1641
+ this._autoRearmFails = 0;
1642
+ this._autoRearmTerminal = false;
1643
+ this._autoRearmFlapped = false;
1644
+ }
1645
+ else {
1646
+ this._autoRearmFails++;
1647
+ // A count-based judgement supersedes a marked refusal from the earlier outage.
1648
+ this._autoRearmTerminal = false;
1649
+ this._autoRearmFlapped = true;
1650
+ }
1651
+ if (!resuming)
1652
+ this._noSessionGen++;
1653
+ this.emit("session-ended", true);
1654
+ // The header re-reads the give-up state only on its own event; republish only when the
1655
+ // judgement above changed it, so the flight's own open/close edges stay the only emits of
1656
+ // an ordinary outage.
1657
+ if (this.autoRearmExhausted !== wasExhausted)
1658
+ this.emit("auto-rearm", this.autoRearming);
1659
+ }
1660
+ void this.maybeAutoRearm();
1661
+ }
1662
+ // The proxy re-probed and no longer finds the session absent: the socket is present after
1663
+ // all, or the table cannot be read because the device is gone. The outage changed nature
1664
+ // under the latched reason, so drop the latch: the header stops asserting "no radar session"
1665
+ // over a reason span that says the device is unreachable, and the automation stops spending
1666
+ // attempts on hardware that is not there. Not a recovery (nothing came back), so _recoveredAt
1667
+ // stays and a later no_session on this device is judged against the real last recovery.
1668
+ retireNoSession() {
1669
+ if (!this.sessionEnded)
1670
+ return;
1671
+ this.sessionEnded = false;
1672
+ this._latchRetired = true;
1673
+ this.emit("session-ended", false);
1674
+ this.emit("auto-rearm", this.autoRearming);
1675
+ }
1676
+ // Auto-re-arm: the recovery the retry loops deliberately do not perform. The stream proxy
1677
+ // never re-enables (enabling binds an identity and mutates device state; a read loop must
1678
+ // not, and a machine consumer holding /stream must never arm a device by holding it), so a
1679
+ // dead session used to sit at "retrying…" until a human found the Reconnect button. This is
1680
+ // that button pressing itself, under conditions that keep the consent story intact:
1681
+ // - only on a diagnosed no_session (the one state a re-enable is known to fix, proven
1682
+ // safe to arm by the device's own socket table — nobody's live session gets clobbered);
1683
+ // - only from a VISIBLE tab (a human is looking; a background tab must not re-arm a device
1684
+ // someone deliberately let idle out, and an MCP-only dashboard has no tab at all);
1685
+ // - never during an ambiguous multi-device pick (that decision belongs to the human);
1686
+ // - at most once per spacing window, and it gives up for the outage after enough failed
1687
+ // broadcasts that the next one clearly needs a human (the button stays on screen).
1688
+ // Cadence comes free: noteNoSession fires the first attempt, pollHealth's 2s tick drives
1689
+ // the rest — including the catch-up attempt when a hidden tab becomes visible again.
1690
+ async maybeAutoRearm() {
1691
+ if (!this.sessionEnded || this.stopped || this.autoRearming || this.enabling)
1692
+ return;
1693
+ // Strict false, not falsy: null means no /health reply has answered yet, and an
1694
+ // unanswered consent question refuses the same as a "no" (the server refuses the
1695
+ // ?auto=1 too, but this keeps the tab from even asking).
1696
+ if (this.autoRearmSuppressed || this.selfArmBlocked !== false)
1697
+ return;
1698
+ if (this.conn.state === "connected")
1699
+ return;
1700
+ if (this.needsDevicePick)
1701
+ return;
1702
+ if (typeof document !== "undefined" && document.visibilityState !== "visible")
1703
+ return;
1704
+ if (this.autoRearmExhausted)
1705
+ return;
1706
+ const now = this.rearmClock();
1707
+ if (now - this._autoRearmLastTs < AUTO_REARM_SPACING_MS)
1708
+ return;
1709
+ this._autoRearmLastTs = now;
1710
+ this.autoRearming = true;
1711
+ // The outage this attempt belongs to (see _noSessionGen).
1712
+ const gen = this._noSessionGen;
1713
+ try {
1714
+ // Inside the try so a throwing "auto-rearm" subscriber cannot leave the latch stuck
1715
+ // true forever (the finally below always clears it).
1716
+ this.emit("auto-rearm", true);
1717
+ // Budget is spent against reconnect()'s own reported outcome. "no_answer" (the
1718
+ // dashboard's own port unreachable — reconnectInner CATCHES that fetch failure, so it
1719
+ // never surfaces as a rejection here) must count: it is the mode where every future
1720
+ // attempt is equally doomed, and without spending budget a dead dashboard would fire
1721
+ // /enable every spacing window forever under a header promising it will keep trying.
1722
+ const outcome = await this.reconnect(true);
1723
+ // An armed reply retires the no-session state inside reconnect() itself (so a manual
1724
+ // press does it too) and stamps the recovery; the budget is NOT refilled by the arm. An
1725
+ // arm that holds refills it at the next outage, an arm the session dies out of within
1726
+ // the spacing window is a flap and counts against it (see noteNoSession).
1727
+ //
1728
+ // Failures are gated on the SAME outage still standing: a refutation that landed
1729
+ // mid-flight ended the outage this attempt belonged to, and its late verdict must not
1730
+ // shrink the NEXT outage's budget — including a next outage that latched during the
1731
+ // flight, which the boolean alone would mistake for this one.
1732
+ // A retired latch is the same outage paused (see _latchRetired), so a verdict landing inside
1733
+ // that window still belongs to it; without this a repeating unplug/replug with a dead session
1734
+ // never reached the cap because every verdict landed while retired.
1735
+ if (outcome !== "armed" && outcome !== "in_flight" && (this.sessionEnded || this._latchRetired) && gen === this._noSessionGen)
1736
+ this._autoRearmFails++;
1737
+ }
1738
+ catch {
1739
+ // Defensive only: the real reconnect() resolves on every path today. A future path
1740
+ // that rejects still must not escape the fire-and-forget call sites or retry free.
1741
+ if ((this.sessionEnded || this._latchRetired) && gen === this._noSessionGen)
1742
+ this._autoRearmFails++;
1743
+ }
1744
+ finally {
1745
+ this.autoRearming = false;
1746
+ this.emit("auto-rearm", false);
1747
+ }
1748
+ }
1749
+ // The Reconnect Radar button — and the auto-re-arm, which is this button pressing itself.
1750
+ // Re-arms the device through the same /enable the picker uses, and reports what came back:
1751
+ // the route already words every failure it can hit, down to naming a missing debug build,
1752
+ // and a user who just pressed a button is owed that answer instead of a dashboard that
1753
+ // keeps saying "waiting for device…" whether the press worked or not.
1754
+ //
1755
+ // Single-flight across BOTH initiators: a manual press mid-auto-attempt (or the reverse)
1756
+ // must not launch a second concurrent /enable — two flights double-broadcast and interleave
1757
+ // their pin/resync answers. `enabling` is store state (emitted "enabling") so the header's
1758
+ // button disables and relabels off the same latch that refuses the overlap.
1759
+ // The outcome the auto-re-arm budget is spent against. "armed" is the device's own yes;
1760
+ // "refused" is a completed reply saying no (the enable flow's worded failures); "no_answer"
1761
+ // is a request that never produced a reply at all — the dashboard's own port unreachable —
1762
+ // which must still spend budget or a dead dashboard fires /enable every spacing window
1763
+ // forever. A latch-refused overlap reports "in_flight" so a caller never mistakes it for a
1764
+ // completed attempt.
1765
+ // `auto` marks an UNATTENDED attempt (the automatic recovery, not a press). The server reads
1766
+ // it to refuse the destructive screen teardown a first /enable can otherwise take — killing a
1767
+ // live cast and deleting saved recordings with nobody pressing anything.
1768
+ async reconnect(auto = false) {
1769
+ if (this.enabling)
1770
+ return "in_flight";
1771
+ this.enabling = true;
1772
+ try {
1773
+ // Emits inside the try so a throwing subscriber cannot leave the latch stuck true —
1774
+ // the finally always clears it. visibleEnableError derives from `enabling` (a flight
1775
+ // suppresses the previous attempt's answer), so the latch flip must republish it: the
1776
+ // header subscribes the reason span to "enable-error" and re-reads only on its own
1777
+ // event.
1778
+ this.emit("enabling", true);
1779
+ this.emit("enable-error", this.visibleEnableError);
1780
+ return await this.reconnectInner(auto);
1781
+ }
1782
+ finally {
1783
+ this.enabling = false;
1784
+ this.emit("enabling", false);
1785
+ this.emit("enable-error", this.visibleEnableError);
1786
+ }
1787
+ }
1788
+ // Spend the rest of this outage's automatic budget at once. Used when a reply says no future
1789
+ // unattended attempt can succeed; the "auto-rearm" emit is what re-renders the header's
1790
+ // give-up wording (that hook re-reads only on its own event).
1791
+ exhaustAutoRearm() {
1792
+ if (this.autoRearmExhausted)
1793
+ return;
1794
+ this._autoRearmFails = AUTO_REARM_MAX_FAILS;
1795
+ this._autoRearmTerminal = true;
1796
+ this.emit("auto-rearm", this.autoRearming);
1797
+ }
1798
+ // Retire the session-ended state and stamp the recovery. Called only from evidence that the
1799
+ // device is actually there — an observed connected report, or an /enable that came back
1800
+ // armed. Deliberately NOT the budget and NOT the spacing clock: whether this recovery earns
1801
+ // the next outage a fresh budget and an immediate attempt is decided when that outage
1802
+ // arrives, by whether this one held (noteNoSession). Resetting both here made the budget
1803
+ // strictly per-outage with nothing counting outages, so a session that died seconds after
1804
+ // every arm was resurrected on every cycle with no give-up reachable. The "auto-rearm" emit
1805
+ // is what lets the header's give-up wording clear (that hook re-reads only on its own event).
1806
+ refuteSessionEnded() {
1807
+ if (!this.sessionEnded) {
1808
+ // A recovery observed while the latch is RETIRED (undiagnosed, then the stream connected
1809
+ // or a press armed) is still the end of that outage: stamp it, so the next no_session is
1810
+ // judged against a real recovery instead of resuming a count from hours ago, and a session
1811
+ // that dies again within the window after it is still read as a flap. Without this the
1812
+ // retired flag outlived the recovery and a fresh outage inherited an exhausted budget.
1813
+ if (this._latchRetired) {
1814
+ this._latchRetired = false;
1815
+ this._recoveredAt = this.rearmClock();
1816
+ }
1817
+ return;
1818
+ }
1819
+ this.sessionEnded = false;
1820
+ this._recoveredAt = this.rearmClock();
1821
+ this._latchRetired = false;
1822
+ this.emit("session-ended", false);
1823
+ this.emit("auto-rearm", this.autoRearming);
1824
+ }
1825
+ async reconnectInner(auto) {
1313
1826
  // Read the epoch BEFORE the request, because the reply describes the outage the user pressed
1314
1827
  // during, not whatever is true when it lands. The failure path is slow (rebuild the forward,
1315
1828
  // broadcast, a ping with its own multi-second ceiling, then a process probe), which is easily long
1316
1829
  // enough for a boundary to pass, and stamping the later epoch would file this reason against an
1317
1830
  // outage it says nothing about.
1318
1831
  const epoch = this._outageEpoch;
1832
+ // And the diagnosed outage this attempt belongs to (see _noSessionGen), for the terminal
1833
+ // refusal below: the same "its own outage only" rule the per-unit budget follows.
1834
+ const gen = this._noSessionGen;
1319
1835
  // Whether THIS press's reply advance performed the real-switch resync. Captured at the
1320
1836
  // advance itself, not before the fetch: a poll can observe an unrelated switch during the
1321
1837
  // multi-second /enable flight, and deciding from a pre-fetch baseline would count that
1322
1838
  // poll's resync as this press's and skip a resync nobody performed for it. Same
1323
1839
  // before-and-after-an-await hazard the epoch capture above avoids.
1324
1840
  let replySwitched = false;
1841
+ let outcome;
1325
1842
  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?");
1843
+ const r = await fetch(auto ? "/enable?auto=1" : "/enable", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
1844
+ 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
1845
  // The reply names the device this press pinned, and the route pins before it arms, so a
1329
1846
  // failing press can itself move the pin (first sight, or a switch to freshly attached
1330
1847
  // hardware). Advance the baseline from the reply BEFORE the reason is written: the later
@@ -1334,8 +1851,23 @@ class Store {
1334
1851
  if (serial !== null)
1335
1852
  this.checkSerialEdge(serial);
1336
1853
  replySwitched = serial !== null && beforeAdvance !== null && serial !== beforeAdvance;
1854
+ outcome = enabled ? "armed" : "refused";
1337
1855
  if (enabled) {
1338
1856
  this.clearEnableError();
1857
+ // An armed reply is the device itself answering (the route verifies with a ping before
1858
+ // reporting enabled), so it retires the no-session state immediately rather than
1859
+ // leaving the header promising a retry for the seconds until a poll observes the
1860
+ // recovery. Here, not in the auto-re-arm caller, so a MANUAL press retires it too.
1861
+ // Deliberately NOT setConn("connected"): the stream has its own reconnect to do, and
1862
+ // only an observation of the WIRE may claim "live".
1863
+ this.refuteSessionEnded();
1864
+ // With sessionEnded retired, the header falls back to conn.msg verbatim — which is
1865
+ // still the outage diagnosis this reply just refuted. Replace the MESSAGE only, never
1866
+ // the state: "connected" stays the wire's claim to make. Worded as the recovery step it
1867
+ // is, distinct from pollHealth's generic "reconnecting…" (the dashboard-unreachable
1868
+ // wording), so the interim frame reads as progress and not as a new problem.
1869
+ if (this.conn.state !== "connected")
1870
+ this.setConn(this.conn.state, "re-enabled, reconnecting the stream…");
1339
1871
  }
1340
1872
  else {
1341
1873
  // Its own field, not conn.msg: pollHealth runs every 2s and its own "device offline"
@@ -1346,16 +1878,32 @@ class Store {
1346
1878
  // frame that arrived while this request was in flight, so it is kept rather than thrown
1347
1879
  // away. The epoch stamp is what stops it being shown for some later outage instead.
1348
1880
  this.enableError = error;
1881
+ this.enableInstructs = instructs;
1349
1882
  this._enableErrorEpoch = epoch;
1350
1883
  this.emit("enable-error", this.visibleEnableError);
1884
+ // A marked refusal is terminal for the automation: the route refuses every later
1885
+ // unattended attempt the same way (the process may not self-arm; the pin moved to
1886
+ // different hardware and only a press may adopt it). Spending the remaining budget on
1887
+ // attempts known to fail would keep the header promising a retry for two more minutes
1888
+ // beside an error span already saying to press Reconnect — two adjacent instructions
1889
+ // pointing different ways. Exhaust the outage's budget now, so the header reads "gave
1890
+ // up" from this reply on, with the reason span saying to press Reconnect. The budget
1891
+ // still refills on recovery.
1892
+ // Gated on the latch like every other late verdict (see maybeAutoRearm): a refutation
1893
+ // that landed mid-flight ended the outage this reply belongs to, and spending the NEXT
1894
+ // outage's budget on it would render "gave up" over an outage with no attempt made.
1895
+ if (refusal !== null && (this.sessionEnded || this._latchRetired) && gen === this._noSessionGen)
1896
+ this.exhaustAutoRearm();
1351
1897
  }
1352
1898
  }
1353
1899
  catch {
1354
1900
  // The dashboard's own port is unreachable, so this press produced no answer about the device.
1355
1901
  // conn reports the dashboard being unreachable, but the reason line is a separate field and
1356
1902
  // 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.
1903
+ // blaming the device for a request that never reached it. The caller still learns this
1904
+ // happened through the returned outcome — clearing the reason must not read as success.
1358
1905
  this.clearEnableError();
1906
+ outcome = "no_answer";
1359
1907
  }
1360
1908
  this.pollHealth();
1361
1909
  this.pollProfile();
@@ -1364,6 +1912,7 @@ class Store {
1364
1912
  // across a real switch; a second open/close/open here would only churn the backfill.
1365
1913
  if (!replySwitched)
1366
1914
  this.resyncStream();
1915
+ return outcome;
1367
1916
  }
1368
1917
  // Kill the dashboard server from the header button. The X-Radar-Dashboard header is the
1369
1918
  // CSRF guard the /shutdown route requires (a foreign origin's fetch cannot set it without a