@slack/radar-mcp 1.17.0 → 1.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource } from "./registry.js";
1
+ import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource } from "./registry.js";
2
2
  // Logcat-scale retention. At the live firehose (~400+ events/sec on the unified Live tab) a
3
3
  // small ring recycles in seconds, so a rare signal (a once-per-5s heartbeat) gets evicted
4
4
  // before you can filter for it. Android Studio / Flipper keep the whole session and filter
@@ -112,12 +112,76 @@ class Store {
112
112
  // (adb not on PATH, server down), which is distinct from "zero devices attached". The header
113
113
  // chip renders this differently so the user knows to check adb, not plug in a phone.
114
114
  devicesError = false;
115
- // Last device-select failure text (an /enable 409 or error), or null when the pick succeeded.
116
- // Distinct from devicesError (adb itself failed) and from conn: a device-select failure used to
117
- // ride conn via setConn("waiting", …), but any healthy pollHealth flips conn back to connected
118
- // within 2s and the message vanished before the user read it. This field is owned by
119
- // selectDevice, survives the health poll, and clears only on a successful pick.
115
+ // Why the last device PICK failed, or null when it succeeded. Owned by selectDevice alone.
116
+ // Distinct from devicesError (adb itself failed) and from conn: a pick failure used to ride conn
117
+ // via setConn("waiting", …), but any pollHealth flips conn within 2s and the message vanished
118
+ // before the user read it. A failed pick is an unfulfilled request for a SPECIFIC device, so it
119
+ // is invalidated by one thing only, a later pick that works, and nothing about device health
120
+ // refutes it. It therefore renders whether or not the dashboard is connected.
120
121
  deviceError = null;
122
+ // Why the last Reconnect press did not arm the device, or null when it did. Owned by reconnect().
123
+ //
124
+ // KEPT SEPARATE FROM deviceError on purpose: a pick failure is about a device the user named,
125
+ // this one is about getting connected at all, and they are invalidated by different events.
126
+ //
127
+ // NOT cleared by any POLL trying to decide whether the reason is still TRUE, deliberately. Five
128
+ // such rules were tried and each lost information or lied, because inference cannot answer that:
129
+ // "connected" only means a device frame arrived within 6 seconds, which refutes "no debug build is
130
+ // running" while refuting nothing at all about "adb: device offline" or an ambiguous pick, and this
131
+ // same field carries all of them.
132
+ //
133
+ // The answerable question is WHICH OUTAGE the reason belongs to, so it is stamped with the outage
134
+ // epoch it was produced in and `visibleEnableError` shows it only during that same epoch. A reason
135
+ // therefore cannot surface in a later outage it does not explain, while a diagnostic still relevant
136
+ // to the CURRENT outage keeps showing for as long as that outage lasts.
137
+ //
138
+ // Four things DO clear it outright, via clearEnableError. Two are not truth judgements: a press
139
+ // whose request never completed has no answer to report, and a REAL change of bound device, one
140
+ // non-null serial to a different one, retires a reason that described different hardware (the
141
+ // observed serial edge and the pick path both perform that clear). Two ARE truth judgements,
142
+ // allowed because they come from a completed action's own answer rather than inference: a
143
+ // successful arm refutes the reason, reconnect and pick alike, whatever the serial did; and a
144
+ // later failed pick supersedes it, because the newest action owns the header. First sight of a
145
+ // serial is not a change of device and keeps the reason. A press does not erase its own answer:
146
+ // the /enable reply echoes the pinned serial, and reconnect() advances the baseline from the
147
+ // reply before the reason is written, so the follow-up poll observes no edge.
148
+ enableError = null;
149
+ _enableErrorEpoch = -1;
150
+ // Counts outages: bumped by setConn when the connection leaves a CONFIRMED connected state.
151
+ _outageEpoch = 0;
152
+ // Pieces of positive evidence that the current connected state is real, at most one per
153
+ // proofSpacingMs. Reset the moment the connection drops. Two are required before leaving "connected"
154
+ // counts as the end of an outage, so neither one flaky success nor one burst of frames can split a
155
+ // continuing outage in two.
156
+ _connProof = 0;
157
+ _lastProofTs = 0;
158
+ // Minimum gap between two pieces of evidence, matching the health poll cadence so the two-proof
159
+ // rule really is the mirror of the two-miss rule. Read-only: tests exercise the floor by driving
160
+ // connClock, never by retuning or disabling the floor itself.
161
+ proofSpacingMs = POLL_HEALTH_MS;
162
+ // The clock the CONNECTION logic reads: stream freshness and the proof spacing floor. Injectable so
163
+ // a test can represent observations that are genuinely seconds apart without sleeping, which is the
164
+ // only way to exercise the spacing floor rather than switching it off. Deliberately NOT used by the
165
+ // cache and rate windows further down: those have unrelated timings, and overriding one clock must
166
+ // not silently retune them.
167
+ connClock = () => Date.now();
168
+ // The reconnect reason the header may actually show: only while disconnected, and only for the
169
+ // outage that produced it. Both conditions in one place so the component cannot get it half right.
170
+ get visibleEnableError() {
171
+ if (this.conn.state === "connected")
172
+ return null;
173
+ return this._enableErrorEpoch === this._outageEpoch ? this.enableError : null;
174
+ }
175
+ // Drop the reason outright. Used where the reason is not merely from another outage but describes a
176
+ // question that was never answered, or a device we are no longer bound to. The epoch stamp handles
177
+ // "belongs to a different outage"; this handles "belongs to nothing".
178
+ clearEnableError() {
179
+ if (this.enableError === null && this._enableErrorEpoch === -1)
180
+ return;
181
+ this.enableError = null;
182
+ this._enableErrorEpoch = -1;
183
+ this.emit("enable-error", this.visibleEnableError);
184
+ }
121
185
  // Capture-source names the device declares on ping (seam builds). null = old build with no
122
186
  // discovery, in which case every tab shows (today's behavior). Emitted as "sources" on change.
123
187
  deviceSources = null;
@@ -250,8 +314,10 @@ class Store {
250
314
  subscriberCount(evt) {
251
315
  return this._subs[evt]?.size ?? 0;
252
316
  }
253
- // Test-only: reset all mutable state to construction defaults. Centralized so the reset list
254
- // cannot drift from the fields (a hand-maintained reset in the test omitted half of them).
317
+ // Test-only: reset data and connection state to construction defaults. Centralized so the
318
+ // reset list cannot drift from the fields (a hand-maintained reset in the test omitted half of
319
+ // them). Deliberately NOT reset: subscribers, live timers and stream handles (start() and
320
+ // openStream() own those lifecycles), and _tabId, which identifies the page for its whole life.
255
321
  _resetForTest() {
256
322
  this.spec = { blank: true, viz: [] };
257
323
  this.conn = { state: "waiting", msg: "connecting…" };
@@ -264,6 +330,12 @@ class Store {
264
330
  this.selectedDevice = null;
265
331
  this.devicesError = false;
266
332
  this.deviceError = null;
333
+ this.enableError = null;
334
+ this._enableErrorEpoch = -1;
335
+ this._outageEpoch = 0;
336
+ this._connProof = 0;
337
+ this._lastProofTs = 0;
338
+ this.connClock = () => Date.now();
267
339
  this.deviceSources = null;
268
340
  this.cache = [];
269
341
  this.cacheKeys = new Set();
@@ -290,6 +362,10 @@ class Store {
290
362
  this._backfillToken = 0;
291
363
  this._dropped = false;
292
364
  this._lastSerial = null;
365
+ // Cancel rather than just forget: a rAF queued before the reset would otherwise fire after
366
+ // it and bump feedVersion on the supposedly fresh store (mirrors clearRecords).
367
+ if (this._rafHandle != null)
368
+ cancelAnimationFrame(this._rafHandle);
293
369
  this._rafPending = false;
294
370
  this._rafHandle = null;
295
371
  }
@@ -415,6 +491,32 @@ class Store {
415
491
  }
416
492
  this.closeStream();
417
493
  }
494
+ // Record one piece of positive evidence that the device is really there, at most one per
495
+ // proofSpacingMs. Two of these are what let a reconnection count as having ENDED an outage.
496
+ //
497
+ // Called ONLY from the two places that actually OBSERVE the device: a device-kind stream frame, and
498
+ // a /health reply saying device true. Not from setConn, and specifically not from pollHealth's
499
+ // fresh-frame fast path, which re-asserts a single stale frame every 2s and could therefore bank
500
+ // both proofs from ONE frame, ending an outage on evidence that never repeated. A busy device still
501
+ // earns its proofs from the real frames themselves, so restricting counting to observation costs it
502
+ // nothing.
503
+ //
504
+ // Spacing matters as much as the count: two consecutive health MISSES are poll-cadence apart by
505
+ // construction, while two SSE frames can land in the same tick, and an EventSource flushing a
506
+ // backlog on reconnect does exactly that. Without the floor a burst passes for a recovery.
507
+ //
508
+ // Skipped while an ambiguous multi-device pick is outstanding, for the same reason setConn refuses
509
+ // to call that state connected: frames can ride a stale forward from a prior pin, so they are not
510
+ // evidence about the device the user has not chosen yet.
511
+ noteDeviceProof() {
512
+ if (this.needsDevicePick)
513
+ return;
514
+ const now = this.connClock();
515
+ if (now - this._lastProofTs < this.proofSpacingMs)
516
+ return;
517
+ this._connProof++;
518
+ this._lastProofTs = now;
519
+ }
418
520
  setConn(state, msg) {
419
521
  // Unpinned multi-device is never "connected": frames can ride a stale forward from a prior
420
522
  // pin and flip the dot green while the per-device surfaces (DB run-as) are broken by the
@@ -426,7 +528,29 @@ class Store {
426
528
  }
427
529
  if (this.conn.state === state && this.conn.msg === (msg || ""))
428
530
  return;
531
+ const wasConnected = this.conn.state === "connected";
429
532
  this.conn = { state, msg: msg || "" };
533
+ // An outage ENDS here, and only a CONFIRMED connection counts as having ended one: two pieces of
534
+ // evidence, each at least proofSpacingMs apart. Both halves matter. The COUNT alone was not
535
+ // enough, because two frames can arrive in one tick and a reconnect backlog burst does exactly
536
+ // that, so a burst passed for a recovery. The SPACING is what makes this a real mirror of the two
537
+ // consecutive misses required before the UI says "device offline", which are poll-cadence apart by
538
+ // construction. Without both, a blip inside a continuing outage splits it in two and permanently
539
+ // orphans the reason the user was just given, for the rest of the outage they are still in.
540
+ if (wasConnected && state !== "connected") {
541
+ if (this._connProof >= 2)
542
+ this._outageEpoch++;
543
+ this._connProof = 0;
544
+ // Restart the spacing clock at the drop, so the first proof of the NEXT recovery has to be
545
+ // earned after it rather than qualifying instantly off a gap that is really the outage itself.
546
+ this._lastProofTs = this.connClock();
547
+ }
548
+ // visibleEnableError is derived from conn, so a conn change can change what the header should
549
+ // show without anything touching enableError itself. Subscribers re-read only on their OWN
550
+ // event (see useStoreValue), so this emit is what keeps the rendered reason honest; without it
551
+ // the message stayed on screen after the dashboard reconnected. Conn changes are already
552
+ // deduped by the early return above, so this is at most one extra emit per real change.
553
+ this.emit("enable-error", this.visibleEnableError);
430
554
  this.emit("conn", this.conn);
431
555
  }
432
556
  async pollSpec() {
@@ -577,12 +701,25 @@ class Store {
577
701
  live = false; // server-replayed history: never alerts/counts twice
578
702
  if (!STREAM_KINDS.includes(f.type))
579
703
  return;
580
- this._lastEventTs = Date.now();
581
- // A live frame proves the stream healed itself (the browser EventSource auto-reconnects on a
582
- // transient blip). Clear _dropped here so recovered() does NOT later tear down this healthy
583
- // stream and re-open it: recovered() should only fire when the stream did NOT self-heal.
584
- this._dropped = false;
585
- this.setConn("connected", "");
704
+ // Only a frame FROM THE DEVICE is evidence the device is connected. Logs are host-side: an
705
+ // `adb logcat` child of the dashboard keeps printing other packages' lines with Radar dead and
706
+ // the Slack app not even running, and each one used to stamp the freshness clock and assert
707
+ // "connected". That parked pollHealth on its <6s fast path forever, so the header read "● live"
708
+ // against a device whose Radar server was gone, and the Reconnect Radar button -- which renders
709
+ // only while NOT connected -- never appeared, leaving no way to re-arm from the dashboard.
710
+ // Frames still reach the cache and the feed below either way; this only governs what the
711
+ // connection state is allowed to claim.
712
+ if (DEVICE_STREAM_KINDS.includes(f.type)) {
713
+ this._lastEventTs = this.connClock();
714
+ // A frame from the device IS an observation of it, so it is where a busy device earns the
715
+ // evidence that lets a recovery end an outage.
716
+ this.noteDeviceProof();
717
+ // A live frame proves the stream healed itself (the browser EventSource auto-reconnects on a
718
+ // transient blip). Clear _dropped here so recovered() does NOT later tear down this healthy
719
+ // stream and re-open it: recovered() should only fire when the stream did NOT self-heal.
720
+ this._dropped = false;
721
+ this.setConn("connected", "");
722
+ }
586
723
  const ev = f.event || {};
587
724
  ev._type = f.type;
588
725
  const isNew = this.cacheFrame(f.type, ev);
@@ -842,11 +979,20 @@ class Store {
842
979
  checkSerialEdge(serial) {
843
980
  if (serial == null || serial === this._lastSerial)
844
981
  return;
845
- // Feed clear + stream resync only on a REAL switch (serial -> other serial): a null->serial
846
- // FIRST pin has no stale feed to drop, it just records the baseline.
982
+ // Feed clear + stream resync + reason retirement only on a REAL switch (serial -> other
983
+ // serial): a null->serial FIRST pin has no stale feed to drop, it just records the baseline.
984
+ // The reason survives the first pin because a failing press is itself what produces a pin.
985
+ // Presses also cover their own re-pins: the /enable reply echoes the pinned serial and
986
+ // reconnect() advances the baseline through this method BEFORE writing the reason, so the
987
+ // clear below can only retire a reason that predates the edge -- one describing the
988
+ // previously bound device -- never the answer a press is about to put on screen.
847
989
  if (this._lastSerial !== null) {
848
990
  this.clearDeviceCaches();
849
991
  this.resyncStream();
992
+ // A reconnect reason is about the device that was bound when it was produced, so a change of
993
+ // bound device retires it. Without this, device A's "no debug build is running" explains
994
+ // device B's outage, because the epoch counts outages and a switch is not one.
995
+ this.clearEnableError();
850
996
  }
851
997
  this._lastSerial = serial;
852
998
  // The DB tab, unlike the feed, DOES carry stale state across a first pin: it loaded unpinned
@@ -876,9 +1022,13 @@ class Store {
876
1022
  this.emit("sources", names);
877
1023
  }
878
1024
  async pollHealth() {
879
- if (Date.now() - this._lastEventTs < 6000) {
1025
+ if (this.connClock() - this._lastEventTs < 6000) {
880
1026
  this._healthMisses = 0;
881
1027
  this.recovered();
1028
+ // Deliberately does NOT count connection proof. This path re-reads the SAME _lastEventTs every
1029
+ // 2s, so a single frame would otherwise bank both proofs and end an outage on evidence that
1030
+ // never repeated. The frame that set _lastEventTs already counted itself, in onFrame, which is
1031
+ // what keeps a busy device able to confirm a recovery.
882
1032
  this.setConn("connected", "");
883
1033
  return;
884
1034
  }
@@ -896,6 +1046,9 @@ class Store {
896
1046
  this.updateSources(Array.isArray(h.sources) ? h.sources : null);
897
1047
  this._healthMisses = 0;
898
1048
  this.recovered();
1049
+ // A real device:true reply is the other genuine observation, and the one a QUIET device
1050
+ // recovers on.
1051
+ this.noteDeviceProof();
899
1052
  this.setConn("connected", "");
900
1053
  }
901
1054
  else if (++this._healthMisses >= 2) {
@@ -978,34 +1131,85 @@ class Store {
978
1131
  /* transient; next poll retries */
979
1132
  }
980
1133
  }
1134
+ // Read an /enable reply into "did Radar arm, and if not, why". The STATUS CODE cannot be the
1135
+ // test: only an ambiguous device is a 409, while every other failure the route reports -- a dead
1136
+ // adb forward, a broadcast adb refused, a broadcast that landed on a device whose server never
1137
+ // answered the ping -- arrives as a 200 whose body says enabled:false and carries the reason. So
1138
+ // the body is the test. Anything that is not an explicit enabled:true counts as not armed,
1139
+ // because the one thing worse than a vague reason is a UI reporting success on an enable that
1140
+ // did nothing.
1141
+ //
1142
+ // A reply that will not PARSE is a third case, and it must not be worded like the second. Not
1143
+ // being able to read the answer says nothing about the device, so it does not get to blame one.
1144
+ // That is the repo's stated convention, in CLAUDE.md under the inconclusive-probe section: "A
1145
+ // probe that cannot always tell must say so in its return type. Never collapse 'could not tell'
1146
+ // into 'no'." So this reports the read failure, and the caller's device-blaming fallback is
1147
+ // reserved for a reply that parsed and simply carried no reason of its own.
1148
+ async readEnableResult(r, fallback) {
1149
+ const body = (await r.json().catch(() => null));
1150
+ if (body === null) {
1151
+ return {
1152
+ enabled: false,
1153
+ error: "Could not read the dashboard reply to this request. Try again.",
1154
+ serial: null,
1155
+ };
1156
+ }
1157
+ const error = typeof body.error === "string" && body.error ? body.error : fallback;
1158
+ const serial = typeof body.device_serial === "string" && body.device_serial ? body.device_serial : null;
1159
+ return { enabled: body.enabled === true, error, serial };
1160
+ }
981
1161
  // Pin a specific device for the session. POSTs the same /enable the reconnect button uses,
982
1162
  // with the chosen serial; on success it runs the same post-enable refresh as reconnect() so
983
1163
  // the UI does not wait for the next poll. On a REAL switch (target serial differs from the one
984
1164
  // last seen) it clears the old device's caches and resyncs HERE, deterministically, rather than
985
1165
  // leaning on pollHealth's serial edge: that edge is starved by the <6s fresh-frame fast path
986
1166
  // while the new stream is already delivering frames, so it may never fire. Same-serial reselect
987
- // skips the clear (nothing stale). A 409/error is surfaced on deviceError (the device chip shows
988
- // it) rather than via conn, which a healthy health poll would overwrite within 2s; the device
989
- // list is refreshed so the dropdown is current and the user can pick a valid device.
1167
+ // skips the clear (nothing stale). A failed pick is surfaced on deviceError (the device chip
1168
+ // shows it) rather than via conn, which a healthy health poll would overwrite within 2s; the
1169
+ // device list is refreshed so the dropdown is current and the user can pick a valid device.
990
1170
  async selectDevice(serial) {
991
1171
  try {
992
1172
  const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
993
- if (!r.ok && r.status === 409) {
994
- const body = await r.json().catch(() => null);
1173
+ // Any reply that did not arm the device takes the failure path, not just the 409. A 200 whose
1174
+ // body says enabled:false used to fall through here as a success: it cleared deviceError,
1175
+ // recorded the serial as switched-to, and resynced a stream against a device holding no
1176
+ // Radar server, so a pick that plainly failed rendered as a pick that worked.
1177
+ const { enabled, error, serial: confirmed } = await this.readEnableResult(r, "Selecting that device did not arm Radar on it.");
1178
+ if (!enabled) {
995
1179
  // Surface the failure on the device chip itself, not via conn: a healthy pollHealth flips
996
1180
  // conn back to connected within 2s and would erase a setConn("waiting", …) message before
997
1181
  // the user reads it. deviceError is owned here and survives the health poll.
998
- this.deviceError = (body && body.error) ? String(body.error) : "device select failed";
1182
+ //
1183
+ // _lastSerial is deliberately NOT advanced HERE, and the two halves of that split matter.
1184
+ // The route pins the device before it forwards or broadcasts, so a failed enable divides in
1185
+ // two: if the pin never landed, nothing switched and a later successful pick of the same
1186
+ // serial must still count as a switch and clear the old device's caches. If the pin DID land
1187
+ // and only the arming failed, the fetchDevices() below reads the server's pinned serial and
1188
+ // checkSerialEdge advances the baseline and clears the caches from there. So the baseline
1189
+ // tracks what the SERVER confirmed, never what this click hoped for.
1190
+ //
1191
+ // The pick is the user's LATEST action, so its answer wins the header: retire any standing
1192
+ // reconnect reason, or the chip suppression in the header would hide this click's feedback
1193
+ // behind the older message.
1194
+ this.clearEnableError();
1195
+ this.deviceError = error;
999
1196
  this.emit("devices", this.devices);
1000
1197
  this.fetchDevices();
1001
1198
  return;
1002
1199
  }
1003
- // A successful pick clears any prior select failure.
1200
+ // A successful pick clears any prior enable failure.
1004
1201
  this.deviceError = null;
1005
1202
  this.emit("devices", this.devices);
1006
- if (serial !== this._lastSerial) {
1203
+ // The pick ARMED the device, which refutes any standing reconnect reason whatever the serial
1204
+ // did -- the same rule as a successful reconnect. Cleared here, inline, because advancing the
1205
+ // baseline below means checkSerialEdge sees no change and can never fire for this switch.
1206
+ this.clearEnableError();
1207
+ // The baseline tracks what the SERVER confirmed: the reply echo when present, the requested
1208
+ // serial only as the fallback for a reply without one. Same policy as reconnect's advance.
1209
+ const bound = confirmed ?? serial;
1210
+ if (bound !== this._lastSerial) {
1007
1211
  this.clearDeviceCaches();
1008
- this._lastSerial = serial;
1212
+ this._lastSerial = bound;
1009
1213
  // Resync the DB tab too: a first pick (null->serial) leaves it holding the failed
1010
1214
  // ambiguous /dbs; a real switch leaves it on the old device's databases.
1011
1215
  this.bumpDbSerial();
@@ -1039,25 +1243,65 @@ class Store {
1039
1243
  this.openStream();
1040
1244
  this.backfill();
1041
1245
  }
1246
+ // The Reconnect Radar button. Re-arms the device through the same /enable the picker uses, and
1247
+ // reports what came back: the route already words every failure it can hit, down to naming a
1248
+ // missing debug build, and a user who just pressed a button is owed that answer instead of a
1249
+ // dashboard that keeps saying "waiting for device…" whether the press worked or not.
1042
1250
  async reconnect() {
1251
+ // Read the epoch BEFORE the request, because the reply describes the outage the user pressed
1252
+ // during, not whatever is true when it lands. The failure path is slow (rebuild the forward,
1253
+ // broadcast, a ping with its own multi-second ceiling, then a process probe), which is easily long
1254
+ // enough for a boundary to pass, and stamping the later epoch would file this reason against an
1255
+ // outage it says nothing about.
1256
+ const epoch = this._outageEpoch;
1257
+ // Whether THIS press's reply advance performed the real-switch resync. Captured at the
1258
+ // advance itself, not before the fetch: a poll can observe an unrelated switch during the
1259
+ // multi-second /enable flight, and deciding from a pre-fetch baseline would count that
1260
+ // poll's resync as this press's and skip a resync nobody performed for it. Same
1261
+ // before-and-after-an-await hazard the epoch capture above avoids.
1262
+ let replySwitched = false;
1043
1263
  try {
1044
1264
  const r = await fetch("/enable", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
1045
- // 409 = ambiguous device (multiple attached, none picked). Surface the server's
1046
- // reason through the existing connection-status line so the user sees why enable
1047
- // did not connect, instead of a silent stall on "reconnecting…".
1048
- if (!r.ok && r.status === 409) {
1049
- const body = await r.json().catch(() => null);
1050
- if (body && body.error)
1051
- this.setConn("waiting", String(body.error));
1265
+ const { enabled, error, serial } = await this.readEnableResult(r, "Reconnect failed. Is a device attached with a debug build of the Slack app running?");
1266
+ // The reply names the device this press pinned, and the route pins before it arms, so a
1267
+ // failing press can itself move the pin (first sight, or a switch to freshly attached
1268
+ // hardware). Advance the baseline from the reply BEFORE the reason is written: the later
1269
+ // poll then observes no edge, so it cannot retire the very reason this reply carries. A
1270
+ // real switch still gets the full retirement of the OLD device's state via checkSerialEdge.
1271
+ const beforeAdvance = this._lastSerial;
1272
+ if (serial !== null)
1273
+ this.checkSerialEdge(serial);
1274
+ replySwitched = serial !== null && beforeAdvance !== null && serial !== beforeAdvance;
1275
+ if (enabled) {
1276
+ this.clearEnableError();
1277
+ }
1278
+ else {
1279
+ // Its own field, not conn.msg: pollHealth runs every 2s and its own "device offline"
1280
+ // message would erase the specific reason within seconds of the press that asked for it.
1281
+ //
1282
+ // Stamped with the outage it belongs to, and stored even if the dashboard has since gone
1283
+ // connected: a reply saying "adb: device offline" is not refuted by a 6-second-old stream
1284
+ // frame that arrived while this request was in flight, so it is kept rather than thrown
1285
+ // away. The epoch stamp is what stops it being shown for some later outage instead.
1286
+ this.enableError = error;
1287
+ this._enableErrorEpoch = epoch;
1288
+ this.emit("enable-error", this.visibleEnableError);
1052
1289
  }
1053
1290
  }
1054
1291
  catch {
1055
- /* ignore */
1292
+ // The dashboard's own port is unreachable, so this press produced no answer about the device.
1293
+ // conn reports the dashboard being unreachable, but the reason line is a separate field and
1294
+ // would otherwise keep showing the PREVIOUS press's answer, presenting it as this press's, and
1295
+ // blaming the device for a request that never reached it.
1296
+ this.clearEnableError();
1056
1297
  }
1057
1298
  this.pollHealth();
1058
1299
  this.pollProfile();
1059
1300
  this.pollSpec();
1060
- this.resyncStream();
1301
+ // checkSerialEdge already resynced the stream if THIS press's reply advanced the baseline
1302
+ // across a real switch; a second open/close/open here would only churn the backfill.
1303
+ if (!replySwitched)
1304
+ this.resyncStream();
1061
1305
  }
1062
1306
  // Kill the dashboard server from the header button. The X-Radar-Dashboard header is the
1063
1307
  // CSRF guard the /shutdown route requires (a foreign origin's fetch cannot set it without a
@@ -114,6 +114,30 @@ interface ShutdownDeps {
114
114
  export declare function shutdownDashboard(server: {
115
115
  close(cb?: () => void): void;
116
116
  }, deps?: ShutdownDeps): Promise<void>;
117
+ /**
118
+ * Arm Radar once, at dashboard boot, so a launch against a freshly restarted app does not land on
119
+ * "waiting for device" until the human finds the Reconnect button. Called by bin.ts from the listen
120
+ * callback, for the same reason startAutoCloseSweep is: only the process that actually WON the port
121
+ * may touch the device, so a second launcher that adopts a running dashboard never re-arms someone
122
+ * else's session.
123
+ *
124
+ * The work itself runs OFF the event loop entirely (see armDevice), because an
125
+ * attached-but-unauthorised or locked device can hold a single adb call at its 5 second ceiling,
126
+ * and a chain of them can run 15 seconds or more. A server that cannot answer meanwhile breaks
127
+ * the adopt path this file otherwise protects carefully: a second launcher hits EADDRINUSE,
128
+ * probes the loopback /spec with a 2 second timeout to recognise this dashboard, and declares
129
+ * the port foreign and exits if that probe does not answer.
130
+ *
131
+ * NOT routed through handleEnable, which is written around an HTTP response. Two of the steps it
132
+ * additionally performs really are no-ops in a fresh process (resetState and resetDbState only clear
133
+ * in-process fields that are already at their defaults), but two are NOT, and this is deliberately
134
+ * left as a known gap rather than claimed away: resetScreenState() kills orphaned device-side
135
+ * screenrecord processes left by a crashed prior dashboard, and the switched-device branch
136
+ * (cleanupPulledDatabases + logSession.restart) is gated on a serial inherited from the environment,
137
+ * so a boot carrying a stale ANDROID_SERIAL can legitimately be a switch. Pressing Reconnect still
138
+ * performs both. If a third step is ever needed here, extract the shared core instead of copying it.
139
+ */
140
+ export declare function armOnBoot(): void;
117
141
  /**
118
142
  * Start the periodic auto-close sweep. Called once by bin.ts AFTER a successful listen bind, not
119
143
  * from createServer, so importing this module (or spinning a throwaway server in a test) never