@slack/radar-mcp 1.22.0 → 1.24.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 (44) hide show
  1. package/README.md +62 -12
  2. package/dist/mcp/dashboard-identity.d.ts +10 -0
  3. package/dist/mcp/dashboard-identity.js +20 -0
  4. package/dist/mcp/debug-package-reset.d.ts +5 -0
  5. package/dist/mcp/debug-package-reset.js +28 -0
  6. package/dist/mcp/flags-tools.d.ts +2 -0
  7. package/dist/mcp/flags-tools.js +15 -1
  8. package/dist/mcp/index.js +172 -142
  9. package/dist/mcp/radar-http.d.ts +22 -0
  10. package/dist/mcp/radar-http.js +63 -0
  11. package/dist/mcp/radar-response.d.ts +1 -0
  12. package/dist/mcp/session-enable.d.ts +15 -0
  13. package/dist/mcp/session-enable.js +195 -33
  14. package/dist/mcp/sources-gate.js +5 -0
  15. package/dist/mcp/switchboard-tools.d.ts +5 -2
  16. package/dist/mcp/switchboard-tools.js +18 -12
  17. package/dist/mcp/test-cases.d.ts +14 -0
  18. package/dist/mcp/test-cases.js +77 -0
  19. package/dist/mcp/test-runs-tools.d.ts +8 -0
  20. package/dist/mcp/test-runs-tools.js +95 -0
  21. package/dist/mcp/tools.js +106 -171
  22. package/dist/mcp/web-child-env.js +2 -1
  23. package/dist/shared/android.d.ts +75 -10
  24. package/dist/shared/android.js +352 -109
  25. package/dist/shared/constants.d.ts +17 -5
  26. package/dist/shared/constants.js +59 -5
  27. package/dist/shared/db.d.ts +1 -1
  28. package/dist/shared/db.js +21 -14
  29. package/dist/shared/debug-log.js +2 -4
  30. package/dist/shared/enable-diagnosis.d.ts +27 -1
  31. package/dist/shared/enable-diagnosis.js +73 -0
  32. package/dist/shared/log-session.d.ts +2 -1
  33. package/dist/shared/logcat-capture.js +17 -1
  34. package/dist/shared/prefs.js +4 -5
  35. package/dist/shared/radar-request-raw.js +3 -1
  36. package/dist/shared/switchboard.d.ts +1 -0
  37. package/dist/shared/switchboard.js +3 -1
  38. package/dist/shared/transport.d.ts +30 -0
  39. package/dist/web/install-app.d.ts +18 -0
  40. package/dist/web/install-app.js +60 -7
  41. package/dist/web/macapp/RadarApp.swift +147 -1
  42. package/dist/web/server.d.ts +17 -0
  43. package/dist/web/server.js +180 -35
  44. package/package.json +1 -1
@@ -69,13 +69,25 @@ export declare const WEB_PORT_DEFAULT = 8100;
69
69
  * commits to redirecting RADAR_PORT at it.
70
70
  */
71
71
  export declare const WEBAPP_DEFAULT_PORT = 1989;
72
+ /** Env var that pins the Slack debug package, for a profile running two debug builds at once. */
73
+ export declare const DEBUG_PACKAGE_ENV = "SLACK_RADAR_DEBUG_PACKAGE";
74
+ export declare const DEFAULT_DEBUG_PKG = "com.Slack.internal.debug";
72
75
  /**
73
- * The Slack debug build whose sandbox the host can `run-as` into. Both the
74
- * on-device SQLite browser (db.ts) and the app log-buffer reader (debug-log.ts)
75
- * read sandbox files through `adb exec-out "run-as <pkg> ..."`, which only works
76
- * on a debuggable build. Defined once here so the two readers cannot drift.
76
+ * The debug app ids the Slack app ships: applicationId com.Slack, flavors internal, intune and
77
+ * prototype (or none), debug build type. Auto-detect from ps adopts only these; anything else
78
+ * needs SLACK_RADAR_DEBUG_PACKAGE, so a lookalike process never gets the token.
77
79
  */
78
- export declare const SLACK_DEBUG_PKG = "com.Slack.internal.debug";
80
+ export declare const SHIPPED_DEBUG_PACKAGES: readonly string[];
81
+ /** A ps NAME may carry a `:process` suffix; the package is what comes before it. */
82
+ export declare function debugPackageFromPsName(name: string): string | null;
83
+ /** The env override, or null when unset. An invalid value still comes back so the caller can fail loudly. */
84
+ export declare function debugPackageOverride(): string | null;
85
+ /** Error text for an env value that breaks the rule, or null when the env is unset or fine. */
86
+ export declare function debugPackageOverrideError(): string | null;
87
+ export declare function slackDebugPackage(): string;
88
+ export declare function setSlackDebugPackage(pkg: string): void;
89
+ /** Back to env-or-default, for a device switch. A lost request keeps the armed package. */
90
+ export declare function resetSlackDebugPackage(): void;
79
91
  /**
80
92
  * Host-side ceiling on a single response we forward into the model context. A
81
93
  * proxied device response (large trace/clog payloads) or a session-spool query
@@ -84,13 +84,67 @@ export const WEB_PORT_DEFAULT = 8100;
84
84
  * commits to redirecting RADAR_PORT at it.
85
85
  */
