@slack/radar-mcp 1.19.0 → 1.21.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 (44) hide show
  1. package/README.md +48 -8
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +67 -16
  4. package/dist/mcp/index.js +24 -7
  5. package/dist/mcp/network-detail.d.ts +5 -0
  6. package/dist/mcp/network-detail.js +86 -0
  7. package/dist/mcp/radar-response.d.ts +7 -0
  8. package/dist/mcp/radar-response.js +15 -0
  9. package/dist/mcp/session-backfill.d.ts +9 -3
  10. package/dist/mcp/session-backfill.js +77 -17
  11. package/dist/mcp/session-detail.js +54 -2
  12. package/dist/mcp/session-query.js +53 -11
  13. package/dist/mcp/sources-gate.js +4 -0
  14. package/dist/mcp/switchboard-tools.d.ts +9 -0
  15. package/dist/mcp/switchboard-tools.js +40 -0
  16. package/dist/mcp/tools.js +69 -18
  17. package/dist/shared/constants.d.ts +14 -3
  18. package/dist/shared/constants.js +14 -3
  19. package/dist/shared/event-spool.js +3 -2
  20. package/dist/shared/form-body.d.ts +18 -0
  21. package/dist/shared/form-body.js +251 -0
  22. package/dist/shared/stream.d.ts +1 -1
  23. package/dist/shared/switchboard.d.ts +9 -0
  24. package/dist/shared/switchboard.js +54 -0
  25. package/dist/shared/wire.d.ts +32 -0
  26. package/dist/web/install-app.d.ts +64 -1
  27. package/dist/web/install-app.js +174 -24
  28. package/dist/web/macapp/RadarApp.swift +1287 -71
  29. package/dist/web/public/index.html +216 -11
  30. package/dist/web/public/next/app.js +22 -12
  31. package/dist/web/public/next/db.js +180 -18
  32. package/dist/web/public/next/feed.js +571 -53
  33. package/dist/web/public/next/filters.js +160 -34
  34. package/dist/web/public/next/form-body.js +252 -0
  35. package/dist/web/public/next/inspector.js +103 -12
  36. package/dist/web/public/next/registry.js +33 -3
  37. package/dist/web/public/next/store.js +577 -53
  38. package/dist/web/public/next/voice-model.js +532 -0
  39. package/dist/web/public/next/voice.js +397 -0
  40. package/dist/web/server.d.ts +110 -6
  41. package/dist/web/server.js +436 -40
  42. package/dist/web/spec.d.ts +13 -6
  43. package/dist/web/spec.js +89 -6
  44. package/package.json +3 -3
