@slack/radar-mcp 1.24.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.
@@ -1,6 +1,6 @@
1
1
  import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource, levelRank, FIELD_VALUES, EXCLUDE_MAX_TERMS, EXCLUDE_MAX_TERM_LENGTH, SWITCHBOARD_KINDS, CACHE_TTL_MS, normalizeStreamType } from "./registry.js";
2
2
  import { byRecordTime, cutFromVotes, inSessionCut, outranks, runRows, sameSessionCut, sessionVote } from "./voice-model.js";
3
- import { savedTurnLabel } from "./switchboard-note.js";
3
+ import { SERVER_SESSION_ID_CAP, cardLabel, savedTurnLabel } from "./switchboard-note.js";
4
4
  export const UNAUTHORIZED_HEAD = "device refused this session (HTTP 401)";
5
5
  // Logcat-scale retention. At the live firehose (~400+ events/sec on the unified Live tab) a
6
6
  // small ring recycles in seconds, so a rare signal (a once-per-5s heartbeat) gets evicted
@@ -109,7 +109,7 @@ function writeViewMemory(mem) {
109
109
  const POLL_PROFILE_MS = 5000;
110
110
  const GRAPH_N = 60;
111
111
  const PERSEC_N = 30;
112
- const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package", "trace_name", "span_name", "kind", "frame_type", "state_kind", "phase", "event", "clock", "outcome"];
112
+ const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package", "trace_name", "span_name", "kind", "frame_type", "state_kind", "phase", "event", "clock", "outcome", "trigger", "card_kind"];
113
113
  const PACKAGE_CAP = 1000; // package values learned off the stream; bounded (was Infinity in the PoC, B4)
114
114
  // ---- pre-built dashboards: one tab each. Presets carry only generic placeholders; real
115
115
  // endpoints/channels/event-names are learned LIVE from the device stream. The one baked value
@@ -625,6 +625,19 @@ export class Store {
625
625
  // under the id. undefined means not learned yet; null means the summary reported the key but it
626
626
  // was itself null (see voice-model.ts's serverSessionId).
627
627
  _switchboardSummaryServerId = new Map();
628
+ // Every ready id of the call, oldest first, from every path (the refill page, and live and
629
+ // replayed ready records). Absent on an older build.
630
+ _switchboardSummaryServerIds = new Map();
631
+ // The newest mic codec label from every path (live, replayed and the refill page), so the panel
632
+ // keeps it after the config record ages out of the cache. Absent on a build older than wire
633
+ // revision 5 that sent no config record.
634
+ _switchboardSummaryMicEncoding = new Map();
635
+ // The record id that label is good through: the refill's page, or a newer live config record.
636
+ // Kept so an older replayed config or a late refill cannot put back a codec a reconnect replaced.
637
+ _switchboardSummaryMicEncodingThrough = new Map();
638
+ // The highest record id the id list covers: the refill's page, moved forward on each append. A
639
+ // replayed (non-live) ready at or below it is already in the list or aged out of it.
640
+ _switchboardSummaryServerIdsThrough = new Map();
628
641
  // saved_turn_counts per session id, off the same refill envelope and dropped with it on a new run,
629
642
  // with the newest record id that envelope carried: the counts are a snapshot through that id, and
630
643
  // the panel adds the saved_turn rows newer than it. Absent until a refill lands one; an older
@@ -840,6 +853,10 @@ export class Store {
840
853
  this._backfillToken = 0;
841
854
  this._switchboardRuns = new Map();
842
855
  this._switchboardSummaryServerId = new Map();
856
+ this._switchboardSummaryServerIds = new Map();
857
+ this._switchboardSummaryMicEncoding = new Map();
858
+ this._switchboardSummaryMicEncodingThrough = new Map();
859
+ this._switchboardSummaryServerIdsThrough = new Map();
843
860
  this._switchboardSummarySavedTurnCounts = new Map();
844
861
  this._sbBestBegin = null;
845
862
  this._sbBestAny = null;
@@ -926,6 +943,10 @@ export class Store {
926
943
  // claim the new device's sessions of the same id.
927
944
  this._switchboardRuns = new Map();
928
945
  this._switchboardSummaryServerId = new Map();
946
+ this._switchboardSummaryServerIds = new Map();
947
+ this._switchboardSummaryMicEncoding = new Map();
948
+ this._switchboardSummaryMicEncodingThrough = new Map();
949
+ this._switchboardSummaryServerIdsThrough = new Map();
929
950
  this._switchboardSummarySavedTurnCounts = new Map();
930
951
  // The old device's declared sources do not describe the new one; null until its next poll.
931
952
  this.updateSources(null);
@@ -1447,6 +1468,27 @@ export class Store {
1447
1468
  // id's current run counts: one from an older process under the same id names another call.
1448
1469
  if (ev.kind === "session" && ev.event === "ready" && Object.hasOwn(ev, "server_session_id") && inSwitchboardRun(ev, run)) {
1449
1470
  this._switchboardSummaryServerId.set(ev.session_id, ev.server_session_id ?? null);
1471
+ // A reconnect's new id joins the list the refill learned, so a long call keeps the older
1472
+ // ids after their ready rows age out. The device keeps its newest 8, and so does this.
1473
+ const ids = this._switchboardSummaryServerIds.get(ev.session_id);
1474
+ // A replayed ready (refill page, backfill) at or below what the list covers is old news and
1475
+ // would land out of order; a newer one, like a stream-recovery backfill's, still appends.
1476
+ const through = this._switchboardSummaryServerIdsThrough.get(ev.session_id) ?? -Infinity;
1477
+ const replayedOld = !live && typeof ev.id === "number" && ev.id <= through;
1478
+ if (ids && !replayedOld && typeof ev.server_session_id === "string" && !ids.includes(ev.server_session_id)) {
1479
+ this._switchboardSummaryServerIds.set(ev.session_id, [...ids, ev.server_session_id].slice(-SERVER_SESSION_ID_CAP));
1480
+ if (typeof ev.id === "number" && ev.id > through)
1481
+ this._switchboardSummaryServerIdsThrough.set(ev.session_id, ev.id);
1482
+ }
1483
+ }
1484
+ // Same for the mic codec: hold the newest config's label, so the panel keeps it (and a
1485
+ // reconnect's switch) after the config row ages out. An older replayed config never wins.
1486
+ if (ev.kind === "session" && ev.event === "config" && typeof ev.mic_encoding === "string" && typeof ev.id === "number" && inSwitchboardRun(ev, run)) {
1487
+ const through = this._switchboardSummaryMicEncodingThrough.get(ev.session_id) ?? -Infinity;
1488
+ if (ev.id > through) {
1489
+ this._switchboardSummaryMicEncoding.set(ev.session_id, ev.mic_encoding);
1490
+ this._switchboardSummaryMicEncodingThrough.set(ev.session_id, ev.id);
1491
+ }
1450
1492
  }
1451
1493
  if (ev.kind === "saved_turn" && typeof ev.outcome === "string" && typeof ev.id === "number" && inSwitchboardRun(ev, run)) {
1452
1494
  run.savedTurns.set(ev.id, ev.outcome);
@@ -1488,6 +1530,10 @@ export class Store {
1488
1530
  }
1489
1531
  if (reused) {
1490
1532
  this._switchboardSummaryServerId.delete(sid);
1533
+ this._switchboardSummaryServerIds.delete(sid);
1534
+ this._switchboardSummaryMicEncoding.delete(sid);
1535
+ this._switchboardSummaryMicEncodingThrough.delete(sid);
1536
+ this._switchboardSummaryServerIdsThrough.delete(sid);
1491
1537
  this._switchboardSummarySavedTurnCounts.delete(sid);
1492
1538
  }
1493
1539
  if (!run || reused) {
@@ -1703,6 +1749,32 @@ export class Store {
1703
1749
  if (this._switchboardRuns.get(sessionId) === run && Object.hasOwn(detail ?? {}, "server_session_id")) {
1704
1750
  this._switchboardSummaryServerId.set(sessionId, detail.server_session_id ?? null);
1705
1751
  }
1752
+ if (this._switchboardRuns.get(sessionId) === run && Array.isArray(detail?.server_session_ids)) {
1753
+ this._switchboardSummaryServerIds.set(sessionId, detail.server_session_ids.filter((x) => typeof x === "string"));
1754
+ // The device read the list and the page together, so the list covers the page's highest id,
1755
+ // or the highest id held when the fetch went out if that is higher.
1756
+ let idsThrough = heldThroughId;
1757
+ for (const e of detail?.events || []) {
1758
+ const id = e?.id;
1759
+ if (typeof id === "number" && id > idsThrough)
1760
+ idsThrough = id;
1761
+ }
1762
+ this._switchboardSummaryServerIdsThrough.set(sessionId, idsThrough);
1763
+ }
1764
+ if (this._switchboardRuns.get(sessionId) === run && typeof detail?.mic_encoding === "string") {
1765
+ // Good through the page's highest id, like the id list. A live config newer than that,
1766
+ // seen while the fetch was out, keeps its label.
1767
+ let micThrough = heldThroughId;
1768
+ for (const e of detail?.events || []) {
1769
+ const id = e?.id;
1770
+ if (typeof id === "number" && id > micThrough)
1771
+ micThrough = id;
1772
+ }
1773
+ if (micThrough >= (this._switchboardSummaryMicEncodingThrough.get(sessionId) ?? -Infinity)) {
1774
+ this._switchboardSummaryMicEncoding.set(sessionId, detail.mic_encoding);
1775
+ this._switchboardSummaryMicEncodingThrough.set(sessionId, micThrough);
1776
+ }
1777
+ }
1706
1778
  // The device reads the summary and the page together, so the counts stop at the page's
1707
1779
  // highest id, or at the highest id held when the fetch went out if that is higher (an empty
1708
1780
  // page). With neither, every row the stream brings is newer.
@@ -1737,6 +1809,16 @@ export class Store {
1737
1809
  switchboardSummaryServerId(sessionId) {
1738
1810
  return this._switchboardSummaryServerId.get(sessionId);
1739
1811
  }
1812
+ // Every server_session_id the refill reported for sessionId, oldest first; undefined on an older
1813
+ // build or before the refill lands.
1814
+ switchboardSummaryServerIds(sessionId) {
1815
+ return this._switchboardSummaryServerIds.get(sessionId);
1816
+ }
1817
+ // The newest mic codec label held for sessionId, from the live stream, a replay or the refill;
1818
+ // undefined before any of them brings one.
1819
+ switchboardSummaryMicEncoding(sessionId) {
1820
+ return this._switchboardSummaryMicEncoding.get(sessionId);
1821
+ }
1740
1822
  // The saved_turn outcomes seen for sessionId's current run, by record id; undefined before any
1741
1823
  // record of the id.
1742
1824
  switchboardSavedTurnOutcomes(sessionId) {
@@ -2919,7 +3001,7 @@ export function switchboardFields(ev) {
2919
3001
  const num = (v) => (typeof v === "number" ? v : undefined);
2920
3002
  switch (kind) {
2921
3003
  // Searchable here like any other switchboard field, not just shown on the summary pill.
2922
- case "session": return [kind, ev.event, ev.server_session_id];
3004
+ case "session": return [kind, ev.event, ev.server_session_id, typeof ev.mic_encoding === "string" ? ev.mic_encoding : undefined];
2923
3005
  case "state": return [kind, ev.state_kind, ev.from, ev.to, ev.cause];
2924
3006
  case "frame": return [kind, ev.direction, ev.frame_type, num(ev.bytes)];
2925
3007
  case "phase": return [kind, ev.phase, num(ev.duration_ms)];
@@ -2934,6 +3016,10 @@ export function switchboardFields(ev) {
2934
3016
  const label = savedTurnLabel(ev.outcome, ev.has_thread);
2935
3017
  return [kind, ev.outcome, label && label !== ev.outcome ? label : undefined];
2936
3018
  }
3019
+ // The ids and labels, so a search for an approval id finds its moves.
3020
+ case "card": return [kind, ev.card_kind, ev.event, ev.by, ev.card_id, cardLabel(ev.card_kind, ev.event, ev.by)];
3021
+ // The labels and the try number, so a search for either label finds the row.
3022
+ case "reconnect_try": return [kind, ev.trigger, ev.outcome, num(ev.try)];
2937
3023
  default: return [kind];
2938
3024
  }
2939
3025
  }
@@ -8,6 +8,16 @@ export function capitalizeSwitchboardNote(note) {
8
8
  // A peak at or above this is clipping. Shared here so the report and the dashboard sparkline use
9
9
  // the same threshold.
10
10
  export const CLIP_PEAK = 0.99;
11
+ // What the mic codec costs on the uplink, for the strip and the report header. The sizes are
12
+ // 24 kHz x 2 bytes x 0.2 s for pcm16, and the provider's own note for adts. An unknown label is
13
+ // the device's to add, so it has no note and prints as sent.
14
+ const MIC_ENCODING_NOTES = {
15
+ pcm16: "raw 24 kHz PCM, about 9.6 KB per 200 ms uplink audio frame",
16
+ adts: "AAC in ADTS frames, uplink audio frames about a tenth of pcm16",
17
+ };
18
+ export function micEncodingNote(label) {
19
+ return Object.hasOwn(MIC_ENCODING_NOTES, label) ? MIC_ENCODING_NOTES[label] : null;
20
+ }
11
21
  // A turn record's `clock` in words. Shared here so the feed row and the report read the same.
12
22
  // An unknown value is the device's to add, so it shows as sent rather than throwing.
13
23
  const TURN_CLOCK_LABELS = {
@@ -18,6 +28,27 @@ const TURN_CLOCK_LABELS = {
18
28
  export function switchboardClockLabel(clock) {
19
29
  return Object.hasOwn(TURN_CLOCK_LABELS, clock) ? TURN_CLOCK_LABELS[clock] : clock;
20
30
  }
31
+ // The most server session ids the device lists in a summary (server_session_ids). The host trims
32
+ // its own lists to the same count, so a summary built here matches one the device sent.
33
+ export const SERVER_SESSION_ID_CAP = 8;
34
+ // The panel's words for a reconnect's trigger and outcome. An unknown token is the device's to add,
35
+ // so it shows as sent rather than throwing; hasOwn keeps a name like "constructor" from finding an
36
+ // Object.prototype member.
37
+ const RECONNECT_TRIGGER_WORDS = { restart: "server restart", drop: "dropped connection", settings: "settings change" };
38
+ const RECONNECT_OUTCOME_WORDS = { ready: "back", retry: "failed, trying again", refused: "refused, call ended" };
39
+ export function reconnectTriggerWord(trigger) {
40
+ return Object.hasOwn(RECONNECT_TRIGGER_WORDS, trigger) ? RECONNECT_TRIGGER_WORDS[trigger] : trigger;
41
+ }
42
+ export function reconnectOutcomeWord(outcome) {
43
+ return Object.hasOwn(RECONNECT_OUTCOME_WORDS, outcome) ? RECONNECT_OUTCOME_WORDS[outcome] : outcome;
44
+ }
45
+ // A reconnect_try record in the export line's words ("drop try 2 ready", "drop gave_up after 2
46
+ // tries"), shared by the feed row and the report. A missing try number reads "?".
47
+ export function reconnectTryLabel(trigger, outcome, n) {
48
+ if (outcome === "gave_up")
49
+ return `${trigger} gave_up after ${n ?? "?"} ${n === 1 ? "try" : "tries"}`;
50
+ return `${trigger} try ${n ?? "?"} ${outcome}`;
51
+ }
21
52
  // The saved_turn outcomes, the one list the feed row, the panel and the report read. `applied`
22
53
  // (a subtitle line still held the frame's item) and `no_line` (no line held it any more, a normal
23
54
  // late save, still kept) keep the turn; the drop reasons lose it. The words are the row's and the
@@ -34,6 +65,40 @@ export const SAVED_TURN_DROP_OUTCOMES = Object.keys(SAVED_TURN_DROPS);
34
65
  export const SAVED_TURN_KEPT_OUTCOMES = Object.keys(SAVED_TURN_KEPT);
35
66
  // The four a revision 3 build always counts, in the order the panel and the report list them.
36
67
  export const SAVED_TURN_OUTCOMES = [...Object.keys(SAVED_TURN_KEPT), ...SAVED_TURN_DROP_OUTCOMES];
68
+ // A card record in words, shared by the feed row, the voice panel and the report. A kind or event
69
+ // the device adds later shows as sent, and a missing field reads "?", so nothing throws.
70
+ const CARD_KIND_WORDS = { tool_approval: "tool approval", auth_prompt: "connect prompt" };
71
+ // An event in this set takes the card down; "shown" and "carried" put it up.
72
+ const CARD_CLOSING_EVENTS = ["answered", "refused", "declined", "closed", "replaced", "expired", "cleared"];
73
+ const CARD_OPENING_EVENTS = ["shown", "carried"];
74
+ export function cardKindWord(kind) {
75
+ if (typeof kind !== "string" || !kind)
76
+ return "?";
77
+ return Object.hasOwn(CARD_KIND_WORDS, kind) ? CARD_KIND_WORDS[kind] : kind;
78
+ }
79
+ export function cardLabel(kind, event, by) {
80
+ const eventWord = typeof event === "string" && event ? event : "?";
81
+ return `${cardKindWord(kind)} ${eventWord}${typeof by === "string" && by ? ` by ${by}` : ""}`;
82
+ }
83
+ // The cards still up after these records, in the order they came up. Shown or carried puts a card
84
+ // up (a re-sent one keeps its place), the closing events take it down, and an event it does not
85
+ // know changes nothing, so a newer device build cannot make a card look gone.
86
+ export function openCards(records) {
87
+ const open = new Map();
88
+ for (const r of records) {
89
+ if (r.kind !== "card" || typeof r.card_kind !== "string" || typeof r.card_id !== "string" || typeof r.event !== "string")
90
+ continue;
91
+ const key = `${r.card_kind}\u0000${r.card_id}`;
92
+ if (CARD_OPENING_EVENTS.includes(r.event)) {
93
+ if (!open.has(key))
94
+ open.set(key, { kind: r.card_kind, id: r.card_id });
95
+ }
96
+ else if (CARD_CLOSING_EVENTS.includes(r.event)) {
97
+ open.delete(key);
98
+ }
99
+ }
100
+ return [...open.values()];
101
+ }
37
102
  // Code points a free-form device string could use to fake a line break, a report boundary, or a
38
103
  // hidden direction override: controls, bidi marks, zero-width characters, U+2028/2029 (a newline
39
104
  // to a browser), and the BOM. Here rather than in the report so the panel strips the same set.
@@ -91,3 +156,14 @@ export function savedTurnCountEntries(counts) {
91
156
  out.push({ outcome: k, count: read(k) });
92
157
  return out;
93
158
  }
159
+ // The server endings that are a normal end, not a fault. Matches the device's `endsNormally`. An
160
+ // older device build sends plain "Server" for these too, and that stays an error since nothing
161
+ // says which ending it was.
162
+ const NORMAL_SERVER_ENDINGS = ["Server:live_session_limit", "Server:session_limit", "Server:live_idle_timeout", "Server:live_call_ended"];
163
+ export function serverEndedNormally(cause) {
164
+ return typeof cause === "string" && NORMAL_SERVER_ENDINGS.includes(cause);
165
+ }
166
+ // A connection state record that moved to Failed on a normal server ending.
167
+ export function connectionEndedNormally(r) {
168
+ return r.kind === "state" && r.state_kind === "connection" && r.to === "Failed" && serverEndedNormally(r.cause);
169
+ }
@@ -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) : [],