@slack/radar-mcp 1.21.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +114 -18
  2. package/dist/mcp/api-paths.d.ts +2 -2
  3. package/dist/mcp/api-paths.js +4 -19
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +210 -145
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/radar-export-get.d.ts +30 -0
  10. package/dist/mcp/radar-export-get.js +49 -0
  11. package/dist/mcp/radar-http.d.ts +22 -0
  12. package/dist/mcp/radar-http.js +61 -0
  13. package/dist/mcp/radar-response.d.ts +5 -1
  14. package/dist/mcp/radar-response.js +8 -3
  15. package/dist/mcp/session-backfill.js +3 -4
  16. package/dist/mcp/session-enable.d.ts +15 -0
  17. package/dist/mcp/session-enable.js +268 -19
  18. package/dist/mcp/snapshot.js +42 -26
  19. package/dist/mcp/sources-gate.js +6 -0
  20. package/dist/mcp/stale-dashboard.d.ts +23 -0
  21. package/dist/mcp/stale-dashboard.js +122 -0
  22. package/dist/mcp/switchboard-spool.d.ts +12 -0
  23. package/dist/mcp/switchboard-spool.js +107 -0
  24. package/dist/mcp/switchboard-tools.d.ts +9 -0
  25. package/dist/mcp/switchboard-tools.js +144 -6
  26. package/dist/mcp/test-cases.d.ts +14 -0
  27. package/dist/mcp/test-cases.js +77 -0
  28. package/dist/mcp/test-runs-tools.d.ts +8 -0
  29. package/dist/mcp/test-runs-tools.js +95 -0
  30. package/dist/mcp/tools.d.ts +4 -1
  31. package/dist/mcp/tools.js +101 -21
  32. package/dist/mcp/web-child-env.d.ts +4 -1
  33. package/dist/mcp/web-child-env.js +4 -1
  34. package/dist/shared/android.d.ts +44 -0
  35. package/dist/shared/android.js +234 -24
  36. package/dist/shared/constants.d.ts +9 -4
  37. package/dist/shared/constants.js +9 -4
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/ios-logs.d.ts +10 -0
  41. package/dist/shared/ios-logs.js +91 -0
  42. package/dist/shared/ios.d.ts +25 -2
  43. package/dist/shared/ios.js +157 -3
  44. package/dist/{web → shared}/log-session.d.ts +45 -31
  45. package/dist/shared/log-session.js +300 -0
  46. package/dist/shared/logcat-capture.js +17 -1
  47. package/dist/shared/radar-request-raw.d.ts +7 -0
  48. package/dist/shared/radar-request-raw.js +89 -0
  49. package/dist/shared/radar-token.d.ts +25 -0
  50. package/dist/shared/radar-token.js +164 -0
  51. package/dist/shared/stream.d.ts +3 -0
  52. package/dist/shared/stream.js +107 -15
  53. package/dist/shared/switchboard-host-store.d.ts +21 -0
  54. package/dist/shared/switchboard-host-store.js +166 -0
  55. package/dist/shared/switchboard-note.d.ts +15 -0
  56. package/dist/shared/switchboard-note.js +92 -0
  57. package/dist/shared/switchboard-report-file.d.ts +5 -0
  58. package/dist/shared/switchboard-report-file.js +26 -0
  59. package/dist/shared/switchboard-report.d.ts +20 -0
  60. package/dist/shared/switchboard-report.js +406 -0
  61. package/dist/shared/switchboard.d.ts +111 -2
  62. package/dist/shared/switchboard.js +436 -3
  63. package/dist/shared/transport.d.ts +49 -3
  64. package/dist/shared/version.d.ts +2 -0
  65. package/dist/shared/version.js +18 -0
  66. package/dist/shared/wire.d.ts +14 -1
  67. package/dist/web/install-app.d.ts +75 -8
  68. package/dist/web/install-app.js +330 -67
  69. package/dist/web/macapp/RadarApp.swift +487 -23
  70. package/dist/web/public/index.html +51 -9
  71. package/dist/web/public/next/app.js +33 -18
  72. package/dist/web/public/next/feed.js +102 -15
  73. package/dist/web/public/next/flags.js +3 -0
  74. package/dist/web/public/next/inspector.js +69 -3
  75. package/dist/web/public/next/prefs.js +5 -2
  76. package/dist/web/public/next/registry.js +18 -5
  77. package/dist/web/public/next/store.js +455 -29
  78. package/dist/web/public/next/switchboard-note.js +93 -0
  79. package/dist/web/public/next/toast.js +9 -5
  80. package/dist/web/public/next/voice-model.js +215 -35
  81. package/dist/web/public/next/voice.js +173 -18
  82. package/dist/web/server.d.ts +15 -11
  83. package/dist/web/server.js +690 -168
  84. package/dist/web/spec.d.ts +2 -1
  85. package/dist/web/spec.js +2 -1
  86. package/package.json +2 -2
  87. package/dist/web/log-session.js +0 -166
@@ -1,4 +1,7 @@
1
- import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource, levelRank, FIELD_VALUES, EXCLUDE_MAX_TERMS, EXCLUDE_MAX_TERM_LENGTH, SWITCHBOARD_KINDS, CACHE_TTL_MS } from "./registry.js";
1
+ import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource, levelRank, FIELD_VALUES, EXCLUDE_MAX_TERMS, EXCLUDE_MAX_TERM_LENGTH, SWITCHBOARD_KINDS, CACHE_TTL_MS, normalizeStreamType } from "./registry.js";
2
+ import { byRecordTime, cutFromVotes, inSessionCut, outranks, runRows, sameSessionCut, sessionVote } from "./voice-model.js";
3
+ import { savedTurnLabel } from "./switchboard-note.js";
4
+ export const UNAUTHORIZED_HEAD = "device refused this session (HTTP 401)";
2
5
  // Logcat-scale retention. At the live firehose (~400+ events/sec on the unified Live tab) a
3
6
  // small ring recycles in seconds, so a rare signal (a once-per-5s heartbeat) gets evicted
4
7
  // before you can filter for it. Android Studio / Flipper keep the whole session and filter
