@slack/radar-mcp 1.18.0 → 1.19.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/README.md +9 -4
- package/dist/mcp/index.js +18 -1
- package/dist/mcp/web-child-env.js +10 -7
- package/dist/shared/android.d.ts +10 -21
- package/dist/shared/android.js +40 -10
- package/dist/shared/dashboard-screen.d.ts +2 -2
- package/dist/shared/ios.d.ts +5 -10
- package/dist/shared/ios.js +23 -5
- package/dist/shared/screen-artifacts.d.ts +18 -1
- package/dist/shared/screen-artifacts.js +18 -2
- package/dist/shared/screen.d.ts +8 -14
- package/dist/shared/screen.js +26 -45
- package/dist/shared/transport.d.ts +31 -19
- package/dist/shared/wire.d.ts +24 -0
- package/dist/shared/wire.js +6 -0
- package/dist/web/bin.js +13 -9
- package/dist/web/macapp/RadarApp.swift +24 -4
- package/dist/web/public/index.html +39 -4
- package/dist/web/public/next/app.js +186 -18
- package/dist/web/public/next/feed.js +60 -11
- package/dist/web/public/next/filter.js +24 -11
- package/dist/web/public/next/screen.js +154 -73
- package/dist/web/public/next/store.js +639 -28
- package/dist/web/server.d.ts +29 -8
- package/dist/web/server.js +634 -65
- package/package.json +1 -1
package/dist/web/server.js
CHANGED
|
@@ -16,6 +16,9 @@ import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../s
|
|
|
16
16
|
import { LogSession } from "./log-session.js";
|
|
17
17
|
import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
|
|
18
18
|
import { grantScreenConsent, hasScreenConsent, detectDisplay, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, capturePath, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
|
|
19
|
+
// The disk half of the screen reap, imported from the module that owns the only implementation of
|
|
20
|
+
// it. screen.js re-exports the same function for its own callers.
|
|
21
|
+
import { SCREEN_DIRECTORY, cleanupRecordings } from "../shared/screen-artifacts.js";
|
|
19
22
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
20
23
|
const WEB_PORT = Number(process.env.SLACK_RADAR_WEB_PORT ?? WEB_PORT_DEFAULT);
|
|
21
24
|
const INDEX_PATH = path.join(__dirname, "public", "index.html");
|
|
@@ -63,15 +66,79 @@ const SPEC_PATH = path.join(SPEC_DIR, `web-spec-${WEB_PORT}.json`);
|
|
|
63
66
|
// (JSON.stringify of the body) on every poll, and adding fields here would perturb that
|
|
64
67
|
// fingerprint every launch for a reason unrelated to the actual spec.
|
|
65
68
|
const SELF_HEAL_PATH = path.join(SPEC_DIR, "self-heal.json");
|
|
69
|
+
// mcp/index.ts overwrites this on every MCP server boot. Per-machine like self-heal.json (not
|
|
70
|
+
// port-scoped): the question is "has any MCP server booted on this machine", which is not a
|
|
71
|
+
// property of a port. Unlike self-heal.json the writer is a SEPARATE process that can be a
|
|
72
|
+
// different version, so a missing marker means "not seen yet", never "the tools are missing".
|
|
73
|
+
// Resolved per call, not at module load like SPEC_DIR: os.homedir() reads HOME at call time,
|
|
74
|
+
// which lets an in-process test point the read at a scratch home instead of touching the
|
|
75
|
+
// developer's real marker.
|
|
76
|
+
function mcpSeenPath() {
|
|
77
|
+
return path.join(os.homedir(), ".slack-radar", "mcp-last-seen.json");
|
|
78
|
+
}
|
|
66
79
|
const transport = createTransport();
|
|
67
80
|
const dashboardScreen = createDashboardScreenController(transport);
|
|
68
|
-
// The serial
|
|
69
|
-
//
|
|
70
|
-
//
|
|
71
|
-
// DIFFER on a null pin: `switched` is
|
|
72
|
-
//
|
|
73
|
-
|
|
81
|
+
// The serial this process last did screen housekeeping for: seeded by boot's orphan reap
|
|
82
|
+
// (armDevice) and advanced by every /enable that pins real hardware. Kept here rather than
|
|
83
|
+
// trusting `selection.switched`, so the decision cannot be perturbed by anything that clears
|
|
84
|
+
// ANDROID_SERIAL or by a reconcile change. The two also DIFFER on a null pin: `switched` is
|
|
85
|
+
// absent when nothing is attached, while this keeps the last real arm across an empty-device
|
|
86
|
+
// enable, which turns out to be the interesting case.
|
|
74
87
|
let lastArmedSerial = null;
|
|
88
|
+
// Whether the orphan reap has run AT ALL in this process. The one-shot itself is decided in one
|
|
89
|
+
// place, reapScreenOnce below, so boot and /enable cannot drift on the question "has this process
|
|
90
|
+
// reaped yet". handleEnable's device-switch teardown also marks the flag spent, because a switch
|
|
91
|
+
// earns a teardown on every switch rather than once per process, so it is deliberately not a
|
|
92
|
+
// caller of the one-shot.
|
|
93
|
+
let reapedThisProcess = false;
|
|
94
|
+
// Only the dashboard on the DEFAULT port reaps unprompted at boot. The pkill matches by cmdline
|
|
95
|
+
// device-wide, and handlePortInUse hands people `SLACK_RADAR_WEB_PORT=8101 slack-radar web` in an
|
|
96
|
+
// error message, so a sidecar launched on that advice would kill the primary dashboard's live cast
|
|
97
|
+
// with nobody pressing anything. A sidecar leaves reapedThisProcess false, so its /enable fallback
|
|
98
|
+
// still reaps on a press, which is where the responsibility belongs.
|
|
99
|
+
const MAY_REAP_AT_BOOT = WEB_PORT === WEB_PORT_DEFAULT;
|
|
100
|
+
/**
|
|
101
|
+
* The one full screen teardown a process performs on its own initiative: kill any orphaned
|
|
102
|
+
* device-side screenrecord a crashed predecessor left running, and delete its stale clips.
|
|
103
|
+
*
|
|
104
|
+
* Owns the one-shot decision on `reapedThisProcess`, so boot and /enable cannot drift on "has
|
|
105
|
+
* this process reaped yet", and returns whether it performed the teardown so a caller with
|
|
106
|
+
* nothing else to do can fall back to a detection reset. (The device-switch teardown in
|
|
107
|
+
* handleEnable marks the flag spent without calling this; see the flag's own comment.)
|
|
108
|
+
*
|
|
109
|
+
* The switch memory is deliberately NOT its business: `lastArmedSerial` records what a process
|
|
110
|
+
* ARMED, which happens on boots this function never runs for.
|
|
111
|
+
*
|
|
112
|
+
* `serial` null means no device to reap ON: zero attached, an ambiguous multi-device desk, an
|
|
113
|
+
* unauthorized device, or a listing adb could not read. The pkill needs a serial, so it waits for
|
|
114
|
+
* a later call; `clearFilesWithoutDevice` lets BOOT still delete a killed predecessor's clips in
|
|
115
|
+
* that state, which needs no device. /enable passes false, because by then the clips on disk can
|
|
116
|
+
* be this process's own work.
|
|
117
|
+
*
|
|
118
|
+
* Callers that cannot reach this at boot, and therefore depend on the /enable fallback:
|
|
119
|
+
* - iOS never reaps at boot: armDevice needs selectDeviceAsync and only AndroidTransport
|
|
120
|
+
* implements it, so /enable is iOS's only session-boundary screen cleanup. Permanent.
|
|
121
|
+
* - SLACK_RADAR_NO_ARM / SLACK_RADAR_AGENT_LAUNCH return in armOnBoot before armDevice.
|
|
122
|
+
* - A dashboard on a non-default port, per MAY_REAP_AT_BOOT above.
|
|
123
|
+
*/
|
|
124
|
+
function reapScreenOnce(serial, clearFilesWithoutDevice) {
|
|
125
|
+
if (reapedThisProcess)
|
|
126
|
+
return false;
|
|
127
|
+
if (serial === null) {
|
|
128
|
+
// Disk half only. Deliberately does NOT set the flag: no orphaned screenrecord has been
|
|
129
|
+
// killed yet, so a later pin still has its teardown to spend.
|
|
130
|
+
//
|
|
131
|
+
// Reach worth knowing: ~/.slack-radar/screen is per USER, not per port, so this deletes a
|
|
132
|
+
// second dashboard's captures too, while the pkill behind the serial gate leaves its cast
|
|
133
|
+
// running and writing to an unlinked file, so its save reports a name it cannot serve.
|
|
134
|
+
if (clearFilesWithoutDevice)
|
|
135
|
+
cleanupRecordings();
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
dashboardScreen.reset();
|
|
139
|
+
reapedThisProcess = true;
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
75
142
|
// The ONE ceiling for every device ping this file makes (boot-arm, /health, /enable all go
|
|
76
143
|
// through pingDevice). A shorter one turns ordinary latency into a false negative: boot would
|
|
77
144
|
// read a live-but-slow session as absent, and /health would flap the connection dot. Observed
|
|
@@ -137,6 +204,20 @@ function loadSelfHeal() {
|
|
|
137
204
|
return {};
|
|
138
205
|
}
|
|
139
206
|
}
|
|
207
|
+
// mcpSeen false is the normal "no MCP client has ever connected" state the header's setup hint
|
|
208
|
+
// keys off, so a missing or corrupt marker must read that way rather than as an error. Only the
|
|
209
|
+
// boolean rides the wire: the marker's timestamp is validity evidence for THIS read, and the
|
|
210
|
+
// header renders nothing in the state where a timestamp exists to show.
|
|
211
|
+
function loadSetupHint() {
|
|
212
|
+
try {
|
|
213
|
+
const parsed = JSON.parse(fs.readFileSync(mcpSeenPath(), "utf8"));
|
|
214
|
+
// A timestamp is the whole marker, so a parseable file without one is not evidence of a boot.
|
|
215
|
+
return { mcpSeen: typeof parsed.seenAt === "string" };
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return { mcpSeen: false };
|
|
219
|
+
}
|
|
220
|
+
}
|
|
140
221
|
// Start every run from a clean slate so a refresh/restart opens blank — UNLESS the
|
|
141
222
|
// process was spawned with an initial spec (SLACK_RADAR_INITIAL_SPEC). The MCP
|
|
142
223
|
// open_radar_dashboard handler sets that env on a cold spawn so the spec file is
|
|
@@ -186,6 +267,16 @@ export function cleanupOnBind() {
|
|
|
186
267
|
process.once(sig, cleanupPulledDatabases);
|
|
187
268
|
}
|
|
188
269
|
}
|
|
270
|
+
/**
|
|
271
|
+
* Arm the screen cleanup-on-exit handlers for THIS process. Same post-bind discipline, and the
|
|
272
|
+
* same reason, as cleanupOnBind and seedInitialSpec: the handler deletes ~/.slack-radar/screen
|
|
273
|
+
* captures, which are per USER rather than per port, so a second launcher that LOSES the bind
|
|
274
|
+
* would delete the running dashboard's clips on its way out. Registered from createServer()
|
|
275
|
+
* before, which is exactly the window that made adopting a dashboard cost the winner its saves.
|
|
276
|
+
*/
|
|
277
|
+
export function registerScreenCleanupOnBind() {
|
|
278
|
+
dashboardScreen.registerCleanup();
|
|
279
|
+
}
|
|
189
280
|
// --- Dashboard presence + auto-close ------------------------------------------
|
|
190
281
|
//
|
|
191
282
|
// The dashboard never tore itself down: closing every browser tab left this Node
|
|
@@ -435,20 +526,26 @@ function pingDevice(timeoutMs = PING_PROBE_MS) {
|
|
|
435
526
|
*
|
|
436
527
|
* NOT routed through handleEnable, which is written around an HTTP response. Two of the steps it
|
|
437
528
|
* additionally performs really are no-ops in a fresh process (resetState and resetDbState only clear
|
|
438
|
-
* in-process fields that are already at their defaults)
|
|
439
|
-
*
|
|
440
|
-
*
|
|
441
|
-
*
|
|
442
|
-
*
|
|
443
|
-
*
|
|
529
|
+
* in-process fields that are already at their defaults). The screen teardown is NOT a no-op and runs
|
|
530
|
+
* here instead (see armDevice): boot owns the orphan reap, which is what lets /enable reserve its
|
|
531
|
+
* own teardown for a genuine device switch rather than spend one on its first press. /enable still
|
|
532
|
+
* reaps as a fallback when boot could not pin a serial to reap for, so a launch that cannot arm
|
|
533
|
+
* does not leave the orphan alive for the whole process. One gap is deliberately left rather than
|
|
534
|
+
* claimed away: the switched-device branch (cleanupPulledDatabases + logSession.restart) is gated
|
|
535
|
+
* on a serial inherited from the environment, so a boot carrying a stale ANDROID_SERIAL can
|
|
536
|
+
* legitimately be a switch, and only Reconnect performs that part. If a third step is ever needed
|
|
537
|
+
* here, extract the shared core instead of copying it.
|
|
444
538
|
*/
|
|
445
539
|
export function armOnBoot() {
|
|
446
540
|
// An agent-spawned dashboard must not reach the device on its own. open_radar_dashboard is exempt
|
|
447
|
-
// from the MCP session gate precisely BECAUSE opening a dashboard could not arm anything
|
|
448
|
-
//
|
|
449
|
-
//
|
|
450
|
-
//
|
|
451
|
-
//
|
|
541
|
+
// from the MCP session gate precisely BECAUSE opening a dashboard could not arm anything by itself,
|
|
542
|
+
// and arming here would quietly remove the premise that exemption rests on: an agent call would arm
|
|
543
|
+
// a device and begin logcat capture to disk with no human action, and its child is detached with
|
|
544
|
+
// stdio ignored so even a failure line would reach nobody. The client's automatic re-enable is
|
|
545
|
+
// gated on the same flag (surfaced as /health's self_arm_blocked, and enforced server-side by
|
|
546
|
+
// handleEnable's own ?auto=1 refusal), so neither the boot nor an open tab
|
|
547
|
+
// arms an agent-spawned dashboard. A human launch, whether a terminal `slack-radar web` or the dock
|
|
548
|
+
// app, sets no marker: it arms here, and its tab may recover a dead session unattended.
|
|
452
549
|
if (process.env.SLACK_RADAR_AGENT_LAUNCH)
|
|
453
550
|
return;
|
|
454
551
|
// Escape hatch, matching this file's other automatic-on-boot behaviours (SLACK_RADAR_NO_OPEN,
|
|
@@ -489,6 +586,38 @@ async function armDevice() {
|
|
|
489
586
|
if (!transport.selectDeviceAsync)
|
|
490
587
|
return;
|
|
491
588
|
const selection = await transport.selectDeviceAsync(null);
|
|
589
|
+
// Reap what a crashed predecessor left behind, before any user work exists in THIS process. The
|
|
590
|
+
// pkill's device-wide reach (it matches the `output-format=h264` cmdline, so a hand-run
|
|
591
|
+
// `screenrecord --output-format=h264` is matched too) is why MAY_REAP_AT_BOOT keeps this to the
|
|
592
|
+
// canonical dashboard; the orphans it clears congest the single adb transport for everyone.
|
|
593
|
+
//
|
|
594
|
+
// Ahead of the already-armed check below on purpose: the reap must happen even when boot has
|
|
595
|
+
// nothing to arm, or a crashed dashboard whose device-side session is still live is never
|
|
596
|
+
// cleaned up. reapScreenOnce owns the rest, including deferring to an /enable that landed
|
|
597
|
+
// inside this function's own adb chain and already reaped.
|
|
598
|
+
//
|
|
599
|
+
// A boot that clears files but pins nothing does not make the consent panel's promise
|
|
600
|
+
// unconditional, and that promise is the outgoing process's job anyway (its exit handler
|
|
601
|
+
// deletes the same files with no device involved). The boots listed on reapScreenOnce still
|
|
602
|
+
// leave a KILLED predecessor's clips for one more restart, which is reachable rather than
|
|
603
|
+
// academic: /screen/* gates on consent alone and needs no arm.
|
|
604
|
+
const bootPin = selection.ok ? (selection.serial ?? null) : null;
|
|
605
|
+
if (MAY_REAP_AT_BOOT)
|
|
606
|
+
reapScreenOnce(bootPin, true);
|
|
607
|
+
// Seed the switch memory on EVERY boot that pinned something, outside the reap gate: this
|
|
608
|
+
// records what this process armed, which a sidecar does just as much as the canonical dashboard,
|
|
609
|
+
// while the gate above is only about who may fire a device-wide kill unprompted. Coupling the
|
|
610
|
+
// two would leave a sidecar's first /enable onto DIFFERENT hardware reading as a first pin, so
|
|
611
|
+
// the switch would skip cleanupPulledDatabases and logSession.restart and hand device B device
|
|
612
|
+
// A's retained logcat ring. The first /enable of the SAME hardware still takes the light path.
|
|
613
|
+
//
|
|
614
|
+
// Only when nothing has seeded yet: a deliberate /enable can land inside this function's own
|
|
615
|
+
// adb listing, and its pin is the newer of the two. armDevice runs once per process and
|
|
616
|
+
// handleEnable is the only other writer, so a non-null value here can only be that enable's,
|
|
617
|
+
// and letting a late-resolving boot overwrite it would make the next plain re-arm of the
|
|
618
|
+
// enable's device read as a switch and spend a full teardown on live work.
|
|
619
|
+
if (bootPin && lastArmedSerial === null)
|
|
620
|
+
lastArmedSerial = bootPin;
|
|
492
621
|
if (!selection.ok)
|
|
493
622
|
return;
|
|
494
623
|
// The forward could not be built. Nothing to arm, and the dashboard is still usable for a
|
|
@@ -504,7 +633,7 @@ async function armDevice() {
|
|
|
504
633
|
// devices/emulators found"), and that is the deliberately quiet case. An attached but
|
|
505
634
|
// unauthorized device also selects nothing, so the gate is the raw listing, which keeps
|
|
506
635
|
// exactly that case loud.
|
|
507
|
-
if (reason && selection.devices
|
|
636
|
+
if (reason && (selection.devices?.length ?? 0) > 0) {
|
|
508
637
|
console.log(`Radar could not be armed at startup: ${reason}`);
|
|
509
638
|
}
|
|
510
639
|
return;
|
|
@@ -565,7 +694,6 @@ export function startAutoCloseSweep(server) {
|
|
|
565
694
|
* exercise the route without exiting the process. bin.ts calls createServer() with no args.
|
|
566
695
|
*/
|
|
567
696
|
export function createServer(onShutdown) {
|
|
568
|
-
dashboardScreen.registerCleanup();
|
|
569
697
|
const server = http.createServer((req, res) => {
|
|
570
698
|
// One chokepoint for every route: a request whose Host is not this loopback dashboard is a
|
|
571
699
|
// rebound foreign origin, not our client (see isLocalHostHeader). Rejected before routing so
|
|
@@ -622,6 +750,10 @@ export function createServer(onShutdown) {
|
|
|
622
750
|
sendJson(res, 200, loadSelfHeal());
|
|
623
751
|
return;
|
|
624
752
|
}
|
|
753
|
+
if (url === "/setup-hint" && req.method === "GET") {
|
|
754
|
+
sendJson(res, 200, loadSetupHint());
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
625
757
|
if (url === "/setspec" && req.method === "POST") {
|
|
626
758
|
handleSetSpec(req, res, isAuthoredRequest(req.headers));
|
|
627
759
|
return;
|
|
@@ -656,9 +788,12 @@ export function createServer(onShutdown) {
|
|
|
656
788
|
return;
|
|
657
789
|
}
|
|
658
790
|
if (urlPath === "/enable" && req.method === "POST") {
|
|
659
|
-
const
|
|
791
|
+
const params = new URL(url, `http://localhost:${WEB_PORT}`).searchParams;
|
|
792
|
+
const serial = params.get("device_serial");
|
|
660
793
|
// Deliberately not awaited; handleEnable answers res itself and never rejects.
|
|
661
|
-
|
|
794
|
+
// ?auto=1 marks the dashboard's own unattended recovery; see handleEnable's `auto`.
|
|
795
|
+
const auto = params.get("auto") === "1";
|
|
796
|
+
void handleEnable(res, serial, isAuthoredRequest(req.headers), auto);
|
|
662
797
|
return;
|
|
663
798
|
}
|
|
664
799
|
if (url === "/stream" && req.method === "GET") {
|
|
@@ -954,6 +1089,19 @@ async function handleHealth(res) {
|
|
|
954
1089
|
boundProfile: profile,
|
|
955
1090
|
device_serial: selected?.serial ?? null,
|
|
956
1091
|
device_label: selected?.label ?? null,
|
|
1092
|
+
// Whether THIS PROCESS is forbidden from touching the device on its own. Two reasons
|
|
1093
|
+
// today: an agent spawned it (open_radar_dashboard is exempt from the MCP session gate
|
|
1094
|
+
// precisely because opening a dashboard cannot itself reach the device, and an
|
|
1095
|
+
// agent-spawned tab that re-armed on its own would remove the premise that exemption
|
|
1096
|
+
// rests on), or SLACK_RADAR_NO_ARM, which suppresses the boot arm and is documented as
|
|
1097
|
+
// the opt-out that "most deserves" one because it is the first behaviour to touch
|
|
1098
|
+
// physical hardware. Automatic recovery is the second such behaviour, so it honours the
|
|
1099
|
+
// same flags: otherwise setting NO_ARM stopped the boot arm and a visible tab armed the
|
|
1100
|
+
// device ten seconds later anyway. The client's automatic re-enable reads this and
|
|
1101
|
+
// refuses to arm (handleEnable refuses an ?auto=1 server-side too). Sent as one derived
|
|
1102
|
+
// boolean so a future third reason to refuse has one place to join, and the client needs
|
|
1103
|
+
// no env knowledge.
|
|
1104
|
+
self_arm_blocked: !!process.env.SLACK_RADAR_AGENT_LAUNCH || !!process.env.SLACK_RADAR_NO_ARM,
|
|
957
1105
|
// Capture sources the build declares on ping (seam builds only); null on older builds.
|
|
958
1106
|
sources,
|
|
959
1107
|
});
|
|
@@ -996,6 +1144,7 @@ const READ_ONLY_EXACT = new Set([
|
|
|
996
1144
|
"/health",
|
|
997
1145
|
"/spec",
|
|
998
1146
|
"/self-heal",
|
|
1147
|
+
"/setup-hint", // reads a boolean marker; never touches the device
|
|
999
1148
|
"/stream", // EventSource cannot set headers, so this must stay open
|
|
1000
1149
|
"/backfill",
|
|
1001
1150
|
"/detail",
|
|
@@ -1126,15 +1275,161 @@ processState = "unknown") {
|
|
|
1126
1275
|
onEnabled?.();
|
|
1127
1276
|
return { enabled };
|
|
1128
1277
|
}
|
|
1129
|
-
|
|
1278
|
+
// `instructs` travels with every failed reply: whether the wording tells the user what to do
|
|
1279
|
+
// next, decided where the wording is written rather than guessed from its prose by the client
|
|
1280
|
+
// (some reasons pass adb's own stderr straight through, which no verb list can classify). Here
|
|
1281
|
+
// only the "stopped" wording gives an instruction (launch a debug build and retry).
|
|
1282
|
+
return { enabled, error: deviceServerSilentError(processState), instructs: processState === "stopped" };
|
|
1283
|
+
}
|
|
1284
|
+
// One /enable at a time, full stop. Every visible tab diagnoses the same dead session off one
|
|
1285
|
+
// shared memo (diagnoseStreamOutage), so each fires its own immediate ?auto=1 in the same window,
|
|
1286
|
+
// and two concurrent runEnable calls race on the shared transport: the second's resetState()
|
|
1287
|
+
// clears lastActivateError under the first's in-flight activateAsync, and the first then reports
|
|
1288
|
+
// the generic "did not respond" wording instead of the adb error this route exists to show (and
|
|
1289
|
+
// both spend a budget slot on it). A pick for another device mid-flight races the same way and
|
|
1290
|
+
// moves the pin under the first flight's forward, so different targets never overlap either;
|
|
1291
|
+
// they queue. Same shape as outageDiagnosisInflight for the join: a request identical to the
|
|
1292
|
+
// flight in progress receives the winner's reply rather than a refusal, since a refusal is
|
|
1293
|
+
// terminal for the joiner's automation and would spend its whole budget on an attempt that may
|
|
1294
|
+
// have succeeded.
|
|
1295
|
+
//
|
|
1296
|
+
// Joins are for the SAME target only (a pick for device B must not adopt A's answer), and a
|
|
1297
|
+
// human press never joins an unattended flight: the press earns things the timer may not (the
|
|
1298
|
+
// screen teardown, adopting swapped hardware), so it waits for the flight to settle and then
|
|
1299
|
+
// runs on its own. An unattended attempt arriving during a press does join it; the press's reply
|
|
1300
|
+
// is a superset of what the attempt could have earned. A joiner's own `authored` is never
|
|
1301
|
+
// consulted: its only effect would be markKeepAlive, which is global and idempotent, so the
|
|
1302
|
+
// winner's call covers it.
|
|
1303
|
+
let enableInFlight = null;
|
|
1304
|
+
// Test seam: the next runEnable rejects with this error after `delayMs` (long enough for a second
|
|
1305
|
+
// request to join the flight), to prove a rejection still answers every request riding the flight
|
|
1306
|
+
// instead of leaving them (and the client's Reconnect button) hanging.
|
|
1307
|
+
let enableFaultForTest = null;
|
|
1308
|
+
export function _setEnableFaultForTest(err, delayMs = 300) {
|
|
1309
|
+
enableFaultForTest = err ? { err, delayMs } : null;
|
|
1310
|
+
}
|
|
1311
|
+
async function handleEnable(res, deviceSerial, authored,
|
|
1312
|
+
// An UNATTENDED re-arm (the dashboard's own automatic recovery of a diagnosed-dead session,
|
|
1313
|
+
// marked with ?auto=1). See runEnable for what it may and may not do.
|
|
1314
|
+
auto = false) {
|
|
1315
|
+
// `||`, not `??`: an empty ?device_serial= means "no serial" to selectDevice too, so the two
|
|
1316
|
+
// requests must share one slot key.
|
|
1317
|
+
const target = deviceSerial || null;
|
|
1318
|
+
// The server-side half of the self-arm consent boundary. The client refuses off /health's
|
|
1319
|
+
// self_arm_blocked, but that field only reaches it on the first /health reply, and the
|
|
1320
|
+
// no_session diagnosis can beat that reply on a fresh tab, so the promise that an
|
|
1321
|
+
// agent-spawned (or SLACK_RADAR_NO_ARM) process never arms on its own is enforced here, where
|
|
1322
|
+
// the ?auto=1 marker already arrives. Answered before any side effect and before any join: a
|
|
1323
|
+
// forbidden process must not even pin a device for an attempt it is refusing, and this
|
|
1324
|
+
// per-request refusal must never be replaced by the reply of a human press it overlaps.
|
|
1325
|
+
if (auto && (process.env.SLACK_RADAR_AGENT_LAUNCH || process.env.SLACK_RADAR_NO_ARM)) {
|
|
1326
|
+
sendJson(res, 200, {
|
|
1327
|
+
enabled: false,
|
|
1328
|
+
error: "This dashboard may not arm the device on its own. Press Reconnect to arm it.",
|
|
1329
|
+
instructs: true,
|
|
1330
|
+
// A machine-readable marker for a refusal no later automatic attempt can change: the client
|
|
1331
|
+
// reads it to stop retrying and tell the user the next press is theirs, instead of burning
|
|
1332
|
+
// its budget on attempts this route will refuse the same way every time.
|
|
1333
|
+
refusal: "self_arm_blocked",
|
|
1334
|
+
});
|
|
1335
|
+
return;
|
|
1336
|
+
}
|
|
1337
|
+
// The rules above are held as invariants, not checked once: after any wait the slot may hold a
|
|
1338
|
+
// NEW flight (another tab's attempt, a pick for another device), so re-evaluate until nothing
|
|
1339
|
+
// stands in the way. The loop hands out its decision: the flight this request may join, or
|
|
1340
|
+
// null for "run your own". Acting on that binding rather than re-reading the slot keeps the
|
|
1341
|
+
// rule in one place; a re-read would need the same predicate again and would rot the first
|
|
1342
|
+
// time an await lands between the two.
|
|
1343
|
+
let joinable = null;
|
|
1344
|
+
for (;;) {
|
|
1345
|
+
const flight = enableInFlight;
|
|
1346
|
+
if (!flight)
|
|
1347
|
+
break;
|
|
1348
|
+
if (flight.serial === target && (auto || !flight.auto)) {
|
|
1349
|
+
joinable = flight;
|
|
1350
|
+
break;
|
|
1351
|
+
}
|
|
1352
|
+
await flight.p.catch(() => undefined);
|
|
1353
|
+
}
|
|
1354
|
+
let p;
|
|
1355
|
+
if (joinable) {
|
|
1356
|
+
p = joinable.p;
|
|
1357
|
+
}
|
|
1358
|
+
else {
|
|
1359
|
+
// .finally with an identity check, so a flight that settles after a successor took the slot
|
|
1360
|
+
// never clears the successor.
|
|
1361
|
+
p = runEnable(target, authored, auto).finally(() => {
|
|
1362
|
+
if (enableInFlight?.p === p)
|
|
1363
|
+
enableInFlight = null;
|
|
1364
|
+
});
|
|
1365
|
+
enableInFlight = { serial: target, auto, p };
|
|
1366
|
+
}
|
|
1367
|
+
let reply;
|
|
1368
|
+
try {
|
|
1369
|
+
reply = await p;
|
|
1370
|
+
}
|
|
1371
|
+
catch (e) {
|
|
1372
|
+
// Nothing in runEnable is meant to reject, but a rejection that escaped here left every
|
|
1373
|
+
// request on the flight unanswered: the client's fetch never resolved, `enabling` stayed
|
|
1374
|
+
// latched, the Reconnect button stayed disabled and the automation never ran again.
|
|
1375
|
+
reply = {
|
|
1376
|
+
status: 500,
|
|
1377
|
+
body: { enabled: false, error: `Enable failed: ${e.message}. Try again.`, instructs: true },
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
sendJson(res, reply.status, reply.body);
|
|
1130
1381
|
}
|
|
1131
1382
|
/**
|
|
1132
|
-
*
|
|
1383
|
+
* The /enable body: one attempt against the device, run by handleEnable at most once at a time
|
|
1384
|
+
* per target. Re-arm Radar from the dashboard. Mirrors the recovery sequence: reset cached
|
|
1133
1385
|
* forward state, rebuild a clean adb forward, and re-broadcast activation, so the
|
|
1134
1386
|
* user never has to drop to a terminal. Delegates entirely to AndroidTransport;
|
|
1135
1387
|
* no adb shelling here.
|
|
1136
1388
|
*/
|
|
1137
|
-
async function
|
|
1389
|
+
async function runEnable(deviceSerial, authored,
|
|
1390
|
+
// An UNATTENDED re-arm (the dashboard's own automatic recovery of a diagnosed-dead session,
|
|
1391
|
+
// marked with ?auto=1). It never takes the destructive screen teardown below — that reap
|
|
1392
|
+
// kills a live cast and deletes saved recordings, so a human press or an MCP enable earns
|
|
1393
|
+
// it and a timer does not. Two refusals in this handler enforce that: an auto attempt from
|
|
1394
|
+
// a process whose env forbids self-arming is refused before any device work, and an auto
|
|
1395
|
+
// attempt onto DIFFERENT hardware than this process last armed is refused before the
|
|
1396
|
+
// teardown decision; the same-device auto path takes the detection-only reset.
|
|
1397
|
+
auto) {
|
|
1398
|
+
if (enableFaultForTest) {
|
|
1399
|
+
const fault = enableFaultForTest;
|
|
1400
|
+
enableFaultForTest = null;
|
|
1401
|
+
await new Promise((r) => setTimeout(r, fault.delayMs));
|
|
1402
|
+
throw fault.err;
|
|
1403
|
+
}
|
|
1404
|
+
// The unattended path decides "different hardware?" BEFORE anything is touched. selectDevice
|
|
1405
|
+
// below pins as it answers, and the reset/select/DB-drop/logcat-restart that used to run ahead
|
|
1406
|
+
// of this check had already re-pointed the process at the new device by the time the refusal
|
|
1407
|
+
// went out, under wording that said nothing had moved. resolveDevice is the same pick with no
|
|
1408
|
+
// pin, so a refused attempt leaves the process exactly as it found it (the transport keeps
|
|
1409
|
+
// its old selection, the pulled-DB scratch and the retained logcat ring stay). A transport
|
|
1410
|
+
// without resolveDevice falls back to the post-pin check further down. The listing runs again
|
|
1411
|
+
// inside selectDevice below; that second listing is the price of a refusal that changes
|
|
1412
|
+
// nothing, so do not reuse this one to save it.
|
|
1413
|
+
if (auto && transport.resolveDevice) {
|
|
1414
|
+
const would = transport.resolveDevice(deviceSerial ?? null);
|
|
1415
|
+
const target = would.ok ? (would.serial ?? null) : null;
|
|
1416
|
+
if (target !== null && lastArmedSerial !== null && target !== lastArmedSerial) {
|
|
1417
|
+
return { status: 200, body: {
|
|
1418
|
+
enabled: false,
|
|
1419
|
+
// "A different device" rather than "the device changed": the pin has not moved, and the
|
|
1420
|
+
// header's device chip may already be naming the newcomer as the one attached.
|
|
1421
|
+
error: "A different device is attached. Press Reconnect to use it.",
|
|
1422
|
+
instructs: true,
|
|
1423
|
+
// Terminal for the automation (see the marker on the env refusal above): lastArmedSerial is
|
|
1424
|
+
// kept, so every later unattended attempt onto this device is refused identically.
|
|
1425
|
+
refusal: "device_changed",
|
|
1426
|
+
// The pin did not move to the new device: this is still the old one, or null once the
|
|
1427
|
+
// listing noticed the old one is gone (every listing reconciles a vanished pin). Never the
|
|
1428
|
+
// new serial, so the client's baseline cannot advance off a refusal that armed nothing.
|
|
1429
|
+
device_serial: transport.getSelectedDevice?.()?.serial ?? null,
|
|
1430
|
+
} };
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1138
1433
|
transport.resetState();
|
|
1139
1434
|
// A reconnect may be a different device / re-armed profile, so drop the cached DB user
|
|
1140
1435
|
// set + sqlite path; the next /dbs re-detects the profiles fresh.
|
|
@@ -1147,12 +1442,12 @@ async function handleEnable(res, deviceSerial, authored) {
|
|
|
1147
1442
|
// here with the list, before forwarding OR the screen reset.
|
|
1148
1443
|
const selection = transport.selectDevice?.(deviceSerial ?? null);
|
|
1149
1444
|
if (selection && !selection.ok) {
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1445
|
+
return { status: 409, body: {
|
|
1446
|
+
enabled: false,
|
|
1447
|
+
error: selection.error,
|
|
1448
|
+
instructs: selection.instructs,
|
|
1449
|
+
devices: selection.devices,
|
|
1450
|
+
} };
|
|
1156
1451
|
}
|
|
1157
1452
|
// The serial pinned at REPLY time, which under an overlapping /enable can differ from the pin
|
|
1158
1453
|
// this press made -- and reply time is the correct read: the verify probe rode the forward as
|
|
@@ -1167,21 +1462,74 @@ async function handleEnable(res, deviceSerial, authored) {
|
|
|
1167
1462
|
// deletes the saved recordings, and tears down a live cast the user may be watching this second;
|
|
1168
1463
|
// iOS's deletes the saved recordings on disk. Running that on every enable meant a plain re-arm
|
|
1169
1464
|
// of the SAME device destroyed work nobody asked it to, and it made the enable route unsafe to
|
|
1170
|
-
// call from anything automatic. So the full teardown is
|
|
1465
|
+
// call from anything automatic. So the full teardown is earned by one of two things:
|
|
1171
1466
|
// - the pin moved to DIFFERENT hardware, so every piece of per-device screen state is stale, or
|
|
1172
|
-
// -
|
|
1173
|
-
//
|
|
1467
|
+
// - nothing has reaped in this process yet, which reapScreenOnce answers: boot never pinned a
|
|
1468
|
+
// serial, never ran at all, or was a sidecar on a non-default port.
|
|
1469
|
+
//
|
|
1470
|
+
// The second is not the old per-process one-shot back: that spent a teardown on the first enable
|
|
1471
|
+
// even when boot had already reaped. reapScreenOnce fires only when boot did not, and without it
|
|
1472
|
+
// such a process never reaps for its whole lifetime, because the switch gate needs a prior armed
|
|
1473
|
+
// serial and only an arm can set one. Neither is ever earned by an unattended attempt (see the
|
|
1474
|
+
// `auto` parameter): a switched auto attempt is refused outright below, and a same-device one
|
|
1475
|
+
// takes the detection-only reset.
|
|
1476
|
+
//
|
|
1477
|
+
// Live work IS in reach on that path, and iOS is where it matters. armDevice returns before the
|
|
1478
|
+
// reap unless the transport implements selectDeviceAsync, and only AndroidTransport does
|
|
1479
|
+
// (src/shared/ios.ts has the sync selectDevice alone), so boot never reaps on iOS and this
|
|
1480
|
+
// fallback is the only session-boundary screen cleanup iOS gets. An iOS recording also needs no
|
|
1481
|
+
// /enable to exist: startRecording only needs ensureForward, which selects the booted simulator
|
|
1482
|
+
// itself. So a first /enable there can stop a recording the user started. Kept anyway, because
|
|
1483
|
+
// deleting this branch would remove screen cleanup from iOS entirely. Android reaches less far:
|
|
1484
|
+
// the common ambiguous host cannot resolve a device for screenrecord without a pin, so no cast
|
|
1485
|
+
// can have started, and only a single-device host with the boot arm suppressed can hold live work.
|
|
1486
|
+
//
|
|
1174
1487
|
// Everything else gets the detection reset only, which is all a same-device re-arm actually needs.
|
|
1175
1488
|
const pinned = selection && selection.ok ? (selection.serial ?? null) : null;
|
|
1176
1489
|
// A null pin means "nothing attached", not "the hardware changed".
|
|
1177
1490
|
const switched = pinned !== null && lastArmedSerial !== null && pinned !== lastArmedSerial;
|
|
1178
|
-
//
|
|
1179
|
-
//
|
|
1180
|
-
|
|
1181
|
-
|
|
1491
|
+
// An unattended attempt must not adopt DIFFERENT hardware than this process last armed: a
|
|
1492
|
+
// hardware swap is a human-scale event, and the swap teardown below (kill the live cast,
|
|
1493
|
+
// delete saved clips, pkill screenrecord device-wide) is exactly the destructive step a
|
|
1494
|
+
// timer never earns. Refusing — rather than arming without the teardown — also keeps
|
|
1495
|
+
// lastArmedSerial intact, so the press that follows still reads the swap and spends the
|
|
1496
|
+
// teardown it is owed; arming here and advancing the serial would hide the swap from that
|
|
1497
|
+
// press.
|
|
1498
|
+
if (switched && auto) {
|
|
1499
|
+
// The pin has already moved to the new hardware (selectDevice above), and the stream proxy
|
|
1500
|
+
// reasserts its forward onto the current pin on every connect, so from here the tab reads the
|
|
1501
|
+
// NEW device. The per-device state that belongs to the OLD one must not follow it: the
|
|
1502
|
+
// retained logcat ring would replay device A's lines into a stream now serving device B, and
|
|
1503
|
+
// the pulled-DB scratch is A's. Same two drops the switched path below performs; only the
|
|
1504
|
+
// screen teardown is withheld, and lastArmedSerial stays put so the press earns it.
|
|
1505
|
+
cleanupPulledDatabases();
|
|
1506
|
+
logSession?.restart();
|
|
1507
|
+
return { status: 200, body: {
|
|
1508
|
+
enabled: false,
|
|
1509
|
+
// Reachable only on a transport without resolveDevice (or a listing that changed between
|
|
1510
|
+
// the resolve above and this pick), so the pin HAS moved here; say so.
|
|
1511
|
+
error: "The attached device changed and the dashboard now points at it. Press Reconnect to arm it.",
|
|
1512
|
+
instructs: true,
|
|
1513
|
+
// Terminal for the automation (see the marker on the env refusal above): lastArmedSerial is
|
|
1514
|
+
// kept, so every later unattended attempt onto this device is refused identically.
|
|
1515
|
+
refusal: "device_changed",
|
|
1516
|
+
device_serial: pinnedSerial(),
|
|
1517
|
+
} };
|
|
1518
|
+
}
|
|
1519
|
+
if (switched) {
|
|
1520
|
+
// A real hardware change earns the teardown every time, not once per process, so this is the
|
|
1521
|
+
// one reap that does not go through reapScreenOnce. Setting the flag here still tells a later
|
|
1522
|
+
// caller that this process has reaped.
|
|
1523
|
+
reapedThisProcess = true;
|
|
1182
1524
|
dashboardScreen.reset();
|
|
1183
1525
|
}
|
|
1184
|
-
else {
|
|
1526
|
+
else if (auto || !reapScreenOnce(pinned, false)) {
|
|
1527
|
+
// No teardown was owed — or this is the unattended auto re-arm, which may never spend one
|
|
1528
|
+
// (see the `auto` parameter): the one-shot stays unspent for the next human press, which is
|
|
1529
|
+
// where the responsibility for killing a live cast and deleting clips belongs. false covers
|
|
1530
|
+
// the empty-cable enable for the same reason the seed below needs a real pin: there is no
|
|
1531
|
+
// device to reap on, so spending the one-shot there would leave a later real pin with
|
|
1532
|
+
// nothing left to earn a teardown with.
|
|
1185
1533
|
dashboardScreen.resetDetection();
|
|
1186
1534
|
}
|
|
1187
1535
|
// Only remember a serial we actually ARMED. selectDevice returns { ok: true, serial: null } when
|
|
@@ -1215,12 +1563,13 @@ async function handleEnable(res, deviceSerial, authored) {
|
|
|
1215
1563
|
const forwarded = forwardForRead();
|
|
1216
1564
|
if (!forwarded) {
|
|
1217
1565
|
const reason = transport.getLastForwardError?.() ?? null;
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1566
|
+
return { status: 200, body: {
|
|
1567
|
+
enabled: false,
|
|
1568
|
+
error: reason ?? "ADB forward failed. Is a device connected?",
|
|
1569
|
+
// adb's own text, or a question: neither tells the user what to do.
|
|
1570
|
+
instructs: false,
|
|
1571
|
+
device_serial: pinnedSerial(),
|
|
1572
|
+
} };
|
|
1224
1573
|
}
|
|
1225
1574
|
// activateAsync() never throws; a failed broadcast is recorded on the transport.
|
|
1226
1575
|
// Surfacing it here gives the dashboard user the actual adb error instead of a bare
|
|
@@ -1235,27 +1584,33 @@ async function handleEnable(res, deviceSerial, authored) {
|
|
|
1235
1584
|
}
|
|
1236
1585
|
const activateError = transport.getLastActivateError?.() ?? null;
|
|
1237
1586
|
if (activateError) {
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1587
|
+
return { status: 200, body: {
|
|
1588
|
+
enabled: false,
|
|
1589
|
+
error: `Broadcast failed: ${activateError}. Is the device connected?`,
|
|
1590
|
+
instructs: false,
|
|
1591
|
+
device_serial: pinnedSerial(),
|
|
1592
|
+
} };
|
|
1244
1593
|
}
|
|
1245
1594
|
// Verify by pinging the device the same way /health does (the shared pingDevice, so the
|
|
1246
1595
|
// ceiling and the three-state rules cannot drift from the other probe sites).
|
|
1247
1596
|
const ping = await pingDevice();
|
|
1248
1597
|
const enabled = ping.state === "armed" && ping.status === 200;
|
|
1598
|
+
// A verified arm refutes any cached "no_session" the same way a stream connect does (the
|
|
1599
|
+
// memo is evidence about a session this route just restored): without this, another stream
|
|
1600
|
+
// client's mid-retry memo read could announce the pre-arm diagnosis for up to its TTL and
|
|
1601
|
+
// drive that tab to fire a spurious /enable against the live session.
|
|
1602
|
+
if (enabled)
|
|
1603
|
+
invalidateOutageDiagnosis();
|
|
1249
1604
|
// Probe the process state only on the failure path: a successful enable needs no diagnosis,
|
|
1250
1605
|
// and the probe is a real adb round trip. Capped short, because by this point the failure is
|
|
1251
1606
|
// already established and the user is watching a request that has stalled their SSE tabs; an
|
|
1252
1607
|
// explanation must not cost more than the operation it explains. The MCP path keeps the
|
|
1253
1608
|
// patient default, where seconds of ping retries have already elapsed and a real answer
|
|
1254
1609
|
// beats a fast "unknown".
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1610
|
+
return { status: 200, body: {
|
|
1611
|
+
...enableResultBody(enabled, keepAliveHookFor(authored), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
|
|
1612
|
+
device_serial: pinnedSerial(),
|
|
1613
|
+
} };
|
|
1259
1614
|
}
|
|
1260
1615
|
// The device-buffered source kinds, in one table so a new source is one row here: the
|
|
1261
1616
|
// device API route segment (clog and trace pluralize; the rest match the kind name) and
|
|
@@ -1679,13 +2034,12 @@ function handleScreen(req, res) {
|
|
|
1679
2034
|
sendJson(res, 502, { ok: false, error: "screencap failed; is the device awake and connected?" });
|
|
1680
2035
|
return;
|
|
1681
2036
|
}
|
|
1682
|
-
const SC_TMP = path.join(os.homedir(), ".slack-radar", "screen");
|
|
1683
2037
|
const safe = new Date().toISOString().replace(/[:.]/g, "-");
|
|
1684
|
-
const out = path.join(
|
|
2038
|
+
const out = path.join(SCREEN_DIRECTORY, `radar_screen_${safe}.png`);
|
|
1685
2039
|
try {
|
|
1686
|
-
fs.mkdirSync(
|
|
2040
|
+
fs.mkdirSync(SCREEN_DIRECTORY, { recursive: true, mode: 0o700 });
|
|
1687
2041
|
try {
|
|
1688
|
-
fs.chmodSync(
|
|
2042
|
+
fs.chmodSync(SCREEN_DIRECTORY, 0o700);
|
|
1689
2043
|
}
|
|
1690
2044
|
catch { /* best-effort */ }
|
|
1691
2045
|
fs.writeFileSync(out, png, { mode: 0o600 });
|
|
@@ -1861,13 +2215,15 @@ function handleScreen(req, res) {
|
|
|
1861
2215
|
// Drop the server-side copy once it has been handed over. A capture is a full frame of
|
|
1862
2216
|
// whatever is on the phone, and the download is the point of making it, so keeping it after
|
|
1863
2217
|
// delivery just leaves device-screen content sitting in the tmp dir for the rest of the
|
|
1864
|
-
// session -- cleanupRecordings only runs on
|
|
1865
|
-
//
|
|
1866
|
-
//
|
|
2218
|
+
// session -- cleanupRecordings only runs on a session boundary (dashboard boot, a device
|
|
2219
|
+
// switch, a first enable boot could not reap for, a deliberate re-detect) and on exit. The
|
|
2220
|
+
// user's own copy is untouched, and reveal in the packaged app points at that copy in
|
|
2221
|
+
// ~/Downloads, not at this one. Unlinking a file mid-read is safe, this stream keeps its
|
|
2222
|
+
// descriptor.
|
|
1867
2223
|
//
|
|
1868
2224
|
// Hung off "close" rather than "finish" so an ABORTED transfer drops the file too. Nothing
|
|
1869
2225
|
// retries a download, so keeping it after an abort just leaves a full frame of the device
|
|
1870
|
-
// screen in the tmp dir until
|
|
2226
|
+
// screen in the tmp dir until the next session boundary, which is the leftover this removes.
|
|
1871
2227
|
res.on("close", () => {
|
|
1872
2228
|
try {
|
|
1873
2229
|
fs.unlinkSync(p);
|
|
@@ -1965,12 +2321,138 @@ export function parseLogcat(line, resolvePkg = packageForPid) {
|
|
|
1965
2321
|
package: resolvePkg(pidN),
|
|
1966
2322
|
};
|
|
1967
2323
|
}
|
|
2324
|
+
// How long a freshly opened device stream may go without response HEADERS before the attempt is
|
|
2325
|
+
// declared dead. A healthy device answers /api/stream immediately; the pathological case this
|
|
2326
|
+
// bounds is a dead device-side socket behind a LIVE adb forward, where the host adb server
|
|
2327
|
+
// accepts the TCP connection unconditionally and then nothing ever answers — no error event, no
|
|
2328
|
+
// end event, just silence (observed live 2026-09-03: a stream that emitted no _status frame at
|
|
2329
|
+
// all). Generous enough to sit above pingDevice's observed 2.2s worst case.
|
|
2330
|
+
const STREAM_RESPONSE_TIMEOUT_MS = 6000;
|
|
2331
|
+
// Test seam: the real deadline is deliberately generous, which would make every hang-mode test
|
|
2332
|
+
// wait it out in real time. Never read anywhere else.
|
|
2333
|
+
let streamResponseTimeoutMs = STREAM_RESPONSE_TIMEOUT_MS;
|
|
2334
|
+
export function _setStreamResponseTimeoutForTest(ms) {
|
|
2335
|
+
streamResponseTimeoutMs = ms ?? STREAM_RESPONSE_TIMEOUT_MS;
|
|
2336
|
+
}
|
|
2337
|
+
// Why the device stream keeps dying, answered from the device's own socket table — the one read
|
|
2338
|
+
// the adb forward cannot distort (see pingDevice's classification rules: through a forward, an
|
|
2339
|
+
// absent socket and a live-but-hiccuping session both present as resets). ABSENT means no radar
|
|
2340
|
+
// server is bound anywhere on the device: the session ENDED (idle watchdog, app restart), and
|
|
2341
|
+
// only a re-enable brings it back — which the retry loop deliberately never performs (enabling
|
|
2342
|
+
// binds an identity and mutates device state; a read loop must not, and a wire-contract machine
|
|
2343
|
+
// consumer holding /stream must never arm a device by holding it). The dashboard CLIENT acts on
|
|
2344
|
+
// this instead: its auto-re-arm is the human's own tab pressing its own Reconnect.
|
|
2345
|
+
//
|
|
2346
|
+
// One probe at a time, memoized briefly: every open stream connection retries on its own clock,
|
|
2347
|
+
// so several tabs against a dead session would otherwise each run their own adb read (a call
|
|
2348
|
+
// with a 5s ceiling) every few seconds.
|
|
2349
|
+
const OUTAGE_DIAGNOSIS_TTL_MS = 8000;
|
|
2350
|
+
let outageDiagnosisTtlMs = OUTAGE_DIAGNOSIS_TTL_MS;
|
|
2351
|
+
// Test seam for the memo TTL: the collapse-slot invariants below are only observable once the
|
|
2352
|
+
// memo has expired, and 8 seconds of wall clock per assertion is the flake this seam avoids.
|
|
2353
|
+
export function _setOutageDiagnosisTtlForTest(ms) {
|
|
2354
|
+
outageDiagnosisTtlMs = ms ?? OUTAGE_DIAGNOSIS_TTL_MS;
|
|
2355
|
+
}
|
|
2356
|
+
let lastOutageDiagnosis = null;
|
|
2357
|
+
let outageDiagnosisInflight = null;
|
|
2358
|
+
// Bumped wherever a live connect invalidates the diagnosis. A probe is an adb round trip
|
|
2359
|
+
// with a 5s ceiling racing a 1-2s reconnect cadence, so probe-resolves-after-recovery is the
|
|
2360
|
+
// COMMON ordering: without the generation check, that late resolution would re-poison the
|
|
2361
|
+
// just-cleared memo with a fresh timestamp, and any other stream (a second tab) or a quick
|
|
2362
|
+
// re-drop of this one would inherit "no_session" for the full TTL and re-arm against the
|
|
2363
|
+
// live session.
|
|
2364
|
+
let outageDiagnosisGeneration = 0;
|
|
2365
|
+
// Test seam: the real probe reaches a physical device over adb, which a test host may or may
|
|
2366
|
+
// not have, so tests pin the answer instead of inheriting whatever hardware is attached.
|
|
2367
|
+
let outageProbe = () => transport.radarSocketPresentAsync?.() ?? Promise.resolve("unknown");
|
|
2368
|
+
export function _setOutageProbeForTest(probe) {
|
|
2369
|
+
outageProbe = probe ?? (() => transport.radarSocketPresentAsync?.() ?? Promise.resolve("unknown"));
|
|
2370
|
+
lastOutageDiagnosis = null;
|
|
2371
|
+
outageDiagnosisInflight = null;
|
|
2372
|
+
outageDiagnosisGeneration++;
|
|
2373
|
+
// This is the "restore the diagnosis machinery" seam, so the TTL goes back with the rest: a
|
|
2374
|
+
// test that shortened it and forgot its own restore must not leak a 50ms memo into the next.
|
|
2375
|
+
outageDiagnosisTtlMs = OUTAGE_DIAGNOSIS_TTL_MS;
|
|
2376
|
+
}
|
|
2377
|
+
// Test seams for the diagnosis cache itself. The generation rule is a pure invariant about
|
|
2378
|
+
// ordering (a probe that resolves after an invalidation must not cache), and driving it
|
|
2379
|
+
// through the real stream would mean racing an adb-shaped probe against a live reconnect
|
|
2380
|
+
// cadence on the wall clock — the flake this pair exists to avoid.
|
|
2381
|
+
export function _diagnoseOutageForTest() {
|
|
2382
|
+
return diagnoseStreamOutage();
|
|
2383
|
+
}
|
|
2384
|
+
export function _invalidateOutageDiagnosisForTest() {
|
|
2385
|
+
invalidateOutageDiagnosis();
|
|
2386
|
+
}
|
|
2387
|
+
// A live connect refutes any "no_session" — cached, in flight, or both. Exported to the
|
|
2388
|
+
// connect callback only through this helper so the memo and the pending write cannot be
|
|
2389
|
+
// invalidated separately (clearing just the memo was cycle-2's reopened race).
|
|
2390
|
+
function invalidateOutageDiagnosis() {
|
|
2391
|
+
lastOutageDiagnosis = null;
|
|
2392
|
+
// Drop the in-flight slot too: its eventual result is pre-invalidation evidence, and a
|
|
2393
|
+
// post-recovery consult must start a FRESH probe rather than await (or worse, adopt) the
|
|
2394
|
+
// orphan. The orphan's own cleanup is identity-checked, so it cannot null a successor.
|
|
2395
|
+
outageDiagnosisInflight = null;
|
|
2396
|
+
outageDiagnosisGeneration++;
|
|
2397
|
+
}
|
|
2398
|
+
async function diagnoseStreamOutage() {
|
|
2399
|
+
const now = Date.now();
|
|
2400
|
+
if (lastOutageDiagnosis && now - lastOutageDiagnosis.ts < outageDiagnosisTtlMs) {
|
|
2401
|
+
return lastOutageDiagnosis.reason;
|
|
2402
|
+
}
|
|
2403
|
+
if (outageDiagnosisInflight)
|
|
2404
|
+
return outageDiagnosisInflight;
|
|
2405
|
+
const generation = outageDiagnosisGeneration;
|
|
2406
|
+
// A holder rather than a bare binding: the async body needs its own promise's identity for
|
|
2407
|
+
// the slot-release check below, and it can run synchronously up to its first await —
|
|
2408
|
+
// before any direct `const probe = …` binding would initialize.
|
|
2409
|
+
const holder = { p: null };
|
|
2410
|
+
holder.p = (async () => {
|
|
2411
|
+
let reason = null;
|
|
2412
|
+
try {
|
|
2413
|
+
// The probe is CALLED synchronously (concurrent consults rely on it starting inside this
|
|
2414
|
+
// tick), but a synchronous throw is turned into a rejection so the body still suspends at
|
|
2415
|
+
// the await. Without that, a sync throw would let this whole body finish BEFORE the caller
|
|
2416
|
+
// stores holder.p into the collapse slot; the slot would then hold an already-settled
|
|
2417
|
+
// promise that the identity-checked release below never clears, wedging every later
|
|
2418
|
+
// consult on a stale null until the next live connect.
|
|
2419
|
+
let probe;
|
|
2420
|
+
try {
|
|
2421
|
+
probe = Promise.resolve(outageProbe());
|
|
2422
|
+
}
|
|
2423
|
+
catch (e) {
|
|
2424
|
+
probe = Promise.reject(e);
|
|
2425
|
+
}
|
|
2426
|
+
reason = (await probe) === "absent" ? "no_session" : null;
|
|
2427
|
+
}
|
|
2428
|
+
catch {
|
|
2429
|
+
// An unreadable socket table is "unknown", and unknown never classifies an outage.
|
|
2430
|
+
}
|
|
2431
|
+
// Release the collapse slot only if it is still OURS: a probe orphaned by an
|
|
2432
|
+
// invalidation (a live connect, the test seam) must not null a successor's in-flight
|
|
2433
|
+
// promise and briefly break the one-probe-at-a-time collapse.
|
|
2434
|
+
if (outageDiagnosisInflight === holder.p)
|
|
2435
|
+
outageDiagnosisInflight = null;
|
|
2436
|
+
// A stale probe reports nothing and caches nothing: evidence gathered before the
|
|
2437
|
+
// invalidation describes an outage that already ended.
|
|
2438
|
+
if (generation !== outageDiagnosisGeneration)
|
|
2439
|
+
return null;
|
|
2440
|
+
lastOutageDiagnosis = { ts: Date.now(), reason };
|
|
2441
|
+
return reason;
|
|
2442
|
+
})();
|
|
2443
|
+
outageDiagnosisInflight = holder.p;
|
|
2444
|
+
return holder.p;
|
|
2445
|
+
}
|
|
1968
2446
|
/**
|
|
1969
2447
|
* Self-healing SSE proxy. Keeps ONE long-lived response open to the browser and
|
|
1970
2448
|
* internally (re)connects to the device `/api/stream` every couple seconds while
|
|
1971
2449
|
* it is down, so the browser's EventSource never sees a close and never gives up.
|
|
1972
2450
|
* Every other retry it rebuilds the adb forward (the real cause of recurring
|
|
1973
2451
|
* "unreachable"), reusing AndroidTransport rather than shelling adb directly.
|
|
2452
|
+
* When retries keep failing it additionally asks WHY (see diagnoseStreamOutage)
|
|
2453
|
+
* and stamps the answer as `reason` on the `_status` frame, so a client can tell
|
|
2454
|
+
* "transport blip, the proxy will heal this" from "no radar session exists and
|
|
2455
|
+
* someone has to re-enable".
|
|
1974
2456
|
*
|
|
1975
2457
|
* When the active spec wants logs (source "log" or "all"), the handler subscribes
|
|
1976
2458
|
* to the shared session-long logSession: it is first replayed the entire retained
|
|
@@ -1989,11 +2471,26 @@ function handleStream(req, res) {
|
|
|
1989
2471
|
let upstream = null;
|
|
1990
2472
|
let closed = false;
|
|
1991
2473
|
let lastState = "";
|
|
1992
|
-
|
|
1993
|
-
|
|
2474
|
+
let lastReason = "";
|
|
2475
|
+
let headersDeadline = null;
|
|
2476
|
+
const announce = (state, msg, reason) => {
|
|
2477
|
+
// Dedup on state AND reason, with one asymmetry: a diagnosed outage keeps its diagnosis.
|
|
2478
|
+
// The retry loop re-announces generic "waiting" wording on every failed attempt, and once
|
|
2479
|
+
// this outage has been classified (reason set), that generic repeat is the SAME outage
|
|
2480
|
+
// described worse — letting it through would strip the reason the client is acting on
|
|
2481
|
+
// (see the dashboard's auto-re-arm) a second or two after it arrived. A reason CHANGE does
|
|
2482
|
+
// pass: the re-diagnosis retires a stale no_session with reason "undiagnosed" (a frame the
|
|
2483
|
+
// client reads as "drop the latch", not as a diagnosis of its own).
|
|
2484
|
+
if (state === lastState && !reason && lastReason)
|
|
2485
|
+
return;
|
|
2486
|
+
if (state === lastState && (reason ?? "") === lastReason)
|
|
1994
2487
|
return;
|
|
1995
2488
|
lastState = state;
|
|
1996
|
-
|
|
2489
|
+
lastReason = reason ?? "";
|
|
2490
|
+
const event = { state, msg };
|
|
2491
|
+
if (reason)
|
|
2492
|
+
event.reason = reason;
|
|
2493
|
+
res.write(`data: ${JSON.stringify({ type: "_status", event })}\n\n`);
|
|
1997
2494
|
};
|
|
1998
2495
|
// Keep the persistent logcat capture armed for the life of this connection.
|
|
1999
2496
|
// start() is idempotent, so it is safe to call both on initial setup and from
|
|
@@ -2027,6 +2524,41 @@ function handleStream(req, res) {
|
|
|
2027
2524
|
return;
|
|
2028
2525
|
settled = true;
|
|
2029
2526
|
retries++;
|
|
2527
|
+
// A failure that keeps repeating deserves a WHY. The second attempt (the first repeat —
|
|
2528
|
+
// one failure is routine) and a coarse cadence after that, so a fresh classification can
|
|
2529
|
+
// still ARRIVE mid-outage without running an adb probe on every 2s retry. announce never
|
|
2530
|
+
// downgrades a reasoned waiting to a generic one on its own (see its dedup asymmetry), but
|
|
2531
|
+
// a later probe that no longer finds the session absent (the socket is present, or the
|
|
2532
|
+
// table cannot be read because the device is gone) RETIRES a diagnosis this outage
|
|
2533
|
+
// announced: the outage changed nature under the latched reason, and without this the
|
|
2534
|
+
// client's headline kept asserting "no radar session" over a reason span saying the device
|
|
2535
|
+
// is unreachable, while its automation spent attempts on hardware that was not there.
|
|
2536
|
+
// Fire-and-forget: the probe must never delay the reconnect cadence it is describing.
|
|
2537
|
+
if (retries === 2 || retries % 6 === 0) {
|
|
2538
|
+
// A probe orphaned by an invalidation (this tab's own arm landing, an MCP activate, a live
|
|
2539
|
+
// connect) reports null exactly like a fresh "not absent" answer would. The generation tells
|
|
2540
|
+
// them apart: a stale null must not retire a diagnosis against a session that just armed.
|
|
2541
|
+
const generation = outageDiagnosisGeneration;
|
|
2542
|
+
void diagnoseStreamOutage().then((reason) => {
|
|
2543
|
+
// The connected check closes a REPRODUCED race: the probe is an adb round trip (5s
|
|
2544
|
+
// ceiling) racing a 1-2s reconnect cadence, so a session restored during its flight
|
|
2545
|
+
// (an auto-re-arm landing, an MCP activate, a manual press) can reconnect this stream
|
|
2546
|
+
// before the probe resolves — and announcing the stale diagnosis then would drive the
|
|
2547
|
+
// client to fire /enable AGAINST THE LIVE SESSION it just got back, the exact clobber
|
|
2548
|
+
// the socket-table diagnosis exists to prevent.
|
|
2549
|
+
if (closed || lastState === "connected" || generation !== outageDiagnosisGeneration)
|
|
2550
|
+
return;
|
|
2551
|
+
if (reason === null) {
|
|
2552
|
+
// "Not absent" covers both a socket that is present and a table that could not be read
|
|
2553
|
+
// (device gone, adb busy), so the wording asserts no cause; the generic per-retry
|
|
2554
|
+
// message is what the loop would say anyway.
|
|
2555
|
+
if (lastReason === "no_session")
|
|
2556
|
+
announce("waiting", "device not answering, retrying…", "undiagnosed");
|
|
2557
|
+
return;
|
|
2558
|
+
}
|
|
2559
|
+
announce("waiting", "no radar session on the device", reason);
|
|
2560
|
+
});
|
|
2561
|
+
}
|
|
2030
2562
|
// planReconnect (shared/stream.ts) owns the cadence: every other retry it
|
|
2031
2563
|
// rebuilds a clean forward before reconnecting and returns the delay. One
|
|
2032
2564
|
// implementation for this proxy and the MCP stream, so a tuning change
|
|
@@ -2042,12 +2574,44 @@ function handleStream(req, res) {
|
|
|
2042
2574
|
// (tuned for "device end died"), which would only catch a foreign repoint by luck on
|
|
2043
2575
|
// half of attempts; this cheap check-first call covers every attempt instead.
|
|
2044
2576
|
forwardForRead();
|
|
2577
|
+
// Bound the wait for response headers: see STREAM_RESPONSE_TIMEOUT_MS. Without this, the
|
|
2578
|
+
// accepted-but-never-answered connect mode fires none of the callbacks below and the
|
|
2579
|
+
// stream sits silent forever — no _status, no retry, nothing for a client to act on.
|
|
2580
|
+
// Per-ATTEMPT const, mirrored into the connection-scoped slot only for the close
|
|
2581
|
+
// teardown: each attempt's handlers clear their OWN deadline, so a stale attempt's late
|
|
2582
|
+
// error event can never clear the live attempt's timer out from under it.
|
|
2583
|
+
const myDeadline = setTimeout(() => {
|
|
2584
|
+
if (closed)
|
|
2585
|
+
return;
|
|
2586
|
+
announce("waiting", "device not answering, retrying…");
|
|
2587
|
+
try {
|
|
2588
|
+
upstream?.destroy();
|
|
2589
|
+
}
|
|
2590
|
+
catch {
|
|
2591
|
+
// already torn down
|
|
2592
|
+
}
|
|
2593
|
+
retry();
|
|
2594
|
+
}, streamResponseTimeoutMs);
|
|
2595
|
+
headersDeadline = myDeadline;
|
|
2045
2596
|
upstream = http.request({
|
|
2046
2597
|
host: RADAR_HOST,
|
|
2047
2598
|
port: RADAR_PORT,
|
|
2048
2599
|
path: "/api/stream",
|
|
2049
2600
|
method: "GET",
|
|
2050
2601
|
}, (up) => {
|
|
2602
|
+
clearTimeout(myDeadline);
|
|
2603
|
+
if (headersDeadline === myDeadline)
|
|
2604
|
+
headersDeadline = null;
|
|
2605
|
+
// A fresh outage on a long-lived connection must diagnose as early as the first one:
|
|
2606
|
+
// the "second failure" trigger and planReconnect's every-other-attempt forward
|
|
2607
|
+
// rebuild both key off this counter, and neither should inherit the count from an
|
|
2608
|
+
// outage that already recovered.
|
|
2609
|
+
retries = 0;
|
|
2610
|
+
// A live connect refutes any "no_session" — the cached memo AND a probe still in
|
|
2611
|
+
// flight (see invalidateOutageDiagnosis): without this, other stream clients would
|
|
2612
|
+
// re-read the pre-recovery diagnosis for up to its TTL and re-arm against the
|
|
2613
|
+
// healthy session.
|
|
2614
|
+
invalidateOutageDiagnosis();
|
|
2051
2615
|
announce("connected", "device stream connected");
|
|
2052
2616
|
// Re-arm logs on the same path the device proxy heals on: if the device
|
|
2053
2617
|
// dropped and came back, `adb logcat` had exited; restart it (idempotent)
|
|
@@ -2064,6 +2628,9 @@ function handleStream(req, res) {
|
|
|
2064
2628
|
});
|
|
2065
2629
|
});
|
|
2066
2630
|
upstream.on("error", () => {
|
|
2631
|
+
clearTimeout(myDeadline);
|
|
2632
|
+
if (headersDeadline === myDeadline)
|
|
2633
|
+
headersDeadline = null;
|
|
2067
2634
|
announce("waiting", "device unreachable, retrying…");
|
|
2068
2635
|
retry();
|
|
2069
2636
|
});
|
|
@@ -2120,6 +2687,8 @@ function handleStream(req, res) {
|
|
|
2120
2687
|
req.on("close", () => {
|
|
2121
2688
|
closed = true;
|
|
2122
2689
|
clearInterval(heartbeat);
|
|
2690
|
+
if (headersDeadline)
|
|
2691
|
+
clearTimeout(headersDeadline);
|
|
2123
2692
|
if (unsubscribeLogs)
|
|
2124
2693
|
unsubscribeLogs(); // detach listener; capture stays up
|
|
2125
2694
|
try {
|