@slack/radar-mcp 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mcp/index.js +35 -47
- package/dist/mcp/session-enable.d.ts +17 -0
- package/dist/mcp/session-enable.js +104 -0
- package/dist/shared/android.d.ts +3 -0
- package/dist/shared/android.js +48 -11
- package/dist/shared/constants.d.ts +9 -2
- package/dist/shared/constants.js +9 -2
- package/dist/shared/stream.d.ts +23 -0
- package/dist/shared/stream.js +109 -16
- package/dist/shared/transport.d.ts +18 -0
- package/dist/web/server.js +22 -16
- package/package.json +1 -1
package/dist/mcp/index.js
CHANGED
|
@@ -16,6 +16,7 @@ import { buildBufferPath, createSnapshot } from "./snapshot.js";
|
|
|
16
16
|
import { clampLogLimit, shapeLogsResult } from "./logs-result.js";
|
|
17
17
|
import { querySession, clampByteCap, toNum } from "./session-query.js";
|
|
18
18
|
import { resolveDetailById } from "./session-detail.js";
|
|
19
|
+
import { runSessionEnable } from "./session-enable.js";
|
|
19
20
|
import { backfillSpool, BACKFILL_SOURCES, makeSerializedRunner, } from "./session-backfill.js";
|
|
20
21
|
import { handleListDatabases, handleListTables, handleQueryDatabase, } from "./db-tools.js";
|
|
21
22
|
import { cleanupPulledDatabases, initializeDatabasePath, resetDbState, } from "../shared/db.js";
|
|
@@ -276,7 +277,7 @@ async function runMcpServer() {
|
|
|
276
277
|
// a truncation marker rather than a partial JSON blob the parser would choke on. Bulk exports go
|
|
277
278
|
// through capture_snapshot, not this path. The ceiling now lives in constants so the device path
|
|
278
279
|
// and the session-query byte cap share one value.
|
|
279
|
-
function radarRequest(requestPath) {
|
|
280
|
+
function radarRequest(requestPath, timeoutMs = 10000) {
|
|
280
281
|
return new Promise((resolve, reject) => {
|
|
281
282
|
// settled-guard: req.destroy() on the cap path fires "error" (ECONNRESET) AFTER we have
|
|
282
283
|
// already resolved the truncation, so every settle goes through these wrappers and the
|
|
@@ -298,7 +299,7 @@ async function runMcpServer() {
|
|
|
298
299
|
host: RADAR_HOST,
|
|
299
300
|
port: RADAR_PORT,
|
|
300
301
|
path: requestPath,
|
|
301
|
-
timeout:
|
|
302
|
+
timeout: timeoutMs,
|
|
302
303
|
}, (res) => {
|
|
303
304
|
let data = "";
|
|
304
305
|
let bytes = 0;
|
|
@@ -376,55 +377,42 @@ async function runMcpServer() {
|
|
|
376
377
|
// --- Tool handlers ---
|
|
377
378
|
async function handleSessionEnable(args) {
|
|
378
379
|
const timeout = args?.timeout_minutes || 5;
|
|
379
|
-
|
|
380
|
-
//
|
|
381
|
-
//
|
|
382
|
-
//
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
sessionEnabled = false;
|
|
387
|
-
const reason = device.getLastForwardError?.() ?? null;
|
|
388
|
-
return textResult({
|
|
389
|
-
error: reason ??
|
|
390
|
-
"Port forwarding failed. Ensure a device is connected.",
|
|
391
|
-
enabled: false,
|
|
392
|
-
platform: device.platform,
|
|
393
|
-
}, true);
|
|
394
|
-
}
|
|
395
|
-
device.activate(timeout);
|
|
396
|
-
// Open the session event spool, then backfill the device rings into it. Note the live SSE push can
|
|
397
|
-
// start DURING the backfill: the backfill pulls the ring lists via callRadar, which opens the
|
|
398
|
-
// stream on its first fetch, so the trailing connectStream() below is usually a no-op (it only
|
|
399
|
-
// opens the stream when the backfill wrote nothing and never called callRadar, e.g. empty rings).
|
|
400
|
-
// Correctness does NOT rely on connect ordering. It relies on two things: the (source, id) have-set
|
|
401
|
-
// that skips a row already in the spool, and the unconditional read-time collapse (every read folds
|
|
402
|
-
// a duplicated id to one frame), so a frame the live push and the backfill both write surfaces once.
|
|
403
|
-
// Serialized so it cannot overlap a reconnect backfill. Never throws; a device blip just skips it.
|
|
404
|
-
startSpool();
|
|
405
|
-
await runBackfillSerialized();
|
|
406
|
-
connectStream();
|
|
407
|
-
// Open the session event spool so every streamed frame is captured to a host
|
|
408
|
-
// file for the life of this enabled session.
|
|
409
|
-
startSpool();
|
|
410
|
-
await new Promise((r) => setTimeout(r, 500));
|
|
380
|
+
// The orchestration lives in session-enable.ts (testable without the stdio
|
|
381
|
+
// server this module starts at load); this handler wires the real effects
|
|
382
|
+
// and owns the session flag. sessionEnabled goes true up front so the
|
|
383
|
+
// backfill's device pulls pass the session gate, then follows the outcome.
|
|
384
|
+
// The catch covers a future refactor introducing a rejecting await: without
|
|
385
|
+
// it the gate would stay open (sessionEnabled true) on a half-torn session
|
|
386
|
+
// while the SDK reports an opaque error.
|
|
411
387
|
try {
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
388
|
+
sessionEnabled = true;
|
|
389
|
+
const outcome = await runSessionEnable(timeout, {
|
|
390
|
+
device,
|
|
391
|
+
destroyStream,
|
|
392
|
+
connectStream,
|
|
393
|
+
isStreamConnected,
|
|
394
|
+
resetDbState,
|
|
395
|
+
startSpool,
|
|
396
|
+
runBackfill: runBackfillSerialized,
|
|
397
|
+
// A health ping does not need the default 10s: a half-alive server
|
|
398
|
+
// (accepts TCP, never answers) would otherwise stretch the verify loop
|
|
399
|
+
// past the MCP client's 60s tool-call timeout, and the crafted error
|
|
400
|
+
// would never reach the user. 2s keeps worst-case enable wall time far
|
|
401
|
+
// under that ceiling.
|
|
402
|
+
ping: () => radarRequest("/api/ping", 2000),
|
|
403
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
418
404
|
});
|
|
405
|
+
sessionEnabled = outcome.enabled;
|
|
406
|
+
return textResult(outcome.body, !outcome.enabled);
|
|
419
407
|
}
|
|
420
|
-
catch {
|
|
408
|
+
catch (e) {
|
|
409
|
+
sessionEnabled = false;
|
|
410
|
+
destroyStream();
|
|
421
411
|
return textResult({
|
|
422
|
-
|
|
412
|
+
error: `Enable failed unexpectedly: ${e.message}`,
|
|
413
|
+
enabled: false,
|
|
423
414
|
platform: device.platform,
|
|
424
|
-
|
|
425
|
-
ping: "failed",
|
|
426
|
-
note: "Radar activated but ping failed. Device may need a moment.",
|
|
427
|
-
});
|
|
415
|
+
}, true);
|
|
428
416
|
}
|
|
429
417
|
}
|
|
430
418
|
function handleSessionDisable() {
|
|
@@ -668,7 +656,7 @@ async function runMcpServer() {
|
|
|
668
656
|
}
|
|
669
657
|
}
|
|
670
658
|
// --- MCP Server ---
|
|
671
|
-
const server = new Server({ name: "slack-radar", version: "1.
|
|
659
|
+
const server = new Server({ name: "slack-radar", version: "1.11.0" }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
|
|
672
660
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
673
661
|
tools: TOOL_DEFINITIONS,
|
|
674
662
|
}));
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { DeviceTransport } from "../shared/transport.js";
|
|
2
|
+
export interface EnableDeps {
|
|
3
|
+
device: DeviceTransport;
|
|
4
|
+
destroyStream: () => void;
|
|
5
|
+
connectStream: () => void;
|
|
6
|
+
isStreamConnected: () => boolean;
|
|
7
|
+
resetDbState: () => void;
|
|
8
|
+
startSpool: () => void;
|
|
9
|
+
runBackfill: () => Promise<unknown>;
|
|
10
|
+
ping: () => Promise<Record<string, unknown>>;
|
|
11
|
+
sleep: (ms: number) => Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
export interface EnableOutcome {
|
|
14
|
+
body: Record<string, unknown>;
|
|
15
|
+
enabled: boolean;
|
|
16
|
+
}
|
|
17
|
+
export declare function runSessionEnable(timeoutMinutes: number, deps: EnableDeps): Promise<EnableOutcome>;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Ping-verify cadence: first probe fast (a healthy server answers immediately;
|
|
2
|
+
// this is the whole latency of a normal enable), then two patient retries to
|
|
3
|
+
// absorb real server startup.
|
|
4
|
+
const PING_WAITS_MS = [500, 1000, 1000];
|
|
5
|
+
export async function runSessionEnable(timeoutMinutes, deps) {
|
|
6
|
+
const { device, destroyStream, connectStream, isStreamConnected, resetDbState, startSpool, runBackfill, ping, sleep, } = deps;
|
|
7
|
+
// Tear down the old stream (and its reconnect loop) FIRST, then drop all cached
|
|
8
|
+
// transport state so this enable starts clean. Without the reset, a stale adb
|
|
9
|
+
// forward (device end dead after an idle timeout or a replug) makes ensureForward()
|
|
10
|
+
// a cached no-op, and a user id cached from an earlier detect can pin the enable
|
|
11
|
+
// broadcast to the wrong profile. The web server's handleEnable (server.ts) has
|
|
12
|
+
// always reset for the same reason; the MCP path was missing it.
|
|
13
|
+
destroyStream();
|
|
14
|
+
device.resetState();
|
|
15
|
+
// A re-enable may be a different device or a re-armed profile, so drop the cached DB
|
|
16
|
+
// user set + sqlite path; the next DB tool call re-detects the profiles fresh.
|
|
17
|
+
resetDbState();
|
|
18
|
+
if (!device.ensureForward()) {
|
|
19
|
+
const reason = device.getLastForwardError?.() ?? null;
|
|
20
|
+
return {
|
|
21
|
+
enabled: false,
|
|
22
|
+
body: {
|
|
23
|
+
error: reason ?? "Port forwarding failed. Ensure a device is connected.",
|
|
24
|
+
enabled: false,
|
|
25
|
+
platform: device.platform,
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
device.activate(timeoutMinutes);
|
|
30
|
+
const activateError = device.getLastActivateError?.() ?? null;
|
|
31
|
+
if (activateError) {
|
|
32
|
+
// The broadcast failed at the adb level. The device server may STILL be alive
|
|
33
|
+
// (armed by a prior session, or the broadcast timed out on a loaded device
|
|
34
|
+
// after landing), so probe before failing: a working server beats a pedantic
|
|
35
|
+
// error, and a dead one gets a real error instead of the old silent
|
|
36
|
+
// enabled:true + failing tools.
|
|
37
|
+
try {
|
|
38
|
+
await ping();
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return {
|
|
42
|
+
enabled: false,
|
|
43
|
+
body: {
|
|
44
|
+
error: `Radar activation broadcast failed: ${activateError}. Is the device connected? Check adb devices.`,
|
|
45
|
+
enabled: false,
|
|
46
|
+
platform: device.platform,
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// Open the session event spool, then backfill the device rings into it. The live
|
|
52
|
+
// SSE push can start DURING the backfill (the backfill pulls via the injected
|
|
53
|
+
// fetch, which opens the stream on its first call), so the trailing
|
|
54
|
+
// connectStream() is usually a no-op. Correctness does not rely on connect
|
|
55
|
+
// ordering: the (source, id) have-set and the read-time collapse fold any
|
|
56
|
+
// frame both paths write into one.
|
|
57
|
+
startSpool();
|
|
58
|
+
await runBackfill();
|
|
59
|
+
connectStream();
|
|
60
|
+
// Verify the device server actually came up. A broadcast can land nowhere and
|
|
61
|
+
// still exit 0 (no receiver: radar modules missing from the build, or a
|
|
62
|
+
// wrong-profile target). Retry to absorb real startup latency before
|
|
63
|
+
// declaring it dead.
|
|
64
|
+
let status = null;
|
|
65
|
+
for (const waitMs of PING_WAITS_MS) {
|
|
66
|
+
await sleep(waitMs);
|
|
67
|
+
try {
|
|
68
|
+
status = await ping();
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// Retry until the waits are exhausted.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (status === null) {
|
|
76
|
+
destroyStream();
|
|
77
|
+
return {
|
|
78
|
+
enabled: false,
|
|
79
|
+
body: {
|
|
80
|
+
error: "Radar broadcast sent but the device server did not respond. Is a debug build with the slack-radar modules installed and running on the active profile?",
|
|
81
|
+
enabled: false,
|
|
82
|
+
platform: device.platform,
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
enabled: true,
|
|
88
|
+
body: {
|
|
89
|
+
enabled: true,
|
|
90
|
+
platform: device.platform,
|
|
91
|
+
stream_connected: isStreamConnected(),
|
|
92
|
+
// The broadcast failed but the server answered (armed by a prior session).
|
|
93
|
+
// activate()'s success branch never ran, so the logcat capture is not
|
|
94
|
+
// armed: get_recent_logs degrades to the device ring for this session.
|
|
95
|
+
// Named so the degradation is visible instead of silent.
|
|
96
|
+
...(activateError
|
|
97
|
+
? {
|
|
98
|
+
logcat_capture: "not started (activation broadcast failed; logs fall back to the device ring)",
|
|
99
|
+
}
|
|
100
|
+
: {}),
|
|
101
|
+
...status,
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
package/dist/shared/android.d.ts
CHANGED
|
@@ -25,10 +25,13 @@ export declare class AndroidTransport implements DeviceTransport {
|
|
|
25
25
|
private currentTimeoutMinutes;
|
|
26
26
|
private radarEnabled;
|
|
27
27
|
private lastForwardError;
|
|
28
|
+
private lastActivateError;
|
|
28
29
|
ensureForward(): boolean;
|
|
29
30
|
getLastForwardError(): string | null;
|
|
30
31
|
activate(timeoutMinutes: number): void;
|
|
32
|
+
getLastActivateError(): string | null;
|
|
31
33
|
resetState(): void;
|
|
34
|
+
dropForward(): void;
|
|
32
35
|
isForwarded(): boolean;
|
|
33
36
|
getTimeoutMinutes(): number;
|
|
34
37
|
getActiveUserId(): string | null;
|
package/dist/shared/android.js
CHANGED
|
@@ -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
|
-
|
|
7
|
+
import { RADAR_PORT } from "./constants.js";
|
|
8
8
|
const SOCKET_NAME = "slack-radar";
|
|
9
9
|
const ENABLE_ACTION = "slack.debug.ENABLE_RADAR";
|
|
10
10
|
/**
|
|
@@ -90,6 +90,7 @@ export class AndroidTransport {
|
|
|
90
90
|
currentTimeoutMinutes = 5;
|
|
91
91
|
radarEnabled = false;
|
|
92
92
|
lastForwardError = null;
|
|
93
|
+
lastActivateError = null;
|
|
93
94
|
ensureForward() {
|
|
94
95
|
if (this.portForwarded)
|
|
95
96
|
return true;
|
|
@@ -98,6 +99,16 @@ export class AndroidTransport {
|
|
|
98
99
|
"adb binary not found. Set ANDROID_HOME or install Android SDK platform-tools. Searched: PATH, $ANDROID_HOME/platform-tools/adb, ~/Library/Android/sdk/platform-tools/adb, ~/Android/Sdk/platform-tools/adb, /usr/local/bin/adb, /opt/homebrew/bin/adb.";
|
|
99
100
|
return false;
|
|
100
101
|
}
|
|
102
|
+
// 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.
|
|
106
|
+
try {
|
|
107
|
+
execSync(`${ADB} forward --remove tcp:${RADAR_PORT}`, { timeout: 5000 });
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// No existing mapping, or adb hiccup; the add below surfaces real failures.
|
|
111
|
+
}
|
|
101
112
|
try {
|
|
102
113
|
execSync(`${ADB} forward tcp:${RADAR_PORT} localabstract:${SOCKET_NAME}`, {
|
|
103
114
|
timeout: 5000,
|
|
@@ -115,8 +126,10 @@ export class AndroidTransport {
|
|
|
115
126
|
return this.lastForwardError;
|
|
116
127
|
}
|
|
117
128
|
activate(timeoutMinutes) {
|
|
118
|
-
if (!ADB)
|
|
129
|
+
if (!ADB) {
|
|
130
|
+
this.lastActivateError = "adb binary not found";
|
|
119
131
|
return;
|
|
132
|
+
}
|
|
120
133
|
const timeout = timeoutMinutes || this.currentTimeoutMinutes;
|
|
121
134
|
if (this.radarEnabled && timeout === this.currentTimeoutMinutes)
|
|
122
135
|
return;
|
|
@@ -125,22 +138,37 @@ export class AndroidTransport {
|
|
|
125
138
|
execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout}`, { timeout: 5000 });
|
|
126
139
|
this.currentTimeoutMinutes = timeout;
|
|
127
140
|
this.radarEnabled = true;
|
|
141
|
+
this.lastActivateError = null;
|
|
128
142
|
// Start streaming logcat to a session-scoped file so reads are not
|
|
129
143
|
// subject to the device ring buffer rotating under load.
|
|
130
144
|
registerCleanup();
|
|
131
145
|
startCapture(ADB);
|
|
132
146
|
}
|
|
133
|
-
catch {
|
|
134
|
-
// Broadcast failed
|
|
147
|
+
catch (e) {
|
|
148
|
+
// Broadcast failed, device may not be connected. Recorded so the enable
|
|
149
|
+
// path can report it instead of claiming success with a failing ping.
|
|
150
|
+
// radarEnabled drops too: a prior success no longer proves the device
|
|
151
|
+
// side is armed, and leaving it true would make every later activate()
|
|
152
|
+
// early-return and never re-send the broadcast.
|
|
153
|
+
this.radarEnabled = false;
|
|
154
|
+
this.lastActivateError = e.message;
|
|
135
155
|
}
|
|
136
156
|
}
|
|
157
|
+
getLastActivateError() {
|
|
158
|
+
return this.lastActivateError;
|
|
159
|
+
}
|
|
137
160
|
resetState() {
|
|
138
161
|
this.portForwarded = false;
|
|
139
162
|
this.detectedUserId = null;
|
|
140
163
|
this.radarEnabled = false;
|
|
141
164
|
this.lastForwardError = null;
|
|
165
|
+
this.lastActivateError = null;
|
|
142
166
|
// Capture has its own idle timer; not stopped on activation reset (see logcat-capture.ts).
|
|
143
167
|
}
|
|
168
|
+
dropForward() {
|
|
169
|
+
this.portForwarded = false;
|
|
170
|
+
this.lastForwardError = null;
|
|
171
|
+
}
|
|
144
172
|
isForwarded() {
|
|
145
173
|
return this.portForwarded;
|
|
146
174
|
}
|
|
@@ -272,7 +300,10 @@ export class AndroidTransport {
|
|
|
272
300
|
if (!ADB)
|
|
273
301
|
throw new Error("adb not found on PATH or common SDK locations");
|
|
274
302
|
const timeout = timeoutMinutes || this.currentTimeoutMinutes;
|
|
275
|
-
|
|
303
|
+
// Unknown prior user (null) counts as changed: the running capture may be
|
|
304
|
+
// scoped to a profile we could not detect, and appending this profile's
|
|
305
|
+
// run to it would mix profiles in one file. Rotating is the safe default.
|
|
306
|
+
const profileChanged = this.detectedUserId !== userId;
|
|
276
307
|
execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout}`, { timeout: 5000 });
|
|
277
308
|
this.detectedUserId = userId;
|
|
278
309
|
this.currentTimeoutMinutes = timeout;
|
|
@@ -288,17 +319,23 @@ export class AndroidTransport {
|
|
|
288
319
|
detectDebugBuildUser() {
|
|
289
320
|
if (this.detectedUserId !== null)
|
|
290
321
|
return this.detectedUserId;
|
|
291
|
-
if (!ADB)
|
|
292
|
-
|
|
293
|
-
return this.detectedUserId;
|
|
294
|
-
}
|
|
322
|
+
if (!ADB)
|
|
323
|
+
return "0";
|
|
295
324
|
try {
|
|
296
325
|
const ps = execSync(`${ADB} shell "ps -A -o USER,NAME 2>/dev/null | grep Slack | grep debug"`, { timeout: 5000, encoding: "utf-8" }).trim();
|
|
326
|
+
// Cache only when a debug-build process was actually seen. Caching the "0"
|
|
327
|
+
// fallback would pin every later enable to user 0 for the process lifetime,
|
|
328
|
+
// so a work-profile build (user 10) launched after a failed detect would
|
|
329
|
+
// never receive the enable broadcast.
|
|
330
|
+
const match = ps.match(/u(\d+)_/);
|
|
331
|
+
if (!match)
|
|
332
|
+
return "0";
|
|
297
333
|
this.detectedUserId = parseUserFromPsOutput(ps);
|
|
334
|
+
return this.detectedUserId;
|
|
298
335
|
}
|
|
299
336
|
catch {
|
|
300
|
-
|
|
337
|
+
// grep exits non-zero when Slack is not running; do not cache the fallback.
|
|
338
|
+
return "0";
|
|
301
339
|
}
|
|
302
|
-
return this.detectedUserId;
|
|
303
340
|
}
|
|
304
341
|
}
|
|
@@ -6,8 +6,15 @@
|
|
|
6
6
|
* Falls back to "unknown" if package.json cannot be read (should not happen in a real install).
|
|
7
7
|
*/
|
|
8
8
|
export declare const RADAR_VERSION: string;
|
|
9
|
-
/**
|
|
10
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Port used to reach the on-device radar HTTP server via forwarding. Shared
|
|
11
|
+
* by the HTTP clients (stream, radarRequest) AND the adb forward target in
|
|
12
|
+
* android.ts so the two cannot point at different ports. The env override
|
|
13
|
+
* exists for tests only: stream lifecycle tests stand up a local server on an
|
|
14
|
+
* ephemeral port so they cannot collide with a real forwarded device on 8099.
|
|
15
|
+
* Set before module load, like SLACK_RADAR_WEB_PORT.
|
|
16
|
+
*/
|
|
17
|
+
export declare const RADAR_PORT: number;
|
|
11
18
|
/** Host address for the forwarded connection. */
|
|
12
19
|
export declare const RADAR_HOST = "127.0.0.1";
|
|
13
20
|
/** Max events to retain in each local SSE buffer. */
|
package/dist/shared/constants.js
CHANGED
|
@@ -15,8 +15,15 @@ export const RADAR_VERSION = (() => {
|
|
|
15
15
|
return "unknown";
|
|
16
16
|
}
|
|
17
17
|
})();
|
|
18
|
-
/**
|
|
19
|
-
|
|
18
|
+
/**
|
|
19
|
+
* Port used to reach the on-device radar HTTP server via forwarding. Shared
|
|
20
|
+
* by the HTTP clients (stream, radarRequest) AND the adb forward target in
|
|
21
|
+
* android.ts so the two cannot point at different ports. The env override
|
|
22
|
+
* exists for tests only: stream lifecycle tests stand up a local server on an
|
|
23
|
+
* ephemeral port so they cannot collide with a real forwarded device on 8099.
|
|
24
|
+
* Set before module load, like SLACK_RADAR_WEB_PORT.
|
|
25
|
+
*/
|
|
26
|
+
export const RADAR_PORT = Number(process.env.SLACK_RADAR_DEVICE_PORT) || 8099;
|
|
20
27
|
/** Host address for the forwarded connection. */
|
|
21
28
|
export const RADAR_HOST = "127.0.0.1";
|
|
22
29
|
/** Max events to retain in each local SSE buffer. */
|
package/dist/shared/stream.d.ts
CHANGED
|
@@ -11,6 +11,20 @@ export interface ParsedSSE {
|
|
|
11
11
|
}
|
|
12
12
|
export declare const localNetworkBuffer: RadarEvent[];
|
|
13
13
|
export declare const localRtmBuffer: RadarEvent[];
|
|
14
|
+
/**
|
|
15
|
+
* Decide whether this reconnect attempt rebuilds the adb forward, perform the
|
|
16
|
+
* rebuild if so, and return the delay before the next connect. Does not call
|
|
17
|
+
* setTimeout itself so the decision is unit-testable without a live socket.
|
|
18
|
+
*
|
|
19
|
+
* Prefers dropForward() (drops only the cached forward flag) over resetState()
|
|
20
|
+
* so a rebuild does not wipe the detected user id mid-session: a full reset
|
|
21
|
+
* followed by a re-detect while the app process is down would rebind the
|
|
22
|
+
* session to user 0, losing a work-profile binding.
|
|
23
|
+
*
|
|
24
|
+
* @param t transport whose forward may be stale
|
|
25
|
+
* @param attempt 1-based failure count since the last successful connect
|
|
26
|
+
*/
|
|
27
|
+
export declare function planReconnect(t: DeviceTransport, attempt: number): number;
|
|
14
28
|
/** Set the reconnect hook. Called once after each successful reconnect. Pass null to clear it. */
|
|
15
29
|
export declare function setOnReconnect(fn: (() => void) | null): void;
|
|
16
30
|
export declare function noteStreamConnected(): void;
|
|
@@ -18,6 +32,15 @@ export declare function _resetReconnectStateForTest(): void;
|
|
|
18
32
|
export declare function isStreamConnected(): boolean;
|
|
19
33
|
export declare function clearLocalBuffers(): void;
|
|
20
34
|
export declare function getStreamConnection(): http.ClientRequest | null;
|
|
35
|
+
/**
|
|
36
|
+
* Deliberate teardown: destroy the live stream AND stop the reconnect loop.
|
|
37
|
+
* Cancelling the pending timer matters as much as the destroy — without it a
|
|
38
|
+
* disable (or an enable-restart) leaves a timer that resurrects the stream
|
|
39
|
+
* seconds later, refilling buffers the caller just cleared and churning adb
|
|
40
|
+
* forward rebuilds against a session the user turned off. The destroyed
|
|
41
|
+
* request's own async failure events are ignored by the ownership check in
|
|
42
|
+
* connectStream's handlers (they no longer own streamConnection).
|
|
43
|
+
*/
|
|
21
44
|
export declare function destroyStream(): void;
|
|
22
45
|
/**
|
|
23
46
|
* Push an event into the appropriate local buffer, enforcing MAX_LOCAL_BUFFER.
|
package/dist/shared/stream.js
CHANGED
|
@@ -11,6 +11,74 @@ export const localRtmBuffer = [];
|
|
|
11
11
|
let streamConnection = null;
|
|
12
12
|
let streamConnected = false;
|
|
13
13
|
const eventWaiters = [];
|
|
14
|
+
// Reconnect cadence. A plain retry reuses the existing adb forward; every other
|
|
15
|
+
// attempt rebuilds it, because a forward whose device end died is not revived by
|
|
16
|
+
// waiting (the stream would retry into a dead socket forever). Mirrors the web
|
|
17
|
+
// stream proxy's cadence (src/web/server.ts).
|
|
18
|
+
const RETRY_DELAY_MS = 2000;
|
|
19
|
+
const REBUILD_RETRY_DELAY_MS = 1500;
|
|
20
|
+
// Failures since the last successful connect; drives the every-other-attempt
|
|
21
|
+
// rebuild. The pending reconnect timer is held module-level so destroyStream()
|
|
22
|
+
// can cancel it: an intentional teardown (disable, enable-restart) must stop
|
|
23
|
+
// the loop, or it resurrects the stream the user just closed.
|
|
24
|
+
let reconnectAttempts = 0;
|
|
25
|
+
let reconnectTimer = null;
|
|
26
|
+
/**
|
|
27
|
+
* Decide whether this reconnect attempt rebuilds the adb forward, perform the
|
|
28
|
+
* rebuild if so, and return the delay before the next connect. Does not call
|
|
29
|
+
* setTimeout itself so the decision is unit-testable without a live socket.
|
|
30
|
+
*
|
|
31
|
+
* Prefers dropForward() (drops only the cached forward flag) over resetState()
|
|
32
|
+
* so a rebuild does not wipe the detected user id mid-session: a full reset
|
|
33
|
+
* followed by a re-detect while the app process is down would rebind the
|
|
34
|
+
* session to user 0, losing a work-profile binding.
|
|
35
|
+
*
|
|
36
|
+
* @param t transport whose forward may be stale
|
|
37
|
+
* @param attempt 1-based failure count since the last successful connect
|
|
38
|
+
*/
|
|
39
|
+
export function planReconnect(t, attempt) {
|
|
40
|
+
if (attempt % 2 === 0) {
|
|
41
|
+
if (t.dropForward) {
|
|
42
|
+
t.dropForward();
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
t.resetState();
|
|
46
|
+
}
|
|
47
|
+
t.ensureForward();
|
|
48
|
+
return REBUILD_RETRY_DELAY_MS;
|
|
49
|
+
}
|
|
50
|
+
return RETRY_DELAY_MS;
|
|
51
|
+
}
|
|
52
|
+
// Schedule the next reconnect attempt. Stale-callback dedup happens at the
|
|
53
|
+
// call sites (the failure handlers no-op unless their request still owns
|
|
54
|
+
// streamConnection), so by the time this runs the disconnect is real. The
|
|
55
|
+
// timer callback keeps the loop alive when a rebuild attempt could not
|
|
56
|
+
// restore the forward (device unplugged): connectStream would early-return
|
|
57
|
+
// on !isForwarded() and the loop would otherwise die permanently, leaving
|
|
58
|
+
// the stream down even after the device comes back.
|
|
59
|
+
function scheduleReconnect() {
|
|
60
|
+
// Never leave a previous timer untracked: if a second chain schedules while
|
|
61
|
+
// one is pending, overwriting the ref would orphan the first timer beyond
|
|
62
|
+
// destroyStream()'s reach, and it would resurrect the stream after a
|
|
63
|
+
// deliberate teardown. The connectStream guard makes this near-unreachable;
|
|
64
|
+
// this is the backstop.
|
|
65
|
+
if (reconnectTimer)
|
|
66
|
+
clearTimeout(reconnectTimer);
|
|
67
|
+
streamConnection = null;
|
|
68
|
+
streamConnected = false;
|
|
69
|
+
reconnectAttempts++;
|
|
70
|
+
const delay = transport
|
|
71
|
+
? planReconnect(transport, reconnectAttempts)
|
|
72
|
+
: RETRY_DELAY_MS;
|
|
73
|
+
reconnectTimer = setTimeout(() => {
|
|
74
|
+
reconnectTimer = null;
|
|
75
|
+
if (transport && !transport.isForwarded()) {
|
|
76
|
+
scheduleReconnect();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
connectStream();
|
|
80
|
+
}, delay);
|
|
81
|
+
}
|
|
14
82
|
// Fires once after a RECONNECT (not the first connect), so the owner can backfill the device ring
|
|
15
83
|
// rows the ~2s gap dropped. index.ts sets it to the backfill; unset it is a no-op, so the web
|
|
16
84
|
// server (which shares this module) and tests are unaffected. hasConnectedOnce gates it to a true
|
|
@@ -52,7 +120,21 @@ export function clearLocalBuffers() {
|
|
|
52
120
|
export function getStreamConnection() {
|
|
53
121
|
return streamConnection;
|
|
54
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Deliberate teardown: destroy the live stream AND stop the reconnect loop.
|
|
125
|
+
* Cancelling the pending timer matters as much as the destroy — without it a
|
|
126
|
+
* disable (or an enable-restart) leaves a timer that resurrects the stream
|
|
127
|
+
* seconds later, refilling buffers the caller just cleared and churning adb
|
|
128
|
+
* forward rebuilds against a session the user turned off. The destroyed
|
|
129
|
+
* request's own async failure events are ignored by the ownership check in
|
|
130
|
+
* connectStream's handlers (they no longer own streamConnection).
|
|
131
|
+
*/
|
|
55
132
|
export function destroyStream() {
|
|
133
|
+
if (reconnectTimer) {
|
|
134
|
+
clearTimeout(reconnectTimer);
|
|
135
|
+
reconnectTimer = null;
|
|
136
|
+
}
|
|
137
|
+
reconnectAttempts = 0;
|
|
56
138
|
if (streamConnection) {
|
|
57
139
|
streamConnection.destroy();
|
|
58
140
|
streamConnection = null;
|
|
@@ -132,10 +214,33 @@ export function waitForEvents({ event_type, channel, source, timeout_ms = 30000,
|
|
|
132
214
|
});
|
|
133
215
|
}
|
|
134
216
|
export function connectStream() {
|
|
135
|
-
|
|
217
|
+
// The reconnectTimer check keeps an external caller (a tool call landing in
|
|
218
|
+
// the gap between a drop and the scheduled retry) from opening a competing
|
|
219
|
+
// request: scheduleReconnect nulls streamConnection, so without this the
|
|
220
|
+
// call would slip past the first check, and its failure would schedule a
|
|
221
|
+
// second timer chain. The loop itself is unaffected: the timer callback
|
|
222
|
+
// nulls reconnectTimer before calling here.
|
|
223
|
+
if (streamConnection || reconnectTimer || !transport?.isForwarded())
|
|
136
224
|
return;
|
|
225
|
+
// Ownership guard shared by all three failure callbacks of this request. A
|
|
226
|
+
// destroyed request emits its failure events asynchronously (verified: res
|
|
227
|
+
// "error"/"aborted" fire a tick after destroy()), so by the time a stale
|
|
228
|
+
// callback runs, a NEWER healthy stream may own streamConnection. Without
|
|
229
|
+
// this check the stale callback would null the live stream (orphaning it,
|
|
230
|
+
// still buffering, no longer reachable by destroyStream) and schedule a
|
|
231
|
+
// duplicate connect: two live streams double-delivering every event. The
|
|
232
|
+
// guard also dedups the three callbacks of one failed attempt: the first to
|
|
233
|
+
// run hands ownership to scheduleReconnect, the rest see a mismatch.
|
|
234
|
+
const fail = () => {
|
|
235
|
+
if (streamConnection !== req)
|
|
236
|
+
return;
|
|
237
|
+
scheduleReconnect();
|
|
238
|
+
};
|
|
137
239
|
const req = http.get({ host: RADAR_HOST, port: RADAR_PORT, path: "/api/stream", timeout: 0 }, (res) => {
|
|
138
240
|
streamConnected = true;
|
|
241
|
+
// Connected cleanly, so the next disconnect starts its rebuild cadence
|
|
242
|
+
// from attempt 1 rather than inheriting a counter grown across the session.
|
|
243
|
+
reconnectAttempts = 0;
|
|
139
244
|
// Fire the reconnect hook on a true reconnect (not the first connect). Kept in its own fn so
|
|
140
245
|
// the logic is unit-testable without a live socket.
|
|
141
246
|
noteStreamConnected();
|
|
@@ -156,21 +261,9 @@ export function connectStream() {
|
|
|
156
261
|
}
|
|
157
262
|
}
|
|
158
263
|
});
|
|
159
|
-
res.on("end",
|
|
160
|
-
|
|
161
|
-
streamConnected = false;
|
|
162
|
-
setTimeout(connectStream, 2000);
|
|
163
|
-
});
|
|
164
|
-
res.on("error", () => {
|
|
165
|
-
streamConnection = null;
|
|
166
|
-
streamConnected = false;
|
|
167
|
-
setTimeout(connectStream, 2000);
|
|
168
|
-
});
|
|
169
|
-
});
|
|
170
|
-
req.on("error", () => {
|
|
171
|
-
streamConnection = null;
|
|
172
|
-
streamConnected = false;
|
|
173
|
-
setTimeout(connectStream, 2000);
|
|
264
|
+
res.on("end", fail);
|
|
265
|
+
res.on("error", fail);
|
|
174
266
|
});
|
|
267
|
+
req.on("error", fail);
|
|
175
268
|
streamConnection = req;
|
|
176
269
|
}
|
|
@@ -30,6 +30,15 @@ export interface DeviceTransport {
|
|
|
30
30
|
activate(timeoutMinutes: number): void;
|
|
31
31
|
/** Reset all connection state (forwarding, activation, caches). */
|
|
32
32
|
resetState(): void;
|
|
33
|
+
/**
|
|
34
|
+
* Drop only the cached forwarding state so the next ensureForward() rebuilds
|
|
35
|
+
* the mapping, keeping activation state and the detected user id intact.
|
|
36
|
+
* Reconnect paths use this instead of resetState(): a full reset mid-session
|
|
37
|
+
* would force a user re-detect that can rebind a work-profile session to
|
|
38
|
+
* user 0 while the app process is briefly down. Optional; callers fall back
|
|
39
|
+
* to resetState() when absent.
|
|
40
|
+
*/
|
|
41
|
+
dropForward?(): void;
|
|
33
42
|
/** Whether forwarding has been established. */
|
|
34
43
|
isForwarded(): boolean;
|
|
35
44
|
/** Current auto-shutdown timeout in minutes. */
|
|
@@ -89,6 +98,15 @@ export interface DeviceTransport {
|
|
|
89
98
|
* "device not connected" message. Optional; implementations may omit it.
|
|
90
99
|
*/
|
|
91
100
|
getLastForwardError?(): string | null;
|
|
101
|
+
/**
|
|
102
|
+
* Returns the error message from the last `activate()` attempt, or null if the
|
|
103
|
+
* last attempt succeeded or none has happened. activate() itself never throws
|
|
104
|
+
* (a failed broadcast is expected when no device is attached), so this is the
|
|
105
|
+
* only way callers can tell "activated" from "broadcast never landed" and
|
|
106
|
+
* report a real error instead of a silently dead session. Optional;
|
|
107
|
+
* implementations may omit it.
|
|
108
|
+
*/
|
|
109
|
+
getLastActivateError?(): string | null;
|
|
92
110
|
/**
|
|
93
111
|
* Returns the path of the session-scoped log capture file, or null if no
|
|
94
112
|
* capture is running. Surfaced in tool responses so the model can reason
|
package/dist/web/server.js
CHANGED
|
@@ -5,6 +5,7 @@ import path from "path";
|
|
|
5
5
|
import { spawn } from "child_process";
|
|
6
6
|
import { fileURLToPath } from "url";
|
|
7
7
|
import { AndroidTransport, resolveAdbPath } from "../shared/android.js";
|
|
8
|
+
import { planReconnect } from "../shared/stream.js";
|
|
8
9
|
import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
|
|
9
10
|
import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, } from "../shared/db.js";
|
|
10
11
|
import { LogSession } from "./log-session.js";
|
|
@@ -452,13 +453,15 @@ function handleEnable(res) {
|
|
|
452
453
|
});
|
|
453
454
|
return;
|
|
454
455
|
}
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
456
|
+
// activate() never throws; a failed broadcast is recorded on the transport.
|
|
457
|
+
// Surfacing it here gives the dashboard user the actual adb error instead of
|
|
458
|
+
// a bare enabled:false after the ping probe times out.
|
|
459
|
+
transport.activate(transport.getTimeoutMinutes());
|
|
460
|
+
const activateError = transport.getLastActivateError?.() ?? null;
|
|
461
|
+
if (activateError) {
|
|
459
462
|
sendJson(res, 200, {
|
|
460
463
|
enabled: false,
|
|
461
|
-
error: `Broadcast failed: ${
|
|
464
|
+
error: `Broadcast failed: ${activateError}. Is the device connected?`,
|
|
462
465
|
});
|
|
463
466
|
return;
|
|
464
467
|
}
|
|
@@ -469,7 +472,15 @@ function handleEnable(res) {
|
|
|
469
472
|
if (replied)
|
|
470
473
|
return;
|
|
471
474
|
replied = true;
|
|
472
|
-
|
|
475
|
+
// A failed probe gets guidance, not a bare false: the broadcast landed (or
|
|
476
|
+
// exited 0 with no receiver), so the likely causes are a build without the
|
|
477
|
+
// radar modules or the wrong profile. Mirrors the MCP enable message.
|
|
478
|
+
sendJson(res, 200, enabled
|
|
479
|
+
? { enabled }
|
|
480
|
+
: {
|
|
481
|
+
enabled,
|
|
482
|
+
error: "Radar broadcast sent but the device server did not respond. Is a debug build with the slack-radar modules running on the active profile?",
|
|
483
|
+
});
|
|
473
484
|
};
|
|
474
485
|
const probe = http.request({
|
|
475
486
|
host: RADAR_HOST,
|
|
@@ -1001,16 +1012,11 @@ function handleStream(req, res) {
|
|
|
1001
1012
|
return;
|
|
1002
1013
|
settled = true;
|
|
1003
1014
|
retries++;
|
|
1004
|
-
//
|
|
1005
|
-
//
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
setTimeout(connect, 1500);
|
|
1010
|
-
}
|
|
1011
|
-
else {
|
|
1012
|
-
setTimeout(connect, 2000);
|
|
1013
|
-
}
|
|
1015
|
+
// planReconnect (shared/stream.ts) owns the cadence: every other retry it
|
|
1016
|
+
// rebuilds a clean forward before reconnecting and returns the delay. One
|
|
1017
|
+
// implementation for this proxy and the MCP stream, so a tuning change
|
|
1018
|
+
// cannot silently move only one of them.
|
|
1019
|
+
setTimeout(connect, planReconnect(transport, retries));
|
|
1014
1020
|
};
|
|
1015
1021
|
const connect = () => {
|
|
1016
1022
|
if (closed)
|