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 type PreviewAutomationLoadError,
10} from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as PubSub from "effect/PubSub";
17import * as Queue from "effect/Queue";
18import * as Schema from "effect/Schema";
19import * as Scope from "effect/Scope";
20import * as Semaphore from "effect/Semaphore";
21import * as Stream from "effect/Stream";
22import * as Ndjson from "effect/encoding/Ndjson";
23import * as NodeCrypto from "node:crypto";
24import * as NodeNet from "node:net";
25
26import * as ServerConfig from "../config.ts";
27import { writeAllToFileDescriptor } from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
28
29const decodeEvent = Schema.decodeUnknownEffect(DesktopBrowserEvent);
30const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(DesktopBrowserCommand));
31
32export interface DesktopTabKey {
33 readonly threadId: string;
34 readonly tabId: string;
35}
36
37const keyOf = ({ threadId, tabId }: DesktopTabKey) => `${threadId}\u0000${tabId}`;
38
39export class DesktopBrowserChannel extends Context.Service<
40 DesktopBrowserChannel,
41 {
42 readonly available: boolean;
43 /** Subscribe before checking so concurrent attaches cannot be missed. */
44 readonly awaitAttached: (key: DesktopTabKey, timeout: Duration.Input) => Effect.Effect<boolean>;
45 readonly detached: Stream.Stream<DesktopTabKey>;
46 readonly attached: Stream.Stream<DesktopTabKey>;
47 readonly isAttached: (key: DesktopTabKey) => Effect.Effect<boolean>;
48 /** Whether a desktop window draws the tab on screen, which no streamed viewer counts. */
49 readonly isShown: (key: DesktopTabKey) => boolean;
50 /** Resolves true once the tab is shown, or false on timeout. */
51 readonly awaitShown: (key: DesktopTabKey, timeout: Duration.Input) => Effect.Effect<boolean>;
52 /** A load failure the desktop saw, possibly before the server connected to the tab. */
53 readonly loadFailure: (key: DesktopTabKey) => PreviewAutomationLoadError | undefined;
54 readonly endpoint: (key: DesktopTabKey) => Effect.Effect<string, never, Scope.Scope>;
55 readonly pointer: (
56 key: DesktopTabKey,
57 pointer: { readonly phase: "move" | "click"; readonly x: number; readonly y: number },
58 ) => Effect.Effect<void>;
59 readonly viewerSize: (
60 key: DesktopTabKey,
61 size: { readonly width: number; readonly height: number } | null,
62 ) => Effect.Effect<void>;
63 /** Never fails. A failed write means a broken channel; the next backend starts with no turns. */
64 readonly turn: (threadId: string, active: boolean) => Effect.Effect<void>;
65 }
66>()("t3/preview/DesktopBrowserChannel") {}
67
68const make = Effect.gen(function* () {
69 const config = yield* ServerConfig.ServerConfig;
70 const inputFd = config.desktopBrowserFd;
71 const controlFd = config.desktopBrowserControlFd;
72 const changes = yield* PubSub.unbounded<{ key: DesktopTabKey; attached: boolean }>();
73 const attachedTabs = new Set<string>();
74 // Missing reports protect desktop tabs until the renderer explicitly marks them hidden.
75 const shownTabs = new Map<string, boolean>();
76 const shownReports = yield* PubSub.unbounded<string>();
77 const loadFailures = new Map<string, PreviewAutomationLoadError>();
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.fn("DesktopBrowserChannel.awaitAttached")(function () {
85 return Effect.succeed(false);
86 }),
87 detached: Stream.empty,
88 attached: Stream.empty,
89 isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function () {
90 return Effect.succeed(false);
91 }),
92 endpoint: Effect.fn("DesktopBrowserChannel.endpoint")(function () {
93 return Effect.die("No desktop app is attached to this server.");
94 }),
95 turn: Effect.fn("DesktopBrowserChannel.turn")(function () {
96 return Effect.void;
97 }),
98 pointer: Effect.fn("DesktopBrowserChannel.pointer")(function () {
99 return Effect.void;
100 }),
101 viewerSize: Effect.fn("DesktopBrowserChannel.viewerSize")(function () {
102 return Effect.void;
103 }),
104 isShown: () => false,
105 awaitShown: Effect.fn("DesktopBrowserChannel.awaitShown")(function () {
106 return Effect.succeed(false);
107 }),
108 loadFailure: () => undefined,
109 });
110 }
111
112 const command = (message: DesktopBrowserCommandType) =>
113 writeLock.withPermits(1)(
114 encodeCommand(message).pipe(
115 Effect.flatMap((line) => writeAllToFileDescriptor(controlFd, Buffer.from(`${line}\n`))),
116 Effect.catchCause((cause) =>
117 Effect.logWarning("desktop browser command failed", { cause }),
118 ),
119 ),
120 );
121
122 // Use cancellable socket reads; filesystem pipe reads keep Node alive after scope shutdown.
123 const readable = yield* Effect.acquireRelease(
124 Effect.sync(() => new NodeNet.Socket({ fd: inputFd, readable: true, writable: false })),
125 (stream) => Effect.sync(() => stream.destroy()),
126 );
127 yield* NodeStream.fromReadable<Uint8Array, Error>({
128 evaluate: () => readable,
129 closeOnDone: true,
130 onError: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
131 }).pipe(
132 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
133 Stream.mapEffect((value) => decodeEvent(value).pipe(Effect.option)),
134 Stream.runForEach((decoded) => {
135 if (Option.isNone(decoded)) return Effect.void;
136 const event = decoded.value;
137 const key = { threadId: event.threadId, tabId: event.tabId };
138 const id = keyOf(key);
139 switch (event.type) {
140 case "cdp": {
141 const queue = inbound.get(id);
142 return queue ? Queue.offer(queue, event.message).pipe(Effect.asVoid) : Effect.void;
143 }
144 case "attached":
145 attachedTabs.add(id);
146 return PubSub.publish(changes, { key, attached: true });
147 case "loadFailed":
148 loadFailures.set(id, {
149 url: event.url.slice(0, 2048),
150 code: event.code,
151 description: event.description,
152 });
153 return Effect.void;
154 case "detached": {
155 attachedTabs.delete(id);
156 shownTabs.delete(id);
157 loadFailures.delete(id);
158 const queue = inbound.get(id);
159 return (queue ? Queue.shutdown(queue) : Effect.void).pipe(
160 Effect.andThen(PubSub.publish(changes, { key, attached: false })),
161 );
162 }
163 case "shown":
164 shownTabs.set(id, event.shown);
165 return event.shown ? PubSub.publish(shownReports, id) : Effect.void;
166 }
167 }),
168 Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })),
169 Effect.ensuring(
170 Effect.sync(() => {
171 shownTabs.clear();
172 loadFailures.clear();
173 }),
174 ),
175 Effect.forkScoped,
176 );
177
178 const endpoint = Effect.fn("DesktopBrowserChannel.endpoint")(function* (key: DesktopTabKey) {
179 const id = keyOf(key);
180 const secret = NodeCrypto.randomBytes(24).toString("base64url");
181 const server = yield* NodeSocketServer.makeWebSocket({
182 host: "127.0.0.1",
183 port: 0,
184 path: `/${secret}`,
185 }).pipe(Effect.orDie);
186 const queue = yield* Queue.unbounded<string>();
187 inbound.set(id, queue);
188 // A detach before this registration shut down no queue, so check again.
189 if (!attachedTabs.has(id)) {
190 inbound.delete(id);
191 return yield* Effect.die("The desktop tab detached before the server connected.");
192 }
193 yield* Effect.addFinalizer(() =>
194 Effect.gen(function* () {
195 if (inbound.get(id) === queue) inbound.delete(id);
196 yield* Queue.shutdown(queue);
197 yield* command({ type: "release", ...key });
198 }),
199 );
200 // The relay serves one Playwright connection; a second would see the first's sessions.
201 let connected = false;
202 yield* server
203 .run((socket) =>
204 Effect.gen(function* () {
205 if (connected) return;
206 connected = true;
207 const writer = yield* socket.writer;
208 const reader = yield* socket.reader;
209 // A detach shuts the queue down. Ending here closes the socket, so Playwright's
210 // pending commands fail instead of waiting forever for the tab to answer.
211 const toPlaywright = Stream.fromQueue(queue).pipe(
212 Stream.runForEach((message) => writer.write(message)),
213 Effect.exit,
214 );
215 const decoder = new TextDecoder();
216 const toDesktop = reader.pull.pipe(
217 Effect.flatMap((frames) =>
218 Effect.forEach(
219 frames,
220 (frame) =>
221 command({
222 type: "cdp",
223 ...key,
224 message: typeof frame === "string" ? frame : decoder.decode(frame),
225 }),
226 { discard: true },
227 ),
228 ),
229 Effect.forever,
230 );
231 return yield* Effect.raceFirst(toPlaywright, toDesktop);
232 }).pipe(Effect.scoped, Effect.ignore),
233 )
234 .pipe(Effect.forkScoped);
235 const address = server.address;
236 if (address._tag !== "InetAddressV4") return yield* Effect.die("Unexpected relay address.");
237 return `ws://127.0.0.1:${address.port}/${secret}`;
238 });
239
240 const isShown = (key: DesktopTabKey) => shownTabs.get(keyOf(key)) ?? true;
241
242 return DesktopBrowserChannel.of({
243 available: true,
244 awaitAttached: Effect.fn("DesktopBrowserChannel.awaitAttached")(function (key, timeout) {
245 return Effect.scoped(
246 Effect.gen(function* () {
247 const subscription = yield* PubSub.subscribe(changes);
248 if (attachedTabs.has(keyOf(key))) return true;
249 return yield* Stream.fromSubscription(subscription).pipe(
250 Stream.filter((change) => change.attached && keyOf(change.key) === keyOf(key)),
251 Stream.runHead,
252 Effect.map(Option.isSome),
253 Effect.timeoutOption(timeout),
254 Effect.map((result) => Option.getOrElse(result, () => false)),
255 );
256 }),
257 );
258 }),
259 detached: Stream.fromPubSub(changes).pipe(
260 Stream.filter((change) => !change.attached),
261 Stream.map((change) => change.key),
262 ),
263 attached: Stream.fromPubSub(changes).pipe(
264 Stream.filter((change) => change.attached),
265 Stream.map((change) => change.key),
266 ),
267 isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function (key) {
268 return Effect.sync(() => attachedTabs.has(keyOf(key)));
269 }),
270 isShown,
271 awaitShown: Effect.fn("DesktopBrowserChannel.awaitShown")(function (key, timeout) {
272 return Effect.scoped(
273 Effect.gen(function* () {
274 const subscription = yield* PubSub.subscribe(shownReports);
275 if (isShown(key)) return true;
276 return yield* Stream.fromSubscription(subscription).pipe(
277 Stream.filter((id) => id === keyOf(key)),
278 Stream.runHead,
279 Effect.map(Option.isSome),
280 Effect.timeoutOption(timeout),
281 Effect.map((result) => Option.getOrElse(result, () => false)),
282 );
283 }),
284 );
285 }),
286 loadFailure: (key) => loadFailures.get(keyOf(key)),
287 endpoint,
288 turn: Effect.fn("DesktopBrowserChannel.turn")(function (threadId, active) {
289 return command({ type: "turn", threadId, active });
290 }),
291 pointer: Effect.fn("DesktopBrowserChannel.pointer")(function (key, pointer) {
292 return command({ type: "pointer", ...key, ...pointer });
293 }),
294 viewerSize: Effect.fn("DesktopBrowserChannel.viewerSize")(function (key, size) {
295 return command({ type: "viewerSize", ...key, size });
296 }),
297 });
298});
299
300export const layer = Layer.effect(DesktopBrowserChannel, make);