@slack/radar-mcp 1.11.0 → 1.13.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 (38) hide show
  1. package/README.md +12 -2
  2. package/dist/mcp/api-paths.js +2 -0
  3. package/dist/mcp/flags-tools.d.ts +71 -0
  4. package/dist/mcp/flags-tools.js +158 -0
  5. package/dist/mcp/index.js +103 -5
  6. package/dist/mcp/prefs-tools.d.ts +15 -0
  7. package/dist/mcp/prefs-tools.js +204 -0
  8. package/dist/mcp/session-enable.d.ts +2 -1
  9. package/dist/mcp/session-enable.js +29 -2
  10. package/dist/mcp/snapshot.js +6 -1
  11. package/dist/mcp/sources-gate.d.ts +23 -0
  12. package/dist/mcp/sources-gate.js +63 -0
  13. package/dist/mcp/tools.js +102 -2
  14. package/dist/shared/android.d.ts +33 -1
  15. package/dist/shared/android.js +203 -6
  16. package/dist/shared/constants.d.ts +8 -0
  17. package/dist/shared/constants.js +13 -1
  18. package/dist/shared/db.d.ts +21 -3
  19. package/dist/shared/db.js +89 -23
  20. package/dist/shared/feature-flags.d.ts +6 -0
  21. package/dist/shared/feature-flags.js +17 -0
  22. package/dist/shared/prefs.d.ts +78 -0
  23. package/dist/shared/prefs.js +416 -0
  24. package/dist/shared/transport.d.ts +68 -0
  25. package/dist/web/log-session.d.ts +13 -0
  26. package/dist/web/log-session.js +16 -0
  27. package/dist/web/public/index.html +129 -3
  28. package/dist/web/public/next/app.js +82 -4
  29. package/dist/web/public/next/feed.js +270 -14
  30. package/dist/web/public/next/filter.js +200 -0
  31. package/dist/web/public/next/flags.js +179 -0
  32. package/dist/web/public/next/prefs.js +399 -0
  33. package/dist/web/public/next/registry.js +16 -6
  34. package/dist/web/public/next/store.js +250 -11
  35. package/dist/web/server.js +267 -7
  36. package/dist/web/spec.d.ts +7 -7
  37. package/dist/web/spec.js +15 -9
  38. package/package.json +1 -1
