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

DesktopBrowserChannel.ts

225 lines8.9 KB

1// @effect-diagnostics nodeBuiltinImport:off - Bridges Playwright's WebSocket transport to the desktop's fds.
2/**
3 * The server end of the desktop browser channel (see `DesktopBrowserEvent`).
4 *
5 * Playwright connects over CDP only through a WebSocket URL, so each attached
6 * desktop tab gets a loopback endpoint with an unguessable path. Its frames
7 * cross the bootstrap file descriptors to the desktop's relay, which owns the
8 * tab's `webContents.debugger`. The endpoint only bridges to that one tab.
9 */
10import * as NodeStream from "@effect/platform-node/NodeStream";
11import * as NodeSocketServer from "@effect/platform-node/NodeSocketServer";
12import {
13 DesktopBrowserCommand,
14 DesktopBrowserEvent,
15 type DesktopBrowserCommand as DesktopBrowserCommandType,
16} from "@t3tools/contracts";
17import * as Context from "effect/Context";
18import * as Duration from "effect/Duration";
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 Queue from "effect/Queue";
24import * as Schema from "effect/Schema";
25import * as Scope from "effect/Scope";
26import * as Semaphore from "effect/Semaphore";
27import * as Stream from "effect/Stream";
28import * as Ndjson from "effect/encoding/Ndjson";
29import * as NodeCrypto from "node:crypto";
30import * as NodeFS from "node:fs";
31​
32import * as ServerConfig from "../config.ts";
33import { writeAllToFileDescriptor } from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
34​
35const decodeEvent = Schema.decodeUnknownEffect(DesktopBrowserEvent);
36const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(DesktopBrowserCommand));
37​
38export interface DesktopTabKey {
39 readonly threadId: string;
40 readonly tabId: string;
42​
43const keyOf = ({ threadId, tabId }: DesktopTabKey) => `${threadId}\u0000${tabId}`;
44​
45export class DesktopBrowserChannel extends Context.Service<
46 DesktopBrowserChannel,
47 {
48 /** False when this server was not started by a desktop app. */
49 readonly available: boolean;
50 /**
51 * Waits for a tab to be attached. Subscribes before it checks, so an
52 * attach landing in between is never missed. False after `timeout`.
53 */
54 readonly awaitAttached: (key: DesktopTabKey, timeout: Duration.Input) => Effect.Effect<boolean>;
55 /** Desktop tabs as they detach. */
56 readonly detached: Stream.Stream<DesktopTabKey>;
57 readonly isAttached: (key: DesktopTabKey) => Effect.Effect<boolean>;
58 /**
59 * A one-connection CDP endpoint for an attached tab. Closing the scope
60 * releases the tab on the desktop and stops the endpoint.
61 */
62 readonly endpoint: (key: DesktopTabKey) => Effect.Effect<string, never, Scope.Scope>;
63 /** Draws the agent's cursor over a tab the desktop renders. */
64 readonly pointer: (
65 key: DesktopTabKey,
66 pointer: { readonly phase: "move" | "click"; readonly x: number; readonly y: number },
67 ) => Effect.Effect<void>;
68 }
69>()("t3/preview/DesktopBrowserChannel") {}
70​
71const make = Effect.gen(function* () {
72 const config = yield* ServerConfig.ServerConfig;
73 const inputFd = config.desktopBrowserFd;
74 const controlFd = config.desktopBrowserControlFd;
75 const changes = yield* PubSub.unbounded<{ key: DesktopTabKey; attached: boolean }>();
76 const attachedTabs = new Set<string>();
77 /** CDP frames from the desktop, per tab, for the endpoint connected to it. */
78 const inbound = new Map<string, Queue.Queue<string>>();
79 const writeLock = yield* Semaphore.make(1);
80​
81 if (inputFd === undefined || controlFd === undefined) {
82 return DesktopBrowserChannel.of({
83 available: false,
84 awaitAttached: () => Effect.succeed(false),
85 detached: Stream.empty,
86 isAttached: () => Effect.succeed(false),
87 endpoint: () => Effect.die("No desktop app is attached to this server."),
88 pointer: () => Effect.void,
89 });
90 }
91​
92 const command = (message: DesktopBrowserCommandType) =>
93 writeLock.withPermits(1)(
94 encodeCommand(message).pipe(
95 Effect.flatMap((line) => writeAllToFileDescriptor(controlFd, Buffer.from(`${line}\n`))),
96 Effect.catchCause((cause) =>
97 Effect.logWarning("desktop browser command failed", { cause }),
98 ),
99 ),
100 );
101​
102 const readable = yield* Effect.acquireRelease(
103 Effect.sync(() => NodeFS.createReadStream("", { fd: inputFd, autoClose: true })),
104 (stream) => Effect.sync(() => stream.destroy()),
105 );
106 yield* NodeStream.fromReadable<Uint8Array, Error>({
107 evaluate: () => readable,
108 closeOnDone: true,
109 onError: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
110 }).pipe(
111 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
112 Stream.mapEffect((value) => decodeEvent(value).pipe(Effect.option)),
113 Stream.runForEach((decoded) => {
114 if (Option.isNone(decoded)) return Effect.void;
115 const event = decoded.value;
116 const key = { threadId: event.threadId, tabId: event.tabId };
117 const id = keyOf(key);
118 switch (event.type) {
119 case "cdp": {
120 const queue = inbound.get(id);
121 return queue ? Queue.offer(queue, event.message).pipe(Effect.asVoid) : Effect.void;
122 }
123 case "attached":
124 attachedTabs.add(id);
125 return PubSub.publish(changes, { key, attached: true });
126 case "detached": {
127 attachedTabs.delete(id);
128 const queue = inbound.get(id);
129 return (queue ? Queue.shutdown(queue) : Effect.void).pipe(
130 Effect.andThen(PubSub.publish(changes, { key, attached: false })),
131 );
132 }
133 }
134 }),
135 Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })),
136 Effect.forkScoped,
137 );
138​
139 const endpoint = (key: DesktopTabKey) =>
140 Effect.gen(function* () {
141 const id = keyOf(key);
142 const secret = NodeCrypto.randomBytes(24).toString("base64url");
143 const server = yield* NodeSocketServer.makeWebSocket({
144 host: "127.0.0.1",
145 port: 0,
146 path: `/${secret}`,
147 }).pipe(Effect.orDie);
148 const queue = yield* Queue.unbounded<string>();
149 inbound.set(id, queue);
150 // A detach before this registration shut down no queue, so check again.
151 if (!attachedTabs.has(id)) {
152 inbound.delete(id);
153 return yield* Effect.die("The desktop tab detached before the server connected.");
154 }
155 yield* Effect.addFinalizer(() =>
156 Effect.gen(function* () {
157 if (inbound.get(id) === queue) inbound.delete(id);
158 yield* Queue.shutdown(queue);
159 yield* command({ type: "release", ...key });
160 }),
161 );
162 // The relay serves one Playwright connection; a second would see the first's sessions.
163 let connected = false;
164 yield* server
165 .run((socket) =>
166 Effect.gen(function* () {
167 if (connected) return;
168 connected = true;
169 const writer = yield* socket.writer;
170 const reader = yield* socket.reader;
171 yield* Stream.fromQueue(queue).pipe(
172 Stream.runForEach((message) => writer.write(message)),
173 Effect.forkScoped,
174 );
175 const decoder = new TextDecoder();
176 return yield* reader.pull.pipe(
177 Effect.flatMap((frames) =>
178 Effect.forEach(
179 frames,
180 (frame) =>
181 command({
182 type: "cdp",
183 ...key,
184 message: typeof frame === "string" ? frame : decoder.decode(frame),
185 }),
186 { discard: true },
187 ),
188 ),
189 Effect.forever,
190 );
191 }).pipe(Effect.scoped, Effect.ignore),
192 )
193 .pipe(Effect.forkScoped);
194 const address = server.address;
195 if (address._tag !== "InetAddressV4") return yield* Effect.die("Unexpected relay address.");
196 return `ws://127.0.0.1:${address.port}/${secret}`;
197 });
198​
199 return DesktopBrowserChannel.of({
200 available: true,
201 awaitAttached: (key, timeout) =>
202 Effect.scoped(
203 Effect.gen(function* () {
204 const subscription = yield* PubSub.subscribe(changes);
205 if (attachedTabs.has(keyOf(key))) return true;
206 return yield* Stream.fromSubscription(subscription).pipe(
207 Stream.filter((change) => change.attached && keyOf(change.key) === keyOf(key)),
208 Stream.runHead,
209 Effect.map(Option.isSome),
210 Effect.timeoutOption(timeout),
211 Effect.map((result) => Option.getOrElse(result, () => false)),
212 );
213 }),
214 ),
215 detached: Stream.fromPubSub(changes).pipe(
216 Stream.filter((change) => !change.attached),
217 Stream.map((change) => change.key),
218 ),
219 isAttached: (key) => Effect.sync(() => attachedTabs.has(keyOf(key))),
220 endpoint,
221 pointer: (key, pointer) => command({ type: "pointer", ...key, ...pointer }),
222 });
223});
224​
225export const layer = Layer.effect(DesktopBrowserChannel, make);