@slack/radar-mcp 1.20.0 → 1.22.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 (91) hide show
  1. package/README.md +75 -17
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +56 -20
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +138 -36
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/network-detail.d.ts +5 -0
  10. package/dist/mcp/network-detail.js +86 -0
  11. package/dist/mcp/radar-export-get.d.ts +30 -0
  12. package/dist/mcp/radar-export-get.js +49 -0
  13. package/dist/mcp/radar-response.d.ts +11 -1
  14. package/dist/mcp/radar-response.js +23 -3
  15. package/dist/mcp/session-backfill.d.ts +9 -3
  16. package/dist/mcp/session-backfill.js +76 -17
  17. package/dist/mcp/session-detail.js +54 -2
  18. package/dist/mcp/session-enable.d.ts +1 -0
  19. package/dist/mcp/session-enable.js +146 -15
  20. package/dist/mcp/session-query.js +53 -11
  21. package/dist/mcp/snapshot.js +42 -26
  22. package/dist/mcp/sources-gate.js +5 -0
  23. package/dist/mcp/stale-dashboard.d.ts +23 -0
  24. package/dist/mcp/stale-dashboard.js +122 -0
  25. package/dist/mcp/switchboard-spool.d.ts +12 -0
  26. package/dist/mcp/switchboard-spool.js +107 -0
  27. package/dist/mcp/switchboard-tools.d.ts +18 -0
  28. package/dist/mcp/switchboard-tools.js +178 -0
  29. package/dist/mcp/tools.d.ts +4 -1
  30. package/dist/mcp/tools.js +114 -23
  31. package/dist/mcp/web-child-env.d.ts +4 -1
  32. package/dist/mcp/web-child-env.js +4 -1
  33. package/dist/shared/android.d.ts +43 -0
  34. package/dist/shared/android.js +227 -19
  35. package/dist/shared/constants.d.ts +19 -4
  36. package/dist/shared/constants.js +19 -4
  37. package/dist/shared/event-spool.js +3 -2
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/form-body.d.ts +18 -0
  41. package/dist/shared/form-body.js +251 -0
  42. package/dist/shared/ios-logs.d.ts +10 -0
  43. package/dist/shared/ios-logs.js +91 -0
  44. package/dist/shared/ios.d.ts +25 -2
  45. package/dist/shared/ios.js +157 -3
  46. package/dist/{web → shared}/log-session.d.ts +45 -31
  47. package/dist/shared/log-session.js +300 -0
  48. package/dist/shared/radar-request-raw.d.ts +7 -0
  49. package/dist/shared/radar-request-raw.js +89 -0
  50. package/dist/shared/radar-token.d.ts +25 -0
  51. package/dist/shared/radar-token.js +164 -0
  52. package/dist/shared/stream.d.ts +4 -1
  53. package/dist/shared/stream.js +107 -15
  54. package/dist/shared/switchboard-host-store.d.ts +21 -0
  55. package/dist/shared/switchboard-host-store.js +166 -0
  56. package/dist/shared/switchboard-note.d.ts +15 -0
  57. package/dist/shared/switchboard-note.js +92 -0
  58. package/dist/shared/switchboard-report-file.d.ts +5 -0
  59. package/dist/shared/switchboard-report-file.js +26 -0
  60. package/dist/shared/switchboard-report.d.ts +20 -0
  61. package/dist/shared/switchboard-report.js +406 -0
  62. package/dist/shared/switchboard.d.ts +118 -0
  63. package/dist/shared/switchboard.js +487 -0
  64. package/dist/shared/transport.d.ts +43 -3
  65. package/dist/shared/version.d.ts +2 -0
  66. package/dist/shared/version.js +18 -0
  67. package/dist/shared/wire.d.ts +46 -1
  68. package/dist/web/install-app.d.ts +57 -8
  69. package/dist/web/install-app.js +270 -60
  70. package/dist/web/macapp/RadarApp.swift +340 -22
  71. package/dist/web/public/index.html +216 -12
  72. package/dist/web/public/next/app.js +43 -22
  73. package/dist/web/public/next/db.js +4 -1
  74. package/dist/web/public/next/feed.js +604 -59
  75. package/dist/web/public/next/filters.js +158 -40
  76. package/dist/web/public/next/flags.js +3 -0
  77. package/dist/web/public/next/form-body.js +252 -0
  78. package/dist/web/public/next/inspector.js +171 -14
  79. package/dist/web/public/next/prefs.js +5 -2
  80. package/dist/web/public/next/registry.js +35 -3
  81. package/dist/web/public/next/store.js +947 -69
  82. package/dist/web/public/next/switchboard-note.js +93 -0
  83. package/dist/web/public/next/toast.js +9 -5
  84. package/dist/web/public/next/voice-model.js +712 -0
  85. package/dist/web/public/next/voice.js +552 -0
  86. package/dist/web/server.d.ts +20 -9
  87. package/dist/web/server.js +834 -174
  88. package/dist/web/spec.d.ts +11 -6
  89. package/dist/web/spec.js +62 -6
  90. package/package.json +4 -4
  91. package/dist/web/log-session.js +0 -166
