Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Names download files on the shared disk.
2/** The manager owns the single debugger attachment; the relay shares it. */
3import {
4 DesktopBrowserCommand,
5 DesktopBrowserEvent,
6 type DesktopBrowserEvent as DesktopBrowserEventType,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as NodePath from "node:path";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as PubSub from "effect/PubSub";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16
17import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts";
18import { sendPageCommand } from "./GuestInput.ts";
19
20const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent));
21const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand));
22const lineEncoder = new TextEncoder();
23const AGENT_INPUT_COMMAND =
24 /"method":"(?:Input\.|Page\.navigate"|Runtime\.(?:evaluate|callFunctionOn)")/;
25/** The same commands as above, by method, for the relay's sends. */
26const AGENT_INPUT_METHOD = /^(?:Input\.|Page\.navigate$|Runtime\.(?:evaluate|callFunctionOn)$)/;
27const AGENT_DOWNLOAD_WINDOW_MS = 5_000;
28const FOCUS_IDLE = "5 seconds";
29
30export interface DesktopBrowserTabKey {
31 readonly threadId: string;
32 readonly tabId: string;
33}
34
35export interface DesktopBrowserTabDebugger {
36 readonly webContents: Electron.WebContents;
37 readonly debugger: Electron.Debugger;
38}
39
40const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`;
41
42interface AttachedTab {
43 readonly key: DesktopBrowserTabKey;
44 readonly debuggee: DesktopBrowserTabDebugger;
45 relay: CdpRelayConnection | null;
46 screenshotTurn: object | null;
47 /** Each holds focus and painting while `held` and whoever queued it still waits on it. */
48 readonly waitingScreenshots: Array<{
49 readonly start: () => void;
50 readonly live: () => boolean;
51 held: boolean;
52 }>;
53 downloadDirectory: string | null;
54 pendingDownloadGuid: string | null;
55 agentInputAt: number;
56 focusEmulated: boolean;
57 focusChange: Promise<void> | null;
58 focusUses: number;
59 /** Each pending command, by the extra session waiting on it; the main connection's have none. */
60 readonly focusPending: Map<
61 object,
62 { readonly owner: string | undefined; readonly paints: boolean }
63 >;
64 /** Whether the client keeps the guest painting, as published on `painting`. */
65 painting: boolean;
66 /**
67 * Driven by the agent since its thread's last turn ended or the guest last throttled. A
68 * turn's start can reach us after its first command, so this holds focus once it does.
69 */
70 agentUsed: boolean;
71 focusReleasing: boolean;
72 /** The sessions streaming the guest; one stopping leaves the others' screencasts running. */
73 readonly screencasts: Set<string | undefined>;
74 readonly onMessage: (
75 event: Electron.Event,
76 method: string,
77 params: unknown,
78 sessionId: string,
79 ) => void;
80 readonly onNewDocument: () => void;
81}
82
83export class DesktopBrowserHost extends Context.Service<
84 DesktopBrowserHost,
85 {
86 readonly events: Stream.Stream<Uint8Array>;
87 readonly handleCommandLine: (line: string) => Effect.Effect<void>;
88 readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void;
89 readonly detach: (key: DesktopBrowserTabKey) => void;
90 readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
91 readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
92 readonly pointers: Stream.Stream<{
93 readonly key: DesktopBrowserTabKey;
94 readonly phase: "move" | "click";
95 readonly x: number;
96 readonly y: number;
97 }>;
98 /** Whether a guest needs its frames painted while the panel hides it. */
99 readonly painting: Stream.Stream<{
100 readonly key: DesktopBrowserTabKey;
101 readonly active: boolean;
102 }>;
103 }
104>()("@t3tools/desktop/preview/DesktopBrowserHost") {}
105
106export const make = Effect.gen(function* () {
107 const outbox = yield* PubSub.unbounded<DesktopBrowserEventType>();
108 const pointers = yield* PubSub.sliding<{
109 readonly key: DesktopBrowserTabKey;
110 readonly phase: "move" | "click";
111 readonly x: number;
112 readonly y: number;
113 }>(16);
114 const painting = yield* PubSub.unbounded<{
115 readonly key: DesktopBrowserTabKey;
116 readonly active: boolean;
117 }>();
118 const runFork = Effect.runForkWith(yield* Effect.context<never>());
119 const tabs = new Map<string, AttachedTab>();
120 /** Threads whose agent turn runs, by the server's account. */
121 const agentTurns = new Set<string>();
122 const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
123
124 const nextScreenshot = (tab: AttachedTab) => {
125 tab.screenshotTurn = null;
126 tab.waitingScreenshots.shift()?.start();
127 releaseFocusWhenIdle(tab);
128 syncPainting(tab);
129 };
130
131 /**
132 * Chromium below 157 crashes the whole app when a guest's renderer exits with a
133 * screenshot copy in flight (crbug.com/567321049). Overlapping screenshots make that
134 * far likelier, and one the server gave up on stays pending in Chromium, so each guest
135 * gets one at a time. One whose relay or session has since gone is dropped unsent.
136 */
137 const takeScreenshot = (
138 tab: AttachedTab,
139 relay: CdpRelayConnection,
140 ownerLive: () => boolean,
141 /** Sends only while `current` holds; holds focus and painting only while `held`. */
142 capture: (current: () => boolean, held: boolean) => Promise<unknown>,
143 ) =>
144 new Promise<unknown>((resolve, reject) => {
145 const live = () => tab.relay === relay && ownerLive();
146 const waiting = {
147 start: () => {
148 if (!live()) {
149 reject(new Error("The preview connection that asked for this screenshot closed."));
150 nextScreenshot(tab);
151 return;
152 }
153 const turn = {};
154 tab.screenshotTurn = turn;
155 capture(() => tab.screenshotTurn === turn && live(), waiting.held)
156 .finally(() => {
157 if (tab.screenshotTurn === turn) nextScreenshot(tab);
158 })
159 .then(resolve, reject);
160 },
161 live,
162 held: true,
163 };
164 if (tab.screenshotTurn === null) waiting.start();
165 else {
166 // The one ahead may be abandoned mid-capture; it needs frames to finish and free its turn.
167 tab.waitingScreenshots.push(waiting);
168 setFocusEmulation(tab, true);
169 syncPainting(tab);
170 }
171 });
172
173 /**
174 * Chromium counts a focus-emulated guest as captured, so a guest the panel hides would
175 * never throttle. Without it, a hidden guest paints no frames and focus() fires no focus
176 * events, so the guest is emulated focused while the server drives it or streams it.
177 */
178 const setFocusEmulation = (tab: AttachedTab, enabled: boolean) => {
179 if (tab.focusEmulated === enabled) return;
180 tab.focusEmulated = enabled;
181 // A guest that refuses it, or a debugger already gone, behaves as unfocused.
182 const change: Promise<void> = tab.debuggee.debugger
183 .sendCommand("Emulation.setFocusEmulationEnabled", { enabled })
184 .then(
185 () => undefined,
186 () => undefined,
187 )
188 .finally(() => {
189 if (tab.focusChange === change) tab.focusChange = null;
190 });
191 tab.focusChange = change;
192 };
193
194 const waitingHolds = (tab: AttachedTab) =>
195 tab.waitingScreenshots.some((waiting) => waiting.held && waiting.live());
196
197 const releaseFocusWhenIdle = (tab: AttachedTab) => {
198 if (tab.focusReleasing) return;
199 tab.focusReleasing = true;
200 runFork(
201 Effect.gen(function* () {
202 let uses: number;
203 do {
204 uses = tab.focusUses;
205 yield* Effect.sleep(FOCUS_IDLE);
206 } while (uses !== tab.focusUses);
207 tab.focusReleasing = false;
208 // The last pending command to settle starts another idle wait.
209 if (tab.focusPending.size > 0 || tab.screencasts.size > 0 || waitingHolds(tab)) {
210 return;
211 }
212 // The agent pauses to think between steps; its tab stays focused until the turn ends.
213 if (tab.agentUsed && agentTurns.has(tab.key.threadId)) return;
214 tab.agentUsed = false;
215 if (tabs.get(keyOf(tab.key)) === tab) setFocusEmulation(tab, false);
216 }),
217 );
218 };
219
220 /**
221 * Electron composites no offscreen guest, so its screenshot or screencast waits for a frame
222 * that never comes. The client paints the guest behind the app while one is pending; the
223 * capture then finishes on its own, and the guest goes back offscreen once none is.
224 */
225 const syncPainting = (tab: AttachedTab) => {
226 const active =
227 tabs.get(keyOf(tab.key)) === tab &&
228 (tab.screencasts.size > 0 ||
229 waitingHolds(tab) ||
230 [...tab.focusPending.values()].some((hold) => hold.paints));
231 if (tab.painting === active) return;
232 tab.painting = active;
233 runFork(PubSub.publish(painting, { key: tab.key, active }));
234 };
235
236 /** A command may wait on the page's next frame, so the guest stays focused until it settles. */
237 const holdFocus = <A>(
238 tab: AttachedTab,
239 method: string,
240 owner: string | undefined,
241 work: () => Promise<A>,
242 ) => {
243 const pending = {};
244 tab.focusPending.set(pending, { owner, paints: method === "Page.captureScreenshot" });
245 tab.focusUses += 1;
246 setFocusEmulation(tab, true);
247 releaseFocusWhenIdle(tab);
248 syncPainting(tab);
249 return work().finally(() => {
250 if (!tab.focusPending.delete(pending)) return;
251 tab.focusUses += 1;
252 releaseFocusWhenIdle(tab);
253 syncPainting(tab);
254 });
255 };
256
257 /**
258 * Chromium can leave a command unanswered, so the screenshot guard's release points
259 * also end every hold: a released relay has no one waiting, and a new document answers
260 * nothing pending from the old one. A released relay's screencast has no viewer to stop it.
261 */
262 const dropFocusHolds = (tab: AttachedTab) => {
263 tab.focusPending.clear();
264 releaseFocusWhenIdle(tab);
265 syncPainting(tab);
266 };
267
268 const dropRelay = (tab: AttachedTab) => {
269 tab.relay = null;
270 tab.screencasts.clear();
271 tab.agentUsed = false;
272 dropFocusHolds(tab);
273 };
274
275 /** A detached session, such as a closed viewer, waits on nothing it sent. */
276 const dropSessionHolds = (tab: AttachedTab, owner: string) => {
277 tab.screencasts.delete(owner);
278 for (const [pending, hold] of tab.focusPending) {
279 if (hold.owner === owner) tab.focusPending.delete(pending);
280 }
281 releaseFocusWhenIdle(tab);
282 syncPainting(tab);
283 };
284
285 /**
286 * A command the server stopped waiting on, such as a timed-out screenshot or evaluation,
287 * may never settle; the turn's end ends every hold. The agent also sends on its own extra
288 * session, so this cannot spare other sessions; a viewer's screencast still holds.
289 */
290 const endAgentTurn = (threadId: string) => {
291 agentTurns.delete(threadId);
292 for (const tab of tabs.values()) {
293 if (tab.key.threadId !== threadId) continue;
294 tab.agentUsed = false;
295 // Still sent in turn, so the queue keeps moving, but no longer kept painting.
296 for (const waiting of tab.waitingScreenshots) waiting.held = false;
297 dropFocusHolds(tab);
298 }
299 };
300
301 const relayFor = (tab: AttachedTab) => {
302 if (tab.relay) return tab.relay;
303 const { webContents, debugger: debuggee } = tab.debuggee;
304 const send = (method: string, params: Record<string, unknown>, sessionId?: string) =>
305 sendPageCommand(webContents, debuggee, method, params, sessionId);
306 const detachedOwners = new Set<string>();
307 /** Viewers and recordings stream; the agent's own sessions never do. */
308 const streamingOwners = new Set<string>();
309 const relay: CdpRelayConnection = createCdpRelayConnection(
310 {
311 send: (method, params, sessionId, owner) => {
312 // A child session's screencast is not the page's, such as a late one on a detached session.
313 if (sessionId === undefined && method === "Page.startScreencast") {
314 tab.screencasts.add(owner);
315 if (owner !== undefined) streamingOwners.add(owner);
316 } else if (sessionId === undefined && method === "Page.stopScreencast") {
317 tab.screencasts.delete(owner);
318 }
319 // A person's input through a viewer, or Playwright's own housekeeping, is not the agent's.
320 if (
321 AGENT_INPUT_METHOD.test(method) &&
322 (owner === undefined || !streamingOwners.has(owner))
323 ) {
324 tab.agentUsed = true;
325 }
326 // Waits for focus emulation; insertText and other non-CDP input would not queue behind it.
327 const forward = (current?: () => boolean) => {
328 const change = tab.focusChange;
329 const run = () =>
330 tab.relay === relay && (current === undefined || current())
331 ? send(method, params, sessionId)
332 : Promise.reject(new Error("The page this screenshot was for has moved on."));
333 return change === null ? run() : change.then(run);
334 };
335 return method === "Page.captureScreenshot"
336 ? takeScreenshot(
337 tab,
338 relay,
339 () => owner === undefined || !detachedOwners.has(owner),
340 (current, held) =>
341 held ? holdFocus(tab, method, owner, () => forward(current)) : forward(current),
342 )
343 : method === "Page.startScreencast"
344 ? holdFocus(tab, method, owner, forward).catch((cause: unknown) => {
345 // A viewer can outlive a refused stream; nothing is streaming for it.
346 if (sessionId === undefined && tab.relay === relay) tab.screencasts.delete(owner);
347 releaseFocusWhenIdle(tab);
348 syncPainting(tab);
349 throw cause;
350 })
351 : holdFocus(tab, method, owner, forward);
352 },
353 sessionDetached: (owner) => {
354 detachedOwners.add(owner);
355 dropSessionHolds(tab, owner);
356 },
357 targetId: () =>
358 debuggee
359 .sendCommand("Target.getTargetInfo")
360 .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId),
361 url: () => webContents.getURL(),
362 title: () => webContents.getTitle(),
363 userAgent: () => webContents.getUserAgent(),
364 setDownloadDirectory: (directory) => {
365 tab.downloadDirectory = directory;
366 },
367 },
368 (message) => {
369 if (tab.relay === relay && tabs.get(keyOf(tab.key)) === tab) {
370 emit({ type: "cdp", ...tab.key, message });
371 }
372 },
373 // Announcing the tab again would reconnect Playwright, and the page could
374 // replay the same oversized event, so the tab stays detached.
375 () => {
376 if (tab.relay !== relay || tabs.get(keyOf(tab.key)) !== tab) return;
377 // Disabling auto-attach detaches child sessions and releases their debugger pauses.
378 void debuggee
379 .sendCommand("Target.setAutoAttach", {
380 autoAttach: false,
381 waitForDebuggerOnStart: false,
382 flatten: true,
383 })
384 .catch(() => {});
385 if (tab.screencasts.size > 0) {
386 void debuggee.sendCommand("Page.stopScreencast").catch(() => {});
387 }
388 setFocusEmulation(tab, false);
389 detach(tab.key);
390 },
391 );
392 tab.relay = relay;
393 return relay;
394 };
395
396 // CDP supplies the path before this runs; otherwise Electron opens a Save dialog.
397 const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => {
398 const tab = [...tabs.values()].find(
399 (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory,
400 );
401 if (!tab?.downloadDirectory || !tab.pendingDownloadGuid) return false;
402 item.setSavePath(NodePath.join(tab.downloadDirectory, tab.pendingDownloadGuid));
403 tab.pendingDownloadGuid = null;
404 return true;
405 };
406
407 const detach = (key: DesktopBrowserTabKey) => {
408 const id = keyOf(key);
409 const tab = tabs.get(id);
410 if (!tab) return;
411 tabs.delete(id);
412 tab.relay = null;
413 tab.debuggee.debugger.off("message", tab.onMessage);
414 tab.debuggee.webContents.off("did-navigate", tab.onNewDocument);
415 syncPainting(tab);
416 emit({ type: "detached", ...key });
417 };
418
419 const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
420 const id = keyOf(key);
421 if (tabs.get(id)?.debuggee.webContents === debuggee.webContents) return;
422 detach(key);
423 const tab: AttachedTab = {
424 key,
425 debuggee,
426 relay: null,
427 screenshotTurn: null,
428 waitingScreenshots: [],
429 downloadDirectory: null,
430 pendingDownloadGuid: null,
431 agentInputAt: Number.NEGATIVE_INFINITY,
432 focusEmulated: false,
433 focusChange: null,
434 focusUses: 0,
435 focusPending: new Map(),
436 painting: false,
437 agentUsed: false,
438 focusReleasing: false,
439 screencasts: new Set(),
440 onMessage: (_event, method, params, sessionId) => {
441 if (method === "Page.downloadWillBegin") {
442 const guid = (params as { guid?: unknown } | undefined)?.guid;
443 tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
444 }
445 tab.relay?.event(method, params, sessionId);
446 },
447 // A screenshot pending when the page loads a new document, a reload included, can
448 // stay unanswered. A crashed page lands here once it reloads, well after its renderer died.
449 onNewDocument: () => {
450 // Before the next screenshot starts, so its own hold survives.
451 dropFocusHolds(tab);
452 if (tab.screenshotTurn !== null) nextScreenshot(tab);
453 },
454 };
455 tabs.set(id, tab);
456 debuggee.debugger.on("message", tab.onMessage);
457 debuggee.webContents.on("did-navigate", tab.onNewDocument);
458 emit({ type: "attached", ...key });
459 };
460
461 const handleCommandLine = (line: string) =>
462 Effect.sync(() => {
463 const command = decodeCommand(line);
464 if (Option.isNone(command)) return;
465 if (command.value.type === "turn") {
466 if (command.value.active) agentTurns.add(command.value.threadId);
467 else endAgentTurn(command.value.threadId);
468 return;
469 }
470 const tab = tabs.get(keyOf(command.value));
471 if (!tab) return;
472 if (command.value.type === "pointer") {
473 const { threadId, tabId, phase, x, y } = command.value;
474 runFork(PubSub.publish(pointers, { key: { threadId, tabId }, phase, x, y }));
475 return;
476 }
477 if (command.value.type === "release") {
478 dropRelay(tab);
479 return;
480 }
481 if (AGENT_INPUT_COMMAND.test(command.value.message)) tab.agentInputAt = performance.now();
482 relayFor(tab).receive(command.value.message);
483 });
484
485 const humanStartedDownload = (source: Electron.WebContents) => {
486 const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
487 return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS;
488 };
489
490 const announceAll = Effect.suspend(() => {
491 // A new backend: the old one's turns ended without telling us.
492 agentTurns.clear();
493 return Effect.forEach(
494 [...tabs.values()],
495 (tab) => {
496 dropRelay(tab);
497 return PubSub.publish(outbox, { type: "attached", ...tab.key });
498 },
499 { discard: true },
500 );
501 });
502
503 return DesktopBrowserHost.of({
504 pointers: Stream.fromPubSub(pointers),
505 painting: Stream.fromPubSub(painting),
506 // Subscribes before announcing, so no attach falls between the two.
507 events: Stream.unwrap(
508 Effect.gen(function* () {
509 const subscription = yield* PubSub.subscribe(outbox);
510 yield* announceAll;
511 return Stream.fromSubscription(subscription);
512 }),
513 ).pipe(Stream.map((event) => lineEncoder.encode(`${encodeEvent(event)}\n`))),
514 handleCommandLine,
515 attach,
516 detach,
517 placeDownload,
518 humanStartedDownload,
519 });
520});
521
522export const layer = Layer.effect(DesktopBrowserHost, make);