@slack/radar-mcp 1.9.1 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,74 @@ export const localRtmBuffer = [];
11
11
  let streamConnection = null;
12
12
  let streamConnected = false;
13
13
  const eventWaiters = [];
14
+ // Reconnect cadence. A plain retry reuses the existing adb forward; every other
15
+ // attempt rebuilds it, because a forward whose device end died is not revived by
16
+ // waiting (the stream would retry into a dead socket forever). Mirrors the web
17
+ // stream proxy's cadence (src/web/server.ts).
18
+ const RETRY_DELAY_MS = 2000;
19
+ const REBUILD_RETRY_DELAY_MS = 1500;
20
+ // Failures since the last successful connect; drives the every-other-attempt
21
+ // rebuild. The pending reconnect timer is held module-level so destroyStream()
22
+ // can cancel it: an intentional teardown (disable, enable-restart) must stop
23
+ // the loop, or it resurrects the stream the user just closed.
24
+ let reconnectAttempts = 0;
25
+ let reconnectTimer = null;
26
+ /**
27
+ * Decide whether this reconnect attempt rebuilds the adb forward, perform the
28
+ * rebuild if so, and return the delay before the next connect. Does not call
29
+ * setTimeout itself so the decision is unit-testable without a live socket.
30
+ *
31
+ * Prefers dropForward() (drops only the cached forward flag) over resetState()
32
+ * so a rebuild does not wipe the detected user id mid-session: a full reset
33
+ * followed by a re-detect while the app process is down would rebind the
34
+ * session to user 0, losing a work-profile binding.
35
+ *
36
+ * @param t transport whose forward may be stale
37
+ * @param attempt 1-based failure count since the last successful connect
38
+ */
39
+ export function planReconnect(t, attempt) {
40
+ if (attempt % 2 === 0) {
41
+ if (t.dropForward) {
42
+ t.dropForward();
43
+ }
44
+ else {
45
+ t.resetState();
46
+ }
47
+ t.ensureForward();
48
+ return REBUILD_RETRY_DELAY_MS;
49
+ }
50
+ return RETRY_DELAY_MS;
51
+ }
52
+ // Schedule the next reconnect attempt. Stale-callback dedup happens at the
53
+ // call sites (the failure handlers no-op unless their request still owns
54
+ // streamConnection), so by the time this runs the disconnect is real. The
55
+ // timer callback keeps the loop alive when a rebuild attempt could not
56
+ // restore the forward (device unplugged): connectStream would early-return
57
+ // on !isForwarded() and the loop would otherwise die permanently, leaving
58
+ // the stream down even after the device comes back.
59
+ function scheduleReconnect() {
60
+ // Never leave a previous timer untracked: if a second chain schedules while
61
+ // one is pending, overwriting the ref would orphan the first timer beyond
62
+ // destroyStream()'s reach, and it would resurrect the stream after a
63
+ // deliberate teardown. The connectStream guard makes this near-unreachable;
64
+ // this is the backstop.
65
+ if (reconnectTimer)
66
+ clearTimeout(reconnectTimer);
67
+ streamConnection = null;
68
+ streamConnected = false;
69
+ reconnectAttempts++;
70
+ const delay = transport
71
+ ? planReconnect(transport, reconnectAttempts)
72
+ : RETRY_DELAY_MS;
73
+ reconnectTimer = setTimeout(() => {
74
+ reconnectTimer = null;
75
+ if (transport && !transport.isForwarded()) {
76
+ scheduleReconnect();
77
+ return;
78
+ }
79
+ connectStream();
80
+ }, delay);
81
+ }
14
82
  // Fires once after a RECONNECT (not the first connect), so the owner can backfill the device ring
15
83
  // rows the ~2s gap dropped. index.ts sets it to the backfill; unset it is a no-op, so the web
16
84
  // server (which shares this module) and tests are unaffected. hasConnectedOnce gates it to a true