@@ -1,7 +1,11 @@
1
1
  import type { ParsedSSE, RadarEvent } from "../shared/stream.js";
2
2
  export declare const BACKFILL_SOURCES: Map<string, string>;
3
+ export declare const SWITCHBOARD_BACKFILL_LIMIT = 2000;
3
4
  export interface BackfillDeps {
4
5
  fetchList: (source: string) => Promise<RadarEvent[]>;
6
+ fetchJson: (apiPath: string) => Promise<Record<string, unknown> | null>;
7
+ switchboardLimit?: number;
8
+ switchboardDeadlineMs?: number;
5
9
  readSpool: () => ParsedSSE[];
6
10
  write: (frame: ParsedSSE) => void;
7
11
  }
@@ -12,9 +16,11 @@ export interface BackfillSummary {
12
16
  * Backfill the device rings into the spool.
13
17
  *
14
18
  * For each backfillable source it fetches the device ring list, reads what the spool already holds,
15
- * and writes only the rows whose (base source, id) is NOT already present (as a summary OR as a
16
- * cached detail). Frames are written in the SAME shape the SSE push produces ({type: source,
17
- * event: row}) and oldest-first (ascending id) so the spool stays append-ordered like the live push.
19
+ * and writes only the rows whose dedupKey is NOT already present (as a summary OR as a cached
20
+ * detail). Switchboard is fetched per session (see fetchSwitchboardRows) and keyed with its
21
+ * timestamp. Frames are written in the SAME shape the SSE push produces ({type: source,
22
+ * event: row}) and oldest-first (ascending id, or timestamp for switchboard) so the spool stays
23
+ * append-ordered like the live push.
18
24
  *
19
25
  * Never throws: a failed list fetch for one source is swallowed (that source is simply not
20
26
  * backfilled this round) so a device blip cannot break enable or the stream. A row with no numeric
@@ -1,3 +1,4 @@
1
+ import { SWITCHBOARD_BACKFILL_DEADLINE_MS, SWITCHBOARD_KIND, newestSwitchboardSessionIds, switchboardListPath, switchboardPageEvents, switchboardSessionPath, } from "../shared/switchboard.js";
1
2
  import { baseSourceOf } from "./session-query.js";
2
3
  // The sources with a device ring and a list endpoint, each paired with the buildApiPath list-tool
3
4
  // name so the fetch reuses the pinned device-route table instead of hand-building a path. This is
@@ -10,6 +11,11 @@ export const BACKFILL_SOURCES = new Map([
10
11
  ["clog", "get_recent_clogs"],
11
12
  ["trace", "get_recent_traces"],
12
13
  ]);
14
+ // Switchboard has no flat ring list: the device keeps it per session, two routes deep, so it is
15
+ // its own leg below rather than a BACKFILL_SOURCES row. Backfill asks for one page of the
16
+ // device's max, 2000 (the default 50 is a few seconds of a live voice session); at about 250
17
+ // bytes a record that stays under the device's 1 MB response cap.
18
+ export const SWITCHBOARD_BACKFILL_LIMIT = 2000;
13
19
  // A read frame's numeric id, or undefined when it carries none. Only rows with a numeric id can be
14
20
  // deduped; a row with no id is written every round (it cannot be matched against the spool).
15
21
  function frameId(frame) {
@@ -26,8 +32,6 @@ function frameId(frame) {
26
32
  function baseSourceOfFrame(frame) {
27
33
  return baseSourceOf(frame.type) ?? frame.type;
28
34
  }
29
- // The dedup key for a (source, id) pair. NUL-separated so an id that contains a source substring
30
- // cannot collide with a different (source, id) pair.
31
35
  // Read a row's numeric id, or undefined. The device rows are plain objects of unknown shape.
32
36
  function numId(row) {
33
37
  if (typeof row !== "object" || row === null)
@@ -35,16 +39,26 @@ function numId(row) {
35
39
  const raw = row.id;
36
40
  return typeof raw === "number" ? raw : undefined;
37
41
  }
38
- function dedupKey(source, id) {
39
- return `${source}\u0000${id}`;
42
+ // The dedup key for a row. (source, id) for the ring sources, whose ids are unique for the life
43
+ // of the spool. Switchboard adds the record's timestamp: the plugin's id counter restarts with the
44
+ // app process, so two voice sessions either side of a restart both hold an id 1 and only the
45
+ // timestamp tells them apart. NUL-separated so an id that contains a source substring cannot
46
+ // collide with a different (source, id) pair.
47
+ function dedupKey(source, id, row) {
48
+ if (source !== SWITCHBOARD_KIND)
49
+ return `${source}\u0000${id}`;
50
+ const ts = row?.timestamp;
51
+ return `${source}\u0000${id}\u0000${typeof ts === "number" ? ts : ""}`;
40
52
  }
41
53
  /**
42
54
  * Backfill the device rings into the spool.
43
55
  *
44
56
  * For each backfillable source it fetches the device ring list, reads what the spool already holds,
45
- * and writes only the rows whose (base source, id) is NOT already present (as a summary OR as a
46
- * cached detail). Frames are written in the SAME shape the SSE push produces ({type: source,
47
- * event: row}) and oldest-first (ascending id) so the spool stays append-ordered like the live push.
57
+ * and writes only the rows whose dedupKey is NOT already present (as a summary OR as a cached
58
+ * detail). Switchboard is fetched per session (see fetchSwitchboardRows) and keyed with its
59
+ * timestamp. Frames are written in the SAME shape the SSE push produces ({type: source,
60
+ * event: row}) and oldest-first (ascending id, or timestamp for switchboard) so the spool stays
61
+ * append-ordered like the live push.
48
62
  *
49
63
  * Never throws: a failed list fetch for one source is swallowed (that source is simply not
50
64
  * backfilled this round) so a device blip cannot break enable or the stream. A row with no numeric
@@ -61,13 +75,18 @@ export async function backfillSpool(deps) {
61
75
  const id = frameId(frame);
62
76
  if (id === undefined)
63
77
  continue;
64
- have.add(dedupKey(baseSourceOfFrame(frame), id));
78
+ have.add(dedupKey(baseSourceOfFrame(frame), id, frame.event));
65
79
  }
66
80
  // Fetch all sources in parallel: each is an independent device pull, so running them concurrently
67
- // caps the wall time at one fetch, not the sum of four (each callRadar has its own timeout). A
68
- // per-source rejection is contained by allSettled so one blip never fails the others or enable.
81
+ // caps the wall time at the longer of one fetch (each callRadar has its own timeout) and the
82
+ // switchboard leg's deadline, not the sum of them all. A per-source rejection is contained by
83
+ // allSettled so one blip never fails the others or enable.
69
84
  const sources = [...BACKFILL_SOURCES.keys()];
70
- const results = await Promise.allSettled(sources.map((source) => deps.fetchList(source)));
85
+ const results = await Promise.allSettled([
86
+ ...sources.map((source) => deps.fetchList(source)),
87
+ fetchSwitchboardRows(deps),
88
+ ]);
89
+ sources.push(SWITCHBOARD_KIND);
71
90
  // Write sequentially over the resolved lists so the shared `have` dedup set is updated race-free.
72
91
  for (let i = 0; i < sources.length; i++) {
73
92
  const source = sources[i];
@@ -78,11 +97,15 @@ export async function backfillSpool(deps) {
78
97
  const rows = settled.value;
79
98
  if (!Array.isArray(rows))
80
99
  continue;
81
- // Append oldest-first so the spool stays append=ascending-id, which the newest-first read walk
82
- // and the before_id pager depend on. The device already returns oldest-first, but sort by id
83
- // ascending here rather than trust the order, matching the web server's defensive sort; a row
84
- // with no numeric id keeps its relative position. This also makes the fetch order irrelevant.
85
- const ordered = [...rows]
100
+ // Append oldest-first so each source's rows land in time order. The device already returns
101
+ // oldest-first, but sort by id ascending here rather than trust the order, matching the web
102
+ // server's defensive sort; a row with no numeric id keeps its relative position. This also
103
+ // makes the fetch order irrelevant. Switchboard is already sorted by timestamp in its leg: its
104
+ // ids restart with the app process, so across a restart the id order is not the time order.
105
+ // Append order is not global time order: a backfill of a reconnect gap appends after frames
106
+ // the live stream already wrote, and the pager keys on append seq, so a reader that wants time
107
+ // order sorts by each frame's timestamp.
108
+ const ordered = source === SWITCHBOARD_KIND ? rows : [...rows]
86
109
  .map((row, idx) => ({ row, idx }))
87
110
  .sort((a, b) => {
88
111
  const ai = numId(a.row);
@@ -97,7 +120,7 @@ export async function backfillSpool(deps) {
97
120
  continue;
98
121
  const id = numId(row);
99
122
  if (id !== undefined) {
100
- const key = dedupKey(source, id);
123
+ const key = dedupKey(source, id, row);
101
124
  if (have.has(key))
102
125
  continue;
103
126
  // Mark it held so a duplicate id within THIS same list is not written twice either.
@@ -109,6 +132,42 @@ export async function backfillSpool(deps) {
109
132
  }
110
133
  return { written };
111
134
  }
135
+ // The switchboard leg: list the sessions, take the newest few, fetch each one's page with the
136
+ // limit forwarded, and hand back every record oldest first by its own timestamp (the pages land in
137
+ // any order, and the sort is stable so records sharing a timestamp keep the device's order). A
138
+ // device that predates the source (no route, error JSON, non-JSON) answers null at every step and
139
+ // contributes nothing; one session failing leaves the others intact. Never throws: the caller's
140
+ // allSettled would contain it, but the leg owns its own failures the way fetchJson does.
141
+ //
142
+ // The leg is two waves (list, then pages), so on its own it could hold enable for two callRadar
143
+ // timeouts while a device sits on /api/switchboard. It races SWITCHBOARD_BACKFILL_DEADLINE_MS and
144
+ // past it resolves with the pages that had landed; a fetch still open then is left to callRadar's
145
+ // own timeout and its page is dropped.
146
+ function fetchSwitchboardRows(deps) {
147
+ const limit = deps.switchboardLimit ?? SWITCHBOARD_BACKFILL_LIMIT;
148
+ const deadlineMs = deps.switchboardDeadlineMs ?? SWITCHBOARD_BACKFILL_DEADLINE_MS;
149
+ const landed = [];
150
+ const when = (e) => (typeof e.timestamp === "number" ? e.timestamp : 0);
151
+ return new Promise((resolve) => {
152
+ let settled = false;
153
+ const finish = () => {
154
+ if (settled)
155
+ return;
156
+ settled = true;
157
+ clearTimeout(timer);
158
+ resolve(landed.flat().sort((a, b) => when(a) - when(b)));
159
+ };
160
+ const timer = setTimeout(finish, deadlineMs);
161
+ const walk = async () => {
162
+ const list = await deps.fetchJson(switchboardListPath()).catch(() => null);
163
+ await Promise.all(newestSwitchboardSessionIds(list).map(async (id) => {
164
+ const page = await deps.fetchJson(switchboardSessionPath(id, limit)).then(switchboardPageEvents, () => []);
165
+ landed.push(page);
166
+ }));
167
+ };
168
+ walk().then(finish, finish);
169
+ });
170
+ }
112
171
  // Serialize an async run so two triggers never overlap. The wiring layer (index.ts) calls the real
113
172
  // backfill from two places: the enable path and the reconnect hook. If a reconnect fires while a run
114
173
  // is still awaiting its device fetches, a second run would snapshot the same point-in-time `have` set
@@ -10,6 +10,7 @@
10
10
  // once, cache it, and return it. A pull failure degrades to the summary. It never throws.
11
11
  import { MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
12
12
  import { buildApiPath } from "./api-paths.js";
13
+ import { DECODED_COPY_KEYS, stripOwned, withDecodedRequestBody } from "./network-detail.js";
13
14
  import { detailTypeFor, selectById } from "./session-query.js";
14
15
  // Sources whose spool frame is a SUMMARY, so an id read must pull the body from the device once and
15
16
  // write it back. The value is the device-detail tool name buildApiPath already knows, so the pull
@@ -96,8 +97,27 @@ export async function resolveDetailById(frames, id, source, deps, cap = MAX_RADA
96
97
  // on every id-path branch that returns a frame so an oversized clog or device-pushed detail served
97
98
  // from file cannot flood the model context. An optional summary note rides along when the frame
98
99
  // still fits; if the frame itself is too big, the exceeds-cap note replaces it.
100
+ //
101
+ // A network detail also gets the decoded form-body view here, on the way out and after any spool
102
+ // write, so a query_session id read carries the same reading aid get_network_call_detail does,
103
+ // without the decoded copy ever being persisted. The cap is measured on what goes out, and the
104
+ // decoration never costs a record: when the decorated frame is over budget the decoded copy goes
105
+ // first (the omitted note in its place, the truncation flag kept); if that is still over, the
106
+ // note goes and the flag alone stays; if even that is over, the record goes out as stored with
107
+ // only the decoder's own keys removed, which is what went out before any of this existed; only a
108
+ // record that is over budget in that form is dropped.
99
109
  function cappedFrameResult(frame, cap, note) {
100
- if (Buffer.byteLength(JSON.stringify(frame)) > cap) {
110
+ const fits = (f) => Buffer.byteLength(JSON.stringify(f)) <= cap;
111
+ const decorated = decorateFrame(frame);
112
+ const bare = bareFrame(frame);
113
+ let served = decorated;
114
+ if (!fits(served))
115
+ served = withoutDecodedCopy(served);
116
+ if (!fits(served))
117
+ served = flagOnly(bare, decorated);
118
+ if (!fits(served))
119
+ served = bare;
120
+ if (!fits(served)) {
101
121
  return {
102
122
  frames: [],
103
123
  count: 0,
@@ -105,5 +125,37 @@ function cappedFrameResult(frame, cap, note) {
105
125
  note: "the frame with that id alone exceeds the byte cap",
106
126
  };
107
127
  }
108
- return { frames: [frame], count: 1, truncated: false, ...(note !== undefined ? { note } : {}) };
128
+ return { frames: [served], count: 1, truncated: false, ...(note !== undefined ? { note } : {}) };
129
+ }
130
+ const DECODED_OVER_CAP_NOTE = "decoded form would put the record over the response byte cap; request_body holds the raw bytes";
131
+ // Drop the decoded copy (and its unparsed-field notes) from a decorated frame, leaving every other
132
+ // decoration in place, and say why. A frame that carried no decoded copy is returned as it is.
133
+ function withoutDecodedCopy(frame) {
134
+ if (!DECODED_COPY_KEYS.some((k) => k in frame.event))
135
+ return frame;
136
+ const event = { ...frame.event };
137
+ for (const k of DECODED_COPY_KEYS)
138
+ delete event[k];
139
+ event.request_body_decoded_omitted = DECODED_OVER_CAP_NOTE;
140
+ return { ...frame, event };
141
+ }
142
+ // The bare frame plus only the truncation flag, when the decorated frame carried it.
143
+ function flagOnly(bare, decorated) {
144
+ if (decorated.event.request_body_truncated !== true)
145
+ return bare;
146
+ return { ...bare, event: { ...bare.event, request_body_truncated: true } };
147
+ }
148
+ // The stored network detail with the decoder's own keys removed (a spool written by another
149
+ // version could carry stale ones); any other frame as it is.
150
+ function bareFrame(frame) {
151
+ if (frame.type !== "network_detail")
152
+ return frame;
153
+ const event = stripOwned(frame.event);
154
+ return event === frame.event ? frame : { ...frame, event };
155
+ }
156
+ function decorateFrame(frame) {
157
+ if (frame.type !== "network_detail")
158
+ return frame;
159
+ const event = withDecodedRequestBody(frame.event);
160
+ return event === frame.event ? frame : { ...frame, event };
109
161
  }
@@ -4,6 +4,7 @@ export interface EnableDeps {
4
4
  destroyStream: () => void;
5
5
  connectStream: () => void;
6
6
  isStreamConnected: () => boolean;
7
+ wasStreamRejected: () => boolean;
7
8
  resetDbState: () => void;
8
9
  startSpool: () => void;
9
10
  runBackfill: () => Promise<unknown>;
@@ -9,12 +9,21 @@
9
9
  // that exits 0 with no receiver (radar modules missing, wrong profile), which the
10
10
  // old code reported as enabled:true with a failing ping.
11
11
  import { deviceServerSilentError, readProcessState, } from "../shared/enable-diagnosis.js";
12
- // Ping-verify cadence: first probe fast (a healthy server answers immediately;
13
- // this is the whole latency of a normal enable), then two patient retries to
14
- // absorb real server startup.
15
- const PING_WAITS_MS = [500, 1000, 1000];
12
+ import { ENABLE_PING_WAITS_MS } from "../shared/constants.js";
13
+ import { clearRadarTokenCache, openModeWarningAfterEnable, tokenFileMessage, unauthorizedMessageFor, } from "../shared/radar-token.js";
14
+ // The device answered the ping with HTTP 401: the token is refused, the app is not down.
15
+ class PingRefused extends Error {
16
+ }
16
17
  export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
17
- const { device, destroyStream, connectStream, isStreamConnected, resetDbState, startSpool, runBackfill, ping, sleep, onDeviceSwitch, } = deps;
18
+ const outcome = await enableSession(timeoutMinutes, deviceSerial, deps);
19
+ // activate() starts a transport-owned log capture before the app is verified. An enable that
20
+ // ends disabled must not leave that child running, or leave its lines for the next enable.
21
+ if (!outcome.enabled)
22
+ deps.device.stopLogCapture?.();
23
+ return outcome;
24
+ }
25
+ async function enableSession(timeoutMinutes, deviceSerial, deps) {
26
+ const { device, destroyStream, connectStream, isStreamConnected, wasStreamRejected, resetDbState, startSpool, runBackfill, ping, sleep, onDeviceSwitch, } = deps;
18
27
  // Tear down the old stream (and its reconnect loop) FIRST, then drop all cached
19
28
  // transport state so this enable starts clean. Without the reset, a stale adb
20
29
  // forward (device end dead after an idle timeout or a replug) makes ensureForward()
@@ -49,6 +58,7 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
49
58
  if (selection && selection.ok && selection.switched) {
50
59
  onDeviceSwitch();
51
60
  }
61
+ clearRadarTokenCache();
52
62
  if (!device.ensureForward()) {
53
63
  const reason = device.getLastForwardError?.() ?? null;
54
64
  return {
@@ -60,8 +70,99 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
60
70
  },
61
71
  };
62
72
  }
63
- device.activate(timeoutMinutes);
73
+ const identifiedPing = async () => {
74
+ const status = await ping();
75
+ if (device.acceptsRadarPeer && !device.acceptsRadarPeer(status)) {
76
+ throw new Error(`The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`);
77
+ }
78
+ return status;
79
+ };
80
+ const verifiedPing = async () => {
81
+ const status = await identifiedPing();
82
+ if (status.http_status === 401)
83
+ throw new PingRefused("the device refused the ping");
84
+ if (device.acceptsRadarPeer && status.status !== "ok") {
85
+ throw new Error(typeof status.error === "string" ? status.error : "Radar is not armed");
86
+ }
87
+ return status;
88
+ };
89
+ // Simulator Radar is already reachable on the Mac's loopback; verify its identity before
90
+ // starting backfill or SSE so an Android adb forward occupying the same port is never consumed.
91
+ if (device.acceptsRadarPeer) {
92
+ let status = null;
93
+ try {
94
+ status = await ping();
95
+ }
96
+ catch (error) {
97
+ // Nothing answered (ECONNREFUSED, a timeout). Say so in the platform's terms instead of
98
+ // handing back the raw socket error.
99
+ const reason = error instanceof Error ? error.message : String(error);
100
+ return {
101
+ enabled: false,
102
+ body: {
103
+ error: `No Radar listener answered for the ${device.platform} app (${reason}).` +
104
+ (device.radarListenerHint ? ` ${device.radarListenerHint}` : ""),
105
+ enabled: false,
106
+ platform: device.platform,
107
+ },
108
+ };
109
+ }
110
+ if (!device.acceptsRadarPeer(status)) {
111
+ return {
112
+ enabled: false,
113
+ body: {
114
+ error: `The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`,
115
+ enabled: false,
116
+ platform: device.platform,
117
+ },
118
+ };
119
+ }
120
+ }
121
+ if (device.activateAsync) {
122
+ await device.activateAsync(timeoutMinutes);
123
+ }
124
+ else {
125
+ device.activate(timeoutMinutes);
126
+ }
127
+ const tokenFileError = device.getLastActivateTokenFileError?.() ?? null;
128
+ if (tokenFileError) {
129
+ return {
130
+ enabled: false,
131
+ body: { error: tokenFileMessage(tokenFileError, "mcp"), enabled: false, platform: device.platform },
132
+ };
133
+ }
64
134
  const activateError = device.getLastActivateError?.() ?? null;
135
+ // A host-log-only transport has a real session boundary without an app-side Radar HTTP
136
+ // listener. Selecting the device and starting its capture are sufficient; probing the
137
+ // host-global Radar port here would either reject a healthy session or, worse, accept an
138
+ // unrelated listener. Keep the HTTP/spool/backfill path below exclusive to transports that
139
+ // explicitly advertise it. No shipped transport takes this branch today (Android and the iOS
140
+ // Simulator both serve Radar HTTP); it is the contract for one that only has host logs.
141
+ if (!device.supportsRadarHttpTools && device.supportsHostLogs) {
142
+ if (activateError) {
143
+ return {
144
+ enabled: false,
145
+ body: {
146
+ error: `Log capture activation failed: ${activateError}`,
147
+ enabled: false,
148
+ platform: device.platform,
149
+ },
150
+ };
151
+ }
152
+ const selected = device.getSelectedDevice?.() ?? null;
153
+ return {
154
+ enabled: true,
155
+ body: {
156
+ enabled: true,
157
+ platform: device.platform,
158
+ stream_connected: false,
159
+ log_capture: "host",
160
+ ...(selected
161
+ ? { device_serial: selected.serial, device_label: selected.label }
162
+ : {}),
163
+ },
164
+ };
165
+ }
65
166
  if (activateError) {
66
167
  // The broadcast failed at the adb level. The device server may STILL be alive
67
168
  // (armed by a prior session, or the broadcast timed out on a loaded device
@@ -69,13 +170,17 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
69
170
  // error, and a dead one gets a real error instead of the old silent
70
171
  // enabled:true + failing tools.
71
172
  try {
72
- await ping();
173
+ await verifiedPing();
73
174
  }
74
- catch {
175
+ catch (error) {
75
176
  return {
76
177
  enabled: false,
77
178
  body: {
78
- error: `Radar activation broadcast failed: ${activateError}. Is the device connected? Check adb devices.`,
179
+ error: error instanceof PingRefused
180
+ ? `Radar activation broadcast failed: ${activateError}. ${unauthorizedMessageFor(device)}`
181
+ : device.radarListenerHint
182
+ ? `Radar activation failed: ${activateError}. ${device.radarListenerHint}`
183
+ : `Radar activation broadcast failed: ${activateError}. Is the device connected? Check adb devices.`,
79
184
  enabled: false,
80
185
  platform: device.platform,
81
186
  },
@@ -87,27 +192,41 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
87
192
  // fetch, which opens the stream on its first call), so the trailing
88
193
  // connectStream() is usually a no-op. Correctness does not rely on connect
89
194
  // ordering: the (source, id) have-set and the read-time collapse fold any
90
- // frame both paths write into one.
195
+ // frame both paths write into one. Skipped while the device refused the stream:
196
+ // connecting clears that latch, and the check after the pings needs it.
91
197
  startSpool();
92
198
  await runBackfill();
93
- connectStream();
199
+ if (!wasStreamRejected())
200
+ connectStream();
94
201
  // Verify the device server actually came up. A broadcast can land nowhere and
95
202
  // still exit 0 (no receiver: radar modules missing from the build, or a
96
203
  // wrong-profile target). Retry to absorb real startup latency before
97
204
  // declaring it dead.
98
205
  let status = null;
99
- for (const waitMs of PING_WAITS_MS) {
206
+ let saw401 = false;
207
+ for (const waitMs of ENABLE_PING_WAITS_MS) {
100
208
  await sleep(waitMs);
101
209
  try {
102
- status = await ping();
210
+ status = await verifiedPing();
103
211
  break;
104
212
  }
105
- catch {
106
- // Retry until the waits are exhausted.
213
+ catch (error) {
214
+ if (error instanceof PingRefused)
215
+ saw401 = true;
107
216
  }
108
217
  }
109
218
  if (status === null) {
110
219
  destroyStream();
220
+ if (saw401) {
221
+ return {
222
+ enabled: false,
223
+ body: {
224
+ error: unauthorizedMessageFor(device),
225
+ enabled: false,
226
+ platform: device.platform,
227
+ },
228
+ };
229
+ }
111
230
  // Checked fresh, not from a cache, but only here, seconds after the broadcast: backfill,
112
231
  // stream connect, and three ping retries have already run. A confirmed "stopped" does not
113
232
  // prove the app was never launched. It is equally consistent with the app receiving the
@@ -124,7 +243,18 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
124
243
  },
125
244
  };
126
245
  }
246
+ // A late pass means the 401 tore the first stream down, or the device refused
247
+ // the backfill's stream and the connect above was skipped. Either way the rings
248
+ // hold what the spool missed.
249
+ if (saw401 || wasStreamRejected()) {
250
+ connectStream();
251
+ await runBackfill();
252
+ }
253
+ else if (!isStreamConnected())
254
+ connectStream();
127
255
  const selected = device.getSelectedDevice?.() ?? null;
256
+ // A tokened enable that stays open did not take, so name its broadcast failure.
257
+ const openModeWarning = openModeWarningAfterEnable(status.token_required, activateError);
128
258
  return {
129
259
  enabled: true,
130
260
  body: {
@@ -144,6 +274,7 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
144
274
  }
145
275
  : {}),
146
276
  ...status,
277
+ ...(openModeWarning ? { warning: openModeWarning } : {}),
147
278
  },
148
279
  };
149
280
  }
@@ -68,22 +68,63 @@ export function baseSourceOf(type) {
68
68
  function baseSourceOfFrame(frame) {
69
69
  return baseSourceOf(frame.type) ?? frame.type;
70
70
  }
71
+ // The list-read collapse key: (base source, id, timestamp). A summary and its pulled detail share
72
+ // all three (the device writes the record's timestamp on both routes), so they still fold to one.
73
+ // Two records that share an id but not a timestamp are two records: the device id counters
74
+ // restart with the app process, and switchboard in particular reuses id 1 on every restart, so an
75
+ // id-only key would hide the earlier process's records.
76
+ //
77
+ // A frame with no numeric timestamp cannot be keyed on its own. `stamps` holds, per (base, id),
78
+ // the distinct numeric timestamps seen in the list: when there is exactly one, the unstamped frame
79
+ // is that record (a detail route that omits the field) and folds onto it; otherwise it keys on the
80
+ // id alone, since there is no telling which record it belongs to. A detail the device restamped
81
+ // carries a different number and stays its own record.
82
+ function groupKey(frame, id) {
83
+ return `${baseSourceOfFrame(frame)}\u0000${id}`;
84
+ }
85
+ function frameTimestamp(frame) {
86
+ const ts = frame.event?.timestamp;
87
+ return typeof ts === "number" ? ts : undefined;
88
+ }
89
+ function collapseKey(frame, id, stamps) {
90
+ const group = groupKey(frame, id);
91
+ let ts = frameTimestamp(frame);
92
+ if (ts === undefined) {
93
+ const seen = stamps.get(group);
94
+ if (seen !== undefined && seen.size === 1)
95
+ ts = [...seen][0];
96
+ }
97
+ return `${group}\u0000${ts ?? ""}`;
98
+ }
71
99
  // After a lazy pull the spool holds BOTH a summary and its `<source>_detail` for the same id, so an
72
- // unfiltered list read would show that id twice. Collapse each (base source, id) pair to one frame,
73
- // preferring the detail (the fuller record). A frame with no numeric id, or whose (base, id) pair
74
- // appears once, passes through untouched. Order is preserved so the newest-first walk is unaffected.
75
- // Pure: it only reshapes the frame list. The dedup is by base source via baseSourceOfFrame, never a
76
- // hard-coded source-name switch, so a future plugin source dedups for free.
100
+ // unfiltered list read would show that id twice. Collapse each collapseKey to one frame, preferring
101
+ // the detail (the fuller record). A frame with no numeric id, or whose key appears once, passes
102
+ // through untouched. Order is preserved so the newest-first walk is unaffected. Pure: it only
103
+ // reshapes the frame list. The dedup is by base source via baseSourceOfFrame, never a hard-coded
104
+ // source-name switch, so a future plugin source dedups for free.
77
105
  function dedupSummaryDetail(frames) {
78
- // First pass: for each (base source, id) key, remember the LAST frame that carried it. Append
79
- // order means the last write wins, so a reused id resolves to its freshest record, not a stale
80
- // detail. Mirrors selectById's recency rule.
106
+ // Index the timestamps each (base, id) group carries, so an unstamped frame can fold onto its
107
+ // group's one record (see collapseKey).
108
+ const stamps = new Map();
109
+ for (const frame of frames) {
110
+ const id = frameId(frame);
111
+ const ts = id === undefined ? undefined : frameTimestamp(frame);
112
+ if (id === undefined || ts === undefined)
113
+ continue;
114
+ const group = groupKey(frame, id);
115
+ const seen = stamps.get(group) ?? new Set();
116
+ seen.add(ts);
117
+ stamps.set(group, seen);
118
+ }
119
+ // First pass: for each key, remember the LAST frame that carried it. Append order means the last
120
+ // write wins, so a re-pulled detail resolves to its freshest record, not a stale one. Mirrors
121
+ // selectById's recency rule.
81
122
  const winner = new Map();
82
123
  for (const frame of frames) {
83
124
  const id = frameId(frame);
84
125
  if (id === undefined)
85
126
  continue;
86
- winner.set(`${baseSourceOfFrame(frame)}\u0000${id}`, frame);
127
+ winner.set(collapseKey(frame, id, stamps), frame);
87
128
  }
88
129
  // Second pass: keep no-id frames as-is; for id-bearing frames emit only the winner, at the
89
130
  // position of the key's FIRST appearance so the newest-first walk order stays stable.
@@ -95,7 +136,7 @@ function dedupSummaryDetail(frames) {
95
136
  out.push(frame);
96
137
  continue;
97
138
  }
98
- const key = `${baseSourceOfFrame(frame)}\u0000${id}`;
139
+ const key = collapseKey(frame, id, stamps);
99
140
  if (emitted.has(key))
100
141
  continue;
101
142
  emitted.add(key);
@@ -224,7 +265,8 @@ export function querySession(frames, rawFilter, epoch) {
224
265
  // id-bypass, PURE mirror of the id path. In production handleQuerySession resolves an id read via
225
266
  // resolveDetailById (which does the lazy device pull) before this function is reached, so this
226
267
  // branch does not run for the MCP tool. It stays as the pure, no-pull reference the unit tests
227
- // exercise: same selectById + byte-cap semantics, minus the device fetch. Keep the two in step.
268
+ // exercise: same selectById, the hard cap on the stored frame, minus the device fetch and minus
269
+ // the form-body decoration the live path adds on the way out.
228
270
  // Prefer a stored detail frame over a summary; honor the hard cap so no single id floods context.
229
271
  if (filter.id !== undefined) {
230
272
  const idCap = clampByteCap(filter.byte_cap);