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

DesktopBrowserHost.test.ts

251 lines9.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - Stands in for an Electron debugger.
2import { describe, expect, it } from "@effect/vitest";
3import { DesktopBrowserEvent } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Queue from "effect/Queue";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import * as NodeEvents from "node:events";
10​
11import * as DesktopBrowserHost from "./DesktopBrowserHost.ts";
12​
13const decodeEvent = Schema.decodeUnknownSync(Schema.fromJsonString(DesktopBrowserEvent));
14const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
15const decodeCdpReply = Schema.decodeUnknownSync(
16 Schema.fromJsonString(Schema.Struct({ id: Schema.Number })),
17);
18const key = { threadId: "thread-1", tabId: "tab-1" };
19/** Sends a page command whose id the fake debugger records as it receives it. */
20const command = (
21 host: DesktopBrowserHost.DesktopBrowserHost["Service"],
22 id: number,
23 method: string,
24) =>
25 host.handleCommandLine(
26 encodeJson({
27 type: "cdp",
28 ...key,
29 message: encodeJson({ id, method, params: { id }, sessionId: "t3-preview-page" }),
30 }),
31 );
32​
33const makeDebuggee = () => {
34 const emitter = new NodeEvents.EventEmitter();
35 const pending: Array<() => void> = [];
36 const sent: Array<unknown> = [];
37 const sendWaiters: Array<() => void> = [];
38 const debuggee = Object.assign(emitter, {
39 sendCommand: (method: string, params?: { id?: number }) =>
40 new Promise((resolve) => {
41 if (method === "Target.getTargetInfo") {
42 resolve({ targetInfo: { targetId: "GUEST" } });
43 return;
44 }
45 sent.push(params?.id);
46 pending.push(() => resolve({ method }));
47 sendWaiters.shift()?.();
48 }),
49 });
50 const webContents = Object.assign(new NodeEvents.EventEmitter(), {
51 getURL: () => "http://localhost/",
52 getTitle: () => "Page",
53 getUserAgent: () => "Electron",
54 });
55 return {
56 tab: {
57 webContents: webContents as unknown as Electron.WebContents,
58 debugger: debuggee as unknown as Electron.Debugger,
59 },
60 emit: (method: string, params: unknown) => emitter.emit("message", {}, method, params, ""),
61 navigate: () => webContents.emit("did-navigate"),
62 /** Ids of the commands the debugger received, in order. */
63 sent,
64 nextSend: () => new Promise<void>((resolve) => sendWaiters.push(resolve)),
65 release: () => pending.splice(0).forEach((resolve) => resolve()),
66 releaseFirst: () => pending.shift()?.(),
67 };
68};
69​
70const takeEvents = (host: DesktopBrowserHost.DesktopBrowserHost["Service"], count: number) =>
71 host.events.pipe(
72 Stream.take(count),
73 Stream.runCollect,
74 Effect.map((lines) => lines.map((line) => decodeEvent(new TextDecoder().decode(line)))),
75 );
76​
77/**
78 * Ids of the replies the host sends, in order. A screenshot's reply leaves after its turn
79 * has passed on, so by then the next waiting screenshot, if any, has been sent. Subscribe
80 * before sending commands: a new subscriber releases the tab's relay.
81 */
82const watchReplies = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) =>
83 Effect.gen(function* () {
84 const replies = yield* Queue.unbounded<number>();
85 yield* host.events.pipe(
86 Stream.map((line) => decodeEvent(new TextDecoder().decode(line))),
87 Stream.runForEach((event) =>
88 event.type === "cdp" ? Queue.offer(replies, decodeCdpReply(event.message).id) : Effect.void,
89 ),
90 Effect.forkScoped,
91 );
92 yield* Effect.yieldNow;
93 return replies;
94 });
95​
96describe("DesktopBrowserHost", () => {
97 it.effect("announces tabs already attached to a backend that starts later", () =>
98 Effect.gen(function* () {
99 const host = yield* DesktopBrowserHost.make;
100 host.attach(key, makeDebuggee().tab);
101​
102 expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
103 expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
104 }),
105 );
106​
107 it.effect("drops replies from a relay the server released", () =>
108 Effect.gen(function* () {
109 const host = yield* DesktopBrowserHost.make;
110 const debuggee = makeDebuggee();
111 host.attach(key, debuggee.tab);
112 const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped);
113​
114 yield* Effect.yieldNow;
115 const command = (id: number, method: string) =>
116 host.handleCommandLine(
117 encodeJson({
118 type: "cdp",
119 ...key,
120 message: encodeJson({ id, method, sessionId: "t3-preview-page" }),
121 }),
122 );
123 yield* command(1, "Page.captureScreenshot");
124 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
125 yield* command(2, "DOM.enable");
126 debuggee.release();
127 const [, reply] = yield* Fiber.join(reader);
128​
129 expect(reply).toMatchObject({ type: "cdp" });
130 expect(decodeCdpReply((reply as { message: string }).message).id).toBe(2);
131 }).pipe(Effect.scoped),
132 );
133​
134 it.effect("sends a page one screenshot at a time", () =>
135 Effect.gen(function* () {
136 const host = yield* DesktopBrowserHost.make;
137 const debuggee = makeDebuggee();
138 host.attach(key, debuggee.tab);
139 const replies = yield* watchReplies(host);
140​
141 yield* command(host, 1, "Page.captureScreenshot");
142 yield* command(host, 2, "Page.captureScreenshot");
143 yield* command(host, 3, "DOM.enable");
144 expect(debuggee.sent).toEqual([1, 3]);
145​
146 debuggee.releaseFirst();
147 expect(yield* Queue.take(replies)).toBe(1);
148 expect(debuggee.sent).toEqual([1, 3, 2]);
149 }).pipe(Effect.scoped),
150 );
151​
152 it.effect("stops waiting on a screenshot the page navigated away from", () =>
153 Effect.gen(function* () {
154 const host = yield* DesktopBrowserHost.make;
155 const debuggee = makeDebuggee();
156 host.attach(key, debuggee.tab);
157 const replies = yield* watchReplies(host);
158​
159 yield* command(host, 1, "Page.captureScreenshot");
160 yield* command(host, 2, "Page.captureScreenshot");
161 yield* command(host, 3, "Page.captureScreenshot");
162 debuggee.navigate();
163 expect(debuggee.sent).toEqual([1, 2]);
164​
165 // The superseded screenshot answering late must not start a third beside the second.
166 debuggee.releaseFirst();
167 expect(yield* Queue.take(replies)).toBe(1);
168 expect(debuggee.sent).toEqual([1, 2]);
169​
170 debuggee.releaseFirst();
171 expect(yield* Queue.take(replies)).toBe(2);
172 expect(debuggee.sent).toEqual([1, 2, 3]);
173 }).pipe(Effect.scoped),
174 );
175​
176 it.effect("drops screenshots a released relay left waiting", () =>
177 Effect.gen(function* () {
178 const host = yield* DesktopBrowserHost.make;
179 const debuggee = makeDebuggee();
180 host.attach(key, debuggee.tab);
181​
182 yield* command(host, 1, "Page.captureScreenshot");
183 yield* command(host, 2, "Page.captureScreenshot");
184 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
185 yield* command(host, 3, "Page.captureScreenshot");
186 expect(debuggee.sent).toEqual([1]);
187​
188 const sent = debuggee.nextSend();
189 debuggee.release();
190 yield* Effect.promise(() => sent);
191 expect(debuggee.sent).toEqual([1, 3]);
192 }),
193 );
194​
195 it.effect("saves a server tab's download under its CDP guid where the server asked", () =>
196 Effect.gen(function* () {
197 const host = yield* DesktopBrowserHost.make;
198 const debuggee = makeDebuggee();
199 host.attach(key, debuggee.tab);
200 const paths: Array<string> = [];
201 const item = {
202 setSavePath: (path: string) => void paths.push(path),
203 } as unknown as Electron.DownloadItem;
204​
205 expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false);
206 yield* host.handleCommandLine(
207 encodeJson({
208 type: "cdp",
209 ...key,
210 message: encodeJson({
211 id: 1,
212 method: "Browser.setDownloadBehavior",
213 params: { behavior: "allowAndName", downloadPath: "/srv/downloads" },
214 }),
215 }),
216 );
217 debuggee.emit("Browser.downloadWillBegin", { guid: "guid-1", suggestedFilename: "r.csv" });
218 expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(true);
219 expect(paths).toEqual(["/srv/downloads/guid-1"]);
220 }),
221 );
222​
223 it.effect("tells a download the person clicked from one the agent's input started", () =>
224 Effect.gen(function* () {
225 const host = yield* DesktopBrowserHost.make;
226 const debuggee = makeDebuggee();
227 host.attach(key, debuggee.tab);
228​
229 yield* host.handleCommandLine(
230 encodeJson({
231 type: "cdp",
232 ...key,
233 message: encodeJson({ id: 1, method: "DOM.getDocument", params: {} }),
234 }),
235 );
236 expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(true);
237 yield* host.handleCommandLine(
238 encodeJson({
239 type: "cdp",
240 ...key,
241 message: encodeJson({
242 id: 2,
243 method: "Input.dispatchMouseEvent",
244 params: { type: "mousePressed", x: 1, y: 1 },
245 }),
246 }),
247 );
248 expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(false);
249 }),
250 );
251});