@slack/radar-mcp 1.11.0 → 1.12.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 +2 -2
- package/dist/mcp/index.js +42 -5
- package/dist/mcp/prefs-tools.d.ts +15 -0
- package/dist/mcp/prefs-tools.js +204 -0
- package/dist/mcp/session-enable.d.ts +2 -1
- package/dist/mcp/session-enable.js +29 -2
- package/dist/mcp/snapshot.js +6 -1
- package/dist/mcp/tools.js +65 -2
- package/dist/shared/android.d.ts +33 -1
- package/dist/shared/android.js +203 -6
- package/dist/shared/constants.d.ts +8 -0
- package/dist/shared/constants.js +13 -1
- package/dist/shared/db.d.ts +14 -0
- package/dist/shared/db.js +16 -5
- package/dist/shared/prefs.d.ts +78 -0
- package/dist/shared/prefs.js +416 -0
- package/dist/shared/transport.d.ts +68 -0
- package/dist/web/log-session.d.ts +13 -0
- package/dist/web/log-session.js +16 -0
- package/dist/web/public/index.html +108 -3
- package/dist/web/public/next/app.js +58 -2
- package/dist/web/public/next/feed.js +261 -12
- package/dist/web/public/next/filter.js +200 -0
- package/dist/web/public/next/prefs.js +399 -0
- package/dist/web/public/next/registry.js +7 -6
- package/dist/web/public/next/store.js +201 -10
- package/dist/web/server.js +214 -5
- package/dist/web/spec.d.ts +7 -7
- package/dist/web/spec.js +12 -9
- package/package.json +1 -1
|
@@ -32,6 +32,7 @@ export const MODES = [
|
|
|
32
32
|
{ key: "trace", label: "Traces", spec: { title: "Traces", summary: "Performance trace spans, click to see timing details and tags.", source: "trace", viz: ["rate", "graph", "feed", "inspector"], series: [{ metric: "ratePerSec", label: "spans/s", unit: "/s" }, { metric: "avg", field: "duration_ms", label: "avg ms", unit: "ms" }] } },
|
|
33
33
|
{ key: "log", label: "Logs", spec: { title: "Device Logs", summary: "Live Slack app logcat, color-coded by level. Scroll the full session buffer, select a range, copy raw lines.", source: "log", viz: ["feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
|
|
34
34
|
{ key: "db", label: "Database", spec: { title: "Device DB", summary: "Browse the on-device SQLite databases (read-only snapshot).", source: "db" } },
|
|
35
|
+
{ key: "prefs", label: "Preferences", spec: { title: "Device Preferences", summary: "Browse the on-device SharedPreferences (including feature-flag overrides), read-only.", source: "prefs" } },
|
|
35
36
|
];
|
|
36
37
|
// A preset is identified by what it DOES, not how it is labelled. canonicalSpecKey reduces a
|
|
37
38
|
// spec to its behavioral identity so a spec that is semantically a preset still matches it
|
|
@@ -73,7 +74,23 @@ class Store {
|
|
|
73
74
|
spec = { blank: true, viz: [] };
|
|
74
75
|
conn = { state: "waiting", msg: "connecting…" };
|
|
75
76
|
profileLabel = "detecting…";
|
|
77
|
+
serverVersion = "";
|
|
76
78
|
profiles = [];
|
|
79
|
+
// Attached devices + the currently pinned one, for the header device picker. Mirrors how
|
|
80
|
+
// profiles/profileLabel are stored: plain fields the header reads via useStoreValue, refreshed
|
|
81
|
+
// off the same poll loop and emitted on a named event.
|
|
82
|
+
devices = [];
|
|
83
|
+
selectedDevice = null;
|
|
84
|
+
// True when the last /_control/devices poll reported adb_error: `adb devices` itself failed
|
|
85
|
+
// (adb not on PATH, server down), which is distinct from "zero devices attached". The header
|
|
86
|
+
// chip renders this differently so the user knows to check adb, not plug in a phone.
|
|
87
|
+
devicesError = false;
|
|
88
|
+
// Last device-select failure text (an /enable 409 or error), or null when the pick succeeded.
|
|
89
|
+
// Distinct from devicesError (adb itself failed) and from conn: a device-select failure used to
|
|
90
|
+
// ride conn via setConn("waiting", …), but any healthy pollHealth flips conn back to connected
|
|
91
|
+
// within 2s and the message vanished before the user read it. This field is owned by
|
|
92
|
+
// selectDevice, survives the health poll, and clears only on a successful pick.
|
|
93
|
+
deviceError = null;
|
|
77
94
|
cache = [];
|
|
78
95
|
cacheKeys = new Set();
|
|
79
96
|
seen = {};
|
|
@@ -86,6 +103,11 @@ class Store {
|
|
|
86
103
|
liveMatches = 0;
|
|
87
104
|
graph = null;
|
|
88
105
|
feedVersion = 0;
|
|
106
|
+
// Bumped on every observed serial change (first pin included), emitted as "db-resync". The DB
|
|
107
|
+
// tab keys its remount off this so it drops stale picked-db/table/results and re-fetches /dbs
|
|
108
|
+
// when the bound device changes — including the null->serial FIRST pin, where the tab loaded
|
|
109
|
+
// unpinned and its /dbs failed with an ambiguous run-as before any device was pinned.
|
|
110
|
+
dbSerialVersion = 0;
|
|
89
111
|
customActive = false;
|
|
90
112
|
lastCustomSpec = null;
|
|
91
113
|
detailCache = new Map();
|
|
@@ -107,6 +129,11 @@ class Store {
|
|
|
107
129
|
// connected but the dead EventSource is never re-opened and the device ring is never pulled,
|
|
108
130
|
// so the tab shows nothing until a manual refresh.
|
|
109
131
|
_dropped = false;
|
|
132
|
+
// The device_serial last seen from /health. Lets pollHealth detect a device SWITCH under a
|
|
133
|
+
// live dashboard (a re-enable that repinned ANDROID_SERIAL to different hardware) so it can
|
|
134
|
+
// drop the old device's cached feed once, on the switch edge. null = not yet observed; the
|
|
135
|
+
// first non-null serial just records it and does NOT clear (nothing stale to drop yet).
|
|
136
|
+
_lastSerial = null;
|
|
110
137
|
_rafPending = false;
|
|
111
138
|
_intervals = [];
|
|
112
139
|
// ---- shared detail cache (bounded FIFO) ----
|
|
@@ -188,7 +215,12 @@ class Store {
|
|
|
188
215
|
this.spec = { blank: true, viz: [] };
|
|
189
216
|
this.conn = { state: "waiting", msg: "connecting…" };
|
|
190
217
|
this.profileLabel = "detecting…";
|
|
218
|
+
this.serverVersion = "";
|
|
191
219
|
this.profiles = [];
|
|
220
|
+
this.devices = [];
|
|
221
|
+
this.selectedDevice = null;
|
|
222
|
+
this.devicesError = false;
|
|
223
|
+
this.deviceError = null;
|
|
192
224
|
this.cache = [];
|
|
193
225
|
this.cacheKeys = new Set();
|
|
194
226
|
this.seen = {};
|
|
@@ -199,6 +231,7 @@ class Store {
|
|
|
199
231
|
this.liveMatches = 0;
|
|
200
232
|
this.graph = null;
|
|
201
233
|
this.feedVersion = 0;
|
|
234
|
+
this.dbSerialVersion = 0;
|
|
202
235
|
this.customActive = false;
|
|
203
236
|
this.lastCustomSpec = null;
|
|
204
237
|
this.detailCache = new Map();
|
|
@@ -212,8 +245,38 @@ class Store {
|
|
|
212
245
|
this._lastBoundLabel = null;
|
|
213
246
|
this._backfillToken = 0;
|
|
214
247
|
this._dropped = false;
|
|
248
|
+
this._lastSerial = null;
|
|
215
249
|
this._rafPending = false;
|
|
216
250
|
}
|
|
251
|
+
// Build the graph aggregate structure for the current spec: one zero-filled series per
|
|
252
|
+
// spec.series entry, or null when the spec has no graph. Shared by applySpec (fresh spec) and
|
|
253
|
+
// clearDeviceCaches (device switch) so the two paths cannot drift.
|
|
254
|
+
buildGraph() {
|
|
255
|
+
if (this.spec.blank || this.spec.source === "db" || this.spec.source === "prefs" || !Array.isArray(this.spec.viz) || !this.spec.viz.includes("graph") || !Array.isArray(this.spec.series)) {
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
return { N: GRAPH_N, series: this.spec.series.map((s) => ({ def: s, buckets: new Array(GRAPH_N).fill(0), counts: new Array(GRAPH_N).fill(0) })) };
|
|
259
|
+
}
|
|
260
|
+
// Drop every device-scoped cache when the dashboard switches to different hardware. The old
|
|
261
|
+
// device's records, dedup keys, learned field values, and detail bodies belong to the wrong
|
|
262
|
+
// phone. The live aggregates (counter, rate, graph) reset too: backfill re-ACCUMULATES into
|
|
263
|
+
// them rather than rebuilding them, so leaving them would layer the new device's counts on
|
|
264
|
+
// top of the old device's totals. The graph is REBUILT zero-filled (not nulled): nothing else
|
|
265
|
+
// reconstructs it after a switch, so nulling it would blank the Network/Trace charts until the
|
|
266
|
+
// next tab change. Timers and spec are left running.
|
|
267
|
+
clearDeviceCaches() {
|
|
268
|
+
this.cache = [];
|
|
269
|
+
this.cacheKeys = new Set();
|
|
270
|
+
this.seen = {};
|
|
271
|
+
this.detailCache = new Map();
|
|
272
|
+
this._capSeen = new Set();
|
|
273
|
+
this._capQueue = [];
|
|
274
|
+
this.total = 0;
|
|
275
|
+
this.liveMatches = 0;
|
|
276
|
+
this.times = [];
|
|
277
|
+
this.perSec = new Array(PERSEC_N).fill(0);
|
|
278
|
+
this.graph = this.buildGraph();
|
|
279
|
+
}
|
|
217
280
|
// ---- start everything ----
|
|
218
281
|
start() {
|
|
219
282
|
this.bootDefault();
|
|
@@ -237,6 +300,14 @@ class Store {
|
|
|
237
300
|
this.closeStream();
|
|
238
301
|
}
|
|
239
302
|
setConn(state, msg) {
|
|
303
|
+
// Unpinned multi-device is never "connected": frames can ride a stale forward from a prior
|
|
304
|
+
// pin and flip the dot green while the per-device surfaces (DB run-as) are broken by the
|
|
305
|
+
// ambiguity. Override any connected claim to a waiting "pick one" until a device is pinned.
|
|
306
|
+
// Centralized here so every caller (pollHealth, onFrame) is covered by the one derived getter.
|
|
307
|
+
if (state === "connected" && this.needsDevicePick) {
|
|
308
|
+
state = "waiting";
|
|
309
|
+
msg = "multiple devices attached, pick one";
|
|
310
|
+
}
|
|
240
311
|
if (this.conn.state === state && this.conn.msg === (msg || ""))
|
|
241
312
|
return;
|
|
242
313
|
this.conn = { state, msg: msg || "" };
|
|
@@ -244,7 +315,17 @@ class Store {
|
|
|
244
315
|
}
|
|
245
316
|
async pollSpec() {
|
|
246
317
|
try {
|
|
247
|
-
const
|
|
318
|
+
const res = await fetch("/spec");
|
|
319
|
+
// The server already stamps its version on /spec (the adopt-path check);
|
|
320
|
+
// reuse it here so the header can show which Radar version is serving.
|
|
321
|
+
// A missing header clears the badge rather than pinning a stale value
|
|
322
|
+
// (an older server rebound to the port would not send it).
|
|
323
|
+
const ver = res.headers.get("X-Radar-Version") ?? "";
|
|
324
|
+
if (ver !== this.serverVersion) {
|
|
325
|
+
this.serverVersion = ver;
|
|
326
|
+
this.emit("version", ver);
|
|
327
|
+
}
|
|
328
|
+
const spec = await res.json();
|
|
248
329
|
const key = JSON.stringify(spec);
|
|
249
330
|
if (key === this._specKey)
|
|
250
331
|
return;
|
|
@@ -298,15 +379,12 @@ class Store {
|
|
|
298
379
|
this.liveMatches = 0;
|
|
299
380
|
this.times = [];
|
|
300
381
|
this.perSec = new Array(PERSEC_N).fill(0);
|
|
301
|
-
this.graph = null;
|
|
302
382
|
this._capQueue.length = 0;
|
|
303
|
-
|
|
304
|
-
this.graph = { N: GRAPH_N, series: this.spec.series.map((s) => ({ def: s, buckets: new Array(GRAPH_N).fill(0), counts: new Array(GRAPH_N).fill(0) })) };
|
|
305
|
-
}
|
|
383
|
+
this.graph = this.buildGraph();
|
|
306
384
|
this.emit("spec", this.spec);
|
|
307
|
-
// DB browser + blank: fully quiet the streaming engine so it does not compete with
|
|
308
|
-
//
|
|
309
|
-
if (this.spec.blank || this.spec.source === "db") {
|
|
385
|
+
// DB/Prefs browser + blank: fully quiet the streaming engine so it does not compete with
|
|
386
|
+
// point-in-time operations. Close the SSE stream AND stop the per-second tick. The 100k cache is left intact.
|
|
387
|
+
if (this.spec.blank || this.spec.source === "db" || this.spec.source === "prefs") {
|
|
310
388
|
this.closeStream();
|
|
311
389
|
if (this._tick) {
|
|
312
390
|
clearInterval(this._tick);
|
|
@@ -584,6 +662,17 @@ class Store {
|
|
|
584
662
|
get matchedRetained() {
|
|
585
663
|
return this.viewFrames().length;
|
|
586
664
|
}
|
|
665
|
+
// 2+ READY devices attached but none pinned yet: a real, renderable state, not "connected".
|
|
666
|
+
// The header shows a "pick a device…" dropdown and the conn dot says so, instead of riding a
|
|
667
|
+
// stale forward and claiming live while the per-device surfaces (DB run-as) are broken by
|
|
668
|
+
// ambiguity. Ready-state only, matching the picker's option list and the server's ambiguity
|
|
669
|
+
// rule: an offline or unauthorized entry cannot be picked, so it must not put the dot in a
|
|
670
|
+
// pick-one state the dropdown cannot resolve. A pinned session (selectedDevice set) is never
|
|
671
|
+
// in this state, even with 2 devices attached.
|
|
672
|
+
get needsDevicePick() {
|
|
673
|
+
return (this.devices.filter((d) => d.state === "device").length >= 2 &&
|
|
674
|
+
this.selectedDevice === null);
|
|
675
|
+
}
|
|
587
676
|
matches(ev) {
|
|
588
677
|
const m = this.spec.match;
|
|
589
678
|
if (!m)
|
|
@@ -606,6 +695,33 @@ class Store {
|
|
|
606
695
|
const op = h.op || ">";
|
|
607
696
|
return op === ">" ? v > h.value : op === ">=" ? v >= h.value : op === "<" ? v < h.value : op === "<=" ? v <= h.value : v === h.value;
|
|
608
697
|
}
|
|
698
|
+
// Device-SWITCH edge detection, shared by pollHealth (quiet case) and fetchDevices (busy
|
|
699
|
+
// observer case). A changed non-null serial means a re-enable repinned to different hardware:
|
|
700
|
+
// drop the old device's cached feed + resync the stream ONCE. Skip the first observation
|
|
701
|
+
// (_lastSerial null): there is nothing stale to clear yet, just record the baseline. A null
|
|
702
|
+
// serial (not reported this poll) is ignored, never resets the baseline.
|
|
703
|
+
checkSerialEdge(serial) {
|
|
704
|
+
if (serial == null || serial === this._lastSerial)
|
|
705
|
+
return;
|
|
706
|
+
// Feed clear + stream resync only on a REAL switch (serial -> other serial): a null->serial
|
|
707
|
+
// FIRST pin has no stale feed to drop, it just records the baseline.
|
|
708
|
+
if (this._lastSerial !== null) {
|
|
709
|
+
this.clearDeviceCaches();
|
|
710
|
+
this.resyncStream();
|
|
711
|
+
}
|
|
712
|
+
this._lastSerial = serial;
|
|
713
|
+
// The DB tab, unlike the feed, DOES carry stale state across a first pin: it loaded unpinned
|
|
714
|
+
// and its /dbs failed with an ambiguous run-as. So the db-resync fires on ANY serial change,
|
|
715
|
+
// including null->serial, so the tab drops that failed state and re-fetches once pinned.
|
|
716
|
+
this.bumpDbSerial();
|
|
717
|
+
}
|
|
718
|
+
// Signal the DB tab to drop its picked-db/table/results and reload /dbs. The DB module cannot
|
|
719
|
+
// import the store (it is a point-in-time view with no SSE engine), so app.ts subscribes and
|
|
720
|
+
// remounts DbBrowser off this counter. Fires on every bound-device change, first pin included.
|
|
721
|
+
bumpDbSerial() {
|
|
722
|
+
this.dbSerialVersion++;
|
|
723
|
+
this.emit("db-resync", this.dbSerialVersion);
|
|
724
|
+
}
|
|
609
725
|
// ---- health + profile ----
|
|
610
726
|
async pollHealth() {
|
|
611
727
|
if (Date.now() - this._lastEventTs < 6000) {
|
|
@@ -616,6 +732,12 @@ class Store {
|
|
|
616
732
|
}
|
|
617
733
|
try {
|
|
618
734
|
const h = await (await fetch("/health")).json();
|
|
735
|
+
// Detect a device SWITCH under the live dashboard off /health's pinned serial. This edge
|
|
736
|
+
// only covers the QUIET case: the fresh-frame early return above skips this fetch while the
|
|
737
|
+
// stream is busy, so a switch made from another tab (whose stream stays busy here) is caught
|
|
738
|
+
// instead by fetchDevices, which polls /_control/devices every 5s regardless of stream
|
|
739
|
+
// activity. Between the two, both busy and quiet observer tabs converge within 5s.
|
|
740
|
+
this.checkSerialEdge(h.device_serial ?? null);
|
|
619
741
|
if (h.device) {
|
|
620
742
|
this._healthMisses = 0;
|
|
621
743
|
this.recovered();
|
|
@@ -644,6 +766,7 @@ class Store {
|
|
|
644
766
|
this.resyncStream();
|
|
645
767
|
}
|
|
646
768
|
async pollProfile() {
|
|
769
|
+
this.fetchDevices();
|
|
647
770
|
try {
|
|
648
771
|
const [profilesR, healthR] = await Promise.all([
|
|
649
772
|
fetch("/_control/profiles").then((r) => r.json()).catch(() => null),
|
|
@@ -667,6 +790,66 @@ class Store {
|
|
|
667
790
|
/* leave the last label */
|
|
668
791
|
}
|
|
669
792
|
}
|
|
793
|
+
// Pull the attached-device list + the pinned device for the header picker. Fired off the
|
|
794
|
+
// profile poll loop (same cadence as profiles) and again whenever an /enable 409 lands, so the
|
|
795
|
+
// dropdown reflects what is actually attached when the user is asked to disambiguate.
|
|
796
|
+
async fetchDevices() {
|
|
797
|
+
try {
|
|
798
|
+
const r = await (await fetch("/_control/devices")).json();
|
|
799
|
+
this.devices = r?.devices || [];
|
|
800
|
+
this.selectedDevice = r?.selected || null;
|
|
801
|
+
this.devicesError = !!r?.adb_error;
|
|
802
|
+
// Observer-tab switch coverage: a busy stream keeps pollHealth on its fresh-frame fast path,
|
|
803
|
+
// so its serial edge never fires. This poll gets the pinned serial regardless of stream
|
|
804
|
+
// activity, so drive the same switch detection off it (no extra request).
|
|
805
|
+
this.checkSerialEdge(this.selectedDevice?.serial ?? null);
|
|
806
|
+
this.emit("devices", this.devices);
|
|
807
|
+
}
|
|
808
|
+
catch {
|
|
809
|
+
/* transient; next poll retries */
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
// Pin a specific device for the session. POSTs the same /enable the reconnect button uses,
|
|
813
|
+
// with the chosen serial; on success it runs the same post-enable refresh as reconnect() so
|
|
814
|
+
// the UI does not wait for the next poll. On a REAL switch (target serial differs from the one
|
|
815
|
+
// last seen) it clears the old device's caches and resyncs HERE, deterministically, rather than
|
|
816
|
+
// leaning on pollHealth's serial edge: that edge is starved by the <6s fresh-frame fast path
|
|
817
|
+
// while the new stream is already delivering frames, so it may never fire. Same-serial reselect
|
|
818
|
+
// skips the clear (nothing stale). A 409/error is surfaced on deviceError (the device chip shows
|
|
819
|
+
// it) rather than via conn, which a healthy health poll would overwrite within 2s; the device
|
|
820
|
+
// list is refreshed so the dropdown is current and the user can pick a valid device.
|
|
821
|
+
async selectDevice(serial) {
|
|
822
|
+
try {
|
|
823
|
+
const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST" });
|
|
824
|
+
if (!r.ok && r.status === 409) {
|
|
825
|
+
const body = await r.json().catch(() => null);
|
|
826
|
+
// Surface the failure on the device chip itself, not via conn: a healthy pollHealth flips
|
|
827
|
+
// conn back to connected within 2s and would erase a setConn("waiting", …) message before
|
|
828
|
+
// the user reads it. deviceError is owned here and survives the health poll.
|
|
829
|
+
this.deviceError = (body && body.error) ? String(body.error) : "device select failed";
|
|
830
|
+
this.emit("devices", this.devices);
|
|
831
|
+
this.fetchDevices();
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
// A successful pick clears any prior select failure.
|
|
835
|
+
this.deviceError = null;
|
|
836
|
+
this.emit("devices", this.devices);
|
|
837
|
+
if (serial !== this._lastSerial) {
|
|
838
|
+
this.clearDeviceCaches();
|
|
839
|
+
this._lastSerial = serial;
|
|
840
|
+
// Resync the DB tab too: a first pick (null->serial) leaves it holding the failed
|
|
841
|
+
// ambiguous /dbs; a real switch leaves it on the old device's databases.
|
|
842
|
+
this.bumpDbSerial();
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
catch {
|
|
846
|
+
/* ignore; the refresh below re-syncs state */
|
|
847
|
+
}
|
|
848
|
+
this.pollHealth();
|
|
849
|
+
this.pollProfile();
|
|
850
|
+
this.pollSpec();
|
|
851
|
+
this.resyncStream();
|
|
852
|
+
}
|
|
670
853
|
// Re-open the SSE stream and backfill the device ring for the ACTIVE streaming source, so the
|
|
671
854
|
// current tab repopulates from what the device already holds (not just new live events).
|
|
672
855
|
// Needed because the EventSource does not survive a device drop and pollSpec only re-applies
|
|
@@ -682,14 +865,22 @@ class Store {
|
|
|
682
865
|
resyncStream() {
|
|
683
866
|
this._dropped = false;
|
|
684
867
|
const src = this.spec.source;
|
|
685
|
-
if (this.spec.blank || !src || src === "db")
|
|
868
|
+
if (this.spec.blank || !src || src === "db" || src === "prefs")
|
|
686
869
|
return;
|
|
687
870
|
this.openStream();
|
|
688
871
|
this.backfill();
|
|
689
872
|
}
|
|
690
873
|
async reconnect() {
|
|
691
874
|
try {
|
|
692
|
-
await fetch("/enable", { method: "POST" });
|
|
875
|
+
const r = await fetch("/enable", { method: "POST" });
|
|
876
|
+
// 409 = ambiguous device (multiple attached, none picked). Surface the server's
|
|
877
|
+
// reason through the existing connection-status line so the user sees why enable
|
|
878
|
+
// did not connect, instead of a silent stall on "reconnecting…".
|
|
879
|
+
if (!r.ok && r.status === 409) {
|
|
880
|
+
const body = await r.json().catch(() => null);
|
|
881
|
+
if (body && body.error)
|
|
882
|
+
this.setConn("waiting", String(body.error));
|
|
883
|
+
}
|
|
693
884
|
}
|
|
694
885
|
catch {
|
|
695
886
|
/* ignore */
|
package/dist/web/server.js
CHANGED
|
@@ -7,7 +7,8 @@ import { fileURLToPath } from "url";
|
|
|
7
7
|
import { AndroidTransport, resolveAdbPath } from "../shared/android.js";
|
|
8
8
|
import { planReconnect } from "../shared/stream.js";
|
|
9
9
|
import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
|
|
10
|
-
import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, } from "../shared/db.js";
|
|
10
|
+
import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, availableUsers, } from "../shared/db.js";
|
|
11
|
+
import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../shared/prefs.js";
|
|
11
12
|
import { LogSession } from "./log-session.js";
|
|
12
13
|
import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
|
|
13
14
|
import { screenCapabilities, refreshScreenCapabilities, grantScreenConsent, hasScreenConsent, detectDisplay, displayNote, captureScreenshot, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, startRecording, stopRecording, recordingPath, resetScreenState, registerScreenCleanup, resolveFfmpeg, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
|
|
@@ -46,6 +47,14 @@ export function shouldDropLogFrame(replay, writableLength, cap = MAX_SSE_WRITABL
|
|
|
46
47
|
const SPEC_DIR = path.join(os.homedir(), ".slack-radar");
|
|
47
48
|
const SPEC_PATH = path.join(SPEC_DIR, `web-spec-${WEB_PORT}.json`);
|
|
48
49
|
const transport = new AndroidTransport();
|
|
50
|
+
// Reassert the shared adb forward before every HTTP-based device read. Mirrors
|
|
51
|
+
// mcp/index.ts's forwardForRead(): this process's own portForwarded cache cannot see a
|
|
52
|
+
// repoint made by a SEPARATE process (the MCP server) sharing the same host-global
|
|
53
|
+
// forward port -- the split-brain flows both ways. Platforms without a shared
|
|
54
|
+
// host-level forward may omit reassertForward, so this falls back to ensureForward.
|
|
55
|
+
function forwardForRead() {
|
|
56
|
+
return transport.reassertForward?.() ?? transport.ensureForward();
|
|
57
|
+
}
|
|
49
58
|
// One session-long logcat capture shared across every dashboard stream
|
|
50
59
|
// connection. The device cannot replay logcat history to us, so the dashboard
|
|
51
60
|
// keeps its own bounded session ring here and replays it to each newly opened
|
|
@@ -168,8 +177,9 @@ export function createServer() {
|
|
|
168
177
|
handleHealth(res);
|
|
169
178
|
return;
|
|
170
179
|
}
|
|
171
|
-
if (
|
|
172
|
-
|
|
180
|
+
if (urlPath === "/enable" && req.method === "POST") {
|
|
181
|
+
const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
|
|
182
|
+
handleEnable(res, serial);
|
|
173
183
|
return;
|
|
174
184
|
}
|
|
175
185
|
if (url === "/stream" && req.method === "GET") {
|
|
@@ -196,6 +206,18 @@ export function createServer() {
|
|
|
196
206
|
handleDbQuery(req, res);
|
|
197
207
|
return;
|
|
198
208
|
}
|
|
209
|
+
if (url.split("?")[0] === "/prefs" && req.method === "GET") {
|
|
210
|
+
handlePrefsList(req, res);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (url.startsWith("/prefsread") && req.method === "GET") {
|
|
214
|
+
handlePrefsRead(req, res);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (url.startsWith("/prefssearch") && req.method === "GET") {
|
|
218
|
+
handlePrefsSearch(req, res);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
199
221
|
if (url === "/_control/profiles" && req.method === "GET") {
|
|
200
222
|
listProfiles(res);
|
|
201
223
|
return;
|
|
@@ -206,6 +228,10 @@ export function createServer() {
|
|
|
206
228
|
activateRadar(res, userId);
|
|
207
229
|
return;
|
|
208
230
|
}
|
|
231
|
+
if (url === "/_control/devices" && req.method === "GET") {
|
|
232
|
+
listDevices(res);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
209
235
|
if (url.startsWith("/screen/")) {
|
|
210
236
|
handleScreen(req, res);
|
|
211
237
|
return;
|
|
@@ -365,6 +391,14 @@ async function handleSetSpec(req, res) {
|
|
|
365
391
|
* forward/proxy base as the rest of the server.
|
|
366
392
|
*/
|
|
367
393
|
function handleHealth(res) {
|
|
394
|
+
// Reassert before reading: see forwardForRead's doc comment. Without this, a foreign
|
|
395
|
+
// repoint of the shared port (the MCP process switching devices) makes /health probe
|
|
396
|
+
// the WRONG device while still labeling the reply with THIS process's own (correct)
|
|
397
|
+
// device_serial -- a misleading "connected" status for a device this process is not
|
|
398
|
+
// actually reading. reassertForward's cheap check-first path (adb forward --list) keeps
|
|
399
|
+
// the cost low on the 2s poll cadence; it only pays for a real rebuild when the shared
|
|
400
|
+
// port is actually pointed somewhere else.
|
|
401
|
+
forwardForRead();
|
|
368
402
|
// A probe can fire BOTH an "end" and an "error"/"timeout" (partial response then socket
|
|
369
403
|
// drop), so guard the response to exactly one write. Without this the second sendJson
|
|
370
404
|
// does a second writeHead -> ERR_HTTP_HEADERS_SENT -> uncaught -> the whole server dies.
|
|
@@ -377,11 +411,14 @@ function handleHealth(res) {
|
|
|
377
411
|
if (replied)
|
|
378
412
|
return;
|
|
379
413
|
replied = true;
|
|
414
|
+
const selected = transport.getSelectedDevice?.() ?? null;
|
|
380
415
|
sendJson(res, 200, {
|
|
381
416
|
device,
|
|
382
417
|
screen: screenCapabilities(),
|
|
383
418
|
boundUserId: boundUserId ?? null,
|
|
384
419
|
boundProfile: boundProfile ?? null,
|
|
420
|
+
device_serial: selected?.serial ?? null,
|
|
421
|
+
device_label: selected?.label ?? null,
|
|
385
422
|
});
|
|
386
423
|
};
|
|
387
424
|
const probe = http.request({
|
|
@@ -438,13 +475,51 @@ function handleHealth(res) {
|
|
|
438
475
|
* user never has to drop to a terminal. Delegates entirely to AndroidTransport;
|
|
439
476
|
* no adb shelling here.
|
|
440
477
|
*/
|
|
441
|
-
function handleEnable(res) {
|
|
478
|
+
function handleEnable(res, deviceSerial) {
|
|
442
479
|
transport.resetState();
|
|
443
480
|
// A reconnect may be a different device / re-armed profile, so drop the cached DB user
|
|
444
481
|
// set + sqlite path; the next /dbs re-detects the profiles fresh.
|
|
445
482
|
resetDbState();
|
|
483
|
+
// Pin the target device BEFORE any adb call, including resetScreenState's pkill below --
|
|
484
|
+
// that call has no serial of its own and would otherwise target whatever `adb` defaults
|
|
485
|
+
// to (or fail ambiguously) on a multi-device host, running one adb call outside the
|
|
486
|
+
// "pin before any adb call" invariant every other call site in this handler honors. An
|
|
487
|
+
// ambiguous choice (multiple devices, no serial) or an unattached explicit serial fails
|
|
488
|
+
// here with the list, before forwarding OR the screen reset.
|
|
489
|
+
const selection = transport.selectDevice?.(deviceSerial ?? null);
|
|
490
|
+
if (selection && !selection.ok) {
|
|
491
|
+
sendJson(res, 409, {
|
|
492
|
+
enabled: false,
|
|
493
|
+
error: selection.error,
|
|
494
|
+
devices: selection.devices,
|
|
495
|
+
});
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
446
498
|
resetScreenState(); // re-detect the active display + clear any stale cast on re-arm
|
|
447
|
-
|
|
499
|
+
// On a switch to a different device, drop this device's pulled DB scratch AND the
|
|
500
|
+
// retained logcat capture -- both are per-device state resetDbState()/resetScreenState()
|
|
501
|
+
// above do not cover. logSession.restart() (not stop()) is deliberate here: stop() alone
|
|
502
|
+
// preserves the ring buffer for a transient same-device drop, but a real switch means
|
|
503
|
+
// every retained line belongs to the WRONG device, and the ring would replay device A's
|
|
504
|
+
// history into a freshly opened /stream on device B (mirrors the MCP side's onDeviceSwitch,
|
|
505
|
+
// which resets its own local buffers/spool/capture on the same switch signal). start() is
|
|
506
|
+
// idempotent, so a still-open Logs tab just keeps polling and picks the new child back up
|
|
507
|
+
// on its next /stream reconnect; nothing here needs to force-restart it eagerly.
|
|
508
|
+
if (selection && selection.ok && selection.switched) {
|
|
509
|
+
cleanupPulledDatabases();
|
|
510
|
+
logSession.restart();
|
|
511
|
+
}
|
|
512
|
+
// Reassert the forward is pointed at the selected device before reading. On a device
|
|
513
|
+
// switch or after a multi-process repoint (e.g., MCP server switched to a different
|
|
514
|
+
// device), the cached forward may be stale even though ensureForward() would not detect
|
|
515
|
+
// it on this process. Mirrors forwardForRead's split-brain handling: two processes
|
|
516
|
+
// sharing the same host-level forward must both reassert before assuming it is still
|
|
517
|
+
// good. Use forwardForRead's own result directly rather than also calling
|
|
518
|
+
// transport.ensureForward() again -- resetState() at the top of this handler already
|
|
519
|
+
// dropped the portForwarded cache, so a second unconditional ensureForward() call would
|
|
520
|
+
// only ever be a genuine repeat rebuild (on the rare reassert-failed path), never a
|
|
521
|
+
// no-op skip; forwardForRead already tried its best.
|
|
522
|
+
const forwarded = forwardForRead();
|
|
448
523
|
if (!forwarded) {
|
|
449
524
|
const reason = transport.getLastForwardError?.() ?? null;
|
|
450
525
|
sendJson(res, 200, {
|
|
@@ -518,6 +593,11 @@ export const DEVICE_SOURCES = {
|
|
|
518
593
|
* `[{type, event}]` frames mirroring the stream shape.
|
|
519
594
|
*/
|
|
520
595
|
function handleBackfill(req, res) {
|
|
596
|
+
// Reassert before reading: see forwardForRead's doc comment. A failed reassert still
|
|
597
|
+
// falls through to the request below rather than erroring out here -- the device-side
|
|
598
|
+
// request will surface its own connection failure, matching the pre-existing behavior
|
|
599
|
+
// when the forward was never set up at all.
|
|
600
|
+
forwardForRead();
|
|
521
601
|
const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
|
|
522
602
|
const src = u.searchParams.get("source") ?? "network";
|
|
523
603
|
const limit = Math.min(500, Number(u.searchParams.get("limit")) || 200);
|
|
@@ -584,6 +664,8 @@ export function failDetailResponse(res, status) {
|
|
|
584
664
|
* to `/api/<kind>/<id>` so the inspector can fetch a clicked row's payload.
|
|
585
665
|
*/
|
|
586
666
|
function handleDetail(req, res) {
|
|
667
|
+
// Reassert before reading: see forwardForRead's doc comment.
|
|
668
|
+
forwardForRead();
|
|
587
669
|
const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
|
|
588
670
|
const id = u.searchParams.get("id");
|
|
589
671
|
const kind = u.searchParams.get("kind") ?? "network";
|
|
@@ -692,6 +774,113 @@ async function handleDbQuery(req, res) {
|
|
|
692
774
|
}
|
|
693
775
|
sendJson(res, status, payload);
|
|
694
776
|
}
|
|
777
|
+
// --- On-device SharedPreferences browser (source: "prefs") ---
|
|
778
|
+
//
|
|
779
|
+
// These delegate to shared/prefs.ts (run-as + ADB, read-only; PR1, already tested). Mirrors
|
|
780
|
+
// handleDb* above: compute payload+status BEFORE writing headers, errors surface as 200
|
|
781
|
+
// {error} in-pane rather than a transport error. User resolution reuses dbUser (it only reads
|
|
782
|
+
// req/WEB_PORT/transport, nothing db-specific) rather than duplicating a prefsUser().
|
|
783
|
+
function handlePrefsList(req, res) {
|
|
784
|
+
const adbPath = resolveAdbPath();
|
|
785
|
+
if (!adbPath) {
|
|
786
|
+
sendJson(res, 200, { error: "adb not found. Ensure platform-tools is installed and on PATH.", files: [], available_users: [] });
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
try {
|
|
790
|
+
const user = dbUser(req);
|
|
791
|
+
const result = listPrefsFiles(adbPath, user);
|
|
792
|
+
if (!result) {
|
|
793
|
+
sendJson(res, 200, { error: "unable to list preferences files. Is the debug build installed and is a device connected?", files: [], available_users: availableUsers() });
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
sendJson(res, 200, {
|
|
797
|
+
user: result.user,
|
|
798
|
+
available_users: availableUsers(),
|
|
799
|
+
files: result.files,
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
catch (e) {
|
|
804
|
+
sendJson(res, 200, { error: e.message, files: [], available_users: [] });
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
async function handlePrefsRead(req, res) {
|
|
808
|
+
const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
|
|
809
|
+
const file = u.searchParams.get("file") ?? "";
|
|
810
|
+
const user = dbUser(req);
|
|
811
|
+
const keysParam = u.searchParams.get("keys") ?? "";
|
|
812
|
+
const keys = keysParam ? keysParam.split(",").filter((k) => k.trim().length > 0) : null;
|
|
813
|
+
const adbPath = resolveAdbPath();
|
|
814
|
+
if (!adbPath) {
|
|
815
|
+
sendJson(res, 200, { error: "adb not found. Ensure platform-tools is installed and on PATH." });
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
let payload;
|
|
819
|
+
try {
|
|
820
|
+
const readResult = await readPrefsFile(adbPath, file, user);
|
|
821
|
+
if ("error" in readResult) {
|
|
822
|
+
payload = { error: readResult.error };
|
|
823
|
+
}
|
|
824
|
+
else {
|
|
825
|
+
const parsed = parsePrefsXml(readResult.xml);
|
|
826
|
+
if ("parseError" in parsed) {
|
|
827
|
+
payload = { error: parsed.parseError };
|
|
828
|
+
}
|
|
829
|
+
else {
|
|
830
|
+
// Web route is human-consumable (renders to a scrolling table), so unlike the MCP
|
|
831
|
+
// get_prefs handler it does NOT byte-cap the response -- only the keys filter (if
|
|
832
|
+
// any) narrows what is returned. device_read_truncated is a real data-completeness
|
|
833
|
+
// signal (the 256KB on-device read cap) and is passed through either way.
|
|
834
|
+
//
|
|
835
|
+
// total_entries is the file's TRUE entry count, before any filtering -- keys narrows
|
|
836
|
+
// what is RETURNED, it does not shrink what the file actually has. Reporting the
|
|
837
|
+
// post-filter count for both fields (the original bug) makes the UI's "X of Y" always
|
|
838
|
+
// read "N of N" the moment keys is used, hiding how much of the file was left out.
|
|
839
|
+
const entries = keys && keys.length
|
|
840
|
+
? parsed.entries.filter((e) => keys.includes(e.key))
|
|
841
|
+
: parsed.entries;
|
|
842
|
+
payload = {
|
|
843
|
+
file,
|
|
844
|
+
user: readResult.user,
|
|
845
|
+
entries,
|
|
846
|
+
...(readResult.truncated ? { device_read_truncated: true } : {}),
|
|
847
|
+
total_entries: parsed.entries.length,
|
|
848
|
+
returned_entries: entries.length,
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
catch (e) {
|
|
854
|
+
payload = { error: String(e.message).split("\n")[0] };
|
|
855
|
+
}
|
|
856
|
+
sendJson(res, 200, payload);
|
|
857
|
+
}
|
|
858
|
+
async function handlePrefsSearch(req, res) {
|
|
859
|
+
const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
|
|
860
|
+
const query = u.searchParams.get("query") ?? "";
|
|
861
|
+
const user = dbUser(req);
|
|
862
|
+
const adbPath = resolveAdbPath();
|
|
863
|
+
if (!adbPath) {
|
|
864
|
+
sendJson(res, 200, { error: "adb not found. Ensure platform-tools is installed and on PATH." });
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
let payload;
|
|
868
|
+
try {
|
|
869
|
+
const result = await searchPrefs(adbPath, query, user);
|
|
870
|
+
payload = {
|
|
871
|
+
query,
|
|
872
|
+
user: result.user,
|
|
873
|
+
available_users: availableUsers(),
|
|
874
|
+
results: result.results,
|
|
875
|
+
...(result.truncated ? { truncated: true } : {}),
|
|
876
|
+
...(result.skipped && result.skipped.length ? { skipped: result.skipped } : {}),
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
catch (e) {
|
|
880
|
+
payload = { error: String(e.message).split("\n")[0] };
|
|
881
|
+
}
|
|
882
|
+
sendJson(res, 200, payload);
|
|
883
|
+
}
|
|
695
884
|
/**
|
|
696
885
|
* Screen overlay routes. The live screen shows real DMs and message content, so the
|
|
697
886
|
* stream and record routes are gated behind an explicit per-process consent (granted
|
|
@@ -1022,6 +1211,11 @@ function handleStream(req, res) {
|
|
|
1022
1211
|
if (closed)
|
|
1023
1212
|
return;
|
|
1024
1213
|
settled = false;
|
|
1214
|
+
// Reassert before every connect (initial AND each retry): see forwardForRead's doc
|
|
1215
|
+
// comment. planReconnect already forces a hard forward rebuild on every OTHER retry
|
|
1216
|
+
// (tuned for "device end died"), which would only catch a foreign repoint by luck on
|
|
1217
|
+
// half of attempts; this cheap check-first call covers every attempt instead.
|
|
1218
|
+
forwardForRead();
|
|
1025
1219
|
upstream = http.request({
|
|
1026
1220
|
host: RADAR_HOST,
|
|
1027
1221
|
port: RADAR_PORT,
|
|
@@ -1115,6 +1309,21 @@ function listProfiles(res) {
|
|
|
1115
1309
|
const activeUserId = transport.getActiveUserId();
|
|
1116
1310
|
sendJson(res, 200, { profiles, active_user_id: activeUserId });
|
|
1117
1311
|
}
|
|
1312
|
+
// The attached-device list + the currently pinned device, for the dashboard's device picker.
|
|
1313
|
+
// listDevices() returns null when the adb listing itself failed (not "zero attached"); surface
|
|
1314
|
+
// that as adb_error:true with an empty list so the client can say why instead of showing "none".
|
|
1315
|
+
function listDevices(res) {
|
|
1316
|
+
// Distinguish null (adb listing failed) from [] (no devices): null means we cannot tell what
|
|
1317
|
+
// is attached, so tell the client with adb_error instead of a bare "none". A transport with no
|
|
1318
|
+
// listDevices() at all (undefined) is treated as "no devices", not an adb error.
|
|
1319
|
+
const listed = transport.listDevices?.();
|
|
1320
|
+
const adbError = listed === null;
|
|
1321
|
+
sendJson(res, 200, {
|
|
1322
|
+
devices: listed ?? [],
|
|
1323
|
+
selected: transport.getSelectedDevice?.() ?? null,
|
|
1324
|
+
...(adbError ? { adb_error: true } : {}),
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1118
1327
|
function activateRadar(res, userId) {
|
|
1119
1328
|
// Reset cached state so ensureForward() re-runs adb forward. This handles
|
|
1120
1329
|
// stale forwards after device-side idle timeout or profile switching.
|