@slack/radar-mcp 1.10.0 → 1.12.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/dist/mcp/tools.js CHANGED
@@ -25,6 +25,8 @@ export const SERVER_INSTRUCTIONS = [
25
25
  '- "did I get X" / "did X happen" -> search(query="X") across ALL buffers, not just one',
26
26
  '- "everything since I enabled" / "the whole session" / "what did I miss" -> query_session',
27
27
  '- "check the debug logs" -> get_recent_logs (tag is OPTIONAL: pass tag="FKDebug" to filter, or omit it for all recent lines)',
28
+ '- "what feature-flag overrides are set?" / "check debug_features" -> search_prefs(query="X") or get_prefs(file="debug_features_...xml"). This shows MANUAL OVERRIDES only, not effective flag state: debug_features_*.xml holds only flags the debug menu overrode, and an override is deleted once it matches the server value. A flag missing from this file can still be ON server-side -- absence means "no override," never "disabled."',
29
+ '- "what did the app remember" / "what is cached in prefs" / "what team_prefs are set" -> list_prefs then get_prefs',
28
30
  '- "save this" / "file this as a bug" / "share this" / "bundle this" / "attach to ticket" / "give me a repro" / "snapshot this" / "preserve this" / "hold this state" / "save what you just saw" -> capture_snapshot',
29
31
  "",
30
32
  "Key behaviors:",
@@ -38,10 +40,17 @@ export const SERVER_INSTRUCTIONS = [
38
40
  " build can run on more than one user (personal=0, plus a work profile or secondary user),",
39
41
  " and only the first to bind the socket wins. If events seem to come from the wrong app, tell",
40
42
  " the user which profile is bound and use list_profiles + activate_for_user to switch.",
43
+ "- MULTIPLE DEVICES: with more than one device attached, enable fails and returns the list of",
44
+ " attached serials. Retry _radar_session_enable with device_serial set to one of them. When the",
45
+ " intent is unclear (you cannot tell which device the user means), ask which device before retrying;",
46
+ " do not guess. The enable success response names the bound device via device_label, so confirm it",
47
+ " matches what the user expected. The picked device applies to every tool for the whole session. Do",
48
+ " not confuse this with profiles: profiles are separate users on ONE device (personal vs work), while",
49
+ " devices are separate hardware.",
41
50
  "- Screenshots default to 720px. Use full_res=true only when detail matters.",
42
51
  "- Setup: /slack-radar-setup",
43
52
  "- Manual enable (no skill): adb shell am broadcast -a slack.debug.ENABLE_RADAR --ei timeout_minutes 5 -p com.Slack.internal.debug",
44
- " Then: adb forward tcp:8099 localabstract:slack-radar",
53
+ " Then: adb forward tcp:8099 localabstract:slack-radar (prefix adb -s <serial> when multiple devices are attached)",
45
54
  "",
46
55
  "WEB DASHBOARD (/radar-ui):",
47
56
  "A browser-based dashboard (http://localhost:8100) shows the same live device data as",
@@ -119,7 +128,7 @@ export const SERVER_INSTRUCTIONS = [
119
128
  export const TOOL_DEFINITIONS = [
120
129
  {
121
130
  name: "ping",
122
- description: "Check if Slack Radar is running. Returns uptime, buffer sizes, remaining session time, stream status, and which app/profile is bound: android_user_id (0 = personal, non-zero = a secondary user such as a work profile), profile ('personal'/'secondary'), and package.",
131
+ description: "Check if Slack Radar is running. Returns uptime, buffer sizes, remaining session time, stream status, the Radar MCP tool version (mcp_version), and which app/profile is bound: android_user_id (0 = personal, non-zero = a secondary user such as a work profile), profile ('personal'/'secondary'), and package.",
123
132
  inputSchema: {
124
133
  type: "object",
125
134
  properties: {
@@ -361,6 +370,10 @@ export const TOOL_DEFINITIONS = [
361
370
  type: "object",
362
371
  properties: {
363
372
  timeout_minutes: { type: "number", description: "Device-side auto-shutdown timeout in minutes (default: 5)" },
373
+ device_serial: {
374
+ type: "string",
375
+ description: "Target device serial from adb devices. Optional; auto-selected when exactly one device is attached. When multiple devices are attached the enable fails with the list; retry with one of the listed serials.",
376
+ },
364
377
  },
365
378
  },
366
379
  annotations: { readOnlyHint: false, idempotentHint: true },
@@ -504,6 +517,56 @@ export const TOOL_DEFINITIONS = [
504
517
  },
505
518
  annotations: { readOnlyHint: true },
506
519
  },
520
+ {
521
+ name: "list_prefs",
522
+ description: "List the app's SharedPreferences XML files (including feature-flag files like debug_features_*.xml, which holds manual overrides, and easy_features_*.xml, the persisted server snapshot), with file sizes and the Android user they were read from.",
523
+ inputSchema: {
524
+ type: "object",
525
+ properties: {
526
+ user: {
527
+ type: "string",
528
+ pattern: "^[0-9]*$",
529
+ description: "Android user ID to read (0=personal, 10+=work profile). If omitted, uses the first available user.",
530
+ },
531
+ },
532
+ },
533
+ annotations: { readOnlyHint: true },
534
+ },
535
+ {
536
+ name: "get_prefs",
537
+ description: "Read a SharedPreferences file, parse it, and return its entries (key, type, value). When keys are provided, filter to those keys only (exact match). Reads the on-disk XML, which can lag the app's live in-memory state by the async-write window, so a value may be slightly stale. debug_features_* holds manual overrides only -- a flag absent there means no override was set, not that the flag is off. easy_features_*/feature_flags_* is the persisted server snapshot, not an override list -- a hit there is the server's value, still subject to the same write-lag caveat.",
538
+ inputSchema: {
539
+ type: "object",
540
+ properties: {
541
+ file: { type: "string", description: "Filename from list_prefs, e.g. 'default_preferences.xml'" },
542
+ user: {
543
+ type: "string",
544
+ pattern: "^[0-9]*$",
545
+ description: "Android user ID (0=personal, 10+=work profile). If omitted, uses the first available user.",
546
+ },
547
+ keys: { type: "array", items: { type: "string" }, description: "If provided, filter results to only these keys (exact match). Omit to return all entries." },
548
+ },
549
+ required: ["file"],
550
+ },
551
+ annotations: { readOnlyHint: true },
552
+ },
553
+ {
554
+ name: "search_prefs",
555
+ description: "Search SharedPreferences across all files for a user. Performs case-insensitive substring search on key names and stringified values. Returns per-file match results. Reads the on-disk XML, which can lag the app's live in-memory state by the async-write window, so a value may be slightly stale. A hit in debug_features_* is a manual override -- no hit means no override, not that the flag is off. A hit in easy_features_*/feature_flags_* is the server's persisted value, not an override.",
556
+ inputSchema: {
557
+ type: "object",
558
+ properties: {
559
+ query: { type: "string", description: "Search substring (case-insensitive)" },
560
+ user: {
561
+ type: "string",
562
+ pattern: "^[0-9]*$",
563
+ description: "Android user ID (0=personal, 10+=work profile). If omitted, uses the first available user.",
564
+ },
565
+ },
566
+ required: ["query"],
567
+ },
568
+ annotations: { readOnlyHint: true },
569
+ },
507
570
  ];
508
571
  /**
509
572
  * Check whether a tool call should be blocked by the session gate.
@@ -1,4 +1,4 @@
1
- import type { DeviceTransport, LogResult } from "./transport.js";
1
+ import type { DeviceInfo, DeviceTransport, LogResult } from "./transport.js";
2
2
  /**
3
3
  * Resolve the adb binary. MCP servers spawned from GUI launchers (Spotlight,
4
4
  * Raycast, Dock) do not inherit the user's shell PATH, so a bare `adb` call
@@ -18,6 +18,19 @@ export declare function resolveAdbPath(): string | null;
18
18
  * "10", which is often a work profile, but the id alone cannot prove that).
19
19
  */
20
20
  export declare function parseUserFromPsOutput(psOutput: string): string;
21
+ /**
22
+ * Parse `adb devices -l` output into a list of attached devices. Skips the
23
+ * "List of devices attached" header and the daemon-restart preamble adb sometimes
24
+ * prints ("* daemon not running; starting now at tcp:5037", "* daemon started
25
+ * successfully"). Each real entry is "<serial> <state> [key:value ...]"; the label
26
+ * comes from the model: field with underscores turned to spaces (adb renders spaces
27
+ * in model names as underscores), falling back to the serial when no model is present.
28
+ */
29
+ export declare function parseAdbDevicesOutput(raw: string): {
30
+ serial: string;
31
+ label: string;
32
+ state: string;
33
+ }[];
21
34
  export declare class AndroidTransport implements DeviceTransport {
22
35
  readonly platform = "android";
23
36
  private portForwarded;
@@ -25,10 +38,16 @@ export declare class AndroidTransport implements DeviceTransport {
25
38
  private currentTimeoutMinutes;
26
39
  private radarEnabled;
27
40
  private lastForwardError;
41
+ private lastActivateError;
42
+ private selectedDevice;
28
43
  ensureForward(): boolean;
44
+ private rebuildForward;
45
+ reassertForward(): boolean;
29
46
  getLastForwardError(): string | null;
30
47
  activate(timeoutMinutes: number): void;
48
+ getLastActivateError(): string | null;
31
49
  resetState(): void;
50
+ dropForward(): void;
32
51
  isForwarded(): boolean;
33
52
  getTimeoutMinutes(): number;
34
53
  getActiveUserId(): string | null;
@@ -50,5 +69,21 @@ export declare class AndroidTransport implements DeviceTransport {
50
69
  label: string;
51
70
  }[];
52
71
  activateForUser(userId: string, timeoutMinutes: number): void;
72
+ listDevices(): DeviceInfo[] | null;
73
+ private reconcileSelectedDevice;
74
+ selectDevice(serial: string | null): {
75
+ ok: true;
76
+ serial: string | null;
77
+ switched?: boolean;
78
+ } | {
79
+ ok: false;
80
+ error: string;
81
+ devices: DeviceInfo[];
82
+ };
83
+ getSelectedDevice(): {
84
+ serial: string;
85
+ label: string;
86
+ } | null;
87
+ private pin;
53
88
  private detectDebugBuildUser;
54
89
  }
@@ -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, RADAR_VERSION } from "./constants.js";
8
8
  const SOCKET_NAME = "slack-radar";
9
9
  const ENABLE_ACTION = "slack.debug.ENABLE_RADAR";
10
10
  /**
@@ -83,6 +83,44 @@ export function parseUserFromPsOutput(psOutput) {
83
83
  const secondaryUser = userIds.find((id) => id !== "0");
84
84
  return secondaryUser ?? userIds[0];
85
85
  }
86
+ /**
87
+ * Parse `adb devices -l` output into a list of attached devices. Skips the
88
+ * "List of devices attached" header and the daemon-restart preamble adb sometimes
89
+ * prints ("* daemon not running; starting now at tcp:5037", "* daemon started
90
+ * successfully"). Each real entry is "<serial> <state> [key:value ...]"; the label
91
+ * comes from the model: field with underscores turned to spaces (adb renders spaces
92
+ * in model names as underscores), falling back to the serial when no model is present.
93
+ */
94
+ export function parseAdbDevicesOutput(raw) {
95
+ if (!raw || !raw.trim())
96
+ return [];
97
+ const devices = [];
98
+ for (const line of raw.split("\n")) {
99
+ const trimmed = line.trim();
100
+ if (!trimmed)
101
+ continue;
102
+ // Header and daemon-restart preamble lines are not device entries.
103
+ if (trimmed.startsWith("List of devices attached"))
104
+ continue;
105
+ if (trimmed.startsWith("*"))
106
+ continue;
107
+ const parts = trimmed.split(/\s+/);
108
+ // A real entry is at least "<serial> <state>".
109
+ if (parts.length < 2)
110
+ continue;
111
+ const serial = parts[0];
112
+ const state = parts[1];
113
+ let label = serial;
114
+ for (const field of parts.slice(2)) {
115
+ if (field.startsWith("model:")) {
116
+ label = field.slice("model:".length).replace(/_/g, " ");
117
+ break;
118
+ }
119
+ }
120
+ devices.push({ serial, label, state });
121
+ }
122
+ return devices;
123
+ }
86
124
  export class AndroidTransport {
87
125
  platform = "android";
88
126
  portForwarded = false;
@@ -90,14 +128,36 @@ export class AndroidTransport {
90
128
  currentTimeoutMinutes = 5;
91
129
  radarEnabled = false;
92
130
  lastForwardError = null;
131
+ lastActivateError = null;
132
+ // The device pinned by selectDevice, surfaced via getSelectedDevice for the enable
133
+ // body and web /health. Not cleared by resetState: the env pin is sticky by design.
134
+ selectedDevice = null;
93
135
  ensureForward() {
94
136
  if (this.portForwarded)
95
137
  return true;
138
+ return this.rebuildForward();
139
+ }
140
+ // Re-issue `adb forward` for RADAR_PORT unconditionally, ignoring the portForwarded
141
+ // cache. Shared by ensureForward's cache-miss path and reassertForward, which must
142
+ // never trust the cache (see reassertForward's doc comment on shared-transport.ts).
143
+ rebuildForward() {
96
144
  if (!ADB) {
97
145
  this.lastForwardError =
98
146
  "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
147
  return false;
100
148
  }
149
+ // Drop any existing mapping first. Re-issuing `adb forward` over a stale mapping
150
+ // (one whose device end died, e.g. after a device disconnect, OR one a separate
151
+ // process on this host repointed to a different device) has been observed to leave
152
+ // the dead/wrong mapping in place; remove-then-add reliably revives/repoints it. The
153
+ // remove fails harmlessly when no mapping exists. process.env.ANDROID_SERIAL (set by
154
+ // pin()) targets both calls at OUR device, not whichever adb would pick by default.
155
+ try {
156
+ execSync(`${ADB} forward --remove tcp:${RADAR_PORT}`, { timeout: 5000 });
157
+ }
158
+ catch {
159
+ // No existing mapping, or adb hiccup; the add below surfaces real failures.
160
+ }
101
161
  try {
102
162
  execSync(`${ADB} forward tcp:${RADAR_PORT} localabstract:${SOCKET_NAME}`, {
103
163
  timeout: 5000,
@@ -111,36 +171,82 @@ export class AndroidTransport {
111
171
  return false;
112
172
  }
113
173
  }
174
+ // Called before every HTTP-based device read (see transport.ts's doc comment for why:
175
+ // this process's own portForwarded cache cannot detect a repoint made by a SEPARATE
176
+ // process sharing the host-global port). A full forward --remove + add on every read
177
+ // would add adb round-trip latency to the common case (one MCP session, no repoint),
178
+ // so this checks the cheap, already-authoritative source first -- `adb forward --list`
179
+ // -- and only pays for a rebuild when the live mapping does not already point our
180
+ // RADAR_PORT at our pinned serial.
181
+ reassertForward() {
182
+ const serial = process.env.ANDROID_SERIAL;
183
+ if (serial && ADB) {
184
+ try {
185
+ const list = execSync(`${ADB} forward --list`, {
186
+ timeout: 5000,
187
+ encoding: "utf-8",
188
+ });
189
+ const wanted = `${serial} tcp:${RADAR_PORT} localabstract:${SOCKET_NAME}`;
190
+ if (list.split("\n").some((line) => line.trim() === wanted)) {
191
+ this.portForwarded = true;
192
+ this.lastForwardError = null;
193
+ return true;
194
+ }
195
+ }
196
+ catch {
197
+ // Listing failed; fall through to the unconditional rebuild below, which
198
+ // surfaces a concrete error if adb itself is unreachable.
199
+ }
200
+ }
201
+ return this.rebuildForward();
202
+ }
114
203
  getLastForwardError() {
115
204
  return this.lastForwardError;
116
205
  }
117
206
  activate(timeoutMinutes) {
118
- if (!ADB)
207
+ if (!ADB) {
208
+ this.lastActivateError = "adb binary not found";
119
209
  return;
210
+ }
120
211
  const timeout = timeoutMinutes || this.currentTimeoutMinutes;
121
212
  if (this.radarEnabled && timeout === this.currentTimeoutMinutes)
122
213
  return;
123
214
  try {
124
215
  const userId = this.detectDebugBuildUser();
125
- execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout}`, { timeout: 5000 });
216
+ execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout} --es mcp_version ${RADAR_VERSION}`, { timeout: 5000 });
126
217
  this.currentTimeoutMinutes = timeout;
127
218
  this.radarEnabled = true;
219
+ this.lastActivateError = null;
128
220
  // Start streaming logcat to a session-scoped file so reads are not
129
221
  // subject to the device ring buffer rotating under load.
130
222
  registerCleanup();
131
223
  startCapture(ADB);
132
224
  }
133
- catch {
134
- // Broadcast failed — device may not be connected
225
+ catch (e) {
226
+ // Broadcast failed, device may not be connected. Recorded so the enable
227
+ // path can report it instead of claiming success with a failing ping.
228
+ // radarEnabled drops too: a prior success no longer proves the device
229
+ // side is armed, and leaving it true would make every later activate()
230
+ // early-return and never re-send the broadcast.
231
+ this.radarEnabled = false;
232
+ this.lastActivateError = e.message;
135
233
  }
136
234
  }
235
+ getLastActivateError() {
236
+ return this.lastActivateError;
237
+ }
137
238
  resetState() {
138
239
  this.portForwarded = false;
139
240
  this.detectedUserId = null;
140
241
  this.radarEnabled = false;
141
242
  this.lastForwardError = null;
243
+ this.lastActivateError = null;
142
244
  // Capture has its own idle timer; not stopped on activation reset (see logcat-capture.ts).
143
245
  }
246
+ dropForward() {
247
+ this.portForwarded = false;
248
+ this.lastForwardError = null;
249
+ }
144
250
  isForwarded() {
145
251
  return this.portForwarded;
146
252
  }
@@ -272,8 +378,11 @@ export class AndroidTransport {
272
378
  if (!ADB)
273
379
  throw new Error("adb not found on PATH or common SDK locations");
274
380
  const timeout = timeoutMinutes || this.currentTimeoutMinutes;
275
- const profileChanged = this.detectedUserId !== null && this.detectedUserId !== userId;
276
- execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout}`, { timeout: 5000 });
381
+ // Unknown prior user (null) counts as changed: the running capture may be
382
+ // scoped to a profile we could not detect, and appending this profile's
383
+ // run to it would mix profiles in one file. Rotating is the safe default.
384
+ const profileChanged = this.detectedUserId !== userId;
385
+ execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout} --es mcp_version ${RADAR_VERSION}`, { timeout: 5000 });
277
386
  this.detectedUserId = userId;
278
387
  this.currentTimeoutMinutes = timeout;
279
388
  this.radarEnabled = true;
@@ -285,20 +394,145 @@ export class AndroidTransport {
285
394
  registerCleanup();
286
395
  startCapture(ADB);
287
396
  }
397
+ // Every listing is also the cheapest place to notice a pinned device disconnecting
398
+ // WITHOUT an explicit re-enable (PR #94 review, stse): selectedDevice previously only
399
+ // cleared inside selectDevice() itself, so a passive poll (the web dashboard's device
400
+ // picker, /health) kept naming a device that had already unplugged until the next
401
+ // enable happened. Every listing call site (this session's own selectDevice() AND the
402
+ // dashboard's /_control/devices poll) now gets the correction for free, without an
403
+ // extra round trip and without waiting on an enable that may never come.
404
+ listDevices() {
405
+ if (!ADB)
406
+ return [];
407
+ try {
408
+ const raw = execSync(`${ADB} devices -l`, {
409
+ timeout: 5000,
410
+ encoding: "utf-8",
411
+ });
412
+ // Empty output parses to [] — a valid "no devices attached" success, distinct
413
+ // from the null below which means the listing itself failed.
414
+ const devices = parseAdbDevicesOutput(raw);
415
+ this.reconcileSelectedDevice(devices);
416
+ return devices;
417
+ }
418
+ catch {
419
+ // adb hiccup or no server: the listing failed, so we cannot tell what is
420
+ // attached. Leave selectedDevice as-is -- a failed listing is not evidence the
421
+ // pinned device is gone, just that we could not check right now.
422
+ return null;
423
+ }
424
+ }
425
+ // Drop the recorded selection if its serial is no longer in the attached list, so
426
+ // getSelectedDevice() (read by /health and the dashboard header) never claims a
427
+ // device that has disconnected. Deliberately does NOT touch process.env.ANDROID_SERIAL
428
+ // here: selectDevice()'s own sticky-pin branch (case b) still needs to see the stale
429
+ // env var to decide whether to auto-fall-through to a single remaining device, and that
430
+ // decision belongs to selectDevice, not to every passive listing call.
431
+ reconcileSelectedDevice(devices) {
432
+ if (!this.selectedDevice)
433
+ return;
434
+ const stillAttached = devices.some((d) => d.serial === this.selectedDevice.serial && d.state === "device");
435
+ if (!stillAttached)
436
+ this.selectedDevice = null;
437
+ }
438
+ selectDevice(serial) {
439
+ const devices = this.listDevices();
440
+ if (devices === null) {
441
+ return {
442
+ ok: false,
443
+ error: "Could not list devices (adb devices failed). Check adb and retry.",
444
+ devices: [],
445
+ };
446
+ }
447
+ const attached = devices.filter((d) => d.state === "device");
448
+ const listAttached = () => attached.map((d) => `${d.serial} (${d.label})`).join(", ");
449
+ // The device this session was bound to before this call. A switch (prior set and
450
+ // the new pin differs) tells the orchestrator to reset device-scoped session state.
451
+ // `|| null` (not `??`) on the env var: an externally exported but EMPTY
452
+ // ANDROID_SERIAL must read the same as unset, or the first-ever selectDevice call
453
+ // on such a host would compute prior = "" and wrongly report switched:true (empty
454
+ // string is falsy-not-nullish, so ?? alone would let "" leak through as a real prior).
455
+ const prior = this.selectedDevice?.serial ?? (process.env.ANDROID_SERIAL || null);
456
+ const switchedTo = (pinned) => prior !== null && prior !== pinned;
457
+ // (a) Explicit serial: honor it only when that device is actually attached.
458
+ if (serial) {
459
+ const match = attached.find((d) => d.serial === serial);
460
+ if (match) {
461
+ this.pin(match.serial, match.label);
462
+ return { ok: true, serial: match.serial, switched: switchedTo(match.serial) };
463
+ }
464
+ const list = attached.length > 0 ? listAttached() : "none";
465
+ return {
466
+ ok: false,
467
+ error: `Device ${serial} is not attached (or not authorized). Attached: ${list}`,
468
+ devices,
469
+ };
470
+ }
471
+ // (b) Sticky pin: keep a previously pinned serial when it is still attached, else
472
+ // drop the stale env var and fall through to a fresh auto-pick.
473
+ const pinned = process.env.ANDROID_SERIAL;
474
+ if (pinned) {
475
+ const stillAttached = attached.find((d) => d.serial === pinned);
476
+ if (stillAttached) {
477
+ this.pin(stillAttached.serial, stillAttached.label);
478
+ return { ok: true, serial: stillAttached.serial, switched: switchedTo(stillAttached.serial) };
479
+ }
480
+ // The pinned device detached. Drop the stale env pin AND the recorded selection so
481
+ // /health does not keep claiming a device that is gone.
482
+ delete process.env.ANDROID_SERIAL;
483
+ this.selectedDevice = null;
484
+ }
485
+ // (c) Exactly one attached device: auto-pin it.
486
+ if (attached.length === 1) {
487
+ this.pin(attached[0].serial, attached[0].label);
488
+ return { ok: true, serial: attached[0].serial, switched: switchedTo(attached[0].serial) };
489
+ }
490
+ // (d) Zero devices (or a fake adb that does not answer `devices -l`): no-op. The
491
+ // existing ensureForward failure path reports no-device cleanly, and returning
492
+ // ok/null keeps every flow that fakes adb without a listing green.
493
+ if (attached.length === 0) {
494
+ // Nothing attached: clear any recorded selection so /health reports no device.
495
+ this.selectedDevice = null;
496
+ return { ok: true, serial: null };
497
+ }
498
+ // (e) 2+ attached devices with no explicit choice: ambiguous. The transport error stays a
499
+ // neutral, surface-agnostic core; each caller (MCP, web) appends its own retry guidance.
500
+ return {
501
+ ok: false,
502
+ error: `Multiple devices attached; specify which one. Attached: ${listAttached()}.`,
503
+ devices,
504
+ };
505
+ }
506
+ getSelectedDevice() {
507
+ return this.selectedDevice;
508
+ }
509
+ // Pin the process-wide ANDROID_SERIAL so every later adb call site (execSync/execFileSync,
510
+ // ~30 of them) targets this device without per-call plumbing, and record it for
511
+ // getSelectedDevice. adb devices ignores ANDROID_SERIAL, so listing stays global.
512
+ pin(serial, label) {
513
+ process.env.ANDROID_SERIAL = serial;
514
+ this.selectedDevice = { serial, label };
515
+ }
288
516
  detectDebugBuildUser() {
289
517
  if (this.detectedUserId !== null)
290
518
  return this.detectedUserId;
291
- if (!ADB) {
292
- this.detectedUserId = "0";
293
- return this.detectedUserId;
294
- }
519
+ if (!ADB)
520
+ return "0";
295
521
  try {
296
522
  const ps = execSync(`${ADB} shell "ps -A -o USER,NAME 2>/dev/null | grep Slack | grep debug"`, { timeout: 5000, encoding: "utf-8" }).trim();
523
+ // Cache only when a debug-build process was actually seen. Caching the "0"
524
+ // fallback would pin every later enable to user 0 for the process lifetime,
525
+ // so a work-profile build (user 10) launched after a failed detect would
526
+ // never receive the enable broadcast.
527
+ const match = ps.match(/u(\d+)_/);
528
+ if (!match)
529
+ return "0";
297
530
  this.detectedUserId = parseUserFromPsOutput(ps);
531
+ return this.detectedUserId;
298
532
  }
299
533
  catch {
300
- this.detectedUserId = "0";
534
+ // grep exits non-zero when Slack is not running; do not cache the fallback.
535
+ return "0";
301
536
  }
302
- return this.detectedUserId;
303
537
  }
304
538
  }
@@ -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. */
@@ -47,3 +54,11 @@ export declare const SLACK_DEBUG_PKG = "com.Slack.internal.debug";
47
54
  * the session-query byte cap share one ceiling and cannot drift.
48
55
  */
49
56
  export declare const MAX_RADAR_RESPONSE_BYTES: number;
57
+ /**
58
+ * Response budget for get_prefs, separate from MAX_RADAR_RESPONSE_BYTES: a prefs file capped
59
+ * at 256KB on-device already fits well under the 1MB general ceiling, but a smaller, dedicated
60
+ * budget keeps a single get_prefs call from being the one response that eats most of a model's
61
+ * context window on a chatty multi-tool turn. Defined here, not locally in prefs-tools.ts, so
62
+ * any future second caller of this cap shares it rather than risking drift.
63
+ */
64
+ export declare const MAX_PREFS_RESPONSE_BYTES: number;
@@ -9,14 +9,25 @@ import { createRequire } from "module";
9
9
  export const RADAR_VERSION = (() => {
10
10
  try {
11
11
  const require = createRequire(import.meta.url);
12
- return require("../../package.json").version ?? "unknown";
12
+ const raw = require("../../package.json").version ?? "unknown";
13
+ // Restrict to semver-safe characters. The value is interpolated into an
14
+ // `adb shell am broadcast` string (android.ts), so a hand-edited version in
15
+ // a linked checkout must not be able to carry shell metacharacters.
16
+ return raw.replace(/[^0-9A-Za-z.+-]/g, "") || "unknown";
13
17
  }
14
18
  catch {
15
19
  return "unknown";
16
20
  }
17
21
  })();
18
- /** Port used to reach the on-device radar HTTP server via forwarding. */
19
- export const RADAR_PORT = 8099;
22
+ /**
23
+ * Port used to reach the on-device radar HTTP server via forwarding. Shared
24
+ * by the HTTP clients (stream, radarRequest) AND the adb forward target in
25
+ * android.ts so the two cannot point at different ports. The env override
26
+ * exists for tests only: stream lifecycle tests stand up a local server on an
27
+ * ephemeral port so they cannot collide with a real forwarded device on 8099.
28
+ * Set before module load, like SLACK_RADAR_WEB_PORT.
29
+ */
30
+ export const RADAR_PORT = Number(process.env.SLACK_RADAR_DEVICE_PORT) || 8099;
20
31
  /** Host address for the forwarded connection. */
21
32
  export const RADAR_HOST = "127.0.0.1";
22
33
  /** Max events to retain in each local SSE buffer. */
@@ -56,3 +67,11 @@ export const SLACK_DEBUG_PKG = "com.Slack.internal.debug";
56
67
  * the session-query byte cap share one ceiling and cannot drift.
57
68
  */
58
69
  export const MAX_RADAR_RESPONSE_BYTES = 1024 * 1024;
70
+ /**
71
+ * Response budget for get_prefs, separate from MAX_RADAR_RESPONSE_BYTES: a prefs file capped
72
+ * at 256KB on-device already fits well under the 1MB general ceiling, but a smaller, dedicated
73
+ * budget keeps a single get_prefs call from being the one response that eats most of a model's
74
+ * context window on a chatty multi-tool turn. Defined here, not locally in prefs-tools.ts, so
75
+ * any future second caller of this cap shares it rather than risking drift.
76
+ */
77
+ export const MAX_PREFS_RESPONSE_BYTES = 64 * 1024;
@@ -27,6 +27,20 @@ export declare function availableUsers(): string[];
27
27
  * query can never silently disagree on which profile's store they touch.
28
28
  */
29
29
  export declare function resetDbState(): void;
30
+ /**
31
+ * Local copy path, scoped by Android user AND device serial. A work + personal profile
32
+ * can each hold a databases/<same-name> with DIFFERENT contents; without the user in the
33
+ * path, pulling one would overwrite the other's copy and queries would read the wrong
34
+ * profile's store. Likewise, two attached DEVICES can each have their own user-0
35
+ * databases/<same-name> with different contents (multi-device support, PR #94) -- without
36
+ * the serial too, switching devices would serve device A's plaintext store under a
37
+ * device-B session, correctness resting entirely on cleanupPulledDatabases() firing on
38
+ * every switch rather than being structurally impossible. process.env.ANDROID_SERIAL is
39
+ * the same pin every adb call site in this file already targets (see pin() in android.ts);
40
+ * "single" covers a single-device host with no pin set, matching the existing "single"
41
+ * fallback for an unset user.
42
+ */
43
+ export declare function localPath(name: string, user: string): string;
30
44
  /**
31
45
  * List the on-device databases for the given Android user (the dashboard's bound
32
46
  * profile). Filters out WAL/SHM/journal sidecar files. Returns the resolved user and
package/dist/shared/db.js CHANGED
@@ -186,14 +186,25 @@ function assertSafeName(name) {
186
186
  }
187
187
  }
188
188
  /**
189
- * Local copy path, scoped by Android user. A work + personal profile can each hold a
190
- * databases/<same-name> with DIFFERENT contents; without the user in the path, pulling
191
- * one would overwrite the other's copy and queries would read the wrong profile's store.
189
+ * Local copy path, scoped by Android user AND device serial. A work + personal profile
190
+ * can each hold a databases/<same-name> with DIFFERENT contents; without the user in the
191
+ * path, pulling one would overwrite the other's copy and queries would read the wrong
192
+ * profile's store. Likewise, two attached DEVICES can each have their own user-0
193
+ * databases/<same-name> with different contents (multi-device support, PR #94) -- without
194
+ * the serial too, switching devices would serve device A's plaintext store under a
195
+ * device-B session, correctness resting entirely on cleanupPulledDatabases() firing on
196
+ * every switch rather than being structurally impossible. process.env.ANDROID_SERIAL is
197
+ * the same pin every adb call site in this file already targets (see pin() in android.ts);
198
+ * "single" covers a single-device host with no pin set, matching the existing "single"
199
+ * fallback for an unset user.
192
200
  */
193
- function localPath(name, user) {
201
+ // Exported for testability only (mirrors assertReadOnlyQuery/isExplainQuery below);
202
+ // callers within this file use it directly.
203
+ export function localPath(name, user) {
194
204
  const safeName = name.replace(/[^A-Za-z0-9._-]/g, "_");
195
205
  const safeUser = (user || "single").replace(/[^A-Za-z0-9._-]/g, "_");
196
- return path.join(DB_TMP, `u${safeUser}-${safeName}.sqlite`);
206
+ const safeSerial = (process.env.ANDROID_SERIAL || "single").replace(/[^A-Za-z0-9._-]/g, "_");
207
+ return path.join(DB_TMP, `d${safeSerial}-u${safeUser}-${safeName}.sqlite`);
197
208
  }
198
209
  /**
199
210
  * Resolve the Android user to target. The dashboard passes the profile it is bound to