@slack/radar-mcp 1.14.0 → 1.17.1

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 (49) hide show
  1. package/README.md +15 -3
  2. package/dist/mcp/db-tools.js +23 -0
  3. package/dist/mcp/dispatch.d.ts +4 -0
  4. package/dist/mcp/dispatch.js +26 -0
  5. package/dist/mcp/index.js +105 -37
  6. package/dist/mcp/platform-detect.d.ts +110 -0
  7. package/dist/mcp/platform-detect.js +246 -0
  8. package/dist/mcp/prefs-tools.d.ts +4 -3
  9. package/dist/mcp/prefs-tools.js +26 -3
  10. package/dist/mcp/session-enable.js +19 -1
  11. package/dist/mcp/snapshot.js +4 -1
  12. package/dist/mcp/sources-gate.js +6 -3
  13. package/dist/mcp/tools.d.ts +11 -0
  14. package/dist/mcp/tools.js +38 -0
  15. package/dist/mcp/web-child-env.d.ts +1 -0
  16. package/dist/mcp/web-child-env.js +32 -0
  17. package/dist/shared/android.d.ts +89 -1
  18. package/dist/shared/android.js +352 -78
  19. package/dist/shared/constants.d.ts +25 -1
  20. package/dist/shared/constants.js +27 -1
  21. package/dist/shared/db.js +11 -2
  22. package/dist/shared/debug-log.js +6 -1
  23. package/dist/shared/enable-diagnosis.d.ts +28 -0
  24. package/dist/shared/enable-diagnosis.js +41 -0
  25. package/dist/shared/prefs.d.ts +0 -5
  26. package/dist/shared/prefs.js +6 -2
  27. package/dist/shared/screen.d.ts +46 -9
  28. package/dist/shared/screen.js +74 -11
  29. package/dist/shared/transport.d.ts +62 -5
  30. package/dist/shared/webapp.d.ts +50 -0
  31. package/dist/shared/webapp.js +65 -0
  32. package/dist/web/bin.js +5 -1
  33. package/dist/web/install-app.d.ts +87 -0
  34. package/dist/web/install-app.js +703 -0
  35. package/dist/web/macapp/RadarApp.swift +466 -0
  36. package/dist/web/public/icons/radar-1024.png +0 -0
  37. package/dist/web/public/icons/radar.svg +40 -0
  38. package/dist/web/public/index.html +41 -1
  39. package/dist/web/public/next/app.js +19 -4
  40. package/dist/web/public/next/db.js +145 -5
  41. package/dist/web/public/next/feed.js +18 -0
  42. package/dist/web/public/next/hooks.js +10 -1
  43. package/dist/web/public/next/registry.js +18 -10
  44. package/dist/web/public/next/screen.js +147 -43
  45. package/dist/web/public/next/store.js +393 -51
  46. package/dist/web/public/next/toast.js +134 -0
  47. package/dist/web/server.d.ts +26 -1
  48. package/dist/web/server.js +341 -113
  49. package/package.json +2 -2
