@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
@@ -1,11 +1,13 @@
1
- import { execFile, execSync, execFileSync } from "child_process";
1
+ import { execFile, execSync, execFileSync, spawn, } from "child_process";
2
2
  import fs from "fs";
3
3
  import os from "os";
4
4
  import path from "path";
5
5
  import { promisify } from "util";
6
6
  import { readDebugLogBuffer } from "./debug-log.js";
7
7
  import { filterLogLines, getCaptureFilePath, isCapturing, readRecentLogs, registerCleanup, rotateCaptureIfNeeded, startCapture, stopCapture, } from "./logcat-capture.js";
8
- import { RADAR_PORT, RADAR_VERSION } from "./constants.js";
8
+ import { RADAR_PORT, RADAR_VERSION, SLACK_DEBUG_PKG } from "./constants.js";
9
+ import { getOrCreateRadarToken } from "./radar-token.js";
10
+ import { LogSession } from "./log-session.js";
9
11
  const SOCKET_NAME = "slack-radar";
10
12
  const ENABLE_ACTION = "slack.debug.ENABLE_RADAR";
11
13
  /**
@@ -23,6 +25,35 @@ const PS_PROBE_TIMEOUT_MS = 5000;
23
25
  const LIST_DEVICES_TIMEOUT_MS = Number(process.env.SLACK_RADAR_ADB_LIST_TIMEOUT_MS) > 0
24
26
  ? Number(process.env.SLACK_RADAR_ADB_LIST_TIMEOUT_MS)
25
27
  : 5000;
28
+ // The enable broadcast waits for ordered delivery, and a cold debug build has been observed to
29
+ // hold completion past 5 seconds, so it gets a taller ceiling than the quick adb queries.
30
+ const ENABLE_BROADCAST_TIMEOUT_MS = 15_000;
31
+ function stderrText(raw) {
32
+ // Redact before the cut so a token crossing it cannot survive.
33
+ const text = (typeof raw === "string" ? raw : Buffer.isBuffer(raw) ? raw.toString("utf8") : "")
34
+ .replace(/[0-9a-f]{64,}/g, "<redacted>");
35
+ const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
36
+ const firstLine = lines[0] ?? "";
37
+ const reason = firstLine.endsWith(":") && lines[1] ? `${firstLine} ${lines[1]}` : firstLine;
38
+ // ADB tags and trailing punctuation would repeat the caller wording.
39
+ return reason.slice(0, 200)
40
+ .replace(/^(?:adb: |error: )+/, "")
41
+ .replace(/[.!]+$/, "");
42
+ }
43
+ // Return a bare reason because every caller adds its own failure wording.
44
+ export function describeBroadcastFailure(error) {
45
+ const failure = error;
46
+ // execFile (async) marks a timeout kill with killed; execFileSync reports code ETIMEDOUT.
47
+ if (failure.killed || failure.code === "ETIMEDOUT") {
48
+ return `timed out after ${ENABLE_BROADCAST_TIMEOUT_MS / 1000}s ` +
49
+ "(the device or the debug build did not finish delivering the broadcast)";
50
+ }
51
+ const reason = stderrText(failure.stderr);
52
+ const exitCode = typeof failure.status === "number" ? failure.status : typeof failure.code === "number" ? failure.code : null;
53
+ const errno = typeof failure.code === "string" ? failure.code : null;
54
+ const head = exitCode !== null ? `adb exited ${exitCode}` : errno ? `adb failed (${errno})` : "adb failed";
55
+ return reason ? `${head}: ${reason}` : head;
56
+ }
26
57
  /**
27
58
  * Resolve the adb binary. MCP servers spawned from GUI launchers (Spotlight,
28
59
  * Raycast, Dock) do not inherit the user's shell PATH, so a bare `adb` call
@@ -76,6 +107,109 @@ export function resolveAdbPath() {
76
107
  // Module-level resolution, done once at import time. The MCP process lifetime
77
108
  // is short enough (session-scoped) that we do not need to re-resolve.
78
109
  const ADB = resolveAdbPath();
110
+ // Logcat line parsing for the dashboard's transport-owned host log session. Format:
111
+ // "MM-DD HH:MM:SS.mmm PID TID L Tag: message"
112
+ const LOG_LINE_RE = /^(\d\d-\d\d \d\d:\d\d:\d\d\.\d+)\s+(\d+)\s+(\d+)\s+([VDIWEF])\s+([^:]*?):\s?(.*)$/;
113
+ const LOG_LEVELS = {
114
+ V: "VERBOSE",
115
+ D: "DEBUG",
116
+ I: "INFO",
117
+ W: "WARN",
118
+ E: "ERROR",
119
+ F: "FATAL",
120
+ };
121
+ /**
122
+ * A device-scoped PID -> package snapshot for dashboard log rows.
123
+ *
124
+ * Android reuses PIDs, and a dashboard can switch between devices without restarting its
125
+ * process. Replacing the whole snapshot on refresh, rather than appending to a module-global
126
+ * map, prevents a PID on the new process/device from inheriting the old package label.
127
+ */
128
+ export class AndroidPidPackageMap {
129
+ spawnProcessList;
130
+ packages = new Map();
131
+ refreshVersion = 0;
132
+ activeRefresh = 0;
133
+ lastRefresh = 0;
134
+ constructor(spawnProcessList = () => {
135
+ const adb = resolveAdbPath();
136
+ return adb ? spawn(adb, ["shell", "ps", "-A", "-o", "PID,NAME"]) : null;
137
+ }) {
138
+ this.spawnProcessList = spawnProcessList;
139
+ }
140
+ resolve(pid) {
141
+ const hit = this.packages.get(pid);
142
+ if (hit !== undefined)
143
+ return hit;
144
+ // Unknown PID: a rate-limited refresh so a later line resolves. A hit never refreshes,
145
+ // so steady logs from known processes do not keep `adb shell ps` running.
146
+ if (Date.now() - this.lastRefresh > 3000)
147
+ this.refresh();
148
+ return undefined;
149
+ }
150
+ refresh() {
151
+ if (this.activeRefresh !== 0)
152
+ return;
153
+ const ps = this.spawnProcessList();
154
+ if (!ps)
155
+ return;
156
+ const version = ++this.refreshVersion;
157
+ this.activeRefresh = version;
158
+ this.lastRefresh = Date.now();
159
+ let out = "";
160
+ let failed = false;
161
+ ps.stdout?.on("data", (chunk) => (out += chunk.toString()));
162
+ ps.on("error", () => {
163
+ failed = true;
164
+ if (this.activeRefresh === version)
165
+ this.activeRefresh = 0;
166
+ });
167
+ ps.on("close", (code) => {
168
+ if (this.activeRefresh === version)
169
+ this.activeRefresh = 0;
170
+ if (failed || code !== 0 || this.refreshVersion !== version)
171
+ return;
172
+ const next = new Map();
173
+ for (const line of out.split("\n")) {
174
+ const match = line.trim().match(/^(\d+)\s+(\S+)$/);
175
+ if (match)
176
+ next.set(Number(match[1]), match[2]);
177
+ }
178
+ // A listing that parsed to nothing (a device mid-reboot, a truncated shell) says nothing
179
+ // about which PIDs exist, so it must not wipe the labels lines are still resolving against.
180
+ if (next.size > 0)
181
+ this.packages = next;
182
+ });
183
+ }
184
+ reset() {
185
+ // Invalidate an in-flight `ps` result. It may still emit close later, but its
186
+ // version can no longer replace the new device's package snapshot.
187
+ this.refreshVersion++;
188
+ this.activeRefresh = 0;
189
+ this.packages.clear();
190
+ this.lastRefresh = 0;
191
+ }
192
+ }
193
+ let dashboardLogIdSequence = 0;
194
+ /** Parse one adb logcat threadtime line into the dashboard's normalized log frame. */
195
+ export function parseAndroidLogcat(line, resolvePackage = () => undefined) {
196
+ const match = line.match(LOG_LINE_RE);
197
+ if (!match)
198
+ return null;
199
+ const [, logTimestamp, pid, tid, level, tag, message] = match;
200
+ const numericPid = Number(pid);
201
+ return {
202
+ id: ++dashboardLogIdSequence,
203
+ timestamp: Date.now(),
204
+ log_ts: logTimestamp,
205
+ pid: numericPid,
206
+ tid: Number(tid),
207
+ level: LOG_LEVELS[level] ?? level,
208
+ tag: tag.trim(),
209
+ message,
210
+ package: resolvePackage(numericPid),
211
+ };
212
+ }
79
213
  // Promisified execFile for the *Async transport methods below. argv form (no shell), so an
