@slack/radar-mcp 1.9.1 → 1.11.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.
package/README.md CHANGED
@@ -40,10 +40,11 @@ slack-radar
40
40
 
41
41
  Opens `http://localhost:8100` automatically. Set `SLACK_RADAR_WEB_PORT` to use a different port. (`slack-radar-web` still works as a direct alias.) Tabs:
42
42
 
43
- * **Live** — network, RTM, analytics clogs, and Slack-app logcat in one timeline
43
+ * **Live** — network, RTM, analytics clogs, traces, and Slack-app logcat in one timeline
44
44
  * **Network** — calls per second vs response time, every call listed, slow ones flagged
45
45
  * **RTM** — real-time websocket events
46
46
  * **Clogs** — analytics events, click one to see its payload
47
+ * **Traces** — performance trace spans with durations, click one for its timing and tags
47
48
  * **Logs** — device logcat, filtered to the Slack app (switch app or clear the filter)
48
49
  * **Database** — read-only browser for the on-device SQLite stores (pick a database, then a table, or run a read-only query). See the data-handling note below.
49
50
  * **Custom** — a tab Claude builds on request. Ask a Claude Code session in your terminal for a view the pre-built tabs do not cover (e.g. "graph calls per second and flag the slow ones"); it authors the view via the `open_radar_dashboard` tool and it appears here. Persists until you refresh the page.
@@ -140,10 +141,10 @@ What gets captured depends on the in-app server implementation. The MCP server i
140
141
  * **Network calls**: OkHttp interceptor. Ring buffer: 400 calls.
141
142
  * **RTM events**: WebSocket listener. Ring buffer: 2000 events.
142
143
  * **Clogs**: Analytics interceptor. Ring buffer: 1000 events. Persists across radar activation cycles.
143
- * **Traces**: Performance span observer. Ring buffer: 1000 spans. Persists across radar activation cycles.
144
+ * **Traces**: Performance span observer. Ring buffer: 2000 spans. Persists across radar activation cycles.
144
145
  * **SQLite database** (Database tab, web dashboard only): when you open a database, a read-only **plaintext** copy of that on-device store (message text, request/response bodies, user/channel/team IDs) is pulled to a temp directory **on your own machine** (`os.tmpdir()/slack-radar-db-<port>`, files mode 0600). Auto-deleted when the dashboard process stops.
145
146
 
146
- The network, RTM, and clog captures are in-memory ring buffers. The Database tab is the exception: it writes a plaintext copy of the selected on-device database to a temp file on your host for the duration of the session. Review before sharing anything from it.
147
+ The network, RTM, clog, and trace captures are in-memory ring buffers. The Database tab is the exception: it writes a plaintext copy of the selected on-device database to a temp file on your host for the duration of the session. Review before sharing anything from it.
147
148
 
148
149
  ### What gets captured, in detail
149
150
 
package/dist/mcp/index.js CHANGED
@@ -16,6 +16,7 @@ import { buildBufferPath, createSnapshot } from "./snapshot.js";
16
16
  import { clampLogLimit, shapeLogsResult } from "./logs-result.js";
17
17
  import { querySession, clampByteCap, toNum } from "./session-query.js";
18
18
  import { resolveDetailById } from "./session-detail.js";
19
+ import { runSessionEnable } from "./session-enable.js";
19
20
  import { backfillSpool, BACKFILL_SOURCES, makeSerializedRunner, } from "./session-backfill.js";
20
21
  import { handleListDatabases, handleListTables, handleQueryDatabase, } from "./db-tools.js";
21
22
  import { cleanupPulledDatabases, initializeDatabasePath, resetDbState, } from "../shared/db.js";
