Open History to see the last commit
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";
25import { clipboard } from "electron";
26
27import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts";
28import { createDesktopBrowserKeyboard } from "./DesktopBrowserKeyboard.ts";
29
30const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent));
31const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand));
32const lineEncoder = new TextEncoder();
33/** CDP commands through which an agent clicks, types, or navigates the page. */
34const AGENT_INPUT_COMMAND =
35 /"method":"(?:Input\.|Page\.navigate"|Runtime\.(?:evaluate|callFunctionOn)")/;
36/** How long after an agent's input a download still counts as the agent's. */
37const AGENT_DOWNLOAD_WINDOW_MS = 5_000;
38
39export interface DesktopBrowserTabKey {
40 readonly threadId: string;
41 readonly tabId: string;
42}
43
44/** A tab's debugger, as the preview manager lends it to the relay. */
45export interface DesktopBrowserTabDebugger {
46 readonly webContents: Electron.WebContents;
47 readonly debugger: Electron.Debugger;
48}
49
50const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`;
51
52interface AttachedTab {
53 readonly key: DesktopBrowserTabKey;
54 readonly debuggee: DesktopBrowserTabDebugger;
55 readonly keyboard: ReturnType<typeof createDesktopBrowserKeyboard>;
56 relay: CdpRelayConnection | null;
57 /** Where the server wants this tab's downloads; null keeps Electron's own handling. */
58 downloadDirectory: string | null;
59 /** The guid CDP gave the download that is about to start. */
60 pendingDownloadGuid: string | null;
61 /** When the server last sent this page input, which only an agent does. */
62 agentInputAt: number;
63 readonly onMessage: (
64 event: Electron.Event,
65 method: string,
66 params: unknown,
67 sessionId: string,
68 ) => void;
69}
70
71export class DesktopBrowserHost extends Context.Service<
72 DesktopBrowserHost,
73 {
74 /**
75 * Newline-delimited events for a backend's browser fd. Each run starts by
76 * announcing the tabs already attached, so a restarted backend hears them.
77 */
78 readonly events: Stream.Stream<Uint8Array>;
79 /** One line from the backend's browser control fd. */
80 readonly handleCommandLine: (line: string) => Effect.Effect<void>;
81 /** Offers a server tab's `<webview>` to the server. */
82 readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void;
83 /** Withdraws it: closed, swapped, crashed, or devtools needs the debugger. */
84 readonly detach: (key: DesktopBrowserTabKey) => void;
85 /**
86 * Whether a server tab's download came from the person at this desktop:
87 * the server sent the page no input just before it started.
88 */
89 readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
90 /** Suppresses desktop shortcuts while a native agent key is being delivered. */
91 readonly isDispatchingKeyboard: (source: Electron.WebContents) => boolean;
92 /** Points a server tab's download at the server; false for any other download. */
93 readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
94 /** The agent's cursor positions for attached tabs, keyed by their server tab. */
95 readonly pointers: Stream.Stream<{
96 readonly key: DesktopBrowserTabKey;
97 readonly phase: "move" | "click";
98 readonly x: number;
99 readonly y: number;
100 }>;
101 }
102>()("@t3tools/desktop/preview/DesktopBrowserHost") {}
103
104export const make = Effect.gen(function* () {
105 const outbox = yield* PubSub.unbounded<DesktopBrowserEventType>();
106 const pointers = yield* PubSub.sliding<{
107 readonly key: DesktopBrowserTabKey;
108 readonly phase: "move" | "click";
109 readonly x: number;
110 readonly y: number;
111 }>(16);
112 const runFork = Effect.runForkWith(yield* Effect.context<never>());
113 const tabs = new Map<string, AttachedTab>();
114 const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
115
116 const relayFor = (tab: AttachedTab) => {
117 if (tab.relay) return tab.relay;
118 const { webContents, debugger: debuggee } = tab.debuggee;
119 const relay: CdpRelayConnection = createCdpRelayConnection(
120 {
121 send: (method, params, sessionId) =>
122 sessionId === undefined &&
123 (method === "Input.insertText" || method === "Input.dispatchKeyEvent")
124 ? tab.keyboard.send(method, params)
125 : sessionId === undefined
126 ? debuggee.sendCommand(method, params)
127 : debuggee.sendCommand(method, params, sessionId),
128 targetId: () =>
129 debuggee
130 .sendCommand("Target.getTargetInfo")
131 .then((result: { targetInfo: { targetId: string } }) => result.targetInfo.targetId),
132 url: () => webContents.getURL(),
133 title: () => webContents.getTitle(),
134 userAgent: () => webContents.getUserAgent(),
135 setDownloadDirectory: (directory) => {
136 tab.downloadDirectory = directory;
137 },
138 },
139 // A released relay's late replies belong to a connection that is gone.
140 (message) => {
141 if (tab.relay === relay && tabs.get(keyOf(tab.key)) === tab) {
142 emit({ type: "cdp", ...tab.key, message });
143 }
144 },
145 );
146 tab.relay = relay;
147 return relay;
148 };
149
150 /**
151 * Saves a download from a server tab where the server's Playwright expects
152 * it. Without a path Electron would open its Save dialog over the app for a
153 * file the agent asked for. CDP names the download just before this runs.
154 */
155 const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => {
156 const tab = [...tabs.values()].find(
157 (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory,
158 );
159 if (!tab?.downloadDirectory || !tab.pendingDownloadGuid) return false;
160 item.setSavePath(NodePath.join(tab.downloadDirectory, tab.pendingDownloadGuid));
161 tab.pendingDownloadGuid = null;
162 return true;
163 };
164
165 const detach = (key: DesktopBrowserTabKey) => {
166 const id = keyOf(key);
167 const tab = tabs.get(id);
168 if (!tab) return;
169 tab.keyboard.cancel();
170 tabs.delete(id);
171 tab.debuggee.debugger.off("message", tab.onMessage);
172 emit({ type: "detached", ...key });
173 };
174
175 const attach = (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => {
176 const id = keyOf(key);
177 if (tabs.get(id)?.debuggee.webContents === debuggee.webContents) return;
178 detach(key);
179 const tab: AttachedTab = {
180 key,
181 debuggee,
182 keyboard: createDesktopBrowserKeyboard(debuggee.webContents, debuggee.debugger, () =>
183 clipboard.read(),
184 ),
185 relay: null,
186 downloadDirectory: null,
187 pendingDownloadGuid: null,
188 agentInputAt: Number.NEGATIVE_INFINITY,
189 onMessage: (_event, method, params, sessionId) => {
190 if (method === "Browser.downloadWillBegin") {
191 const guid = (params as { guid?: unknown } | undefined)?.guid;
192 tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
193 }
194 tab.relay?.event(method, params, sessionId);
195 },
196 };
197 tabs.set(id, tab);
198 debuggee.debugger.on("message", tab.onMessage);
199 emit({ type: "attached", ...key });
200 };
201
202 const handleCommandLine = (line: string) =>
203 Effect.sync(() => {
204 const command = decodeCommand(line);
205 if (Option.isNone(command)) return;
206 const tab = tabs.get(keyOf(command.value));
207 if (!tab) return;
208 if (command.value.type === "pointer") {
209 const { threadId, tabId, phase, x, y } = command.value;
210 runFork(PubSub.publish(pointers, { key: { threadId, tabId }, phase, x, y }));
211 return;
212 }
213 if (command.value.type === "release") {
214 // A new server connection starts with a fresh relay and fresh sessions.
215 tab.keyboard.cancel();
216 tab.relay = null;
217 return;
218 }
219 if (AGENT_INPUT_COMMAND.test(command.value.message)) tab.agentInputAt = performance.now();
220 relayFor(tab).receive(command.value.message);
221 });
222
223 const humanStartedDownload = (source: Electron.WebContents) => {
224 const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source);
225 return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS;
226 };
227
228 // Read when a backend starts, not when the host is built.
229 const announceAll = Effect.suspend(() =>
230 Effect.forEach(
231 [...tabs.values()],
232 (tab) => {
233 tab.keyboard.cancel();
234 tab.relay = null;
235 return PubSub.publish(outbox, { type: "attached", ...tab.key });
236 },
237 { discard: true },
238 ),
239 );
240
241 return DesktopBrowserHost.of({
242 pointers: Stream.fromPubSub(pointers),
243 // Subscribes before announcing, so no attach falls between the two.
244 events: Stream.unwrap(
245 Effect.gen(function* () {
246 const subscription = yield* PubSub.subscribe(outbox);
247 yield* announceAll;
248 return Stream.fromSubscription(subscription);
249 }),
250 ).pipe(Stream.map((event) => lineEncoder.encode(`${encodeEvent(event)}\n`))),
251 handleCommandLine,
252 attach,
253 detach,
254 placeDownload,
255 humanStartedDownload,
256 isDispatchingKeyboard: (source) =>
257 [...tabs.values()].some(
258 (tab) => tab.debuggee.webContents === source && tab.keyboard.isDispatching(),
259 ),
260 });
261});
262
263export const layer = Layer.effect(DesktopBrowserHost, make);