@@ -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
- import { RADAR_PORT } from "./constants.js";
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;
@@ -91,18 +129,29 @@ export class AndroidTransport {
91
129
  radarEnabled = false;
92
130
  lastForwardError = null;
93
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;
94
135
  ensureForward() {
95
136
  if (this.portForwarded)
96
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() {
97
144
  if (!ADB) {
98
145
  this.lastForwardError =
99
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.";
100
147
  return false;
101
148
  }
102
149
  // 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.
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.
106
155
  try {
107
156
  execSync(`${ADB} forward --remove tcp:${RADAR_PORT}`, { timeout: 5000 });
108
157
  }
@@ -122,6 +171,35 @@ export class AndroidTransport {
122
171
  return false;
123
172
  }
124
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
+ }
125
203
  getLastForwardError() {
126
204
  return this.lastForwardError;
127
205
  }
@@ -135,7 +213,7 @@ export class AndroidTransport {
135
213
  return;
136
214
  try {
137
215
  const userId = this.detectDebugBuildUser();
138
- 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 });
139
217
  this.currentTimeoutMinutes = timeout;
140
218
  this.radarEnabled = true;
141
219
  this.lastActivateError = null;
@@ -304,7 +382,7 @@ export class AndroidTransport {
304
382
  // scoped to a profile we could not detect, and appending this profile's
305
383
  // run to it would mix profiles in one file. Rotating is the safe default.
306
384
  const profileChanged = this.detectedUserId !== userId;
307
- execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout}`, { timeout: 5000 });
385
+ execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout} --es mcp_version ${RADAR_VERSION}`, { timeout: 5000 });
308
386
  this.detectedUserId = userId;
309
387
  this.currentTimeoutMinutes = timeout;
310
388
  this.radarEnabled = true;
@@ -316,6 +394,125 @@ export class AndroidTransport {
316
394
  registerCleanup();
317
395
  startCapture(ADB);
318
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
+ }
319
516
  detectDebugBuildUser() {
320
517
  if (this.detectedUserId !== null)
321
518
  return this.detectedUserId;
@@ -54,3 +54,11 @@ export declare const SLACK_DEBUG_PKG = "com.Slack.internal.debug";
54
54
  * the session-query byte cap share one ceiling and cannot drift.
55
55
  */
56
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,7 +9,11 @@ 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";
@@ -63,3 +67,11 @@ export const SLACK_DEBUG_PKG = "com.Slack.internal.debug";
63
67
  * the session-query byte cap share one ceiling and cannot drift.
64
68
  */
65
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
@@ -38,12 +52,16 @@ export declare function listDatabases(user?: string | null): {
38
52
  availableUsers: string[];
39
53
  names: string[];
40
54
  };
55
+ export declare function assertCompleteSqliteFile(name: string, bytes: Buffer | undefined): void;
41
56
  /**
42
57
  * Stream a database off the device to a local 0600 copy (scoped to the target user) and
43
58
  * return its path. `run-as ... cp` into shared storage fails silently (sandbox), so the
44
- * working path is `exec-out cat` piped to a host file. Validates the SQLite magic header
45
- * so a missing DB (whose `cat` emits an error string, not file bytes) fails with a clear
46
- * message instead of being written as a junk file that later trips an opaque parse error.
59
+ * working path is `exec-out cat` piped to a host file. Validates via
60
+ * `assertCompleteSqliteFile` (magic header, page-size legality, whole-file-size) so a
61
+ * missing or truncated pull fails with a clear message instead of being written as a junk
62
+ * file that later trips an opaque parse error. Retries the pull once on a transient
63
+ * truncation before giving up: `adb exec-out` hiccups are usually a one-shot glitch, and a
64
+ * silent retry means a dashboard user never sees the error for the common case.
47
65
  *
48
66
  * WAL: Slack's on-device DBs are WAL-mode and the live app holds write connections open,
49
67
  * so recently-committed rows live in the `-wal` sidecar, NOT yet in the main file. Pulling
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
@@ -235,12 +246,56 @@ export function listDatabases(user) {
235
246
  .filter((n) => !/-(wal|shm|journal)$/.test(n));
236
247
  return { user: u, availableUsers: available, names };
237
248
  }
249
+ /**
250
+ * Reject a pulled DB buffer that is not a whole, complete SQLite file, before it is written
251
+ * to disk and cached. Three independent checks:
252
+ *
253
+ * 1. The magic header (first 16 bytes) AND a minimum length of 512 bytes, the smallest legal
254
+ * whole SQLite file (the smallest legal page size). Catches a missing/unreadable DB,
255
+ * whose `cat` emits an error string instead of file bytes, and also guards the page-size
256
+ * read below: without this floor, a buffer that happens to be exactly 16-17 bytes (magic
257
+ * present, nothing after) would throw an unhandled RangeError from `readUInt16BE`
258
+ * instead of this function's own clear error.
259
+ * 2. Page-size legality: the format only allows a power of two from 512 to 32768 at header
260
+ * offset 16-17 (big-endian), or the special-cased value 1 meaning 65536. `adb exec-out`
261
+ * streaming a live, multi-MB DB can truncate mid-page (an adb transport hiccup, or the
262
+ * app writing to the file while it is being read) and still pass check 1, since the
263
+ * header is the FIRST bytes of the stream and truncation happens later. If the cut lands
264
+ * inside the page-size field itself, the field can read as 0 or some other illegal value
265
+ * -- that is itself proof of truncation, not a value to skip validating.
266
+ * 3. Whole-file-size check: a complete SQLite file is always an exact multiple of its own
267
+ * (now known-legal) page size. A byte count that does not divide evenly is proof the
268
+ * stream was cut short somewhere past the header.
269
+ *
270
+ * Exported so this is testable without a device (mirrors assertReadOnlyQuery / isExplainQuery
271
+ * below, which exist for the same reason): pullDatabase's actual adb call cannot run in CI.
272
+ */
273
+ const MIN_SQLITE_FILE_SIZE = 512;
274
+ export function assertCompleteSqliteFile(name, bytes) {
275
+ if (!bytes ||
276
+ bytes.length < MIN_SQLITE_FILE_SIZE ||
277
+ !bytes.subarray(0, SQLITE_MAGIC.length).equals(SQLITE_MAGIC)) {
278
+ throw new Error(`"${name}" did not come back as a valid SQLite file (${bytes ? bytes.length : 0} bytes). It may not exist on the device, the org may not be loaded on this profile, or the database may be encrypted.`);
279
+ }
280
+ const declaredPageSize = bytes.readUInt16BE(16);
281
+ const pageSize = declaredPageSize === 1 ? 65536 : declaredPageSize;
282
+ const isLegalPageSize = pageSize === 65536 || (pageSize >= 512 && pageSize <= 32768 && (pageSize & (pageSize - 1)) === 0);
283
+ if (!isLegalPageSize) {
284
+ throw new Error(`"${name}" came back with an invalid page-size field (${declaredPageSize}). The device pull was likely cut off mid-stream and landed inside the header; retry.`);
285
+ }
286
+ if (bytes.length % pageSize !== 0) {
287
+ throw new Error(`"${name}" came back truncated (${bytes.length} bytes is not a whole multiple of its ${pageSize}-byte page size). The device pull was likely cut off mid-stream; retry.`);
288
+ }
289
+ }
238
290
  /**
239
291
  * Stream a database off the device to a local 0600 copy (scoped to the target user) and
240
292
  * return its path. `run-as ... cp` into shared storage fails silently (sandbox), so the
241
- * working path is `exec-out cat` piped to a host file. Validates the SQLite magic header
242
- * so a missing DB (whose `cat` emits an error string, not file bytes) fails with a clear
243
- * message instead of being written as a junk file that later trips an opaque parse error.
293
+ * working path is `exec-out cat` piped to a host file. Validates via
294
+ * `assertCompleteSqliteFile` (magic header, page-size legality, whole-file-size) so a
295
+ * missing or truncated pull fails with a clear message instead of being written as a junk
296
+ * file that later trips an opaque parse error. Retries the pull once on a transient
297
+ * truncation before giving up: `adb exec-out` hiccups are usually a one-shot glitch, and a
298
+ * silent retry means a dashboard user never sees the error for the common case.
244
299
  *
245
300
  * WAL: Slack's on-device DBs are WAL-mode and the live app holds write connections open,
246
301
  * so recently-committed rows live in the `-wal` sidecar, NOT yet in the main file. Pulling
@@ -263,22 +318,33 @@ export async function pullDatabase(name, user, force = false) {
263
318
  // force=true to re-stream when the user wants the current device state.
264
319
  if (!force && fs.existsSync(local))
265
320
  return local;
321
+ // A truncated pull is retried ONCE, silently, before giving up: an adb transport hiccup on
322
+ // a multi-MB stream is usually a one-shot glitch that a plain re-pull clears, and the
323
+ // common case should never surface an error to the user at all. Only the truncation checks
324
+ // (assertCompleteSqliteFile) are retried, not an adb-level failure (missing DB, run-as
325
+ // rejection) -- that failure mode is not transient and retrying it just doubles the wait
326
+ // before the same clear error.
266
327
  let bytes;
267
- try {
268
- // Async exec-out so a multi-MB pull does not block the event loop (which would hang
269
- // every other tab, the stream, and /health for the duration of the pull).
270
- bytes = await runAdbAsync([
271
- "exec-out",
272
- `run-as ${DB_PKG} ${userFlag(u)} cat databases/${name}`,
273
- ]);
274
- }
275
- catch {
276
- throw new Error(`"${name}" is not readable on the device (not present for this profile, or run-as failed). List databases to see what is there.`);
277
- }
278
- if (!bytes ||
279
- bytes.length < SQLITE_MAGIC.length ||
280
- !bytes.subarray(0, SQLITE_MAGIC.length).equals(SQLITE_MAGIC)) {
281
- throw new Error(`"${name}" did not come back as a valid SQLite file (${bytes ? bytes.length : 0} bytes). It may not exist on the device, the org may not be loaded on this profile, or the database may be encrypted.`);
328
+ for (let attempt = 0; attempt < 2; attempt++) {
329
+ try {
330
+ // Async exec-out so a multi-MB pull does not block the event loop (which would hang
331
+ // every other tab, the stream, and /health for the duration of the pull).
332
+ bytes = await runAdbAsync([
333
+ "exec-out",
334
+ `run-as ${DB_PKG} ${userFlag(u)} cat databases/${name}`,
335
+ ]);
336
+ }
337
+ catch {
338
+ throw new Error(`"${name}" is not readable on the device (not present for this profile, or run-as failed). List databases to see what is there.`);
339
+ }
340
+ try {
341
+ assertCompleteSqliteFile(name, bytes);
342
+ break;
343
+ }
344
+ catch (e) {
345
+ if (attempt === 1)
346
+ throw e;
347
+ }
282
348
  }
283
349
  fs.writeFileSync(local, bytes, { mode: 0o600 });
284
350
  // Pull the WAL sidecars alongside the main file so the normal (non-immutable) open below
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Rewrite the device's raw "Not Found" into an actionable message. The route 404s as valid
3
+ * JSON ({"error":"Not Found"}) on builds that predate the feature-flag Radar plugin, which is
4
+ * correct but useless to a caller with no way to know this route is plugin-gated.
5
+ */
6
+ export declare function friendlyFeatureFlagError(error: unknown): string;
@@ -0,0 +1,17 @@
1
+ // Shared feature-flag response handling for the two callers that read the device's
2
+ // /api/feature_flags route: the MCP tools (flags-tools.ts) and the web dashboard's Flags tab
3
+ // (web/server.ts). Both need the same "Not Found" rewrite for builds that predate the
4
+ // feature-flag Radar plugin, so it lives here once instead of drifting between two copies.
5
+ /**
6
+ * Rewrite the device's raw "Not Found" into an actionable message. The route 404s as valid
7
+ * JSON ({"error":"Not Found"}) on builds that predate the feature-flag Radar plugin, which is
8
+ * correct but useless to a caller with no way to know this route is plugin-gated.
9
+ */
10
+ export function friendlyFeatureFlagError(error) {
11
+ if (typeof error !== "string")
12
+ return "Unknown device error.";
13
+ if (error === "Not Found") {
14
+ return "This debug build does not serve feature flags yet (update to a build with the feature-flag Radar plugin).";
15
+ }
16
+ return error;
17
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * On-device SharedPreferences reader (host-side, read-only).
3
+ *
4
+ * The Slack app stores configuration, feature flags, and user preferences in standard
5
+ * Android SharedPreferences XML files under `shared_prefs/`. This reader streams them
6
+ * off-device via `adb exec-out run-as`, parses the XML, and offers search/filter.
7
+ * Nothing is written on the device; no app rebuild needed. Dual-profile aware (personal
8
+ * user 0 and work profiles user 10+).
9
+ *
10
+ * SECURITY: preference values can include user IDs, team IDs, org IDs, and feature flag
11
+ * state. This reader only returns files/keys/values to the caller (no host-side file
12
+ * written), with a privacy note reminding the caller to review before sharing.
13
+ */
14
+ /**
15
+ * List SharedPreferences files for a user, with their sizes.
16
+ * Via `run-as ... ls -la shared_prefs/` and parse name+size.
17
+ * Returns null on run-as failure.
18
+ */
19
+ export declare function listPrefsFiles(adbPath: string, user?: string): {
20
+ user: string;
21
+ files: {
22
+ name: string;
23
+ size: number;
24
+ }[];
25
+ } | null;
26
+ /**
27
+ * Read a SharedPreferences XML file from the device.
28
+ * Via `adb exec-out run-as ... cat shared_prefs/<name>`.
29
+ * Validates filename and user first. Caps read at 256KB (truncated: true if larger).
30
+ * Returns { xml: string, user: string, truncated?: boolean } on success or { error: string } on failure.
31
+ * Retries once after ~200ms if the first read fails (mid-write .bak swap).
32
+ */
33
+ export declare function readPrefsFile(adbPath: string, name: string, user?: string): Promise<{
34
+ xml: string;
35
+ user: string;
36
+ truncated?: boolean;
37
+ } | {
38
+ error: string;
39
+ }>;
40
+ export type PrefsValue = string | boolean | number | string[];
41
+ export type PrefsType = "boolean" | "int" | "long" | "float" | "string" | "set";
42
+ export interface PrefsEntry {
43
+ key: string;
44
+ type: PrefsType;
45
+ value: PrefsValue;
46
+ }
47
+ /**
48
+ * Parse SharedPreferences XML into typed entries.
49
+ * Handles: boolean, int, long, float, string, set (with string children).
50
+ * Returns { entries: [...] } on success or { parseError: string } on failure.
51
+ * Handles: entity unescaping, self-closing and open-close forms, empty map, garbage input.
52
+ * Never throws.
53
+ */
54
+ export declare function parsePrefsXml(xml: string): {
55
+ entries: PrefsEntry[];
56
+ } | {
57
+ parseError: string;
58
+ };
59
+ /**
60
+ * Search preferences across all files for a user.
61
+ * Case-insensitive substring search on key names and stringified values.
62
+ * Returns per-file match results, capped at 200 total matches across all files
63
+ * (truncated: true when the cap was hit, so a caller can tell "no more matches"
64
+ * apart from "matches exist beyond this page" — plain array truncation would lose
65
+ * that flag on JSON.stringify, since non-index array properties are not serialized).
66
+ * A file that fails to read (run-as denial, mid-write on both attempts) or fails to
67
+ * parse is skipped and named in `skipped`, so a caller can tell "no match in this file"
68
+ * apart from "this file could not be checked."
69
+ */
70
+ export declare function searchPrefs(adbPath: string, query: string, user?: string): Promise<{
71
+ results: {
72
+ file: string;
73
+ matches: PrefsEntry[];
74
+ }[];
75
+ user: string;
76
+ truncated?: boolean;
77
+ skipped?: string[];
78
+ }>;