dsh-embedded-browser-next 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1629 @@
1
+ /**
2
+ * The panel's live channel: one stream per *watched* session, input back to the
3
+ * session the panel belongs to.
4
+ *
5
+ * Chrome only emits `Page.startScreencast` frames for the **active** tab
6
+ * (`references/PITFALLS.md` #13), and a DSH host runs one Chrome for every
7
+ * session. So this hub is the single owner of "which tab is in front": the
8
+ * session whose panel is actually being looked at gets a real screencast, every
9
+ * other attached session is served by polled `Page.captureScreenshot` frames,
10
+ * and input is replayed into the panel's own session rather than into "the"
11
+ * page. Activation is deliberately confined here — the AI never moves the
12
+ * foreground, because every tab accepts injected input either way.
13
+ *
14
+ * @module dsh-embedded-browser/screencast
15
+ */
16
+
17
+ import { appendFileSync, statSync, writeFileSync } from 'node:fs'
18
+ import { sleep } from './browser.js'
19
+ import { logFile } from './diagnostics.js'
20
+ import { saveDownload } from './downloads.js'
21
+ import { MjpegSink } from './mjpeg.js'
22
+ import { Residency } from './residency.js'
23
+
24
+ /**
25
+ * One line per reporting window on the whole picture path: frames produced,
26
+ * bytes pushed, frames dropped by back-pressure, the current frame ceiling, and
27
+ * what the panel measured for itself.
28
+ *
29
+ * "The frame rate is low" has four candidate causes — Chrome composites slowly,
30
+ * the socket cannot drain, the decoder is slow, or the panel paints slowly — and
31
+ * they cannot be told apart from a number in the status bar. This file is how
32
+ * they are told apart.
33
+ */
34
+ const STREAM_LOG = logFile('browser-stream.log', 'DSH_BROWSER_STREAM_LOG')
35
+
36
+ /**
37
+ * A stream log left unbounded grew to several megabytes of idle heartbeat lines
38
+ * (one per 2.5 s pushState) before anyone looked. The cap is what turns a
39
+ * diagnostic into a bounded one.
40
+ */
41
+ const STREAM_LOG_MAX_BYTES = 1024 * 1024
42
+
43
+ /** Append one diagnostic line; a failing trace must never disturb the stream. */
44
+ function streamLog(line) {
45
+ if (STREAM_LOG === '') return
46
+ try {
47
+ if ((statSync(STREAM_LOG, { throwIfNoEntry: false })?.size ?? 0) > STREAM_LOG_MAX_BYTES) {
48
+ writeFileSync(STREAM_LOG, `${new Date().toISOString()} stream log rotated\n`)
49
+ }
50
+ appendFileSync(STREAM_LOG, `${new Date().toISOString()} ${line}\n`)
51
+ } catch {
52
+ /* diagnostics are best-effort */
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Drop frames (rather than queue them) once a socket is this far behind.
58
+ *
59
+ * The ceiling is **per session and derived from the frames actually flowing**,
60
+ * not a constant. At ~200 KB a frame, 3 MB meant fifteen frames of slack — half a
61
+ * second of lag that the panel faithfully played out. A megabyte keeps the
62
+ * backlog around a fifth of a second, which is a delay nobody notices but a stall
63
+ * everybody does.
64
+ *
65
+ * The constants below are the guard rails of that derivation: never less than
66
+ * three frames' worth (a single big frame must not trip the gate), never more
67
+ * than a megabyte.
68
+ */
69
+ const MIN_BUFFERED_BYTES = 128 * 1024
70
+ const MAX_BUFFERED_BYTES = 1024 * 1024
71
+ /** Frames of backlog tolerated before frames are dropped instead of queued. */
72
+ const BUFFERED_FRAMES = 3
73
+
74
+ /** How often the panels are told about URL/title/session changes. */
75
+ const STATE_POLL_MS = 2500
76
+
77
+ /**
78
+ * First gate of the stall watchdog, and its hard ceiling.
79
+ *
80
+ * A screencast is **change-driven**: a page that is sitting still emits no frames
81
+ * at all. "No frame for a while" therefore says nothing about the pipeline — only
82
+ * "an input got no frame in reply" does. The gate doubles on each fruitless
83
+ * restart and resets the moment a frame arrives, so a genuinely dead pipe heals
84
+ * within seconds while a healthy-but-quiet page is never touched.
85
+ */
86
+ const STALL_BASE_MS = 8000
87
+ const STALL_MAX_MS = 300_000
88
+
89
+ /** Polled frame cadence for sessions that are not in front (~7 fps at 140 ms). */
90
+ const DEFAULT_POLL_MS = 140
91
+
92
+ /**
93
+ * Frame-rate gates used when the viewer is behind.
94
+ *
95
+ * The bottleneck on a moving picture is not the capture, it is the viewer's own
96
+ * decoder: a 1151×799 JPEG measured ~204 KB on a playing video, and Chrome emits
97
+ * up to ~54 fps, so the pipeline was pushing **8 MB/s** into an `<img>` that could
98
+ * not keep up. Measured result: `writableLength` climbing to 860 KB (four frames
99
+ * of backlog) and 200+ dropped frames — the picture stayed visible but stuttered,
100
+ * which reads as "特别特别的卡".
101
+ *
102
+ * Dropping frames after they are queued does not fix that; the queue is already
103
+ * the lag. Gating *before* sending does: 25 ms is 40 fps, 50 ms is 20 fps, and on
104
+ * a video 20–40 fps is visually complete. The gate only engages while bytes are
105
+ * actually backed up, so ordinary scrolling keeps full rate.
106
+ */
107
+ const FRAME_GATE_LIGHT_MS = 25
108
+ const FRAME_GATE_HEAVY_MS = 50
109
+
110
+ /** Backlog, in frames, at which the gate stops being polite. */
111
+ const FRAME_GATE_HEAVY_FRAMES = 1.5
112
+
113
+ /**
114
+ * How long after the last input the stream returns to the sharp profile.
115
+ *
116
+ * Moving and reading want opposite things. While the picture moves, a smaller,
117
+ * coarser frame arrives and decodes sooner — that is what "跟手" is made of. Once
118
+ * the hand stops, the same picture is going to be read, so sharpness wins again.
119
+ * 320 ms is longer than the gap inside one wheel gesture (one notch every ~30 ms)
120
+ * and shorter than a person's pause before reading, so a gesture never flips the
121
+ * profile back and forth in the middle.
122
+ */
123
+ const PROFILE_IDLE_MS = 320
124
+
125
+ /** Shortest interval between two profile swaps, so a flick never thrashes CDP. */
126
+ const PROFILE_MIN_GAP_MS = 120
127
+
128
+ /**
129
+ * Gap under which two inputs count as one continuous gesture.
130
+ *
131
+ * A wheel gesture repeats every ~16–30 ms and a drag every frame, so this is
132
+ * comfortably above both and far below the pause between two separate gestures.
133
+ *
134
+ * The distinction matters because a swap is not free: `stop` + `start` measured
135
+ * 3–61 ms, which is the same order as the transfer it saves. For one isolated
136
+ * click the trade is a loss — measured p50 was 18–24 ms sharp against 20–28 ms
137
+ * adaptive. For a sustained scroll it is a large win, because the cost is paid
138
+ * once and every following frame is four times smaller.
139
+ */
140
+ const BURST_GAP_MS = 120
141
+
142
+ /**
143
+ * How long a profile swap may occupy the CDP wire.
144
+ *
145
+ * The wire is shared with every input command, and the CDP default is 30 s: one
146
+ * swap that never answers sits in front of the next wheel event for half a
147
+ * minute, which is exactly how a test run went from 40 s to six minutes. A swap
148
+ * only improves a picture that is already arriving, so it gets a budget far below
149
+ * that and gives up instead of holding the input path hostage.
150
+ */
151
+ const SWAP_TIMEOUT_MS = 1500
152
+
153
+
154
+ /** CDP modifier bitmask values. */
155
+ const MODIFIERS = { alt: 1, ctrl: 2, meta: 4, shift: 8 }
156
+
157
+ /** Translate the panel's modifier list into the CDP bitmask. */
158
+ function modifierMask(list) {
159
+ if (!Array.isArray(list)) return 0
160
+ let mask = 0
161
+ for (const name of list) mask |= MODIFIERS[name] ?? 0
162
+ return mask
163
+ }
164
+
165
+ /**
166
+ * Bridges every session's page to the panels that render it.
167
+ */
168
+ export class ScreencastHub {
169
+ /**
170
+ * @param options - browser manager, logger, metrics config, human broker.
171
+ */
172
+ constructor({ manager, logger, viewport, renderScale, fitPanelAspect, transport, quality, maxWidth, maxHeight, human, pollMs = DEFAULT_POLL_MS, adaptive = true, fastScale = 0.55, fastQuality = 50, residency }) {
173
+ this.manager = manager
174
+ this.logger = logger
175
+ /**
176
+ * Which conversation keeps its real browser, and when one is closed.
177
+ *
178
+ * The hub owns the guest table, so it is the only place that knows which
179
+ * sessions currently have a real browser — the sweeper asks it. The policy
180
+ * itself lives in `Residency` so "may this go?" is testable without Electron.
181
+ */
182
+ this.residency = residency ?? new Residency({ logger })
183
+ /** sessionId -> timer waiting for a panel to confirm its guest is gone. */
184
+ this.reclaimWatch = new Map()
185
+ /**
186
+ * sessionId -> `{ at, reason }` for panels that went away and did **not** come
187
+ * back.
188
+ *
189
+ * The agent has to be told that the browser it was driving is gone, because the
190
+ * alternative — silently answering from the headless tab — looks identical to
191
+ * success while describing a different machine (no logins, freshly loaded
192
+ * page). It is *not* an error: the human may have walked away on purpose, and
193
+ * deciding whether to stop, retry, or tell them is the agent's call, not ours.
194
+ */
195
+ this.lostPanel = new Map()
196
+ /** Sessions the sweeper has asked to let go, so the reason is not lost. */
197
+ this.reclaiming = new Set()
198
+ this.viewport = viewport
199
+ // Frames arrive at `viewport × renderScale`; the panel must divide bitmap
200
+ // coordinates by this to get back to CDP's CSS-pixel input space.
201
+ this.renderScale = Number.isFinite(Number(renderScale)) ? Math.min(2, Math.max(1, Number(renderScale))) : 1
202
+ /** Whether a panel may reshape the viewport to its own aspect ratio. */
203
+ this.fitPanelAspect = fitPanelAspect !== false
204
+ /** `mjpeg` streams into an <img>; `ws` feeds the canvas fallback. */
205
+ this.transport = transport === 'ws' ? 'ws' : 'mjpeg'
206
+ this.quality = quality
207
+ this.maxWidth = maxWidth
208
+ this.maxHeight = maxHeight
209
+ this.human = human
210
+ this.pollMs = Math.max(60, pollMs)
211
+ /**
212
+ * Whether the picture trades sharpness for hand-following while it moves.
213
+ *
214
+ * `off` pins every frame to the configured quality and size, which is exactly
215
+ * the behaviour of the previous release.
216
+ */
217
+ this.adaptive = adaptive !== false
218
+ /** Edge multiplier of the fast profile, relative to the sharp ceiling. */
219
+ const scale = Number(fastScale)
220
+ this.fastScale = Number.isFinite(scale) ? Math.min(1, Math.max(0.25, scale)) : 0.55
221
+ /** JPEG quality of the fast profile. */
222
+ const fast = Number(fastQuality)
223
+ this.fastQuality = Number.isFinite(fast) ? Math.min(95, Math.max(20, Math.round(fast))) : 50
224
+ /** `sharp` while the page is being read, `fast` while it is being moved. */
225
+ this.profile = 'sharp'
226
+ /** Timestamp of the last swap, backing the anti-thrash gap. */
227
+ this.profileAt = 0
228
+ /** Timer that walks the profile back to `sharp` once the hand stops. */
229
+ this.profileTimer = undefined
230
+ /** Timestamp of the newest input that expects a repaint. */
231
+ this.lastMoveAt = 0
232
+ /**
233
+ * Exponential moving average of one encoded frame, in bytes.
234
+ *
235
+ * Drives the back-pressure gate: a ceiling that is a fixed number of bytes is
236
+ * a different number of *frames* on every page, and the number of frames of
237
+ * backlog is the only thing that turns into visible lag.
238
+ */
239
+ this.avgFrameBytes = 0
240
+ /** Panel connections; each carries `sessionId`, `watching` and `focusedAt`. */
241
+ this.connections = new Set()
242
+ /** sessionId whose tab is held in front and streamed with the real screencast. */
243
+ this.watched = undefined
244
+ this.stream = undefined
245
+ this.streamTask = Promise.resolve()
246
+ /** sessionId -> { timer, busy, lastFrameAt } */
247
+ this.pollers = new Map()
248
+ /** sessionId -> { count, since } backing the `fps` number the panel shows. */
249
+ this.frameStats = new Map()
250
+ this.stateTimer = undefined
251
+ this.lastStates = new Map()
252
+ this.lastOverview = undefined
253
+ this.framesDropped = 0
254
+ /** Frames the rate gate held back because the viewer was still busy. */
255
+ this.framesGated = 0
256
+ this.pollFrames = 0
257
+ this.focusSeq = 0
258
+ /**
259
+ * Following a native panel's navigation in the host browser.
260
+ *
261
+ * `followTarget` is the newest URL to load; `following` says a loop is already
262
+ * draining it. Only the newest one is kept, because the human can click three
263
+ * links faster than one page loads and walking through every intermediate page
264
+ * would load three pages nobody asked for.
265
+ */
266
+ this.followTarget = ''
267
+ this.following = false
268
+ /**
269
+ * Native panels that can act as the browser.
270
+ *
271
+ * A panel showing a real Chromium guest owns the page the human is looking at,
272
+ * and that browser is the one sites do not treat as a bot. When one is mounted
273
+ * for a session, tool calls are forwarded to it instead of driving the second,
274
+ * invisible, headless browser.
275
+ */
276
+ this.guestGlue = new Map()
277
+ this.guestPending = new Map()
278
+ this.guestSeq = 0
279
+ /**
280
+ * Sessions whose page lives in a real browser window instead of the panel.
281
+ *
282
+ * The panel mounts a guest for every session with `open: true`, and a mounted
283
+ * guest wins routing — so after a switch to the window the panel kept taking
284
+ * the tool calls back (measured 2026-11-29: navigate answered `via: panel`
285
+ * right after the window opened). This set travels in every state push, and
286
+ * the panel skips its guest while it is true.
287
+ */
288
+ this.windowed = new Set()
289
+ /**
290
+ * sessionId -> `{ lastFrameAt, lastInputAt, gate }` — the watchdog's memory.
291
+ *
292
+ * It deliberately lives on the hub rather than on `this.stream`, because
293
+ * `startStream()` builds a **new** stream object for every (re)start. Keeping
294
+ * the state there meant a restart reset the backoff to 8 s and refreshed
295
+ * `lastInputAt` to "just now", so a still page looked like a freshly-touched
296
+ * one that had stalled: the watchdog restarted the stream every ten seconds,
297
+ * forever, with its own log line promising "next check in 16s".
298
+ */
299
+ this.health = new Map()
300
+ }
301
+
302
+ /** The watchdog state for one session, created on first use. */
303
+ healthOf(sessionId) {
304
+ let state = this.health.get(sessionId)
305
+ if (state === undefined) {
306
+ // `lastInputAt: 0` means "nobody has touched this yet" on purpose. Seeding it
307
+ // with `Date.now()` made a freshly opened panel look like a page that had
308
+ // just been interacted with, so a still page was judged stale exactly once,
309
+ // eight seconds after opening. A stream that never produces a first frame
310
+ // still heals: any real input arms the watchdog.
311
+ state = { lastFrameAt: Date.now(), lastInputAt: 0, gate: STALL_BASE_MS }
312
+ this.health.set(sessionId, state)
313
+ }
314
+ return state
315
+ }
316
+
317
+ /** Count one frame handed to a session's panels. */
318
+ countFrame(sessionId, bytes = 0) {
319
+ // Guard the accumulator: `NaN += 0` is still NaN, so one non-numeric size
320
+ // would poison this session's byte counter for the rest of the process and
321
+ // every later `kb=` line would read NaN.
322
+ const size = Number.isFinite(Number(bytes)) ? Number(bytes) : 0
323
+ let stat = this.frameStats.get(sessionId)
324
+ if (stat === undefined) {
325
+ stat = { count: 0, bytes: 0, since: Date.now() }
326
+ this.frameStats.set(sessionId, stat)
327
+ }
328
+ stat.count += 1
329
+ stat.bytes = Number.isFinite(stat.bytes) ? stat.bytes + size : size
330
+ }
331
+
332
+ /**
333
+ * Close one measurement window and reset it.
334
+ *
335
+ * @param sessionId - session whose panels are being measured.
336
+ * @returns `{ fps, frames, bytes, span }`, or undefined while the window is
337
+ * too short to mean anything (a freshly attached panel, or a still page).
338
+ */
339
+ takeWindow(sessionId) {
340
+ const stat = this.frameStats.get(sessionId)
341
+ if (stat === undefined) return undefined
342
+ const span = Date.now() - stat.since
343
+ if (span < 400) return undefined
344
+ const frames = stat.count
345
+ // Self-heal a value that was already poisoned before the guard existed.
346
+ const bytes = Number.isFinite(stat.bytes) ? stat.bytes : 0
347
+ stat.count = 0
348
+ stat.bytes = 0
349
+ stat.since = Date.now()
350
+ return { fps: Math.round((frames * 1000) / span), frames, bytes, span }
351
+ }
352
+
353
+ /** Every panel attached to one session. */
354
+ connectionsFor(sessionId) {
355
+ const list = []
356
+ for (const connection of this.connections) {
357
+ if (connection.sessionId === sessionId) list.push(connection)
358
+ }
359
+ return list
360
+ }
361
+
362
+ /**
363
+ * Whether this session already has an `<img>` viewer taking the frames.
364
+ *
365
+ * When it does, the session's WebSocket panel is control-and-input only: sending
366
+ * it the same frames as well would double the bandwidth for pictures nobody
367
+ * paints.
368
+ *
369
+ * @param sessionId - session to test.
370
+ * @returns True when at least one MJPEG sink is attached.
371
+ */
372
+ hasMjpegViewer(sessionId) {
373
+ for (const connection of this.connections) {
374
+ if (connection.sessionId === sessionId && connection instanceof MjpegSink) return true
375
+ }
376
+ return false
377
+ }
378
+
379
+ /** Send one control message to every panel, or to one session's panels. */
380
+ broadcast(message, sessionId) {
381
+ for (const connection of this.connections) {
382
+ if (sessionId !== undefined && connection.sessionId !== sessionId) continue
383
+ connection.sendJson(message)
384
+ }
385
+ }
386
+
387
+ /** Accept a panel connection for one session. */
388
+ async attach(connection, sessionId) {
389
+ connection.sessionId = sessionId
390
+ connection.watching = false
391
+ connection.focusedAt = 0
392
+ this.connections.add(connection)
393
+ connection.on('close', () => {
394
+ this.connections.delete(connection)
395
+ // A panel that goes away takes its guest with it: any tool call waiting on it
396
+ // must fail now rather than sit until its timeout.
397
+ this.dropGuest(connection)
398
+ void this.sync()
399
+ })
400
+ connection.on('message', (message) => {
401
+ if (message.type !== 'text') return
402
+ let payload
403
+ try {
404
+ payload = JSON.parse(message.data)
405
+ } catch {
406
+ return
407
+ }
408
+ void this.handleMessage(connection, payload).catch((error) => {
409
+ this.logger?.debug?.(`panel message failed: ${error.message}`)
410
+ })
411
+ })
412
+ await this.welcome(connection, sessionId)
413
+ }
414
+
415
+ /**
416
+ * Accept a receive-only HTTP viewer for one session.
417
+ *
418
+ * The response is a `multipart/x-mixed-replace` stream that a plain `<img>`
419
+ * renders, so the panel never decodes a frame in JavaScript. Input and control
420
+ * still travel over that session's WebSocket: a replacement response has no
421
+ * upstream, and keeping one control channel avoids two sources of truth for
422
+ * focus.
423
+ *
424
+ * @param sessionId - the session whose tab this viewer watches.
425
+ * @param response - the HTTP response to hold open.
426
+ * @returns the sink, so the caller can inspect or close it.
427
+ */
428
+ async attachMjpeg(sessionId, response) {
429
+ const sink = new MjpegSink({ response, logger: this.logger })
430
+ sink.sessionId = sessionId
431
+ // An `<img>` viewer *is* somebody watching, even though it sends no input.
432
+ // Marking it idle would tie the whole stream's survival to the WebSocket
433
+ // control channel: one transient socket blip would make `sync()` decide the
434
+ // session is unwatched, stop the screencast, and freeze a picture that is
435
+ // still on screen. Input still arrives over the socket; looking does not.
436
+ sink.watching = true
437
+ sink.focusedAt = Date.now()
438
+ this.connections.add(sink)
439
+ sink.on('close', () => {
440
+ this.connections.delete(sink)
441
+ void this.sync()
442
+ })
443
+ // A browser that navigates away or a panel that unmounts closes the socket
444
+ // without telling us; the response is the authority.
445
+ response.on('close', () => sink.close())
446
+ await this.welcome(sink, sessionId)
447
+ return sink
448
+ }
449
+
450
+ /**
451
+ * Wake the session's tab, greet the viewer and give it one frame to paint.
452
+ *
453
+ * Shared by both transports so a WebSocket panel and an `<img>` viewer take the
454
+ * exact same path — the frames are identical, only their destination differs.
455
+ *
456
+ * @param connection - a WebSocket connection or an MJPEG sink.
457
+ * @param sessionId - the session to attach it to.
458
+ */
459
+ async welcome(connection, sessionId) {
460
+ let [status, browser] = await Promise.all([
461
+ this.manager.status(sessionId),
462
+ this.manager.status(),
463
+ ])
464
+ // [dsh-rc5 fix] A panel that just became visible is the strongest signal that
465
+ // this session wants a browser: the idle reaper (default 10 min) may have
466
+ // taken the process down, and a host restart drops every tab. Without this the
467
+ // panel attaches to a dead session and stays black, which is the
468
+ // "无法连接 / 连不上" report. It costs one status read when the browser is up.
469
+ if (browser.running !== true || status.session?.open !== true) {
470
+ try {
471
+ await this.manager.ensureSession(sessionId)
472
+ ;[status, browser] = await Promise.all([
473
+ this.manager.status(sessionId),
474
+ this.manager.status(),
475
+ ])
476
+ } catch (error) {
477
+ this.logger?.warn?.(`panel wake failed: ${error.message}`)
478
+ }
479
+ }
480
+ connection.sendJson({
481
+ type: 'hello',
482
+ sessionId,
483
+ // The *live* viewport, not the configured one: the panel maps pointer
484
+ // coordinates through it, and a shaped session is 1440×1726, not 1440×900.
485
+ viewport: status.session?.viewport ?? this.viewport,
486
+ renderScale: this.renderScale,
487
+ quality: this.quality,
488
+ transport: this.transport,
489
+ // The panel draws its own quality hint from these: `adaptive` off means the
490
+ // number never changes, so there is nothing to show.
491
+ adaptive: this.adaptive,
492
+ profile: this.profile,
493
+ mode: status.session?.open === true ? 'poll' : 'idle',
494
+ // The panel mounts a guest as soon as it sees `open`, and `windowed` is what
495
+ // stops it from mounting a second copy of a page that lives in a real
496
+ // window. Carrying it in `hello` closes the gap where the first state push
497
+ // arrives a beat late and a 300ms mount timer wins the race.
498
+ windowed: this.windowed.has(sessionId),
499
+ status,
500
+ browser,
501
+ human: this.human.snapshot(sessionId),
502
+ })
503
+ await this.seedFrame(connection)
504
+ await this.sync()
505
+ await this.pushState({ force: true })
506
+ }
507
+
508
+ /**
509
+ * Recompute the foreground session and the poller set.
510
+ *
511
+ * Serialized through `streamTask`: a panel that disconnects stops its stream
512
+ * asynchronously, and starting the next one before that finished used to kill
513
+ * the new screencast (the reconnect race this plugin was born with).
514
+ */
515
+ async sync() {
516
+ let want
517
+ let best = -1
518
+ for (const connection of this.connections) {
519
+ if (connection.watching === true && connection.focusedAt > best) {
520
+ best = connection.focusedAt
521
+ want = connection.sessionId
522
+ }
523
+ }
524
+ if (want !== this.watched) {
525
+ this.watched = want
526
+ this.manager.setWatched(want)
527
+ this.streamTask = this.streamTask
528
+ .then(async () => {
529
+ await this.stopStream()
530
+ if (want !== undefined) await this.startStream(want)
531
+ })
532
+ .catch((error) => this.logger?.warn?.(`screencast switch failed: ${error.message}`))
533
+ await this.streamTask
534
+ } else if (want !== undefined) {
535
+ // A freshly created session tab steals the foreground; put it back.
536
+ await this.manager.activateSession(want)
537
+ // Activation clears the emulated viewport, so a tab that merely got pushed
538
+ // to the front would silently lose the panel's shape.
539
+ await this.manager.restoreViewport(want)
540
+ }
541
+
542
+ const needed = new Set()
543
+ for (const connection of this.connections) {
544
+ // A native guest paints itself. Encoding frames for it would spend a full
545
+ // viewport of CPU per second to produce a picture nothing displays.
546
+ if (connection.native === true) continue
547
+ if (connection.sessionId !== this.watched) needed.add(connection.sessionId)
548
+ }
549
+ for (const sessionId of [...this.pollers.keys()]) {
550
+ if (!needed.has(sessionId)) this.stopPoller(sessionId)
551
+ }
552
+ for (const sessionId of needed) {
553
+ if (!this.pollers.has(sessionId)) this.startPoller(sessionId)
554
+ }
555
+ this.ensureStateTimer()
556
+ }
557
+
558
+ /**
559
+ * The `Page.startScreencast` arguments for one profile.
560
+ *
561
+ * CDP fixes these for the life of a screencast — re-issuing `startScreencast`
562
+ * while one is running answers `Screencast is already active`, so changing them
563
+ * means `stop` + `start` (measured at 3–61 ms, i.e. at most one frame).
564
+ *
565
+ * @param name - `sharp` or `fast`; defaults to the profile in force.
566
+ * @returns the CDP parameters, with the ceiling resolved from the current
567
+ * viewport so a shaped panel keeps its shape in both profiles.
568
+ */
569
+ streamParams(name = this.profile) {
570
+ if (name === 'fast') {
571
+ return {
572
+ format: 'jpeg',
573
+ quality: this.fastQuality,
574
+ // Only the *frame ceiling* shrinks, never the page's viewport: resizing
575
+ // the emulated viewport would reflow the page (hundreds of milliseconds
576
+ // and a layout jump) every time a wheel gesture started.
577
+ maxWidth: Math.max(320, Math.round(this.maxWidth * this.fastScale)),
578
+ maxHeight: Math.max(240, Math.round(this.maxHeight * this.fastScale)),
579
+ everyNthFrame: 1,
580
+ }
581
+ }
582
+ return {
583
+ format: 'jpeg',
584
+ quality: this.quality,
585
+ maxWidth: this.maxWidth,
586
+ maxHeight: this.maxHeight,
587
+ everyNthFrame: 1,
588
+ }
589
+ }
590
+
591
+ /**
592
+ * How many bytes of unflushed frame data a sink may hold before frames are
593
+ * dropped instead of queued.
594
+ *
595
+ * Dropping is the point: a dropped frame costs nothing but a skipped picture,
596
+ * while a queued one is *latency the viewer pays on every later frame*. The
597
+ * gate is expressed in frames, because "three frames behind" is the quantity a
598
+ * person perceives, and one frame is 8 KB on a mostly-text page and 350 KB on a
599
+ * video page.
600
+ *
601
+ * @param frameBytes - size of the frame about to be sent.
602
+ * @returns the byte ceiling for this send.
603
+ */
604
+ bufferedLimit(frameBytes) {
605
+ const average = this.avgFrameBytes > 0 ? this.avgFrameBytes : Number(frameBytes) || 0
606
+ const wanted = Math.max(average, Number(frameBytes) || 0) * BUFFERED_FRAMES
607
+ if (!Number.isFinite(wanted) || wanted <= 0) return MAX_BUFFERED_BYTES
608
+ return Math.min(MAX_BUFFERED_BYTES, Math.max(MIN_BUFFERED_BYTES, Math.round(wanted)))
609
+ }
610
+
611
+ /** Fold one frame size into the moving average that sizes the backlog gate. */
612
+ observeFrameBytes(bytes) {
613
+ const size = Number(bytes)
614
+ if (!Number.isFinite(size) || size <= 0) return
615
+ this.avgFrameBytes = this.avgFrameBytes === 0 ? size : this.avgFrameBytes * 0.8 + size * 0.2
616
+ }
617
+
618
+ /**
619
+ * How long to wait before sending another frame, given the current backlog.
620
+ *
621
+ * A backlog of zero means the viewer is keeping up and the picture may run at
622
+ * full speed. Anything above zero means the next frame would be queued behind
623
+ * work the viewer has not done yet, and queueing is exactly what turns into the
624
+ * lag people feel — so the gate slows the source down instead.
625
+ *
626
+ * @param backlog - bytes the viewers have not consumed yet.
627
+ * @returns the minimum interval between frames, in ms (0 = no limit).
628
+ */
629
+ frameInterval(backlog) {
630
+ if (!(backlog > 0)) return 0
631
+ const average = this.avgFrameBytes
632
+ if (average > 0 && backlog >= average * FRAME_GATE_HEAVY_FRAMES) return FRAME_GATE_HEAVY_MS
633
+ return FRAME_GATE_LIGHT_MS
634
+ }
635
+
636
+ /**
637
+ * Note that somebody is moving the picture right now.
638
+ *
639
+ * Called for every input that is expected to repaint (the same set the stall
640
+ * watchdog arms on — a bare mouse move must not count, or simply hovering would
641
+ * pin the stream to the coarse profile).
642
+ *
643
+ * Only a **continuous** gesture switches to `fast`. The first input of a burst
644
+ * merely records the time; the second one, arriving within `BURST_GAP_MS`, is
645
+ * what proves the page is being scrubbed rather than clicked once. Switching on
646
+ * every isolated click would pay the 3–61 ms swap for a picture that was going
647
+ * to settle immediately anyway.
648
+ */
649
+ noteActivity() {
650
+ if (this.adaptive !== true || this.stream === undefined) return
651
+ const now = Date.now()
652
+ const previous = this.lastMoveAt
653
+ this.lastMoveAt = now
654
+ if (previous > 0 && now - previous < BURST_GAP_MS && this.profile !== 'fast') {
655
+ void this.swapProfile('fast')
656
+ }
657
+ this.armIdle()
658
+ }
659
+
660
+ /** (Re)start the countdown that returns the picture to full sharpness. */
661
+ armIdle() {
662
+ if (this.adaptive !== true) return
663
+ clearTimeout(this.profileTimer)
664
+ this.profileTimer = setTimeout(() => {
665
+ this.profileTimer = undefined
666
+ void this.swapProfile('sharp')
667
+ }, PROFILE_IDLE_MS)
668
+ this.profileTimer.unref?.()
669
+ }
670
+
671
+ /**
672
+ * Swap the frame profile, restarting the screencast if one is running.
673
+ *
674
+ * Serialized through `streamTask` for the same reason `sync()` is: a swap and a
675
+ * session switch interleaving would stop the pipe twice and start it twice, and
676
+ * the second `startScreencast` on an already-running stream is an error.
677
+ */
678
+ async swapProfile(name) {
679
+ if (this.adaptive !== true) return
680
+ if (this.profile === name) return
681
+ const now = Date.now()
682
+ if (now - this.profileAt < PROFILE_MIN_GAP_MS) {
683
+ // Too soon after the last swap: fold this one into the pending idle walk
684
+ // rather than thrashing CDP.
685
+ if (name === 'fast') return
686
+ clearTimeout(this.profileTimer)
687
+ this.profileTimer = setTimeout(() => {
688
+ this.profileTimer = undefined
689
+ void this.swapProfile('sharp')
690
+ }, PROFILE_MIN_GAP_MS)
691
+ this.profileTimer.unref?.()
692
+ return
693
+ }
694
+ const previous = this.profile
695
+ this.profile = name
696
+ this.profileAt = now
697
+ const stream = this.stream
698
+ if (stream === undefined) return
699
+ const params = this.streamParams()
700
+ let applied = false
701
+ this.streamTask = this.streamTask
702
+ .then(async () => {
703
+ // A session switch or a panel leaving may have replaced or stopped the
704
+ // stream while this swap waited in the queue; only act on the live one.
705
+ if (this.stream !== stream) return
706
+ try {
707
+ await stream.page.send('Page.stopScreencast', undefined, undefined, SWAP_TIMEOUT_MS)
708
+ await stream.page.send('Page.startScreencast', params, undefined, SWAP_TIMEOUT_MS)
709
+ applied = true
710
+ } catch (error) {
711
+ // A swap is an improvement, never a requirement: if the wire swallowed
712
+ // it, roll the belief back so the hub does not advertise a profile the
713
+ // page is not streaming, and give up quietly.
714
+ this.profile = previous
715
+ this.logger?.warn?.(`profile swap to ${name} failed: ${error.message}`)
716
+ // The stop half may still have landed, which leaves the pipe dead.
717
+ // `restartStream()` waits on the queue this code is inside, so the
718
+ // recovery has to be scheduled from outside it.
719
+ const timer = setTimeout(() => { void this.restartStream() }, 0)
720
+ timer.unref?.()
721
+ }
722
+ })
723
+ .catch((error) => this.logger?.warn?.(`profile swap failed: ${error.message}`))
724
+ await this.streamTask
725
+ if (applied !== true) return
726
+ streamLog(`profile sid=${stream.sessionId.slice(-6)} now=${this.profile} q=${params.quality} ${params.maxWidth}x${params.maxHeight}`)
727
+ this.broadcast({ type: 'profile', profile: this.profile, quality: params.quality }, stream.sessionId)
728
+ }
729
+
730
+ /** Start the real screencast for one session (it becomes the active tab). */
731
+ async startStream(sessionId) {
732
+ // [dsh-rc5 fix] Wake the tab on demand instead of silently returning: a
733
+ // reaped browser or a restarted host leaves the panel attached to nothing,
734
+ // and the old early return made that state permanent until the user typed.
735
+ let record = this.manager.session(sessionId)
736
+ if (record === undefined) {
737
+ record = await this.manager.ensureSession(sessionId).catch(() => undefined)
738
+ }
739
+ if (record === undefined) {
740
+ this.logger?.debug?.(`stream requested for ${sessionId} without a tab`)
741
+ return
742
+ }
743
+ const page = record.page
744
+ const stream = { sessionId, page, detach: [] }
745
+ // Touch the watchdog state but never reset it: a restart is exactly the case
746
+ // the backoff has to survive.
747
+ this.healthOf(sessionId)
748
+ this.stream = stream
749
+ await this.manager.activateSession(sessionId)
750
+ // Activation drops the emulated viewport, and every path that starts a stream
751
+ // ends up here — including the plain `sync()` one that a focus request takes.
752
+ // Restoring it anywhere else leaves that path unguarded, which is exactly how
753
+ // the panel ended up measuring a 16:10 page while asking for 0.75.
754
+ await this.manager.restoreViewport(sessionId)
755
+ stream.detach.push(
756
+ page.on('Page.screencastFrame', (params) => {
757
+ void this.onFrame(params, sessionId)
758
+ }),
759
+ page.on('Page.frameNavigated', () => {
760
+ void this.pushState()
761
+ }),
762
+ )
763
+ // A fresh stream starts still: whatever profile the previous one was left in
764
+ // belongs to a gesture that has long ended, and starting coarse would show
765
+ // the first frame of a new panel visibly soft.
766
+ clearTimeout(this.profileTimer)
767
+ this.profileTimer = undefined
768
+ this.profile = 'sharp'
769
+ await page.send('Page.startScreencast', this.streamParams())
770
+ this.broadcast({ type: 'stream', mode: 'screencast' }, sessionId)
771
+ // Seed the rate window even though a still page emits no frames: without an
772
+ // entry the panel cannot tell "nothing is moving" from "no measurement yet",
773
+ // and the status line would simply stay blank.
774
+ if (!this.frameStats.has(sessionId)) this.frameStats.set(sessionId, { count: 0, since: Date.now() })
775
+ this.logger?.debug?.(`screencast started (${sessionId})`)
776
+ }
777
+
778
+ /** Stop the active screencast, keeping the emulated viewport in place. */
779
+ async stopStream() {
780
+ const stream = this.stream
781
+ if (stream === undefined) return
782
+ this.stream = undefined
783
+ // No pipe to sharpen: a pending walk back to `sharp` would fire at a stream
784
+ // that no longer exists and only log a failure.
785
+ clearTimeout(this.profileTimer)
786
+ this.profileTimer = undefined
787
+ this.profile = 'sharp'
788
+ for (const off of stream.detach) off()
789
+ // Only the screencast stops here: clearing the emulated viewport as well
790
+ // would flip the page between two sizes on every switch, and a panel
791
+ // mid-mapping would then aim at the wrong coordinates.
792
+ await stream.page.send('Page.stopScreencast').catch(() => {})
793
+ this.logger?.debug?.(`screencast stopped (${stream.sessionId})`)
794
+ }
795
+
796
+ /**
797
+ * Restart the active screencast so a new frame ceiling takes effect.
798
+ *
799
+ * `Page.startScreencast` fixes `maxWidth`/`maxHeight` for the whole session, so
800
+ * a viewport change has to bounce the stream — otherwise Chrome keeps
801
+ * downscaling every frame to the old ceiling and the added sharpness is lost.
802
+ */
803
+ async restartStream() {
804
+ const sessionId = this.watched
805
+ if (sessionId === undefined) return
806
+ this.streamTask = this.streamTask
807
+ .then(async () => {
808
+ await this.stopStream()
809
+ await this.startStream(sessionId)
810
+ })
811
+ .catch((error) => this.logger?.warn?.(`screencast restart failed: ${error.message}`))
812
+ await this.streamTask
813
+ }
814
+
815
+ /** Fan one JPEG frame of a session to that session's panels. */
816
+ async onFrame(params, sessionId) {
817
+ const stream = this.stream
818
+ if (stream === undefined || stream.sessionId !== sessionId) return
819
+ let payload
820
+ try {
821
+ payload = Buffer.from(params.data, 'base64')
822
+ } catch {
823
+ return
824
+ }
825
+ // A frame proves the pipe is alive, so the watchdog starts over.
826
+ const health = this.healthOf(sessionId)
827
+ health.lastFrameAt = Date.now()
828
+ health.gate = STALL_BASE_MS
829
+ this.countFrame(sessionId, payload.length)
830
+ this.observeFrameBytes(payload.length)
831
+ // Acknowledge **first**: Chrome will not capture the next frame until this
832
+ // one is acked, so waiting for the fan-out (up to seven socket writes per
833
+ // viewer) would put that write cost in front of every frame's capture. The
834
+ // ack is fire-and-forget for the same reason.
835
+ if (params.sessionId !== undefined) {
836
+ stream.page.send('Page.screencastFrameAck', { sessionId: params.sessionId }).catch(() => {})
837
+ }
838
+ const limit = this.bufferedLimit(payload.length)
839
+ // With an <img> viewer attached, the WebSocket panel is input-only.
840
+ const httpOnly = this.hasMjpegViewer(sessionId)
841
+ const viewers = []
842
+ for (const connection of this.connectionsFor(sessionId)) {
843
+ if (httpOnly && !(connection instanceof MjpegSink)) continue
844
+ viewers.push(connection)
845
+ }
846
+ if (viewers.length === 0) return
847
+ // Slow the source down while the viewer is still busy with earlier frames.
848
+ // Gating here is what keeps a video from queueing four frames of lag; the
849
+ // frame is already acked above, so Chrome keeps capturing either way.
850
+ let backlog = 0
851
+ for (const connection of viewers) backlog = Math.max(backlog, connection.bufferedAmount ?? 0)
852
+ const interval = this.frameInterval(backlog)
853
+ const now = Date.now()
854
+ if (interval > 0 && now - (health.lastSentAt ?? 0) < interval) {
855
+ this.framesGated += 1
856
+ return
857
+ }
858
+ health.lastSentAt = now
859
+ for (const connection of viewers) {
860
+ if (connection.bufferedAmount > limit) {
861
+ this.framesDropped += 1
862
+ continue
863
+ }
864
+ connection.sendBinary(payload)
865
+ }
866
+ }
867
+
868
+ /** Poll one frame for a session that cannot own the foreground. */
869
+ startPoller(sessionId) {
870
+ const timer = setInterval(() => {
871
+ void this.pollOnce(sessionId)
872
+ }, this.pollMs)
873
+ timer.unref?.()
874
+ this.pollers.set(sessionId, { timer, busy: false, lastFrameAt: 0 })
875
+ this.broadcast({ type: 'stream', mode: 'poll' }, sessionId)
876
+ }
877
+
878
+ stopPoller(sessionId) {
879
+ const state = this.pollers.get(sessionId)
880
+ if (state === undefined) return
881
+ clearInterval(state.timer)
882
+ this.pollers.delete(sessionId)
883
+ }
884
+
885
+ async pollOnce(sessionId) {
886
+ const state = this.pollers.get(sessionId)
887
+ if (state === undefined || state.busy) return
888
+ const targets = this.connectionsFor(sessionId)
889
+ if (targets.length === 0) return
890
+ const record = this.manager.session(sessionId)
891
+ if (record === undefined) return
892
+ state.busy = true
893
+ const startedAt = Date.now()
894
+ try {
895
+ // `optimizeForSpeed` matters here: a hidden tab is throttled, and the
896
+ // default capture path measured ~190 ms against ~59 ms with this flag.
897
+ const shot = await record.page.send('Page.captureScreenshot', { format: 'jpeg', quality: this.quality, optimizeForSpeed: true })
898
+ const payload = Buffer.from(shot.data, 'base64')
899
+ state.lastFrameAt = Date.now()
900
+ this.pollFrames += 1
901
+ this.countFrame(sessionId, payload.length)
902
+ this.observeFrameBytes(payload.length)
903
+ this.logger?.debug?.(`poll frame ok (${sessionId}) in ${Date.now() - startedAt}ms, ${payload.length} bytes`)
904
+ const limit = this.bufferedLimit(payload.length)
905
+ const httpOnly = this.hasMjpegViewer(sessionId)
906
+ for (const connection of targets) {
907
+ if (httpOnly && !(connection instanceof MjpegSink)) continue
908
+ if (connection.bufferedAmount > limit) {
909
+ this.framesDropped += 1
910
+ continue
911
+ }
912
+ connection.sendBinary(payload)
913
+ }
914
+ } catch (error) {
915
+ this.logger?.debug?.(`poll frame failed (${sessionId}) after ${Date.now() - startedAt}ms: ${error.message}`)
916
+ } finally {
917
+ state.busy = false
918
+ }
919
+ }
920
+
921
+ /** Keep the 2.5s state poll (and the stall watchdog) running while panels exist. */
922
+ ensureStateTimer() {
923
+ if (this.connections.size === 0) {
924
+ clearInterval(this.stateTimer)
925
+ this.stateTimer = undefined
926
+ return
927
+ }
928
+ if (this.stateTimer !== undefined) return
929
+ this.stateTimer = setInterval(() => {
930
+ void this.pushState()
931
+ this.checkStreamHealth()
932
+ }, STATE_POLL_MS)
933
+ this.stateTimer.unref?.()
934
+ }
935
+
936
+ /**
937
+ * Self-heal a stalled screencast: Chrome stops emitting frames if an
938
+ * acknowledgement is ever lost, and the panel would sit on a frozen image.
939
+ *
940
+ * It cannot tell that apart from a page that simply did not change, so the
941
+ * gate backs off every time a restart fails to produce a frame and is reset by
942
+ * `onFrame`. See {@link STALL_BASE_MS}.
943
+ */
944
+ checkStreamHealth() {
945
+ const stream = this.stream
946
+ if (stream === undefined) return
947
+ if (this.connectionsFor(stream.sessionId).length === 0) return
948
+ // Gate on the hub-owned state, never on the stream object: `startStream()`
949
+ // replaces that object on every restart and would silently reset the backoff.
950
+ const health = this.healthOf(stream.sessionId)
951
+ // A stall means **input produced no frame**, not "no frame for a while".
952
+ // A page that reacts and then settles is perfectly healthy: after a single
953
+ // scroll the frames stop because the page stopped moving, and judging that by
954
+ // elapsed time restarted a live stream about eight seconds after every
955
+ // interaction. Comparing the two timestamps is the honest test — and with no
956
+ // input at all, `lastInputAt` is 0, so an untouched page is never a stall.
957
+ if (health.lastFrameAt >= health.lastInputAt) return
958
+ const now = Date.now()
959
+ const waited = now - health.lastInputAt
960
+ if (waited < health.gate) return
961
+ // Claim the attempt **now**: `startStream()` is asynchronous, so without this
962
+ // the next tick (2.5 s later) would judge the same stale input again and queue
963
+ // a second restart before the first finished.
964
+ health.lastInputAt = now
965
+ health.gate = Math.min(health.gate * 2, STALL_MAX_MS)
966
+ this.logger?.warn?.(
967
+ `screencast produced no frame for ${Math.round(waited / 1000)}s after input for ${stream.sessionId} — restarting (next check in ${Math.round(health.gate / 1000)}s)`,
968
+ )
969
+ const sessionId = stream.sessionId
970
+ this.streamTask = this.streamTask
971
+ .then(async () => {
972
+ await this.stopStream()
973
+ await this.startStream(sessionId)
974
+ })
975
+ .catch((error) => this.logger?.warn?.(`screencast restart failed: ${error.message}`))
976
+ }
977
+
978
+ /**
979
+ * Whether a native panel can serve this session's tool calls.
980
+ *
981
+ * @param sessionId - the calling session.
982
+ * @returns true when a mounted panel registered itself for that session.
983
+ */
984
+ guestAvailable(sessionId) {
985
+ // A page in a real browser window is not the panel's to answer for. Even a
986
+ // stale guest that re-mounts after the switch must not win routing back.
987
+ if (this.windowed.has(sessionId)) return false
988
+ const connection = this.guestGlue.get(sessionId)
989
+ if (connection === undefined) return false
990
+ return connection.closed !== true
991
+ }
992
+
993
+ /** The page now lives in a real browser window; the panel must stay out of routing. */
994
+ markWindowed(sessionId) {
995
+ this.windowed.add(sessionId)
996
+ }
997
+
998
+ /** The page is back on a panel layer; the guest may take routing again. */
999
+ clearWindowed(sessionId) {
1000
+ this.windowed.delete(sessionId)
1001
+ }
1002
+
1003
+ /**
1004
+ * Every session is back on a panel layer.
1005
+ *
1006
+ * A real window is one process for **all** conversations, so closing it (or a
1007
+ * fallback after somebody closed it) releases every session at once — clearing
1008
+ * one id per conversation would leave the rest marked `windowed` forever, with
1009
+ * no window left to answer for them.
1010
+ */
1011
+ clearWindowedAll() {
1012
+ const had = this.windowed.size > 0
1013
+ this.windowed.clear()
1014
+ return had
1015
+ }
1016
+
1017
+ /**
1018
+ * Run one operation inside a native panel's guest and wait for its answer.
1019
+ *
1020
+ * This is a plain request/response over the panel's own socket: the panel owns the
1021
+ * page, so every question about that page has to be asked there. A timeout is not
1022
+ * optional — the panel can be closed, crashed or stuck on a modal dialog, and a
1023
+ * tool call that hangs forever is worse than one that reports a reason.
1024
+ *
1025
+ * @param sessionId - the calling session.
1026
+ * @param method - operation name the panel understands.
1027
+ * @param params - method arguments; must be JSON-serializable.
1028
+ * @param options - `timeoutMs` budget.
1029
+ * @returns the panel's result.
1030
+ */
1031
+ async callGuest(sessionId, method, params = {}, { timeoutMs = 30_000 } = {}) {
1032
+ const connection = this.guestGlue.get(sessionId)
1033
+ if (connection === undefined || connection.closed === true) {
1034
+ throw new Error('guest-unavailable: no native browser panel is mounted for this session')
1035
+ }
1036
+ const id = (this.guestSeq += 1)
1037
+ // Hold the residency open for the whole round trip. A call in flight is the
1038
+ // clearest possible "in use", and reclaiming the page mid-call would make the
1039
+ // answer describe a browser that no longer exists.
1040
+ this.residency.enter(sessionId)
1041
+ try {
1042
+ return await new Promise((resolve, reject) => {
1043
+ const timer = setTimeout(() => {
1044
+ this.guestPending.delete(id)
1045
+ reject(new Error(`guest timeout: ${method} did not answer in ${timeoutMs} ms (is the panel busy with a dialog?)`))
1046
+ }, timeoutMs)
1047
+ this.guestPending.set(id, { resolve, reject, timer, connection })
1048
+ try {
1049
+ connection.sendJson({ type: 'guest-call', id, method, params })
1050
+ } catch (error) {
1051
+ this.guestPending.delete(id)
1052
+ clearTimeout(timer)
1053
+ reject(error instanceof Error ? error : new Error(String(error)))
1054
+ }
1055
+ })
1056
+ } finally {
1057
+ this.residency.leave(sessionId)
1058
+ }
1059
+ }
1060
+
1061
+ /** Fail every outstanding call for one connection (it went away). */
1062
+ dropGuest(connection) {
1063
+ for (const [sessionId, held] of this.guestGlue) {
1064
+ if (held === connection) this.guestGlue.delete(sessionId)
1065
+ }
1066
+ for (const [id, pending] of this.guestPending) {
1067
+ // The id space is global and several sessions can have a panel mounted at
1068
+ // once (`keepMounted`), so a disconnect must only fail *its own* calls.
1069
+ // Clearing the whole map failed a healthy session's in-flight call with
1070
+ // `guest-disconnected` whenever a different panel went away (2026-11-30).
1071
+ if (pending.connection !== connection) continue
1072
+ clearTimeout(pending.timer)
1073
+ pending.reject(new Error(`guest-disconnected`))
1074
+ this.guestPending.delete(id)
1075
+ }
1076
+ }
1077
+
1078
+ /** Push per-session state (and the overview) to the panels that care. */
1079
+ async pushState({ force = false } = {}) {
1080
+ const sessions = new Set()
1081
+ for (const connection of this.connections) sessions.add(connection.sessionId)
1082
+ for (const sessionId of sessions) {
1083
+ const status = await this.manager.status(sessionId).catch(() => undefined)
1084
+ if (status === undefined) continue
1085
+ const measured = this.takeWindow(sessionId)
1086
+ const next = {
1087
+ type: 'state',
1088
+ sessionId,
1089
+ running: status.running,
1090
+ mode: status.mode,
1091
+ open: status.session?.open === true,
1092
+ url: status.session?.url ?? null,
1093
+ title: status.session?.title ?? null,
1094
+ // Only a change here means "the AI navigated". A panel showing a native
1095
+ // guest loads the host's URL on this signal and ignores it otherwise, so
1096
+ // the human's own navigation is never undone.
1097
+ navSeq: this.manager.navSeq ?? 0,
1098
+ viewport: status.session?.viewport ?? null,
1099
+ stream: this.watched === sessionId ? 'screencast' : this.pollers.has(sessionId) ? 'poll' : 'idle',
1100
+ fps: measured?.fps ?? null,
1101
+ human: this.human.snapshot(sessionId) ?? null,
1102
+ // The panel's tick box reads this, and so does the "who holds a real
1103
+ // browser" list: pinning is per conversation, not per host.
1104
+ pinned: this.residency.isPinned(sessionId),
1105
+ // True while the page lives in a real browser window: the panel must not
1106
+ // mount a guest then, or routing flips back to the panel (see `windowed`).
1107
+ windowed: this.windowed.has(sessionId),
1108
+ }
1109
+ const previous = this.lastStates.get(sessionId)
1110
+ const changed =
1111
+ force ||
1112
+ previous === undefined ||
1113
+ previous.url !== next.url ||
1114
+ previous.title !== next.title ||
1115
+ previous.open !== next.open ||
1116
+ previous.running !== next.running ||
1117
+ JSON.stringify(previous.human) !== JSON.stringify(next.human) ||
1118
+ previous.pinned !== next.pinned ||
1119
+ previous.windowed !== next.windowed ||
1120
+ previous.stream !== next.stream ||
1121
+ previous.fps !== next.fps
1122
+ this.lastStates.set(sessionId, next)
1123
+ // Only a changed state is worth a line. A heartbeat used to be written on
1124
+ // every 2.5 s push, idle or not — that is what pushed this file into the
1125
+ // megabytes; the numbers that matter travel with the change itself.
1126
+ if (!changed) continue
1127
+ if (measured !== undefined) {
1128
+ const panels = this.connectionsFor(sessionId)
1129
+ const buffered = panels.map((connection) => connection.bufferedAmount).join('/') || '-'
1130
+ // Duck-typed so the hub never has to import the sink: `frames` is the
1131
+ // number of parts actually written to an HTTP viewer. A still `mjpeg=0`
1132
+ // alongside growing CDP frames means the shell buffered the forwarded
1133
+ // stream instead of passing it through.
1134
+ const viewers = panels.filter((connection) => typeof connection.frames === 'number')
1135
+ const written = viewers.length === 0 ? '' : ` mjpeg=${viewers.map((viewer) => `${viewer.frames}/${Math.round(viewer.bytes / 1024)}k`).join('/')}`
1136
+ streamLog(
1137
+ `state sid=${sessionId.slice(-6)} stream=${next.stream} fps=${measured.fps} frames=${measured.frames} ` +
1138
+ `kb=${Math.round(measured.bytes / 1024)} limit=${this.maxWidth}x${this.maxHeight} q=${this.quality} ` +
1139
+ `dropped=${this.framesDropped} gated=${this.framesGated} buffered=${buffered} panels=${panels.length}${written}`,
1140
+ )
1141
+ }
1142
+ this.broadcast(next, sessionId)
1143
+ }
1144
+ const overview = {
1145
+ type: 'sessions',
1146
+ running: this.manager.cdp !== undefined,
1147
+ sessions: this.manager.listSessions(),
1148
+ pending: this.human.snapshotAll(),
1149
+ watched: this.watched ?? null,
1150
+ }
1151
+ const signature = JSON.stringify(overview)
1152
+ if (force || signature !== this.lastOverview) {
1153
+ this.lastOverview = signature
1154
+ this.broadcast(overview)
1155
+ }
1156
+ }
1157
+
1158
+ /**
1159
+ * Close real browsers nobody is using.
1160
+ *
1161
+ * This is memory management, not routing. It runs on a slow timer, only touches
1162
+ * sessions the policy already calls idle, and **never** substitutes the headless
1163
+ * tab for a page someone can see: the panel is asked to unmount its guest, and
1164
+ * tool calls stop being routed only once the panel confirms it is gone. A panel
1165
+ * that does not answer keeps its guest — an unused browser is a much smaller
1166
+ * problem than an agent acting on a page the human is not looking at.
1167
+ *
1168
+ * @param options - clock injection for tests.
1169
+ * @returns the sessions that were asked to let go.
1170
+ */
1171
+ async reapOnce({ now = Date.now() } = {}) {
1172
+ const live = [...this.guestGlue.keys()]
1173
+ if (live.length === 0) return []
1174
+ const doomed = this.residency.reap({
1175
+ live,
1176
+ hasPendingHuman: (sessionId) => this.human.has(sessionId) === true,
1177
+ isWatching: (sessionId) => {
1178
+ for (const connection of this.connections) {
1179
+ if (connection.sessionId === sessionId && connection.watching === true) return true
1180
+ }
1181
+ return false
1182
+ },
1183
+ now,
1184
+ })
1185
+ if (doomed.length === 0) return []
1186
+ for (const sessionId of doomed) {
1187
+ // Re-check at the last moment: a call or a hand-over may have started between
1188
+ // the policy snapshot and this line.
1189
+ if (this.residency.busy(sessionId) === true) continue
1190
+ if (this.human.has(sessionId) === true) continue
1191
+ const idled = Math.round((now - (this.residency.lastUsed.get(sessionId) ?? now)) / 60_000)
1192
+ streamLog(`reclaim ask sid=${sessionId.slice(-6)} idle=${idled}m`)
1193
+ this.reclaiming.add(sessionId)
1194
+ this.broadcast({ type: 'reclaim', sessionId }, sessionId)
1195
+ // The panel unmounts the guest and answers `guest-gone`; waiting for that
1196
+ // keeps routing and pixels describing the same browser. The timer is the
1197
+ // escape hatch for a panel that never answers (an older build, or one whose
1198
+ // socket died): after it, routing falls back rather than hanging forever.
1199
+ clearTimeout(this.reclaimWatch.get(sessionId))
1200
+ const timer = setTimeout(() => {
1201
+ this.reclaimWatch.delete(sessionId)
1202
+ if (this.guestGlue.has(sessionId) !== true) return
1203
+ streamLog(`reclaim forced sid=${sessionId.slice(-6)} (panel did not confirm)`)
1204
+ this.guestGlue.delete(sessionId)
1205
+ this.lostPanel.set(sessionId, { at: Date.now(), reason: 'reclaimed' })
1206
+ this.reclaiming.delete(sessionId)
1207
+ void this.releaseReclaimed(sessionId)
1208
+ }, 5_000)
1209
+ timer.unref?.()
1210
+ this.reclaimWatch.set(sessionId, timer)
1211
+ }
1212
+ await this.pushState({ force: true })
1213
+ return doomed
1214
+ }
1215
+
1216
+ /**
1217
+ * Finish a reclaim by closing the session, not just unmounting its guest.
1218
+ *
1219
+ * Unmounting alone is undone by the panel: `open` is still true, so the native
1220
+ * surface mounts a fresh webview within seconds. Measured 2026-11-28 with a cap
1221
+ * of one — two sessions, `guest gone` then `guest ready` twelve seconds later,
1222
+ * once a minute, forever: the page reloaded under the human and the cap freed
1223
+ * nothing. Closing the session is what makes "let it go" stick, because the next
1224
+ * state push says `open: false` and the panel stops remounting; the following
1225
+ * tool call re-creates the browser on demand, which is what the policy promised.
1226
+ *
1227
+ * @param sessionId - the session whose real browser was reclaimed.
1228
+ */
1229
+ async releaseReclaimed(sessionId) {
1230
+ try {
1231
+ await this.manager.closeSession(sessionId, { reason: 'reclaimed' })
1232
+ } catch (error) {
1233
+ this.logger?.debug?.(`reclaim close failed: ${error?.message ?? error}`)
1234
+ }
1235
+ await this.pushState({ force: true }).catch(() => {})
1236
+ }
1237
+
1238
+ /**
1239
+ * Wait for this session's panel to announce a guest.
1240
+ *
1241
+ * A hand-over is only honest if the human's screen is showing the page the agent
1242
+ * is stuck on. The panel is opened by a state push and mounts asynchronously, so
1243
+ * the caller waits a moment instead of assuming the tab appeared the instant it
1244
+ * was asked for. Bounded on purpose: a deployment with no panel must get its
1245
+ * answer (and its own honest failure), not a hang.
1246
+ *
1247
+ * @param sessionId - the session whose panel should appear.
1248
+ * @param timeoutMs - budget.
1249
+ * @returns whether a guest answered in time.
1250
+ */
1251
+ async waitForGuest(sessionId, timeoutMs = 4_000) {
1252
+ if (this.guestAvailable(sessionId) === true) return true
1253
+ const deadline = Date.now() + Math.max(0, timeoutMs)
1254
+ while (Date.now() < deadline) {
1255
+ await sleep(120)
1256
+ if (this.guestAvailable(sessionId) === true) return true
1257
+ }
1258
+ return this.guestAvailable(sessionId) === true
1259
+ }
1260
+
1261
+ /**
1262
+ * Take (and clear) the "your panel went away" notice for one session.
1263
+ *
1264
+ * Clearing on read keeps it a one-shot: the agent is told once that it is no
1265
+ * longer driving the human's browser, and afterwards a fallback to the headless
1266
+ * tab is just the normal state it chose to continue in.
1267
+ *
1268
+ * @param sessionId - the calling session.
1269
+ * @returns `{ at, reason }` when the panel left and has not returned.
1270
+ */
1271
+ /**
1272
+ * Which surface a session's panel last reported.
1273
+ *
1274
+ * `float` when the human popped the tab out into a floating panel, `sidebar`
1275
+ * when it sits docked. `undefined` means no panel is connected at all — the
1276
+ * caller decides between the visible window and the invisible tab from there.
1277
+ */
1278
+ surfaceOf(sessionId) {
1279
+ // Newest report wins. A session can have more than one connection (two tabs,
1280
+ // or a panel that reconnected without the old one closing cleanly), and taking
1281
+ // the *first* match meant a stale `float` beat the live `sidebar` forever — the
1282
+ // tools then described a docked page as floating while the guest measured
1283
+ // 667x921 (measured 2026-11-27).
1284
+ let best
1285
+ for (const connection of this.connections) {
1286
+ if (connection.sessionId !== sessionId) continue
1287
+ if (connection.surface !== 'float' && connection.surface !== 'sidebar') continue
1288
+ if (best === undefined || (connection.surfaceAt ?? 0) >= (best.surfaceAt ?? 0)) best = connection
1289
+ }
1290
+ return best?.surface
1291
+ }
1292
+
1293
+ takeLostPanel(sessionId) {
1294
+ const lost = this.lostPanel.get(sessionId)
1295
+ if (lost === undefined) return undefined
1296
+ this.lostPanel.delete(sessionId)
1297
+ return lost
1298
+ }
1299
+
1300
+ /** Replay one panel message into that panel's own session. */
1301
+ async handleMessage(connection, message) {
1302
+ const sessionId = connection.sessionId
1303
+ if (message.type === 'guest-ready') {
1304
+ // This panel owns a real guest and is willing to act as the browser for its
1305
+ // session. From here on, tool calls go to it rather than to the headless tab.
1306
+ this.guestGlue.set(sessionId, connection)
1307
+ // A returning panel cancels any "your browser went away" notice: the person
1308
+ // came back before the agent ever acted on it.
1309
+ this.lostPanel.delete(sessionId)
1310
+ // A newly mounted guest counts as use: without this the sweeper would see a
1311
+ // session it has no record of and could reclaim it on the very first tick.
1312
+ this.residency.touch(sessionId)
1313
+ streamLog(`guest ready sid=${sessionId.slice(-6)} pinned=${this.residency.isPinned(sessionId)}`)
1314
+ return
1315
+ }
1316
+ if (message.type === 'guest-gone') {
1317
+ // The panel unmounted its guest (a reclaim, or the human closing it). Tool
1318
+ // calls for this session must stop being routed to a page that is gone.
1319
+ clearTimeout(this.reclaimWatch.get(sessionId))
1320
+ this.reclaimWatch.delete(sessionId)
1321
+ if (this.guestGlue.get(sessionId) === connection) this.guestGlue.delete(sessionId)
1322
+ const reclaimed = this.reclaiming.has(sessionId)
1323
+ this.lostPanel.set(sessionId, {
1324
+ at: Date.now(),
1325
+ reason: reclaimed ? 'reclaimed' : 'closed',
1326
+ })
1327
+ this.reclaiming.delete(sessionId)
1328
+ streamLog(`guest gone sid=${sessionId.slice(-6)}`)
1329
+ if (reclaimed) await this.releaseReclaimed(sessionId)
1330
+ return
1331
+ }
1332
+ if (message.type === 'residency') {
1333
+ // The panel's tick box. Pinning is the human's promise that this conversation
1334
+ // keeps its real browser no matter how long it sits idle.
1335
+ const pinned = this.residency.setPinned(sessionId, message.pinned === true)
1336
+ streamLog(`pin ${pinned ? 'on' : 'off'} sid=${sessionId.slice(-6)}`)
1337
+ await this.pushState({ force: true })
1338
+ return pinned
1339
+ }
1340
+ if (message.type === 'guest-result') {
1341
+ const pending = this.guestPending.get(message.id)
1342
+ if (pending === undefined) return
1343
+ this.guestPending.delete(message.id)
1344
+ clearTimeout(pending.timer)
1345
+ if (message.ok === true) pending.resolve(message.result)
1346
+ else pending.reject(new Error(String(message.error ?? 'guest call failed')))
1347
+ return
1348
+ }
1349
+ if (message.type === 'native') {
1350
+ // This panel shows a real guest, so it is not a viewer: it must not hold a
1351
+ // screencast, and it must not keep a poller alive either.
1352
+ connection.native = true
1353
+ // Deliberately *not* touching `watching`. These are two different questions:
1354
+ // "am I a viewer of a pixel stream" (no) and "is somebody looking at this
1355
+ // browser right now" (the panel tells us separately with focus/blur).
1356
+ // Setting `watching = false` here is what made the residency guard a dead
1357
+ // letter: every native panel reported "nobody is watching" forever, so an
1358
+ // idle browser was reclaimed even while a person was staring at it.
1359
+ await this.sync()
1360
+ return
1361
+ }
1362
+ if (message.type === 'focus') {
1363
+ connection.watching = true
1364
+ connection.focusedAt = ++this.focusSeq
1365
+ await this.sync()
1366
+ return
1367
+ }
1368
+ if (message.type === 'blur') {
1369
+ connection.watching = false
1370
+ await this.sync()
1371
+ return
1372
+ }
1373
+ /**
1374
+ * Which surface this panel is drawn on.
1375
+ *
1376
+ * The Sidebar moves a tab between a docked pane and a floating panel without
1377
+ * telling anyone; the tab keeps its id and its body, so from the host's side
1378
+ * nothing changes except where the human sees it. The panel knows (it reads
1379
+ * `useTabInfo().panel.isFloating`) and says so, because the answer to "where
1380
+ * is the page right now" is part of how the model decides what to do next.
1381
+ */
1382
+ if (message.type === 'surface') {
1383
+ connection.surface = message.floating === true ? 'float' : 'sidebar'
1384
+ connection.surfaceAt = Date.now()
1385
+ await this.sync()
1386
+ return
1387
+ }
1388
+ if (message.type === 'human-done' || message.type === 'human-reply') {
1389
+ const extra = message.type === 'human-reply'
1390
+ ? { reply: typeof message.text === 'string' ? message.text : '' }
1391
+ : message.note !== undefined ? { note: message.note } : {}
1392
+ const settled = this.human.done(message.requestId, extra)
1393
+ if (settled === true) {
1394
+ streamLog(`human-done ok sid=${sessionId.slice(-6)} id=${message.requestId}`)
1395
+ return settled
1396
+ }
1397
+ {
1398
+ // A click that settles nothing used to vanish without a trace, and the symptom
1399
+ // the human saw was "I pressed 我已完成 and the agent kept waiting". Record it,
1400
+ // and re-push state so the panel stops showing a request the broker no longer
1401
+ // has (the usual cause: the panel's copy is older than the live request).
1402
+ streamLog(`human-done ignored sid=${sessionId.slice(-6)} id=${message.requestId} pending=${this.human.has(sessionId)}`)
1403
+ await this.pushState({ force: true })
1404
+ }
1405
+ return settled
1406
+ }
1407
+ if (message.type === 'viewport') {
1408
+ if (this.fitPanelAspect !== true) return
1409
+ // Rate limit. A feedback loop is possible here — restarting the stream
1410
+ // changes what the panel paints, which can nudge its measured aspect, which
1411
+ // asks for another restart — and the measured symptom of that loop was a
1412
+ // screencast that started and stopped every 2~3 ms, delivering no frames at
1413
+ // all. Half a second between shapes is imperceptible and breaks the loop.
1414
+ const now = Date.now()
1415
+ if (now - (this.lastViewportAt ?? 0) < 500) return
1416
+ this.lastViewportAt = now
1417
+ const applied = await this.manager.fitViewport(sessionId, message.aspect)
1418
+ if (applied === undefined) return
1419
+ // The frame ceiling tracks the viewport: it is the last thing that would
1420
+ // silently undo the change, by downscaling every frame back to 1440×900.
1421
+ //
1422
+ // It is also capped by the panel's own physical width. A 2160 px frame in a
1423
+ // 1700 px panel looks identical after the browser scales it down, but costs
1424
+ // 40% more bandwidth and decode time — and decode time is what limits the
1425
+ // panel's frame rate.
1426
+ const ceiling = Math.round(applied.width * this.renderScale)
1427
+ const requested = Number(message.pixelWidth)
1428
+ const capped =
1429
+ Number.isFinite(requested) && requested >= 320 ? Math.min(ceiling, Math.round(requested)) : ceiling
1430
+ // The frame ceiling follows the viewport that was **actually** applied, not
1431
+ // the aspect the panel asked for: the height clamp above can leave a shaped
1432
+ // viewport shorter than the panel's shape, and dividing by the requested
1433
+ // aspect would then stretch every frame to a ratio the page never had.
1434
+ const nextHeight = Math.round(capped * (applied.height / applied.width))
1435
+ const limitChanged = this.maxWidth !== capped || this.maxHeight !== nextHeight
1436
+ this.maxWidth = capped
1437
+ this.maxHeight = nextHeight
1438
+ // Nothing about the stream changed: restarting it would only cost frames.
1439
+ if (applied.changed !== true && limitChanged !== true) return
1440
+ await this.restartStream()
1441
+ await this.pushState({ force: true })
1442
+ return
1443
+ }
1444
+ if (message.type === 'view-nav') {
1445
+ // The human navigated inside the native guest. Follow them, or the AI's next
1446
+ // tool call would operate the page the human already left. The guest is the
1447
+ // one on screen, so it is the truth and the host catches up to it.
1448
+ const url = typeof message.url === 'string' ? message.url : ''
1449
+ if (url === '') return
1450
+ const record = this.manager.session(sessionId)
1451
+ if (record === undefined) return
1452
+ let current = ''
1453
+ try {
1454
+ current = typeof record.page?.url === 'function' ? record.page.url() : ''
1455
+ } catch {
1456
+ /* a page mid-teardown has no URL */
1457
+ }
1458
+ if (current === url) return
1459
+ // One follow at a time, and only the newest one matters. The human can click
1460
+ // three links faster than a page loads; queueing them would walk the host
1461
+ // through every intermediate page, and awaiting inside this message handler
1462
+ // would stall the socket — input, human replies and state pushes included.
1463
+ this.followTarget = url
1464
+ if (this.following === true) return
1465
+ this.following = true
1466
+ void (async () => {
1467
+ try {
1468
+ while (typeof this.followTarget === 'string' && this.followTarget !== '') {
1469
+ const target = this.followTarget
1470
+ this.followTarget = ''
1471
+ try {
1472
+ await this.manager.navigate(sessionId, target, { intent: 'follow' })
1473
+ } catch {
1474
+ /* the guest is already there; a failed follow-up needs no banner */
1475
+ }
1476
+ }
1477
+ } finally {
1478
+ this.following = false
1479
+ await this.pushState({ force: true }).catch(() => {})
1480
+ }
1481
+ })()
1482
+ return
1483
+ }
1484
+ if (message.type === 'probe') {
1485
+ // One-off diagnostics from the panel about the native surface. Written to
1486
+ // the stream log because the panel has no console the maintainer can read.
1487
+ streamLog(`client-probe sid=${sessionId.slice(-6)} ${JSON.stringify(message.data ?? {})}`)
1488
+ return
1489
+ }
1490
+ if (message.type === 'metrics') {
1491
+ // The panel's own numbers: how long a frame takes to decode and to paint.
1492
+ // Without these a low rate can only be guessed at.
1493
+ streamLog(
1494
+ `client sid=${sessionId.slice(-6)} frames=${message.frames} kb=${Math.round(Number(message.bytes ?? 0) / 1024)} ` +
1495
+ `decodeAvg=${message.decodeAvg}ms paintAvg=${message.paintAvg}ms dropped=${this.framesDropped}`,
1496
+ )
1497
+ return
1498
+ }
1499
+ if (message.type === 'play') {
1500
+ await this.seedFrame(connection)
1501
+ return
1502
+ }
1503
+ if (message.type === 'open') {
1504
+ await this.manager.ensureSession(sessionId, { url: typeof message.url === 'string' ? message.url : undefined })
1505
+ await this.sync()
1506
+ await this.pushState({ force: true })
1507
+ return
1508
+ }
1509
+ if (message.type === 'close') {
1510
+ this.human.cancel(sessionId, 'session closed by the human')
1511
+ await this.manager.closeSession(sessionId, { reason: 'closed from the panel' })
1512
+ await this.sync()
1513
+ await this.pushState({ force: true })
1514
+ return
1515
+ }
1516
+ if (message.type === 'nav') {
1517
+ const action = message.action
1518
+ if (action === 'back') await this.manager.goBack(sessionId)
1519
+ else if (action === 'forward') await this.manager.goForward(sessionId)
1520
+ else if (action === 'reload') await this.manager.reload(sessionId)
1521
+ await this.pushState({ force: true })
1522
+ return
1523
+ }
1524
+ if (message.type === 'download') {
1525
+ // The human clicked a download link in the panel. The host cancels the real
1526
+ // download for this session, so the page fetched the bytes and parked them;
1527
+ // writing them here is the only way the click can produce a file.
1528
+ try {
1529
+ const saved = await saveDownload({ name: message.name, base64: message.base64, dir: this.downloadDir })
1530
+ connection.sendJson({ type: 'download-saved', ...saved })
1531
+ } catch (error) {
1532
+ connection.sendJson({ type: 'download-failed', reason: String(error?.message ?? error) })
1533
+ }
1534
+ return
1535
+ }
1536
+ if (message.type !== 'input') return
1537
+ const record = this.manager.session(sessionId)
1538
+ if (record === undefined) return
1539
+ const page = record.page
1540
+ this.manager.touch()
1541
+ const input = message
1542
+ // Only inputs that are *expected* to change the picture reset the watchdog.
1543
+ // A bare `mouseMoved` over a static page repaints nothing, so counting it
1544
+ // would make a user who simply moves the mouse look like a stalled pipeline
1545
+ // and restart the stream every few seconds. The profile switch rides on the
1546
+ // same set of events for the same reason — hovering must not drop sharpness.
1547
+ // A move *with a button held* is a drag, and that does repaint.
1548
+ if (input.kind !== 'mouse' || input.event !== 'move' || Boolean(input.buttons)) {
1549
+ this.healthOf(sessionId).lastInputAt = Date.now()
1550
+ this.noteActivity()
1551
+ }
1552
+ const mask = modifierMask(input.modifiers)
1553
+ if (input.kind === 'mouse') {
1554
+ const event = input.event
1555
+ const type = event === 'move' ? 'mouseMoved' : event === 'down' ? 'mousePressed' : 'mouseReleased'
1556
+ await page.send('Input.dispatchMouseEvent', {
1557
+ type,
1558
+ x: Math.round(input.x),
1559
+ y: Math.round(input.y),
1560
+ button: input.button ?? 'left',
1561
+ buttons: type === 'mouseReleased' || type === 'mouseMoved' ? 0 : 1,
1562
+ clickCount: input.clickCount ?? (type === 'mouseMoved' ? 0 : 1),
1563
+ modifiers: mask,
1564
+ })
1565
+ return
1566
+ }
1567
+ if (input.kind === 'wheel') {
1568
+ await page.send('Input.dispatchMouseEvent', {
1569
+ type: 'mouseWheel',
1570
+ x: Math.round(input.x),
1571
+ y: Math.round(input.y),
1572
+ deltaX: input.deltaX ?? 0,
1573
+ deltaY: input.deltaY ?? 0,
1574
+ modifiers: mask,
1575
+ })
1576
+ return
1577
+ }
1578
+ if (input.kind === 'text') {
1579
+ if (typeof input.text === 'string' && input.text !== '') await page.send('Input.insertText', { text: input.text })
1580
+ return
1581
+ }
1582
+ if (input.kind === 'key') {
1583
+ const down = input.event !== 'up'
1584
+ const common = {
1585
+ key: input.key,
1586
+ code: input.code ?? undefined,
1587
+ windowsVirtualKeyCode: input.keyCode ?? undefined,
1588
+ nativeVirtualKeyCode: input.keyCode ?? undefined,
1589
+ modifiers: mask,
1590
+ }
1591
+ if (down) {
1592
+ const printable = typeof input.text === 'string' && input.text !== '' && mask === 0
1593
+ await page.send('Input.dispatchKeyEvent', {
1594
+ type: printable ? 'keyDown' : 'rawKeyDown',
1595
+ ...common,
1596
+ ...(printable ? { text: input.text, unmodifiedText: input.text } : {}),
1597
+ })
1598
+ } else {
1599
+ await page.send('Input.dispatchKeyEvent', { type: 'keyUp', ...common })
1600
+ }
1601
+ }
1602
+ }
1603
+
1604
+ /** Send one freshly captured frame to a single panel (fills a blank canvas). */
1605
+ async seedFrame(connection) {
1606
+ try {
1607
+ const record = this.manager.session(connection.sessionId)
1608
+ if (record === undefined) return
1609
+ const shot = await record.page.send('Page.captureScreenshot', { format: 'jpeg', quality: this.quality })
1610
+ connection.sendBinary(Buffer.from(shot.data, 'base64'))
1611
+ } catch (error) {
1612
+ this.logger?.debug?.(`seed frame failed: ${error.message}`)
1613
+ }
1614
+ }
1615
+
1616
+ /** Stop every stream and poller, then drop the panels (plugin dispose). */
1617
+ async close() {
1618
+ for (const sessionId of [...this.pollers.keys()]) this.stopPoller(sessionId)
1619
+ clearInterval(this.stateTimer)
1620
+ this.stateTimer = undefined
1621
+ clearTimeout(this.profileTimer)
1622
+ this.profileTimer = undefined
1623
+ await this.streamTask.catch(() => {})
1624
+ await this.stopStream()
1625
+ for (const connection of this.connections) connection.close(1001, 'plugin unloading')
1626
+ this.connections.clear()
1627
+ await sleep(0)
1628
+ }
1629
+ }