@slack/radar-mcp 1.21.0 → 1.23.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 (87) hide show
  1. package/README.md +114 -18
  2. package/dist/mcp/api-paths.d.ts +2 -2
  3. package/dist/mcp/api-paths.js +4 -19
  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 +210 -145
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/radar-export-get.d.ts +30 -0
  10. package/dist/mcp/radar-export-get.js +49 -0
  11. package/dist/mcp/radar-http.d.ts +22 -0
  12. package/dist/mcp/radar-http.js +61 -0
  13. package/dist/mcp/radar-response.d.ts +5 -1
  14. package/dist/mcp/radar-response.js +8 -3
  15. package/dist/mcp/session-backfill.js +3 -4
  16. package/dist/mcp/session-enable.d.ts +15 -0
  17. package/dist/mcp/session-enable.js +268 -19
  18. package/dist/mcp/snapshot.js +42 -26
  19. package/dist/mcp/sources-gate.js +6 -0
  20. package/dist/mcp/stale-dashboard.d.ts +23 -0
  21. package/dist/mcp/stale-dashboard.js +122 -0
  22. package/dist/mcp/switchboard-spool.d.ts +12 -0
  23. package/dist/mcp/switchboard-spool.js +107 -0
  24. package/dist/mcp/switchboard-tools.d.ts +9 -0
  25. package/dist/mcp/switchboard-tools.js +144 -6
  26. package/dist/mcp/test-cases.d.ts +14 -0
  27. package/dist/mcp/test-cases.js +77 -0
  28. package/dist/mcp/test-runs-tools.d.ts +8 -0
  29. package/dist/mcp/test-runs-tools.js +95 -0
  30. package/dist/mcp/tools.d.ts +4 -1
  31. package/dist/mcp/tools.js +101 -21
  32. package/dist/mcp/web-child-env.d.ts +4 -1
  33. package/dist/mcp/web-child-env.js +4 -1
  34. package/dist/shared/android.d.ts +44 -0
  35. package/dist/shared/android.js +234 -24
  36. package/dist/shared/constants.d.ts +9 -4
  37. package/dist/shared/constants.js +9 -4
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/ios-logs.d.ts +10 -0
  41. package/dist/shared/ios-logs.js +91 -0
  42. package/dist/shared/ios.d.ts +25 -2
  43. package/dist/shared/ios.js +157 -3
  44. package/dist/{web → shared}/log-session.d.ts +45 -31
  45. package/dist/shared/log-session.js +300 -0
  46. package/dist/shared/logcat-capture.js +17 -1
  47. package/dist/shared/radar-request-raw.d.ts +7 -0
  48. package/dist/shared/radar-request-raw.js +89 -0
  49. package/dist/shared/radar-token.d.ts +25 -0
  50. package/dist/shared/radar-token.js +164 -0
  51. package/dist/shared/stream.d.ts +3 -0
  52. package/dist/shared/stream.js +107 -15
  53. package/dist/shared/switchboard-host-store.d.ts +21 -0
  54. package/dist/shared/switchboard-host-store.js +166 -0
  55. package/dist/shared/switchboard-note.d.ts +15 -0
  56. package/dist/shared/switchboard-note.js +92 -0
  57. package/dist/shared/switchboard-report-file.d.ts +5 -0
  58. package/dist/shared/switchboard-report-file.js +26 -0
  59. package/dist/shared/switchboard-report.d.ts +20 -0
  60. package/dist/shared/switchboard-report.js +406 -0
  61. package/dist/shared/switchboard.d.ts +111 -2
  62. package/dist/shared/switchboard.js +436 -3
  63. package/dist/shared/transport.d.ts +49 -3
  64. package/dist/shared/version.d.ts +2 -0
  65. package/dist/shared/version.js +18 -0
  66. package/dist/shared/wire.d.ts +14 -1
  67. package/dist/web/install-app.d.ts +75 -8
  68. package/dist/web/install-app.js +330 -67
  69. package/dist/web/macapp/RadarApp.swift +487 -23
  70. package/dist/web/public/index.html +51 -9
  71. package/dist/web/public/next/app.js +33 -18
  72. package/dist/web/public/next/feed.js +102 -15
  73. package/dist/web/public/next/flags.js +3 -0
  74. package/dist/web/public/next/inspector.js +69 -3
  75. package/dist/web/public/next/prefs.js +5 -2
  76. package/dist/web/public/next/registry.js +18 -5
  77. package/dist/web/public/next/store.js +455 -29
  78. package/dist/web/public/next/switchboard-note.js +93 -0
  79. package/dist/web/public/next/toast.js +9 -5
  80. package/dist/web/public/next/voice-model.js +215 -35
  81. package/dist/web/public/next/voice.js +173 -18
  82. package/dist/web/server.d.ts +15 -11
  83. package/dist/web/server.js +690 -168
  84. package/dist/web/spec.d.ts +2 -1
  85. package/dist/web/spec.js +2 -1
  86. package/package.json +2 -2
  87. package/dist/web/log-session.js +0 -166