86
86
  export const WEBAPP_DEFAULT_PORT = 1989;
87
+ /** Env var that pins the Slack debug package, for a profile running two debug builds at once. */
88
+ export const DEBUG_PACKAGE_ENV = "SLACK_RADAR_DEBUG_PACKAGE";
89
+ export const DEFAULT_DEBUG_PKG = "com.Slack.internal.debug";
90
+ // One rule for the env value and for names read off ps. It keeps every name shell-safe (it goes
91
+ // into `adb shell` strings) and inside what the ps grep can see, so an override can never read
92
+ // as a false "stopped".
93
+ const DEBUG_PACKAGE_RULE = /^com\.Slack(\.[A-Za-z0-9_]+)*\.debug$/;
87
94
  /**
88
- * The Slack debug build whose sandbox the host can `run-as` into. Both the
89
- * on-device SQLite browser (db.ts) and the app log-buffer reader (debug-log.ts)
90
- * read sandbox files through `adb exec-out "run-as <pkg> ..."`, which only works
91
- * on a debuggable build. Defined once here so the two readers cannot drift.
95
+ * The debug app ids the Slack app ships: applicationId com.Slack, flavors internal, intune and
96
+ * prototype (or none), debug build type. Auto-detect from ps adopts only these; anything else
97
+ * needs SLACK_RADAR_DEBUG_PACKAGE, so a lookalike process never gets the token.
92
98
  */
93
- export const SLACK_DEBUG_PKG = "com.Slack.internal.debug";
99
+ export const SHIPPED_DEBUG_PACKAGES = [
100
+ "com.Slack.internal.debug",
101
+ "com.Slack.intune.debug",
102
+ "com.Slack.prototype.debug",
103
+ "com.Slack.debug",
104
+ ];
105
+ /** A ps NAME may carry a `:process` suffix; the package is what comes before it. */
106
+ export function debugPackageFromPsName(name) {
107
+ const pkg = name.split(":")[0];
108
+ return DEBUG_PACKAGE_RULE.test(pkg) ? pkg : null;
109
+ }
110
+ /** The env override, or null when unset. An invalid value still comes back so the caller can fail loudly. */
111
+ export function debugPackageOverride() {
112
+ const value = process.env[DEBUG_PACKAGE_ENV];
113
+ return value ? value : null;
114
+ }
115
+ /** Error text for an env value that breaks the rule, or null when the env is unset or fine. */
116
+ export function debugPackageOverrideError() {
117
+ const value = debugPackageOverride();
118
+ if (value === null || DEBUG_PACKAGE_RULE.test(value))
119
+ return null;
120
+ return `${DEBUG_PACKAGE_ENV} must be a Slack debug app id, like com.Slack.intune.debug or com.Slack.debug (letters, digits and underscores between the dots), got "${value}"`;
121
+ }
122
+ function validPackageFrom(value) {
123
+ return value && DEBUG_PACKAGE_RULE.test(value) ? value : null;
124
+ }
125
+ function envOrDefaultPackage() {
126
+ return validPackageFrom(debugPackageOverride()) ?? DEFAULT_DEBUG_PKG;
127
+ }
128
+ /**
129
+ * The Slack debug build whose sandbox the host can `run-as` into: the enable broadcast, the token
130
+ * file, the SQLite browser (db.ts), prefs and the app log-buffer reader all target it, so they
131
+ * cannot drift. The arm sets it to what ps shows, so read it through slackDebugPackage().
132
+ *
133
+ * Precedence: SLACK_RADAR_DEBUG_PACKAGE env > the one debug package ps shows for the bound user
134
+ * (with several, the current one if it is among them) > com.Slack.internal.debug. After an
135
+ * enable, re-arms keep the build it armed; when ps cannot answer, the current build is kept.
136
+ */
137
+ let debugPackage = envOrDefaultPackage();
138
+ export function slackDebugPackage() {
139
+ return debugPackage;
140
+ }
141
+ export function setSlackDebugPackage(pkg) {
142
+ debugPackage = pkg;
143
+ }
144
+ /** Back to env-or-default, for a device switch. A lost request keeps the armed package. */
145
+ export function resetSlackDebugPackage() {
146
+ debugPackage = envOrDefaultPackage();
147
+ }
94
148
  /**
95
149
  * Host-side ceiling on a single response we forward into the model context. A
96
150
  * proxied device response (large trace/clog payloads) or a session-spool query
@@ -38,7 +38,7 @@ export declare function resetDbState(): void;
38
38
  * every switch rather than being structurally impossible. process.env.ANDROID_SERIAL is
39
39
  * the same pin every adb call site in this file already targets (see pin() in android.ts);
40
40
  * "single" covers a single-device host with no pin set, matching the existing "single"
41
- * fallback for an unset user.
41
+ * fallback for an unset user. The package is in the name for the same reason as the serial.
42
42
  */
43
43
  export declare function localPath(name: string, user: string): string;
44
44
  /**
package/dist/shared/db.js CHANGED
@@ -19,9 +19,7 @@ import fs from "fs";
19
19
  import os from "os";
20
20
  import path from "path";
21
21
  import { resolveAdbPath } from "./android.js";
22
- import { SLACK_DEBUG_PKG } from "./constants.js";
23
- /** The debug build whose sandbox we can `run-as` into. */
24
- const DB_PKG = SLACK_DEBUG_PKG;
22
+ import { DEFAULT_DEBUG_PKG, slackDebugPackage } from "./constants.js";
25
23
  /** Dedicated tmp dir for pulled DB copies. Cleaned on start/stop; files written 0600. Scoped by a per-process key so concurrent readers do not collide. */
