@slack/radar-mcp 1.20.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 (41) hide show
  1. package/README.md +11 -6
  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 +62 -16
  17. package/dist/shared/constants.d.ts +10 -0
  18. package/dist/shared/constants.js +10 -0
  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/public/index.html +172 -10
  27. package/dist/web/public/next/app.js +16 -10
  28. package/dist/web/public/next/db.js +4 -1
  29. package/dist/web/public/next/feed.js +515 -57
  30. package/dist/web/public/next/filters.js +158 -40
  31. package/dist/web/public/next/form-body.js +252 -0
  32. package/dist/web/public/next/inspector.js +103 -12
  33. package/dist/web/public/next/registry.js +21 -2
  34. package/dist/web/public/next/store.js +503 -51
  35. package/dist/web/public/next/voice-model.js +532 -0
  36. package/dist/web/public/next/voice.js +397 -0
  37. package/dist/web/server.d.ts +7 -0
  38. package/dist/web/server.js +154 -16
  39. package/dist/web/spec.d.ts +10 -6
  40. package/dist/web/spec.js +61 -6
  41. 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";
@@ -320,6 +321,12 @@ export declare const DEVICE_SOURCES: Record<string, {
320
321
  segment: string;
321
322
  arrayKey: string;
322
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
+ }[]>;
323
330
  /**
324
331
  * Finish a /detail proxy response after an upstream error or timeout. The success
325
332
  * callback streams the upstream response, so headers may already be sent when a later
@@ -1,4 +1,5 @@
1
1
  import http from "http";
2
+ import { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_DEADLINE_MS, SWITCHBOARD_BACKFILL_SESSIONS, newestSwitchboardSessionIds, switchboardListPath, switchboardPageEvents, switchboardSessionPath, } from "../shared/switchboard.js";
2
3
  import fs from "fs";
3
4
  import os from "os";
4
5
  import path from "path";
@@ -1880,12 +1881,111 @@ export const DEVICE_SOURCES = {
1880
1881
  clog: { segment: "clogs", arrayKey: "clogs" },
1881
1882
  trace: { segment: "traces", arrayKey: "traces" },
1882
1883
  };
1884
+ // Switchboard (the Slackbot voice transport) is not a row above because the device keeps it two
1885
+ // levels deep: `GET /api/switchboard` lists session summaries newest first (`total_captured` is
1886
+ // the records the plugin holds; there is no count named `events`), `GET /api/switchboard/<session_id>`
1887
+ // is that summary plus `events`, the page of records oldest first (the newest `limit` of them; the
1888
+ // device pages at 50 when the query is absent, so the caller's limit is forwarded per session or
1889
+ // a talkative session replays as its last few seconds). Records carry a plugin-minted `id`
1890
+ // (strictly increasing across sessions), but there is no per-record /detail, so it stays out of
1891
+ // the table /detail reads. The session cap bounds the round trips on connect (one list plus one
1892
+ // fetch per session); `limit` bounds the records, per session and again on the merged total.
1893
+ // Shapes: SwitchboardSessionSummary in src/shared/wire.ts; `levels` there is unread here (no
1894
+ // waveform yet). The session pick and the paths live in src/shared/switchboard.ts so the MCP's
1895
+ // spool backfill replays the same sessions; re-exported here for the tests that pin them.
1896
+ export { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_SESSIONS, SWITCHBOARD_BACKFILL_DEADLINE_MS };
1897
+ // How much longer than the switchboard leg's own deadline the /backfill route waits before it
1898
+ // replies with what has landed. Same-length timers fire in the order they were armed, and the
1899
+ // route's is armed first, so without this the route would reply before the leg could hand back the
1900
+ // sessions that answered.
1901
+ export const BACKFILL_ROUTE_HEADROOM_MS = 250;
1902
+ function getDeviceJson(apiPath) {
1903
+ let rq;
1904
+ const result = new Promise((resolve) => {
1905
+ rq = http.request({ host: RADAR_HOST, port: RADAR_PORT, path: apiPath, method: "GET", timeout: 4000 }, (up) => {
1906
+ let b = "";
1907
+ up.on("data", (c) => (b += c));
1908
+ up.on("end", () => {
1909
+ try {
1910
+ const j = JSON.parse(b);
1911
+ resolve(j !== null && typeof j === "object" && !Array.isArray(j) ? j : null);
1912
+ }
1913
+ catch {
1914
+ resolve(null);
1915
+ }
1916
+ });
1917
+ up.on("error", () => resolve(null));
1918
+ });
1919
+ rq.on("error", () => resolve(null));
1920
+ rq.on("timeout", () => {
1921
+ rq?.destroy();
1922
+ resolve(null);
1923
+ });
1924
+ rq.on("close", () => resolve(null));
1925
+ rq.end();
1926
+ });
1927
+ return { result, abort: () => rq?.destroy() };
1928
+ }
1929
+ // The switchboard replay: the newest SWITCHBOARD_BACKFILL_SESSIONS sessions' records, oldest first,
1930
+ // trimmed to the newest `limit` records overall, as `{type: "switchboard", event}` frames.
1931
+ // Exported so a test can drive it against a fake device without going through the route; the
1932
+ // deadline is a parameter for the same reason. Each session's page is kept as it lands, so when
1933
+ // the deadline fires the reply is whatever arrived by then (a device sitting on one session's
1934
+ // route costs that session, not the whole replay), and the requests still open are dropped.
1935
+ export function fetchSwitchboardBackfill(limit, deadlineMs = SWITCHBOARD_BACKFILL_DEADLINE_MS) {
1936
+ return new Promise((resolve) => {
1937
+ const landed = [];
1938
+ const inflight = new Set();
1939
+ let settled = false;
1940
+ const finish = () => {
1941
+ if (settled)
1942
+ return;
1943
+ settled = true;
1944
+ clearTimeout(timer);
1945
+ for (const g of inflight)
1946
+ g.abort();
1947
+ inflight.clear();
1948
+ resolve(newestSwitchboardRecords(landed.flat(), limit));
1949
+ };
1950
+ const timer = setTimeout(finish, deadlineMs);
1951
+ fetchSwitchboardSessions(limit, landed, inflight).then(finish, finish);
1952
+ });
1953
+ }
1954
+ // Lists the sessions, then fetches the newest few in parallel, pushing each page onto `landed`
1955
+ // as it arrives and keeping the open requests in `inflight` for the deadline above.
1956
+ async function fetchSwitchboardSessions(limit, landed, inflight) {
1957
+ const get = async (apiPath) => {
1958
+ const g = getDeviceJson(apiPath);
1959
+ inflight.add(g);
1960
+ try {
1961
+ return await g.result;
1962
+ }
1963
+ finally {
1964
+ inflight.delete(g);
1965
+ }
1966
+ };
1967
+ const list = await get(switchboardListPath());
1968
+ await Promise.all(newestSwitchboardSessionIds(list).map(async (id) => {
1969
+ // `events` is the page of records on this route; the list route's count is `total_captured`.
1970
+ landed.push(switchboardPageEvents(await get(switchboardSessionPath(id, limit))));
1971
+ }));
1972
+ }
1973
+ // The merge order for every backfill: the record's own device timestamp, 0 when it has none.
1974
+ const when = (e) => Number(e.timestamp) || 0;
1975
+ // Oldest first by the record's own timestamp, then the newest `limit` kept. The pages arrive in
1976
+ // whatever order the device answers, so arrival order says nothing about time; the sort is stable,
1977
+ // so records sharing a timestamp keep the order the device wrote them in.
1978
+ function newestSwitchboardRecords(records, limit) {
1979
+ const sorted = [...records].sort((a, b) => when(a) - when(b));
1980
+ return sorted.slice(Math.max(0, sorted.length - limit)).map((e) => ({ type: SWITCHBOARD_KIND, event: e }));
1981
+ }
1883
1982
  /**
1884
1983
  * Replay the device's recent ring buffers for a source so a freshly-built tab
1885
1984
  * shows history immediately instead of filling only going forward. The device is
1886
- * the source of truth. "all" pulls network+rtm+clog+trace and merges them oldest->newest;
1887
- * "log" is host-side (no device buffer) and so has nothing to replay. Returns
1888
- * `[{type, event}]` frames mirroring the stream shape.
1985
+ * the source of truth. "all" pulls network+rtm+clog+trace+switchboard and merges them
1986
+ * oldest->newest; "log" is host-side (no device buffer) and so has nothing to replay. Returns
1987
+ * `[{type, event}]` frames mirroring the stream shape. Switchboard records carry `timestamp`
1988
+ * (epoch ms) like the ring kinds, so one sort key orders the merge.
1889
1989
  */
