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