@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.
@@ -6,6 +6,7 @@
6
6
  import { html } from "./html.js";
7
7
  import { useState, useEffect, useRef, useCallback } from "preact/hooks";
8
8
  import { showToast, showSaveToast, onDownloadFinished, revealInFinder, isCaptureDownloadMatch, } from "./toast.js";
9
+ import { useLatestRef } from "./hooks.js";
9
10
  // The MJPEG live stream runs at 20fps (measured sweet spot: 20 beats 12 on both frame
10
11
  // rate and jitter; 30/60 add no frames and worsen jitter). The cache-buster ?t pins a
11
12
  // fresh connection each time the <img> is (re)wired so a stale frame is never reused.
@@ -21,25 +22,29 @@ function snapshotSrc() {
21
22
  // platforms' redetect only re-probes, so their title must not claim it.
22
23
  const REDETECT_TITLE_ANDROID = "Re-detect the display and reset the mirror. Also stops Radar's screen recording on the device.";
23
24
  const REDETECT_TITLE = "Re-detect the display and reset the mirror.";
24
- export function ScreenOverlay({ open, onClose }) {
25
+ export function ScreenOverlay({ open, onClose, capsSource, }) {
25
26
  const [caps, setCaps] = useState(null);
26
27
  const [consent, setConsent] = useState(false);
27
28
  const [recording, setRecording] = useState(false);
28
- const [hint, setHint] = useState("");
29
+ // Two lines with two owners, so neither's writers can destroy the other's message. `status` is
30
+ // the transient line (mirror state, refusals and start failures, redetect results); `save` is
31
+ // the capture lifecycle, the in-progress or recording note and then the outcome in its place,
32
+ // carrying the reveal link and staying up until the next capture. One shared line needed an
33
+ // ownership protocol over one string; the split is what makes "a stream drop cannot erase a
34
+ // save confirmation" structural instead of checked, and keeping the whole capture lifecycle on
35
+ // its own line is what lets the mirror's "live." survive a screenshot.
36
+ const [status, setStatus] = useState("");
37
+ const [save, setSave] = useState(null);
29
38
  // Set once the native side (packaged dock app only) confirms a download actually finished and
30
39
  // reports its real on-disk path -- the requested filename can differ from the final one on a
31
40
  // collision, so this can only be known after the fact, not guessed at request time.
32
41
  const [revealPath, setRevealPath] = useState(null);
33
- // The capture this hint is waiting on, set from the moment a save is requested and cleared
34
- // once some unrelated hint takes the line over.
35
- // The native side reports a finished download hundreds of ms after the request (it can only
36
- // name the real on-disk path once the write completes), and by then the hint may belong to
37
- // something else entirely -- the live-cast effect's 3.5s "live." message is the one that
38
- // shows up in practice. Accepting the path regardless left that unrelated line underlined
39
- // and revealing a PNG. Gating acceptance is what closes it; clearing afterwards cannot,
40
- // because the overwrite has already happened by the time the path arrives.
41
- // It holds the FILE, not just a flag: two captures a download-latency apart would otherwise
42
- // leave the hint naming the second save while a click revealed the first one's file.
42
+ // The capture the save line is waiting on, set from the moment a save is requested. The native
43
+ // side reports a finished download hundreds of ms after the request (it can only name the real
44
+ // on-disk path once the write completes), so the gate is what keeps a late path from attaching
45
+ // to a line that has since moved on to a newer capture. It holds the FILE, not just a flag:
46
+ // two captures a download-latency apart would otherwise leave the line naming the second save
47
+ // while a click revealed the first one's file.
43
48
  const awaitedFile = useRef(null);
44
49
  useEffect(() => onDownloadFinished((path) => {
45
50
  const want = awaitedFile.current;
@@ -55,8 +60,7 @@ export function ScreenOverlay({ open, onClose }) {
55
60
  // unmounts), so an unmount-cleanup never fires to stop a recording on close. Track the
56
61
  // live recording flag in a ref so the open-keyed effect below reads the CURRENT value
57
62
  // (not a stale closure) when it tears down.
58
- const recordingRef = useRef(false);
59
- recordingRef.current = recording;
63
+ const recordingRef = useLatestRef(recording);
60
64
  // Trigger a download by navigating a hidden iframe at the endpoint, never the visible page.
61
65
  // The server already sends Content-Disposition: attachment on these routes, and a browser (or
62
66
  // WKWebView) treats that the same in a subframe as in the main frame: it hands the response to
@@ -79,34 +83,45 @@ export function ScreenOverlay({ open, onClose }) {
79
83
  const triggerDownload = (url) => {
80
84
  getDownloadFrame().src = url;
81
85
  };
82
- // Download whatever /screen/record/stop returns, then unset recording. Shared by the
83
- // explicit stop button and the close-while-recording teardown so both behave identically.
84
- // Always leaves a confirmation behind, both the inline hint AND the floating toast: a silent
85
- // success looks identical to a silent failure, and closing the panel to trigger this (the
86
- // auto-save path right below) unmounts the inline hint before anyone can read it -- the toast
87
- // is what actually survives that.
88
- // Report a completed save the same way for a screenshot and a recording: the inline hint AND
89
- // the floating toast, and the reveal gate opened for THIS save's file, so a native
90
- // download-finished path is accepted only when it is the one this message names.
86
+ // Report a completed save the same way for a screenshot and a recording: the inline save line
87
+ // AND the floating toast, with the reveal gate opened for THIS save's file, so a native
88
+ // download-finished path is accepted only when it is the one this message names. Both surfaces
89
+ // because a silent success looks identical to a silent failure, and closing the panel to trigger
90
+ // this (the auto-save path below) unmounts the inline line before anyone can read it, so the
91
+ // toast is what survives that.
91
92
  // A save whose file the server did not name still gets announced, it just cannot offer reveal:
92
93
  // with no name there is nothing to match a late download path against, and matching nothing is
93
94
  // how the wrong file got revealed in the first place.
95
+ // The outcome replaces the in-progress note IN PLACE: announceStart below put that note on this
96
+ // same line, so nothing here touches the status line, and a mirror message ("live.") survives a
97
+ // capture untouched.
94
98
  const announceSave = useCallback((msg, file) => {
95
99
  awaitedFile.current = file;
96
- setHint(msg);
100
+ setSave(msg);
97
101
  if (file)
98
102
  showSaveToast(msg, file);
99
103
  else
100
104
  showToast(msg);
101
105
  }, []);
102
106
  // Say what actually happened, with the reveal gate shut: there is no file to reveal, so a
103
- // late path from an earlier save must not attach itself to this line.
107
+ // late path from an earlier save must not attach itself to this line. A failure replaces the
108
+ // in-progress note the same way a success does, because it IS this capture's outcome.
104
109
  const announceFailure = useCallback((msg) => {
105
110
  awaitedFile.current = null;
106
111
  setRevealPath(null);
107
- setHint(msg);
112
+ setSave(msg);
108
113
  showToast(msg);
109
114
  }, []);
115
+ // A capture's in-progress note opens the same line its outcome will close, so the note and the
116
+ // answer cannot stack and no capture writer ever crosses onto the status line (the mirror keeps
117
+ // whatever it was saying). Shuts the reveal gate for the PREVIOUS save first: the old line is
118
+ // being replaced, so a click during the request must not reveal the file it used to name, and a
119
+ // late download path from it has nothing to attach to.
120
+ const announceStart = useCallback((msg) => {
121
+ awaitedFile.current = null;
122
+ setRevealPath(null);
123
+ setSave(msg);
124
+ }, []);
110
125
  // Ask the server to save, and only claim success once it says it did. Both capture routes are
111
126
  // two-phase for the same reason: the download itself is a Content-Disposition response the
112
127
  // page cannot observe, so the JSON reply is the only place an error can be seen.
@@ -142,9 +157,9 @@ export function ScreenOverlay({ open, onClose }) {
142
157
  }, [announceFailure, announceSave]);
143
158
  const stopAndSave = useCallback(async () => {
144
159
  setRecording(false);
145
- setHint("stopping recording…");
160
+ announceStart("stopping recording…");
146
161
  await requestSave("/screen/record/stop", "recording", "nothing to save (recording was too short or never started)");
147
- }, [requestSave]);
162
+ }, [announceStart, requestSave]);
148
163
  // Stop + save a running recording when the panel closes. Without this, closing the panel
149
164
  // (or toggling ▣ Screen) mid-recording unmounts the <img> and drops the live viewer, but
150
165
  // the server keeps screenrecord + ffmpeg + a growing mp4 alive (removeViewer only cleans
@@ -161,37 +176,67 @@ export function ScreenOverlay({ open, onClose }) {
161
176
  setConsent(!!c.consent);
162
177
  }
163
178
  catch {
164
- setCaps(null);
179
+ // Keeping prev is the part that changes behavior: on the open path the subscribe effect
180
+ // below has already seeded it off the store, so nulling here would throw away a real answer
181
+ // and strand an open panel on the install prose. The store read is only the cold fallback
182
+ // for a catch that beats that effect.
183
+ setCaps((prev) => prev ?? capsSource.screenCaps);
165
184
  }
166
- }, []);
185
+ }, [capsSource]);
167
186
  useEffect(() => {
168
187
  if (open)
169
188
  loadCaps();
170
189
  }, [open, loadCaps]);
171
- // Sets an ordinary status hint and clears any reveal link along with it. Plain setHint alone
172
- // is wrong for every hint EXCEPT the two save confirmations below: without clearing revealPath,
173
- // an unrelated status line (the live-stream message, a consent error, a re-detect result) would
174
- // stay underlined and clickable pointing at whatever file a PREVIOUS screenshot or recording
175
- // saved, which is exactly the bug seen live -- the "live. Screen again to close." status line
176
- // rendered as if it were a save confirmation, left over from an earlier reveal.
177
- const setPlainHint = useCallback((msg) => {
178
- // Also shuts the reveal gate: once an unrelated line owns the hint, a save's late
179
- // download-finished path has nothing left to attach to and must be ignored.
180
- awaitedFile.current = null;
181
- setRevealPath(null);
182
- setHint(msg);
183
- }, []);
190
+ // Live caps while open: the store mirrors handleHealth's screen object off its /health polls,
191
+ // so a capability change reaches an OPEN overlay without reopening it. What can move is narrow.
192
+ // On Android /health reads the cached probe, so something has to refresh that cache first: this
193
+ // tab pressing the screenshot button, or any tab's /screen/caps?refresh=1. On iOS the caps are
194
+ // rebuilt from a booted simulator whenever something drops the controller cache, and /enable
195
+ // drops it, so an enable press followed by any /health poll is itself a re-probe. loadCaps above
196
+ // stays the on-open authority because its refresh=1 forces a re-detect; this only reacts to
197
+ // later changes.
198
+ useEffect(() => {
199
+ if (!open)
200
+ return;
201
+ // Read the store's existing copy once BEFORE subscribing, the order hooks.ts documents for
202
+ // useStoreValue: updateScreenCaps dedupes, so a copy banked while this overlay was closed
203
+ // never emits again. Seeds only when there is nothing yet, so loadCaps keeps precedence.
204
+ setCaps((prev) => prev ?? capsSource.screenCaps);
205
+ return capsSource.on("screen-caps", (c) => {
206
+ setCaps((prev) => {
207
+ // consent is carried over explicitly because /health's copy never has it (only
208
+ // /screen/caps does), and carrying it by name keeps that structural rather than dependent
209
+ // on the payload staying complete. Nothing reads caps.consent after load (the panel's
210
+ // consent answer is its own state), so the retention is shape stability for the equality
211
+ // below, not a data dependency; the stream itself is held steady by the derived flags.
212
+ const next = { ...c, consent: prev?.consent };
213
+ return prev && JSON.stringify(prev) === JSON.stringify(next) ? prev : next;
214
+ });
215
+ });
216
+ }, [open, capsSource]);
217
+ // The wiring effect keys on these two flags, not on the caps object: caps now move while the
218
+ // panel is open, and an unrelated field flipping (scrcpy appearing, a new installHint) would
219
+ // otherwise re-point the <img>, drop a healthy MJPEG stream and restart the 3.5s first-frame
220
+ // hint. capsKnown separates "no answer yet" from "answered, no mirror" for the downgrade below.
221
+ const liveCast = !!(caps && caps.liveCast);
222
+ const snapshotCast = !!(caps && caps.snapshotCast);
223
+ const capsKnown = !!caps;
224
+ // The single answer the record button and its own handler both read, so the capability half
225
+ // cannot disagree between them; consent stays the handler's own gate, and its refusal names it.
226
+ // False while the caps are unknown: an enabled button whose handler answers "needs ffmpeg" is the
227
+ // contradiction users hit, seconds after granting the consent that same message asks for.
228
+ const canRecord = !!(caps && (caps.recording ?? caps.liveCast));
184
229
  // wire the live <img> once consent + ffmpeg are present
185
230
  useEffect(() => {
186
231
  if (!open || !consent)
187
232
  return;
188
- if (caps && caps.liveCast && imgRef.current) {
233
+ if (liveCast && imgRef.current) {
189
234
  imgRef.current.src = streamSrc();
190
- setPlainHint("capturing first frame (~3s on a foldable)…");
191
- const id = setTimeout(() => setPlainHint("live. ▣ Screen again to close."), 3500);
235
+ setStatus("capturing first frame (~3s on a foldable)…");
236
+ const id = setTimeout(() => setStatus("live. ▣ Screen again to close."), 3500);
192
237
  return () => clearTimeout(id);
193
238
  }
194
- if (caps && caps.snapshotCast && imgRef.current) {
239
+ if (snapshotCast && imgRef.current) {
195
240
  let failures = 0;
196
241
  let inflight = false;
197
242
  let currentUrl = null;
@@ -224,14 +269,20 @@ export function ScreenOverlay({ open, onClose }) {
224
269
  };
225
270
  refresh();
226
271
  const id = setInterval(refresh, 1000);
227
- setPlainHint("simulator mirror (refreshes every second). ▣ Screen again to close.");
272
+ setStatus("simulator mirror (refreshes every second). ▣ Screen again to close.");
228
273
  return () => {
229
274
  clearInterval(id);
230
275
  if (currentUrl)
231
276
  URL.revokeObjectURL(currentUrl);
232
277
  };
233
278
  }
234
- }, [open, consent, caps, setPlainHint]);
279
+ // Losing every mirror while open swaps the body to the install block, so a leftover "live."
280
+ // or simulator-mirror line would sit above text saying ffmpeg is not installed. Clearing the
281
+ // status line unconditionally is safe now that saves live on their own line: everything on
282
+ // this line is transient, and the body swap itself explains the state.
283
+ if (capsKnown && !liveCast && !snapshotCast)
284
+ setStatus("");
285
+ }, [open, consent, capsKnown, liveCast, snapshotCast]);
235
286
  const accept = useCallback(async () => {
236
287
  try {
237
288
  // X-Radar-Dashboard marks this as coming from our own client. Without it the server refuses
@@ -240,28 +291,34 @@ export function ScreenOverlay({ open, onClose }) {
240
291
  setConsent(true);
241
292
  }
242
293
  catch {
243
- setPlainHint("consent failed");
294
+ setStatus("consent failed");
244
295
  }
245
- }, [setPlainHint]);
296
+ }, []);
246
297
  const shot = useCallback(async () => {
247
298
  if (!consent) {
248
- setPlainHint("accept the notice first");
299
+ setStatus("accept the notice first");
249
300
  return;
250
301
  }
251
302
  if (saving)
252
303
  return;
253
304
  setSaving(true);
254
- setPlainHint("taking a screenshot…");
305
+ announceStart("taking a screenshot…");
255
306
  try {
256
307
  await requestSave("/screen/shot/save", "screenshot", "nothing to save");
257
308
  }
258
309
  finally {
259
310
  setSaving(false);
260
311
  }
261
- }, [consent, saving, requestSave, setPlainHint]);
312
+ }, [consent, saving, announceStart, requestSave]);
262
313
  const rec = useCallback(async () => {
263
- if (!consent || !(caps && (caps.recording ?? caps.liveCast))) {
264
- setPlainHint("recording needs ffmpeg + consent");
314
+ // The gate is about STARTING one. A recording already running has to stay stoppable even after
315
+ // the caps that allowed it went away, which they now can while the panel is open.
316
+ if (!recording && !(consent && canRecord)) {
317
+ // Naming ffmpeg is only honest once the server has answered. With consent already given and no
318
+ // caps yet, the refusal says what the body says: the answer is still being fetched.
319
+ setStatus(consent && !capsKnown
320
+ ? "still detecting screen capture support…"
321
+ : "recording needs ffmpeg + consent");
265
322
  return;
266
323
  }
267
324
  if (!recording) {
@@ -269,14 +326,20 @@ export function ScreenOverlay({ open, onClose }) {
269
326
  const response = await fetch("/screen/record/start", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
270
327
  const result = await response.json().catch(() => ({}));
271
328
  if (!response.ok || !result.ok) {
272
- setHint(result.error || "recording failed to start");
329
+ // Start refusals and failures stay on the status line: no capture began, so the save
330
+ // line still holds the LAST capture's outcome, which is still true and still reveals.
331
+ setStatus(result.error || "recording failed to start");
273
332
  return;
274
333
  }
275
334
  setRecording(true);
276
- setHint("recording…");
335
+ // The recording IS the capture in progress, so its note lives on the save line like the
336
+ // other lifecycle notes; "stopping recording…" and then the outcome replace it in place.
337
+ // Leaving it on the status line stranded a false "recording…" for the session once the
338
+ // announcers stopped clearing that line.
339
+ announceStart("recording…");
277
340
  }
278
341
  catch {
279
- setHint("recording failed to start");
342
+ setStatus("recording failed to start");
280
343
  }
281
344
  }
282
345
  else {
@@ -286,23 +349,23 @@ export function ScreenOverlay({ open, onClose }) {
286
349
  if (imgRef.current)
287
350
  imgRef.current.src = streamSrc();
288
351
  }
289
- }, [consent, caps, recording, stopAndSave, setPlainHint]);
352
+ }, [consent, canRecord, capsKnown, recording, announceStart, stopAndSave]);
290
353
  const redetect = useCallback(async () => {
291
- setPlainHint("re-detecting active panel…");
354
+ setStatus("re-detecting active panel…");
292
355
  // Authored: redetect tears down the live cast and deletes finished recordings, so the server
293
356
  // refuses it without proof this is our own client.
294
357
  const r = await (await fetch("/screen/redetect", { headers: { "X-Radar-Dashboard": "1" } }))
295
358
  .json()
296
359
  .catch(() => ({}));
297
360
  if (r.error) {
298
- setPlainHint(r.error);
361
+ setStatus(r.error);
299
362
  }
300
363
  else {
301
364
  if (consent && caps && caps.liveCast && imgRef.current)
302
365
  imgRef.current.src = streamSrc();
303
- setPlainHint("display: " + (r.display || "default"));
366
+ setStatus("display: " + (r.display || "default"));
304
367
  }
305
- }, [consent, caps, setPlainHint]);
368
+ }, [consent, caps]);
306
369
  if (!open)