@@ -52,7 +120,21 @@ export function clearLocalBuffers() {
52
120
  export function getStreamConnection() {
53
121
  return streamConnection;
54
122
  }
123
+ /**
124
+ * Deliberate teardown: destroy the live stream AND stop the reconnect loop.
125
+ * Cancelling the pending timer matters as much as the destroy — without it a
126
+ * disable (or an enable-restart) leaves a timer that resurrects the stream
127
+ * seconds later, refilling buffers the caller just cleared and churning adb
128
+ * forward rebuilds against a session the user turned off. The destroyed
129
+ * request's own async failure events are ignored by the ownership check in
130
+ * connectStream's handlers (they no longer own streamConnection).
131
+ */
55
132
  export function destroyStream() {
133
+ if (reconnectTimer) {
134
+ clearTimeout(reconnectTimer);
135
+ reconnectTimer = null;
136
+ }
137
+ reconnectAttempts = 0;
56
138
  if (streamConnection) {
57
139
  streamConnection.destroy();
58
140
  streamConnection = null;
@@ -132,10 +214,33 @@ export function waitForEvents({ event_type, channel, source, timeout_ms = 30000,
132
214
  });
133
215
  }
134
216
  export function connectStream() {
135
- if (streamConnection || !transport?.isForwarded())
217
+ // The reconnectTimer check keeps an external caller (a tool call landing in
218
+ // the gap between a drop and the scheduled retry) from opening a competing
219
+ // request: scheduleReconnect nulls streamConnection, so without this the
220
+ // call would slip past the first check, and its failure would schedule a
221
+ // second timer chain. The loop itself is unaffected: the timer callback
222
+ // nulls reconnectTimer before calling here.
223
+ if (streamConnection || reconnectTimer || !transport?.isForwarded())
136
224
  return;
225
+ // Ownership guard shared by all three failure callbacks of this request. A
226
+ // destroyed request emits its failure events asynchronously (verified: res
227
+ // "error"/"aborted" fire a tick after destroy()), so by the time a stale
228
+ // callback runs, a NEWER healthy stream may own streamConnection. Without
229
+ // this check the stale callback would null the live stream (orphaning it,
230
+ // still buffering, no longer reachable by destroyStream) and schedule a
231
+ // duplicate connect: two live streams double-delivering every event. The
232
+ // guard also dedups the three callbacks of one failed attempt: the first to
233
+ // run hands ownership to scheduleReconnect, the rest see a mismatch.
234
+ const fail = () => {
235
+ if (streamConnection !== req)
236
+ return;
237
+ scheduleReconnect();
238
+ };
137
239
  const req = http.get({ host: RADAR_HOST, port: RADAR_PORT, path: "/api/stream", timeout: 0 }, (res) => {
138
240
  streamConnected = true;
241
+ // Connected cleanly, so the next disconnect starts its rebuild cadence
242
+ // from attempt 1 rather than inheriting a counter grown across the session.
243
+ reconnectAttempts = 0;
139
244
  // Fire the reconnect hook on a true reconnect (not the first connect). Kept in its own fn so
140
245
  // the logic is unit-testable without a live socket.
141
246
  noteStreamConnected();
@@ -156,21 +261,9 @@ export function connectStream() {
156
261
  }
157
262
  }
158
263
  });
159
- res.on("end", () => {
160
- streamConnection = null;
161
- streamConnected = false;
162
- setTimeout(connectStream, 2000);
163
- });
164
- res.on("error", () => {
165
- streamConnection = null;
166
- streamConnected = false;
167
- setTimeout(connectStream, 2000);
168
- });
169
- });
170
- req.on("error", () => {
171
- streamConnection = null;
172
- streamConnected = false;
173
- setTimeout(connectStream, 2000);
264
+ res.on("end", fail);
265
+ res.on("error", fail);
174
266
  });
267
+ req.on("error", fail);
175
268
  streamConnection = req;
176
269
  }
