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

DesktopBrowserHost.ts

618 lines23.9 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 streaming the guest; one stopping leaves the others' screencasts running. */
79 readonly screencasts: Set<string | undefined>;
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 /** A detached session, such as a closed viewer, waits on nothing it sent. */
293 const dropSessionHolds = (tab: AttachedTab, owner: string) => {
294 tab.screencasts.delete(owner);
295 for (const [pending, holder] of tab.focusPending) {
296 if (holder === owner) tab.focusPending.delete(pending);
297 }
298 releaseFocusWhenIdle(tab);
299 syncPainting(tab);
300 };
301​
302 /**
303 * A command the server stopped waiting on, such as a timed-out screenshot or evaluation,
304 * may never settle; the turn's end ends every focus hold. The agent also sends on its own extra
305 * session, so this cannot spare other sessions; a viewer's screencast still holds.
306 */
307 const endAgentTurn = (threadId: string) => {
308 agentTurns.delete(threadId);
309 for (const tab of tabs.values()) {
310 if (tab.key.threadId !== threadId) continue;
311 tab.agentUsed = false;
312 // Still sent in turn, so the queue keeps moving, but no longer kept focused.
313 for (const waiting of tab.waitingScreenshots) waiting.held = false;
314 dropFocusHolds(tab);
315 }
316 };
317​
318 const relayFor = (tab: AttachedTab) => {
319 if (tab.relay) return tab.relay;
320 const { webContents, debugger: debuggee, cookiesCleared } = tab.debuggee;
321 const send = async (method: string, params: Record<string, unknown>, sessionId?: string) => {
322 const result = await sendPageCommand(webContents, debuggee, method, params, sessionId);
323 if (method === "Network.clearBrowserCookies") await cookiesCleared?.();
324 return result;
325 };
326 const detachedOwners = new Set<string>();
327 /** Viewers and recordings stream; the agent's own sessions never do. */
328 const streamingOwners = new Set<string>();
329 const relay: CdpRelayConnection = createCdpRelayConnection(
330 {
331 send: (method, params, sessionId, owner) => {
332 // A child session's screencast is not the page's, such as a late one on a detached session.
333 if (sessionId === undefined && method === "Page.startScreencast") {
334 tab.screencasts.add(owner);
335 if (owner !== undefined) streamingOwners.add(owner);
336 syncPainting(tab);
337 } else if (sessionId === undefined && method === "Page.stopScreencast") {
338 tab.screencasts.delete(owner);
339 syncPainting(tab);
340 }
341 // A person's input through a viewer, or Playwright's own housekeeping, is not the agent's.
342 if (
343 AGENT_INPUT_METHOD.test(method) &&
344 (owner === undefined || !streamingOwners.has(owner))
345 ) {
346 tab.agentUsed = true;
347 }
348 // Waits for focus emulation; insertText and other non-CDP input would not queue behind it.
349 const forward = (current?: () => boolean) => {
350 const change = tab.focusChange;
351 const run = () =>
352 tab.relay !== relay || (current !== undefined && !current())
353 ? Promise.reject(new Error("The page this screenshot was for has moved on."))
354 : current === undefined
355 ? send(method, params, sessionId)
356 : paintUntilAnswered(tab, () => send(method, params, sessionId));
357 return change === null ? run() : change.then(run);
358 };
359 return method === "Page.captureScreenshot"
360 ? takeScreenshot(
361 tab,
362 relay,
363 () => owner === undefined || !detachedOwners.has(owner),
364 (current, held) =>
365 held ? holdFocus(tab, owner, () => forward(current)) : forward(current),
366 )
367 : method === "Page.startScreencast"
368 ? holdFocus(tab, owner, forward).catch((cause: unknown) => {
369 // A viewer can outlive a refused stream; nothing is streaming for it.
370 if (sessionId === undefined && tab.relay === relay) tab.screencasts.delete(owner);
371 releaseFocusWhenIdle(tab);
372 syncPainting(tab);
373 throw cause;
374 })
375 : holdFocus(tab, owner, forward);
376 },
377 sessionDetached: (owner) => {
378 detachedOwners.add(owner);
379 dropSessionHolds(tab, owner);
380 },
381 targetId: () =>
382 debuggee
383 .sendCommand("Target.getTargetInfo")
384 .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId),
385 url: () => webContents.getURL(),
386 title: () => webContents.getTitle(),
387 userAgent: () => webContents.getUserAgent(),
388 setDownloadDirectory: (directory) => {
389 tab.downloadDirectory = directory;
390 },
391 },
392 (message) => {
393 if (tab.relay === relay && tabs.get(keyOf(tab.key)) === tab) {
394 emit({ type: "cdp", ...tab.key, message });
395 }
396 },
397 // Announcing the tab again would reconnect Playwright, and the page could
398 // replay the same oversized event, so the tab stays detached.
399 () => {
400 if (tab.relay !== relay || tabs.get(keyOf(tab.key)) !== tab) return;
401 // Disabling auto-attach detaches child sessions and releases their debugger pauses.
402 void debuggee
403 .sendCommand("Target.setAutoAttach", {
404 autoAttach: false,
405 waitForDebuggerOnStart: false,
406 flatten: true,
407 })
408 .catch(() => {});
409 if (tab.screencasts.size > 0) {
410 void debuggee.sendCommand("Page.stopScreencast").catch(() => {});
411 }
412 setFocusEmulation(tab, false);
413 detach(tab.key);
414 },
415 );
416 tab.relay = relay;
417 return relay;
418 };
419​
420 // CDP supplies the path before this runs; otherwise Electron opens a Save dialog.
421 const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => {
422 const tab = [...tabs.values()].find(
423 (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory,
424 );
425 if (!tab?.downloadDirectory || !tab.pendingDownloadGuid) return false;
426 item.setSavePath(NodePath.join(tab.downloadDirectory, tab.pendingDownloadGuid));
427 tab.pendingDownloadGuid = null;
428 return true;
429 };
430​
431 const detach = (key: DesktopBrowserTabKey) => {
432 const id = keyOf(key);
433 const tab = tabs.get(id);
434 if (!tab) return;
435 tabs.delete(id);
436 const announced = tab.stopWaiting === null;
437 tab.stopWaiting?.();
438 tab.relay = null;
439 tab.debuggee.debugger.off("message", tab.onMessage);
440 tab.debuggee.webContents.off("did-navigate", tab.onNewDocument);
441 syncPainting(tab);
442 if (announced) emit({ type: "detached", ...key });
443 };
444​
445 const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
446 const id = keyOf(key);
447 if (tabs.get(id)?.debuggee.webContents === debuggee.webContents) return;
448 detach(key);
449 const tab: AttachedTab = {
450 key,
451 debuggee,
452 relay: null,
453 screenshotTurn: null,
454 waitingScreenshots: [],
455 downloadDirectory: null,
456 pendingDownloadGuid: null,
457 agentInputAt: Number.NEGATIVE_INFINITY,
458 focusEmulated: false,
459 focusChange: null,
460 focusUses: 0,
461 focusPending: new Map(),
462 capturing: new Set(),
463 painting: false,
464 agentUsed: false,
465 focusReleasing: false,
466 screencasts: new Set(),
467 onMessage: (_event, method, params, sessionId) => {
468 if (method === "Page.downloadWillBegin") {
469 const guid = (params as { guid?: unknown } | undefined)?.guid;
470 tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
471 }
472 tab.relay?.event(method, params, sessionId);
473 },
474 // A screenshot pending when the page loads a new document, a reload included, can
475 // stay unanswered. A crashed page lands here once it reloads, well after its renderer died.
476 onNewDocument: () => {
477 // Before the next screenshot starts, so its own holds survive.
478 tab.capturing.clear();
479 dropFocusHolds(tab);
480 if (tab.screenshotTurn !== null) nextScreenshot(tab);
481 },
482 stopWaiting: null,
483 };
484 tabs.set(id, tab);
485 debuggee.debugger.on("message", tab.onMessage);
486 debuggee.webContents.on("did-navigate", tab.onNewDocument);
487 const announce = () => {
488 emit({ type: "attached", ...key });
489 const shown = shownTabs.get(id);
490 if (shown !== undefined) emit({ type: "shown", ...key, shown });
491 };
492 if (!debuggee.webContents.isLoadingMainFrame()) {
493 announce();
494 return;
495 }
496 // Electron does not pause a guest for the debugger, so Playwright connecting during its first
497 // commit builds its utility world in the discarded document and every wait on it hangs.
498 const { webContents } = debuggee;
499 // ERR_ABORTED is a newer navigation replacing this one, whose commit is still to come.
500 const onFailLoad = (
501 _event: Electron.Event,
502 code: number,
503 _description: string,
504 _url: string,
505 isMainFrame: boolean,
506 ) => {
507 if (isMainFrame && code !== ERR_ABORTED) ready();
508 };
509 const ready = () => {
510 if (tab.stopWaiting === null) return;
511 // The manager's cleanup for a destroyed guest can still be queued behind another tab's attach.
512 if (webContents.isDestroyed()) return detach(key);
513 tab.stopWaiting();
514 announce();
515 };
516 const timeout = runFork(
517 Effect.sleep(FIRST_PAGE_TIMEOUT).pipe(Effect.andThen(Effect.sync(ready))),
518 );
519 tab.stopWaiting = () => {
520 tab.stopWaiting = null;
521 webContents.off("dom-ready", ready);
522 webContents.off("did-stop-loading", ready);
523 webContents.off("did-fail-load", onFailLoad);
524 runFork(Fiber.interrupt(timeout));
525 };
526 webContents.on("dom-ready", ready);
527 webContents.on("did-stop-loading", ready);
528 webContents.on("did-fail-load", onFailLoad);
529 };
530​
531 const setShown = (key: DesktopBrowserTabKey, shown: boolean | undefined) => {
532 const id = keyOf(key);
533 if (shown === undefined) {
534 shownTabs.delete(id);
535 return;
536 }
537 if (shownTabs.get(id) === shown) return;
538 shownTabs.set(id, shown);
539 if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown });
540 };
541​
542 const loadFailed: DesktopBrowserHost["Service"]["loadFailed"] = (key, failure) => {
543 if (tabs.has(keyOf(key))) emit({ type: "loadFailed", ...key, ...failure });
544 };
545​
546 const handleCommandLine = (line: string) =>
547 Effect.sync(() => {
548 const command = decodeCommand(line);
549 if (Option.isNone(command)) return;
550 if (command.value.type === "turn") {
551 if (command.value.active) agentTurns.add(command.value.threadId);
552 else endAgentTurn(command.value.threadId);
553 return;
554 }
555 const tab = tabs.get(keyOf(command.value));
556 if (!tab) return;
557 if (command.value.type === "pointer") {
558 const { threadId, tabId, phase, x, y } = command.value;
559 runFork(PubSub.publish(pointers, { key: { threadId, tabId }, phase, x, y }));
560 return;
561 }
562 if (command.value.type === "release") {
563 dropRelay(tab);
564 return;
565 }
566 if (AGENT_INPUT_COMMAND.test(command.value.message)) tab.agentInputAt = performance.now();
567 relayFor(tab).receive(command.value.message);
568 });
569​
570 const humanStartedDownload = (source: Electron.WebContents) => {
571 const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
572 return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS;
573 };
574​
575 const announceAll = Effect.suspend(() => {
576 // A new backend: the old one's turns ended without telling us.
577 agentTurns.clear();
578 return Effect.forEach(
579 [...tabs.values()],
580 (tab) => {
581 dropRelay(tab);
582 // Announced once its first page is up.
583 if (tab.stopWaiting !== null) return Effect.void;
584 const shown = shownTabs.get(keyOf(tab.key));
585 return PubSub.publish(outbox, { type: "attached", ...tab.key }).pipe(
586 Effect.andThen(
587 shown !== undefined
588 ? PubSub.publish(outbox, { type: "shown", ...tab.key, shown })
589 : Effect.void,
590 ),
591 );
592 },
593 { discard: true },
594 );
595 });
596​
597 return DesktopBrowserHost.of({
598 pointers: Stream.fromPubSub(pointers),
599 painting: Stream.fromPubSub(painting),
600 // Subscribes before announcing, so no attach falls between the two.
601 events: Stream.unwrap(
602 Effect.gen(function* () {
603 const subscription = yield* PubSub.subscribe(outbox);
604 yield* announceAll;
605 return Stream.fromSubscription(subscription);
606 }),
607 ).pipe(Stream.map((event) => lineEncoder.encode(`${encodeEvent(event)}\n`))),
608 handleCommandLine,
609 attach,
610 detach,
611 loadFailed,
612 setShown,
613 placeDownload,
614 humanStartedDownload,
615 });
616});
617​
618export const layer = Layer.effect(DesktopBrowserHost, make);