@@ -0,0 +1,397 @@
1
+ // The voice panel on the Switchboard tab: one session's connection, mic and speaking state, the
2
+ // handshake waterfall, a tracks strip (model speaking, you capturing, markers) and four stat cards,
3
+ // all derived from the switchboard records the store already holds (voice-model.ts). It sits
4
+ // between the stats strip and the feed; the feed and the inspector below it are untouched, and a
5
+ // marker click hands the ORIGINAL record to the same inspector the feed uses.
6
+ import { html } from "./html.js";
7
+ import { useMemo, useRef, useState } from "preact/hooks";
8
+ import { useStorePulse } from "./hooks.js";
9
+ import { store } from "./store.js";
10
+ import { buildVoiceModel, GAP_P95_BAD_MS, phaseLabel, RATE_MIN_DIVISOR_MS, tickStepMs, ZOOMS } from "./voice-model.js";
11
+ // The stream view draws the panel only on the Switchboard tab and only while the spec keeps the
12
+ // voice key, so a custom spec on that source can leave it out.
13
+ export function showsVoicePanel(spec) {
14
+ return spec.source === "switchboard" && Array.isArray(spec.viz) && spec.viz.includes("voice");
15
+ }
16
+ // SVG geometry, shared with the design the panel was drawn from: a 1000-wide viewBox stretched to
17
+ // the card, so x is a plain fraction of the window. preserveAspectRatio="none" only stretches
18
+ // the x axis (the plot's CSS height matches H 1:1), which is why row and tick labels are drawn as
19
+ // plain HTML over the plot rather than inside the SVG: SVG text at a fixed font-size would
20
+ // stretch or squash with the x scale, and a stretched glyph reads as a bug, not a chart.
21
+ const W = 1000;
22
+ const H = 110;
23
+ const ROW_Y = { model: 12, you: 40, mark: 80 };
24
+ const ROW_H = 18;
25
+ // Markers (and, separately, model/you/muted segments) that land within this many viewBox units
26
+ // of each other (1/1000 of the width) collapse into one glyph, at every zoom, not just the
27
+ // whole-session one: a burst of re-arms a few frames apart is exactly as unreadable crammed into
28
+ // a 60 s window as it is crammed into an hour-long one.
29
+ const COLLAPSE_COL = 1;
30
+ const MARKER_COLOUR = {
31
+ rearm: "var(--warn)",
32
+ stop: "var(--purple)",
33
+ focus: "var(--muted-2)",
34
+ error: "var(--error)",
35
+ // --warn-2 exists in both themes (unlike --warn-text, which is light-only), so the stall gets
36
+ // its own shade rather than reusing --warn; the dashed stroke below keeps it further apart from
37
+ // a re-arm still.
38
+ stall: "var(--warn-2)",
39
+ // Distinct from `focus`'s var(--muted-2): a collapsed group of mixed-kind markers is its own
40
+ // thing, not another shade of the same "quiet" colour.
41
+ mixed: "var(--text)",
42
+ };
43
+ // A timed-out entry's `ms` is how long the panel waited, not a measured duration, so it reads as
44
+ // "timed out after" rather than sitting next to a real phase's plain number -- the two should
45
+ // never look interchangeable, or a slow-but-real session_ready reads as having failed. A
46
+ // neverReached entry (the phase never even started) carries no elapsed time worth showing at all.
47
+ function phaseBarTitle(p) {
48
+ return `${phaseLabel(p.name)} ${p.timedOut ? `timed out after ${(p.ms / 1000).toFixed(1)} s` : p.ms + " ms"}`;
49
+ }
50
+ function phaseInlineText(p) {
51
+ if (p.neverReached)
52
+ return html `${phaseLabel(p.name)} never reached`;
53
+ // The overflow entry's `ms` is a placeholder, not a real duration, so it prints just its own
54
+ // name ("+4 more"), never a bold 0 that would read as an actual measured phase.
55
+ if (p.overflow)
56
+ return html `${phaseLabel(p.name)}`;
57
+ return p.timedOut ? html `${phaseLabel(p.name)} timed out after ${(p.ms / 1000).toFixed(1)} s` : html `${phaseLabel(p.name)} <b>${p.ms}</b>`;
58
+ }
59
+ function dotClass(state) {
60
+ if (state === "Connected")
61
+ return "ok";
62
+ if (state === "Failed")
63
+ return "bad";
64
+ // Disconnected is a settled, unremarkable state (the session ended, or never got going yet
65
+ // some other way): a warn dot there reads as an ongoing problem it is not. Connecting and
66
+ // Reconnecting keep the warn colour, still mid-transition.
67
+ if (state === "Disconnected")
68
+ return "";
69
+ return "warn";
70
+ }
71
+ function micClass(state) {
72
+ if (state === "Capturing")
73
+ return "ok";
74
+ if (state === "Paused")
75
+ return "warn";
76
+ if (state === "Muted")
77
+ return "muted";
78
+ return "";
79
+ }
80
+ export function VoicePanel({ onInspect, now = () => Date.now() }) {
81
+ useStorePulse(store, "tick");
82
+ const [zoom, setZoom] = useState("60s");
83
+ // Rebuilding the model is a pass over the session's records, so it is memoized on "new
84
+ // switchboard data landed" and the zoom, not on every render. The slice is keyed on its own
85
+ // size and newest record, not the shared cache's: the cache also takes log and network frames,
86
+ // and its size goes flat once the ring hits its cap. A live session also rebuilds once a
87
+ // second: its window slides with the clock. An ended session's does not (the model closes at
88
+ // the end record, wherever the clock is), so the clock leaves the key once the session ends.
89
+ const ended = useRef(false);
90
+ const rows = store.cache.filter((c) => c.type === "switchboard").map((c) => c.ev);
91
+ const newest = rows.length ? rows[rows.length - 1] : null;
92
+ const dataKey = `${rows.length}:${newest ? newest.timestamp : ""}:${newest ? newest.id : ""}`;
93
+ const clockKey = ended.current ? 0 : Math.floor(now() / 1000);
94
+ const m = useMemo(() => {
95
+ const model = buildVoiceModel(rows, zoom, now());
96
+ ended.current = model !== null && model.ended;
97
+ return model;
98
+ }, [dataKey, zoom, clockKey]);
99
+ // Records exist but none names a session, or there is no switchboard record at all: draw
100
+ // nothing. The feed's own empty state already tells the person what to do next.
101
+ if (!m)
102
+ return null;
103
+ const z = ZOOMS.find((x) => x.key === zoom) ?? ZOOMS[0];
104
+ // Honest framing for the whole-session zoom when the begin record itself was never seen (an
105
+ // older build, or one the cache has since evicted): the panel does not know when the session
106
+ // actually started, only when its first surviving record showed up. A bounded zoom (60 s, 5
107
+ // min) on an ended session says so too, rather than implying the window still slides with now.
108
+ const zoomTitle = zoom === "whole"
109
+ ? !m.hasBegin
110
+ ? "Since first record seen"
111
+ : m.wholeSpanClamped
112
+ ? `${z.title} (last hour)`
113
+ : z.title
114
+ : m.ended
115
+ ? `last ${z.label} before end`
116
+ : z.title;
117
+ // The window's own stat, not a re-filter of m.markers: same set, one less place computing it.
118
+ const rearms = m.stats.rearms;
119
+ // Same tint rule as the re-arms stat card below: a re-arm on its own is routine, only a starved
120
+ // one (0 B queued) is worth the warn colour up here.
121
+ const rearmsStarved = m.stats.rearmsStarved;
122
+ return html `
123
+ <div class="voice">
124
+ <${SessionStrip} m=${m} />
125
+ <div class="voice-card">
126
+ <div class="voice-hd">
127
+ <span>${zoomTitle}${rearms > 0 ? html ` · <span class=${"voice-hd-rearms" + (rearmsStarved > 0 ? " warn" : "")}>${rearms} ${rearms === 1 ? "re-arm" : "re-arms"}</span>` : null}</span>
128
+ <span class="voice-zoom" role="group" aria-label="tracks window">
129
+ ${ZOOMS.map((o) => html `<button type="button" class=${"voice-zoombtn" + (o.key === zoom ? " on" : "")} aria-pressed=${o.key === zoom ? "true" : "false"} onClick=${() => setZoom(o.key)}>${o.label}</button>`)}
130
+ </span>
131
+ </div>
132
+ <${Tracks} m=${m} title=${zoomTitle} rearms=${rearms} onPick=${onInspect} />
133
+ </div>
134
+ <${StatCards} m=${m} />
135
+ </div>
136
+ `;
137
+ }
138
+ function SessionStrip({ m }) {
139
+ const conn = m.connection;
140
+ // Null after the session ended is a real state (the connection record itself is gone or was
141
+ // never there to begin with), not the "nothing has happened yet" case a brand-new session reads
142
+ // as, so it gets its own wording rather than reusing "no session yet".
143
+ const connText = conn ? conn.to : m.ended ? "connection unknown" : "no session yet";
144
+ // A downlink pill reading 0/s while the model is speaking is not a problem in a session too
145
+ // young to have cleared the rate's own minimum divisor yet -- that is exactly what sessionAgeMs
146
+ // guards against. No begin record at all means the age itself is unknown, so it reads the same
147
+ // as "too young" rather than assuming the worst. Past that age, 0 audio frames arriving while
148
+ // the model is supposedly speaking is the downlink itself running dry, not a startup artifact.
149
+ const downlinkWarn = m.speaking?.to === "speaking" && m.sessionAgeMs !== null && m.sessionAgeMs > RATE_MIN_DIVISOR_MS && m.downlink.perSec === 0;
150
+ return html `
151
+ <div class="voice-card">
152
+ <div class="voice-hd">Session</div>
153
+ <div class="voice-strip">
154
+ <span class="voice-pill"><i class=${"voice-dot " + (conn ? dotClass(conn.to) : "")} aria-hidden="true"></i>${connText}${conn && conn.to === "Failed" && conn.cause ? html ` <span class="voice-note">(${conn.cause})</span>` : null}</span>
155
+ ${m.ended ? html `<span class="voice-note voice-ended">ended</span>` : null}
156
+ <span class="voice-kv">session <b>${String(m.sessionId)}</b></span>
157
+ <span class="voice-pill"><i class=${"voice-dot " + micClass(m.mic?.to)} aria-hidden="true"></i>mic ${m.mic ? m.mic.to : "unknown"}</span>
158
+ <span class="voice-pill"><i class=${"voice-dot " + (m.speaking?.to === "speaking" ? "ok" : "")} aria-hidden="true"></i>model ${m.speaking ? m.speaking.to : "unknown"}</span>
159
+ <span class="voice-kv" title=${`outgoing frames per second over the ${m.ended ? "last 10 s before the session ended" : "last 10 s"}, or the session's own age when younger, counting ${m.uplink.rule} frames`}>uplink <b>${m.uplink.perSec.toFixed(1)}/s</b> ${m.uplink.rule === "audio" ? "audio frames" : "frames"}${m.ended ? " at close" : ""}</span>
160
+ <span class=${"voice-kv" + (downlinkWarn ? " warn" : "")} title=${`incoming ${m.downlink.rule === "audio" ? "audio frames" : "frames"} per second over the ${m.ended ? "last 10 s before the session ended" : "last 10 s"}, or the session's own age when younger; 0 while the model is speaking and the session is older than ${RATE_MIN_DIVISOR_MS / 1000} s means no audio frames are arriving`}>downlink <b>${m.downlink.perSec.toFixed(1)}/s</b> ${m.downlink.rule === "audio" ? "audio frames" : "frames"}${m.ended ? " at close" : ""}</span>
161
+ </div>
162
+ ${m.phases.length
163
+ ? html `
164
+ <div class="voice-phases" title="Start phases, left to right, width proportional to time">
165
+ ${
166
+ // A neverReached entry (branch A's synthetic session_ready, when the handshake
167
+ // never even reached the socket phase) carries no elapsed time worth a bar; nor
168
+ // does the "+N more" overflow entry, which has no real duration of its own either.
169
+ // Both still show up in the inline text below, just not here.
170
+ m.phases
171
+ .filter((p) => !p.neverReached && !p.overflow)
172
+ .map((p) => html `<div class=${"voice-phase" + (p.slow ? " slow" : "")} style=${`flex:${Math.max(p.ms, 60)} 0 0`} title=${phaseBarTitle(p)}></div>`)}
173
+ </div>
174
+ <div class="voice-note voice-phasetext" title=${m.phaseWallIsSum
175
+ ? "start to ready is the sum of the phase durations (no begin or ready record to measure the clock from)"
176
+ : `start to ready is the clock from session begin to the session.ready record; the phase durations sum to ${(m.phaseTotalMs / 1000).toFixed(2)} s and can overlap or leave gaps`}>
177
+ ${m.phases.map((p, i) => html `${i ? " · " : ""}<span class=${p.slow ? "voice-slowtxt" : ""}>${phaseInlineText(p)}</span>`)}
178
+ ${" · start to ready "}${m.phaseTimedOut
179
+ ? m.phaseTimedOutFromBegin
180
+ ? html `never (failed ${(m.phaseTimedOutMs / 1000).toFixed(2)} s after start)`
181
+ : html `never (failed after ${(m.phaseTimedOutMs / 1000).toFixed(2)} s of handshake)`
182
+ : html `<b>${(m.phaseWallMs / 1000).toFixed(2)} s</b>`}
183
+ </div>
184
+ `
185
+ : html `<div class="voice-note">no phase records yet</div>`}
186
+ </div>
187
+ `;
188
+ }
189
+ // Markers whose kind reads as an ongoing risk worth a faint full-height guide, not just a tick on
190
+ // the markers row: a rearm/stall/error's exact moment matters against the whole plot, not just
191
+ // against the other markers next to it. Declared ahead of collapseMarkers, which reads it to
192
+ // decide a collapsed group's own `guide`.
193
+ const GUIDE_KINDS = ["rearm", "stall", "error"];
194
+ function collapseMarkers(markers, x) {
195
+ const byCol = new Map();
196
+ for (const k of markers) {
197
+ const col = Math.round(x(k.t) / COLLAPSE_COL);
198
+ const group = byCol.get(col);
199
+ if (group)
200
+ group.push(k);
201
+ else
202
+ byCol.set(col, [k]);
203
+ }
204
+ const out = [];
205
+ for (const group of byCol.values()) {
206
+ if (group.length === 1) {
207
+ const k = group[0];
208
+ out.push({ kind: k.kind, x: x(k.t), label: k.label, record: k.record, multi: false, guide: GUIDE_KINDS.includes(k.kind) });
209
+ continue;
210
+ }
211
+ const kinds = [...new Set(group.map((k) => k.kind))];
212
+ // A collapsed group that landed the same because it is genuinely the same kind keeps that
213
+ // kind (and its colour), just with a `.voice-marker-multi` class added below to say "more than
214
+ // one lives here" -- only a group of actually different kinds becomes "mixed". Clicking a
215
+ // collapsed group always opens the first record; the title says so once there is more than
216
+ // one to miss.
217
+ const openHint = ", click opens the first, zoom in for the rest";
218
+ if (kinds.length === 1) {
219
+ out.push({ kind: kinds[0], x: x(group[0].t), label: `${group.length} × ${group[0].label}${openHint}`, record: group[0].record, multi: true, guide: GUIDE_KINDS.includes(kinds[0]) });
220
+ }
221
+ else {
222
+ out.push({ kind: "mixed", x: x(group[0].t), label: `${group.length} markers (${kinds.join(", ")})${openHint}`, record: group[0].record, multi: true, guide: kinds.some((k) => GUIDE_KINDS.includes(k)) });
223
+ }
224
+ }
225
+ return out;
226
+ }
227
+ // Adjacent segments whose end and next start land in the same viewBox column (same rule as
228
+ // collapseMarkers) merge into one rect: hundreds of a-few-ms-apart state flips squeezed into a
229
+ // single column would otherwise draw hundreds of overlapping slivers nobody can see apart anyway.
230
+ function mergeSegmentsByColumn(segs, x) {
231
+ const out = [];
232
+ for (const s of segs) {
233
+ const last = out[out.length - 1];
234
+ if (last && Math.round(x(s.from) / COLLAPSE_COL) <= Math.round(x(last.to) / COLLAPSE_COL)) {
235
+ last.to = Math.max(last.to, s.to);
236
+ last.open = last.open || s.open;
237
+ }
238
+ else {
239
+ out.push({ ...s });
240
+ }
241
+ }
242
+ return out;
243
+ }
244
+ function Tracks({ m, title, rearms, onPick }) {
245
+ const { from, to } = m.window;
246
+ const span = Math.max(1, to - from);
247
+ const x = (t) => Math.min(W, Math.max(0, ((t - from) / span) * W));
248
+ const step = tickStepMs(span);
249
+ // Ticks run -step, -2 step, ... back to the left edge; the right edge is now and needs no
250
+ // label. tickStepMs already keeps the count at eight or fewer for any span this panel ever
251
+ // draws (the whole-session zoom is itself clamped to the cache TTL), so there is no separate
252
+ // cap to apply here. One unit reads seconds throughout, or minutes throughout, never mixed on
253
+ // the same axis.
254
+ const unitMinutes = step >= 60_000;
255
+ const ticks = [];
256
+ // Starting the loop at i = 1 already keeps off === 0 (which would sit at `to` itself, the right
257
+ // edge, already read as "now"/"end" below) out of the list, so there is nothing left to skip.
258
+ for (let i = 1; i * step <= span; i++) {
259
+ const off = i * step;
260
+ const label = unitMinutes ? `-${Math.round(off / 60_000)}m` : `-${Math.round(off / 1000)}s`;
261
+ ticks.push({ x: x(to - off), label });
262
+ }
263
+ const seg = (s, row, y, fill, opacity) => html `<rect class=${"voice-seg voice-seg-" + row} x=${x(s.from)} y=${y} width=${Math.max(2, x(s.to) - x(s.from))} height=${ROW_H} rx="3" fill=${fill} opacity=${opacity} />`;
264
+ const segMuted = (s) => html `<rect class="voice-seg voice-seg-muted" x=${x(s.from)} y=${ROW_Y.you} width=${Math.max(2, x(s.to) - x(s.from))} height=${ROW_H} rx="3" fill="url(#voice-hatch)" opacity=".9" stroke="var(--purple)" stroke-width="1.5" vector-effect="non-scaling-stroke" />`;
265
+ const model = mergeSegmentsByColumn(m.model, x);
266
+ const you = mergeSegmentsByColumn(m.you, x);
267
+ const youMuted = mergeSegmentsByColumn(m.youMuted, x);
268
+ const drawn = collapseMarkers(m.markers, x);
269
+ const hasMixed = drawn.some((k) => k.kind === "mixed");
270
+ // A burst reads differently from a plain mixed collapse: still one kind throughout, just more
271
+ // than one record of it landed in the same spot (see DrawMarker.multi).
272
+ const hasBurst = drawn.some((k) => k.multi && k.kind !== "mixed");
273
+ const stalls = m.markers.filter((k) => k.kind === "stall").length;
274
+ const failures = m.markers.filter((k) => k.kind === "error").length;
275
+ const label = `voice tracks, ${title.toLowerCase()}, ${m.model.length} model ${m.model.length === 1 ? "turn" : "turns"}, ${rearms} ${rearms === 1 ? "re-arm" : "re-arms"}${stalls > 0 ? `, ${stalls} ${stalls === 1 ? "stall" : "stalls"}` : ""}${failures > 0 ? `, ${failures} ${failures === 1 ? "failure" : "failures"}` : ""}`;
276
+ // Hit-target rects clamp to the midpoint with each neighbour (sorted by x, not draw order) so
277
+ // two markers close enough for their own rects to overlap instead meet exactly in between --
278
+ // whichever one the click lands nearer to is the one that gets it. The tick and guide lines
279
+ // carry pointer-events:none (below), so the rect really is the only shape a click can land on.
280
+ const hitHalf = (k) => (k.multi ? 14 : 12);
281
+ const byX = [...drawn].sort((a, b) => a.x - b.x);
282
+ const hitRange = new Map();
283
+ byX.forEach((k, i) => {
284
+ const half = hitHalf(k);
285
+ const prev = byX[i - 1];
286
+ const next = byX[i + 1];
287
+ const x1 = Math.max(k.x - half, prev ? (prev.x + k.x) / 2 : -Infinity);
288
+ const x2 = Math.min(k.x + half, next ? (k.x + next.x) / 2 : Infinity);
289
+ hitRange.set(k, { x1, x2 });
290
+ });
291
+ return html `
292
+ <div class="voice-tracks">
293
+ <div class="voice-trackrow">
294
+ <div class="voice-rowlabels" aria-hidden="true">
295
+ <span style=${`top:${(ROW_Y.model / H) * 100}%`}>model</span>
296
+ <span style=${`top:${(ROW_Y.you / H) * 100}%`}>you</span>
297
+ <span style=${`top:${(ROW_Y.mark / H) * 100}%`}>markers</span>
298
+ </div>
299
+ <div class="voice-plot">
300
+ <svg viewBox=${`0 0 ${W} ${H}`} preserveAspectRatio="none" role="img" aria-label=${label}>
301
+ <defs>
302
+ <!-- Horizontal bands, not a rotated line: patternTransform skews under the SVG's
303
+ x-only stretch (preserveAspectRatio="none") the same way a plain shape would,
304
+ so the hatch is built from a rect that never needs a transform to begin with. -->
305
+ <pattern id="voice-hatch" patternUnits="userSpaceOnUse" width="4" height="4">
306
+ <rect width="4" height="1.5" fill="var(--purple)" />
307
+ </pattern>
308
+ </defs>
309
+ ${ticks.map((t) => html `<line x1=${t.x} x2=${t.x} y1="0" y2=${H} stroke="var(--border-2)" stroke-width="1" vector-effect="non-scaling-stroke" />`)}
310
+ ${model.map((s) => seg(s, "model", ROW_Y.model, "var(--blue)", ".45"))}
311
+ ${you.map((s) => seg(s, "you", ROW_Y.you, "var(--accent)", ".4"))}
312
+ ${youMuted.map(segMuted)}
313
+ ${drawn.map((k) => {
314
+ const c = MARKER_COLOUR[k.kind];
315
+ // The stroke width is the burst cue: same-kind bursts read 8, wider than a plain
316
+ // single tick; a mixed group's own tick stays 3 either way, its square head line
317
+ // above carrying the multi cue instead; stop reads its own thinner 2 when it is
318
+ // neither of those.
319
+ const strokeWidth = k.kind === "mixed" ? "3" : k.multi ? "8" : k.kind === "stop" ? "2" : "4";
320
+ // An error's line runs a little taller than the row, and a focus (mic-paused) tick
321
+ // only runs the row's own bottom half, so it reads as a lighter-weight event than
322
+ // the ones that span the full row.
323
+ const topY = k.kind === "error" ? ROW_Y.mark - 6 : k.kind === "focus" ? ROW_Y.mark + ROW_H / 2 : ROW_Y.mark;
324
+ // A stall's square cap plus dash reads as "stopped", distinct from every other
325
+ // marker's round cap -- a re-arm and a stall must never look interchangeable at a
326
+ // glance, colour aside.
327
+ const cap = k.kind === "stall" ? "butt" : "round";
328
+ const dash = k.kind === "stall" ? "4 3" : undefined;
329
+ const multiClass = k.multi ? " voice-marker-multi" : "";
330
+ const range = hitRange.get(k);
331
+ return html `<g class=${"voice-marker voice-marker-" + k.kind + multiClass} style="cursor:pointer" onClick=${() => onPick(k.record)}>
332
+ <rect x=${range.x1} y=${ROW_Y.mark - 10} width=${Math.max(0, range.x2 - range.x1)} height=${ROW_H + 12} fill="transparent" />
333
+ <title>${k.label}</title>
334
+ ${k.guide ? html `<line class="voice-guide" x1=${k.x} x2=${k.x} y1="0" y2=${ROW_Y.mark} stroke=${c} stroke-width="1" vector-effect="non-scaling-stroke" pointer-events="none" />` : null}
335
+ <line x1=${k.x} x2=${k.x} y1=${topY} y2=${ROW_Y.mark + ROW_H} stroke=${c} stroke-width=${strokeWidth} stroke-linecap=${cap} stroke-dasharray=${dash} vector-effect="non-scaling-stroke" pointer-events="none" />
336
+ ${
337
+ // A zero-length, round-capped, thick stroke reads as a dot without ever
338
+ // stretching under the SVG's x-only scale (preserveAspectRatio="none"): a real
339
+ // <circle> or <rect> would squash, since only strokes with vector-effect are
340
+ // safe under that stretch.
341
+ k.kind === "error"
342
+ ? html `<line x1=${k.x} x2=${k.x} y1=${topY} y2=${topY} stroke=${c} stroke-width="7" stroke-linecap="round" vector-effect="non-scaling-stroke" />`
343
+ : k.kind === "mixed"
344
+ ? html `<line x1=${k.x} x2=${k.x} y1=${topY - 6} y2=${topY - 6} stroke="var(--text)" stroke-width="6" stroke-linecap="square" vector-effect="non-scaling-stroke" />`
345
+ : null}
346
+ </g>`;
347
+ })}
348
+ </svg>
349
+ <div class="voice-ticklabels" aria-hidden="true">
350
+ ${ticks.map((t) =>
351
+ // The leftmost tick sits at the plot's own left edge: centring it (the default,
352
+ // set in CSS) would draw half the glyph outside the container, so it anchors at
353
+ // its own start instead. `< 1` viewBox unit, not `=== 0`, because a window edge
354
+ // that lands a hair off zero from float division still reads as the left edge.
355
+ html `<span style=${`left:${(t.x / W) * 100}%${t.x < 1 ? ";transform:none" : ""}`}>${t.label}</span>`)}
356
+ <span style="left:100%;transform:translateX(-100%)">${m.ended ? "end" : "now"}</span>
357
+ </div>
358
+ ${drawn.length === 0 ? html `<div class="voice-note voice-nomarkers">no markers in window</div>` : null}
359
+ </div>
360
+ </div>
361
+ <div class="voice-legend">
362
+ <span class="m">model speaking</span>
363
+ <span class="y">you capturing</span>
364
+ <span class="mu">you (muted)</span>
365
+ <span class="r">playback re-arm</span>
366
+ <span class="s">tts.stop sent</span>
367
+ <span class="st">player stall</span>
368
+ <span class="e">connection failed</span>
369
+ <span class="f">mic paused</span>
370
+ ${hasMixed ? html `<span class="mx">multiple markers</span>` : null}
371
+ ${hasBurst ? html `<span class="mb">burst (several at one spot, hover for the count)</span>` : null}
372
+ </div>
373
+ </div>
374
+ `;
375
+ }
376
+ function StatCards({ m }) {
377
+ const s = m.stats;
378
+ // gapSamples, not p50/p95 > 0: a re-arm with no usable gap_ms (see markers()'s own "unusable
379
+ // gap" case) still counts toward rearms but leaves no sample, which used to read the same as a
380
+ // real gap of exactly 0 ms -- both percentiles are 0 either way, so only the sample count tells
381
+ // them apart.
382
+ const hasGapData = s.gapSamples > 0;
383
+ const gapText = s.rearms === 0 ? "0 / 0 ms" : hasGapData ? `${s.gapP50}/${s.gapP95} ms` : "no gap data";
384
+ const gapClass = s.rearms > 0 && hasGapData ? (s.gapP95 > GAP_P95_BAD_MS ? " bad" : " warn") : "";
385
+ return html `
386
+ <div class="voice-cards">
387
+ <div class=${"voice-stat" + (s.rearmsStarved > 0 ? " warn" : "")} title="a re-arm with 0 B queued had nothing left to play; if the downlink pill also reads 0/s the audio stopped arriving">
388
+ <div class="v">${s.rearms}</div>
389
+ ${s.rearms > 0 ? html `<div class="sub">${s.rearmsStarved} starved (0 B queued)</div>` : null}
390
+ <div class="l">playback re-arms</div>
391
+ </div>
392
+ <div class=${"voice-stat" + gapClass} title=${`p95 over ${GAP_P95_BAD_MS} ms reads as choppy`}><div class="v">${gapText}</div><div class="l">gap at re-arm p50 / p95 (bad > ${GAP_P95_BAD_MS} ms)</div></div>
393
+ <div class=${"voice-stat" + (s.preReadyDrop > 0 ? " warn" : "")} title="jitter trim = the player skipped buffered audio to catch up, expected in small numbers; pre-ready = audio landed before session.ready, check the handshake"><div class="v">${s.jitterTrim} / ${s.preReadyDrop}</div><div class="l">drops: jitter trim / pre-ready</div></div>
394
+ <div class="voice-stat" title="includes control frames; the uplink and downlink pills count audio frames only when the device tags them"><div class="v">${s.framesIn} / ${s.framesOut}</div><div class="l">frames in / out this window (all types)</div></div>
395
+ </div>
396
+ `;
397
+ }
@@ -1,5 +1,6 @@
1
1
  import http from "http";
2
2
  import type { StatusReason } from "../shared/wire.js";
3
+ import { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_DEADLINE_MS, SWITCHBOARD_BACKFILL_SESSIONS } from "../shared/switchboard.js";
3
4
  import { type DashboardScreenController } from "../shared/dashboard-screen.js";
4
5
  import type { ProcessState } from "../shared/transport.js";
5
6
  import { type LogFrame } from "./log-session.js";
@@ -41,7 +42,17 @@ export declare function cleanupOnBind(): void;
41
42
  */
42
43
  export declare function registerScreenCleanupOnBind(): void;
43
44
  export declare const TAB_LIVENESS_MS = 75000;
45
+ /**
46
+ * How recently a tab must have polled to count as SOMEONE USING the dashboard, which is a different
47
+ * question from whether it is stale enough to auto-close, and takes a much tighter answer.
48
+ *
49
+ * Three of the dashboard's own five second profile polls. Generous enough that a live tab never
50
+ * flickers out of it, tight enough that closing a window releases the port in seconds rather than in
51
+ * the minute and a quarter TAB_LIVENESS_MS would impose.
52
+ */
53
+ export declare const TAB_IN_USE_MS = 15000;
44
54
  export declare const AUTO_CLOSE_GRACE_MS: number;
55
+ export declare const MCP_IN_USE_MS: number;
45
56
  /**
46
57
  * Pure auto-close decision, mirroring screen.ts's nextViewerAction/shouldRelaunch precedent:
47
58
  * the sweep owns the timestamp bookkeeping, this owns only the yes/no. Close only when there
@@ -50,6 +61,53 @@ export declare const AUTO_CLOSE_GRACE_MS: number;
50
61
  * Exported for unit testing without a clock or a socket.
51
62
  */
52
63
  export declare function shouldAutoClose(liveTabs: number, everSeen: boolean, msSinceEmpty: number | null): boolean;
64
+ /**
65
+ * Whether anyone is using this dashboard RIGHT NOW, which is a different question from
66
+ * shouldAutoClose() above and deliberately not the same answer.
67
+ *
68
+ * shouldAutoClose adds the grace window, because a process deciding to end itself should be slow
69
+ * about it. This is read by a DIFFERENT process deciding whether it may take the port, and there the
70
+ * grace window is exactly wrong: the five minutes after a dock app quits and its tab closes is the
71
+ * window an upgrade lands in, and a leftover nobody is looking at is the thing that most needs
72
+ * replacing.
73
+ *
74
+ * So: a live tab counts, and an MCP session with no tab open counts (markKeepAlive clears the empty
75
+ * marker without setting everSeen, which is what keeps an hour-long debugging session alive), but a
76
+ * dashboard whose last tab has gone does not.
77
+ *
78
+ * Exported for unit testing without a clock or a socket, same as shouldAutoClose.
79
+ */
80
+ export declare function isInUse(now?: number): boolean;
81
+ /**
82
+ * Which decision an in-use answer is about to inform.
83
+ *
84
+ * `take` is a caller asking whether it may take a port it does not own. `stop` is a caller asking whether
85
+ * it may stop a server it started itself. The two get different answers on purpose, and the reasons are at
86
+ * the two places inUseReason branches on this: a guess that protects a port must not also protect a
87
+ * process from its own parent, and a window sized so a closed tab stops blocking a replacement is too
88
+ * tight for deciding whether somebody is still reading a page.
89
+ */
90
+ export type InUseDecision = "take" | "stop";
91
+ /**
92
+ * WHY this dashboard is in use, not merely whether, because the two claims are worth different
93
+ * decisions to the process asking.
94
+ *
95
+ * A "tab" claim is a window someone has open. A "mcp" claim is an agent session driving this
96
+ * dashboard with no window of its own, and stopping that costs the session's pulled databases, its
97
+ * device pin and its logcat ring, none of which it can get back. A single yes/no cannot tell those
98
+ * apart, so a launcher had to treat them the same, and the only safe reading of "the same" is the
99
+ * cautious one, which then blocks the upgrade this whole path exists to perform.
100
+ *
101
+ * Priority is deliberate: an mcp claim outranks a tab claim, because the app's OWN window is a tab
102
+ * and a decision about whether to disturb someone else must not be answered by our own presence.
103
+ *
104
+ * `ignoreTab` is how a caller asks the narrower question it actually has: is anyone OTHER than my own
105
+ * window using this. The dock app generates the presence id, hands it to the page it loads, and sends
106
+ * it back here, so its own window stops answering for everybody else. Without it the app could not
107
+ * tell its own tab from a real second browser tab, and had to guess; guessing either way is wrong,
108
+ * because one reading kills a page someone is reading and the other never stops anything.
109
+ */
110
+ export declare function inUseReason(now?: number, ignoreTab?: string, decision?: InUseDecision): "tab" | "mcp" | "no";
53
111
  export declare function touchTab(id: string, now?: number): void;
54
112
  /**
55
113
  * Treat an authored MCP write (a /setspec, a successful /enable) as a keep-alive equivalent to
@@ -59,7 +117,7 @@ export declare function touchTab(id: string, now?: number): void;
59
117
  * pin, and the pulled-DB cache. Deliberately does NOT set everSeen: an MCP-only dashboard that
60
118
  * nobody ever opened stays protected by the everSeen guard even after the MCP goes quiet.
61
119
  */
62
- export declare function markKeepAlive(): void;
120
+ export declare function markKeepAlive(now?: number): void;
63
121
  /**
64
122
  * Whether a request may buy the process more life. True for our own client and the MCP, false
65
123
  * for anything else, so a foreign page cannot postpone auto-close forever.
@@ -81,6 +139,43 @@ export declare function isAuthoredRequest(headers: {
81
139
  "x-radar-dashboard"?: string | string[];
82
140
  "content-type"?: string | string[];
83
141
  }): boolean;
142
+ /**
143
+ * "This request comes FROM the tab with this id." Sent by the dashboard page on its own authored
144
+ * writes, so a write can be credited to the window that made it.
145
+ */
146
+ export declare function readTabIdentity(headers: http.IncomingHttpHeaders): string | undefined;
147
+ /**
148
+ * "Leave this id out of the answer." Sent by a launcher asking whether anyone OTHER than the window it
149
+ * owns is using this dashboard.
150
+ *
151
+ * A separate header from the identity one above, carrying the same value, and deliberately so: the app
152
+ * that sends this is NOT the tab. Its window may have failed to load, or may be showing the failure
153
+ * page. One header would invite a future route to treat the app's own probe as proof that its tab is
154
+ * live, which would record presence for a window that does not exist. Two names make that impossible
155
+ * rather than merely discouraged.
156
+ */
157
+ export declare function readIgnoredTab(headers: http.IncomingHttpHeaders): string | undefined;
158
+ /**
159
+ * Which decision the caller says it is about to make. Anything other than the one recognised value reads as
160
+ * `take`, which is both the back-compatible answer (no installed launcher sends this) and the conservative
161
+ * one: it is the reading that protects a port rather than the one that permits a stop.
162
+ */
163
+ export declare function readInUseDecision(headers: http.IncomingHttpHeaders): InUseDecision;
164
+ /**
165
+ * Credit an authored write to whoever made it: a tab that named itself, or an agent session.
166
+ *
167
+ * The distinction is load-bearing, and getting it wrong was a real bug. `markKeepAlive` is what makes
168
+ * inUseReason answer "mcp", and the dashboard PAGE makes authored writes too: `bootDefault` posts
169
+ * /setspec on any page load that finds a blank spec, and every mode switch and filter Apply posts
170
+ * another. So a person opening the dock app and clicking one tab made the server report an agent
171
+ * session for the next MCP_IN_USE_MS, and "mcp" is the one claim nothing overrides — the launcher
172
+ * refuses to replace it and the quit path refuses to stop it. The app then left its own server running
173
+ * on quit, which is the exact leak the quit path exists to close, reachable by ordinary use.
174
+ *
175
+ * A tab's write is credited as presence instead, which is both true and stronger: it is the same thing
176
+ * the tab's own /health poll records. Only a write from something with no tab at all is a session.
177
+ */
178
+ export declare function creditAuthoredWrite(tab: string | undefined, now?: number): void;
84
179
  /**
85
180
  * One sweep tick: prune stale tab ids, maintain the emptySince marker across the 1->0 / 0->1
86
181
  * transitions, and return whether the dashboard should auto-close now. Owns all timestamp
@@ -167,10 +262,10 @@ export declare function createServer(onShutdown?: (server: http.Server) => void)
167
262
  * successful re-arm keeps the dashboard alive (an MCP-driven session can re-enable with no tab
168
263
  * open, and that must not let the idle timer fire out from under it).
169
264
  *
170
- * `onEnabled` fires only on a successful probe. The route passes `markKeepAlive` when the
171
- * request was authored (see isAuthoredRequest) and OMITS it otherwise, so an unauthored caller
172
- * gets the same body but buys no extra process life. Injected rather than called directly so
173
- * the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
265
+ * `onEnabled` fires only on a successful probe. The route passes a hook that credits the WRITER
266
+ * (creditAuthoredWrite) when the request was authored (see isAuthoredRequest) and OMITS it otherwise, so
267
+ * an unauthored caller gets the same body but buys no extra process life. Injected rather than called
268
+ * directly so the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
174
269
  * a real socket to RADAR_HOST:RADAR_PORT, which this function does not touch at all).
175
270
  *
176
271
  * A failed probe gets guidance, not a bare false: the broadcast landed (or exited 0 with no
@@ -183,8 +278,11 @@ export declare function createServer(onShutdown?: (server: http.Server) => void)
183
278
  * through the route cannot cover this — handleEnable's device probe fails with no hardware, which
184
279
  * short-circuits before the hook is ever consulted, so a route-level test passes either way (a
185
280
  * mutation deleting the gate survived the whole suite before this existed).
281
+ *
282
+ * `tab` is the writer, and it decides WHICH credit the hook applies: a re-arm pressed in the dashboard
283
+ * is a window's, not an agent session's. See creditAuthoredWrite.
186
284
  */
187
- export declare function keepAliveHookFor(authored: boolean): (() => void) | undefined;
285
+ export declare function keepAliveHookFor(authored: boolean, tab?: string): (() => void) | undefined;
188
286
  /**
189
287
  * Whether the dashboard serves this request without proof of origin. Everything else is refused
190
288
  * unless authored. Exported so a test can drive the decision directly, and so the open surface is
@@ -223,6 +321,12 @@ export declare const DEVICE_SOURCES: Record<string, {
223
321
  segment: string;
224
322
  arrayKey: string;
225
323
  }>;
324
+ export { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_SESSIONS, SWITCHBOARD_BACKFILL_DEADLINE_MS };
325
+ export declare const BACKFILL_ROUTE_HEADROOM_MS = 250;
326
+ export declare function fetchSwitchboardBackfill(limit: number, deadlineMs?: number): Promise<{
327
+ type: string;
328
+ event: Record<string, unknown>;
329
+ }[]>;
226
330
  /**
227
331
  * Finish a /detail proxy response after an upstream error or timeout. The success
228
332
  * callback streams the upstream response, so headers may already be sent when a later