@@ -30,6 +30,15 @@ export interface DeviceTransport {
30
30
  activate(timeoutMinutes: number): void;
31
31
  /** Reset all connection state (forwarding, activation, caches). */
32
32
  resetState(): void;
33
+ /**
34
+ * Drop only the cached forwarding state so the next ensureForward() rebuilds
35
+ * the mapping, keeping activation state and the detected user id intact.
36
+ * Reconnect paths use this instead of resetState(): a full reset mid-session
37
+ * would force a user re-detect that can rebind a work-profile session to
38
+ * user 0 while the app process is briefly down. Optional; callers fall back
39
+ * to resetState() when absent.
40
+ */
41
+ dropForward?(): void;
33
42
  /** Whether forwarding has been established. */
34
43
  isForwarded(): boolean;
35
44
  /** Current auto-shutdown timeout in minutes. */
@@ -89,6 +98,15 @@ export interface DeviceTransport {
89
98
  * "device not connected" message. Optional; implementations may omit it.
90
99
  */
91
100
  getLastForwardError?(): string | null;
101
+ /**
102
+ * Returns the error message from the last `activate()` attempt, or null if the
103
+ * last attempt succeeded or none has happened. activate() itself never throws
104
+ * (a failed broadcast is expected when no device is attached), so this is the
105
+ * only way callers can tell "activated" from "broadcast never landed" and
106
+ * report a real error instead of a silently dead session. Optional;
107
+ * implementations may omit it.
108
+ */
109
+ getLastActivateError?(): string | null;
92
110
  /**
93
111
  * Returns the path of the session-scoped log capture file, or null if no
94
112
  * capture is running. Surfaced in tool responses so the model can reason
@@ -22,7 +22,7 @@
22
22
  --warn:#ffb454; --warn-2:#ffd479; --error:#ff6b60; --error-2:#ff5b50;
23
23
  --hover:#11202e; --sel:#1d3a52; --hover-soft:#172230; --sel-soft:#1d2c3e;
24
24
  --shadow:rgba(0,0,0,.5); --overlay:rgba(0,0,0,.45);
25
- --chip-net-bg:#13314a; --chip-rtm-bg:#2c1f47; --chip-clog-bg:#10332a; --chip-log-bg:#2a2a2a; --chip-log-fg:#b0b0b0;
25
+ --chip-net-bg:#13314a; --chip-rtm-bg:#2c1f47; --chip-clog-bg:#10332a; --chip-trace-bg:#3a2f10; --chip-log-bg:#2a2a2a; --chip-log-fg:#b0b0b0;
26
26
  --lvl-err-bg:#3a1513; --lvl-warn-bg:#3a2f10; --lvl-info-bg:#10283a; --lvl-dbg-bg:#222;
27
27
  --copybtn-bg:#172a1f; --copybtn-border:#2c5a3e; --copybtn-fg:#7fd6a3;
28
28
  --j-key:#7fb0ff; --j-str:#9fe8bd; --j-num:#ffd479; --j-bool:#c39bff; --j-null:#7e8a99;
@@ -37,7 +37,7 @@
37
37
  --warn:#b06c00; --warn-2:#8a5a00; --error:#d83a30; --error-2:#e0473d;
38
38
  --hover:#eaf1f8; --sel:#d4e6f7; --hover-soft:#eaf1f8; --sel-soft:#dbe9f7;
39
39
  --shadow:rgba(20,40,70,.18); --overlay:rgba(20,30,45,.28);
40
- --chip-net-bg:#dbeafe; --chip-rtm-bg:#ecddfb; --chip-clog-bg:#d6f3e6; --chip-log-bg:#e7ebf0; --chip-log-fg:#4a5666;
40
+ --chip-net-bg:#dbeafe; --chip-rtm-bg:#ecddfb; --chip-clog-bg:#d6f3e6; --chip-trace-bg:#faedcf; --chip-log-bg:#e7ebf0; --chip-log-fg:#4a5666;
41
41
  --lvl-err-bg:#fbdcd9; --lvl-warn-bg:#faedcf; --lvl-info-bg:#dbeafe; --lvl-dbg-bg:#e7ebf0;
42
42
  --copybtn-bg:#dcf3e7; --copybtn-border:#9cd6b8; --copybtn-fg:#0a7d56;
43
43
  --j-key:#1d6fd0; --j-str:#0a7d56; --j-num:#9a6700; --j-bool:#7a3fd0; --j-null:#8a96a3;
@@ -151,11 +151,14 @@
151
151
  .stchip { font-size:10px; font-weight:700; padding:1px 6px; border-radius:4px; font-variant-numeric:tabular-nums; }
152
152
  .stchip.st2 { background:var(--chip-clog-bg); color:var(--accent); } .stchip.st3 { background:var(--lvl-info-bg); color:var(--blue); }
153
153
  .stchip.st4 { background:var(--lvl-warn-bg); color:var(--warn-2); } .stchip.st5 { background:var(--lvl-err-bg); color:var(--error); }
154
- .t-network{ background:var(--chip-net-bg); color:var(--blue); } .t-rtm{ background:var(--chip-rtm-bg); color:var(--purple); } .t-clog{ background:var(--chip-clog-bg); color:var(--accent); } .t-log{ background:var(--chip-log-bg); color:var(--chip-log-fg); }
154
+ .t-network{ background:var(--chip-net-bg); color:var(--blue); } .t-rtm{ background:var(--chip-rtm-bg); color:var(--purple); } .t-clog{ background:var(--chip-clog-bg); color:var(--accent); } .t-trace{ background:var(--chip-trace-bg); color:var(--warn); } .t-log{ background:var(--chip-log-bg); color:var(--chip-log-fg); }
155
155
  .lvl { font-size:10px; font-weight:700; padding:1px 5px; border-radius:4px; }
156
156
  .lvl-ERROR,.lvl-FATAL{ background:var(--lvl-err-bg); color:var(--error); } .lvl-WARN{ background:var(--lvl-warn-bg); color:var(--warn-2); } .lvl-INFO{ background:var(--lvl-info-bg); color:var(--blue); } .lvl-DEBUG,.lvl-VERBOSE{ background:var(--lvl-dbg-bg); color:var(--muted-2); }
157
157
  .logpkg { color:var(--blue-2); background:var(--surface-3); font-size:10.5px; padding:1px 6px; border-radius:4px; white-space:nowrap; max-width:130px; overflow:hidden; text-overflow:ellipsis; }
158
158
  .logtag { color:var(--muted-2); font-weight:600; } .logmsg { color:var(--text-2); overflow:hidden; text-overflow:ellipsis; }
159
+ .durchip { font-size:10px; font-weight:700; padding:1px 6px; border-radius:4px; background:var(--chip-trace-bg); color:var(--warn); font-variant-numeric:tabular-nums; white-space:nowrap; }
160
+ .tracename { color:var(--text-2); font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:40%; }
161
+ .spanname { color:var(--muted-2); overflow:hidden; text-overflow:ellipsis; }
159
162
  .breachbadge { margin-left:auto; background:var(--lvl-err-bg); color:var(--error); font-weight:700; font-size:11.5px; padding:2px 9px; border-radius:999px; white-space:nowrap; }
160
163
  .pill { position:absolute; left:50%; transform:translateX(-50%); top:10px; background:var(--sel); color:var(--text); border:1px solid var(--accent); border-radius:18px; padding:5px 14px; cursor:pointer; box-shadow:0 2px 10px var(--shadow); font-size:12px; z-index:6; }
161
164
  .pill-bottom { top:auto; bottom:14px; background:var(--surface); border-color:var(--border-3); color:var(--muted-2); }
@@ -137,7 +137,7 @@ function StreamView({ spec }) {
137
137
  `;
138
138
  }
139
139
  function Blank() {
140
- return html `<div class="sub"><span class="summary">Pick a dashboard above.</span><span class="tech">Live, Network, RTM, Clogs, Logs — or ask a terminal Claude Code session to build a custom view.</span></div>`;
140
+ return html `<div class="sub"><span class="summary">Pick a dashboard above.</span><span class="tech">Live, Network, RTM, Clogs, Traces, Logs — or ask a terminal Claude Code session to build a custom view.</span></div>`;
141
141
  }
142
142
  function App() {
143
143
  const spec = useStoreValue(store, "spec", () => store.spec);
@@ -21,7 +21,7 @@ function sortOptionsFor(source) {
21
21
  { key: "oldest", label: "oldest first", get: (e) => e.timestamp || 0, dir: "asc" },
22
22
  ];
23
23
  if (source === "all")
24
- opts.push({ key: "type", label: "group by type", get: (e) => ({ network: 0, rtm: 1, clog: 2, log: 3 }[e._type || ""] ?? 9), dir: "asc" });
24
+ opts.push({ key: "type", label: "group by type", get: (e) => ({ network: 0, rtm: 1, clog: 2, trace: 3, log: 4 }[e._type || ""] ?? 9), dir: "asc" });
25
25
  if (source === "network") {
26
26
  opts.push({ key: "slow", label: "slowest (response time)", get: (e) => Number(e.duration_ms), dir: "desc" });
27
27
  opts.push({ key: "status", label: "status code (high→low)", get: (e) => Number(e.status_code), dir: "desc" });
@@ -32,6 +32,10 @@ function sortOptionsFor(source) {
32
32
  opts.push({ key: "evtype", label: "event type (A→Z)", get: (e) => e.event_type || "", dir: "asc" });
33
33
  if (source === "clog")
34
34
  opts.push({ key: "name", label: "clog name (A→Z)", get: (e) => e.event_name || "", dir: "asc" });
35
+ if (source === "trace") {
36
+ opts.push({ key: "slow", label: "slowest (duration)", get: (e) => Number(e.duration_ms), dir: "desc" });
37
+ opts.push({ key: "name", label: "trace name (A→Z)", get: (e) => e.trace_name || "", dir: "asc" });
38
+ }
35
39
  return opts;
36
40
  }
37
41
  // The spec of the tab `dir` steps away from the active one (clamped). Used by the filter box's
@@ -51,6 +55,8 @@ function neighborTabSpec(dir) {
51
55
  function searchText(ev) {
52
56
  if ((ev._type || "") === "log")
53
57
  return [ev.level, ev.package, ev.tag, ev.message].filter(Boolean).join(" ").toLowerCase();
58
+ if ((ev._type || "") === "trace")
59
+ return [ev.trace_name, ev.span_name].filter(Boolean).join(" ").toLowerCase();
54
60
  return [ev.direction, ev.method, ev.event_type, ev.event_name, shortUrl(ev.url), ev.channel].filter(Boolean).join(" ").toLowerCase();
55
61
  }
56
62
  // One raw copy line per frame (Logcat-style), pulled from the ring on copy.
@@ -60,6 +66,8 @@ function rawLine(ev) {
60
66
  return `${t} ${(ev.level || "").toUpperCase()}/${ev.tag || ""}: ${ev.message || ""}`;
61
67
  if (ev._type === "network")
62
68
  return `${t} ${ev.method || "GET"} ${shortUrl(ev.url)} ${ev.status_code ?? ""} ${ev.duration_ms ?? ""}ms`;
69
+ if (ev._type === "trace")
70
+ return `${t} ${ev.trace_name || ""} ${ev.span_name || ""} ${ev.duration_ms ?? ""}ms`;
63
71
  return `${t} ${ev._type} ${ev.event_type || ev.event_name || ""} ${ev.channel || ""}`.trimEnd();
64
72
  }
65
73
  function statusBand(c) {
@@ -90,6 +98,10 @@ function RowBody({ ev, source, highlight }) {
90
98
  const lv = (ev.level || "").toUpperCase();
91
99
  return html `<span class="t">${t}</span>${typeChip}<span class=${"lvl lvl-" + lv}>${lv || "LOG"}</span>${ev.package ? html `<span class="logpkg" title=${ev.package}>${shortPkg(ev.package)}</span>` : null}<span class="logtag">${ev.tag || ""}</span><span class="logmsg">${ev.message || ""}</span>`;
92
100
  }
101
+ if ((ev._type || source) === "trace") {
102
+ const breach = highlight && store.breaches(ev);
103
+ return html `<span class="t">${t}</span>${typeChip}${ev.duration_ms != null ? html `<span class="durchip">${fmtNum(Number(ev.duration_ms))} ms</span>` : null}<span class="tracename">${ev.trace_name || ""}</span><span class="spanname">${ev.span_name || ""}</span>${breach && highlight ? html `<span class="breachbadge">${breachBadge(ev, highlight)}</span>` : null}`;
104
+ }
93
105
  const breach = highlight && store.breaches(ev);
94
106
  const isNet = (ev._type || source) === "network" || ev.url != null;
95
107
  const code = Number(ev.status_code);
@@ -6,7 +6,7 @@ import { html } from "./html.js";
6
6
  import { useState, useEffect } from "preact/hooks";
7
7
  import { esc } from "./esc.js";
8
8
  import { shortUrl, store } from "./store.js";
9
- import { hasDetailEndpoint } from "./registry.js";
9
+ import { hasDetailEndpoint, SOURCES } from "./registry.js";
10
10
  function shq(s) {
11
11
  return "'" + String(s).replace(/'/g, "'\\''") + "'";
12
12
  }
@@ -141,7 +141,7 @@ export function Inspector({ ev, onClose }) {
141
141
  .then((d) => {
142
142
  if (!live)
143
143
  return;
144
- // {error:"Not Found"} = the id was evicted from the device ring (older than ~200). Do
144
+ // {error:"Not Found"} = the id was evicted from the device ring (see SOURCES ringSize). Do
145
145
  // NOT overwrite the good summary; keep the feed row + flag the body is gone.
146
146
  if (d && d.error && d.url == null && d.method == null) {
147
147
  setEvicted(true);
@@ -159,7 +159,7 @@ export function Inspector({ ev, onClose }) {
159
159
  }, [ev]);
160
160
  const kind = ev._type || "";
161
161
  const isNet = kind === "network" || detail.url != null || detail.method != null;
162
- const title = ev.event_name || ev.event_type || shortUrl(ev.url) || kind || "detail";
162
+ const title = ev.trace_name || ev.event_name || ev.event_type || shortUrl(ev.url) || kind || "detail";
163
163
  const copy = (which, e) => {
164
164
  let text = "";
165
165
  if (which === "json")
@@ -201,6 +201,12 @@ export function Inspector({ ev, onClose }) {
201
201
  if (ev.event_name)
202
202
  badges.push(html `<span class="ibadge">${ev.event_name}</span>`);
203
203
  }
204
+ else if (kind === "trace") {
205
+ if (detail.duration_ms != null)
206
+ badges.push(html `<span class="ibadge">${detail.duration_ms} ms</span>`);
207
+ if (ev.span_name)
208
+ badges.push(html `<span class="ibadge">${ev.span_name}</span>`);
209
+ }
204
210
  else if (kind === "log") {
205
211
  if (ev.level)
206
212
  badges.push(html `<span class=${"ibadge lvl-" + String(ev.level).toUpperCase()}>${ev.level}</span>`);
@@ -215,13 +221,19 @@ export function Inspector({ ev, onClose }) {
215
221
  const resHeaders = (detail.response_headers || detail.responseHeaders);
216
222
  const data = parseBody(detail.data);
217
223
  const logMessage = kind === "log" ? detail.message || ev.message : null;
224
+ // Trace tags arrive as a JSON object from the device detail; give them their own section so
225
+ // the interesting payload is not buried in the generic "other fields" dump.
226
+ const traceTags = kind === "trace" && detail.tags != null ? parseBody(detail.tags) : null;
218
227
  // generic "other fields" dump, minus the specially-rendered ones
219
228
  const omit = new Set([
220
229
  "_type", "id", "timestamp", "url", "method", "status_code", "duration_ms",
221
230
  "request_body", "requestBody", "response_body", "responseBody",
222
231
  "request_headers", "requestHeaders", "response_headers", "responseHeaders",
223
232
  "data", "message", "event_type", "event_name", "direction", "channel", "level", "tag", "package", "pid", "tid", "log_ts",
233
+ "trace_name", "span_name", // shown in the title + badges already
224
234
  ]);
235
+ if (traceTags)
236
+ omit.add("tags"); // rendered in its own section below
225
237
  const rest = {};
226
238
  for (const k of Object.keys(detail))
227
239
  if (!omit.has(k))
@@ -235,7 +247,7 @@ export function Inspector({ ev, onClose }) {
235
247
  </div>
236
248
  <div class="ibadges">${badges}</div>
237
249
  ${isNet && detail.url ? html `<div class="iurl" title=${detail.url}>${detail.url}</div>` : null}
238
- ${evicted ? html `<div class="trunc">This call scrolled off the device buffer (it keeps only the last ~200), so the full request/response body is no longer available. The summary above is from the live feed. Open a call sooner to capture its body.</div>` : null}
250
+ ${evicted ? html `<div class="trunc">This ${kind === "network" ? "call" : "record"} scrolled off the device buffer (it keeps the last ~${SOURCES[kind]?.ringSize ?? 200} ${kind} records), so ${SOURCES[kind]?.detailNoun ?? "the full detail"} is no longer available. The summary above is from the live feed.</div>` : null}
239
251
  <div class="copybar">
240
252
  <button class="copybtn" onClick=${(e) => copy("json", e)}>Copy JSON</button>
241
253
  ${isNet ? html `<button class="copybtn" onClick=${(e) => copy("body", e)}>Copy body</button><button class="copybtn" onClick=${(e) => copy("curl", e)}>Copy cURL</button>` : null}
@@ -248,6 +260,7 @@ export function Inspector({ ev, onClose }) {
248
260
  ${reqBody.value != null ? html `<${Section} title="request body"><${Body} parsed=${reqBody} /><//>` : null}
249
261
  ${resBody.value != null ? html `<${Section} title="response body"><${Body} parsed=${resBody} /><//>` : null}
250
262
  ${data.value != null ? html `<${Section} title="data"><${Body} parsed=${data} /><//>` : null}
263
+ ${traceTags && traceTags.value != null ? html `<${Section} title="tags"><${Body} parsed=${traceTags} /><//>` : null}
251
264
  ${reqHeaders ? html `<${Section} title="request headers" sub=${Object.keys(reqHeaders).length} open=${false}><${KV} map=${reqHeaders} /><//>` : null}
252
265
  ${resHeaders ? html `<${Section} title="response headers" sub=${Object.keys(resHeaders).length} open=${false}><${KV} map=${resHeaders} /><//>` : null}
253
266
  ${hasRest ? html `<${Section} title="other fields" open=${!isNet}><${Body} parsed=${{ value: rest, truncated: false }} /><//>` : null}
@@ -8,6 +8,7 @@ export const MATCH_FIELDS = {
8
8
  network: ["url", "method", "status_code"],
9
9
  rtm: ["event_type", "direction", "channel"],
10
10
  clog: ["event_name"],
11
+ trace: ["trace_name", "span_name"],
11
12
  log: ["tag", "level", "message", "pid", "package"],
12
13
  };
13
14
  // `all` = the union of every streaming source's fields (deduped, order-stable). Derived, not
@@ -15,7 +16,7 @@ export const MATCH_FIELDS = {
15
16
  MATCH_FIELDS.all = (() => {
16
17
  const seen = new Set();
17
18
  const out = [];
18
- for (const src of ["network", "rtm", "clog", "log"]) {
19
+ for (const src of ["network", "rtm", "clog", "trace", "log"]) {
19
20
  for (const f of MATCH_FIELDS[src])
20
21
  if (!seen.has(f)) {
21
22
  seen.add(f);
@@ -33,9 +34,10 @@ export const FIELD_VALUES = {
33
34
  // SOURCE registry: one row per source. `kind` routes the view (streaming feed vs the
34
35
  // point-in-time DB browser) without a hardcoded source check.
35
36
  export const SOURCES = {
36
- network: { label: "Network", kind: "stream", hasDetailEndpoint: true },
37
- rtm: { label: "RTM", kind: "stream", hasDetailEndpoint: true },
38
- clog: { label: "Clogs", kind: "stream", hasDetailEndpoint: true },
37
+ network: { label: "Network", kind: "stream", hasDetailEndpoint: true, eagerCapture: true, ringSize: 400, detailNoun: "the full request/response body" },
38
+ rtm: { label: "RTM", kind: "stream", hasDetailEndpoint: true, eagerCapture: true, ringSize: 2000, detailNoun: "the full payload" },
39
+ clog: { label: "Clogs", kind: "stream", hasDetailEndpoint: true, eagerCapture: true, ringSize: 1000, detailNoun: "the full payload" },
40
+ trace: { label: "Traces", kind: "stream", hasDetailEndpoint: true, ringSize: 2000, detailNoun: "the span timing and tag detail" },
39
41
  log: { label: "Logs", kind: "stream", hasDetailEndpoint: false },
40
42
  all: { label: "Live", kind: "stream" },
41
43
  db: { label: "Database", kind: "db" },
@@ -45,11 +47,16 @@ export const SOURCES = {
45
47
  export const STREAM_KINDS = Object.entries(SOURCES)
46
48
  .filter(([k, v]) => v.kind === "stream" && k !== "all")
47
49
  .map(([k]) => k);
48
- // The kinds that have a /detail endpoint (eager body capture + inspector fetch). Derived from
50
+ // The kinds that have a /detail endpoint (inspector click-fetch). Derived from
49
51
  // hasDetailEndpoint so adding a detailable source is one SOURCES edit.
50
52
  export const DETAILABLE_KINDS = Object.entries(SOURCES)
51
53
  .filter(([, v]) => v.hasDetailEndpoint)
52
54
  .map(([k]) => k);
55
+ // The kinds the store eagerly pre-fetches detail for (see eagerCapture above). A subset of
56
+ // DETAILABLE_KINDS; derived so the two flags cannot drift apart silently.
57
+ export const EAGER_CAPTURE_KINDS = Object.entries(SOURCES)
58
+ .filter(([, v]) => v.hasDetailEndpoint && v.eagerCapture)
59
+ .map(([k]) => k);
53
60
  export function hasDetailEndpoint(kind) {
54
61
  return !!SOURCES[kind]?.hasDetailEndpoint;
55
62
  }
@@ -58,7 +65,7 @@ export function hasDetailEndpoint(kind) {
58
65
  // see widgets.ts). A new widget = one key here + one component.
59
66
  export const WIDGETS = ["counter", "rate", "sparkline", "graph"];
60
67
  // Source order for the modebar / global tab-switch (matches the MODES preset order).
61
- export const SOURCE_ORDER = ["all", "network", "rtm", "clog", "log", "db"];
68
+ export const SOURCE_ORDER = ["all", "network", "rtm", "clog", "trace", "log", "db"];
62
69
  // The source options the Filters panel offers: every streaming source (db is its own container,
63
70
  // not a feed filter). Derived from SOURCES so adding a streaming source surfaces it in Filters
64
71
  // with no edit there. Ordered by SOURCE_ORDER (the modebar order) for a stable, familiar list.
@@ -1,4 +1,4 @@
1
- import { STREAM_KINDS, DETAILABLE_KINDS } from "./registry.js";
1
+ import { STREAM_KINDS, EAGER_CAPTURE_KINDS } from "./registry.js";
2
2
  // Logcat-scale retention. At the live firehose (~400+ events/sec on the unified Live tab) a
3
3
  // small ring recycles in seconds, so a rare signal (a once-per-5s heartbeat) gets evicted
4
4
  // before you can filter for it. Android Studio / Flipper keep the whole session and filter
@@ -10,7 +10,7 @@ import { STREAM_KINDS, DETAILABLE_KINDS } from "./registry.js";
10
10
  // the retention rationale stays attached to the numbers.
11
11
  const CACHE_CAP = 100000;
12
12
  const CACHE_TTL_MS = 60 * 60 * 1000;
13
- const DETAILABLE = new Set(DETAILABLE_KINDS); // sources with a server /detail endpoint
13
+ const EAGER_CAPTURE = new Set(EAGER_CAPTURE_KINDS); // sources whose detail is pre-fetched per frame
14
14
  const DETAIL_CACHE_CAP = 1500; // bounded full-detail cache (eager-captured + click-fetched)
15
15
  const CAPTURE_CONCURRENCY = 3; // max parallel background /detail fetches
16
16
  const CAP_SEEN_CAP = 4000; // bound on the dedup set for eager capture
@@ -19,16 +19,17 @@ const POLL_HEALTH_MS = 2000;
19
19
  const POLL_PROFILE_MS = 5000;
20
20
  const GRAPH_N = 60;
21
21
  const PERSEC_N = 30;
22
- const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package"];
22
+ const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package", "trace_name", "span_name"];
23
23
  const PACKAGE_CAP = 1000; // package values learned off the stream; bounded (was Infinity in the PoC, B4)
24
24
  // ---- pre-built dashboards: one tab each. Presets carry only generic placeholders; real
25
25
  // endpoints/channels/event-names are learned LIVE from the device stream. The one baked value
26
26
  // is com.Slack.internal.debug (the debug build's package), which is already public. ----
27
27
  export const MODES = [
28
- { key: "all", label: "Live", spec: { title: "Live", summary: "Live: network, RTM, analytics clogs, and Slack-app logcat in one timeline. (Logs filtered to the Slack app; clear the package chip for all apps.)", source: "all", viz: ["rate", "sparkline", "feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
28
+ { key: "all", label: "Live", spec: { title: "Live", summary: "Live: network, RTM, analytics clogs, traces, and Slack-app logcat in one timeline. (Logs filtered to the Slack app; clear the package chip for all apps.)", source: "all", viz: ["rate", "sparkline", "feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
29
29
  { key: "network", label: "Network", spec: { title: "Network", summary: "Network calls per second vs average response time, every call listed, slow ones flagged.", source: "network", viz: ["rate", "graph", "feed", "inspector"], series: [{ metric: "ratePerSec", label: "calls/s", unit: "/s" }, { metric: "avg", field: "duration_ms", label: "avg ms", unit: "ms" }], highlight: { field: "duration_ms", op: ">", value: 800, label: "slow (>800ms)" }, rateWindowSec: 10 } },
30
30
  { key: "rtm", label: "RTM", spec: { title: "RTM", summary: "Real-time websocket events as they happen.", source: "rtm", viz: ["rate", "feed", "inspector"] } },
31
31
  { key: "clog", label: "Clogs", spec: { title: "Clogs", summary: "Analytics clog events, click any to see its full payload.", source: "clog", viz: ["rate", "feed", "inspector"] } },
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" }] } },
32
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" } } },
33
34
  { key: "db", label: "Database", spec: { title: "Device DB", summary: "Browse the on-device SQLite databases (read-only snapshot).", source: "db" } },
34
35
  ];
@@ -119,8 +120,8 @@ class Store {
119
120
  getDetail(kind, id) {
120
121
  return this.detailCache.get(kind + ":" + id);
121
122
  }
122
- // ---- eager body capture (any DETAILABLE tab, while it is open) ----
123
- // The device keeps only the last ~200 network calls, so a row clicked later is gone. While a
123
+ // ---- eager body capture (any EAGER_CAPTURE tab, while it is open) ----
124
+ // The device ring evicts old records (network keeps 400), so a row clicked later is gone. While a
124
125
  // detailable tab is active we proactively fetch each NEW frame's full body in the background
125
126
  // (concurrency-bounded) and cache it, so clicking an old row never hits eviction. Off on
126
127
  // every other tab (mirrors Flipper's shouldStripResponseBody). Forward-only: no backfill.
@@ -131,7 +132,7 @@ class Store {
131
132
  maybeCapture(ev) {
132
133
  const src = this.spec.source;
133
134
  const kind = ev._type || "";
134
- if (ev.id == null || !DETAILABLE.has(kind))
135
+ if (ev.id == null || !EAGER_CAPTURE.has(kind))
135
136
  return;
136
137
  if (src !== "all" && src !== kind)
137
138
  return;
@@ -30,6 +30,10 @@ export declare function seedInitialSpec(): void;
30
30
  */
31
31
  export declare function cleanupOnBind(): void;
32
32
  export declare function createServer(): http.Server;
33
+ export declare const DEVICE_SOURCES: Record<string, {
34
+ segment: string;
35
+ arrayKey: string;
36
+ }>;
33
37
  /**
34
38
  * Finish a /detail proxy response after an upstream error or timeout. The success
35
39
  * callback streams the upstream response, so headers may already be sent when a later
@@ -5,6 +5,7 @@ import path from "path";
5
5
  import { spawn } from "child_process";
6
6
  import { fileURLToPath } from "url";
7
7
  import { AndroidTransport, resolveAdbPath } from "../shared/android.js";
8
+ import { planReconnect } from "../shared/stream.js";
8
9
  import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
9
10
  import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, } from "../shared/db.js";
10
11
  import { LogSession } from "./log-session.js";
@@ -452,13 +453,15 @@ function handleEnable(res) {
452
453
  });
453
454
  return;
454
455
  }
455
- try {
456
- transport.activate(transport.getTimeoutMinutes());
457
- }
458
- catch (e) {
456
+ // activate() never throws; a failed broadcast is recorded on the transport.
457
+ // Surfacing it here gives the dashboard user the actual adb error instead of
458
+ // a bare enabled:false after the ping probe times out.
459
+ transport.activate(transport.getTimeoutMinutes());
460
+ const activateError = transport.getLastActivateError?.() ?? null;
461
+ if (activateError) {
459
462
  sendJson(res, 200, {
460
463
  enabled: false,
461
- error: `Broadcast failed: ${e.message}. Debug build not running?`,
464
+ error: `Broadcast failed: ${activateError}. Is the device connected?`,
462
465
  });
463
466
  return;
464
467
  }
@@ -469,7 +472,15 @@ function handleEnable(res) {
469
472
  if (replied)
470
473
  return;
471
474
  replied = true;
472
- sendJson(res, 200, { enabled });
475
+ // A failed probe gets guidance, not a bare false: the broadcast landed (or
476
+ // exited 0 with no receiver), so the likely causes are a build without the
477
+ // radar modules or the wrong profile. Mirrors the MCP enable message.
478
+ sendJson(res, 200, enabled
479
+ ? { enabled }
480
+ : {
481
+ enabled,
482
+ error: "Radar broadcast sent but the device server did not respond. Is a debug build with the slack-radar modules running on the active profile?",
483
+ });
473
484
  };
474
485
  const probe = http.request({
475
486
  host: RADAR_HOST,
@@ -489,15 +500,20 @@ function handleEnable(res) {
489
500
  });
490
501
  probe.end();
491
502
  }
492
- const SOURCE_ARRAY_KEY = {
493
- network: "calls",
494
- rtm: "events",
495
- clog: "clogs",
503
+ // The device-buffered source kinds, in one table so a new source is one row here: the
504
+ // device API route segment (clog and trace pluralize; the rest match the kind name) and
505
+ // the array key its list response wraps the records in. Backfill and the /detail proxy
506
+ // both read this, so the two cannot drift apart. Logs are host-side and absent by design.
507
+ export const DEVICE_SOURCES = {
508
+ network: { segment: "network", arrayKey: "calls" },
509
+ rtm: { segment: "rtm", arrayKey: "events" },
510
+ clog: { segment: "clogs", arrayKey: "clogs" },
511
+ trace: { segment: "traces", arrayKey: "traces" },
496
512
  };
497
513
  /**
498
514
  * Replay the device's recent ring buffers for a source so a freshly-built tab
499
515
  * shows history immediately instead of filling only going forward. The device is
500
- * the source of truth. "all" pulls network+rtm+clog and merges them oldest->newest;
516
+ * the source of truth. "all" pulls network+rtm+clog+trace and merges them oldest->newest;
501
517
  * "log" is host-side (no device buffer) and so has nothing to replay. Returns
502
518
  * `[{type, event}]` frames mirroring the stream shape.
503
519
  */
@@ -506,10 +522,10 @@ function handleBackfill(req, res) {
506
522
  const src = u.searchParams.get("source") ?? "network";
507
523
  const limit = Math.min(500, Number(u.searchParams.get("limit")) || 200);
508
524
  const kinds = src === "all"
509
- ? ["network", "rtm", "clog"]
510
- : [src].filter((k) => k !== "log" && k in SOURCE_ARRAY_KEY);
525
+ ? Object.keys(DEVICE_SOURCES)
526
+ : [src].filter((k) => Object.hasOwn(DEVICE_SOURCES, k));
511
527
  const fetchKind = (kind) => new Promise((resolve) => {
512
- const apiPath = `/api/${kind === "clog" ? "clogs" : kind}?limit=${limit}`;
528
+ const apiPath = `/api/${DEVICE_SOURCES[kind].segment}?limit=${limit}`;
513
529
  const rq = http.request({
514
530
  host: RADAR_HOST,
515
531
  port: RADAR_PORT,
@@ -522,7 +538,7 @@ function handleBackfill(req, res) {
522
538
  up.on("end", () => {
523
539
  try {
524
540
  const j = JSON.parse(b);
525
- const arr = j[SOURCE_ARRAY_KEY[kind]] ?? [];
541
+ const arr = j[DEVICE_SOURCES[kind].arrayKey] ?? [];
526
542
  resolve(arr.map((e) => ({ type: kind, event: e })));
527
543
  }
528
544
  catch {
@@ -546,13 +562,6 @@ function handleBackfill(req, res) {
546
562
  })
547
563
  .catch(() => sendJson(res, 200, { frames: [] }));
548
564
  }
549
- // Detail kinds the inspector may request, mapped to their device route segment. The
550
- // device serves clog detail at /api/clogs/ (plural); the rest match the kind name.
551
- const DETAIL_ROUTES = {
552
- network: "network",
553
- rtm: "rtm",
554
- clog: "clogs",
555
- };
556
565
  /**
557
566
  * Finish a /detail proxy response after an upstream error or timeout. The success
558
567
  * callback streams the upstream response, so headers may already be sent when a later
@@ -578,7 +587,7 @@ function handleDetail(req, res) {
578
587
  const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
579
588
  const id = u.searchParams.get("id");
580
589
  const kind = u.searchParams.get("kind") ?? "network";
581
- const route = DETAIL_ROUTES[kind];
590
+ const route = DEVICE_SOURCES[kind]?.segment;
582
591
  if (!id || !route) {
583
592
  res.writeHead(400, { "Content-Type": "application/json; charset=utf-8" });
584
593
  res.end("{}");
@@ -1003,16 +1012,11 @@ function handleStream(req, res) {
1003
1012
  return;
1004
1013
  settled = true;
1005
1014
  retries++;
1006
- // Every other retry, rebuild a clean forward before reconnecting. resetState()
1007
- // drops the cached forward flag so ensureForward() actually re-runs adb forward.
1008
- if (retries % 2 === 0) {
1009
- transport.resetState();
1010
- transport.ensureForward();
1011
- setTimeout(connect, 1500);
1012
- }
1013
- else {
1014
- setTimeout(connect, 2000);
1015
- }
1015
+ // planReconnect (shared/stream.ts) owns the cadence: every other retry it
1016
+ // rebuilds a clean forward before reconnecting and returns the delay. One
1017
+ // implementation for this proxy and the MCP stream, so a tuning change
1018
+ // cannot silently move only one of them.
1019
+ setTimeout(connect, planReconnect(transport, retries));
1016
1020
  };
1017
1021
  const connect = () => {
1018
1022
  if (closed)