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