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

DesktopBrowserHost.ts

225 lines8.3 KB

1// @effect-diagnostics nodeBuiltinImport:off - Names download files on the shared disk.
2/**
3 * The desktop end of the desktop browser channel (see `DesktopBrowserEvent` in
4 * contracts). The primary backend gets two file descriptors at spawn: this
5 * service writes events for the desktop's tabs to one and reads commands from
6 * the other. Each attached tab is reachable only through its `CdpRelay`.
7 *
8 * A tab is attached once its `<webview>` registers with a key the web app
9 * gave it. The preview manager owns the tab's single debugger session and hands
10 * it here; the relay shares it.
11 */
12import {
13 DesktopBrowserCommand,
14 DesktopBrowserEvent,
15 type DesktopBrowserEvent as DesktopBrowserEventType,
16} from "@t3tools/contracts";
17import * as Context from "effect/Context";
18import * as NodePath from "node:path";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as PubSub from "effect/PubSub";
23import * as Schema from "effect/Schema";
24import * as Stream from "effect/Stream";
25​
26import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts";
27​
28const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent));
29const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand));
30const lineEncoder = new TextEncoder();
31​
32export interface DesktopBrowserTabKey {
33 readonly threadId: string;
34 readonly tabId: string;
36​
37/** A tab's debugger, as the preview manager lends it to the relay. */
38export interface DesktopBrowserTabDebugger {
39 readonly webContents: Electron.WebContents;
40 readonly debugger: Electron.Debugger;
42​
43const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`;
44​
45interface AttachedTab {
46 readonly key: DesktopBrowserTabKey;
47 readonly debuggee: DesktopBrowserTabDebugger;
48 relay: CdpRelayConnection | null;
49 /** Where the server wants this tab's downloads; null keeps Electron's own handling. */
50 downloadDirectory: string | null;
51 /** The guid CDP gave the download that is about to start. */
52 pendingDownloadGuid: string | null;
53 readonly onMessage: (
54 event: Electron.Event,
55 method: string,
56 params: unknown,
57 sessionId: string,
58 ) => void;
60​
61export class DesktopBrowserHost extends Context.Service<
62 DesktopBrowserHost,
63 {
64 /**
65 * Newline-delimited events for a backend's browser fd. Each run starts by
66 * announcing the tabs already attached, so a restarted backend hears them.
67 */
68 readonly events: Stream.Stream<Uint8Array>;
69 /** One line from the backend's browser control fd. */
70 readonly handleCommandLine: (line: string) => Effect.Effect<void>;
71 /** Offers a server tab's `<webview>` to the server. */
72 readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void;
73 /** Withdraws it: closed, swapped, crashed, or devtools needs the debugger. */
74 readonly detach: (key: DesktopBrowserTabKey) => void;
75 /** Points a server tab's download at the server; false for any other download. */
76 readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
77 /** The agent's cursor positions for attached tabs, keyed by their server tab. */
78 readonly pointers: Stream.Stream<{
79 readonly key: DesktopBrowserTabKey;
80 readonly phase: "move" | "click";
81 readonly x: number;
82 readonly y: number;
83 }>;
84 }
85>()("@t3tools/desktop/preview/DesktopBrowserHost") {}
86​
87export const make = Effect.gen(function* () {
88 const outbox = yield* PubSub.unbounded<DesktopBrowserEventType>();
89 const pointers = yield* PubSub.sliding<{
90 readonly key: DesktopBrowserTabKey;
91 readonly phase: "move" | "click";
92 readonly x: number;
93 readonly y: number;
94 }>(16);
95 const runFork = Effect.runForkWith(yield* Effect.context<never>());
96 const tabs = new Map<string, AttachedTab>();
97 const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
98​
99 const relayFor = (tab: AttachedTab) => {
100 if (tab.relay) return tab.relay;
101 const { webContents, debugger: debuggee } = tab.debuggee;
102 const relay: CdpRelayConnection = createCdpRelayConnection(
103 {
104 send: (method, params, sessionId) =>
105 sessionId === undefined
106 ? debuggee.sendCommand(method, params)
107 : debuggee.sendCommand(method, params, sessionId),
108 targetId: () =>
109 debuggee
110 .sendCommand("Target.getTargetInfo")
111 .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId),
112 url: () => webContents.getURL(),
113 title: () => webContents.getTitle(),
114 userAgent: () => webContents.getUserAgent(),
115 setDownloadDirectory: (directory) => {
116 tab.downloadDirectory = directory;
117 },
118 },
119 // A released relay's late replies belong to a connection that is gone.
120 (message) => {
121 if (tab.relay === relay && tabs.get(keyOf(tab.key)) === tab) {
122 emit({ type: "cdp", ...tab.key, message });
123 }
124 },
125 );
126 tab.relay = relay;
127 return relay;
128 };
129​
130 /**
131 * Saves a download from a server tab where the server's Playwright expects
132 * it. Without a path Electron would open its Save dialog over the app for a
133 * file the agent asked for. CDP names the download just before this runs.
134 */
135 const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => {
136 const tab = [...tabs.values()].find(
137 (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory,
138 );
139 if (!tab?.downloadDirectory || !tab.pendingDownloadGuid) return false;
140 item.setSavePath(NodePath.join(tab.downloadDirectory, tab.pendingDownloadGuid));
141 tab.pendingDownloadGuid = null;
142 return true;
143 };
144​
145 const detach = (key: DesktopBrowserTabKey) => {
146 const id = keyOf(key);
147 const tab = tabs.get(id);
148 if (!tab) return;
149 tabs.delete(id);
150 tab.debuggee.debugger.off("message", tab.onMessage);
151 emit({ type: "detached", ...key });
152 };
153​
154 const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
155 const id = keyOf(key);
156 if (tabs.get(id)?.debuggee.webContents === debuggee.webContents) return;
157 detach(key);
158 const tab: AttachedTab = {
159 key,
160 debuggee,
161 relay: null,
162 downloadDirectory: null,
163 pendingDownloadGuid: null,
164 onMessage: (_event, method, params, sessionId) => {
165 if (method === "Browser.downloadWillBegin") {
166 const guid = (params as { guid?: unknown } | undefined)?.guid;
167 tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
168 }
169 tab.relay?.event(method, params, sessionId);
170 },
171 };
172 tabs.set(id, tab);
173 debuggee.debugger.on("message", tab.onMessage);
174 emit({ type: "attached", ...key });
175 };
176​
177 const handleCommandLine = (line: string) =>
178 Effect.sync(() => {
179 const command = decodeCommand(line);
180 if (Option.isNone(command)) return;
181 const tab = tabs.get(keyOf(command.value));
182 if (!tab) return;
183 if (command.value.type === "pointer") {
184 const { threadId, tabId, phase, x, y } = command.value;
185 runFork(PubSub.publish(pointers, { key: { threadId, tabId }, phase, x, y }));
186 return;
187 }
188 if (command.value.type === "release") {
189 // A new server connection starts with a fresh relay and fresh sessions.
190 tab.relay = null;
191 return;
192 }
193 relayFor(tab).receive(command.value.message);
194 });
195​
196 // Read when a backend starts, not when the host is built.
197 const announceAll = Effect.suspend(() =>
198 Effect.forEach(
199 [...tabs.values()],
200 (tab) => {
201 tab.relay = null;
202 return PubSub.publish(outbox, { type: "attached", ...tab.key });
203 },
204 { discard: true },
205 ),
206 );
207​
208 return DesktopBrowserHost.of({
209 pointers: Stream.fromPubSub(pointers),
210 // Subscribes before announcing, so no attach falls between the two.
211 events: Stream.unwrap(
212 Effect.gen(function* () {
213 const subscription = yield* PubSub.subscribe(outbox);
214 yield* announceAll;
215 return Stream.fromSubscription(subscription);
216 }),
217 ).pipe(Stream.map((event) => lineEncoder.encode(`${encodeEvent(event)}\n`))),
218 handleCommandLine,
219 attach,
220 detach,
221 placeDownload,
222 });
223});
224​
225export const layer = Layer.effect(DesktopBrowserHost, make);