26
24
  let DB_TMP = path.join(os.tmpdir(), "slack-radar-db");
27
25
  /**
@@ -144,7 +142,7 @@ function userHasBuild(user) {
144
142
  try {
145
143
  runAdb([
146
144
  "shell",
147
- `run-as ${DB_PKG} ${user ? "--user " + user : ""} ls databases >/dev/null 2>&1 && echo ok`,
145
+ `run-as ${slackDebugPackage()} ${user ? "--user " + user : ""} ls databases >/dev/null 2>&1 && echo ok`,
148
146
  ]);
149
147
  return true;
150
148
  }
@@ -163,15 +161,21 @@ function userHasBuild(user) {
163
161
  * it once and reuse; resetDbState() clears it for a device/profile change.
164
162
  */
165
163
  let cachedUsers = null;
164
+ // The list belongs to one package: another debug build has its own set of profiles.
165
+ let cachedUsersPkg = null;
166
166
  export function availableUsers() {
167
- if (cachedUsers)
167
+ if (cachedUsers && cachedUsersPkg === slackDebugPackage())
168
168
  return cachedUsers;
169
+ cachedUsers = null;
169
170
  const ids = deviceUserIds();
170
171
  const found = ids.filter(userHasBuild);
171
172
  // Fallback for an older adb / odd `pm` output: try the no-flag form.
172
173
  const resolved = found.length ? found : userHasBuild("") ? [""] : [];
173
- if (resolved.length)
174
- cachedUsers = resolved; // only cache a successful probe
174
+ if (resolved.length) {
175
+ // only cache a successful probe
176
+ cachedUsers = resolved;
177
+ cachedUsersPkg = slackDebugPackage();
178
+ }
175
179
  return resolved;
176
180
  }
177
181
  /** `--user N` flag for a resolved user, or "" for the single-user case. */