@@ -26,8 +26,26 @@ export const RADAR_VERSION = (() => {
26
26
  * exists for tests only: stream lifecycle tests stand up a local server on an
27
27
  * ephemeral port so they cannot collide with a real forwarded device on 8099.
28
28
  * Set before module load, like SLACK_RADAR_WEB_PORT.
29
+ *
30
+ * `let`, not `const`: the webapp auto-detect path (mcp/platform-detect.ts, wired from
31
+ * createTransport()) needs to repoint every existing RADAR_HOST:RADAR_PORT caller
32
+ * (radarRequest, android.ts's adb forward target) at the webapp dev server's port
33
+ * AFTER this module has already loaded and android callers have already captured the
34
+ * initial value via import. setRadarPort() is the only sanctioned way to change it; the
35
+ * initial-value expression below must stay exactly as it is today so android's
36
+ * zero-config default (8099) never changes.
29
37
  */
30
- export const RADAR_PORT = Number(process.env.SLACK_RADAR_DEVICE_PORT) || 8099;
38
+ export let RADAR_PORT = Number(process.env.SLACK_RADAR_DEVICE_PORT) || 8099;
39
+ /**
40
+ * Override RADAR_PORT after module load. Called exactly once, only by the webapp
41
+ * auto-detect/explicit-platform path in mcp/index.ts's createTransport() -- never on the
42
+ * android path, so android's RADAR_PORT resolution stays byte-for-byte identical to
43
+ * today. ES module `let` exports are live bindings, so every existing importer (stream.ts,
44
+ * android.ts, index.ts's radarRequest) sees the new value immediately, with no re-import.
45
+ */
46
+ export function setRadarPort(port) {
47
+ RADAR_PORT = port;
48
+ }
31
49
  /** Host address for the forwarded connection. */
32
50
  export const RADAR_HOST = "127.0.0.1";
33
51
  /** Max events to retain in each local SSE buffer. */
@@ -52,6 +70,14 @@ export const MAX_LOG_SESSION_BUFFER = 20000;
52
70
  * `SLACK_RADAR_WEB_PORT` env override.
53
71
  */
54
72
  export const WEB_PORT_DEFAULT = 8100;
73
+ /**
74
+ * Default port the webapp Radar debug server listens on, matching
75
+ * webpack/util/default-dev-port.ts in the webapp repo. Hardcoded rather than imported: this
76
+ * package does not depend on the webapp repo. Separate constant from RADAR_PORT/WEB_PORT_DEFAULT
77
+ * -- it names the webapp target's OWN default, which platform-detect.ts probes before anything
78
+ * commits to redirecting RADAR_PORT at it.
79
+ */
80
+ export const WEBAPP_DEFAULT_PORT = 1989;
55
81
  /**
56
82
  * The Slack debug build whose sandbox the host can `run-as` into. Both the
57
83
  * on-device SQLite browser (db.ts) and the app log-buffer reader (debug-log.ts)
package/dist/shared/db.js CHANGED
@@ -47,9 +47,13 @@ function adbBin() {
47
47
  return p;
48
48
  }
49
49
  function runAdb(args, opts = {}) {
50
+ // Every caller reads the return value (toString() or the Buffer itself), so stdout
51
+ // stays "pipe"; stderr is "ignore" since no caller reads .stderr off a thrown error
52
+ // here, only catches and falls back — piping it would just leave it uncollected.
50
53
  return execFileSync(adbBin(), args, {
51
54
  timeout: 15000,
52
55
  maxBuffer: ADB_MAX_BUFFER,
56
+ stdio: ["ignore", "pipe", "ignore"],
53
57
  ...opts,
54
58
  });
55
59
  }
@@ -74,9 +78,11 @@ function runAdbAsync(args) {
74
78
  * binary, and only fall back to a working-but-fts5-less one if none has it (non-FTS DBs still
75
79
  * work there). Cached after first success.
76
80
  */
81
+ // Neither probe reads stdout or stderr; both only check whether the call throws.
82
+ const PROBE_STDIO = ["ignore", "ignore", "ignore"];
77
83
  function hasSqlite(bin) {
78
84
  try {
79
- execFileSync(bin, ["--version"], { timeout: 3000 });
85
+ execFileSync(bin, ["--version"], { timeout: 3000, stdio: PROBE_STDIO });
80
86
  return true;
81
87
  }
82
88
  catch {
@@ -86,7 +92,10 @@ function hasSqlite(bin) {
86
92
  function hasFts5(bin) {
87
93
  try {
88
94
  // throws "no such module: fts5" on a binary built without it
89
- execFileSync(bin, [":memory:", "CREATE VIRTUAL TABLE t USING fts5(x);"], { timeout: 3000 });
95
+ execFileSync(bin, [":memory:", "CREATE VIRTUAL TABLE t USING fts5(x);"], {
96
+ timeout: 3000,
97
+ stdio: PROBE_STDIO,
98
+ });
90
99
  return true;
91
100
  }
92
101
  catch {
@@ -75,7 +75,12 @@ export function readDebugLogBuffer(adbPath, user) {
75
75
  // which exits 0 with the helper error in stdout).
76
76
  const runAs = (userFlag) => {
77
77
  try {
78
- return execFileSync(adbPath, ["exec-out", `run-as ${LOG_PKG} ${userFlag}sh -c 'cat ${catList} 2>/dev/null'`], { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8" });
78
+ return execFileSync(adbPath, ["exec-out", `run-as ${LOG_PKG} ${userFlag}sh -c 'cat ${catList} 2>/dev/null'`], {
79
+ timeout: 10000,
80
+ maxBuffer: ADB_MAX_BUFFER,
81
+ encoding: "utf-8",
82
+ stdio: ["ignore", "pipe", "pipe"],
83
+ });
79
84
  }
80
85
  catch (err) {
81
86
  return err instanceof Error ? err : new Error(String(err));
@@ -0,0 +1,28 @@
1
+ import type { ProcessState } from "./transport.js";
2
+ /**
3
+ * What to tell the user when activation was broadcast but the device server never
4
+ * answered a ping.
5
+ *
6
+ * Only a confirmed "stopped" earns the sharper text. "unknown" means the probe could not
7
+ * reach the device (unplugged after the broadcast landed, unauthorized, adb dead) and the
8
+ * app may well be running fine, so it keeps the generic wording rather than asserting a
9
+ * launch is missing.
10
+ *
11
+ * The wording tracks what the probe actually looks for: a Slack process whose name
12
+ * contains "debug", which covers every debug flavour and deliberately no release or
13
+ * plain-internal build. Saying "no debug build" is therefore true, where "the Slack app is
14
+ * not running" is false for anyone whose com.Slack.internal dogfood build is on screen --
15
+ * and that reader is exactly who needs the debug-build hint.
16
+ */
17
+ export declare function deviceServerSilentError(processState: ProcessState): string;
18
+ /**
19
+ * Read a transport's process probe without letting it break the caller's own failure
20
+ * report. An absent method and a throwing one are both "unknown": a diagnostic that
21
+ * cannot answer must not turn into a claim about the app.
22
+ *
23
+ * @param timeoutMs Optional ceiling handed to the transport. Pass a short one when the
24
+ * failure is already known and this call only explains it.
25
+ */
26
+ export declare function readProcessState(device: {
27
+ processState?(timeoutMs?: number): ProcessState;
28
+ }, timeoutMs?: number): ProcessState;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What to tell the user when activation was broadcast but the device server never
3
+ * answered a ping.
4
+ *
5
+ * Only a confirmed "stopped" earns the sharper text. "unknown" means the probe could not
6
+ * reach the device (unplugged after the broadcast landed, unauthorized, adb dead) and the
7
+ * app may well be running fine, so it keeps the generic wording rather than asserting a
8
+ * launch is missing.
9
+ *
10
+ * The wording tracks what the probe actually looks for: a Slack process whose name
11
+ * contains "debug", which covers every debug flavour and deliberately no release or
12
+ * plain-internal build. Saying "no debug build" is therefore true, where "the Slack app is
13
+ * not running" is false for anyone whose com.Slack.internal dogfood build is on screen --
14
+ * and that reader is exactly who needs the debug-build hint.
15
+ */
16
+ export function deviceServerSilentError(processState) {
17
+ if (processState === "stopped") {
18
+ return ("Radar broadcast sent but the device server did not respond, and no debug build of " +
19
+ "the Slack app is running on the device. Radar only exists in debug builds, so launch " +
20
+ "one and retry. If it keeps stopping right after launch, that points at Radar's own " +
21
+ "activation code, not a missing launch.");
22
+ }
23
+ return ("Radar broadcast sent but the device server did not respond. Is a debug build with " +
24
+ "the slack-radar modules installed and running on the active profile?");
25
+ }
26
+ /**
27
+ * Read a transport's process probe without letting it break the caller's own failure
28
+ * report. An absent method and a throwing one are both "unknown": a diagnostic that
29
+ * cannot answer must not turn into a claim about the app.
30
+ *
31
+ * @param timeoutMs Optional ceiling handed to the transport. Pass a short one when the
32
+ * failure is already known and this call only explains it.
33
+ */
34
+ export function readProcessState(device, timeoutMs) {
35
+ try {
36
+ return device.processState?.(timeoutMs) ?? "unknown";
37
+ }
38
+ catch {
39
+ return "unknown";
40
+ }
41
+ }
@@ -11,11 +11,6 @@
11
11
  * state. This reader only returns files/keys/values to the caller (no host-side file
12
12
  * written), with a privacy note reminding the caller to review before sharing.
13
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
14
  export declare function listPrefsFiles(adbPath: string, user?: string): {
20
15
  user: string;
21
16
  files: {
@@ -64,13 +64,17 @@ function assertSafeUser(user) {
64
64
  * Via `run-as ... ls -la shared_prefs/` and parse name+size.
65
65
  * Returns null on run-as failure.
66
66
  */
67
+ // Both listPrefsFiles calls read the return value via detectRunAsError/parseListOutput, so
68
+ // stdout stays "pipe"; stderr is "ignore", matching this file's own catch-and-return-null
69
+ // handling (no caller here reads .stderr off a thrown error).
70
+ const LIST_STDIO = ["ignore", "pipe", "ignore"];
67
71
  export function listPrefsFiles(adbPath, user) {
68
72
  if (user)
69
73
  assertSafeUser(user);
70
74
  try {
71
75
  const resolvedUser = resolveUser(user);
72
76
  const userFlag = `--user ${resolvedUser} `;
73
- const out = execFileSync(adbPath, ["shell", `run-as ${PREFS_PKG} ${userFlag}ls -la shared_prefs/`], { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8" });
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 });
74
78
  const runAsErr = detectRunAsError(out);
75
79
  if (runAsErr) {
76
80
  // Try without user flag as fallback (see debug-log.ts for rationale). Which user this
@@ -78,7 +82,7 @@ export function listPrefsFiles(adbPath, user) {
78
82
  // profile it just failed to reach) — report "" (db.ts's convention for "ambiguous/
79
83
  // implicit user") rather than mislabeling the result with the requested id.
80
84
  try {
81
- const retry = execFileSync(adbPath, ["shell", `run-as ${PREFS_PKG} ls -la shared_prefs/`], { timeout: 10000, maxBuffer: ADB_MAX_BUFFER, encoding: "utf-8" });
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 });
82
86
  if (!detectRunAsError(retry)) {
83
87
  return parseListOutput(retry, "");
84
88
  }
@@ -38,11 +38,11 @@
38
38
  */
39
39
  import { type ChildProcess } from "child_process";
40
40
  /**
41
- * Remove all recorded mp4s from the screen tmp dir. Recordings capture sensitive
42
- * live screen content and must not linger across sessions on disk. Called on
41
+ * Remove all captures from the screen tmp dir. Recordings and screenshots both hold
42
+ * sensitive live screen content and must not linger across sessions on disk. Called on
43
43
  * resetScreenState() (device re-enable) and on process exit — the same posture the
44
- * DB-browser uses for its pulled copies. Scoped to the radar_screen_*.mp4 names this
45
- * module writes so it never deletes an unrelated file that landed in the dir.
44
+ * DB-browser uses for its pulled copies. Scoped to the names this module writes so it
45
+ * never deletes an unrelated file that landed in the dir.
46
46
  */
47
47
  export declare function cleanupRecordings(): void;
48
48
  /** Resolve an ffmpeg binary, or null if none is installed. Cached. */
@@ -195,12 +195,49 @@ export declare const SCREEN_BOUNDARY = "radarframe";
195
195
  export declare function startRecording(): string | null;
196
196
  export declare function stopRecording(L?: LiveCast): Promise<string | null>;
197
197
  /**
198
- * Resolve a recording for download. Restricted to the screen tmp dir AND to the
199
- * radar_screen_*.mp4 name this module writes: path.basename strips any directory
200
- * (no traversal), and the prefix/extension check means a download request can only
201
- * ever name a radar recording, never an arbitrary file that happened to land in the dir.
198
+ * Resolve a capture (recording or screenshot) for download. Restricted to the screen tmp
199
+ * dir AND to the names this module writes: path.basename strips any directory (no
200
+ * traversal), and the prefix/extension check means a download request can only ever name
201
+ * a radar capture, never an arbitrary file that happened to land in the dir.
202
202
  */
203
- export declare function recordingPath(file: string): string | null;
203
+ export declare function capturePath(file: string): string | null;
204
+ /**
205
+ * Why this reports which half failed instead of returning null for both: the caller turns a
206
+ * failure into user-facing text, and the two halves need different text. "is the device awake and
207
+ * connected?" is the right question when screencap came back empty and actively misleading when
208
+ * the phone answered fine and the HOST could not write the file (a full disk, a bad mode on the
209
+ * dir). Answering a disk problem with a question about the phone is the same dishonesty this
210
+ * two-phase route exists to remove.
211
+ */
212
+ export type ScreenshotSaveResult = {
213
+ ok: true;
214
+ path: string;
215
+ } | {
216
+ ok: false;
217
+ reason: "capture-failed";
218
+ } | {
219
+ ok: false;
220
+ reason: "write-failed";
221
+ detail: string;
222
+ };
223
+ /** The user-facing wording for each way a screenshot save can fail. */
224
+ export declare function screenshotSaveErrorMessage(result: Extract<ScreenshotSaveResult, {
225
+ ok: false;
226
+ }>): string;
227
+ /**
228
+ * Capture a screenshot and write it to the screen tmp dir.
229
+ *
230
+ * Writing to disk is what makes the outcome reportable. Streaming the PNG straight back as
231
+ * a Content-Disposition attachment gave the browser no way to distinguish a saved file from
232
+ * a 403 or a 502: the response never reaches page JavaScript, and a download navigation
233
+ * fires neither load nor error on the frame that requested it. Landing the bytes first
234
+ * turns "did this work" into an ordinary JSON answer, which is the same two-phase shape
235
+ * /screen/record/stop already uses.
236
+ *
237
+ * Same on-disk posture as a recording, and for the same reason: a screenshot is a full
238
+ * frame of whatever is on the phone, so the dir is owner-only and the file owner-read/write.
239
+ */
240
+ export declare function saveScreenshot(): Promise<ScreenshotSaveResult>;
204
241
  /** Reset detection + tear down any live cast. Called on device re-enable and shutdown. */
205
242
  export declare function resetScreenState(): void;
206
243
  /**
@@ -44,16 +44,23 @@ import { promisify } from "util";
44
44
  import { resolveAdbPath } from "./android.js";
45
45
  const SC_TMP = path.join(os.homedir(), ".slack-radar", "screen");
46
46
  /**
47
- * Remove all recorded mp4s from the screen tmp dir. Recordings capture sensitive
48
- * live screen content and must not linger across sessions on disk. Called on
47
+ * The only file names this module writes into the screen tmp dir, and therefore the only
48
+ * ones it will clean up or serve for download. Screenshots (png) joined recordings (mp4)
49
+ * here when screenshots became two-phase: a screenshot has to exist on disk for the
50
+ * outcome to be reportable before the browser is told to download it.
51
+ */
52
+ const CAPTURE_NAME = /^radar_screen_[\w-]+\.(mp4|png)$/;
53
+ /**
54
+ * Remove all captures from the screen tmp dir. Recordings and screenshots both hold
55
+ * sensitive live screen content and must not linger across sessions on disk. Called on
49
56
  * resetScreenState() (device re-enable) and on process exit — the same posture the
50
- * DB-browser uses for its pulled copies. Scoped to the radar_screen_*.mp4 names this
51
- * module writes so it never deletes an unrelated file that landed in the dir.
57
+ * DB-browser uses for its pulled copies. Scoped to the names this module writes so it
58
+ * never deletes an unrelated file that landed in the dir.
52
59
  */
53
60
  export function cleanupRecordings() {
54
61
  try {
55
62
  for (const f of fs.readdirSync(SC_TMP)) {
56
- if (/^radar_screen_[\w-]+\.mp4$/.test(f)) {
63
+ if (CAPTURE_NAME.test(f)) {
57
64
  try {
58
65
  fs.unlinkSync(path.join(SC_TMP, f));
59
66
  }
@@ -622,6 +629,10 @@ export function startLive(fps) {
622
629
  if (L.lastFrame && Date.now() - L.lastFrameTs > 350)
623
630
  pushFrame(L, L.lastFrame);
624
631
  }, 400);
632
+ // Same reasoning as orphanTimer above: a live cast that outlives normal teardown must
633
+ // not be the thing keeping the whole process alive.
634
+ if (typeof L.keepalive.unref === "function")
635
+ L.keepalive.unref();
625
636
  scLive = L;
626
637
  return L;
627
638
  }
@@ -747,18 +758,63 @@ export function stopRecording(L = scLive) {
747
758
  });
748
759
  }
749
760
  /**
750
- * Resolve a recording for download. Restricted to the screen tmp dir AND to the
751
- * radar_screen_*.mp4 name this module writes: path.basename strips any directory
752
- * (no traversal), and the prefix/extension check means a download request can only
753
- * ever name a radar recording, never an arbitrary file that happened to land in the dir.
761
+ * Resolve a capture (recording or screenshot) for download. Restricted to the screen tmp
762
+ * dir AND to the names this module writes: path.basename strips any directory (no
763
+ * traversal), and the prefix/extension check means a download request can only ever name
764
+ * a radar capture, never an arbitrary file that happened to land in the dir.
754
765
  */
755
- export function recordingPath(file) {
766
+ export function capturePath(file) {
756
767
  const base = path.basename(file);
757
- if (!/^radar_screen_[\w-]+\.mp4$/.test(base))
768
+ if (!CAPTURE_NAME.test(base))
758
769
  return null;
759
770
  const p = path.join(SC_TMP, base);
760
771
  return fs.existsSync(p) ? p : null;
761
772
  }
773
+ /** The user-facing wording for each way a screenshot save can fail. */
774
+ export function screenshotSaveErrorMessage(result) {
775
+ return result.reason === "write-failed"
776
+ ? "could not write the screenshot to disk: " + result.detail
777
+ : "screencap failed; is the device awake and connected?";
778
+ }
779
+ /**
780
+ * Capture a screenshot and write it to the screen tmp dir.
781
+ *
782
+ * Writing to disk is what makes the outcome reportable. Streaming the PNG straight back as
783
+ * a Content-Disposition attachment gave the browser no way to distinguish a saved file from
784
+ * a 403 or a 502: the response never reaches page JavaScript, and a download navigation
785
+ * fires neither load nor error on the frame that requested it. Landing the bytes first
786
+ * turns "did this work" into an ordinary JSON answer, which is the same two-phase shape
787
+ * /screen/record/stop already uses.
788
+ *
789
+ * Same on-disk posture as a recording, and for the same reason: a screenshot is a full
790
+ * frame of whatever is on the phone, so the dir is owner-only and the file owner-read/write.
791
+ */
792
+ export async function saveScreenshot() {
793
+ const png = await captureScreenshot();
794
+ if (!png)
795
+ return { ok: false, reason: "capture-failed" };
796
+ const safe = new Date().toISOString().replace(/[:.]/g, "-");
797
+ const out = path.join(SC_TMP, `radar_screen_${safe}.png`);
798
+ // Every host-side step is inside one try, so a failure to CREATE the dir is reported the same
799
+ // way as a failure to write the file. Left outside, an unwritable home threw straight out of
800
+ // here, and the route calling it has no catch, so the request hung until the client timed out.
801
+ try {
802
+ fs.mkdirSync(SC_TMP, { recursive: true, mode: 0o700 });
803
+ // mkdirSync's mode only applies on creation, so a dir from an earlier session keeps its
804
+ // old (world-traversable) perms. Same unconditional chmod startRecording does.
805
+ try {
806
+ fs.chmodSync(SC_TMP, 0o700);
807
+ }
808
+ catch {
809
+ // best-effort; the file mode below is still applied
810
+ }
811
+ fs.writeFileSync(out, png, { mode: 0o600 });
812
+ }
813
+ catch (e) {
814
+ return { ok: false, reason: "write-failed", detail: e.message };
815
+ }
816
+ return { ok: true, path: out };
817
+ }
762
818
  // ---- lifecycle ---------------------------------------------------------------
763
819
  /** Reset detection + tear down any live cast. Called on device re-enable and shutdown. */
764
820
  export function resetScreenState() {
@@ -798,6 +854,13 @@ export function registerScreenCleanup() {
798
854
  process.on("exit", () => {
799
855
  if (scLive)
800
856
  reapCastProcesses(scLive);
857
+ // Also delete the captures here, not only in the signal handlers below. Those handlers are
858
+ // not guaranteed to run: Node fires signal listeners in registration order, and another
859
+ // module registering earlier (logcat-capture does, at server.ts module load) calls
860
+ // process.exit() synchronously, which skips every later SIGTERM listener including ours.
861
+ // "exit" fires no matter who ends the process, so this is the order-independent place for it.
862
+ // Verified live: a SIGTERM'd dashboard used to leave a full-screen PNG on disk.
863
+ cleanupRecordings();
801
864
  });
802
865
  process.on("SIGINT", () => {
803
866
  signalCleanup();
@@ -8,6 +8,17 @@
8
8
  */
9
9
  /** Which underlying source served a getRecentLogs result. */
10
10
  export type LogSource = "app_buffer" | "logcat_capture" | "logcat_ring";
11
+ /**
12
+ * What a fresh process probe actually established. "unknown" is a real answer, not a
13
+ * failure to answer: the probe ran and could not tell (no adb, device detached or
14
+ * unauthorized, timeout). Callers may only sharpen a message on "stopped"; "unknown"
15
+ * has to stay generic, because the app may well be running fine.
16
+ *
17
+ * A probe that cannot always tell must say so in its return type. Collapsing
18
+ * "could not tell" into "stopped" is what produced the wrong "the app is not running"
19
+ * message this type exists to prevent.
20
+ */
21
+ export type ProcessState = "running" | "stopped" | "unknown";
11
22
  /** Lines plus the source that produced them. */
12
23
  export interface LogResult {
13
24
  lines: string[];
@@ -26,8 +37,32 @@ export interface DeviceInfo {
26
37
  state: string;
27
38
  }
28
39
  export interface DeviceTransport {
29
- /** Human-readable platform name (e.g. "android", "ios"). */
40
+ /**
41
+ * Human-readable platform name (e.g. "android", "ios").
42
+ *
43
+ * For display and error text. Do NOT branch capability decisions on it. An optional member
44
+ * being present is the capability check; `platform !== "android"` is a guess that happens to
45
+ * be right today and rejects the next platform by construction rather than by an actual gap.
46
+ */
30
47
  readonly platform: string;
48
+ /**
49
+ * Whether this transport can reach the app's on-device databases and shared preferences.
50
+ *
51
+ * A flag rather than an optional method because the DB and prefs tools do not call through the
52
+ * transport at all -- they shell out to adb themselves (shared/db.ts, shared/prefs.ts) and take
53
+ * a transport only to ask this question. Defaults to unsupported when absent, so a new
54
+ * transport has to opt in deliberately instead of inheriting access it cannot serve.
55
+ */
56
+ readonly supportsLocalFileAccess?: boolean;
57
+ /**
58
+ * Whether this transport has a device dashboard for open_radar_dashboard to open.
59
+ *
60
+ * A flag for the same reason as supportsLocalFileAccess: the dashboard is a separate web server
61
+ * this transport does not serve, so there is no method whose presence could answer the question.
62
+ * The dashboard's own copy is about arming a device and reconnecting to it, which a transport with
63
+ * no device concept cannot honour. Absent means no, so a new transport opts in deliberately.
64
+ */
65
+ readonly supportsDeviceDashboard?: boolean;
31
66
  /**
32
67
  * Set up port forwarding so the device's radar HTTP server is
33
68
  * reachable at localhost:RADAR_PORT. Returns true on success.
@@ -75,21 +110,29 @@ export interface DeviceTransport {
75
110
  * Capture a screenshot from the connected device.
76
111
  * Returns the local file path to the saved image.
77
112
  *
113
+ * Optional: a platform with no device screen to capture (webapp) omits it. Callers must check
114
+ * for the method rather than for a platform name -- see the capability note at the top of this
115
+ * interface.
116
+ *
78
117
  * @param fullRes If true, capture at full resolution
79
118
  */
80
- screenshot(fullRes: boolean): string;
119
+ screenshot?(fullRes: boolean): string;
81
120
  /**
82
121
  * Record a short screen video from the connected device.
83
122
  * Returns the local file path to the saved video.
84
123
  *
124
+ * Optional: omitted by platforms with no device screen (webapp).
125
+ *
85
126
  * @param durationS Recording duration in seconds
86
127
  */
87
- recordScreen(durationS: number): string;
128
+ recordScreen?(durationS: number): string;
88
129
  /**
89
130
  * Get the current app state from the device (visible screens,
90
131
  * fragments, arguments, etc.). Returns a human-readable string.
132
+ *
133
+ * Optional: omitted by platforms with no equivalent introspection (webapp).
91
134
  */
92
- getAppState(): string;
135
+ getAppState?(): string;
93
136
  /**
94
137
  * Get recent log entries, optionally filtered by tag.
95
138
  *
@@ -98,8 +141,10 @@ export interface DeviceTransport {
98
141
  * @param grep Optional text to further filter
99
142
  * @returns The matching lines plus which source served them, so the caller can tell a
100
143
  * true-empty result from a silent fallback to an inferior source.
144
+ *
145
+ * Optional: omitted by platforms with no device log stream (webapp).
101
146
  */
102
- getRecentLogs(tag: string, limit: number, grep?: string): LogResult;
147
+ getRecentLogs?(tag: string, limit: number, grep?: string): LogResult;
103
148
  /**
104
149
  * Returns the currently active user ID, or null if none is set. On Android
105
150
  * this is the profile (e.g. "0" for personal, "10" for work); on iOS it
@@ -135,6 +180,18 @@ export interface DeviceTransport {
135
180
  * implementations may omit it.
136
181
  */
137
182
  getLastActivateError?(): string | null;
183
+ /**
184
+ * State of the target app process on the device, checked fresh (not cached). Lets the
185
+ * enable flow tell a confirmed "stopped" apart from "the probe could not tell" when the
186
+ * device server never answers a ping after activation. Optional; an absent method is
187
+ * the same as "unknown", so `transport.processState?.() ?? "unknown"` is the whole
188
+ * call-site contract and there is no falsy-vs-absent trap to remember.
189
+ *
190
+ * @param timeoutMs Optional ceiling for the probe. A caller that is only explaining a
191
+ * failure it already detected should pass something short, so the diagnosis cannot
192
+ * cost more than the operation it diagnoses. Implementations may ignore it.
193
+ */
194
+ processState?(timeoutMs?: number): ProcessState;
138
195
  /**
139
196
  * Returns the path of the session-scoped log capture file, or null if no
140
197
  * capture is running. Surfaced in tool responses so the model can reason
@@ -0,0 +1,50 @@
1
+ import type { DeviceTransport } from "./transport.js";
2
+ /**
3
+ * DeviceTransport for the webapp Radar debug server: a local dev server plugin, not an Android
4
+ * device reached over adb. There is no adb forward to build, no
5
+ * activation broadcast to send, and no multi-user/profile model, so most of this transport is
6
+ * either a trivial success or a documented no-op -- see each method below for why.
7
+ *
8
+ * Real device operations (screenshot, screen recording, app state, log retrieval) are a
9
+ * deliberate non-goal for webapp, and they are simply ABSENT here rather than present-and-throwing.
10
+ * DeviceTransport declares all four optional, which is the interface's existing way of saying a
11
+ * capability may be missing (dropForward, reassertForward, listDevices and others already work
12
+ * that way). Declaring them and throwing was the same information said less directly: it forced a
13
+ * method to exist in order to announce that it does not, and it left the real answer discoverable
14
+ * only by calling it and catching. Absent members let a caller ask before calling.
15
+ *
16
+ * Same reason `supportsLocalFileAccess` and `supportsDeviceDashboard` are left unset: the DB and
17
+ * prefs tools shell to adb themselves and the dashboard is its own web server, so there is nothing
18
+ * for this transport to implement, and the flags' absent-means-no default states that without a
19
+ * platform-name comparison.
20
+ */
21
+ export declare class WebappTransport implements DeviceTransport {
22
+ readonly platform = "webapp";
23
+ private forwarded;
24
+ private currentTimeoutMinutes;
25
+ /**
26
+ * Nothing to forward -- the webapp dev server already listens on localhost, at whatever
27
+ * port setRadarPort(WEBAPP_DEFAULT_PORT) pointed RADAR_PORT at (see
28
+ * mcp/platform-detect.ts). DeviceTransport.ensureForward() is declared synchronous
29
+ * (`(): boolean`, not `(): Promise<boolean>`), so a real HTTP reachability check cannot
30
+ * live here without either shelling out or a blocking hack, and neither is worth it: the
31
+ * very next thing this transport's caller does is callRadar()'s real HTTP GET against
32
+ * RADAR_HOST:RADAR_PORT, and that call's existing retry-then-disable-session handling
33
+ * already turns an unreachable server into a clean error. So this trivially succeeds
34
+ * (there genuinely is nothing to forward) and lets the real request be the truth-teller.
35
+ */
36
+ ensureForward(): boolean;
37
+ /**
38
+ * No activation broadcast exists on webapp -- the dev server just runs or it does not.
39
+ * Only remember the requested timeout so getTimeoutMinutes() reports it back, mirroring
40
+ * AndroidTransport's activate() contract without the adb side effect.
41
+ */
42
+ activate(timeoutMinutes: number): void;
43
+ resetState(): void;
44
+ isForwarded(): boolean;
45
+ getTimeoutMinutes(): number;
46
+ /** No multi-user concept on webapp. */
47
+ getActiveUserId(): string | null;
48
+ /** Single-user platform: per transport.ts's own doc comment, resolve to "". */
49
+ resolveActiveUser(): string;
50
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * DeviceTransport for the webapp Radar debug server: a local dev server plugin, not an Android
3
+ * device reached over adb. There is no adb forward to build, no
4
+ * activation broadcast to send, and no multi-user/profile model, so most of this transport is
5
+ * either a trivial success or a documented no-op -- see each method below for why.
6
+ *
7
+ * Real device operations (screenshot, screen recording, app state, log retrieval) are a
8
+ * deliberate non-goal for webapp, and they are simply ABSENT here rather than present-and-throwing.
9
+ * DeviceTransport declares all four optional, which is the interface's existing way of saying a
10
+ * capability may be missing (dropForward, reassertForward, listDevices and others already work
11
+ * that way). Declaring them and throwing was the same information said less directly: it forced a
12
+ * method to exist in order to announce that it does not, and it left the real answer discoverable
13
+ * only by calling it and catching. Absent members let a caller ask before calling.
14
+ *
15
+ * Same reason `supportsLocalFileAccess` and `supportsDeviceDashboard` are left unset: the DB and
16
+ * prefs tools shell to adb themselves and the dashboard is its own web server, so there is nothing
17
+ * for this transport to implement, and the flags' absent-means-no default states that without a
18
+ * platform-name comparison.
19
+ */
20
+ export class WebappTransport {
21
+ platform = "webapp";
22
+ forwarded = false;
23
+ currentTimeoutMinutes = 5;
24
+ /**
25
+ * Nothing to forward -- the webapp dev server already listens on localhost, at whatever
26
+ * port setRadarPort(WEBAPP_DEFAULT_PORT) pointed RADAR_PORT at (see
27
+ * mcp/platform-detect.ts). DeviceTransport.ensureForward() is declared synchronous
28
+ * (`(): boolean`, not `(): Promise<boolean>`), so a real HTTP reachability check cannot
29
+ * live here without either shelling out or a blocking hack, and neither is worth it: the
30
+ * very next thing this transport's caller does is callRadar()'s real HTTP GET against
31
+ * RADAR_HOST:RADAR_PORT, and that call's existing retry-then-disable-session handling
32
+ * already turns an unreachable server into a clean error. So this trivially succeeds
33
+ * (there genuinely is nothing to forward) and lets the real request be the truth-teller.
34
+ */
35
+ ensureForward() {
36
+ this.forwarded = true;
37
+ return true;
38
+ }
39
+ /**
40
+ * No activation broadcast exists on webapp -- the dev server just runs or it does not.
41
+ * Only remember the requested timeout so getTimeoutMinutes() reports it back, mirroring
42
+ * AndroidTransport's activate() contract without the adb side effect.
43
+ */
44
+ activate(timeoutMinutes) {
45
+ if (timeoutMinutes)
46
+ this.currentTimeoutMinutes = timeoutMinutes;
47
+ }
48
+ resetState() {
49
+ this.forwarded = false;
50
+ }
51
+ isForwarded() {
52
+ return this.forwarded;
53
+ }
54
+ getTimeoutMinutes() {
55
+ return this.currentTimeoutMinutes;
56
+ }
57
+ /** No multi-user concept on webapp. */
58
+ getActiveUserId() {
59
+ return null;
60
+ }
61
+ /** Single-user platform: per transport.ts's own doc comment, resolve to "". */
62
+ resolveActiveUser() {
63
+ return "";
64
+ }
65
+ }