@slack/radar-mcp 1.23.0 → 1.25.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 (55) hide show
  1. package/README.md +14 -7
  2. package/dist/mcp/dashboard-identity.d.ts +10 -0
  3. package/dist/mcp/dashboard-identity.js +20 -0
  4. package/dist/mcp/debug-package-reset.d.ts +5 -0
  5. package/dist/mcp/debug-package-reset.js +28 -0
  6. package/dist/mcp/flags-tools.d.ts +2 -0
  7. package/dist/mcp/flags-tools.js +10 -2
  8. package/dist/mcp/index.js +74 -54
  9. package/dist/mcp/radar-http.js +3 -1
  10. package/dist/mcp/session-enable.d.ts +1 -0
  11. package/dist/mcp/session-enable.js +52 -8
  12. package/dist/mcp/switchboard-tools.d.ts +5 -2
  13. package/dist/mcp/switchboard-tools.js +18 -12
  14. package/dist/mcp/tools.js +69 -169
  15. package/dist/mcp/web-child-env.js +2 -1
  16. package/dist/shared/android.d.ts +74 -10
  17. package/dist/shared/android.js +344 -103
  18. package/dist/shared/constants.d.ts +17 -5
  19. package/dist/shared/constants.js +59 -5
  20. package/dist/shared/db.d.ts +1 -1
  21. package/dist/shared/db.js +21 -14
  22. package/dist/shared/debug-log.js +2 -4
  23. package/dist/shared/enable-diagnosis.d.ts +27 -1
  24. package/dist/shared/enable-diagnosis.js +73 -0
  25. package/dist/shared/feature-flags.d.ts +11 -0
  26. package/dist/shared/feature-flags.js +18 -4
  27. package/dist/shared/log-session.d.ts +2 -1
  28. package/dist/shared/prefs.js +4 -5
  29. package/dist/shared/radar-request-raw.js +3 -1
  30. package/dist/shared/switchboard-note.d.ts +19 -0
  31. package/dist/shared/switchboard-note.js +76 -0
  32. package/dist/shared/switchboard-report.js +40 -4
  33. package/dist/shared/switchboard.d.ts +2 -1
  34. package/dist/shared/switchboard.js +17 -3
  35. package/dist/shared/transport.d.ts +24 -0
  36. package/dist/shared/wire.d.ts +2 -0
  37. package/dist/web/install-app-cli.d.ts +2 -0
  38. package/dist/web/install-app-cli.js +60 -0
  39. package/dist/web/install-app.d.ts +16 -7
  40. package/dist/web/install-app.js +92 -39
  41. package/dist/web/macapp/RadarApp.swift +12 -11
  42. package/dist/web/public/index.html +4 -2
  43. package/dist/web/public/next/feature-flags.js +33 -0
  44. package/dist/web/public/next/feed.js +13 -2
  45. package/dist/web/public/next/flags.js +15 -3
  46. package/dist/web/public/next/registry.js +4 -4
  47. package/dist/web/public/next/store.js +89 -3
  48. package/dist/web/public/next/switchboard-note.js +76 -0
  49. package/dist/web/public/next/voice-model.js +196 -14
  50. package/dist/web/public/next/voice.js +68 -10
  51. package/dist/web/server.d.ts +17 -0
  52. package/dist/web/server.js +180 -35
  53. package/dist/web/spec.d.ts +1 -1
  54. package/dist/web/spec.js +1 -1
  55. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import { CACHE_TTL_MS } from "./registry.js";
2
- import { CLIP_PEAK, SAVED_TURN_OUTCOMES, savedTurnCountEntries } from "./switchboard-note.js";
2
+ import { CLIP_PEAK, SAVED_TURN_OUTCOMES, SERVER_SESSION_ID_CAP, cardLabel, openCards, savedTurnCountEntries, serverEndedNormally } from "./switchboard-note.js";
3
3
  // Re-exported so a model test can assert the clamp without importing the registry module itself.
4
4
  export { CACHE_TTL_MS };
5
5
  export { CLIP_PEAK };
@@ -159,6 +159,28 @@ export function segments(rows, stateKind, onValue, now) {
159
159
  out.push({ from: openAt, to: Math.max(now, openAt), open: true });
160
160
  return out;
161
161
  }
162
+ // Spans where the user held the reply: a `player` reply_hold opens one, the next reply_unhold
163
+ // closes it, and a hold still open runs to `endT` (the session's end, or now on a live call). A
164
+ // repeated hold while one is open and an unhold with nothing open say nothing new, so they are
165
+ // ignored.
166
+ export function replyHolds(rows, endT) {
167
+ const out = [];
168
+ let openAt = null;
169
+ for (const r of rows) {
170
+ if (r.kind !== "player")
171
+ continue;
172
+ const t = recordTime(r);
173
+ if (r.event === "reply_hold" && openAt === null)
174
+ openAt = t;
175
+ else if (r.event === "reply_unhold" && openAt !== null) {
176
+ out.push({ from: openAt, to: Math.max(t, openAt), open: false });
177
+ openAt = null;
178
+ }
179
+ }
180
+ if (openAt !== null)
181
+ out.push({ from: openAt, to: Math.max(endT, openAt), open: true });
182
+ return out;
183
+ }
162
184
  // A tts.stop marker's own label needs to know what happened after it: whether the model actually
163
185
  // went quiet before the next stop was sent, and how long that took. Scans forward from the stop's
164
186
  // own position rather than the whole array, so an earlier stop never borrows a later stop's quiet.