307
370
  return null;
308
371
  let body;
@@ -319,7 +382,13 @@ export function ScreenOverlay({ open, onClose }) {
319
382
  `;
320
383
  }
321
384
  else if (caps && (caps.liveCast || caps.snapshotCast)) {
322
- body = html `<img id="screenimg" ref=${imgRef} alt="device screen" onError=${() => setPlainHint("stream dropped (device disconnected?). reset to retry.")} />`;
385
+ body = html `<img id="screenimg" ref=${imgRef} alt="device screen" onError=${() => setStatus("stream dropped (device disconnected?). reset to retry.")} />`;
386
+ }
387
+ else if (!capsKnown) {
388
+ // No answer from the server yet: the iOS simctl probe takes seconds, and a failed on-open fetch
389
+ // with an empty store answers nothing at all. The install block below states a negative the
390
+ // server never gave, so it waits until there is an answer to state.
391
+ body = html `<div class="scdetect">Detecting screen capture support…</div>`;
323
392
  }
324
393
  else {
325
394
  const cmd = caps && caps.installHint;
@@ -330,25 +399,37 @@ export function ScreenOverlay({ open, onClose }) {
330
399
  ? html `<span> Install it with this command, then reopen this panel:<br /><br /><code>${cmd}</code> <button class="sccopy" onClick=${(e) => { navigator.clipboard?.writeText(cmd); e.currentTarget.textContent = "copied"; }}>copy</button></span>`
331
400
  : html `<span> Install it with your system package manager (for example <code>brew install ffmpeg</code> on macOS, <code>winget install ffmpeg</code> on Windows, or <code>sudo apt install ffmpeg</code> on Debian/Ubuntu), then reopen this panel.</span>`}
332
401
  </div>
333
- <div class="scinstall">📷 Screenshot works without ffmpeg — use the button above.</div>
402
+ ${caps && caps.screenshot
403
+ ? html `<div class="scinstall">📷 Screenshot works without ffmpeg — use the button above.</div>`
404
+ : null}
334
405
  ${caps && caps.scrcpy ? html `<div class="scinstall">scrcpy is installed; for a native mirror window run <code>scrcpy</code> in a terminal.</div>` : null}
335
406
  `;
336
407
  }