@@ -205,7 +209,7 @@ function assertSafeName(name) {
205
209
  * every switch rather than being structurally impossible. process.env.ANDROID_SERIAL is
206
210
  * the same pin every adb call site in this file already targets (see pin() in android.ts);
207
211
  * "single" covers a single-device host with no pin set, matching the existing "single"
208
- * fallback for an unset user.
212
+ * fallback for an unset user. The package is in the name for the same reason as the serial.
209
213
  */
210
214
  // Exported for testability only (mirrors assertReadOnlyQuery/isExplainQuery below);
211
215
  // callers within this file use it directly.
@@ -213,7 +217,10 @@ export function localPath(name, user) {
213
217
  const safeName = name.replace(/[^A-Za-z0-9._-]/g, "_");
214
218
  const safeUser = (user || "single").replace(/[^A-Za-z0-9._-]/g, "_");
215
219
  const safeSerial = (process.env.ANDROID_SERIAL || "single").replace(/[^A-Za-z0-9._-]/g, "_");
216
- return path.join(DB_TMP, `d${safeSerial}-u${safeUser}-${safeName}.sqlite`);
220
+ // Two debug builds hold different stores under the same user and name. The default build
221
+ // keeps the plain name so copies named before the package could change stay valid.
222
+ const pkgPart = slackDebugPackage() === DEFAULT_DEBUG_PKG ? "" : `-p${slackDebugPackage().replace(/[^A-Za-z0-9._]/g, "_")}`;
223
+ return path.join(DB_TMP, `d${safeSerial}-u${safeUser}${pkgPart}-${safeName}.sqlite`);
217
224
  }
218
225
  /**
219
226
  * Resolve the Android user to target. The dashboard passes the profile it is bound to
@@ -223,7 +230,7 @@ export function localPath(name, user) {
223
230
  function resolveUser(user) {
224
231
  const available = availableUsers();
225
232
  if (!available.length) {
226
- throw new Error(`cannot run-as ${DB_PKG}. Is the debug build installed and is a device connected?`);
233
+ throw new Error(`cannot run-as ${slackDebugPackage()}. Is the debug build installed and is a device connected?`);
227
234
  }
228
235
  if (user != null && available.includes(user))
229
236
  return user;
@@ -241,12 +248,12 @@ export function listDatabases(user) {
241
248
  // profile change clears it via resetDbState() (wired to /enable / reconnect).
242
249
  const available = availableUsers();
243
250
  if (!available.length) {
244
- throw new Error(`cannot run-as ${DB_PKG}. Is the debug build installed and is a device connected?`);
251
+ throw new Error(`cannot run-as ${slackDebugPackage()}. Is the debug build installed and is a device connected?`);
245
252
  }
246
253
  const u = user != null && available.includes(user) ? user : available[0];
247
254
  const out = runAdb([
248
255
  "shell",
249
- `run-as ${DB_PKG} ${userFlag(u)} ls -1 databases`,
256
+ `run-as ${slackDebugPackage()} ${userFlag(u)} ls -1 databases`,
250
257
  ]).toString();
251
258
  const names = out
252
259
  .split("\n")
@@ -340,7 +347,7 @@ export async function pullDatabase(name, user, force = false) {
340
347
  // every other tab, the stream, and /health for the duration of the pull).
341
348
  bytes = await runAdbAsync([
342
349
  "exec-out",
343
- `run-as ${DB_PKG} ${userFlag(u)} cat databases/${name}`,
350
+ `run-as ${slackDebugPackage()} ${userFlag(u)} cat databases/${name}`,
344
351
  ]);
345
352
  }
346
353
  catch {
@@ -370,7 +377,7 @@ export async function pullDatabase(name, user, force = false) {
370
377
  fs.rmSync(sidecar, { force: true });
371
378
  const sb = await runAdbAsync([
372
379
  "exec-out",
373
- `run-as ${DB_PKG} ${userFlag(u)} cat databases/${name}${ext}`,
380
+ `run-as ${slackDebugPackage()} ${userFlag(u)} cat databases/${name}${ext}`,
374
381
  ]);
375
382
  if (sb && sb.length > 0)
376
383
  fs.writeFileSync(sidecar, sb, { mode: 0o600 });
@@ -19,9 +19,7 @@
19
19
  * applied before return.
20
20
  */
21
21
  import { execFileSync } from "child_process";
22
- import { SLACK_DEBUG_PKG } from "./constants.js";
23
- /** The debug build whose sandbox we can `run-as` into. */
24
- const LOG_PKG = SLACK_DEBUG_PKG;
22
+ import { slackDebugPackage } from "./constants.js";
25
23
  /** Number of rolling log files DebugLogger maintains (debug.log0..debug.log5). */
26
24
  const LOG_FILE_COUNT = 6;
27
25
  const ADB_MAX_BUFFER = 16 * 1024 * 1024; // total buffer is ~1.5MB; headroom for safety.
@@ -75,7 +73,7 @@ export function readDebugLogBuffer(adbPath, user) {
75
73
  // which exits 0 with the helper error in stdout).
76
74
  const runAs = (userFlag) => {
77
75
  try {
78
- return execFileSync(adbPath, ["exec-out", `run-as ${LOG_PKG} ${userFlag}sh -c 'cat ${catList} 2>/dev/null'`], {
76
+ return execFileSync(adbPath, ["exec-out", `run-as ${slackDebugPackage()} ${userFlag}sh -c 'cat ${catList} 2>/dev/null'`], {
79
77
  timeout: 10000,
80
78
  maxBuffer: ADB_MAX_BUFFER,
81
79
  encoding: "utf-8",
@@ -1,4 +1,30 @@
1
- import type { ProcessState } from "./transport.js";
1
+ import type { ArgvReason, ProcessState } from "./transport.js";
2
+ /** What pinned a package the pick only checks: the env override, or the build this session armed. */
3
+ export type PinReason = "override" | "held";
4
+ export declare function noDebugBuildRunningMessage(userId: string | null, pkg?: string, reason?: PinReason): string;
5
+ export declare function foreignRadarOwnerMessage(armedPackage: string, owner: string): string;
6
+ export declare class BareEnableError extends Error {
7
+ }
8
+ export declare class NoDebugBuildRunningError extends BareEnableError {
9
+ constructor(userId: string | null, pkg?: string, reason?: PinReason);
10
+ }
11
+ export declare class AmbiguousDebugPackageError extends BareEnableError {
12
+ constructor(userId: string, packages: readonly string[]);
13
+ }
14
+ export declare class UnknownDebugBuildError extends BareEnableError {
15
+ constructor(userId: string, packages: readonly string[]);
16
+ }
17
+ export declare class DebugPackageOverrideError extends BareEnableError {
18
+ constructor(message: string);
19
+ }
20
+ export declare function tokenViaArgvField(device: {
21
+ getLastTokenViaArgv?(): ArgvReason | null;
22
+ }): {
23
+ token_via_argv?: ArgvReason;
24
+ };
25
+ export declare class AndroidUserIdError extends BareEnableError {
26
+ constructor();
27
+ }
2
28
  /**
3
29
  * What to tell the user when activation was broadcast but the device server never
4
30
  * answered a ping.
@@ -1,3 +1,76 @@
1
+ // The one place the "broadcast landed, server stayed silent" message is worded. Both
2
+ // entry points reach this state -- the MCP _radar_session_enable flow and the dashboard's
3
+ // /enable route -- and a user who retries in the other surface must not be told a
4
+ // different story about the same device.
5
+ import { DEBUG_PACKAGE_ENV, debugPackageFromPsName } from "./constants.js";
6
+ // A null user means ps saw no debug build anywhere, so naming the fallback user 0 would be a guess.
7
+ // A pinned package is the one thing known, so the message names it and what pinned it: the
8
+ // variable, or the build this session armed (the way back is to enable again).
9
+ export function noDebugBuildRunningMessage(userId, pkg, reason = "override") {
10
+ if (pkg) {
11
+ const where = userId === null ? "" : ` in Android user ${userId}`;
12
+ if (reason === "held")
13
+ return `${pkg}, the build this session armed, is not running${where}; enable again`;
14
+ return `${pkg} (set by ${DEBUG_PACKAGE_ENV}) is not running${where}; open it, pick its profile with list_profiles, or unset the variable`;
15
+ }
16
+ return userId === null
17
+ ? "no debug build of the Slack app is running; open it and retry"
18
+ : `no debug build of the Slack app is running in Android user ${userId}; open it there and retry`;
19
+ }
20
+ // The ping body can be large and lands in a tool result, so the owner's name is printed only
21
+ // when it looks like a Slack debug package; anything else is "another app".
22
+ export function foreignRadarOwnerMessage(armedPackage, owner) {
23
+ if (debugPackageFromPsName(owner) !== owner) {
24
+ return `Radar on this device is served by another app, not the ${armedPackage} this session armed. ` +
25
+ `Force-stop that app, or disable Radar in the session that armed it, then enable again.`;
26
+ }
27
+ return `Radar on this device is served by ${owner}, not the ${armedPackage} this session armed. ` +
28
+ `Force-stop ${owner}, or disable Radar in the session that armed it, then enable again; ` +
29
+ `or set ${DEBUG_PACKAGE_ENV}=${owner} to read that build instead.`;
30
+ }
31
+ // Errors whose message already tells the user what to do, so every surface shows them bare.
32
+ export class BareEnableError extends Error {
33
+ }
34
+ // Callers branch on the type, never on the sentence.
35
+ export class NoDebugBuildRunningError extends BareEnableError {
36
+ constructor(userId, pkg, reason) {
37
+ super(noDebugBuildRunningMessage(userId, pkg, reason));
38
+ this.name = "NoDebugBuildRunningError";
39
+ }
40
+ }
41
+ // Says what ps saw. It never claims a build is missing, because several are running.
42
+ export class AmbiguousDebugPackageError extends BareEnableError {
43
+ constructor(userId, packages) {
44
+ super(`Slack debug builds are running for user ${userId}: ${packages.join(", ")}. ` +
45
+ `Set ${DEBUG_PACKAGE_ENV} to the one to arm, in the slack-radar MCP server config, and restart the MCP.`);
46
+ this.name = "AmbiguousDebugPackageError";
47
+ }
48
+ }
49
+ // A Slack debug process is on screen, so "no debug build is running" would be false.
50
+ export class UnknownDebugBuildError extends BareEnableError {
51
+ constructor(userId, packages) {
52
+ super(`a Slack debug build ${packages.join(", ")} is running in Android user ${userId} but is not a known flavour; ` +
53
+ `set ${DEBUG_PACKAGE_ENV} to target it`);
54
+ this.name = "UnknownDebugBuildError";
55
+ }
56
+ }
57
+ export class DebugPackageOverrideError extends BareEnableError {
58
+ constructor(message) {
59
+ super(message);
60
+ this.name = "DebugPackageOverrideError";
61
+ }
62
+ }
63
+ // Absent unless the token went over the command line, so a clean enable stays quiet.
64
+ export function tokenViaArgvField(device) {
65
+ const reason = device.getLastTokenViaArgv?.();
66
+ return reason ? { token_via_argv: reason } : {};
67
+ }
68
+ export class AndroidUserIdError extends BareEnableError {
69
+ constructor() {
70
+ super("user_id must be a decimal Android user id (list_profiles shows them)");
71
+ this.name = "AndroidUserIdError";
72
+ }
73
+ }
1
74
  /**
2
75
  * What to tell the user when activation was broadcast but the device server never
3
76
  * answered a ping.
@@ -10,7 +10,8 @@
10
10
  * no stream was attached — the user sees their log count shrink on a tab switch.
11
11
  *
12
12
  * This module fixes that the way Android Studio does: ONE capture process per
13
- * device for the whole server session, feeding a bounded session ring buffer.
13
+ * device for the whole server session, feeding a bounded session ring buffer. A stop keeps
14
+ * the ring, and a later start resumes into it.
14
15
  * Each `/stream` connection subscribes as a listener and is first replayed the
15
16
  * entire retained buffer, then receives live lines. Switching tabs only
16
17
  * adds/removes a listener; the underlying capture and its history are untouched.
@@ -11,7 +11,23 @@ import path from "path";
11
11
  * later. Capturing to a local file from session-enable onward preserves
12
12
  * everything from the enable moment forward.
13
13
  *
14
- * Lifecycle: startCapture on activate, stopCapture on resetState/disable.
14
+ * Starts through ensureLogCapture, a no-op while a child is live:
15
+ * - A landed activate (recordActivateSuccess).
16
+ * - A landed activate_for_user, same profile or not (activateForUser).
17
+ * - An accepted repeat enable (createEnabler).
18
+ * Restarts on a fresh file:
19
+ * - A different or unknown prior profile (activateForUser).
20
+ * - Size rotation (rotateCaptureIfNeeded below).
21
+ * Stops:
22
+ * - Disable (handleSessionDisable) or device switch (onDeviceSwitch).
23
+ * - A full enable that ends disabled (runSessionEnable).
24
+ * - Its idle timer (rescheduleIdleTimer).
25
+ * - The child's own exit (startCapture).
26
+ * - MCP exit (registerCleanup).
27
+ * Survives resetState, the device-side idle timeout, a failed broadcast,
28
+ * any same-device enable that ends enabled, a thrown enable (the catch in
29
+ * createEnabler) and the self-heal auto-disables, which flip
30
+ * sessionEnabled false without stopping the capture.
15
31
  */
16
32
  const LOG_DIR = path.join(os.homedir(), ".slack-radar", "logs");
17
33
  const ROTATION_BYTES = 100 * 1024 * 1024;
@@ -13,10 +13,9 @@
13
13
  */
14
14
  import { execFileSync, execFile } from "child_process";
15
15
  import { promisify } from "util";
16
- import { SLACK_DEBUG_PKG } from "./constants.js";
16
+ import { slackDebugPackage } from "./constants.js";
17
17
  import { detectRunAsError } from "./debug-log.js";
18
18
  import { availableUsers } from "./db.js";
19
- const PREFS_PKG = SLACK_DEBUG_PKG;
20
19
  const ADB_MAX_BUFFER = 2 * 1024 * 1024; // prefs can be large; user 10 observed 1.2MB total
21
20
  // ASYNC, not execFileSync: Node is single-threaded, so a blocking adb call freezes the whole
22
21
  // event loop -- every other in-flight HTTP request (a file click, /health) queues behind it.
@@ -74,7 +73,7 @@ export function listPrefsFiles(adbPath, user) {
74
73
  try {
75
74
  const resolvedUser = resolveUser(user);
76
75
  const userFlag = `--user ${resolvedUser} `;
77
- const out = execFileSync(adbPath, ["shell", `run-as ${PREFS_PKG} ${userFlag}ls -la shared_prefs/`], { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8", stdio: LIST_STDIO });
76
+ const out = execFileSync(adbPath, ["shell", `run-as ${slackDebugPackage()} ${userFlag}ls -la shared_prefs/`], { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8", stdio: LIST_STDIO });
78
77
  const runAsErr = detectRunAsError(out);
79
78
  if (runAsErr) {
80
79
  // Try without user flag as fallback (see debug-log.ts for rationale). Which user this
@@ -82,7 +81,7 @@ export function listPrefsFiles(adbPath, user) {
82
81
  // profile it just failed to reach) — report "" (db.ts's convention for "ambiguous/
83
82
  // implicit user") rather than mislabeling the result with the requested id.
84
83
  try {
85
- const retry = execFileSync(adbPath, ["shell", `run-as ${PREFS_PKG} ls -la shared_prefs/`], { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8", stdio: LIST_STDIO });
84
+ const retry = execFileSync(adbPath, ["shell", `run-as ${slackDebugPackage()} ls -la shared_prefs/`], { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8", stdio: LIST_STDIO });
86
85
  if (!detectRunAsError(retry)) {
87
86
  return parseListOutput(retry, "");
88
87
  }
@@ -171,7 +170,7 @@ export async function readPrefsFile(adbPath, name, user) {
171
170
  // intended behavior of reading it fully and truncating the string afterward.
172
171
  const out = await runAdbAsync(adbPath, [
173
172
  "exec-out",
174
- `run-as ${PREFS_PKG} ${userFlag}cat shared_prefs/${name}`,
173
+ `run-as ${slackDebugPackage()} ${userFlag}cat shared_prefs/${name}`,
175
174
  ]);
176
175
  return { out, denied: !!detectRunAsError(out) };
177
176
  }
@@ -38,7 +38,9 @@ transport, surface = "mcp") {
38
38
  }, idleMs);
39
39
  };
40
40
  try {
41
- req = http.get({ host, port, path: requestPath, headers: radarTokenHeaderFor(transport, surface) }, (res) => {
41
+ // agent: false so no request rides a pooled socket the device already closed; that reads
42
+ // as a dead device (ECONNRESET) and costs a re-arm.
43
+ req = http.get({ host, port, path: requestPath, agent: false, headers: radarTokenHeaderFor(transport, surface) }, (res) => {
42
44
  // Decode once at the end: a multi-byte UTF-8 character can split across chunks.
43
45
  const chunks = [];
44
46
  let bytes = 0;
@@ -9,6 +9,7 @@ export declare function switchboardSessionPath(sessionId: number, limit: number,
9
9
  export declare function newestSwitchboardSessionIds(list: unknown): number[];
10
10
  export declare function switchboardPageEvents(session: unknown): Record<string, unknown>[];
11
11
  export declare function nonNegativeIntArg(v: unknown): number | null;
12
+ export declare const SWITCHBOARD_DEVICE_UNREACHABLE_ERROR = "Device unreachable. Is Radar armed?";
12
13
  export declare const SWITCHBOARD_EXPORT_MAX_LIMIT = 2000;
13
14
  export declare const SWITCHBOARD_DEVICE_RING_CAP = 10000;
14
15
  export declare const SWITCHBOARD_EXPORT_MAX_PAGES = 25;
@@ -70,6 +70,8 @@ export function nonNegativeIntArg(v) {
70
70
  }
71
71
  return Number.isSafeInteger(n) && n >= 0 ? n : null;
72
72
  }
73
+ // The export error for a device that never answered; the MCP swaps it for the enable error when it has one.
74
+ export const SWITCHBOARD_DEVICE_UNREACHABLE_ERROR = "Device unreachable. Is Radar armed?";
73
75
  // The device's per-request cap on a session detail limit.
74
76
  export const SWITCHBOARD_EXPORT_MAX_LIMIT = 2000;
75
77
  // The device's per-session ring cap (docs/wire-contract.md). Eviction checks compare against
@@ -462,7 +464,7 @@ getNewestHostSessionId, sender, surface = "mcp") {
462
464
  : outcome.reason === "not-found"
463
465
  ? `No switchboard session ${outcome.sessionId} on the device (unknown id, or the device already dropped it).`
464
466
  : outcome.reason === "unreachable"
465
- ? "Device unreachable. Is Radar armed?"
467
+ ? SWITCHBOARD_DEVICE_UNREACHABLE_ERROR
466
468
  : outcome.reason === "bad-response" && outcome.sessionId !== undefined
467
469
  ? `The device reply was too large to read (over the ${SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES / (1024 * 1024)} MB size cap), and this process holds no live stream copy of the call.`
468
470
  : "The device answered, but not with anything this export could use.";
@@ -7,7 +7,10 @@
7
7
  * interact only through this interface.
8
8
  */
9
9
  import type { LogSession } from "./log-session.js";
10
+ import type { BareEnableError } from "./enable-diagnosis.js";
10
11
  import type { TokenFileError } from "./radar-token.js";
12
+ /** Why an enable sent the token on the command line instead of the token file. */
13
+ export type ArgvReason = "the token file write failed" | "this build has no token file reader; update it";
11
14
  /** Which underlying source served a getRecentLogs result. */
12
15
  export type LogSource = "app_buffer" | "logcat_capture" | "logcat_ring" | "ios_unified_capture";
13
16
  /**
@@ -117,6 +120,23 @@ export interface DeviceTransport {
117
120
  * Android adb forward can otherwise be mistaken for the selected Simulator app.
118
121
  */
119
122
  acceptsRadarPeer?(ping: Record<string, unknown>): boolean;
123
+ /**
124
+ * The package of a different build that owns the Radar listener, or null when the ping does
125
+ * not show one. Android has one device-side socket, so a second debug build cannot bind it
126
+ * and the ping then answers for the build that did. Kept apart from acceptsRadarPeer: that
127
+ * method makes the enable and the web arm treat a mismatch as "no listener", which would
128
+ * refuse a cold Android enable and change which sources are offered.
129
+ */
130
+ foreignRadarOwner?(ping: Record<string, unknown>): string | null;
131
+ /**
132
+ * Take the package that owns the Radar listener as this transport's own build, when that is
133
+ * safe. A dashboard started by hand on a device another session already armed has no
134
+ * way to learn which build it is reading, and the ping names it. No-op when the transport
135
+ * cannot adopt.
136
+ */
137
+ adoptRadarOwner?(ping: Record<string, unknown>): void;
138
+ /** Forget the build a past arm decided, at the start of a fresh enable or profile switch. */
139
+ releaseDebugBuild?(): void;
120
140
  /**
121
141
  * What the user should do when the app's Radar listener does not answer, for transports
122
142
  * whose default advice ("check adb devices") does not apply. Absent keeps that default.
@@ -248,8 +268,18 @@ export interface DeviceTransport {
248
268
  * implementations may omit it.
249
269
  */
250
270
  getLastActivateError?(): string | null;
271
+ /**
272
+ * Starts the transport's own log capture when none is live. Called after an
273
+ * activate or profile broadcast lands, and by a repeat enable the fast path
274
+ * accepts, since that path skips activate.
275
+ */
276
+ ensureLogCapture?(): void;
251
277
  /** No broadcast went out, so callers report the file problem without probing the device. */
252
278
  getLastActivateTokenFileError?(): TokenFileError | null;
279
+ /** The last enable error whose message already says what to do (no debug build, two builds, a bad package override), shown plain. */
280
+ getLastActivateBareError?(): BareEnableError | null;
281
+ /** Why the last enable sent the token over the command line, or null when it went through the file. */
282
+ getLastTokenViaArgv?(): ArgvReason | null;
253
283
  /**
254
284
  * State of the target app process on the device, checked fresh (not cached). Lets the
255
285
  * enable flow tell a confirmed "stopped" apart from "the probe could not tell" when the
@@ -197,3 +197,21 @@ export declare function runSelfHealPrecheck(): void;
197
197
  /** The awaitable core of runSelfHealPrecheck(), exported so a test can await its outcome
198
198
  * directly instead of polling for the fire-and-forget wrapper to finish. */
199
199
  export declare function runSelfHealPrecheckAsync(): Promise<void>;
200
+ export interface UpdateCheckResult {
201
+ installed: string | null;
202
+ latest: string | null;
203
+ updateAvailable: boolean;
204
+ /** The installed bundle is already newer than the app asking, so a restart (no install) picks it up. */
205
+ restartAvailable?: boolean;
206
+ error?: string;
207
+ }
208
+ /** Whether the registry has a newer Radar than the installed app, or the installed app is already
209
+ * ahead of `runningVersion` and just needs a restart. Never throws; failures land in `error`. */
210
+ export declare function checkForUpdate(runningVersion?: string): Promise<UpdateCheckResult>;
211
+ export interface UpdateNowResult {
212
+ updated: boolean;
213
+ error?: string;
214
+ }
215
+ /** Entry point for `install-app --update-now`. Reuses the self-heal rebuild, so an explicit update
216
+ * stays subject to the same npm config as the background one. */
217
+ export declare function runUpdateNow(): Promise<void>;
@@ -571,6 +571,13 @@ function buildIcns(resourcesDir) {
571
571
  fs.rmSync(iconset, { recursive: true, force: true });
572
572
  }
573
573
  }
574
+ // buildSwiftApp()'s compile is the one step in here that can be slow for a structural reason, and it
575
+ // is bounded at 60s by its own execFileSync timeout, which leaves about 60s of slack against this
576
+ // threshold. The rest is unbounded but local and sub-second in practice (sips, iconutil, lsregister).
577
+ // A lock older than this can only be a crash leftover, the process that made it died before reaching
578
+ // the finally below. Without this, one crashed install would wedge every self-heal check forever,
579
+ // since nothing else ever removes the lock file.
580
+ const STALE_LOCK_MS = 2 * 60 * 1000;
574
581
  /**
575
582
  * Create (or replace) the launcher app. Returns its path.
576
583
  *
@@ -596,13 +603,6 @@ export function installMacApp() {
596
603
  // staging path -- for the self-heal caller that just means trying again next launch.
597
604
  fs.mkdirSync(dir, { recursive: true });
598
605
  const lockPath = path.join(dir, ".install.lock");
599
- // buildSwiftApp()'s compile is the one step in here that can be slow for a structural reason, and it
600
- // is bounded at 60s by its own execFileSync timeout, which leaves about 60s of slack against this
601
- // threshold. The rest is unbounded but local and sub-second in practice (sips, iconutil, lsregister).
602
- // A lock older than this can only be a crash leftover, the process that made it died before reaching
603
- // the finally below. Without this, one crashed install would wedge every self-heal check forever,
604
- // since nothing else ever removes the lock file.
605
- const STALE_LOCK_MS = 2 * 60 * 1000;
606
606
  let lockFd;
607
607
  try {
608
608
  lockFd = fs.openSync(lockPath, "wx");
@@ -1061,3 +1061,56 @@ export async function runSelfHealPrecheckAsync() {
1061
1061
  writeSelfHealState({ checkedAt, outcome: "error", toVersion: RADAR_VERSION, error: e.message });
1062
1062
  }
1063
1063
  }
1064
+ /** Whether the registry has a newer Radar than the installed app, or the installed app is already
1065
+ * ahead of `runningVersion` and just needs a restart. Never throws; failures land in `error`. */
1066
+ export async function checkForUpdate(runningVersion = "unknown") {
1067
+ const read = readInstalledVersion();
1068
+ if (!read.found) {
1069
+ return { installed: null, latest: null, updateAvailable: false, error: "Slack Radar.app is not installed" };
1070
+ }
1071
+ if ((compareVersions(read.plain, runningVersion.split(/[-+]/, 1)[0]) ?? 0) > 0) {
1072
+ return { installed: read.version, latest: null, updateAvailable: false, restartAvailable: true };
1073
+ }
1074
+ const latest = await checkLatestPublishedVersion();
1075
+ if (latest === null) {
1076
+ return { installed: read.version, latest: null, updateAvailable: false, error: "could not reach the npm registry" };
1077
+ }
1078
+ const comparison = compareVersions(latest, read.plain);
1079
+ return { installed: read.version, latest, updateAvailable: comparison !== null && comparison > 0 };
1080
+ }
1081
+ /** Entry point for `install-app --update-now`. Reuses the self-heal rebuild, so an explicit update
1082
+ * stays subject to the same npm config as the background one. */
1083
+ export async function runUpdateNow() {
1084
+ const startedAt = new Date().toISOString();
1085
+ const before = readInstalledVersion();
1086
+ const running = (process.env.RADAR_APP_VERSION ?? "").split(/[-+]/, 1)[0];
1087
+ // Updated means newer than the running app, or than the copy before the install when no version was baked in.
1088
+ const base = parseVersion(running) ? running : before.found ? before.plain : null;
1089
+ const isUpdated = (r) => r.found && base !== null && (compareVersions(r.plain, base) ?? 0) > 0;
1090
+ await runSelfHealPrecheckAsync();
1091
+ let after = readInstalledVersion();
1092
+ // A fresh lock means the launch self-heal beat our rebuild to it, so wait for it to finish.
1093
+ const lock = path.join(appDir(), ".install.lock");
1094
+ while (!isUpdated(after) && Date.now() - (fs.statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? 0) < STALE_LOCK_MS) {
1095
+ await new Promise((resolve) => setTimeout(resolve, 250));
1096
+ after = readInstalledVersion();
1097
+ }
1098
+ const result = { updated: isUpdated(after) };
1099
+ if (!result.updated) {
1100
+ const state = readSelfHealState();
1101
+ const recorded = state && state.checkedAt >= startedAt && state.outcome === "error" ? state.error : undefined;
1102
+ if (recorded !== undefined) {
1103
+ result.error = recorded;
1104
+ }
1105
+ else {
1106
+ // No recorded error: the rebuild resolved a version equal to what's already installed, the
1107
+ // signature of an npm min-release-age hold. Confirm against the registry before naming it.
1108
+ const latest = after.found ? await checkLatestPublishedVersion() : null;
1109
+ result.error =
1110
+ after.found && latest !== null && (compareVersions(latest, after.plain) ?? 0) > 0
1111
+ ? `Your npm config may be holding Radar back on ${after.version}. The published version is ${latest}.`
1112
+ : "The app was not updated. See ~/Library/Logs/slack-radar-dashboard.log for the log.";
1113
+ }
1114
+ }
1115
+ console.log(JSON.stringify(result));
1116
+ }