@@ -0,0 +1,49 @@
1
+ // callRadarForExport's forward-then-retry-once logic as an injectable factory, so a test can
2
+ // drive it with fakes (index.ts connects stdio at module load and cannot be imported).
3
+ /**
4
+ * Build the export path's raw device GET, retrying once after a forward rebuild like callRadar,
5
+ * but without radarRequest's model-context byte budget.
6
+ *
7
+ * A capped result is returned without retrying: the same cap would trip again, and the device
8
+ * did nothing wrong, so none of the reset/reconnect/disable side effects apply. Past the
9
+ * deadline, no further attempt is made.
10
+ */
11
+ export function makeCallRadarForExport(deps, idleMs, overallMs, defaultCapBytes) {
12
+ const msLeft = (deadline) => (deadline === undefined ? undefined : deadline - Date.now());
13
+ return async function callRadarForExport(requestPath, capBytes = defaultCapBytes, deadline) {
14
+ if (!deps.supportsRadarHttpTools())
15
+ return { status: 0, body: null };
16
+ if (!deps.forwardForRead())
17
+ return { status: 0, body: null };
18
+ const firstLeft = msLeft(deadline);
19
+ if (firstLeft !== undefined && firstLeft <= 0)
20
+ return { status: 0, body: null };
21
+ deps.activate(deps.getTimeoutMinutes());
22
+ if (!deps.wasStreamRejected())
23
+ deps.connectStream();
24
+ const first = await deps.request(requestPath, idleMs, overallMs, capBytes, deadline);
25
+ if (first.status !== 0 || first.capped)
26
+ return first;
27
+ // Out of time is not the device's fault, so skip the retry without its disable side effects.
28
+ const retryLeft = msLeft(deadline);
29
+ if (retryLeft !== undefined && retryLeft <= 0)
30
+ return first;
31
+ deps.resetState();
32
+ deps.destroyStream();
33
+ if (!deps.ensureForward()) {
34
+ deps.onSessionDisabled();
35
+ return { status: 0, body: null };
36
+ }
37
+ const secondLeft = msLeft(deadline);
38
+ if (secondLeft !== undefined && secondLeft <= 0)
39
+ return first;
40
+ deps.activate(deps.getTimeoutMinutes());
41
+ // The re-arm is a fresh claim on the device, so a refusal from before it is stale.
42
+ deps.clearStreamRejected();
43
+ deps.connectStream();
44
+ const second = await deps.request(requestPath, idleMs, overallMs, capBytes, deadline);
45
+ if (second.status === 0 && !second.capped)
46
+ deps.onSessionDisabled();
47
+ return second;
48
+ };
49
+ }
@@ -0,0 +1,22 @@
1
+ import { type RadarTokenSender } from "../shared/radar-token.js";
2
+ import { type RadarResponse } from "./radar-response.js";
3
+ export declare const REQUEST_LOST_PREFIX = "Radar did not answer in time: ";
4
+ export declare const REQUEST_TIMED_OUT = "Request timed out";
5
+ export declare const DEFAULT_TIMEOUT_MS = 10000;
6
+ export interface RadarRequestInit {
7
+ method?: "POST" | "DELETE";
8
+ body?: string;
9
+ timeoutMs?: number;
10
+ deadlineMs?: number;
11
+ reportLost?: boolean;
12
+ }
13
+ export declare function radarHttpRequest({ host, port, path, method, body, timeoutMs, deadlineMs, transport }: {
14
+ host: string;
15
+ port: number;
16
+ path: string;
17
+ method?: string;
18
+ body?: string;
19
+ timeoutMs?: number;
20
+ deadlineMs?: number;
21
+ transport: RadarTokenSender;
22
+ }): Promise<RadarResponse>;
@@ -0,0 +1,61 @@
1
+ import http from "http";
2
+ import { MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
3
+ import { radarTokenHeaderFor } from "../shared/radar-token.js";
4
+ import { interpretRadarResponse, responseBudgetError } from "./radar-response.js";
5
+ export const REQUEST_LOST_PREFIX = "Radar did not answer in time: ";
6
+ export const REQUEST_TIMED_OUT = "Request timed out";
7
+ export const DEFAULT_TIMEOUT_MS = 10_000;
8
+ export function radarHttpRequest({ host, port, path, method = "GET", body, timeoutMs = DEFAULT_TIMEOUT_MS, deadlineMs, transport }) {
9
+ return new Promise((resolve, reject) => {
10
+ let settled = false;
11
+ let overallTimer;
12
+ const done = (response) => {
13
+ if (settled)
14
+ return;
15
+ settled = true;
16
+ clearTimeout(overallTimer);
17
+ resolve(response);
18
+ };
19
+ const fail = (error) => {
20
+ if (settled)
21
+ return;
22
+ settled = true;
23
+ clearTimeout(overallTimer);
24
+ reject(error);
25
+ };
26
+ const req = http.request({
27
+ host, port, path, method, timeout: timeoutMs,
28
+ headers: {
29
+ ...radarTokenHeaderFor(transport),
30
+ ...(body === undefined ? {} : {
31
+ "Content-Type": "application/json",
32
+ "Content-Length": Buffer.byteLength(body),
33
+ }),
34
+ },
35
+ }, (res) => {
36
+ let data = "";
37
+ let bytes = 0;
38
+ res.on("data", (chunk) => {
39
+ if (settled)
40
+ return;
41
+ bytes += chunk.length;
42
+ if (bytes > MAX_RADAR_RESPONSE_BYTES) {
43
+ done(responseBudgetError());
44
+ req.destroy();
45
+ return;
46
+ }
47
+ data += chunk;
48
+ });
49
+ res.on("end", () => done(interpretRadarResponse(res.statusCode ?? 0, data)));
50
+ });
51
+ req.on("error", fail);
52
+ const timedOut = () => {
53
+ req.destroy();
54
+ fail(new Error(REQUEST_TIMED_OUT));
55
+ };
56
+ req.on("timeout", timedOut);
57
+ if (deadlineMs !== undefined)
58
+ overallTimer = setTimeout(timedOut, Math.max(0, Math.min(timeoutMs, deadlineMs - Date.now())));
59
+ req.end(body);
60
+ });
61
+ }
@@ -1,6 +1,9 @@
1
+ import { type RadarTokenSender } from "../shared/radar-token.js";
1
2
  export interface RadarResponse {
2
3
  error?: string;
3
- status?: number;
4
+ status?: unknown;
5
+ http_status?: number;
6
+ request_lost?: true;
4
7
  stream_connected?: boolean;
5
8
  local_network_buffer?: number;
6
9
  local_rtm_buffer?: number;
@@ -19,6 +22,7 @@ export interface RadarResponse {
19
22
  * body keeps the existing {raw} behavior, a real if unusual success payload.
20
23
  */
21
24
  export declare function interpretRadarResponse(status: number, body: string): RadarResponse;
25
+ export declare function unauthorizedResponse(response: RadarResponse, sender: RadarTokenSender): RadarResponse;
22
26
  /**
23
27
  * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
24
28
  * on the wire as the bytes arrive; a handler that receives a parsed answer through an injected
@@ -2,6 +2,7 @@
2
2
  // out of index.ts so it is unit-testable: index.ts connects stdio at module load, so importing it
3
3
  // from a test would hang.
4
4
  import { MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
5
+ import { unauthorizedMessageFor } from "../shared/radar-token.js";
5
6
  /**
6
7
  * Turn a device HTTP (status, body) into the RadarResponse the tool layer returns. Parse JSON
7
8
  * when the body is JSON: this preserves the device's own error bodies (e.g. an in-app 404 sends
@@ -24,6 +25,7 @@ export function interpretRadarResponse(status, body) {
24
25
  return {
25
26
  error: `Device returned HTTP ${status} with a non-JSON body. The route may not exist on this build (an older debug build can predate a newer tool), or an upstream error occurred.${bodyDetail}`,
26
27
  status,
28
+ http_status: status,
27
29
  };
28
30
  }
29
31
  return { raw: body };
@@ -32,10 +34,13 @@ export function interpretRadarResponse(status, body) {
32
34
  // RadarResponse, and a downstream `result.error` read on a non-object (esp. null) would throw.
33
35
  // Keep it as a raw payload instead of casting a lie. (The old code cast straight to
34
36
  // RadarResponse and carried this hole; guarding here closes it.)
35
- if (typeof parsed !== "object" || parsed === null) {
36
- return { raw: body };
37
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
38
+ return status >= 400 ? { raw: body, http_status: status } : { raw: body };
37
39
  }
38
- return parsed;
40
+ return status >= 400 ? { ...parsed, http_status: status } : parsed;
41
+ }
42
+ export function unauthorizedResponse(response, sender) {
43
+ return response.http_status === 401 ? { error: unauthorizedMessageFor(sender), http_status: 401 } : response;
39
44
  }
40
45
  /**
41
46
  * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
@@ -12,10 +12,9 @@ export const BACKFILL_SOURCES = new Map([
12
12
  ["trace", "get_recent_traces"],
13
13
  ]);
14
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. Records per session asked for: the device
16
- // holds 2000 per session (SwitchboardRadarPlugin eventCapacity), so this asks for the whole ring;
17
- // without it the device pages at 50, a few seconds of a live voice session. A full page of 2000
18
- // records at about 250 bytes each stays under the device's 1 MB response cap.
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.
19
18
  export const SWITCHBOARD_BACKFILL_LIMIT = 2000;
20
19
  // A read frame's numeric id, or undefined when it carries none. Only rows with a numeric id can be
21
20
  // deduped; a row with no id is written every round (it cannot be matched against the spool).
@@ -1,9 +1,11 @@
1
1
  import type { DeviceTransport } from "../shared/transport.js";
2
2
  export interface EnableDeps {
3
3
  device: DeviceTransport;
4
+ forwardForRead?: () => boolean;
4
5
  destroyStream: () => void;
5
6
  connectStream: () => void;
6
7
  isStreamConnected: () => boolean;
8
+ wasStreamRejected: () => boolean;
7
9
  resetDbState: () => void;
8
10
  startSpool: () => void;
9
11
  runBackfill: () => Promise<unknown>;
@@ -15,4 +17,17 @@ export interface EnableOutcome {
15
17
  body: Record<string, unknown>;
16
18
  enabled: boolean;
17
19
  }
20
+ export interface EnablerHooks {
21
+ isEnabled: () => boolean;
22
+ setEnabled: (enabled: boolean) => void;
23
+ applyEnableOutcome: (outcome: EnableOutcome) => void;
24
+ clearSources: () => void;
25
+ clearStreamRejected: () => void;
26
+ log: (line: string) => void;
27
+ }
28
+ export declare function createEnabler(hooks: EnablerHooks): {
29
+ switchProfile(broadcast: () => void): void;
30
+ enable(timeoutMinutes: number | null | undefined, deviceSerial: string | null, deps: EnableDeps): Promise<EnableOutcome>;
31
+ };
32
+ export declare function refreshEnabledSession(timeoutMinutes: number | null, deviceSerial: string | null, deps: EnableDeps): Promise<EnableOutcome | null>;
18
33
  export declare function runSessionEnable(timeoutMinutes: number, deviceSerial: string | null, deps: EnableDeps): Promise<EnableOutcome>;
@@ -9,12 +9,161 @@
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
+ }
17
+ async function identifiedPing(device, ping) {
18
+ const status = await ping();
19
+ if (device.acceptsRadarPeer && !device.acceptsRadarPeer(status)) {
20
+ throw new Error(`The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`);
21
+ }
22
+ return status;
23
+ }
24
+ async function verifiedPing(device, ping) {
25
+ const status = await identifiedPing(device, ping);
26
+ if (status.http_status === 401)
27
+ throw new PingRefused("the device refused the ping");
28
+ if (device.acceptsRadarPeer && status.status !== "ok") {
29
+ throw new Error(typeof status.error === "string" ? status.error : "Radar is not armed");
30
+ }
31
+ return status;
32
+ }
33
+ function isArmed(status) {
34
+ return status.http_status === undefined && (status.status === "ok" || status.ok === true);
35
+ }
36
+ function selectedDeviceFields(device) {
37
+ const selected = device.getSelectedDevice?.();
38
+ return selected ? { device_serial: selected.serial, device_label: selected.label } : {};
39
+ }
40
+ export function createEnabler(hooks) {
41
+ let inFlight = 0;
42
+ let generation = 0;
43
+ return {
44
+ // A profile switch makes an in-flight repeat ping stale. Bump first so a broadcast that throws still counts.
45
+ switchProfile(broadcast) {
46
+ generation++;
47
+ broadcast();
48
+ },
49
+ async enable(timeoutMinutes, deviceSerial, deps) {
50
+ // An absent or zero timeout keeps the current window.
51
+ const requestedTimeout = timeoutMinutes || null;
52
+ const { device, connectStream, isStreamConnected, destroyStream } = deps;
53
+ try {
54
+ if (hooks.isEnabled() && inFlight === 0) {
55
+ const started = generation;
56
+ const refreshed = await refreshEnabledSession(requestedTimeout, deviceSerial, deps);
57
+ if (refreshed && hooks.isEnabled() && generation === started) {
58
+ if (!isStreamConnected())
59
+ connectStream();
60
+ hooks.applyEnableOutcome(refreshed);
61
+ device.ensureLogCapture?.();
62
+ hooks.log("[radar] _radar_session_enable path=fast");
63
+ return refreshed;
64
+ }
65
+ }
66
+ // A fallback keeps the session window while a disabled session starts at five minutes.
67
+ // Read after the ping so a disable logs the fresh setup it runs.
68
+ const wasEnabled = hooks.isEnabled();
69
+ const timeout = requestedTimeout ?? (wasEnabled ? device.getTimeoutMinutes() : 5);
70
+ hooks.log(`[radar] _radar_session_enable path=${wasEnabled ? "fallback" : "full"}`);
71
+ generation++;
72
+ inFlight++;
73
+ try {
74
+ // The flag goes true up front so the backfill's pulls pass the session gate.
75
+ hooks.setEnabled(true);
76
+ hooks.clearStreamRejected();
77
+ // Full setup clears sources, while a repeat refreshes them from the ping body.
78
+ hooks.clearSources();
79
+ const outcome = await runSessionEnable(timeout, deviceSerial, deps);
80
+ hooks.setEnabled(outcome.enabled);
81
+ hooks.applyEnableOutcome(outcome);
82
+ return outcome;
83
+ }
84
+ finally {
85
+ inFlight--;
86
+ }
87
+ }
88
+ catch (error) {
89
+ // A rejecting await must not leave the gate open on a half-torn session.
90
+ hooks.setEnabled(false);
91
+ hooks.clearSources();
92
+ destroyStream();
93
+ return {
94
+ enabled: false,
95
+ body: {
96
+ error: `Enable failed unexpectedly: ${error.message}`,
97
+ enabled: false,
98
+ platform: device.platform,
99
+ },
100
+ };
101
+ }
102
+ },
103
+ };
104
+ }
105
+ export async function refreshEnabledSession(timeoutMinutes, deviceSerial, deps) {
106
+ const { device } = deps;
107
+ if (!device.supportsRadarHttpTools && device.supportsHostLogs)
108
+ return null;
109
+ if (device.sendsRadarToken && device.getActiveUserId?.() == null)
110
+ return null;
111
+ // A healthy ping does not prove the last broadcast landed; the full flow re-sends it.
112
+ if (device.getLastActivateError?.())
113
+ return null;
114
+ if (timeoutMinutes !== null && timeoutMinutes !== device.getTimeoutMinutes())
115
+ return null;
116
+ if (deviceSerial !== null && device.getSelectedDevice?.()?.serial !== deviceSerial)
117
+ return null;
118
+ const selection = device.resolveDevice?.(deviceSerial);
119
+ if (selection && (!selection.ok || selection.switched))
120
+ return null;
121
+ if (deps.wasStreamRejected())
122
+ return null;
123
+ clearRadarTokenCache();
124
+ const before = device.getSelectedDevice?.()?.serial;
125
+ if (deps.forwardForRead?.() === false)
126
+ return null;
127
+ if (device.getSelectedDevice?.()?.serial !== before)
128
+ return null;
129
+ let status;
130
+ try {
131
+ status = await identifiedPing(device, deps.ping);
132
+ }
133
+ catch {
134
+ return null;
135
+ }
136
+ if (!isArmed(status))
137
+ return null;
138
+ if (status.token_required === false && device.sendsRadarToken)
139
+ return null;
140
+ const activeUserId = device.getActiveUserId?.();
141
+ if (status.android_user_id != null && activeUserId != null && String(status.android_user_id) !== String(activeUserId))
142
+ return null;
143
+ // The caller starts the capture after confirming the session is still current.
144
+ return {
145
+ enabled: true,
146
+ body: {
147
+ enabled: true,
148
+ already_enabled: true,
149
+ platform: device.platform,
150
+ stream_connected: deps.isStreamConnected(),
151
+ ...selectedDeviceFields(device),
152
+ timeout_minutes: device.getTimeoutMinutes(),
153
+ ...status,
154
+ },
155
+ };
156
+ }
16
157
  export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
17
- const { device, destroyStream, connectStream, isStreamConnected, resetDbState, startSpool, runBackfill, ping, sleep, onDeviceSwitch, } = deps;
158
+ const outcome = await enableSession(timeoutMinutes, deviceSerial, deps);
159
+ // activate() starts a transport-owned log capture before the app is verified. An enable that
160
+ // ends disabled must not leave that child running, or leave its lines for the next enable.
161
+ if (!outcome.enabled)
162
+ deps.device.stopLogCapture?.();
163
+ return outcome;
164
+ }
165
+ async function enableSession(timeoutMinutes, deviceSerial, deps) {
166
+ const { device, destroyStream, connectStream, isStreamConnected, wasStreamRejected, resetDbState, startSpool, runBackfill, ping, sleep, onDeviceSwitch, } = deps;
18
167
  // Tear down the old stream (and its reconnect loop) FIRST, then drop all cached
19
168
  // transport state so this enable starts clean. Without the reset, a stale adb
20
169
  // forward (device end dead after an idle timeout or a replug) makes ensureForward()
@@ -49,6 +198,7 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
49
198
  if (selection && selection.ok && selection.switched) {
50
199
  onDeviceSwitch();
51
200
  }
201
+ clearRadarTokenCache();
52
202
  if (!device.ensureForward()) {
53
203
  const reason = device.getLastForwardError?.() ?? null;
54
204
  return {
@@ -60,8 +210,80 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
60
210
  },
61
211
  };
62
212
  }
63
- device.activate(timeoutMinutes);
213
+ // Simulator Radar is already reachable on the Mac's loopback; verify its identity before
214
+ // starting backfill or SSE so an Android adb forward occupying the same port is never consumed.
215
+ if (device.acceptsRadarPeer) {
216
+ let status = null;
217
+ try {
218
+ status = await ping();
219
+ }
220
+ catch (error) {
221
+ // Nothing answered (ECONNREFUSED, a timeout). Say so in the platform's terms instead of
222
+ // handing back the raw socket error.
223
+ const reason = error instanceof Error ? error.message : String(error);
224
+ return {
225
+ enabled: false,
226
+ body: {
227
+ error: `No Radar listener answered for the ${device.platform} app (${reason}).` +
228
+ (device.radarListenerHint ? ` ${device.radarListenerHint}` : ""),
229
+ enabled: false,
230
+ platform: device.platform,
231
+ },
232
+ };
233
+ }
234
+ if (!device.acceptsRadarPeer(status)) {
235
+ return {
236
+ enabled: false,
237
+ body: {
238
+ error: `The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`,
239
+ enabled: false,
240
+ platform: device.platform,
241
+ },
242
+ };
243
+ }
244
+ }
245
+ if (device.activateAsync) {
246
+ await device.activateAsync(timeoutMinutes);
247
+ }
248
+ else {
249
+ device.activate(timeoutMinutes);
250
+ }
251
+ const tokenFileError = device.getLastActivateTokenFileError?.() ?? null;
252
+ if (tokenFileError) {
253
+ return {
254
+ enabled: false,
255
+ body: { error: tokenFileMessage(tokenFileError, "mcp"), enabled: false, platform: device.platform },
256
+ };
257
+ }
64
258
  const activateError = device.getLastActivateError?.() ?? null;
259
+ // A host-log-only transport has a real session boundary without an app-side Radar HTTP
260
+ // listener. Selecting the device and starting its capture are sufficient; probing the
261
+ // host-global Radar port here would either reject a healthy session or, worse, accept an
262
+ // unrelated listener. Keep the HTTP/spool/backfill path below exclusive to transports that
263
+ // explicitly advertise it. No shipped transport takes this branch today (Android and the iOS
264
+ // Simulator both serve Radar HTTP); it is the contract for one that only has host logs.
265
+ if (!device.supportsRadarHttpTools && device.supportsHostLogs) {
266
+ if (activateError) {
267
+ return {
268
+ enabled: false,
269
+ body: {
270
+ error: `Log capture activation failed: ${activateError}`,
271
+ enabled: false,
272
+ platform: device.platform,
273
+ },
274
+ };
275
+ }
276
+ return {
277
+ enabled: true,
278
+ body: {
279
+ enabled: true,
280
+ platform: device.platform,
281
+ stream_connected: false,
282
+ log_capture: "host",
283
+ ...selectedDeviceFields(device),
284
+ },
285
+ };
286
+ }
65
287
  if (activateError) {
66
288
  // The broadcast failed at the adb level. The device server may STILL be alive
67
289
  // (armed by a prior session, or the broadcast timed out on a loaded device
@@ -69,13 +291,17 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
69
291
  // error, and a dead one gets a real error instead of the old silent
70
292
  // enabled:true + failing tools.
71
293
  try {
72
- await ping();
294
+ await verifiedPing(device, ping);
73
295
  }
74
- catch {
296
+ catch (error) {
75
297
  return {
76
298
  enabled: false,
77
299
  body: {
78
- error: `Radar activation broadcast failed: ${activateError}. Is the device connected? Check adb devices.`,
300
+ error: error instanceof PingRefused
301
+ ? `Radar activation broadcast failed: ${activateError}. ${unauthorizedMessageFor(device)}`
302
+ : device.radarListenerHint
303
+ ? `Radar activation failed: ${activateError}. ${device.radarListenerHint}`
304
+ : `Radar activation broadcast failed: ${activateError}. Is the device connected? Check adb devices.`,
79
305
  enabled: false,
80
306
  platform: device.platform,
81
307
  },
@@ -87,27 +313,41 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
87
313
  // fetch, which opens the stream on its first call), so the trailing
88
314
  // connectStream() is usually a no-op. Correctness does not rely on connect
89
315
  // ordering: the (source, id) have-set and the read-time collapse fold any
90
- // frame both paths write into one.
316
+ // frame both paths write into one. Skipped while the device refused the stream:
317
+ // connecting clears that latch, and the check after the pings needs it.
91
318
  startSpool();
92
319
  await runBackfill();
93
- connectStream();
320
+ if (!wasStreamRejected())
321
+ connectStream();
94
322
  // Verify the device server actually came up. A broadcast can land nowhere and
95
323
  // still exit 0 (no receiver: radar modules missing from the build, or a
96
324
  // wrong-profile target). Retry to absorb real startup latency before
97
325
  // declaring it dead.
98
326
  let status = null;
99
- for (const waitMs of PING_WAITS_MS) {
327
+ let saw401 = false;
328
+ for (const waitMs of ENABLE_PING_WAITS_MS) {
100
329
  await sleep(waitMs);
101
330
  try {
102
- status = await ping();
331
+ status = await verifiedPing(device, ping);
103
332
  break;
104
333
  }
105
- catch {
106
- // Retry until the waits are exhausted.
334
+ catch (error) {
335
+ if (error instanceof PingRefused)
336
+ saw401 = true;
107
337
  }
108
338
  }
109
339
  if (status === null) {
110
340
  destroyStream();
341
+ if (saw401) {
342
+ return {
343
+ enabled: false,
344
+ body: {
345
+ error: unauthorizedMessageFor(device),
346
+ enabled: false,
347
+ platform: device.platform,
348
+ },
349
+ };
350
+ }
111
351
  // Checked fresh, not from a cache, but only here, seconds after the broadcast: backfill,
112
352
  // stream connect, and three ping retries have already run. A confirmed "stopped" does not
113
353
  // prove the app was never launched. It is equally consistent with the app receiving the
@@ -124,16 +364,24 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
124
364
  },
125
365
  };
126
366
  }
127
- const selected = device.getSelectedDevice?.() ?? null;
367
+ // A late pass means the 401 tore the first stream down, or the device refused
368
+ // the backfill's stream and the connect above was skipped. Either way the rings
369
+ // hold what the spool missed.
370
+ if (saw401 || wasStreamRejected()) {
371
+ connectStream();
372
+ await runBackfill();
373
+ }
374
+ else if (!isStreamConnected())
375
+ connectStream();
376
+ // A tokened enable that stays open did not take, so name its broadcast failure.
377
+ const openModeWarning = openModeWarningAfterEnable(status.token_required, activateError);
128
378
  return {
129
379
  enabled: true,
130
380
  body: {
131
381
  enabled: true,
132
382
  platform: device.platform,
133
383
  stream_connected: isStreamConnected(),
134
- ...(selected
135
- ? { device_serial: selected.serial, device_label: selected.label }
136
- : {}),
384
+ ...selectedDeviceFields(device),
137
385
  // The broadcast failed but the server answered (armed by a prior session).
138
386
  // activate()'s success branch never ran, so the logcat capture is not
139
387
  // armed: get_recent_logs degrades to the device ring for this session.
@@ -144,6 +392,7 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
144
392
  }
145
393
  : {}),
146
394
  ...status,
395
+ ...(openModeWarning ? { warning: openModeWarning } : {}),
147
396
  },
148
397
  };
149
398
  }