@@ -276,7 +277,7 @@ async function runMcpServer() {
276
277
  // a truncation marker rather than a partial JSON blob the parser would choke on. Bulk exports go
277
278
  // through capture_snapshot, not this path. The ceiling now lives in constants so the device path
278
279
  // and the session-query byte cap share one value.
279
- function radarRequest(requestPath) {
280
+ function radarRequest(requestPath, timeoutMs = 10000) {
280
281
  return new Promise((resolve, reject) => {
281
282
  // settled-guard: req.destroy() on the cap path fires "error" (ECONNRESET) AFTER we have
282
283
  // already resolved the truncation, so every settle goes through these wrappers and the
@@ -298,7 +299,7 @@ async function runMcpServer() {
298
299
  host: RADAR_HOST,
299
300
  port: RADAR_PORT,
300
301
  path: requestPath,
301
- timeout: 10000,
302
+ timeout: timeoutMs,
302
303
  }, (res) => {
303
304
  let data = "";
304
305
  let bytes = 0;
@@ -376,55 +377,42 @@ async function runMcpServer() {
376
377
  // --- Tool handlers ---
377
378
  async function handleSessionEnable(args) {
378
379
  const timeout = args?.timeout_minutes || 5;
379
- sessionEnabled = true;
380
- // A re-enable may be a different device or a re-armed profile, so drop the cached DB
381
- // user set + sqlite path; the next DB tool call re-detects the profiles fresh. Mirrors
382
- // the web server's handleEnable (server.ts), which resets for the same reason.
383
- resetDbState();
384
- const forwarded = device.ensureForward();
385
- if (!forwarded) {
386
- sessionEnabled = false;
387
- const reason = device.getLastForwardError?.() ?? null;
388
- return textResult({
389
- error: reason ??
390
- "Port forwarding failed. Ensure a device is connected.",
391
- enabled: false,
392
- platform: device.platform,
393
- }, true);
394
- }
395
- device.activate(timeout);
396
- // Open the session event spool, then backfill the device rings into it. Note the live SSE push can
397
- // start DURING the backfill: the backfill pulls the ring lists via callRadar, which opens the
398
- // stream on its first fetch, so the trailing connectStream() below is usually a no-op (it only
399
- // opens the stream when the backfill wrote nothing and never called callRadar, e.g. empty rings).
400
- // Correctness does NOT rely on connect ordering. It relies on two things: the (source, id) have-set
401
- // that skips a row already in the spool, and the unconditional read-time collapse (every read folds
402
- // a duplicated id to one frame), so a frame the live push and the backfill both write surfaces once.
403
- // Serialized so it cannot overlap a reconnect backfill. Never throws; a device blip just skips it.
404
- startSpool();
405
- await runBackfillSerialized();
406
- connectStream();
407
- // Open the session event spool so every streamed frame is captured to a host
408
- // file for the life of this enabled session.
409
- startSpool();
410
- await new Promise((r) => setTimeout(r, 500));
380
+ // The orchestration lives in session-enable.ts (testable without the stdio
381
+ // server this module starts at load); this handler wires the real effects
382
+ // and owns the session flag. sessionEnabled goes true up front so the
383
+ // backfill's device pulls pass the session gate, then follows the outcome.
384
+ // The catch covers a future refactor introducing a rejecting await: without
385
+ // it the gate would stay open (sessionEnabled true) on a half-torn session
386
+ // while the SDK reports an opaque error.
411
387
  try {
412
- const status = await radarRequest("/api/ping");
413
- return textResult({
414
- enabled: true,
415
- platform: device.platform,
416
- stream_connected: isStreamConnected(),
417
- ...status,
388
+ sessionEnabled = true;
389
+ const outcome = await runSessionEnable(timeout, {
390
+ device,
391
+ destroyStream,
392
+ connectStream,
393
+ isStreamConnected,
394
+ resetDbState,
395
+ startSpool,
396
+ runBackfill: runBackfillSerialized,
397
+ // A health ping does not need the default 10s: a half-alive server
398
+ // (accepts TCP, never answers) would otherwise stretch the verify loop
399
+ // past the MCP client's 60s tool-call timeout, and the crafted error
400
+ // would never reach the user. 2s keeps worst-case enable wall time far
401
+ // under that ceiling.
402
+ ping: () => radarRequest("/api/ping", 2000),
403
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
418
404
  });
405
+ sessionEnabled = outcome.enabled;
406
+ return textResult(outcome.body, !outcome.enabled);
419
407
  }
420
- catch {
408
+ catch (e) {
409
+ sessionEnabled = false;
410
+ destroyStream();
421
411
  return textResult({
422
- enabled: true,
412
+ error: `Enable failed unexpectedly: ${e.message}`,
413
+ enabled: false,
423
414
  platform: device.platform,
424
- stream_connected: isStreamConnected(),
425
- ping: "failed",
426
- note: "Radar activated but ping failed. Device may need a moment.",
427
- });
415
+ }, true);
428
416
  }
429
417
  }
430
418
  function handleSessionDisable() {
@@ -668,7 +656,7 @@ async function runMcpServer() {
668
656
  }
669
657
  }
670
658
  // --- MCP Server ---
671
- const server = new Server({ name: "slack-radar", version: "1.9.1" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
659
+ const server = new Server({ name: "slack-radar", version: "1.11.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
672
660
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
673
661
  tools: TOOL_DEFINITIONS,
674
662
  }));
@@ -0,0 +1,17 @@
1
+ import type { DeviceTransport } from "../shared/transport.js";
2
+ export interface EnableDeps {
3
+ device: DeviceTransport;
4
+ destroyStream: () => void;
5
+ connectStream: () => void;
6
+ isStreamConnected: () => boolean;
7
+ resetDbState: () => void;
8
+ startSpool: () => void;
9
+ runBackfill: () => Promise<unknown>;
10
+ ping: () => Promise<Record<string, unknown>>;
11
+ sleep: (ms: number) => Promise<void>;
12
+ }
13
+ export interface EnableOutcome {
14
+ body: Record<string, unknown>;
15
+ enabled: boolean;
16
+ }
17
+ export declare function runSessionEnable(timeoutMinutes: number, deps: EnableDeps): Promise<EnableOutcome>;
@@ -0,0 +1,104 @@
1
+ // Ping-verify cadence: first probe fast (a healthy server answers immediately;
2
+ // this is the whole latency of a normal enable), then two patient retries to
3
+ // absorb real server startup.
4
+ const PING_WAITS_MS = [500, 1000, 1000];
5
+ export async function runSessionEnable(timeoutMinutes, deps) {
6
+ const { device, destroyStream, connectStream, isStreamConnected, resetDbState, startSpool, runBackfill, ping, sleep, } = deps;
7
+ // Tear down the old stream (and its reconnect loop) FIRST, then drop all cached
8
+ // transport state so this enable starts clean. Without the reset, a stale adb
9
+ // forward (device end dead after an idle timeout or a replug) makes ensureForward()
10
+ // a cached no-op, and a user id cached from an earlier detect can pin the enable
11
+ // broadcast to the wrong profile. The web server's handleEnable (server.ts) has
12
+ // always reset for the same reason; the MCP path was missing it.
13
+ destroyStream();
14
+ device.resetState();
15
+ // A re-enable may be a different device or a re-armed profile, so drop the cached DB
16
+ // user set + sqlite path; the next DB tool call re-detects the profiles fresh.
17
+ resetDbState();
18
+ if (!device.ensureForward()) {
19
+ const reason = device.getLastForwardError?.() ?? null;
20
+ return {
21
+ enabled: false,
22
+ body: {
23
+ error: reason ?? "Port forwarding failed. Ensure a device is connected.",
24
+ enabled: false,
25
+ platform: device.platform,
26
+ },
27
+ };
28
+ }
29
+ device.activate(timeoutMinutes);
30
+ const activateError = device.getLastActivateError?.() ?? null;
31
+ if (activateError) {
32
+ // The broadcast failed at the adb level. The device server may STILL be alive
33
+ // (armed by a prior session, or the broadcast timed out on a loaded device
34
+ // after landing), so probe before failing: a working server beats a pedantic
35
+ // error, and a dead one gets a real error instead of the old silent
36
+ // enabled:true + failing tools.
37
+ try {
38
+ await ping();
39
+ }
40
+ catch {
41
+ return {
42
+ enabled: false,
43
+ body: {
44
+ error: `Radar activation broadcast failed: ${activateError}. Is the device connected? Check adb devices.`,
45
+ enabled: false,
46
+ platform: device.platform,
47
+ },
48
+ };
49
+ }
50
+ }
51
+ // Open the session event spool, then backfill the device rings into it. The live
52
+ // SSE push can start DURING the backfill (the backfill pulls via the injected
53
+ // fetch, which opens the stream on its first call), so the trailing
54
+ // connectStream() is usually a no-op. Correctness does not rely on connect
55
+ // ordering: the (source, id) have-set and the read-time collapse fold any
56
+ // frame both paths write into one.
57
+ startSpool();
58
+ await runBackfill();
59
+ connectStream();
60
+ // Verify the device server actually came up. A broadcast can land nowhere and
61
+ // still exit 0 (no receiver: radar modules missing from the build, or a
62
+ // wrong-profile target). Retry to absorb real startup latency before
63
+ // declaring it dead.
64
+ let status = null;
65
+ for (const waitMs of PING_WAITS_MS) {
66
+ await sleep(waitMs);
67
+ try {
68
+ status = await ping();
69
+ break;
70
+ }
71
+ catch {
72
+ // Retry until the waits are exhausted.
73
+ }
74
+ }
75
+ if (status === null) {
76
+ destroyStream();
77
+ return {
78
+ enabled: false,
79
+ body: {
80
+ error: "Radar broadcast sent but the device server did not respond. Is a debug build with the slack-radar modules installed and running on the active profile?",
81
+ enabled: false,
82
+ platform: device.platform,
83
+ },
84
+ };
85
+ }
86
+ return {
87
+ enabled: true,
88
+ body: {
89
+ enabled: true,
90
+ platform: device.platform,
91
+ stream_connected: isStreamConnected(),
92
+ // The broadcast failed but the server answered (armed by a prior session).
93
+ // activate()'s success branch never ran, so the logcat capture is not
94
+ // armed: get_recent_logs degrades to the device ring for this session.
95
+ // Named so the degradation is visible instead of silent.
96
+ ...(activateError
97
+ ? {
98
+ logcat_capture: "not started (activation broadcast failed; logs fall back to the device ring)",
99
+ }
100
+ : {}),
101
+ ...status,
102
+ },
103
+ };
104
+ }
@@ -161,8 +161,16 @@ function matchesFilter(frame, f) {
161
161
  return false;
162
162
  if (f.channel !== undefined && e.channel !== f.channel)
163
163
  return false;
164
- if (f.name !== undefined && !includesCI(e.name, f.name))
165
- return false;
164
+ // "name" spans the per-source name fields: clogs carry event_name, traces carry
165
+ // trace_name/span_name; no source emits a literal `name` field. A hit on any counts.
166
+ if (f.name !== undefined) {
167
+ const nameHit = includesCI(e.name, f.name) ||
168
+ includesCI(e.event_name, f.name) ||
169
+ includesCI(e.trace_name, f.name) ||
170
+ includesCI(e.span_name, f.name);
171
+ if (!nameHit)
172
+ return false;
173
+ }
166
174
  // `text` searches the whole serialized frame, so it catches content in any field including the
167
175
  // clog detail payload, not just the named summary fields above.
168
176
  if (f.text !== undefined && !JSON.stringify(frame).toLowerCase().includes(f.text.toLowerCase())) {
package/dist/mcp/tools.js CHANGED
@@ -45,7 +45,7 @@ export const SERVER_INSTRUCTIONS = [
45
45
  "",
46
46
  "WEB DASHBOARD (/radar-ui):",
47
47
  "A browser-based dashboard (http://localhost:8100) shows the same live device data as",
48
- "tabs: Live (everything), Network, RTM, Clogs, and Logs, each with counters, a graph, a",
48
+ "tabs: Live (everything), Network, RTM, Clogs, Traces, and Logs, each with counters, a graph, a",
49
49
  "filterable feed, and a payload inspector. Launched via the /radar-ui skill, which runs",
50
50
  "`npx @slack/radar-mcp web` (a global install also exposes it as `slack-radar`).",
51
51
  "",
@@ -75,7 +75,7 @@ export const SERVER_INSTRUCTIONS = [
75
75
  "screen.installHint, so you can check before suggesting.",
76
76
  "",
77
77
  "CUSTOM DASHBOARD (open_radar_dashboard):",
78
- "The pre-built tabs (Live/Network/RTM/Clogs/Logs) cover the common cases. When the user",
78
+ "The pre-built tabs (Live/Network/RTM/Clogs/Traces/Logs) cover the common cases. When the user",
79
79
  "describes a live view the tabs do not show, SUGGEST building it; invoke open_radar_dashboard",
80
80
  "only after they agree or explicitly ask for a custom view/dashboard (same discipline as",
81
81
  "/radar-ui). To build, translate their words into a spec and call the tool; it renders your",
@@ -86,9 +86,10 @@ export const SERVER_INSTRUCTIONS = [
86
86
  '- "show only RTM events on channel C... and let me click each for its payload"',
87
87
  '- "watch network calls whose body contains <substring>"',
88
88
  "Authoring rules:",
89
- "- source is one of network/rtm/clog/log/all ('all' = one unified timeline).",
89
+ "- source is one of network/rtm/clog/trace/log/all ('all' = one unified timeline).",
90
90
  "- match filters on SUMMARY fields only, by source: network=url/method/status_code,",
91
- " rtm=event_type/direction/channel, clog=event_name, log=tag/level/message/pid/package.",
91
+ " rtm=event_type/direction/channel, clog=event_name, trace=trace_name/span_name,",
92
+ " log=tag/level/message/pid/package.",
92
93
  " NEVER invent a field; a match on a field the stream does not carry silently matches",
93
94
  " nothing. To filter on body text use bodyContains (network/all only), which fetches detail.",
94
95
  "- viz composes counter/rate/sparkline/feed/inspector/graph. graph needs a series array",
@@ -373,7 +374,7 @@ export const TOOL_DEFINITIONS = [
373
374
  {
374
375
  name: "open_radar_dashboard",
375
376
  description: "Build or refine a custom live dashboard tab in the Slack Radar web UI from a spec YOU author. " +
376
- "Suggest this when the user describes a live view the pre-built tabs (Live/Network/RTM/Clogs/Logs) do not cover " +
377
+ "Suggest this when the user describes a live view the pre-built tabs (Live/Network/RTM/Clogs/Traces/Logs) do not cover " +
377
378
  "(e.g. 'graph calls per second vs response time and flag slow ones', 'beep when I get a DM'); invoke it once they agree. " +
378
379
  "Translate the request into the spec fields below and call this tool; it ensures the web dashboard is " +
379
380
  "running (default http://localhost:8100) and renders your spec as a 'Custom' tab, then returns the URL to share. " +
@@ -390,12 +391,12 @@ export const TOOL_DEFINITIONS = [
390
391
  source: {
391
392
  type: "string",
392
393
  enum: [...SOURCES],
393
- description: "Which device stream to read. 'all' is a unified timeline mixing network, RTM, and clog.",
394
+ description: "Which device stream to read. 'all' is a unified timeline mixing network, RTM, clog, trace, and log.",
394
395
  },
395
396
  match: {
396
397
  type: "object",
397
398
  description: "Case-insensitive substring filter on SUMMARY fields, keyed by source. network: url/method/status_code; " +
398
- "rtm: event_type/direction/channel; clog: event_name; log: tag/level/package. NEVER invent a field " +
399
+ "rtm: event_type/direction/channel; clog: event_name; trace: trace_name/span_name; log: tag/level/package. NEVER invent a field " +
399
400
  "(a match on an absent field silently matches nothing). For body text use bodyContains instead.",
400
401
  },
401
402
  bodyContains: {
@@ -25,10 +25,13 @@ export declare class AndroidTransport implements DeviceTransport {
25
25
  private currentTimeoutMinutes;
26
26
  private radarEnabled;
27
27
  private lastForwardError;
28
+ private lastActivateError;
28
29
  ensureForward(): boolean;
29
30
  getLastForwardError(): string | null;
30
31
  activate(timeoutMinutes: number): void;
32
+ getLastActivateError(): string | null;
31
33
  resetState(): void;
34
+ dropForward(): void;
32
35
  isForwarded(): boolean;
33
36
  getTimeoutMinutes(): number;
34
37
  getActiveUserId(): string | null;
@@ -4,7 +4,7 @@ import os from "os";
4
4
  import path from "path";
5
5
  import { readDebugLogBuffer } from "./debug-log.js";
6
6
  import { filterLogLines, getCaptureFilePath, isCapturing, readRecentLogs, registerCleanup, rotateCaptureIfNeeded, startCapture, stopCapture, } from "./logcat-capture.js";
7
- const RADAR_PORT = 8099;
7
+ import { RADAR_PORT } from "./constants.js";
8
8
  const SOCKET_NAME = "slack-radar";
9
9
  const ENABLE_ACTION = "slack.debug.ENABLE_RADAR";
10
10
  /**
@@ -90,6 +90,7 @@ export class AndroidTransport {
90
90
  currentTimeoutMinutes = 5;
91
91
  radarEnabled = false;
92
92
  lastForwardError = null;
93
+ lastActivateError = null;
93
94
  ensureForward() {
94
95
  if (this.portForwarded)
95
96
  return true;
@@ -98,6 +99,16 @@ export class AndroidTransport {
98
99
  "adb binary not found. Set ANDROID_HOME or install Android SDK platform-tools. Searched: PATH, $ANDROID_HOME/platform-tools/adb, ~/Library/Android/sdk/platform-tools/adb, ~/Android/Sdk/platform-tools/adb, /usr/local/bin/adb, /opt/homebrew/bin/adb.";
99
100
  return false;
100
101
  }
102
+ // Drop any existing mapping first. Re-issuing `adb forward` over a stale mapping
103
+ // (one whose device end died, e.g. after a device disconnect) has been observed
104
+ // to leave the dead mapping in place; remove-then-add reliably revives it. The
105
+ // remove fails harmlessly when no mapping exists.
106
+ try {
107
+ execSync(`${ADB} forward --remove tcp:${RADAR_PORT}`, { timeout: 5000 });
108
+ }
109
+ catch {
110
+ // No existing mapping, or adb hiccup; the add below surfaces real failures.
111
+ }
101
112
  try {
102
113
  execSync(`${ADB} forward tcp:${RADAR_PORT} localabstract:${SOCKET_NAME}`, {
103
114
  timeout: 5000,
@@ -115,8 +126,10 @@ export class AndroidTransport {
115
126
  return this.lastForwardError;
116
127
  }
117
128
  activate(timeoutMinutes) {
118
- if (!ADB)
129
+ if (!ADB) {
130
+ this.lastActivateError = "adb binary not found";
119
131
  return;
132
+ }
120
133
  const timeout = timeoutMinutes || this.currentTimeoutMinutes;
121
134
  if (this.radarEnabled && timeout === this.currentTimeoutMinutes)
122
135
  return;
@@ -125,22 +138,37 @@ export class AndroidTransport {
125
138
  execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout}`, { timeout: 5000 });
126
139
  this.currentTimeoutMinutes = timeout;
127
140
  this.radarEnabled = true;
141
+ this.lastActivateError = null;
128
142
  // Start streaming logcat to a session-scoped file so reads are not
129
143
  // subject to the device ring buffer rotating under load.
130
144
  registerCleanup();
131
145
  startCapture(ADB);
132
146
  }
133
- catch {
134
- // Broadcast failed — device may not be connected
147
+ catch (e) {
148
+ // Broadcast failed, device may not be connected. Recorded so the enable
149
+ // path can report it instead of claiming success with a failing ping.
150
+ // radarEnabled drops too: a prior success no longer proves the device
151
+ // side is armed, and leaving it true would make every later activate()
152
+ // early-return and never re-send the broadcast.
153
+ this.radarEnabled = false;
154
+ this.lastActivateError = e.message;
135
155
  }
136
156
  }
157
+ getLastActivateError() {
158
+ return this.lastActivateError;
159
+ }
137
160
  resetState() {
138
161
  this.portForwarded = false;
139
162
  this.detectedUserId = null;
140
163
  this.radarEnabled = false;
141
164
  this.lastForwardError = null;
165
+ this.lastActivateError = null;
142
166
  // Capture has its own idle timer; not stopped on activation reset (see logcat-capture.ts).
143
167
  }
168
+ dropForward() {
169
+ this.portForwarded = false;
170
+ this.lastForwardError = null;
171
+ }
144
172
  isForwarded() {
145
173
  return this.portForwarded;
146
174
  }
@@ -272,7 +300,10 @@ export class AndroidTransport {
272
300
  if (!ADB)
273
301
  throw new Error("adb not found on PATH or common SDK locations");
274
302
  const timeout = timeoutMinutes || this.currentTimeoutMinutes;
275
- const profileChanged = this.detectedUserId !== null && this.detectedUserId !== userId;
303
+ // Unknown prior user (null) counts as changed: the running capture may be
304
+ // scoped to a profile we could not detect, and appending this profile's
305
+ // run to it would mix profiles in one file. Rotating is the safe default.
306
+ const profileChanged = this.detectedUserId !== userId;
276
307
  execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout}`, { timeout: 5000 });
277
308
  this.detectedUserId = userId;
278
309
  this.currentTimeoutMinutes = timeout;
@@ -288,17 +319,23 @@ export class AndroidTransport {
288
319
  detectDebugBuildUser() {
289
320
  if (this.detectedUserId !== null)
290
321
  return this.detectedUserId;
291
- if (!ADB) {
292
- this.detectedUserId = "0";
293
- return this.detectedUserId;
294
- }
322
+ if (!ADB)
323
+ return "0";
295
324
  try {
296
325
  const ps = execSync(`${ADB} shell "ps -A -o USER,NAME 2>/dev/null | grep Slack | grep debug"`, { timeout: 5000, encoding: "utf-8" }).trim();
326
+ // Cache only when a debug-build process was actually seen. Caching the "0"
327
+ // fallback would pin every later enable to user 0 for the process lifetime,
328
+ // so a work-profile build (user 10) launched after a failed detect would
329
+ // never receive the enable broadcast.
330
+ const match = ps.match(/u(\d+)_/);
331
+ if (!match)
332
+ return "0";
297
333
  this.detectedUserId = parseUserFromPsOutput(ps);
334
+ return this.detectedUserId;
298
335
  }
299
336
  catch {
300
- this.detectedUserId = "0";
337
+ // grep exits non-zero when Slack is not running; do not cache the fallback.
338
+ return "0";
301
339
  }
302
- return this.detectedUserId;
303
340
  }
304
341
  }
@@ -6,8 +6,15 @@
6
6
  * Falls back to "unknown" if package.json cannot be read (should not happen in a real install).
7
7
  */
8
8
  export declare const RADAR_VERSION: string;
9
- /** Port used to reach the on-device radar HTTP server via forwarding. */
10
- export declare const RADAR_PORT = 8099;
9
+ /**
10
+ * Port used to reach the on-device radar HTTP server via forwarding. Shared
11
+ * by the HTTP clients (stream, radarRequest) AND the adb forward target in
12
+ * android.ts so the two cannot point at different ports. The env override
13
+ * exists for tests only: stream lifecycle tests stand up a local server on an
14
+ * ephemeral port so they cannot collide with a real forwarded device on 8099.
15
+ * Set before module load, like SLACK_RADAR_WEB_PORT.
16
+ */
17
+ export declare const RADAR_PORT: number;
11
18
  /** Host address for the forwarded connection. */
12
19
  export declare const RADAR_HOST = "127.0.0.1";
13
20
  /** Max events to retain in each local SSE buffer. */
@@ -15,8 +15,15 @@ export const RADAR_VERSION = (() => {
15
15
  return "unknown";
16
16
  }
17
17
  })();
18
- /** Port used to reach the on-device radar HTTP server via forwarding. */
19
- export const RADAR_PORT = 8099;
18
+ /**
19
+ * Port used to reach the on-device radar HTTP server via forwarding. Shared
20
+ * by the HTTP clients (stream, radarRequest) AND the adb forward target in
21
+ * android.ts so the two cannot point at different ports. The env override
22
+ * exists for tests only: stream lifecycle tests stand up a local server on an
23
+ * ephemeral port so they cannot collide with a real forwarded device on 8099.
24
+ * Set before module load, like SLACK_RADAR_WEB_PORT.
25
+ */
26
+ export const RADAR_PORT = Number(process.env.SLACK_RADAR_DEVICE_PORT) || 8099;
20
27
  /** Host address for the forwarded connection. */
21
28
  export const RADAR_HOST = "127.0.0.1";
22
29
  /** Max events to retain in each local SSE buffer. */
@@ -11,6 +11,20 @@ export interface ParsedSSE {
11
11
  }
12
12
  export declare const localNetworkBuffer: RadarEvent[];
13
13
  export declare const localRtmBuffer: RadarEvent[];
14
+ /**
15
+ * Decide whether this reconnect attempt rebuilds the adb forward, perform the
16
+ * rebuild if so, and return the delay before the next connect. Does not call
17
+ * setTimeout itself so the decision is unit-testable without a live socket.
18
+ *
19
+ * Prefers dropForward() (drops only the cached forward flag) over resetState()
20
+ * so a rebuild does not wipe the detected user id mid-session: a full reset
21
+ * followed by a re-detect while the app process is down would rebind the
22
+ * session to user 0, losing a work-profile binding.
23
+ *
24
+ * @param t transport whose forward may be stale
25
+ * @param attempt 1-based failure count since the last successful connect
26
+ */
27
+ export declare function planReconnect(t: DeviceTransport, attempt: number): number;
14
28
  /** Set the reconnect hook. Called once after each successful reconnect. Pass null to clear it. */
15
29
  export declare function setOnReconnect(fn: (() => void) | null): void;
16
30
  export declare function noteStreamConnected(): void;
@@ -18,6 +32,15 @@ export declare function _resetReconnectStateForTest(): void;
18
32
  export declare function isStreamConnected(): boolean;
19
33
  export declare function clearLocalBuffers(): void;
20
34
  export declare function getStreamConnection(): http.ClientRequest | null;
35
+ /**
36
+ * Deliberate teardown: destroy the live stream AND stop the reconnect loop.
37
+ * Cancelling the pending timer matters as much as the destroy — without it a
38
+ * disable (or an enable-restart) leaves a timer that resurrects the stream
39
+ * seconds later, refilling buffers the caller just cleared and churning adb
40
+ * forward rebuilds against a session the user turned off. The destroyed
41
+ * request's own async failure events are ignored by the ownership check in
42
+ * connectStream's handlers (they no longer own streamConnection).
43
+ */
21
44
  export declare function destroyStream(): void;
22
45
  /**
23
46
  * Push an event into the appropriate local buffer, enforcing MAX_LOCAL_BUFFER.