@@ -106,18 +109,18 @@ function writeViewMemory(mem) {
106
109
  const POLL_PROFILE_MS = 5000;
107
110
  const GRAPH_N = 60;
108
111
  const PERSEC_N = 30;
109
- const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package", "trace_name", "span_name", "kind", "frame_type", "state_kind", "phase", "event"];
112
+ const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package", "trace_name", "span_name", "kind", "frame_type", "state_kind", "phase", "event", "clock", "outcome"];
110
113
  const PACKAGE_CAP = 1000; // package values learned off the stream; bounded (was Infinity in the PoC, B4)
111
114
  // ---- pre-built dashboards: one tab each. Presets carry only generic placeholders; real
112
115
  // endpoints/channels/event-names are learned LIVE from the device stream. The one baked value
113
116
  // is com.Slack.internal.debug (the debug build's package), which is already public. ----
114
117
  export const MODES = [
115
- { key: "all", label: "Live", spec: { title: "Live", summary: "Live: network, RTM, analytics clogs, traces, Slack-app logcat and Switchboard voice records in one timeline. The rate and sparkline count every source together, so a voice session raises them the way RTM traffic does. (Logs filtered to the Slack app; clear the package chip for all apps.)", source: "all", viz: ["rate", "sparkline", "feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
118
+ { key: "all", label: "Live", spec: { title: "Live", summary: "Live: network, RTM, analytics clogs, traces, Slack-app logs and Switchboard voice records in one timeline. The rate and sparkline count every source together, so a voice session raises them the way RTM traffic does. (Logs filtered to the Slack app; clear the package chip for all apps.)", source: "all", viz: ["rate", "sparkline", "feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
116
119
  { key: "network", label: "Network", spec: { title: "Network", summary: "Network calls per second vs average response time, every call listed, slow ones flagged.", source: "network", viz: ["rate", "graph", "feed", "inspector"], series: [{ metric: "ratePerSec", label: "calls/s", unit: "/s" }, { metric: "avg", field: "duration_ms", label: "avg ms", unit: "ms" }], highlight: { field: "duration_ms", op: ">", value: 800, label: "slow (>800ms)" }, rateWindowSec: 10 } },
117
120
  { key: "rtm", label: "RTM", spec: { title: "RTM", summary: "Real-time websocket events as they happen.", source: "rtm", viz: ["rate", "feed", "inspector"] } },
118
121
  { key: "clog", label: "Clogs", spec: { title: "Clogs", summary: "Analytics clog events, click any to see its full payload.", source: "clog", viz: ["rate", "feed", "inspector"] } },
119
122
  { key: "trace", label: "Traces", spec: { title: "Traces", summary: "Performance trace spans, click to see timing details and tags.", source: "trace", viz: ["rate", "graph", "feed", "inspector"], series: [{ metric: "ratePerSec", label: "spans/s", unit: "/s" }, { metric: "avg", field: "duration_ms", label: "avg ms", unit: "ms" }] } },
120
- { key: "log", label: "Logs", spec: { title: "Device Logs", summary: "Live Slack app logcat, color-coded by level. Scroll the full session buffer, select a range, copy raw lines.", source: "log", viz: ["feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
123
+ { key: "log", label: "Logs", spec: { title: "Device Logs", summary: "Live Slack app logs, color-coded by level. Scroll the full session buffer, select a range, copy raw lines.", source: "log", viz: ["feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
121
124
  // The voice transport's own records (not logcat): session begin/end, connection, mic and speaking
122
125
  // state changes, every websocket frame with its direction and size, phase timings, player re-arms and
123
126
  // stalls. Events only for now; a waveform view comes later. No level here: the records
@@ -129,6 +132,7 @@ export const MODES = [
129
132
  { key: "prefs", label: "Preferences", spec: { title: "Device Preferences", summary: "Browse the on-device SharedPreferences (including feature-flag overrides), read-only.", source: "prefs" } },
130
133
  { key: "flags", label: "Feature Flags", spec: { title: "Feature Flags", summary: "Every feature flag and experiment the Slack app knows about, with its current effective value (ON/OFF for toggles, group name for experiments), its scope, and whether it is locally overridden. Live-updates as flags and experiments change on the device. Filter by name.", source: "flags" } },
131
134
  ];
135
+ const DEFAULT_LOG_PACKAGE = MODES[0].spec.match?.package ?? "";
132
136
  // Dashboard mode key -> the ping `sources` name that must be present for the tab to work. Only
133
137
  // sources the device ships as plugins are gateable; the rest (network/db/prefs/...) always show,
134
138
  // and each joins this map when its device-side migration lands. Note the mode key is singular
@@ -161,7 +165,7 @@ export function modeServed(key, sources) {
161
165
  // - object keys are sorted so key ORDER never matters.
162
166
  // The presets stay mutually distinct under this reduction (verified by test), so dropping the
163
167
  // copy never collapses two different dashboards into one.
164
- function canonicalSpecKey(spec) {
168
+ function canonicalSpecKey(spec, logPackage = DEFAULT_LOG_PACKAGE) {
165
169
  const norm = (v) => {
166
170
  if (Array.isArray(v))
167
171
  return v.map(norm);
@@ -177,6 +181,12 @@ function canonicalSpecKey(spec) {
177
181
  const cleaned = { ...spec };
178
182
  delete cleaned.title;
179
183
  delete cleaned.summary;
184
+ // The package advertised by /health describes the same built-in Slack-app filter.
185
+ // Normalize only for preset recognition; the authored spec itself is never rewritten.
186
+ if ((cleaned.source === "log" || cleaned.source === "all") &&
187
+ logPackage && cleaned.match?.package === logPackage) {
188
+ cleaned.match = { ...cleaned.match, package: DEFAULT_LOG_PACKAGE };
189
+ }
180
190
  // A level floor is a way of looking at the same tab, not a different tab: the Logs button
181
191
  // stays lit at "level ≥ WARN". `match.package` is deliberately still part of the key, so the app
182
192
  // selector next to it does move you off the preset; the two controls are not meant to agree.
@@ -200,7 +210,7 @@ function canonicalSpecKey(spec) {
200
210
  // preset with a remembered exclude list gets it back. That never overrides a field the target
201
211
  // already carries, so an agent-authored spec that resolves to a preset still pushes exactly what
202
212
  // the agent wrote.
203
- export function specForTab(next, current, remembered = "", memory = store.viewMemory) {
213
+ export function specForTab(next, current, remembered = "", memory = store.viewMemory, logPackage = DEFAULT_LOG_PACKAGE) {
204
214
  const logish = (s) => s === "log" || s === "all";
205
215
  let out = next;
206
216
  if (logish(next.source) && next.minLevel === undefined) {
@@ -210,7 +220,7 @@ export function specForTab(next, current, remembered = "", memory = store.viewMe
210
220
  if (min)
211
221
  out = { ...next, minLevel: min };
212
222
  }
213
- const key = specMatchesMode(next);
223
+ const key = specMatchesMode(next, logPackage);
214
224
  const mem = key ? memory[key] : undefined;
215
225
  if (!mem)
216
226
  return out;
@@ -218,12 +228,17 @@ export function specForTab(next, current, remembered = "", memory = store.viewMe
218
228
  out = { ...out, exclude: [...mem.exclude] };
219
229
  return out;
220
230
  }
221
- export function specMatchesMode(spec) {
231
+ export function specMatchesMode(spec, logPackage = DEFAULT_LOG_PACKAGE) {
222
232
  if (!spec || spec.blank)
223
233
  return null;
224
- const key = canonicalSpecKey(spec);
234
+ const key = canonicalSpecKey(spec, logPackage);
225
235
  return MODES.find((m) => canonicalSpecKey(m.spec) === key)?.key ?? null;
226
236
  }
237
+ // Whether a record of the run's session id belongs to the run itself rather than an older process's
238
+ // run under the same id. With no begin on record there is nothing to tell them apart by.
239
+ function inSwitchboardRun(ev, run) {
240
+ return run.beganAt === null || (typeof ev.timestamp === "number" && ev.timestamp >= run.beganAt);
241
+ }
227
242
  /**
228
243
  * This page's presence id, taken from the URL when whoever opened the page supplied one.
229
244
  *
@@ -326,6 +341,10 @@ export class Store {
326
341
  // "device offline, retrying…" overwrites the msg within one 2s tick and is factually wrong
327
342
  // for this outage mode (the device is fine; the session inside the app ended).
328
343
  sessionEnded = false;
344
+ // A device 401, held until something later outranks it: the device accepts us again (a connected
345
+ // frame, a healthy reply, a press or pick that arms), a reasoned frame names another cause, two
346
+ // health reads in a row fail or come back without a 401, or the bound device changes.
347
+ _refusalMsg = null;
329
348
  // True while ANY /enable flight is in progress — manual press or auto-re-arm — set by
330
349
  // reconnect() itself so one latch covers both initiators. Emitted as "enabling"; the
331
350
  // header's button disables and relabels off it.
@@ -504,6 +523,23 @@ export class Store {
504
523
  return null;
505
524
  return this._enableErrorEpoch === this._outageEpoch ? this.enableError : null;
506
525
  }
526
+ get refusal() {
527
+ return this._refusalMsg;
528
+ }
529
+ setRefusal(msg) {
530
+ if (this._refusalMsg === msg)
531
+ return;
532
+ // Earlier answers do not belong to this refusal. A press made while already latched keeps
533
+ // its answer: it writes after this and re-latches sentence to sentence. A press or pick whose
534
+ // own health poll latches the refusal for the first time loses its answer here and shows
535
+ // the sentence alone, which is the same text it answered with.
536
+ if (this._refusalMsg === null && msg !== null) {
537
+ this.clearEnableError();
538
+ this.clearDeviceError();
539
+ }
540
+ this._refusalMsg = msg;
541
+ this.emit("refusal", msg);
542
+ }
507
543
  // Drop the reason outright. Used where the reason is not merely from another outage but describes a
508
544
  // question that was never answered, or a device we are no longer bound to. The epoch stamp handles
509
545
  // "belongs to a different outage"; this handles "belongs to nothing".
@@ -515,6 +551,13 @@ export class Store {
515
551
  this._enableErrorEpoch = -1;
516
552
  this.emit("enable-error", this.visibleEnableError);
517
553
  }
554
+ clearDeviceError() {
555
+ if (this.deviceError === null)
556
+ return;
557
+ this.deviceError = null;
558
+ this.deviceErrorInstructs = false;
559
+ this.emit("device-error", null);
560
+ }
518
561
  // Capture-source names the device declares on ping (seam builds). null = old build with no
519
562
  // discovery, in which case every tab shows (today's behavior). Emitted as "sources" on change.
520
563
  deviceSources = null;
@@ -573,6 +616,37 @@ export class Store {
573
616
  _specGen = 0;
574
617
  _lastBoundLabel = null;
575
618
  _backfillToken = 0;
619
+ // Per switchboard session id, the run currently held for it. Session ids restart with the app
620
+ // process, so one id can name several runs over a tab's life; see switchboardRunFor for when a
621
+ // begin starts a new one.
622
+ _switchboardRuns = new Map();
623
+ // server_session_id per session_id, for the id's current run only: learned from that run's
624
+ // `ready` record or its per-session refill's detail envelope, and dropped when a new run starts
625
+ // under the id. undefined means not learned yet; null means the summary reported the key but it
626
+ // was itself null (see voice-model.ts's serverSessionId).
627
+ _switchboardSummaryServerId = new Map();
628
+ // saved_turn_counts per session id, off the same refill envelope and dropped with it on a new run,
629
+ // with the newest record id that envelope carried: the counts are a snapshot through that id, and
630
+ // the panel adds the saved_turn rows newer than it. Absent until a refill lands one; an older
631
+ // build never sends it.
632
+ _switchboardSummarySavedTurnCounts = new Map();
633
+ // The two winning votes behind switchboardNewestCut(): the newest begin and the newest non-end
634
+ // record. Updated as rows land so a read is O(1); an eviction or clear that removes a winner
635
+ // marks them stale and the next read rescans the cache once.
636
+ _sbBestBegin = null;
637
+ _sbBestAny = null;
638
+ _sbVotesStale = false;
639
+ // The cut the feed was last bumped for (see announceCutMove).
640
+ _sbAnnouncedCut = null;
641
+ // The rows behind switchboardRunRows() and the cut they were built for (null: rebuild on the
642
+ // next read). A frame only appends to them or notes an evicted row, both O(1); sorting, dropping
643
+ // the evicted rows and copying out wait for a read, so a busy call costs O(run) once per read
644
+ // rather than per frame. _sbRunRowsView is the copy readers get, null once the rows changed.
645
+ _sbRunRows = null;
646
+ _sbRunRowsCut = null;
647
+ _sbRunRowsGone = new Set();
648
+ _sbRunRowsUnsorted = false;
649
+ _sbRunRowsView = null;
576
650
  // True while the connection is in a dropped/waiting state. Lets pollHealth detect the
577
651
  // drop->recover EDGE (device came back) so it can re-open the stream + backfill ONCE on
578
652
  // recovery, instead of every poll. Without this, an auto-recovered tab flips the dot to
@@ -695,6 +769,8 @@ export class Store {
695
769
  // them). Deliberately NOT reset: subscribers, live timers and stream handles (start() and
696
770
  // openStream() own those lifecycles), and _tabId, which identifies the page for its whole life.
697
771
  _resetForTest() {
772
+ this.platform = null;
773
+ this.logPackage = DEFAULT_LOG_PACKAGE;
698
774
  this.lastLogLevel = "";
699
775
  this.viewMemory = {};
700
776
  this.spec = { blank: true, viz: [] };
@@ -715,6 +791,7 @@ export class Store {
715
791
  this._enableErrorEpoch = -1;
716
792
  this.sessionEnded = false;
717
793
  this.enabling = false;
794
+ this._refusalMsg = null;
718
795
  this.autoRearming = false;
719
796
  this.autoRearmSuppressed = false;
720
797
  this.selfArmBlocked = null;
@@ -761,6 +838,18 @@ export class Store {
761
838
  this._specGen = 0;
762
839
  this._lastBoundLabel = null;
763
840
  this._backfillToken = 0;
841
+ this._switchboardRuns = new Map();
842
+ this._switchboardSummaryServerId = new Map();
843
+ this._switchboardSummarySavedTurnCounts = new Map();
844
+ this._sbBestBegin = null;
845
+ this._sbBestAny = null;
846
+ this._sbVotesStale = false;
847
+ this._sbAnnouncedCut = null;
848
+ this._sbRunRows = null;
849
+ this._sbRunRowsCut = null;
850
+ this._sbRunRowsGone = new Set();
851
+ this._sbRunRowsUnsorted = false;
852
+ this._sbRunRowsView = null;
764
853
  this._dropped = false;
765
854
  this._lastSerial = null;
766
855
  // Cancel rather than just forget: a rAF queued before the reset would otherwise fire after
@@ -807,6 +896,8 @@ export class Store {
807
896
  this.cacheKeys = new Set();
808
897
  this._fieldsSeen = new Map();
809
898
  }
899
+ this._sbVotesStale = true;
900
+ this._sbRunRows = null;
810
901
  this.seen = {};
811
902
  this.detailCache = new Map();
812
903
  this._capSeen = new Set();
@@ -831,6 +922,11 @@ export class Store {
831
922
  // phone. Timers and spec are left running.
832
923
  clearDeviceCaches() {
833
924
  this.clearRecords();
925
+ // Session ids restart at 1 on every phone, so the old device's runs and server ids would
926
+ // claim the new device's sessions of the same id.
927
+ this._switchboardRuns = new Map();
928
+ this._switchboardSummaryServerId = new Map();
929
+ this._switchboardSummarySavedTurnCounts = new Map();
834
930
  // The old device's declared sources do not describe the new one; null until its next poll.
835
931
  this.updateSources(null);
836
932
  // Same for the screen capabilities: they come from the old device's platform, so a new phone
@@ -879,6 +975,12 @@ export class Store {
879
975
  // and applied the still-blank spec bootDefault was in the middle of replacing, undoing the
880
976
  // local default bootDefault had just set and stranding the page on the blank placeholder
881
977
  // until the next 700ms tick happened to read the corrected value.
978
+ try {
979
+ // /health waits for the device ping, which can take up to four seconds.
980
+ const health = await (await fetch("/health", { signal: AbortSignal.timeout(6000) })).json();
981
+ this.updatePlatform(health.platform, health.log_package);
982
+ }
983
+ catch { /* retain Android defaults if health is unavailable */ }
882
984
  await this.bootDefault();
883
985
  this.watchStorageAcrossTabs();
884
986
  this.fetchSelfHeal();
@@ -889,7 +991,7 @@ export class Store {
889
991
  this._intervals.push(setInterval(() => this.pollHealth(), POLL_HEALTH_MS));
890
992
  this.pollProfile();
891
993
  this._intervals.push(setInterval(() => this.pollProfile(), POLL_PROFILE_MS));
892
- this._intervals.push(setInterval(() => this.evictCache(), 30000));
994
+ this._intervals.push(setInterval(() => this.evictOnTimer(), 30000));
893
995
  }
894
996
  // Stop all timers + the stream. Not used by the live page (the store is a singleton for the
895
997
  // life of the tab), but lets a test tear the engine down so it does not leak timers.
@@ -941,8 +1043,10 @@ export class Store {
941
1043
  // the ambiguity is about which device to pin, not about whether a session is serving
942
1044
  // frames, and letting the override eat the refutation would leave the header claiming
943
1045
  // "no radar session" about a session that just spoke.
944
- if (state === "connected" && observed)
1046
+ if (state === "connected" && observed) {
945
1047
  this.refuteSessionEnded();
1048
+ this.setRefusal(null);
1049
+ }
946
1050
  // Unpinned multi-device is never "connected": frames can ride a stale forward from a prior
947
1051
  // pin and flip the dot green while the per-device surfaces (DB run-as) are broken by the
948
1052
  // ambiguity. Override any connected claim to a waiting "pick one" until a device is pinned.
@@ -1017,7 +1121,7 @@ export class Store {
1017
1121
  // rather than racing this one and overwriting it back to blank.
1018
1122
  // Through specForTab, as a Live tab click is: the pristine preset would drop the exclusions
1019
1123
  // this browser remembers for Live on every fresh server. viewMemory is read at construction.
1020
- const spec = specForTab(MODES[0].spec, null, this.lastLogLevel, this.viewMemory);
1124
+ const spec = specForTab(this.presetSpec(MODES[0].spec), null, this.lastLogLevel, this.viewMemory, this.logPackage);
1021
1125
  this.applySpec(spec, { local: true });
1022
1126
  await fetch("/setspec", { method: "POST", headers: this.authoredHeaders({ "Content-Type": "application/json" }), body: JSON.stringify(spec) }).catch(() => { });
1023
1127
  }
@@ -1068,7 +1172,7 @@ export class Store {
1068
1172
  this._specKey = key;
1069
1173
  if (this._localPushKey === key)
1070
1174
  this._localPushKey = null;
1071
- this.customActive = !isLocalEdit && !!spec && !spec.blank && specMatchesMode(spec) === null;
1175
+ this.customActive = !isLocalEdit && !!spec && !spec.blank && this.matchesMode(spec) === null;
1072
1176
  if (this.customActive && (!this.lastCustomSpec || JSON.stringify(this.lastCustomSpec) !== key)) {
1073
1177
  this.lastCustomSpec = spec;
1074
1178
  }
@@ -1106,7 +1210,7 @@ export class Store {
1106
1210
  // at click time, a Live click made while a Logs level change was in flight posted a body with no
1107
1211
  // level, and applySpec forgot the level with it.
1108
1212
  pushPreset(preset, opts = {}) {
1109
- return this.updateSpec((base) => specForTab(preset, base, this.lastLogLevel, this.viewMemory), opts);
1213
+ return this.updateSpec((base) => specForTab(this.presetSpec(preset), base, this.lastLogLevel, this.viewMemory, this.logPackage), opts);
1110
1214
  }
1111
1215
  async postSpec(spec, opts) {
1112
1216
  if (opts.local)
@@ -1153,14 +1257,29 @@ export class Store {
1153
1257
  }
1154
1258
  return r;
1155
1259
  }
1260
+ /** Return a platform-specific copy of a built-in preset without mutating MODES. */
1261
+ presetSpec(spec) {
1262
+ if ((spec.source !== "log" && spec.source !== "all") ||
1263
+ spec.match?.package !== DEFAULT_LOG_PACKAGE ||
1264
+ !this.logPackage ||
1265
+ this.logPackage === DEFAULT_LOG_PACKAGE) {
1266
+ return spec;
1267
+ }
1268
+ return { ...spec, match: { ...spec.match, package: this.logPackage } };
1269
+ }
1156
1270
  activeModeKey() {
1157
- return this.customActive ? "__custom__" : specMatchesMode(this.spec);
1271
+ return this.customActive ? "__custom__" : this.matchesMode(this.spec);
1272
+ }
1273
+ matchesMode(spec) {
1274
+ return specMatchesMode(spec, this.logPackage);
1158
1275
  }
1159
1276
  // Rebuild all derived state for a new spec, reconnect the stream (so the server
1160
1277
  // attaches/detaches the host-side logcat session for log/all sources), replay the cache, and
1161
1278
  // backfill the device ring. Mirrors vanilla build(spec). `local` says this page authored the
1162
1279
  // spec (a chip, the level selector, Filters Apply): only then is a preset's view
1163
1280
  // remembered, so a spec an agent pushes neither reads the memory (specForTab) nor rewrites it.
1281
+ platform = null;
1282
+ logPackage = DEFAULT_LOG_PACKAGE;
1164
1283
  applySpec(spec, opts = {}) {
1165
1284
  const prev = this.spec;
1166
1285
  this.spec = spec || { blank: true, viz: [] };
@@ -1168,7 +1287,7 @@ export class Store {
1168
1287
  if (this.spec.source === "log" || this.spec.source === "all") {
1169
1288
  this.lastLogLevel = typeof this.spec.minLevel === "string" ? this.spec.minLevel : "";
1170
1289
  }
1171
- const modeKey = specMatchesMode(this.spec);
1290
+ const modeKey = this.matchesMode(this.spec);
1172
1291
  if (modeKey && opts.local)
1173
1292
  this.rememberView(modeKey, this.spec);
1174
1293
  // A change to the exclude list alone (a kind chip pressed, a term typed or removed) is a view
@@ -1241,7 +1360,7 @@ export class Store {
1241
1360
  // poll re-opens + backfills (recovered()), not just flips the dot green.
1242
1361
  es.onerror = () => {
1243
1362
  this._dropped = true;
1244
- this.setConn("waiting", "reconnecting…");
1363
+ this.setConn("waiting", this._refusalMsg === null ? "reconnecting…" : UNAUTHORIZED_HEAD);
1245
1364
  };
1246
1365
  this._es = es;
1247
1366
  }
@@ -1259,17 +1378,19 @@ export class Store {
1259
1378
  catch {
1260
1379
  return;
1261
1380
  }
1381
+ f.type = normalizeStreamType(f.type);
1262
1382
  if (f.type === "_status") {
1263
1383
  // reason is typed as a plain string on purpose: the client acts on the known value and
1264
1384
  // treats every other value as a retraction (see src/shared/wire.ts StatusReason), so a
1265
1385
  // server that adds a reason later needs no client change.
1266
1386
  const e = f.event;
1387
+ const refused = e.reason === "unauthorized" && typeof e.msg === "string";
1267
1388
  // conn first, reason second: a reasoned frame is itself a waiting report, and
1268
1389
  // noteNoSession's immediate re-arm attempt reads conn.state — handled the other way
1269
1390
  // around, a diagnosis arriving right after a connected blip would see the stale
1270
1391
  // "connected" and skip the immediate attempt it exists for. observed=true: a connected
1271
1392
  // _status is the proxy vouching its upstream actually answered.
1272
- this.setConn(e.state, e.msg, true);
1393
+ this.setConn(e.state, refused ? UNAUTHORIZED_HEAD : e.msg, true);
1273
1394
  // The reason is the outage's CURRENT diagnosis (see src/shared/wire.ts StatusReason): only
1274
1395
  // no_session latches, and any other reason, today "undiagnosed" and whatever a later server
1275
1396
  // adds, retires the latch. Dispatching on the retraction token itself would leave the latch
@@ -1279,6 +1400,13 @@ export class Store {
1279
1400
  this.noteNoSession();
1280
1401
  else
1281
1402
  this.retireNoSession();
1403
+ // A reasoned frame is the current diagnosis, so a non-refusal releases the held refusal.
1404
+ if (!refused)
1405
+ this.setRefusal(null);
1406
+ }
1407
+ if (refused) {
1408
+ this._healthMisses = 0;
1409
+ this.setRefusal(e.msg);
1282
1410
  }
1283
1411
  return;
1284
1412
  }
@@ -1312,6 +1440,18 @@ export class Store {
1312
1440
  }
1313
1441
  const ev = f.event || {};
1314
1442
  ev._type = f.type;
1443
+ if (f.type === "switchboard" && typeof ev.session_id === "number") {
1444
+ const run = this.switchboardRunFor(ev.session_id, ev, live);
1445
+ // Learn a ready record's server_session_id the moment it's seen, live or not, so the pill
1446
+ // keeps it after the ready row itself ages out of the capped cache. Only a ready from the
1447
+ // id's current run counts: one from an older process under the same id names another call.
1448
+ if (ev.kind === "session" && ev.event === "ready" && Object.hasOwn(ev, "server_session_id") && inSwitchboardRun(ev, run)) {
1449
+ this._switchboardSummaryServerId.set(ev.session_id, ev.server_session_id ?? null);
1450
+ }
1451
+ if (ev.kind === "saved_turn" && typeof ev.outcome === "string" && typeof ev.id === "number" && inSwitchboardRun(ev, run)) {
1452
+ run.savedTurns.set(ev.id, ev.outcome);
1453
+ }
1454
+ }
1315
1455
  const isNew = this.cacheFrame(f.type, ev);
1316
1456
  if (this.spec.source !== "all" && f.type !== this.spec.source)
1317
1457
  return;
@@ -1325,6 +1465,43 @@ export class Store {
1325
1465
  return;
1326
1466
  this.accept(ev, live);
1327
1467
  }
1468
+ // The run of `sid` that `ev` belongs to, starting a new one when `ev` shows the id was reused.
1469
+ // A begin later than everything on record for the id's run is a new run under a reused id (ids
1470
+ // restart with the app process), whether it arrives live or by backfill: the old run's server id
1471
+ // is dropped and the new run refilled. An older or repeated begin changes nothing. A run's first
1472
+ // live record (a live begin, or a live row with no begin behind it: opened mid-call, or the
1473
+ // stream just connected) refills it once so its rows and server_session_id fill in beyond that
1474
+ // one record. A run only ever seen by backfill is not refilled, since a fresh store's backfill
1475
+ // can carry several sessions at once.
1476
+ switchboardRunFor(sid, ev, live) {
1477
+ const ts = typeof ev.timestamp === "number" ? ev.timestamp : null;
1478
+ const isBegin = ev.kind === "session" && ev.event === "begin";
1479
+ let run = this._switchboardRuns.get(sid);
1480
+ let reused = false;
1481
+ if (run && isBegin && ts !== null) {
1482
+ const known = run.beganAt ?? run.firstSeenAt;
1483
+ if (known !== null && ts > known)
1484
+ reused = true;
1485
+ // This run's own begin, arriving after some of its rows.
1486
+ else if (run.beganAt === null)
1487
+ run.beganAt = ts;
1488
+ }
1489
+ if (reused) {
1490
+ this._switchboardSummaryServerId.delete(sid);
1491
+ this._switchboardSummarySavedTurnCounts.delete(sid);
1492
+ }
1493
+ if (!run || reused) {
1494
+ run = { beganAt: isBegin ? ts : null, firstSeenAt: ts, filled: false, maxId: -Infinity, savedTurns: new Map() };
1495
+ this._switchboardRuns.set(sid, run);
1496
+ }
1497
+ if (typeof ev.id === "number" && ev.id > run.maxId && inSwitchboardRun(ev, run))
1498
+ run.maxId = ev.id;
1499
+ if (!run.filled && (live || reused)) {
1500
+ run.filled = true;
1501
+ void this.backfillSwitchboardSession(sid, run);
1502
+ }
1503
+ return run;
1504
+ }
1328
1505
  // ---- CACHE ring (dedup + bounded by count and age) ----
1329
1506
  frameKey(type, ev) {
1330
1507
  // Every kind the stream gate admits carries an id (the device kinds mint theirs per app
@@ -1344,10 +1521,17 @@ export class Store {
1344
1521
  if (this.cacheKeys.has(k))
1345
1522
  return false;
1346
1523
  this.cacheKeys.add(k);
1347
- this.cache.push({ type, ev, ts: ev.timestamp || Date.now() });
1524
+ const entry = { type, ev, ts: ev.timestamp || Date.now() };
1525
+ this.cache.push(entry);
1526
+ if (type === "switchboard") {
1527
+ this.voteSwitchboard(entry);
1528
+ this.addToRunRows(ev);
1529
+ }
1348
1530
  this.observe(ev);
1349
1531
  this.noteFields(type, ev);
1350
1532
  this.evictCache();
1533
+ if (type === "switchboard" || this._sbVotesStale)
1534
+ this.announceCutMove();
1351
1535
  return true;
1352
1536
  }
1353
1537
  // True once a row of `source` ("all": of any type) has carried `field` with a non-null value this
@@ -1388,14 +1572,65 @@ export class Store {
1388
1572
  const cutoff = Date.now() - CACHE_TTL_MS;
1389
1573
  const drop = () => {
1390
1574
  const old = this.cache.shift();
1391
- if (old)
1392
- this.cacheKeys.delete(this.frameKey(old.type, old.ev));
1575
+ if (!old)
1576
+ return;
1577
+ this.cacheKeys.delete(this.frameKey(old.type, old.ev));
1578
+ if (old === this._sbBestBegin?.entry || old === this._sbBestAny?.entry)
1579
+ this._sbVotesStale = true;
1580
+ if (old.type === "switchboard" && this._sbRunRows !== null && this._sbRunRowsCut !== null && inSessionCut(old.ev, this._sbRunRowsCut)) {
1581
+ this._sbRunRowsGone.add(old.ev);
1582
+ this._sbRunRowsView = null;
1583
+ }
1393
1584
  };
1394
1585
  while (this.cache.length && this.cache[0].ts < cutoff)
1395
1586
  drop();
1396
1587
  while (this.cache.length > this.cacheCap)
1397
1588
  drop();
1398
1589
  }
1590
+ // The periodic TTL sweep. No frame lands with it, so it announces a moved cut itself.
1591
+ evictOnTimer() {
1592
+ this.evictCache();
1593
+ this.announceCutMove();
1594
+ }
1595
+ // Bump the feed when the newest switchboard cut has moved since the last bump for it. The frame
1596
+ // that moves it may be of another kind (a log line evicting the newest begin at the cap) or not
1597
+ // pass the tab's filter, and neither reaches accept()'s own bump; the feed resnaps on the bump.
1598
+ announceCutMove() {
1599
+ const cut = this.switchboardNewestCut();
1600
+ if (sameSessionCut(cut, this._sbAnnouncedCut))
1601
+ return;
1602
+ this._sbAnnouncedCut = cut;
1603
+ this.bumpFeed();
1604
+ }
1605
+ voteSwitchboard(entry) {
1606
+ if (this._sbVotesStale)
1607
+ return; // the rescan in switchboardNewestCut will count it
1608
+ const vote = sessionVote(entry.ev);
1609
+ if (!vote)
1610
+ return;
1611
+ if (vote.begin && outranks(vote, this._sbBestBegin?.vote ?? null))
1612
+ this._sbBestBegin = { entry, vote };
1613
+ if (!vote.end && outranks(vote, this._sbBestAny?.vote ?? null))
1614
+ this._sbBestAny = { entry, vote };
1615
+ }
1616
+ // A new row joins the held run's rows in place when the run it belongs to is still the newest.
1617
+ // A row that moves the cut (a newer begin, or a newer session) drops them instead, and the next
1618
+ // read rebuilds them for the new run.
1619
+ addToRunRows(ev) {
1620
+ if (this._sbRunRows === null)
1621
+ return;
1622
+ if (this._sbVotesStale || !sameSessionCut(this.switchboardNewestCut(), this._sbRunRowsCut)) {
1623
+ this._sbRunRows = null;
1624
+ return;
1625
+ }
1626
+ if (this._sbRunRowsCut === null || !inSessionCut(ev, this._sbRunRowsCut))
1627
+ return;
1628
+ const rows = this._sbRunRows;
1629
+ if (rows.length && byRecordTime(rows[rows.length - 1], ev) > 0)
1630
+ this._sbRunRowsUnsorted = true;
1631
+ rows.push(ev);
1632
+ this._sbRunRowsView = null;
1633
+ }
1399
1634
  observe(ev) {
1400
1635
  for (const f of SUGGEST_FIELDS) {
1401
1636
  let v = ev[f];
@@ -1450,6 +1685,78 @@ export class Store {
1450
1685
  this.accept(ev, false);
1451
1686
  }
1452
1687
  }
1688
+ // Refill one run's rows, capped at 2000 (a single live-view refill, not the full-session
1689
+ // export), so the panel and feed are not left with only the single record they saw live.
1690
+ // Routed through onFrame(..., false) so it dedupes against what the live stream already
1691
+ // delivered. /api/switchboard/<id> is gated, so this sends the authored header.
1692
+ async backfillSwitchboardSession(sessionId, run) {
1693
+ // Read before the fetch goes out: everything held now predates the device's snapshot.
1694
+ const heldThroughId = run.maxId;
1695
+ try {
1696
+ const res = await fetch(`/api/switchboard/${sessionId}?limit=2000`, { headers: this.authoredHeaders() });
1697
+ const detail = await res.json();
1698
+ // A new-build device always sends server_session_id on the summary (present, maybe null);
1699
+ // an older build omits the key entirely. voice-model.ts's serverSessionId reads the key's
1700
+ // presence as proof the session will eventually report an id, so use Object.hasOwn, not a
1701
+ // truthiness check on the value. A new run that started under the id while this fetch was
1702
+ // out owns the id's entry now, so this run's answer is not written over it.
1703
+ if (this._switchboardRuns.get(sessionId) === run && Object.hasOwn(detail ?? {}, "server_session_id")) {
1704
+ this._switchboardSummaryServerId.set(sessionId, detail.server_session_id ?? null);
1705
+ }
1706
+ // The device reads the summary and the page together, so the counts stop at the page's
1707
+ // highest id, or at the highest id held when the fetch went out if that is higher (an empty
1708
+ // page). With neither, every row the stream brings is newer.
1709
+ const counts = detail?.saved_turn_counts;
1710
+ const hasCounts = this._switchboardRuns.get(sessionId) === run && counts !== null && typeof counts === "object" && !Array.isArray(counts);
1711
+ if (hasCounts) {
1712
+ let throughId = heldThroughId;
1713
+ for (const e of detail?.events || []) {
1714
+ const id = e?.id;
1715
+ if (typeof id === "number" && id > throughId)
1716
+ throughId = id;
1717
+ }
1718
+ this._switchboardSummarySavedTurnCounts.set(sessionId, { counts: counts, throughId });
1719
+ }
1720
+ // A new run under the id, or a device switch, while the fetch was out: the page is another
1721
+ // run's (or another phone's) rows, and must not land in this cache.
1722
+ if (this._switchboardRuns.get(sessionId) !== run)
1723
+ return;
1724
+ for (const e of detail?.events || []) {
1725
+ this.onFrame({ data: JSON.stringify({ type: "switchboard", event: e }) }, false);
1726
+ }
1727
+ // The events may all be rows the tab already holds, which bump nothing; redraw for the counts.
1728
+ if (hasCounts)
1729
+ this.emit("tick", Date.now());
1730
+ }
1731
+ catch {
1732
+ /* device unreachable; the live stream still fills the session in going forward */
1733
+ }
1734
+ }
1735
+ // server_session_id for sessionId, as learned by the refill above: undefined when nothing has
1736
+ // landed yet, a string or null once it has.
1737
+ switchboardSummaryServerId(sessionId) {
1738
+ return this._switchboardSummaryServerId.get(sessionId);
1739
+ }
1740
+ // The saved_turn outcomes seen for sessionId's current run, by record id; undefined before any
1741
+ // record of the id.
1742
+ switchboardSavedTurnOutcomes(sessionId) {
1743
+ return this._switchboardRuns.get(sessionId)?.savedTurns;
1744
+ }
1745
+ // saved_turn_counts for sessionId, as learned by the refill above; undefined until one lands.
1746
+ switchboardSummarySavedTurnCounts(sessionId) {
1747
+ return this._switchboardSummarySavedTurnCounts.get(sessionId);
1748
+ }
1749
+ // A tab opened after the call sees the session only by backfill, which never refills a run (it
1750
+ // can carry several) and is capped, so the panel would have no summary counts and few rows. Fill
1751
+ // the newest session alone, once, the way its first live record would have.
1752
+ fillNewestSwitchboardRun() {
1753
+ const sid = this.switchboardNewestSessionId();
1754
+ const run = sid !== null ? this._switchboardRuns.get(sid) : undefined;
1755
+ if (sid === null || !run || run.filled)
1756
+ return;
1757
+ run.filled = true;
1758
+ void this.backfillSwitchboardSession(sid, run);
1759
+ }
1453
1760
  async backfill() {
1454
1761
  const myToken = ++this._backfillToken;
1455
1762
  const src = this.spec.source;
@@ -1463,6 +1770,7 @@ export class Store {
1463
1770
  return;
1464
1771
  for (const f of r?.frames || [])
1465
1772
  this.onFrame({ data: JSON.stringify(f) }, false);
1773
+ this.fillNewestSwitchboardRun();
1466
1774
  }
1467
1775
  catch {
1468
1776
  /* device unreachable; live stream still self-heals */
@@ -1551,14 +1859,63 @@ export class Store {
1551
1859
  const w = (this.spec.rateWindowSec || 10) * 1000;
1552
1860
  return this.times.filter((t) => t >= now - w).length;
1553
1861
  }
1862
+ // The run the Switchboard tab's feed shows, or null when the cache holds no switchboard row a
1863
+ // session can be read off of. Computed with voice-model.ts's vote and cut, so it agrees with
1864
+ // newestSessionId and sessionRows over the same rows. O(1) unless a winning vote was evicted.
1865
+ switchboardNewestCut() {
1866
+ if (this._sbVotesStale) {
1867
+ this._sbVotesStale = false;
1868
+ this._sbBestBegin = null;
1869
+ this._sbBestAny = null;
1870
+ for (const c of this.cache)
1871
+ if (c.type === "switchboard")
1872
+ this.voteSwitchboard(c);
1873
+ }
1874
+ return cutFromVotes(this._sbBestBegin?.vote ?? null, this._sbBestAny?.vote ?? null);
1875
+ }
1876
+ switchboardNewestSessionId() {
1877
+ return this.switchboardNewestCut()?.sessionId ?? null;
1878
+ }
1879
+ // The rows of switchboardNewestCut()'s run, oldest first, as sessionRows orders them: what the
1880
+ // panel draws and the Switchboard feed shows. The same array until a row of the run lands or
1881
+ // leaves or the cut moves, so a caller can memoize on it; only a moved cut or a clear walks the
1882
+ // cache.
1883
+ switchboardRunRows() {
1884
+ const cut = this.switchboardNewestCut();
1885
+ if (this._sbRunRows === null || !sameSessionCut(cut, this._sbRunRowsCut)) {
1886
+ this._sbRunRowsCut = cut;
1887
+ this._sbRunRows = cut === null ? [] : runRows(this.cache.filter((c) => c.type === "switchboard").map((c) => c.ev), cut);
1888
+ this._sbRunRowsGone.clear();
1889
+ this._sbRunRowsUnsorted = false;
1890
+ this._sbRunRowsView = null;
1891
+ }
1892
+ if (this._sbRunRowsView === null) {
1893
+ const gone = this._sbRunRowsGone;
1894
+ if (gone.size) {
1895
+ this._sbRunRows = this._sbRunRows.filter((r) => !gone.has(r));
1896
+ gone.clear();
1897
+ }
1898
+ if (this._sbRunRowsUnsorted) {
1899
+ this._sbRunRows.sort(byRecordTime);
1900
+ this._sbRunRowsUnsorted = false;
1901
+ }
1902
+ this._sbRunRowsView = this._sbRunRows.slice();
1903
+ }
1904
+ return this._sbRunRowsView;
1905
+ }
1554
1906
  // Events the current tab's feed should show, chronological (oldest->newest). The feed owns
1555
1907
  // inversion/sort; chronological keeps a locked scroll stable (appends never shift an index).
1908
+ // The Switchboard tab shows only the newest session's current run; every other tab, Live
1909
+ // included, shows every row.
1556
1910
  viewFrames() {
1557
1911
  const src = this.spec.source;
1912
+ const cut = src === "switchboard" ? this.switchboardNewestCut() : null;
1558
1913
  const out = [];
1559
1914
  for (const c of this.cache) {
1560
1915
  if (src !== "all" && c.type !== src)
1561
1916
  continue;
1917
+ if (cut !== null && !inSessionCut(c.ev, cut))
1918
+ continue;
1562
1919
  const ev = c.ev;
1563
1920
  ev._type = c.type;
1564
1921
  if (!this.matches(ev))
@@ -1723,6 +2080,7 @@ export class Store {
1723
2080
  // baseline through the device-list refresh AFTER the error was written, so the error is
1724
2081
  // about the device just pinned and must survive the edge it caused.
1725
2082
  this.clearEnableError();
2083
+ this.setRefusal(null);
1726
2084
  }
1727
2085
  this._lastSerial = serial;
1728
2086
  // The DB tab, unlike the feed, DOES carry stale state across a first pin: it loaded unpinned
@@ -1768,13 +2126,41 @@ export class Store {
1768
2126
  this.screenCaps = raw;
1769
2127
  this.emit("screen-caps", this.screenCaps);
1770
2128
  }
2129
+ updatePlatform(raw, rawLogPackage) {
2130
+ if (typeof raw !== "string" || !raw)
2131
+ return;
2132
+ const previous = this.platform;
2133
+ const previousLogPackage = this.logPackage;
2134
+ const nextLogPackage = typeof rawLogPackage === "string" && rawLogPackage
2135
+ ? rawLogPackage
2136
+ : previousLogPackage;
2137
+ if (raw === previous && nextLogPackage === previousLogPackage)
2138
+ return;
2139
+ // Computed even on the first platform read: when start()'s /health loses its race,
2140
+ // bootDefault() has already applied the Android preset, and that spec still needs the
2141
+ // swap. A blank spec (the normal first read) maps to null and falls through below.
2142
+ const key = this.customActive ? "__custom__" : specMatchesMode(this.spec, previousLogPackage);
2143
+ this.platform = raw;
2144
+ this.logPackage = nextLogPackage;
2145
+ if (key !== "all" && key !== "log")
2146
+ return;
2147
+ const mode = MODES.find((candidate) => candidate.key === key);
2148
+ if (!mode)
2149
+ return;
2150
+ const next = specForTab(this.presetSpec(mode.spec), this.spec, this.lastLogLevel, this.viewMemory, this.logPackage);
2151
+ if (JSON.stringify(next) === JSON.stringify(this.spec))
2152
+ return;
2153
+ this.applySpec(next);
2154
+ void this.setSpec(next, { local: true });
2155
+ }
1771
2156
  async pollHealth() {
1772
2157
  // The auto-re-arm cadence rides this existing 2s tick instead of owning a timer: every
1773
2158
  // guard lives inside maybeAutoRearm, so this line is a no-op except mid-outage on a
1774
2159
  // diagnosed dead session. Fire-and-forget so a multi-second /enable flight cannot delay
1775
2160
  // the health read below.
1776
2161
  void this.maybeAutoRearm();
1777
- if (this.connClock() - this._lastEventTs < 6000) {
2162
+ // Pre-refusal device frames do not prove the device still accepts us.
2163
+ if (this._refusalMsg === null && this.connClock() - this._lastEventTs < 6000) {
1778
2164
  this._healthMisses = 0;
1779
2165
  this.recovered();
1780
2166
  // Deliberately does NOT count connection proof. This path re-reads the SAME _lastEventTs every
@@ -1786,6 +2172,7 @@ export class Store {
1786
2172
  }
1787
2173
  try {
1788
2174
  const h = await (await fetch("/health")).json();
2175
+ this.updatePlatform(h.platform, h.log_package);
1789
2176
  // Screen caps ride every /health reply and come from the platform controller, not from the
1790
2177
  // app ping the gate below reads, so they update outside that gate.
1791
2178
  this.updateScreenCaps(h.screen);
@@ -1798,8 +2185,18 @@ export class Store {
1798
2185
  if (h.device === true) {
1799
2186
  this.onHealthDeviceUp(h.sources);
1800
2187
  }
2188
+ else if (h.unauthorized === true && typeof h.unauthorized_msg === "string") {
2189
+ this._healthMisses = 0;
2190
+ this.retireNoSession();
2191
+ this.setRefusal(h.unauthorized_msg);
2192
+ this.setConn("waiting", UNAUTHORIZED_HEAD);
2193
+ }
1801
2194
  else if (++this._healthMisses >= 2) {
1802
2195
  this._dropped = true;
2196
+ // Two replies without 401 end the refusal; one ping can time out. The server counts every
2197
+ // /health ping it answers and after two without a 401 wakes the refused stream on its own,
2198
+ // retracting the refusal on the wire first, so there is nothing to reopen here.
2199
+ this.setRefusal(null);
1803
2200
  this.setConn("waiting", "device offline, retrying…");
1804
2201
  }
1805
2202
  // Whether this dashboard process may arm the device on its own. Read on every health
@@ -1815,6 +2212,8 @@ export class Store {
1815
2212
  catch {
1816
2213
  if (++this._healthMisses >= 2) {
1817
2214
  this._dropped = true;
2215
+ // Two failed reads put the problem at the dashboard, so the refusal no longer applies.
2216
+ this.setRefusal(null);
1818
2217
  this.setConn("waiting", "reconnecting…");
1819
2218
  }
1820
2219
  }
@@ -1882,6 +2281,8 @@ export class Store {
1882
2281
  }).then((r) => r.json()).catch(() => null),
1883
2282
  ]);
1884
2283
  const uid = healthR && healthR.boundUserId;
2284
+ if (healthR)
2285
+ this.updatePlatform(healthR.platform, healthR.log_package);
1885
2286
  // pollHealth's fresh-frame fast path can skip its /health fetch indefinitely on a chatty
1886
2287
  // stream; this 5s poll already fetched /health, so a device:true here is handled by the SAME
1887
2288
  // helper pollHealth uses (sources, misses, recovery, proof, connected — and through the
@@ -1901,9 +2302,18 @@ export class Store {
1901
2302
  // the first attempt would wait for a reply instead of firing on the diagnosis.
1902
2303
  if (healthR)
1903
2304
  this.noteSelfArmBlocked(healthR.self_arm_blocked, healthR.device === true);
1904
- this.profiles = (profilesR && profilesR.profiles) || [];
2305
+ const profileList = profilesR && Array.isArray(profilesR.profiles) ? profilesR.profiles : null;
2306
+ this.profiles = profileList || [];
1905
2307
  if (uid == null) {
1906
- this.profileLabel = this._lastBoundLabel ? "last seen " + this._lastBoundLabel + " — reconnecting…" : "waiting for device…";
2308
+ // Not every transport has Android-style user/work profiles. A successful empty profile
2309
+ // response means the concept is inapplicable; a failed response remains unknown and must
2310
+ // keep the existing waiting/reconnecting message rather than hiding a real Android issue.
2311
+ this.profileLabel =
2312
+ healthR?.device === true && profileList?.length === 0
2313
+ ? ""
2314
+ : this._lastBoundLabel
2315
+ ? "last seen " + this._lastBoundLabel + " — reconnecting…"
2316
+ : "waiting for device…";
1907
2317
  this.emit("profile", this.profileLabel);
1908
2318
  return;
1909
2319
  }
@@ -2017,14 +2427,17 @@ export class Store {
2017
2427
  return;
2018
2428
  }
2019
2429
  // A successful pick clears any prior enable failure.
2020
- this.deviceError = null;
2021
- this.deviceErrorInstructs = false;
2022
- this.emit("device-error", null);
2430
+ this.clearDeviceError();
2023
2431
  this.emit("devices", this.devices);
2024
2432
  // The pick ARMED the device, which refutes any standing reconnect reason whatever the serial
2025
2433
  // did -- the same rule as a successful reconnect. Cleared here, inline, because advancing the
2026
2434
  // baseline below means checkSerialEdge sees no change and can never fire for this switch.
2027
2435
  this.clearEnableError();
2436
+ this.setRefusal(null);
2437
+ // The head wording an armed Reconnect uses while the stream has not spoken yet. Only the
2438
+ // message changes; "connected" stays the wire's claim to make.
2439
+ if (this.conn.state !== "connected")
2440
+ this.setConn(this.conn.state, "re-enabled, reconnecting the stream…");
2028
2441
  // The baseline tracks what the SERVER confirmed: the reply echo when present, the requested
2029
2442
  // serial only as the fallback for a reply without one. Same policy as reconnect's advance.
2030
2443
  const bound = confirmed ?? serial;
@@ -2310,6 +2723,7 @@ export class Store {
2310
2723
  // Deliberately NOT setConn("connected"): the stream has its own reconnect to do, and
2311
2724
  // only an observation of the WIRE may claim "live".
2312
2725
  this.refuteSessionEnded();
2726
+ this.setRefusal(null);
2313
2727
  // With sessionEnded retired, the header falls back to conn.msg verbatim — which is
2314
2728
  // still the outage diagnosis this reply just refuted. Replace the MESSAGE only, never
2315
2729
  // the state: "connected" stays the wire's claim to make. Worded as the recovery step it
@@ -2496,18 +2910,30 @@ export function searchText(ev) {
2496
2910
  }
2497
2911
  // A switchboard record's kind followed by that kind's key fields, in a fixed order, e.g.
2498
2912
  // ["frame", "incoming", "tts.state", 120], ["state", "connection", "Connecting", "Connected"],
2499
- // ["phase", "socket", 412], ["player", "rearm", 38, 4096], ["session", "begin"]. This list is the
2913
+ // ["phase", "socket", 412], ["player", "rearm", 38, 4096], ["session", "begin"],
2914
+ // ["turn", "no_card", 1840], ["saved_turn", "missing_field", "dropped: missing field"]. This list is the
2500
2915
  // search haystack; the row summary (feed.ts switchboardSummary) reads the same fields by name, and
2501
2916
  // a test holds the two together. The record's `id` is deliberately not searchable, as for the other kinds.
2502
2917
  export function switchboardFields(ev) {
2503
2918
  const kind = ev.kind || "";
2504
2919
  const num = (v) => (typeof v === "number" ? v : undefined);
2505
2920
  switch (kind) {
2506
- case "session": return [kind, ev.event];
2921
+ // Searchable here like any other switchboard field, not just shown on the summary pill.
2922
+ case "session": return [kind, ev.event, ev.server_session_id];
2507
2923
  case "state": return [kind, ev.state_kind, ev.from, ev.to, ev.cause];
2508
2924
  case "frame": return [kind, ev.direction, ev.frame_type, num(ev.bytes)];
2509
2925
  case "phase": return [kind, ev.phase, num(ev.duration_ms)];
2510
2926
  case "player": return [kind, ev.event, num(ev.gap_ms), num(ev.bytes_queued)];
2927
+ case "levels": return [kind, num(ev.sample_count)];
2928
+ // The raw clock token, not the row's words, the same way a frame keeps "unknown".
2929
+ case "turn": return [kind, ev.clock, num(ev.response_ms)];
2930
+ // The raw outcome token too, then the row's words ("dropped: missing field", "saved (line
2931
+ // moved on), thread") so a search for what the row says finds it; an unknown outcome's words
2932
+ // are its token, quoted when it collides with a label word.
2933
+ case "saved_turn": {
2934
+ const label = savedTurnLabel(ev.outcome, ev.has_thread);
2935
+ return [kind, ev.outcome, label && label !== ev.outcome ? label : undefined];
2936
+ }
2511
2937
  default: return [kind];
2512
2938
  }
2513
2939
  }