408
+ // A running recording keeps its stop button no matter what the caps say now. Caps move while the
409
+ // panel is open, so gating on the current ones alone would render "■ stop" disabled the moment a
410
+ // simulator shut down, leaving the close path as the only way to end a recording in progress.
411
+ // The screenshot button below stays gated on `saving` alone because neither it nor its handler
412
+ // reads the caps: the POST is what finds out whether a capture works, and it reports its own
413
+ // failure, so there is no claim here to keep in step with.
414
+ const recDisabled = saving || (!recording && !canRecord);
337
415
  return html `
338
416
  <div id="screenpanel" class="on">
339
417
  <div class="schead">
340
418
  <span class="sctitle">Device screen</span>
341
419
  <button class="scbtn" onClick=${shot} disabled=${saving} title="Full-resolution screenshot">📷</button>
342
- <button class=${"scbtn" + (recording ? " rec" : "")} disabled=${saving || (!!caps && !(caps.recording ?? caps.liveCast))} onClick=${rec} title="Record to mp4">${recording ? "■ stop" : "● rec"}</button>
420
+ <button class=${"scbtn" + (recording ? " rec" : "")} disabled=${recDisabled} onClick=${rec} title="Record to mp4">${recording ? "■ stop" : "● rec"}</button>
343
421
  <button class="scbtn" onClick=${redetect} title=${caps?.platform === "android" ? REDETECT_TITLE_ANDROID : REDETECT_TITLE}>⟳ reset</button>
344
422
  <button class="scbtn" onClick=${onClose} title="Close">✕</button>
345
423
  </div>
346
- <div
347
- id="schint"
348
- style=${revealPath ? { cursor: "pointer", textDecoration: "underline" } : undefined}
349
- title=${revealPath ? "Click to show in Finder" : undefined}
350
- onClick=${revealPath ? () => revealInFinder(revealPath) : undefined}
351
- >${hint}</div>
424
+ <div id="schint">${status}</div>
425
+ ${save
426
+ ? html `<div
427
+ id="scsave"
428
+ style=${revealPath ? { cursor: "pointer", textDecoration: "underline" } : undefined}
429
+ title=${revealPath ? "Click to show in Finder" : undefined}
430
+ onClick=${revealPath ? () => revealInFinder(revealPath) : undefined}
431
+ >${save}</div>`
432
+ : null}
352
433
  <div id="screenbody">${body}</div>
353
434
  </div>
354
435
  `;