@@ -265,13 +287,23 @@ export function markers(rows, window) {
265
287
  const wasSpeaking = lastSpeakingTo !== "quiet";
266
288
  out.push({ kind: "stop", t, label: stopFollowUpLabel(rows, i, t, wasSpeaking, ended), record: r });
267
289
  }
290
+ else if (r.kind === "card") {
291
+ out.push({ kind: "card", t, label: cardLabel(r.card_kind, r.event, r.by), record: r });
292
+ }
268
293
  else if (r.kind === "state" && r.state_kind === "mic" && r.to === "Paused") {
269
294
  const cause = str(r.cause);
270
295
  out.push({ kind: "focus", t, label: cause ? `mic Paused (${cause})` : "mic Paused", record: r });
271
296
  }
272
297
  else if (r.kind === "state" && r.state_kind === "connection" && r.to === "Failed") {
273
298
  const cause = str(r.cause);
274
- out.push({ kind: "error", t, label: cause ? `connection Failed (${cause})` : "connection Failed", record: r });
299
+ // A server ending that is a normal end (a limit, the model's goodbye) is not a fault, so it
300
+ // gets its own neutral kind instead of the red error.
301
+ if (serverEndedNormally(cause)) {
302
+ out.push({ kind: "ending", t, label: `server ended the call (${cause})`, record: r });
303
+ }
304
+ else {
305
+ out.push({ kind: "error", t, label: cause ? `connection Failed (${cause})` : "connection Failed", record: r });
306
+ }
275
307
  }
276
308
  }
277
309
  return out;
