@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.
@@ -5,8 +5,10 @@ import path from "path";
5
5
  import { spawn } from "child_process";
6
6
  import { fileURLToPath } from "url";
7
7
  import { AndroidTransport, resolveAdbPath } from "../shared/android.js";
8
+ import { planReconnect } from "../shared/stream.js";
8
9
  import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
9
- import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, } from "../shared/db.js";
10
+ import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, availableUsers, } from "../shared/db.js";
11
+ import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../shared/prefs.js";
10
12
  import { LogSession } from "./log-session.js";
11
13
  import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
12
14
  import { screenCapabilities, refreshScreenCapabilities, grantScreenConsent, hasScreenConsent, detectDisplay, displayNote, captureScreenshot, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, startRecording, stopRecording, recordingPath, resetScreenState, registerScreenCleanup, resolveFfmpeg, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
@@ -45,6 +47,14 @@ export function shouldDropLogFrame(replay, writableLength, cap = MAX_SSE_WRITABL
45
47
  const SPEC_DIR = path.join(os.homedir(), ".slack-radar");
46
48
  const SPEC_PATH = path.join(SPEC_DIR, `web-spec-${WEB_PORT}.json`);
47
49
  const transport = new AndroidTransport();
50
+ // Reassert the shared adb forward before every HTTP-based device read. Mirrors
51
+ // mcp/index.ts's forwardForRead(): this process's own portForwarded cache cannot see a
52
+ // repoint made by a SEPARATE process (the MCP server) sharing the same host-global
53
+ // forward port -- the split-brain flows both ways. Platforms without a shared
54
+ // host-level forward may omit reassertForward, so this falls back to ensureForward.
55
+ function forwardForRead() {
56
+ return transport.reassertForward?.() ?? transport.ensureForward();
57
+ }
48
58
  // One session-long logcat capture shared across every dashboard stream
49
59
  // connection. The device cannot replay logcat history to us, so the dashboard
50
60
  // keeps its own bounded session ring here and replays it to each newly opened
@@ -167,8 +177,9 @@ export function createServer() {
167
177
  handleHealth(res);
168
178
  return;
169
179
  }
170
- if (url === "/enable" && req.method === "POST") {
171
- handleEnable(res);
180
+ if (urlPath === "/enable" && req.method === "POST") {
181
+ const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
182
+ handleEnable(res, serial);
172
183
  return;
173
184
  }
174
185
  if (url === "/stream" && req.method === "GET") {
@@ -195,6 +206,18 @@ export function createServer() {
195
206
  handleDbQuery(req, res);
196
207
  return;
197
208
  }
209
+ if (url.split("?")[0] === "/prefs" && req.method === "GET") {
210
+ handlePrefsList(req, res);
211
+ return;
212
+ }
213
+ if (url.startsWith("/prefsread") && req.method === "GET") {
214
+ handlePrefsRead(req, res);
215
+ return;
216
+ }
217
+ if (url.startsWith("/prefssearch") && req.method === "GET") {
218
+ handlePrefsSearch(req, res);
219
+ return;
220
+ }
198
221
  if (url === "/_control/profiles" && req.method === "GET") {
199
222
  listProfiles(res);
200
223
  return;
@@ -205,6 +228,10 @@ export function createServer() {
205
228
  activateRadar(res, userId);
206
229
  return;
207
230
  }
231
+ if (url === "/_control/devices" && req.method === "GET") {
232
+ listDevices(res);
233
+ return;
234
+ }
208
235
  if (url.startsWith("/screen/")) {
209
236
  handleScreen(req, res);
210
237
  return;
@@ -364,6 +391,14 @@ async function handleSetSpec(req, res) {
364
391
  * forward/proxy base as the rest of the server.
365
392
  */
366
393
  function handleHealth(res) {
394
+ // Reassert before reading: see forwardForRead's doc comment. Without this, a foreign
395
+ // repoint of the shared port (the MCP process switching devices) makes /health probe
396
+ // the WRONG device while still labeling the reply with THIS process's own (correct)
397
+ // device_serial -- a misleading "connected" status for a device this process is not
398
+ // actually reading. reassertForward's cheap check-first path (adb forward --list) keeps
399
+ // the cost low on the 2s poll cadence; it only pays for a real rebuild when the shared
400
+ // port is actually pointed somewhere else.
401
+ forwardForRead();
367
402
  // A probe can fire BOTH an "end" and an "error"/"timeout" (partial response then socket
368
403
  // drop), so guard the response to exactly one write. Without this the second sendJson
369
404
  // does a second writeHead -> ERR_HTTP_HEADERS_SENT -> uncaught -> the whole server dies.
@@ -376,11 +411,14 @@ function handleHealth(res) {
376
411
  if (replied)
377
412
  return;
378
413
  replied = true;
414
+ const selected = transport.getSelectedDevice?.() ?? null;
379
415
  sendJson(res, 200, {
380
416
  device,
381
417
  screen: screenCapabilities(),
382
418
  boundUserId: boundUserId ?? null,
383
419
  boundProfile: boundProfile ?? null,
420
+ device_serial: selected?.serial ?? null,
421
+ device_label: selected?.label ?? null,
384
422
  });
385
423
  };
386
424
  const probe = http.request({
@@ -437,13 +475,51 @@ function handleHealth(res) {
437
475
  * user never has to drop to a terminal. Delegates entirely to AndroidTransport;
438
476
  * no adb shelling here.
439
477
  */
440
- function handleEnable(res) {
478
+ function handleEnable(res, deviceSerial) {
441
479
  transport.resetState();
442
480
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
443
481
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
444
482
  resetDbState();
483
+ // Pin the target device BEFORE any adb call, including resetScreenState's pkill below --
484
+ // that call has no serial of its own and would otherwise target whatever `adb` defaults
485
+ // to (or fail ambiguously) on a multi-device host, running one adb call outside the
486
+ // "pin before any adb call" invariant every other call site in this handler honors. An
487
+ // ambiguous choice (multiple devices, no serial) or an unattached explicit serial fails
488
+ // here with the list, before forwarding OR the screen reset.
489
+ const selection = transport.selectDevice?.(deviceSerial ?? null);
490
+ if (selection && !selection.ok) {
491
+ sendJson(res, 409, {
492
+ enabled: false,
493
+ error: selection.error,
494
+ devices: selection.devices,
495
+ });
496
+ return;
497
+ }
445
498
  resetScreenState(); // re-detect the active display + clear any stale cast on re-arm
446
- const forwarded = transport.ensureForward();
499
+ // On a switch to a different device, drop this device's pulled DB scratch AND the
500
+ // retained logcat capture -- both are per-device state resetDbState()/resetScreenState()
501
+ // above do not cover. logSession.restart() (not stop()) is deliberate here: stop() alone
502
+ // preserves the ring buffer for a transient same-device drop, but a real switch means
503
+ // every retained line belongs to the WRONG device, and the ring would replay device A's
504
+ // history into a freshly opened /stream on device B (mirrors the MCP side's onDeviceSwitch,
505
+ // which resets its own local buffers/spool/capture on the same switch signal). start() is
506
+ // idempotent, so a still-open Logs tab just keeps polling and picks the new child back up
507
+ // on its next /stream reconnect; nothing here needs to force-restart it eagerly.
508
+ if (selection && selection.ok && selection.switched) {
509
+ cleanupPulledDatabases();
510
+ logSession.restart();
511
+ }
512
+ // Reassert the forward is pointed at the selected device before reading. On a device
513
+ // switch or after a multi-process repoint (e.g., MCP server switched to a different
514
+ // device), the cached forward may be stale even though ensureForward() would not detect
515
+ // it on this process. Mirrors forwardForRead's split-brain handling: two processes
516
+ // sharing the same host-level forward must both reassert before assuming it is still
517
+ // good. Use forwardForRead's own result directly rather than also calling
518
+ // transport.ensureForward() again -- resetState() at the top of this handler already
519
+ // dropped the portForwarded cache, so a second unconditional ensureForward() call would
520
+ // only ever be a genuine repeat rebuild (on the rare reassert-failed path), never a
521
+ // no-op skip; forwardForRead already tried its best.
522
+ const forwarded = forwardForRead();
447
523
  if (!forwarded) {
448
524
  const reason = transport.getLastForwardError?.() ?? null;
449
525
  sendJson(res, 200, {
@@ -452,13 +528,15 @@ function handleEnable(res) {
452
528
  });
453
529
  return;
454
530
  }
455
- try {
456
- transport.activate(transport.getTimeoutMinutes());
457
- }
458
- catch (e) {
531
+ // activate() never throws; a failed broadcast is recorded on the transport.
532
+ // Surfacing it here gives the dashboard user the actual adb error instead of
533
+ // a bare enabled:false after the ping probe times out.
534
+ transport.activate(transport.getTimeoutMinutes());
535
+ const activateError = transport.getLastActivateError?.() ?? null;
536
+ if (activateError) {
459
537
  sendJson(res, 200, {
460
538
  enabled: false,
461
- error: `Broadcast failed: ${e.message}. Debug build not running?`,
539
+ error: `Broadcast failed: ${activateError}. Is the device connected?`,
462
540
  });
463
541
  return;
464
542
  }
@@ -469,7 +547,15 @@ function handleEnable(res) {
469
547
  if (replied)
470
548
  return;
471
549
  replied = true;
472
- sendJson(res, 200, { enabled });
550
+ // A failed probe gets guidance, not a bare false: the broadcast landed (or
551
+ // exited 0 with no receiver), so the likely causes are a build without the
552
+ // radar modules or the wrong profile. Mirrors the MCP enable message.
553
+ sendJson(res, 200, enabled
554
+ ? { enabled }
555
+ : {
556
+ enabled,
557
+ error: "Radar broadcast sent but the device server did not respond. Is a debug build with the slack-radar modules running on the active profile?",
558
+ });
473
559
  };
474
560
  const probe = http.request({
475
561
  host: RADAR_HOST,
@@ -507,6 +593,11 @@ export const DEVICE_SOURCES = {
507
593
  * `[{type, event}]` frames mirroring the stream shape.
508
594
  */
509
595
  function handleBackfill(req, res) {
596
+ // Reassert before reading: see forwardForRead's doc comment. A failed reassert still
597
+ // falls through to the request below rather than erroring out here -- the device-side
598
+ // request will surface its own connection failure, matching the pre-existing behavior
599
+ // when the forward was never set up at all.
600
+ forwardForRead();
510
601
  const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
511
602
  const src = u.searchParams.get("source") ?? "network";
512
603
  const limit = Math.min(500, Number(u.searchParams.get("limit")) || 200);
@@ -573,6 +664,8 @@ export function failDetailResponse(res, status) {
573
664
  * to `/api/<kind>/<id>` so the inspector can fetch a clicked row's payload.
574
665
  */
575
666
  function handleDetail(req, res) {
667
+ // Reassert before reading: see forwardForRead's doc comment.
668
+ forwardForRead();
576
669
  const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
577
670
  const id = u.searchParams.get("id");
578
671
  const kind = u.searchParams.get("kind") ?? "network";
@@ -681,6 +774,113 @@ async function handleDbQuery(req, res) {
681
774
  }
682
775
  sendJson(res, status, payload);
683
776
  }
777
+ // --- On-device SharedPreferences browser (source: "prefs") ---
778
+ //
779
+ // These delegate to shared/prefs.ts (run-as + ADB, read-only; PR1, already tested). Mirrors
780
+ // handleDb* above: compute payload+status BEFORE writing headers, errors surface as 200
781
+ // {error} in-pane rather than a transport error. User resolution reuses dbUser (it only reads
782
+ // req/WEB_PORT/transport, nothing db-specific) rather than duplicating a prefsUser().
783
+ function handlePrefsList(req, res) {
784
+ const adbPath = resolveAdbPath();
785
+ if (!adbPath) {
786
+ sendJson(res, 200, { error: "adb not found. Ensure platform-tools is installed and on PATH.", files: [], available_users: [] });
787
+ return;
788
+ }
789
+ try {
790
+ const user = dbUser(req);
791
+ const result = listPrefsFiles(adbPath, user);
792
+ if (!result) {
793
+ sendJson(res, 200, { error: "unable to list preferences files. Is the debug build installed and is a device connected?", files: [], available_users: availableUsers() });
794
+ }
795
+ else {
796
+ sendJson(res, 200, {
797
+ user: result.user,
798
+ available_users: availableUsers(),
799
+ files: result.files,
800
+ });
801
+ }
802
+ }
803
+ catch (e) {
804
+ sendJson(res, 200, { error: e.message, files: [], available_users: [] });
805
+ }
806
+ }
807
+ async function handlePrefsRead(req, res) {
808
+ const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
809
+ const file = u.searchParams.get("file") ?? "";
810
+ const user = dbUser(req);
811
+ const keysParam = u.searchParams.get("keys") ?? "";
812
+ const keys = keysParam ? keysParam.split(",").filter((k) => k.trim().length > 0) : null;
813
+ const adbPath = resolveAdbPath();
814
+ if (!adbPath) {
815
+ sendJson(res, 200, { error: "adb not found. Ensure platform-tools is installed and on PATH." });
816
+ return;
817
+ }
818
+ let payload;
819
+ try {
820
+ const readResult = await readPrefsFile(adbPath, file, user);
821
+ if ("error" in readResult) {
822
+ payload = { error: readResult.error };
823
+ }
824
+ else {
825
+ const parsed = parsePrefsXml(readResult.xml);
826
+ if ("parseError" in parsed) {
827
+ payload = { error: parsed.parseError };
828
+ }
829
+ else {
830
+ // Web route is human-consumable (renders to a scrolling table), so unlike the MCP
831
+ // get_prefs handler it does NOT byte-cap the response -- only the keys filter (if
832
+ // any) narrows what is returned. device_read_truncated is a real data-completeness
833
+ // signal (the 256KB on-device read cap) and is passed through either way.
834
+ //
835
+ // total_entries is the file's TRUE entry count, before any filtering -- keys narrows
836
+ // what is RETURNED, it does not shrink what the file actually has. Reporting the
837
+ // post-filter count for both fields (the original bug) makes the UI's "X of Y" always
838
+ // read "N of N" the moment keys is used, hiding how much of the file was left out.
839
+ const entries = keys && keys.length
840
+ ? parsed.entries.filter((e) => keys.includes(e.key))
841
+ : parsed.entries;
842
+ payload = {
843
+ file,
844
+ user: readResult.user,
845
+ entries,
846
+ ...(readResult.truncated ? { device_read_truncated: true } : {}),
847
+ total_entries: parsed.entries.length,
848
+ returned_entries: entries.length,
849
+ };
850
+ }
851
+ }
852
+ }
853
+ catch (e) {
854
+ payload = { error: String(e.message).split("\n")[0] };
855
+ }
856
+ sendJson(res, 200, payload);
857
+ }
858
+ async function handlePrefsSearch(req, res) {
859
+ const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
860
+ const query = u.searchParams.get("query") ?? "";
861
+ const user = dbUser(req);
862
+ const adbPath = resolveAdbPath();
863
+ if (!adbPath) {
864
+ sendJson(res, 200, { error: "adb not found. Ensure platform-tools is installed and on PATH." });
865
+ return;
866
+ }
867
+ let payload;
868
+ try {
869
+ const result = await searchPrefs(adbPath, query, user);
870
+ payload = {
871
+ query,
872
+ user: result.user,
873
+ available_users: availableUsers(),
874
+ results: result.results,
875
+ ...(result.truncated ? { truncated: true } : {}),
876
+ ...(result.skipped && result.skipped.length ? { skipped: result.skipped } : {}),
877
+ };
878
+ }
879
+ catch (e) {
880
+ payload = { error: String(e.message).split("\n")[0] };
881
+ }
882
+ sendJson(res, 200, payload);
883
+ }
684
884
  /**
685
885
  * Screen overlay routes. The live screen shows real DMs and message content, so the
686
886
  * stream and record routes are gated behind an explicit per-process consent (granted
@@ -1001,21 +1201,21 @@ function handleStream(req, res) {
1001
1201
  return;
1002
1202
  settled = true;
1003
1203
  retries++;
1004
- // Every other retry, rebuild a clean forward before reconnecting. resetState()
1005
- // drops the cached forward flag so ensureForward() actually re-runs adb forward.
1006
- if (retries % 2 === 0) {
1007
- transport.resetState();
1008
- transport.ensureForward();
1009
- setTimeout(connect, 1500);
1010
- }
1011
- else {
1012
- setTimeout(connect, 2000);
1013
- }
1204
+ // planReconnect (shared/stream.ts) owns the cadence: every other retry it
1205
+ // rebuilds a clean forward before reconnecting and returns the delay. One
1206
+ // implementation for this proxy and the MCP stream, so a tuning change
1207
+ // cannot silently move only one of them.
1208
+ setTimeout(connect, planReconnect(transport, retries));
1014
1209
  };
1015
1210
  const connect = () => {
1016
1211
  if (closed)
1017
1212
  return;
1018
1213
  settled = false;
1214
+ // Reassert before every connect (initial AND each retry): see forwardForRead's doc
1215
+ // comment. planReconnect already forces a hard forward rebuild on every OTHER retry
1216
+ // (tuned for "device end died"), which would only catch a foreign repoint by luck on
1217
+ // half of attempts; this cheap check-first call covers every attempt instead.
1218
+ forwardForRead();
1019
1219
  upstream = http.request({
1020
1220
  host: RADAR_HOST,
1021
1221
  port: RADAR_PORT,
@@ -1109,6 +1309,21 @@ function listProfiles(res) {
1109
1309
  const activeUserId = transport.getActiveUserId();
1110
1310
  sendJson(res, 200, { profiles, active_user_id: activeUserId });
1111
1311
  }
1312
+ // The attached-device list + the currently pinned device, for the dashboard's device picker.
1313
+ // listDevices() returns null when the adb listing itself failed (not "zero attached"); surface
1314
+ // that as adb_error:true with an empty list so the client can say why instead of showing "none".
1315
+ function listDevices(res) {
1316
+ // Distinguish null (adb listing failed) from [] (no devices): null means we cannot tell what
1317
+ // is attached, so tell the client with adb_error instead of a bare "none". A transport with no
1318
+ // listDevices() at all (undefined) is treated as "no devices", not an adb error.
1319
+ const listed = transport.listDevices?.();
1320
+ const adbError = listed === null;
1321
+ sendJson(res, 200, {
1322
+ devices: listed ?? [],
1323
+ selected: transport.getSelectedDevice?.() ?? null,
1324
+ ...(adbError ? { adb_error: true } : {}),
1325
+ });
1326
+ }
1112
1327
  function activateRadar(res, userId) {
1113
1328
  // Reset cached state so ensureForward() re-runs adb forward. This handles
1114
1329
  // stale forwards after device-side idle timeout or profile switching.
@@ -5,17 +5,17 @@
5
5
  * and the same validate/coerce pass runs on every push so a malformed spec surfaces
6
6
  * an error instead of rendering silent zeros.
7
7
  *
8
- * Most sources are live STREAMS (network/rtm/clog/trace/log/all). `db` is the odd one out:
9
- * a read-only, point-in-time SQLite BROWSER over the on-device databases, with no viz /
10
- * series / match (it has its own list -> tables -> query-grid view). The coerce and
11
- * validate passes short-circuit for `db` accordingly.
8
+ * Most sources are live STREAMS (network/rtm/clog/trace/log/all). `db` and `prefs` are the
9
+ * odd ones out: read-only, point-in-time BROWSERS (SQLite databases, SharedPreferences files)
10
+ * with no viz / series / match (each has its own list -> detail view). The coerce and
11
+ * validate passes short-circuit for both accordingly.
12
12
  */
13
13
  /**
14
14
  * Sources the dashboard can read. The first six are live streams; "all" is their unified
15
- * timeline. "db" is a read-only on-device SQLite browser (a point-in-time snapshot, not a
16
- * stream) and is handled as a distinct view.
15
+ * timeline. "db" and "prefs" are read-only point-in-time browsers (not streams) and are each
16
+ * handled as a distinct view.
17
17
  */
18
- export declare const SOURCES: readonly ["rtm", "network", "clog", "trace", "log", "all", "db"];
18
+ export declare const SOURCES: readonly ["rtm", "network", "clog", "trace", "log", "all", "db", "prefs"];
19
19
  export type Source = (typeof SOURCES)[number];
20
20
  /** Widgets a spec may compose. */
21
21
  export declare const VIZ: readonly ["counter", "rate", "sparkline", "feed", "inspector", "graph"];
package/dist/web/spec.js CHANGED
@@ -5,17 +5,17 @@
5
5
  * and the same validate/coerce pass runs on every push so a malformed spec surfaces
6
6
  * an error instead of rendering silent zeros.
7
7
  *
8
- * Most sources are live STREAMS (network/rtm/clog/trace/log/all). `db` is the odd one out:
9
- * a read-only, point-in-time SQLite BROWSER over the on-device databases, with no viz /
10
- * series / match (it has its own list -> tables -> query-grid view). The coerce and
11
- * validate passes short-circuit for `db` accordingly.
8
+ * Most sources are live STREAMS (network/rtm/clog/trace/log/all). `db` and `prefs` are the
9
+ * odd ones out: read-only, point-in-time BROWSERS (SQLite databases, SharedPreferences files)
10
+ * with no viz / series / match (each has its own list -> detail view). The coerce and
11
+ * validate passes short-circuit for both accordingly.
12
12
  */
13
13
  /**
14
14
  * Sources the dashboard can read. The first six are live streams; "all" is their unified
15
- * timeline. "db" is a read-only on-device SQLite browser (a point-in-time snapshot, not a
16
- * stream) and is handled as a distinct view.
15
+ * timeline. "db" and "prefs" are read-only point-in-time browsers (not streams) and are each
16
+ * handled as a distinct view.
17
17
  */
18
- export const SOURCES = ["rtm", "network", "clog", "trace", "log", "all", "db"];
18
+ export const SOURCES = ["rtm", "network", "clog", "trace", "log", "all", "db", "prefs"];
19
19
  /** Widgets a spec may compose. */
20
20
  export const VIZ = [
21
21
  "counter",
@@ -50,8 +50,8 @@ export function coerceSpec(input) {
50
50
  if (!isRecord(input))
51
51
  return BLANK_SPEC;
52
52
  const s = input;
53
- // The DB browser has no match/viz/series to repair; leave its db/table/sql untouched.
54
- if (s.source === "db")
53
+ // The DB and Prefs browsers have no match/viz/series to repair; leave them untouched.
54
+ if (s.source === "db" || s.source === "prefs")
55
55
  return s;
56
56
  if (typeof s.match === "string") {
57
57
  // "all" mixes types whose summary fields differ, so a single field guess
@@ -110,6 +110,9 @@ export function validateSpec(s) {
110
110
  }
111
111
  return null;
112
112
  }
113
+ // The Prefs browser is likewise a distinct, self-contained view: no viz/series/match.
114
+ if (spec.source === "prefs")
115
+ return null;
113
116
  if (spec.match !== undefined && !isRecord(spec.match)) {
114
117
  return "match must be an object";
115
118
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slack/radar-mcp",
3
- "version": "1.10.0",
3
+ "version": "1.12.0",
4
4
  "description": "MCP server and web dashboard for on-device debugging of the Slack Android app via ADB",
5
5
  "type": "module",
6
6
  "main": "dist/mcp/index.js",