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

DesktopBrowserHost.ts

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