80
214
  // interpolated value can never break out of a command string, and stdout/stderr are captured
81
215
  // rather than inherited, matching the stdio discipline execsync-stdio.test.mjs pins.
@@ -87,8 +221,8 @@ const ADB_NOT_FOUND_FORWARD_ERROR = "adb binary not found. Set ANDROID_HOME or i
87
221
  // comment for why the `|| exit 9` and the trailing `|| true` are each load-bearing.
88
222
  const PS_DEBUG_BUILD_SCRIPT = 'out=$(ps -A -o USER,NAME) || exit 9; echo "$out" | grep Slack | grep debug || true';
89
223
  // The enable broadcast, in argv form so the sync and async activate paths send the exact
90
- // same command.
91
- function enableBroadcastArgs(userId, timeoutMinutes) {
224
+ // same command. The package target keeps other receivers from reading the token.
225
+ function enableBroadcastArgs(userId, timeoutMinutes, token) {
92
226
  return [
93
227
  "shell",
94
228
  "am",
@@ -97,12 +231,17 @@ function enableBroadcastArgs(userId, timeoutMinutes) {
97
231
  userId,
98
232
  "-a",
99
233
  ENABLE_ACTION,
234
+ "-p",
235
+ SLACK_DEBUG_PKG,
100
236
  "--ei",
101
237
  "timeout_minutes",
102
238
  String(timeoutMinutes),
103
239
  "--es",
104
240
  "mcp_version",
105
241
  RADAR_VERSION,
242
+ "--es",
243
+ "radar_token",
244
+ token,
106
245
  ];
107
246
  }
108
247
  /**
@@ -167,10 +306,22 @@ export function parseAdbDevicesOutput(raw) {
167
306
  }
168
307
  return devices;
169
308
  }
309
+ function spawnAndroidLogcat() {
310
+ const adb = resolveAdbPath();
311
+ if (!adb)
312
+ throw new Error(ADB_NOT_FOUND_FORWARD_ERROR);
313
+ return spawn(adb, ["logcat", "-v", "threadtime", "-T", "1"], {
314
+ stdio: ["ignore", "pipe", "ignore"],
315
+ });
316
+ }
170
317
  export class AndroidTransport {
171
318
  platform = "android";
319
+ logPackage = SLACK_DEBUG_PKG;
320
+ supportsHostLogs = true;
321
+ logSession;
172
322
  // The Android debug build serves Radar's HTTP API through the adb-forwarded local socket.
173
323
  supportsRadarHttpTools = true;
324
+ sendsRadarToken = true;
174
325
  // adb reaches the app's databases and shared prefs through run-as, so the DB and prefs tools
175
326
  // (which shell to adb themselves) are cleared to run.
176
327
  supportsLocalFileAccess = true;
@@ -182,9 +333,21 @@ export class AndroidTransport {
182
333
  radarEnabled = false;
183
334
  lastForwardError = null;
184
335
  lastActivateError = null;
336
+ lastActivateTokenFileError = null;
185
337
  // The device pinned by selectDevice, surfaced via getSelectedDevice for the enable
186
338
  // body and web /health. Not cleared by resetState: the env pin is sticky by design.
187
339
  selectedDevice = null;
340
+ dashboardPidPackages;
341
+ constructor(dependencies = {}) {
342
+ this.dashboardPidPackages = new AndroidPidPackageMap(dependencies.spawnProcessList);
343
+ const spawnLogcat = dependencies.spawnLogcat ?? spawnAndroidLogcat;
344
+ this.logSession = new LogSession(() => {
345
+ const child = spawnLogcat();
346
+ // Warm the PID labels only once the capture exists, so a failed spawn costs no `ps`.
347
+ this.dashboardPidPackages.refresh();
348
+ return child;
349
+ }, (line) => parseAndroidLogcat(line, (pid) => this.dashboardPidPackages.resolve(pid)));
350
+ }
188
351
  ensureForward() {
189
352
  if (this.portForwarded)
190
353
  return true;
@@ -324,12 +487,15 @@ export class AndroidTransport {
324
487
  const timeout = timeoutMinutes || this.currentTimeoutMinutes;
325
488
  if (this.radarEnabled && timeout === this.currentTimeoutMinutes)
326
489
  return;
490
+ const token = this.readArmToken();
491
+ if (token === null)
492
+ return;
327
493
  try {
328
494
  const userId = this.detectDebugBuildUser();
329
495
  // Same taller ceiling as the async twin: the broadcast waits for ordered delivery and a
330
496
  // cold debug build can hold completion past 5 seconds.
331
- execFileSync(ADB, enableBroadcastArgs(userId, timeout), {
332
- timeout: 15000,
497
+ execFileSync(ADB, enableBroadcastArgs(userId, timeout, token), {
498
+ timeout: ENABLE_BROADCAST_TIMEOUT_MS,
333
499
  stdio: ["ignore", "ignore", "pipe"],
334
500
  });
335
501
  this.recordActivateSuccess(timeout);
@@ -352,12 +518,15 @@ export class AndroidTransport {
352
518
  const timeout = timeoutMinutes || this.currentTimeoutMinutes;
353
519
  if (this.radarEnabled && timeout === this.currentTimeoutMinutes)
354
520
  return;
521
+ const token = this.readArmToken();
522
+ if (token === null)
523
+ return;
355
524
  try {
356
525
  const userId = await this.detectDebugBuildUserAsync();
357
526
  // The broadcast waits for ordered delivery, and a cold debug build has been observed to
358
527
  // hold completion past 5 seconds; a killed broadcast reads as a failed arm, so this one
359
528
  // call gets a taller ceiling than the quick adb queries.
360
- await execFileAsync(ADB, enableBroadcastArgs(userId, timeout), { timeout: 15000 });
529
+ await execFileAsync(ADB, enableBroadcastArgs(userId, timeout, token), { timeout: ENABLE_BROADCAST_TIMEOUT_MS });
361
530
  this.recordActivateSuccess(timeout);
362
531
  }
363
532
  catch (e) {
@@ -394,9 +563,8 @@ export class AndroidTransport {
394
563
  this.currentTimeoutMinutes = timeout;
395
564
  this.radarEnabled = true;
396
565
  this.lastActivateError = null;
397
- registerCleanup();
398
- if (ADB)
399
- startCapture(ADB);
566
+ this.lastActivateTokenFileError = null;
567
+ this.ensureLogCapture();
400
568
  }
401
569
  // Broadcast failed, device may not be connected. Recorded so the enable path can report
402
570
  // it instead of claiming success with a failing ping. radarEnabled drops too: a prior
@@ -404,17 +572,36 @@ export class AndroidTransport {
404
572
  // later activate() early-return and never re-send the broadcast.
405
573
  recordActivateFailure(e) {
406
574
  this.radarEnabled = false;
407
- this.lastActivateError = e.message;
575
+ this.lastActivateError = describeBroadcastFailure(e);
576
+ }
577
+ readArmToken() {
578
+ this.lastActivateTokenFileError = null;
579
+ try {
580
+ return getOrCreateRadarToken();
581
+ }
582
+ catch (error) {
583
+ this.radarEnabled = false;
584
+ this.lastActivateTokenFileError = error;
585
+ this.lastActivateError = error.message;
586
+ return null;
587
+ }
408
588
  }
409
589
  getLastActivateError() {
410
590
  return this.lastActivateError;
411
591
  }
592
+ // One capture start for activate, a profile switch and a repeat enable; startCapture skips a live child.
593
+ ensureLogCapture() { registerCleanup(); if (ADB)
594
+ startCapture(ADB); }
595
+ getLastActivateTokenFileError() {
596
+ return this.lastActivateTokenFileError;
597
+ }
412
598
  resetState() {
413
599
  this.portForwarded = false;
414
600
  this.detectedUserId = null;
415
601
  this.radarEnabled = false;
416
602
  this.lastForwardError = null;
417
603
  this.lastActivateError = null;
604
+ this.lastActivateTokenFileError = null;
418
605
  // Capture has its own idle timer; not stopped on activation reset (see logcat-capture.ts).
419
606
  }
420
607
  dropForward() {
@@ -523,16 +710,22 @@ export class AndroidTransport {
523
710
  source: "logcat_ring",
524
711
  };
525
712
  }
713
+ stopLogCapture() {
714
+ stopCapture();
715
+ this.logSession.stop();
716
+ }
526
717
  // Shares psDebugBuildProbe's `ps` call rather than repeating the pipeline: two copies
527
718
  // of the same command drifted independently once already.
528
719
  listProfiles() {
529
- const fallback = [{ userId: "0", label: "Personal (user 0)" }];
530
- const ps = this.psDebugBuildLine();
531
- if (!ps)
532
- return fallback;
720
+ const probe = this.psDebugBuildProbe();
721
+ if (probe.state !== "running") {
722
+ throw new Error(probe.state === "stopped"
723
+ ? "The Slack debug build is not running. Start it, then call list_profiles again."
724
+ : "Could not check for the Slack debug build. Connect exactly one device and make sure adb is installed, then call list_profiles again.");
725
+ }
533
726
  const seen = new Set();
534
727
  const profiles = [];
535
- for (const line of ps.split("\n")) {
728
+ for (const line of probe.lines.split("\n")) {
536
729
  const match = line.match(/u(\d+)_/);
537
730
  if (match && !seen.has(match[1])) {
538
731
  seen.add(match[1]);
@@ -543,7 +736,7 @@ export class AndroidTransport {
543
736
  });
544
737
  }
545
738
  }
546
- return profiles.length > 0 ? profiles : fallback;
739
+ return profiles.length > 0 ? profiles : [{ userId: "0", label: "Personal (user 0)" }];
547
740
  }
548
741
  activateForUser(userId, timeoutMinutes) {
549
742
  if (!ADB)
@@ -553,22 +746,30 @@ export class AndroidTransport {
553
746
  // scoped to a profile we could not detect, and appending this profile's
554
747
  // run to it would mix profiles in one file. Rotating is the safe default.
555
748
  const profileChanged = this.detectedUserId !== userId;
749
+ this.lastActivateTokenFileError = null;
750
+ const token = getOrCreateRadarToken();
556
751
  // The same argv and the same tall ceiling as activate's twins: the broadcast waits for
557
752
  // ordered delivery and a cold debug build can hold completion past 5 seconds.
558
- execFileSync(ADB, enableBroadcastArgs(userId, timeout), {
559
- timeout: 15000,
560
- stdio: ["ignore", "ignore", "pipe"],
561
- });
753
+ try {
754
+ execFileSync(ADB, enableBroadcastArgs(userId, timeout, token), {
755
+ timeout: ENABLE_BROADCAST_TIMEOUT_MS,
756
+ stdio: ["ignore", "ignore", "pipe"],
757
+ });
758
+ }
759
+ catch (error) {
760
+ throw new Error(describeBroadcastFailure(error));
761
+ }
562
762
  this.detectedUserId = userId;
563
763
  this.currentTimeoutMinutes = timeout;
564
764
  this.radarEnabled = true;
765
+ // This broadcast landed, so the enable error it replaces is stale.
766
+ this.lastActivateError = null;
565
767
  // Profile switch means the interesting scope changed; drop the old
566
768
  // capture so the new session starts from a fresh file scoped to this
567
769
  // profile's debug run.
568
770
  if (profileChanged)
569
771
  stopCapture();
570
- registerCleanup();
571
- startCapture(ADB);
772
+ this.ensureLogCapture();
572
773
  }
573
774
  // Every listing is also the cheapest place to notice a pinned device disconnecting
574
775
  // WITHOUT an explicit re-enable (PR #94 review, stse): selectedDevice previously only
@@ -627,8 +828,10 @@ export class AndroidTransport {
627
828
  if (!this.selectedDevice)
628
829
  return;
629
830
  const stillAttached = devices.some((d) => d.serial === this.selectedDevice.serial && d.state === "device");
630
- if (!stillAttached)
831
+ if (!stillAttached) {
631
832
  this.selectedDevice = null;
833
+ this.dashboardPidPackages.reset();
834
+ }
632
835
  }
633
836
  selectDevice(serial) {
634
837
  return this.pickFromListing(this.listDevices(), serial, true);
@@ -737,6 +940,13 @@ export class AndroidTransport {
737
940
  // ~30 of them) targets this device without per-call plumbing, and record it for
738
941
  // getSelectedDevice. adb devices ignores ANDROID_SERIAL, so listing stays global.
739
942
  pin(serial, label) {
943
+ const prior = this.selectedDevice?.serial ?? (process.env.ANDROID_SERIAL || null);
944
+ if (prior !== null && prior !== serial) {
945
+ // Both belong to the old device: its PID labels, and a logcat child that inherited the old
946
+ // ANDROID_SERIAL and would keep reading that device. restart() also drops the old ring.
947
+ this.dashboardPidPackages.reset();
948
+ this.logSession.restart();
949
+ }
740
950
  process.env.ANDROID_SERIAL = serial;
741
951
  this.selectedDevice = { serial, label };
742
952
  }
@@ -36,6 +36,8 @@ export declare function setRadarPort(port: number): void;
36
36
  export declare const RADAR_HOST = "127.0.0.1";
37
37
  /** Max events to retain in each local SSE buffer. */
38
38
  export declare const MAX_LOCAL_BUFFER = 500;
39
+ /** Waits between device pings after an enable broadcast. */
40
+ export declare const ENABLE_PING_WAITS_MS: readonly number[];
39
41
  /**
40
42
  * Max parsed logcat frames the web dashboard retains for the whole server
41
43
  * session. The device does not buffer logcat host-side, so the dashboard keeps
@@ -44,12 +46,15 @@ export declare const MAX_LOCAL_BUFFER = 500;
44
46
  * instead of only the lines that arrive after the reconnect. Bounded so a long,
45
47
  * chatty session cannot grow without limit. logcat is captured for ALL apps (the
46
48
  * dashboard filters by package client-side), so the depth is sized for an all-app
47
- * stream: at typical line sizes this keeps the buffer well under ~10 MB (a
48
- * stack-trace-heavy session runs larger per line, so treat this as a typical, not
49
- * a hard, ceiling). Like Android Studio's logcat, retention is a bounded ring —
50
- * the oldest lines age out once the cap is reached, not kept forever.
49
+ * stream. A separate estimated-byte ceiling handles stack-trace-heavy sessions.
50
+ * Like Android Studio's logcat, retention is a bounded ring — the oldest lines
51
+ * age out once either cap is reached, not kept forever.
51
52
  */
52
53
  export declare const MAX_LOG_SESSION_BUFFER = 20000;
54
+ /** Maximum estimated serialized size of one host-captured log frame. */
55
+ export declare const MAX_LOG_FRAME_BYTES: number;
56
+ /** Maximum estimated serialized size retained by one host log session. */
57
+ export declare const MAX_LOG_SESSION_BYTES: number;
53
58
  /**
54
59
  * Default port for the web dashboard. Shared so the MCP `open_radar_dashboard`
55
60
  * tool POSTs its spec to the same port the web server listens on; both honor the
@@ -51,6 +51,8 @@ export function setRadarPort(port) {
51
51
  export const RADAR_HOST = "127.0.0.1";
52
52
  /** Max events to retain in each local SSE buffer. */
53
53
  export const MAX_LOCAL_BUFFER = 500;
54
+ /** Waits between device pings after an enable broadcast. */
55
+ export const ENABLE_PING_WAITS_MS = [500, 1000, 1000];
54
56
  /**
55
57
  * Max parsed logcat frames the web dashboard retains for the whole server
56
58
  * session. The device does not buffer logcat host-side, so the dashboard keeps
@@ -59,12 +61,15 @@ export const MAX_LOCAL_BUFFER = 500;
59
61
  * instead of only the lines that arrive after the reconnect. Bounded so a long,
60
62
  * chatty session cannot grow without limit. logcat is captured for ALL apps (the
61
63
  * dashboard filters by package client-side), so the depth is sized for an all-app
62
- * stream: at typical line sizes this keeps the buffer well under ~10 MB (a
63
- * stack-trace-heavy session runs larger per line, so treat this as a typical, not
64
- * a hard, ceiling). Like Android Studio's logcat, retention is a bounded ring —
65
- * the oldest lines age out once the cap is reached, not kept forever.
64
+ * stream. A separate estimated-byte ceiling handles stack-trace-heavy sessions.
65
+ * Like Android Studio's logcat, retention is a bounded ring — the oldest lines
66
+ * age out once either cap is reached, not kept forever.
66
67
  */
67
68
  export const MAX_LOG_SESSION_BUFFER = 20000;
69
+ /** Maximum estimated serialized size of one host-captured log frame. */
70
+ export const MAX_LOG_FRAME_BYTES = 1024 * 1024;
71
+ /** Maximum estimated serialized size retained by one host log session. */
72
+ export const MAX_LOG_SESSION_BYTES = 10 * 1024 * 1024;
68
73
  /**
69
74
  * Default port for the web dashboard. Shared so the MCP `open_radar_dashboard`
70
75
  * tool POSTs its spec to the same port the web server listens on; both honor the
@@ -2,5 +2,6 @@
2
2
  * Rewrite the device's raw "Not Found" into an actionable message. The route 404s as valid
3
3
  * JSON ({"error":"Not Found"}) on builds that predate the feature-flag Radar plugin, which is
4
4
  * correct but useless to a caller with no way to know this route is plugin-gated.
5
+ * A 401 is not read here; both callers decide it from the HTTP status before this runs.
5
6
  */
6
7
  export declare function friendlyFeatureFlagError(error: unknown): string;
@@ -6,6 +6,7 @@
6
6
  * Rewrite the device's raw "Not Found" into an actionable message. The route 404s as valid
7
7
  * JSON ({"error":"Not Found"}) on builds that predate the feature-flag Radar plugin, which is
8
8
  * correct but useless to a caller with no way to know this route is plugin-gated.
9
+ * A 401 is not read here; both callers decide it from the HTTP status before this runs.
9
10
  */
10
11
  export function friendlyFeatureFlagError(error) {
11
12
  if (typeof error !== "string")
@@ -0,0 +1,10 @@
1
+ /** iOS Simulator unified-log adapter for Radar. */
2
+ import { type ChildProcess } from "node:child_process";
3
+ import type { LogFrame } from "./log-session.js";
4
+ export declare const SLACK_IOS_PACKAGE = "com.tinyspeck.chatlyio";
5
+ export declare function iosLogLevel(value: unknown): string;
6
+ /** Parse one `log stream --style ndjson` record into Radar's normalized shape. */
7
+ export declare function parseIosUnifiedLog(line: string): LogFrame | null;
8
+ /** A readable line for get_recent_logs and snapshot-style output. */
9
+ export declare function formatIosLogFrame(frame: LogFrame): string;
10
+ export declare function spawnIosUnifiedLogStream(simulatorUdid: string): ChildProcess;
@@ -0,0 +1,91 @@
1
+ /** iOS Simulator unified-log adapter for Radar. */
2
+ import { spawn } from "node:child_process";
3
+ import path from "node:path";
4
+ const SLACK_IOS_PROCESS = "Slack";
5
+ export const SLACK_IOS_PACKAGE = "com.tinyspeck.chatlyio";
6
+ function numberField(value) {
7
+ const parsed = typeof value === "number" ? value : Number(value);
8
+ return Number.isFinite(parsed) ? parsed : 0;
9
+ }
10
+ function iosTimestamp(value) {
11
+ if (typeof value !== "string")
12
+ return null;
13
+ const match = value.match(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})\.(\d{3})\d*([+-]\d{2})(\d{2})$/);
14
+ if (!match)
15
+ return null;
16
+ const parsed = Date.parse(`${match[1]}T${match[2]}.${match[3]}${match[4]}:${match[5]}`);
17
+ return Number.isFinite(parsed) ? parsed : null;
18
+ }
19
+ export function iosLogLevel(value) {
20
+ switch (String(value ?? "").toLowerCase()) {
21
+ case "debug": return "DEBUG";
22
+ case "info": return "INFO";
23
+ case "error": return "ERROR";
24
+ case "fault": return "FATAL";
25
+ case "default": return "INFO";
26
+ default: return String(value ?? "INFO").toUpperCase() || "INFO";
27
+ }
28
+ }
29
+ /** Parse one `log stream --style ndjson` record into Radar's normalized shape. */
30
+ export function parseIosUnifiedLog(line) {
31
+ let record;
32
+ try {
33
+ record = JSON.parse(line);
34
+ }
35
+ catch {
36
+ // simctl/log can print host-account warnings before the NDJSON stream.
37
+ return null;
38
+ }
39
+ if (!record || record.eventType !== "logEvent" || typeof record.eventMessage !== "string")
40
+ return null;
41
+ const timestamp = iosTimestamp(record.timestamp);
42
+ if (timestamp === null)
43
+ return null;
44
+ const logTimestamp = record.timestamp;
45
+ const subsystem = typeof record.subsystem === "string" && record.subsystem
46
+ ? record.subsystem
47
+ : undefined;
48
+ const category = typeof record.category === "string" && record.category
49
+ ? record.category
50
+ : undefined;
51
+ const processImagePath = typeof record.processImagePath === "string"
52
+ ? record.processImagePath
53
+ : "";
54
+ const processName = typeof record.process === "string" && record.process
55
+ ? record.process
56
+ : processImagePath ? path.basename(processImagePath) : SLACK_IOS_PROCESS;
57
+ return {
58
+ id: 0,
59
+ timestamp,
60
+ package: SLACK_IOS_PACKAGE,
61
+ log_ts: logTimestamp,
62
+ pid: numberField(record.processID),
63
+ tid: numberField(record.threadID),
64
+ level: iosLogLevel(record.messageType),
65
+ tag: category ?? subsystem ?? processName,
66
+ message: record.eventMessage,
67
+ ...(subsystem ? { subsystem } : {}),
68
+ ...(processName ? { process: processName } : {}),
69
+ };
70
+ }
71
+ /** A readable line for get_recent_logs and snapshot-style output. */
72
+ export function formatIosLogFrame(frame) {
73
+ const match = frame.log_ts.match(/\b(\d{2}:\d{2}:\d{2})\.(\d{3})/);
74
+ const time = match
75
+ ? `${match[1]}.${match[2]}`
76
+ : new Date(frame.timestamp).toISOString().slice(11, 23);
77
+ return `${time} ${frame.level} ${frame.tag}: ${frame.message}`;
78
+ }
79
+ export function spawnIosUnifiedLogStream(simulatorUdid) {
80
+ return spawn("xcrun", [
81
+ "simctl", "spawn", simulatorUdid,
82
+ "log", "stream",
83
+ "--style", "ndjson",
84
+ "--level", "debug",
85
+ "--type", "log",
86
+ "--predicate", `subsystem BEGINSWITH "com.tinyspeck"`,
87
+ ],
88
+ // `log stream` is long-lived and nobody consumes diagnostics here. Leaving
89
+ // stderr piped would eventually backpressure and stall stdout on noisy runs.
90
+ { stdio: ["ignore", "pipe", "ignore"] });
91
+ }
@@ -1,10 +1,13 @@
1
- import type { DeviceInfo, DevicePick, DeviceTransport } from "./transport.js";
1
+ import { type ChildProcess } from "child_process";
2
+ import { LogSession } from "./log-session.js";
3
+ import type { LogResult, DeviceInfo, DevicePick, DeviceTransport } from "./transport.js";
2
4
  export type IosScreenshotCapturer = (simulatorUdid: string, outputPath: string) => void;
3
5
  export type IosScreenRecorder = (simulatorUdid: string, outputPath: string, durationSeconds: number) => void;
4
6
  export interface IosSimulatorTransportDependencies {
5
7
  readBootedSimulators?: () => string;
6
8
  captureScreenshot?: IosScreenshotCapturer;
7
9
  recordScreen?: IosScreenRecorder;
10
+ spawnLogStream?: (simulatorUdid: string) => ChildProcess;
8
11
  }
9
12
  /** Convert a CoreSimulator runtime identifier into the label users see in Xcode. */
10
13
  export declare function simulatorRuntimeLabel(identifier: string): string;
@@ -31,14 +34,23 @@ export declare function recordIosSimulatorScreen(simulatorUdid: string, outputPa
31
34
  /** Host-side transport for iOS Simulators. */
32
35
  export declare class IosSimulatorTransport implements DeviceTransport {
33
36
  readonly platform = "ios";
34
- readonly supportsRadarHttpTools = false;
37
+ readonly logPackage = "com.tinyspeck.chatlyio";
38
+ readonly supportsHostLogs = true;
39
+ readonly supportsRadarHttpTools = true;
40
+ readonly radarListenerHint = "Open the Slack app on the Simulator with Radar enabled, then retry.";
41
+ readonly supportsDeviceDashboard = true;
42
+ readonly logSession: LogSession;
35
43
  private forwarded;
44
+ private logIdSequence;
36
45
  private timeoutMinutes;
37
46
  private selectedDevice;
47
+ private logSimulatorUdid;
38
48
  private lastForwardError;
49
+ private lastActivateError;
39
50
  private readonly readBootedSimulators;
40
51
  private readonly captureSimulatorScreenshot;
41
52
  private readonly recordSimulatorScreen;
53
+ private readonly spawnSimulatorLogStream;
42
54
  constructor(dependencies?: IosSimulatorTransportDependencies);
43
55
  listDevices(): DeviceInfo[] | null;
44
56
  selectDevice(serial: string | null): DevicePick;
@@ -55,10 +67,21 @@ export declare class IosSimulatorTransport implements DeviceTransport {
55
67
  resetState(): void;
56
68
  dropForward(): void;
57
69
  getLastForwardError(): string | null;
70
+ private prepareActivation;
71
+ private enableRadar;
58
72
  activate(timeoutMinutes: number): void;
73
+ activateAsync(timeoutMinutes: number): Promise<void>;
74
+ getLastActivateError(): string | null;
75
+ acceptsRadarPeer(ping: Record<string, unknown>): boolean;
59
76
  getTimeoutMinutes(): number;
60
77
  getActiveUserId(): string | null;
61
78
  resolveActiveUser(): string;
79
+ getRecentLogs(tag: string, limit: number, grep?: string): LogResult;
80
+ /**
81
+ * End this session's capture and drop what it retained. get_recent_logs promises lines
82
+ * captured since the session was enabled, so a later enable must not replay these.
83
+ */
84
+ stopLogCapture(): void;
62
85
  screenshot(fullRes: boolean): string;
63
86
  recordScreen(durationS: number): string;
64
87
  private reconcileSelectedDevice;