Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopBrowserHost.ts

547 lines20.8 KB

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