1890
1990
  function handleBackfill(req, res) {
1891
1991
  // Reassert before reading: see forwardForRead's doc comment. A failed reassert still
@@ -1895,12 +1995,51 @@ function handleBackfill(req, res) {
1895
1995
  forwardForRead();
1896
1996
  const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
1897
1997
  const src = u.searchParams.get("source") ?? "network";
1898
- const limit = Math.min(500, Number(u.searchParams.get("limit")) || 200);
1998
+ // Clamped below at 1: a negative limit would slice the switchboard replay to nothing. Truncated
1999
+ // first so a fractional limit reaches the device as a whole number it can parse.
2000
+ const limit = Math.max(1, Math.min(500, Math.trunc(Number(u.searchParams.get("limit"))) || 200));
1899
2001
  const kinds = src === "all"
1900
2002
  ? Object.keys(DEVICE_SOURCES)
1901
2003
  : [src].filter((k) => Object.hasOwn(DEVICE_SOURCES, k));
2004
+ const wantsSwitchboard = src === "all" || src === SWITCHBOARD_KIND;
2005
+ // Every leg lands its frames here as it finishes; the reply is whatever has landed when the last
2006
+ // leg settles or the route's deadline fires, whichever is first. A ring leg has only the
2007
+ // socket's inactivity timeout, which measures silence, not progress: the device writes each
2008
+ // body in one go, but a large page over a slow adb pipe keeps bytes trickling and a wedged
2009
+ // tunnel can stall mid-body, and either would otherwise hold the whole reply. The switchboard
2010
+ // leg keeps its own deadline, armed later and for the same span, so the route gives it headroom
2011
+ // to fire first and hand back the sessions that did answer; a slow session route then costs that
2012
+ // session alone, not the replay.
2013
+ const landed = [];
2014
+ const inflight = new Set();
2015
+ let settled = false;
2016
+ const finish = () => {
2017
+ if (settled)
2018
+ return;
2019
+ settled = true;
2020
+ clearTimeout(timer);
2021
+ for (const rq of inflight)
2022
+ rq.destroy();
2023
+ inflight.clear();
2024
+ const merged = landed.flat().sort((a, b) => when(a.event) - when(b.event));
2025
+ sendJson(res, 200, { frames: merged });
2026
+ };
2027
+ // The ceiling for every leg, ring legs included: the switchboard span already sits above the
2028
+ // ring legs' 4 s socket timeout, so one number serves both.
2029
+ const timer = setTimeout(finish, SWITCHBOARD_BACKFILL_DEADLINE_MS + BACKFILL_ROUTE_HEADROOM_MS);
1902
2030
  const fetchKind = (kind) => new Promise((resolve) => {
1903
2031
  const apiPath = `/api/${DEVICE_SOURCES[kind].segment}?limit=${limit}`;
2032
+ // Settles once whichever of end, error, timeout or close comes first; the route's deadline
2033
+ // destroys the request, which raises close with no error, so close settles it too.
2034
+ let legDone = false;
2035
+ const done = (frames) => {
2036
+ if (legDone)
2037
+ return;
2038
+ legDone = true;
2039
+ inflight.delete(rq);
2040
+ landed.push(frames);
2041
+ resolve();
2042
+ };
1904
2043
  const rq = http.request({
1905
2044
  host: RADAR_HOST,
1906
2045
  port: RADAR_PORT,
@@ -1910,32 +2049,31 @@ function handleBackfill(req, res) {
1910
2049
  }, (up) => {
1911
2050
  let b = "";
1912
2051
  up.on("data", (c) => (b += c));
2052
+ up.on("error", () => done([]));
1913
2053
  up.on("end", () => {
1914
2054
  try {
1915
2055
  const j = JSON.parse(b);
1916
2056
  const arr = j[DEVICE_SOURCES[kind].arrayKey] ?? [];
1917
- resolve(arr.map((e) => ({ type: kind, event: e })));
2057
+ done(arr.map((e) => ({ type: kind, event: e })));
1918
2058
  }
1919
2059
  catch {
1920
- resolve([]);
2060
+ done([]);
1921
2061
  }
1922
2062
  });
1923
2063
  });
1924
- rq.on("error", () => resolve([]));
2064
+ inflight.add(rq);
2065
+ rq.on("error", () => done([]));
2066
+ rq.on("close", () => done([]));
1925
2067
  rq.on("timeout", () => {
1926
2068
  rq.destroy();
1927
- resolve([]);
2069
+ done([]);
1928
2070
  });
1929
2071
  rq.end();
1930
2072
  });
1931
- Promise.all(kinds.map(fetchKind))
1932
- .then((lists) => {
1933
- const merged = lists
1934
- .flat()
1935
- .sort((a, b) => (Number(a.event.timestamp) || 0) - (Number(b.event.timestamp) || 0));
1936
- sendJson(res, 200, { frames: merged });
1937
- })
1938
- .catch(() => sendJson(res, 200, { frames: [] }));
2073
+ const legs = kinds.map(fetchKind);
2074
+ if (wantsSwitchboard)
2075
+ legs.push(fetchSwitchboardBackfill(limit).then((frames) => { landed.push(frames); }));
2076
+ Promise.all(legs).then(finish, finish);
1939
2077
  }
1940
2078
  /**
1941
2079
  * Finish a /detail proxy response after an upstream error or timeout. The success