@@ -279,10 +311,15 @@ export function markers(rows, window) {
279
311
  // `pending` requires evidence the build reports ids at all (a ready or levels record, or the
280
312
  // summary key present). A ready record with no id settles it as "no id"; a null summary does
281
313
  // not, since the summary is a snapshot rather than the one-shot event.
282
- export function serverSessionId(rows, ended, summaryServerSessionId) {
314
+ export function serverSessionId(rows, ended, summaryServerSessionId, summaryServerSessionIds) {
283
315
  let id = null;
284
316
  let knownNewBuild = false;
285
317
  let seenReady = false;
318
+ const all = summaryServerSessionIds ? [...new Set(summaryServerSessionIds)] : [];
319
+ // The refill holds up to 2000 rows but the summary list only the newest 8, so a ready row for an
320
+ // id before the list's last one is older than the list. Only rows after that id's row extend it.
321
+ const listLast = all.length > 0 ? all[all.length - 1] : null;
322
+ let pastListLast = listLast === null;
286
323
  for (const r of rows) {
287
324
  if (r.kind === "levels")
288
325
  knownNewBuild = true;
@@ -291,15 +328,22 @@ export function serverSessionId(rows, ended, summaryServerSessionId) {
291
328
  knownNewBuild = true;
292
329
  seenReady = true;
293
330
  const v = str(r.server_session_id);
294
- if (v !== null)
331
+ if (v !== null) {
295
332
  id = v;
333
+ if (summaryServerSessionIds && !all.includes(v) && pastListLast)
334
+ all.push(v);
335
+ if (v === listLast)
336
+ pastListLast = true;
337
+ }
296
338
  }
339
+ if (all.length > SERVER_SESSION_ID_CAP)
340
+ all.splice(0, all.length - SERVER_SESSION_ID_CAP);
297
341
  if (summaryServerSessionId !== undefined) {
298
342
  knownNewBuild = true;
299
343
  if (id === null && summaryServerSessionId !== null)
300
344
  id = summaryServerSessionId;
301
345
  }
302
- return { id, pending: knownNewBuild && id === null && !ended && !seenReady };
346
+ return { id, pending: knownNewBuild && id === null && !ended && !seenReady, all };
303
347
  }
304
348
  // Whether the rows prove the device had no server id: a held ready record, and none of them named
305
349
  // one. A null summary id is not proof, since a refill taken at begin reads null before the ready
@@ -462,18 +506,31 @@ export function downlinkRate(rows, now, windowMs = RATE_WINDOW_MS, sessionBeginA
462
506
  // past this many unknown-order entries the waterfall reads as noise, not a chart, so the rest
463
507
  // collapse into one "+N more" entry rather than drawing all of them.
464
508
  const MAX_EXTRA_PHASES = 8;
465
- // One entry per phase name in handshake order, the latest record of a name winning; names the
509
+ // One entry per phase name in handshake order, the latest record of a name winning (socket and
510
+ // session_ready read the handshake's own, the first ready and the socket before it); names the
466
511
  // order does not know go after, in arrival order, capped at MAX_EXTRA_PHASES with a trailing
467
512
  // "+N more" entry. A phase without a numeric duration is skipped.
468
- export function phases(rows) {
513
+ // The handshake ends at the first timed session_ready; a reconnect repeats socket and
514
+ // session_ready after it. -1 when there is none yet.
515
+ export function firstReadyIndex(rows) {
516
+ return rows.findIndex((r) => r.kind === "phase" && str(r.phase) === "session_ready" && num(r.duration_ms) !== null);
517
+ }
518
+ export function phases(rows, firstReady = firstReadyIndex(rows)) {
469
519
  const byName = new Map();
470
- for (const r of rows) {
520
+ // Letting a reconnect's socket or session_ready win would time the start off the last
521
+ // reconnect, so only those two names stop at the first ready; every other name still takes its
522
+ // latest record.
523
+ for (const [i, r] of rows.entries()) {
471
524
  if (r.kind !== "phase")
472
525
  continue;
473
526
  const name = str(r.phase);
474
527
  const ms = num(r.duration_ms);
475
528
  if (name === null || ms === null)
476
529
  continue;
530
+ if (firstReady !== -1 && name === "socket" && i > firstReady)
531
+ continue;
532
+ if (firstReady !== -1 && name === "session_ready" && i !== firstReady)
533
+ continue;
477
534
  byName.set(name, ms);
478
535
  }
479
536
  const known = PHASE_ORDER.filter((n) => byName.has(n));
@@ -488,6 +545,109 @@ export function phases(rows) {
488
545
  list.push({ name: `+${overflow} more`, ms: 0, slow: false, overflow: true });
489
546
  return { list, totalMs: list.reduce((a, p) => a + p.ms, 0) };
490
547
  }
548
+ // What happened after the handshake's first session_ready, read only off the socket and
549
+ // session_ready phase records so it works even when no Reconnecting state ever arrived. A socket
550
+ // opens a reconnect and the next session_ready closes it; a ready with no socket open stands
551
+ // alone, and a socket still open at the end has no ready yet.
552
+ export function reconnects(rows, firstReady = firstReadyIndex(rows)) {
553
+ const after = rows.slice(firstReady + 1);
554
+ // The device's own try records stand without the first ready: a long call's cache can hold a
555
+ // recent try after the handshake rows aged out. Phase-only guessing still needs the ready.
556
+ if (after.some((r) => r.kind === "reconnect_try")) {
557
+ const rowsFromTries = reconnectsFromTries(after);
558
+ if (firstReady === -1)
559
+ for (const rc of rowsFromTries)
560
+ rc.unnumbered = true;
561
+ return capReconnects(rowsFromTries, true);
562
+ }
563
+ if (firstReady === -1)
564
+ return [];
565
+ const recs = after.filter(isReconnectPhase);
566
+ const out = [];
567
+ let open = null;
568
+ for (const r of recs) {
569
+ const ms = num(r.duration_ms);
570
+ const at = recordTime(r);
571
+ if (str(r.phase) === "socket") {
572
+ // A second socket before any ready means the open try gave up; it stays listed as abandoned.
573
+ if (open)
574
+ open.abandoned = true;
575
+ open = { n: out.length + 1, socketMs: ms, readyMs: null, at };
576
+ out.push(open);
577
+ }
578
+ else if (open) {
579
+ open.readyMs = ms;
580
+ open = null;
581
+ }
582
+ else {
583
+ out.push({ n: out.length + 1, socketMs: null, readyMs: ms, at });
584
+ }
585
+ }
586
+ return capReconnects(out);
587
+ }
588
+ // A timed socket or session_ready phase, the two a reconnect repeats.
589
+ function isReconnectPhase(r) {
590
+ const phase = str(r.phase);
591
+ return r.kind === "phase" && (phase === "socket" || phase === "session_ready") && num(r.duration_ms) !== null;
592
+ }
593
+ function capReconnects(out, tries = false) {
594
+ if (out.length <= MAX_EXTRA_PHASES)
595
+ return out;
596
+ // Keep the newest, so the try still in flight stays in view.
597
+ const hidden = out.length - MAX_EXTRA_PHASES;
598
+ const lead = { n: hidden, socketMs: null, readyMs: null, at: 0, overflow: true };
599
+ if (tries)
600
+ lead.tries = true;
601
+ return [lead, ...out.slice(hidden)];
602
+ }
603
+ // With reconnect_try records the device says how each try ended, so a try record decides its row
604
+ // (a replaced socket shows as that try's retry, never as abandoned). The socket and session_ready
605
+ // phases since the previous try record join the row. n counts reconnects: a try 1, or a gave_up
606
+ // after 0 tries, opens a new one. Phases after the last try record make one open row.
607
+ function reconnectsFromTries(rows) {
608
+ const out = [];
609
+ let reconnectNo = 0;
610
+ let socketMs = null;
611
+ let readyMs = null;
612
+ let pendingAt = null;
613
+ let lastOutcome = null;
614
+ for (const r of rows) {
615
+ if (isReconnectPhase(r)) {
616
+ const ms = num(r.duration_ms);
617
+ if (pendingAt === null)
618
+ pendingAt = recordTime(r);
619
+ if (str(r.phase) === "socket")
620
+ socketMs = ms;
621
+ else
622
+ readyMs = ms;
623
+ }
624
+ else if (r.kind === "reconnect_try") {
625
+ const tryN = num(r.try);
626
+ const outcome = str(r.outcome) ?? "?";
627
+ const gaveUp = outcome === "gave_up";
628
+ if (reconnectNo === 0 || (gaveUp ? tryN === 0 : tryN === 1))
629
+ reconnectNo++;
630
+ const row = {
631
+ n: reconnectNo,
632
+ socketMs: gaveUp ? null : socketMs,
633
+ readyMs: gaveUp ? null : readyMs,
634
+ at: (gaveUp ? null : pendingAt) ?? recordTime(r) ?? 0,
635
+ trigger: str(r.trigger) ?? "?",
636
+ outcome,
637
+ };
638
+ if (tryN !== null)
639
+ row.tryN = tryN;
640
+ out.push(row);
641
+ socketMs = readyMs = pendingAt = null;
642
+ lastOutcome = outcome;
643
+ }
644
+ }
645
+ if (pendingAt !== null) {
646
+ // After a retry the open try belongs to the same reconnect; after anything else it is a new one.
647
+ out.push({ n: lastOutcome === "retry" ? reconnectNo : reconnectNo + 1, socketMs, readyMs, at: pendingAt });
648
+ }
649
+ return out;
650
+ }
491
651
  // Nearest-rank percentile: the value at ceil(p * n), 1-based, of the sorted sample. 0 for an
492
652
  // empty sample, so a card can print 0 rather than a dash.
493
653
  export function percentile(values, p) {
@@ -505,6 +665,7 @@ export function windowStats(rows, from, to) {
505
665
  let rearmsStarved = 0;
506
666
  const gaps = [];
507
667
  let jitterTrim = 0;
668
+ let holdRefuse = 0;
508
669
  let preReadyDrop = 0;
509
670
  let framesIn = 0;
510
671
  let framesOut = 0;
@@ -528,6 +689,8 @@ export function windowStats(rows, from, to) {
528
689
  }
529
690
  else if (r.event === "jitter_trim")
530
691
  jitterTrim++;
692
+ else if (r.event === "hold_refuse")
693
+ holdRefuse++;
531
694
  else if (r.event === "pre_ready_drop")
532
695
  preReadyDrop++;
533
696
  }
@@ -544,8 +707,9 @@ export function windowStats(rows, from, to) {
544
707
  gapP50: percentile(gaps, 0.5),
545
708
  gapP95: percentile(gaps, 0.95),
546
709
  gapSamples: gaps.length,
547
- dropped: jitterTrim + preReadyDrop,
710
+ dropped: jitterTrim + holdRefuse + preReadyDrop,
548
711
  jitterTrim,
712
+ holdRefuse,
549
713
  preReadyDrop,
550
714
  framesIn,
551
715
  framesOut,
@@ -588,7 +752,7 @@ export function tickStepMs(spanMs) {
588
752
  // session (no switchboard record at all, or only ones missing session_id / timestamp).
589
753
  // The caller resolves `summaryServerSessionId`, `summarySavedTurnCounts` and `savedTurnOutcomes`
590
754
  // so this module stays store-free.
591
- export function buildVoiceModel(rows, zoom, now, summaryServerSessionId, summarySavedTurnCounts, savedTurnOutcomes) {
755
+ export function buildVoiceModel(rows, zoom, now, summaryServerSessionId, summarySavedTurnCounts, savedTurnOutcomes, summaryServerSessionIds, summaryMicEncoding) {
592
756
  const sessionId = newestSessionId(rows);
593
757
  if (sessionId === null)
594
758
  return null;
@@ -602,7 +766,8 @@ export function buildVoiceModel(rows, zoom, now, summaryServerSessionId, summary
602
766
  const closeAt = endedAt !== null ? endedAt : now;
603
767
  const window = windowFor(modelRows, zoom, closeAt);
604
768
  const inWindow = (s) => s.to >= window.from && s.from <= window.to;
605
- const ph = phases(modelRows);
769
+ const firstReady = firstReadyIndex(modelRows);
770
+ const ph = phases(modelRows, firstReady);
606
771
  const hasReady = ph.list.some((p) => p.name === "session_ready");
607
772
  const socketIdx = ph.list.findIndex((p) => p.name === "socket");
608
773
  const socketRec = [...modelRows].filter((r) => r.kind === "phase" && r.phase === "socket").pop();
@@ -611,9 +776,19 @@ export function buildVoiceModel(rows, zoom, now, summaryServerSessionId, summary
611
776
  // The last `to: "Failed"` connection record, not just the latest connection state: a trailing
612
777
  // Disconnected (or any other state) after the real Failed(Timeout) must not hide it.
613
778
  let lastFailed = null;
779
+ // Whether only Disconnected moves came after that Failed. The goodbye can still be playing
780
+ // when the controller settles to Disconnected, so that keeps the normal ending; any other move
781
+ // means the call went on.
782
+ let settledSinceFailed = false;
614
783
  for (const r of modelRows) {
615
- if (r.kind === "state" && r.state_kind === "connection" && str(r.to) === "Failed") {
784
+ if (r.kind !== "state" || r.state_kind !== "connection")
785
+ continue;
786
+ if (str(r.to) === "Failed") {
616
787
  lastFailed = { to: "Failed", cause: str(r.cause), at: recordTime(r) };
788
+ settledSinceFailed = true;
789
+ }
790
+ else if (str(r.to) !== "Disconnected") {
791
+ settledSinceFailed = false;
617
792
  }
618
793
  }
619
794
  const failedAt = lastFailed ? lastFailed.at : null;
@@ -665,7 +840,7 @@ export function buildVoiceModel(rows, zoom, now, summaryServerSessionId, summary
665
840
  // phase record's own timestamp, when both exist, rather than the phase durations' sum -- two
666
841
  // phases can overlap or leave a gap the durations alone never show. Falls back to the sum when
667
842
  // either is missing.
668
- const readyRec = modelRows.filter((r) => r.kind === "phase" && str(r.phase) === "session_ready" && num(r.duration_ms) !== null).pop();
843
+ const readyRec = firstReady === -1 ? undefined : modelRows[firstReady];
669
844
  const phaseWallIsSum = !(readyRec && beginRec);
670
845
  const phaseWallMs = phaseWallIsSum ? ph.totalMs : recordTime(readyRec) - recordTime(beginRec);
671
846
  let connection = latestConn;
@@ -678,12 +853,15 @@ export function buildVoiceModel(rows, zoom, now, summaryServerSessionId, summary
678
853
  return {
679
854
  sessionId,
680
855
  connection,
856
+ endedNormally: settledSinceFailed && serverEndedNormally(lastFailed?.cause),
681
857
  mic: latestState(modelRows, "mic"),
682
858
  speaking: latestState(modelRows, "speaking"),
683
859
  uplink: uplinkRate(modelRows, closeAt, RATE_WINDOW_MS, beginAt),
684
860
  downlink: downlinkRate(modelRows, closeAt, RATE_WINDOW_MS, beginAt),
685
861
  sessionAgeMs: beginAt !== null ? closeAt - beginAt : null,
686
862
  phases: ph.list,
863
+ reconnects: reconnects(modelRows, firstReady),
864
+ beginAt,
687
865
  phaseTotalMs: ph.totalMs,
688
866
  phaseTimedOut,
689
867
  phaseWallMs,
@@ -694,6 +872,8 @@ export function buildVoiceModel(rows, zoom, now, summaryServerSessionId, summary
694
872
  model: segments(modelRows, "speaking", "speaking", closeAt).filter(inWindow),
695
873
  you: segments(modelRows, "mic", "Capturing", closeAt).filter(inWindow),
696
874
  youMuted: segments(modelRows, "mic", "Muted", closeAt).filter(inWindow),
875
+ micEncoding: summaryMicEncoding ?? null,
876
+ replyHolds: replyHolds(modelRows, closeAt).filter(inWindow),
697
877
  markers: markers(modelRows, { from: window.from, to: window.to, ended: endedAt !== null }),
698
878
  stats: windowStats(modelRows, window.from, window.to),
699
879
  hasBegin,
@@ -702,9 +882,11 @@ export function buildVoiceModel(rows, zoom, now, summaryServerSessionId, summary
702
882
  // real to have been clamped away from, whatever its earliest surviving record's own age is.
703
883
  wholeSpanClamped: hasBegin && whole.clamped,
704
884
  ended: endedAt !== null,
705
- serverSession: serverSessionId(modelRows, endedAt !== null, summaryServerSessionId),
885
+ serverSession: serverSessionId(modelRows, endedAt !== null, summaryServerSessionId, summaryServerSessionIds),
706
886
  serverSessionNone: readyNamedNoServerId(modelRows),
707
887
  savedTurns: savedTurnCounts(modelRows, summarySavedTurnCounts, savedTurnOutcomes),
888
+ openCards: modelRows.some((r) => r.kind === "card") ? openCards(modelRows) : null,
889
+ cardsPartial: !hasBegin,
708
890
  hasLevels,
709
891
  micLevels: hasLevels ? micLevelPoints(modelRows, window.from, window.to) : [],
710
892
  playbackLevels: hasLevels ? playbackLevelPoints(modelRows, window.from, window.to) : [],
@@ -8,7 +8,7 @@ import { useMemo, useRef, useState } from "preact/hooks";
8
8
  import { useStorePulse } from "./hooks.js";
9
9
  import { store } from "./store.js";
10
10
  import { showToast } from "./toast.js";
11
- import { capitalizeSwitchboardNote, SAVED_TURN_KEPT_OUTCOMES, savedTurnCountWord } from "./switchboard-note.js";
11
+ import { capitalizeSwitchboardNote, cardKindWord, micEncodingNote, reconnectOutcomeWord, reconnectTriggerWord, SAVED_TURN_KEPT_OUTCOMES, savedTurnCountWord } from "./switchboard-note.js";
12
12
  import { buildVoiceModel, CLIP_PEAK, dbfsHeight, GAP_P95_BAD_MS, phaseLabel, RATE_MIN_DIVISOR_MS, tickStepMs, ZOOMS } from "./voice-model.js";
13
13
  // The stream view draws the panel only on the Switchboard tab and only while the spec keeps the
14
14
  // voice key, so a custom spec on that source can leave it out.
@@ -39,10 +39,14 @@ const MARKER_COLOUR = {
39
39
  stop: "var(--purple)",
40
40
  focus: "var(--muted-2)",
41
41
  error: "var(--error)",
42
+ // Neutral on purpose: --muted-2 is focus, and a normal ending is not a fault.
43
+ ending: "var(--muted)",
42
44
  // --warn-2 exists in both themes (unlike --warn-text, which is light-only), so the stall gets
43
45
  // its own shade rather than reusing --warn; the dashed stroke below keeps it further apart from
44
46
  // a re-arm still.
45
47
  stall: "var(--warn-2)",
48
+ // A shade of blue none of the other markers use, so a card tick is not read as a fault.
49
+ card: "var(--blue-2)",
46
50
  // Distinct from `focus`'s var(--muted-2): a collapsed group of mixed-kind markers is its own
47
51
  // thing, not another shade of the same "quiet" colour.
48
52
  mixed: "var(--text)",
@@ -63,11 +67,35 @@ function phaseInlineText(p) {
63
67
  return html `${phaseLabel(p.name)}`;
64
68
  return p.timedOut ? html `${phaseLabel(p.name)} timed out after ${(p.ms / 1000).toFixed(1)} s` : html `${phaseLabel(p.name)} <b>${p.ms}</b>`;
65
69
  }
66
- function dotClass(state) {
70
+ function reconnectText(rc, ended, beginAt) {
71
+ if (rc.overflow)
72
+ return html `+${rc.n} earlier${rc.tries ? (rc.n === 1 ? " try" : " tries") : ""}`;
73
+ const label = rc.unnumbered ? "reconnect" : `reconnect #${rc.n}`;
74
+ const at = beginAt !== null ? ` · at ${((rc.at - beginAt) / 1000).toFixed(1)} s` : "";
75
+ const socket = rc.socketMs !== null ? html ` · socket <b>${rc.socketMs}</b>` : null;
76
+ const readyPart = rc.readyMs !== null ? html ` · session.ready <b>${rc.readyMs}</b>` : null;
77
+ if (rc.outcome !== undefined) {
78
+ // The model always sets trigger next to outcome.
79
+ const trigger = rc.trigger;
80
+ const after = `after a ${reconnectTriggerWord(trigger)}`;
81
+ if (rc.outcome === "gave_up") {
82
+ return html `${label} · ${after} · gave up after ${rc.tryN ?? "?"} ${rc.tryN === 1 ? "try" : "tries"}${at}`;
83
+ }
84
+ return html `${label} · ${after} · try ${rc.tryN ?? "?"}${socket}${readyPart} · ${reconnectOutcomeWord(rc.outcome)}${at}`;
85
+ }
86
+ const ready = readyPart ??
87
+ (rc.abandoned
88
+ ? " · no session.ready, the next try replaced it"
89
+ : ended
90
+ ? " · session.ready never came"
91
+ : " · waiting on session.ready");
92
+ return html `${label}${socket}${ready}${at}`;
93
+ }
94
+ function dotClass(state, endedNormally = false) {
67
95
  if (state === "Connected")
68
96
  return "ok";
69
97
  if (state === "Failed")
70
- return "bad";
98
+ return endedNormally ? "" : "bad";
71
99
  // Disconnected is a settled, unremarkable state (the session ended, or never got going yet
72
100
  // some other way): a warn dot there reads as an ongoing problem it is not. Connecting and
73
101
  // Reconnecting keep the warn colour, still mid-transition.
@@ -169,16 +197,18 @@ export function VoicePanel({ onInspect, now = () => Date.now() }) {
169
197
  const rows = store.switchboardRunRows();
170
198
  const sid = store.switchboardNewestSessionId();
171
199
  const summaryServerSessionId = sid !== null ? store.switchboardSummaryServerId(sid) : undefined;
200
+ const summaryServerSessionIds = sid !== null ? store.switchboardSummaryServerIds(sid) : undefined;
201
+ const summaryMicEncoding = sid !== null ? store.switchboardSummaryMicEncoding(sid) : undefined;
172
202
  const summarySavedTurnCounts = sid !== null ? store.switchboardSummarySavedTurnCounts(sid) : undefined;
173
203
  // Mutated in place as saved_turn rows land; each new one of the drawn run also lands in `rows`,
174
204
  // which rebuilds the model.
175
205
  const savedTurnOutcomes = sid !== null ? store.switchboardSavedTurnOutcomes(sid) : undefined;
176
206
  const clockKey = ended.current ? 0 : Math.floor(now() / 1000);
177
207
  const m = useMemo(() => {
178
- const model = buildVoiceModel(rows, zoom, now(), summaryServerSessionId, summarySavedTurnCounts, savedTurnOutcomes);
208
+ const model = buildVoiceModel(rows, zoom, now(), summaryServerSessionId, summarySavedTurnCounts, savedTurnOutcomes, summaryServerSessionIds, summaryMicEncoding);
179
209
  ended.current = model !== null && model.ended;
180
210
  return model;
181
- }, [rows, zoom, summaryServerSessionId, summarySavedTurnCounts, savedTurnOutcomes, clockKey]);
211
+ }, [rows, zoom, summaryServerSessionId, summaryServerSessionIds, summaryMicEncoding, summarySavedTurnCounts, savedTurnOutcomes, clockKey]);
182
212
  // Records exist but none names a session, or there is no switchboard record at all: draw
183
213
  // nothing. The feed's own empty state already tells the person what to do next.
184
214
  if (!m)
@@ -240,23 +270,25 @@ function SessionStrip({ m }) {
240
270
  // never there to begin with), not the "nothing has happened yet" case a brand-new session reads
241
271
  // as, so it gets its own wording rather than reusing "no session yet".
242
272
  const connText = conn ? conn.to : m.ended ? "connection unknown" : "no session yet";
273
+ // After a normal server ending the goodbye is still playing out, so a quiet downlink is expected.
243
274
  // A downlink pill reading 0/s while the model is speaking is not a problem in a session too
244
275
  // young to have cleared the rate's own minimum divisor yet -- that is exactly what sessionAgeMs
245
276
  // guards against. No begin record at all means the age itself is unknown, so it reads the same
246
277
  // as "too young" rather than assuming the worst. Past that age, 0 audio frames arriving while
247
278
  // the model is supposedly speaking is the downlink itself running dry, not a startup artifact.
248
- const downlinkWarn = m.speaking?.to === "speaking" && m.sessionAgeMs !== null && m.sessionAgeMs > RATE_MIN_DIVISOR_MS && m.downlink.perSec === 0;
279
+ const downlinkWarn = !m.endedNormally && m.speaking?.to === "speaking" && m.sessionAgeMs !== null && m.sessionAgeMs > RATE_MIN_DIVISOR_MS && m.downlink.perSec === 0;
249
280
  return html `
250
281
  <div class="voice-card">
251
282
  <div class="voice-hd">Session</div>
252
283
  <div class="voice-strip">
253
- <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>
284
+ <span class="voice-pill" title=${m.endedNormally ? "the server ended the call normally (a limit or the model's goodbye)" : undefined}><i class=${"voice-dot " + (conn ? dotClass(conn.to, m.endedNormally) : "")} aria-hidden="true"></i>${connText}${conn && (conn.to === "Failed" || conn.to === "Reconnecting") && conn.cause ? html ` <span class="voice-note">(${conn.cause})</span>` : null}</span>
254
285
  ${m.ended ? html `<span class="voice-note voice-ended">ended</span>` : null}
255
286
  <span class="voice-kv">session <b>${String(m.sessionId)}</b></span>
256
287
  <span class="voice-pill"><i class=${"voice-dot " + micClass(m.mic?.to)} aria-hidden="true"></i>mic ${m.mic ? m.mic.to : "unknown"}</span>
288
+ ${m.micEncoding ? html `<span class="voice-kv" title=${micEncodingNote(m.micEncoding) ?? undefined}>codec <b>${m.micEncoding}</b></span>` : null}
257
289
  <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>
258
290
  ${m.serverSession.id
259
- ? html `<button type="button" class="voice-pill voice-pill-server" title="server session id, click to copy" onClick=${() => copyServerSessionId(m.serverSession.id)}>server <b>${m.serverSession.id}</b></button>`
291
+ ? html `<button type="button" class="voice-pill voice-pill-server" title=${m.serverSession.all.length > 1 ? `server session ids: ${m.serverSession.all.join(", ")}. Click copies the newest.` : "server session id, click to copy"} onClick=${() => copyServerSessionId(m.serverSession.id)}>server <b>${m.serverSession.id}</b>${m.serverSession.all.length > 1 ? ` +${m.serverSession.all.length - 1}` : ""}</button>`
260
292
  : m.serverSession.pending
261
293
  ? html `<span class="voice-pill voice-pill-server voice-note" title="waiting on the device's session.ready record">server id pending</span>`
262
294
  : m.savedTurns?.some((c) => c.outcome === "other_session" && c.count > 0)
@@ -267,7 +299,10 @@ function SessionStrip({ m }) {
267
299
  ${m.savedTurns
268
300
  ? html `<span class=${"voice-kv" + (m.savedTurns.some((c) => !SAVED_TURN_KEPT_OUTCOMES.includes(c.outcome) && c.count > 0) ? " warn" : "")} title="what happened to each spoken turn, by outcome: the device count when this tab loaded the session, plus the turns seen since (or the turns this tab has seen, when those are more); saved (line moved on) is a late save whose line already moved on, still kept; the dropped ones, and any outcome this dashboard does not know, are the ones to look into">turns ${m.savedTurns.map((c, i) => html `${i ? " · " : ""}${savedTurnCountWord(c.outcome)} <b>${c.count}</b>`)}</span>`
269
301
  : null}
270
- <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>
302
+ ${m.openCards
303
+ ? html `<span class="voice-kv" title=${cardsTitle(m)}>cards up <b>${m.openCards.length}</b>${m.cardsPartial ? " seen" : ""}${m.ended ? " at close" : ""}</span>`
304
+ : null}
305
+ <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${m.micEncoding && micEncodingNote(m.micEncoding) ? `; mic codec ${m.micEncoding}: ${micEncodingNote(m.micEncoding)}` : ""}`}>uplink <b>${m.uplink.perSec.toFixed(1)}/s</b> ${m.uplink.rule === "audio" ? "audio frames" : "frames"}${m.ended ? " at close" : ""}</span>
271
306
  <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>
272
307
  </div>
273
308
  ${m.phases.length
@@ -294,6 +329,9 @@ function SessionStrip({ m }) {
294
329
  </div>
295
330
  `
296
331
  : html `<div class="voice-note">no phase records yet</div>`}
332
+ ${
333
+ // Outside the phases block: a long call can hold reconnect rows after the startup rows aged out.
334
+ m.reconnects.map((rc) => html `<div class="voice-note voice-reconnect">${reconnectText(rc, m.ended, m.beginAt)}</div>`)}
297
335
  </div>
298
336
  `;
299
337
  }
@@ -385,6 +423,7 @@ function levelBars(points, y, h, x, colour, rowClass) {
385
423
  </g>`;
386
424
  });
387
425
  }
426
+ const HOLD_TITLE = "reply on hold: audio kept arriving and queued, the mic stayed open with the uplink muted; silence here is the pause, not loss";
388
427
  function Tracks({ m, title, rearms, onPick }) {
389
428
  const H = plotHeight(m.hasLevels);
390
429
  const { from, to } = m.window;
@@ -410,8 +449,12 @@ function Tracks({ m, title, rearms, onPick }) {
410
449
  const model = mergeSegmentsByColumn(m.model, x);
411
450
  const you = mergeSegmentsByColumn(m.you, x);
412
451
  const youMuted = mergeSegmentsByColumn(m.youMuted, x);
452
+ const holds = mergeSegmentsByColumn(m.replyHolds, x);
453
+ // Spans the playback rows only: the model row, plus the playback level row when levels are drawn.
454
+ const holdBand = (s, y, h) => html `<rect class="voice-seg voice-seg-hold" x=${x(s.from)} y=${y} width=${Math.max(2, x(s.to) - x(s.from))} height=${h} fill="var(--muted-2)" opacity=".25"><title>${HOLD_TITLE}</title></rect>`;
413
455
  const drawn = collapseMarkers(m.markers, x);
414
456
  const hasMixed = drawn.some((k) => k.kind === "mixed");
457
+ const hasCard = drawn.some((k) => k.kind === "card");
415
458
  // A burst reads differently from a plain mixed collapse: still one kind throughout, just more
416
459
  // than one record of it landed in the same spot (see DrawMarker.multi).
417
460
  const hasBurst = drawn.some((k) => k.multi && k.kind !== "mixed");
@@ -459,6 +502,8 @@ function Tracks({ m, title, rearms, onPick }) {
459
502
  ${model.map((s) => seg(s, "model", ROW_Y.model, "var(--blue)", ".45"))}
460
503
  ${you.map((s) => seg(s, "you", ROW_Y.you, "var(--accent)", ".4"))}
461
504
  ${youMuted.map(segMuted)}
505
+ ${holds.map((s) => holdBand(s, ROW_Y.model, ROW_H))}
506
+ ${m.hasLevels ? holds.map((s) => holdBand(s, ROW_Y.playbackLevel, LEVEL_ROW_H)) : null}
462
507
  ${drawn.map((k) => {
463
508
  const c = MARKER_COLOUR[k.kind];
464
509
  // The stroke width is the burst cue: same-kind bursts read 8, wider than a plain
@@ -515,11 +560,14 @@ function Tracks({ m, title, rearms, onPick }) {
515
560
  <span class="m">model speaking</span>
516
561
  <span class="y">you capturing</span>
517
562
  <span class="mu">you (muted)</span>
563
+ ${holds.length > 0 ? html `<span class="hd" title=${HOLD_TITLE}>reply on hold (you paused it)</span>` : null}
518
564
  <span class="r">playback re-arm</span>
519
565
  <span class="s">tts.stop sent</span>
520
566
  <span class="st">player stall</span>
521
567
  <span class="e">connection failed</span>
568
+ <span class="en">server ended the call</span>
522
569
  <span class="f">mic paused</span>
570
+ ${hasCard ? html `<span class="cd">card</span>` : null}
523
571
  ${hasClipping ? html `<span class="clip">clipping</span>` : null}
524
572
  ${hasMixed ? html `<span class="mx">multiple markers</span>` : null}
525
573
  ${hasBurst ? html `<span class="mb">burst (several at one spot, hover for the count)</span>` : null}
@@ -528,6 +576,16 @@ function Tracks({ m, title, rearms, onPick }) {
528
576
  </div>
529
577
  `;
530
578
  }
579
+ // Partial rows cannot say no card is waiting, so the title owns up to what the tab holds.
580
+ function cardsTitle(m) {
581
+ const open = m.openCards ?? [];
582
+ const partial = m.cardsPartial
583
+ ? "this tab holds only the newest records of this call, so a card shown before them is not counted; export the session for every record. "
584
+ : "";
585
+ if (open.length === 0)
586
+ return m.cardsPartial ? partial.trim() : "no card is waiting";
587
+ return `${partial}shown or carried with no later record: ${open.map((c) => `${cardKindWord(c.kind)} ${c.id}`).join("; ")}`;
588
+ }
531
589
  function StatCards({ m }) {
532
590
  const s = m.stats;
533
591
  // gapSamples, not p50/p95 > 0: a re-arm with no usable gap_ms (see markers()'s own "unusable
@@ -545,7 +603,7 @@ function StatCards({ m }) {
545
603
  <div class="l">playback re-arms</div>
546
604
  </div>
547
605
  <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>
548
- <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>
606
+ <div class=${"voice-stat" + (s.holdRefuse > 0 || s.preReadyDrop > 0 ? " warn" : "")} title="jitter trim = the player skipped buffered audio to catch up, expected in small numbers; hold refuse = a held reply's queue was full, so the newest audio was dropped; pre-ready = audio landed before session.ready, check the handshake"><div class="v">${s.jitterTrim} / ${s.holdRefuse} / ${s.preReadyDrop}</div><div class="l">drops: jitter trim / hold refuse / pre-ready</div></div>
549
607
  <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>
550
608
  </div>
551
609
  `;
@@ -3,6 +3,7 @@ import type { StatusReason } from "../shared/wire.js";
3
3
  import { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_DEADLINE_MS, SWITCHBOARD_BACKFILL_SESSIONS, type SwitchboardExportGet } from "../shared/switchboard.js";
4
4
  import { type DashboardScreenController } from "../shared/dashboard-screen.js";
5
5
  import type { ProcessState } from "../shared/transport.js";
6
+ import type { LogSession } from "../shared/log-session.js";
6
7
  declare const WEB_PORT: number;
7
8
  /**
8
9
  * Decide whether to drop a log frame under backpressure. LIVE frames are dropped
@@ -15,6 +16,14 @@ declare const WEB_PORT: number;
15
16
  * without a socket. `cap` defaults to the live ceiling.
16
17
  */
17
18
  export declare function shouldDropLogFrame(replay: boolean, writableLength: number, cap?: number): boolean;
19
+ export declare const DEVICE_ABSENT_BACKOFF_MS = 10000;
20
+ /** Milliseconds left in the device-absent window, 0 when it is not open. */
21
+ export declare function deviceAbsentMsLeft(now?: number): number;
22
+ export declare function markDeviceAbsent(now?: number): void;
23
+ export declare function resetDeviceAbsentForTest(): void;
24
+ export declare function _setDeviceAbsentBackoffForTest(ms: number | null): void;
25
+ type CaptureSession = Pick<LogSession, "isRunning" | "start" | "stop" | "subscribe" | "subscribeStatus" | "takeLastFailure" | "registerCleanup" | "restart">;
26
+ export declare function _setLogSessionForTest(session: CaptureSession | undefined): void;
18
27
  /**
19
28
  * Write the starting spec for a server that is taking ownership of this port. MUST be
20
29
  * called only AFTER a successful listen() bind, never at module load: importing this
@@ -189,6 +198,14 @@ export declare function getPresenceState(): {
189
198
  everSeen: boolean;
190
199
  emptySince: number | null;
191
200
  };
201
+ /**
202
+ * Keep the host log capture only while a tab is polling or a log stream is open.
203
+ * Stopping keeps the ring, so a tab that comes back still replays the history. Starting is
204
+ * limited to a capture some log stream armed earlier. Exported for tests with a fake clock.
205
+ */
206
+ export declare function reconcileCapture(now?: number): "start" | "stop" | "keep";
207
+ /** One sweep step: auto-close wins, otherwise the capture is reconciled. */
208
+ export declare function sweepTick(now: number, onClose: () => void): void;
192
209
  /** Reset presence between tests (module state is a process singleton). */
193
210
  export declare function resetPresenceForTest(): void;
194
211
  interface ShutdownDeps {