Open History to see the last commit
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
20/** A tab's webContents and debugger, with the debugger's commands left pending until released. */
21const makeDebuggee = () => {
22 const emitter = new NodeEvents.EventEmitter();
23 const pending: Array<() => void> = [];
24 const debuggee = Object.assign(emitter, {
25 sendCommand: (method: string) =>
26 new Promise((resolve) => {
27 if (method === "Target.getTargetInfo") {
28 resolve({ targetInfo: { targetId: "GUEST" } });
29 return;
30 }
31 pending.push(() => resolve({ method }));
32 }),
33 });
34 const webContents = {
35 getURL: () => "http://localhost/",
36 getTitle: () => "Page",
37 getUserAgent: () => "Electron",
38 };
39 return {
40 tab: {
41 webContents: webContents as unknown as Electron.WebContents,
42 debugger: debuggee as unknown as Electron.Debugger,
43 },
44 emit: (method: string, params: unknown) => emitter.emit("message", {}, method, params, ""),
45 release: () => pending.splice(0).forEach((resolve) => resolve()),
46 };
47};
48
49/** Reads `count` events from one backend's subscription. */
50const takeEvents = (host: DesktopBrowserHost.DesktopBrowserHost["Service"], count: number) =>
51 host.events.pipe(
52 Stream.take(count),
53 Stream.runCollect,
54 Effect.map((lines) => lines.map((line) => decodeEvent(new TextDecoder().decode(line)))),
55 );
56
57describe("DesktopBrowserHost", () => {
58 it.effect("announces tabs already attached to a backend that starts later", () =>
59 Effect.gen(function* () {
60 const host = yield* DesktopBrowserHost.make;
61 host.attach(key, makeDebuggee().tab);
62 // A restarted backend subscribes after the attach and still hears it.
63 expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
64 expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]);
65 }),
66 );
67
68 it.effect("drops replies from a relay the server released", () =>
69 Effect.gen(function* () {
70 const host = yield* DesktopBrowserHost.make;
71 const debuggee = makeDebuggee();
72 host.attach(key, debuggee.tab);
73 const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped);
74 // Wait until the reader has received the announcement.
75 yield* Effect.yieldNow;
76 const command = (id: number, method: string) =>
77 host.handleCommandLine(
78 encodeJson({
79 type: "cdp",
80 ...key,
81 message: encodeJson({ id, method, sessionId: "t3-preview-page" }),
82 }),
83 );
84 yield* command(1, "Page.captureScreenshot");
85 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
86 yield* command(2, "DOM.enable");
87 debuggee.release();
88 yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
89 const [, reply] = yield* Fiber.join(reader);
90 // Only the new connection's reply arrives; the old one's id could collide.
91 expect(reply).toMatchObject({ type: "cdp" });
92 expect(decodeCdpReply((reply as { message: string }).message).id).toBe(2);
93 }).pipe(Effect.scoped),
94 );
95
96 it.effect("does not type deferred commands from a released connection", () =>
97 Effect.gen(function* () {
98 const host = yield* DesktopBrowserHost.make;
99 const debuggee = makeDebuggee();
100 const started = Promise.withResolvers<void>();
101 const resume = Promise.withResolvers<void>();
102 const edits: Array<string> = [];
103 let first = true;
104 Object.assign(debuggee.tab.webContents, {
105 mainFrame: {
106 frames: [],
107 executeJavaScript: async (source: string) => {
108 if (source.includes("indexOf(element.contentWindow)")) {
109 if (first) {
110 first = false;
111 started.resolve();
112 await resume.promise;
113 }
114 return -1;
115 }
116 edits.push(source);
117 return true;
118 },
119 },
120 });
121 const replies = yield* Queue.unbounded<DesktopBrowserEvent>();
122 yield* host.events.pipe(
123 Stream.runForEach((line) =>
124 Queue.offer(replies, decodeEvent(new TextDecoder().decode(line))),
125 ),
126 Effect.forkScoped,
127 );
128 host.attach(key, debuggee.tab);
129 expect(yield* Queue.take(replies)).toEqual({ type: "attached", ...key });
130 const type = (id: number, text: string) =>
131 host.handleCommandLine(
132 encodeJson({
133 type: "cdp",
134 ...key,
135 message: encodeJson({
136 id,
137 method: "Input.insertText",
138 params: { text },
139 sessionId: "t3-preview-page",
140 }),
141 }),
142 );
143 yield* type(1, "obsolete active input");
144 yield* Effect.promise(() => started.promise);
145 yield* type(2, "obsolete queued input");
146 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
147 yield* type(3, "fresh input");
148 resume.resolve();
149 const reply = yield* Queue.take(replies);
150 expect(reply).toMatchObject({ type: "cdp" });
151 expect(decodeCdpReply((reply as { message: string }).message).id).toBe(3);
152 expect(edits).toHaveLength(1);
153 expect(edits[0]).toContain("fresh input");
154 expect(host.isDispatchingKeyboard(debuggee.tab.webContents)).toBe(false);
155 }).pipe(Effect.scoped),
156 );
157
158 it.effect("saves a server tab's download under its CDP guid where the server asked", () =>
159 Effect.gen(function* () {
160 const host = yield* DesktopBrowserHost.make;
161 const debuggee = makeDebuggee();
162 host.attach(key, debuggee.tab);
163 const paths: Array<string> = [];
164 const item = {
165 setSavePath: (path: string) => void paths.push(path),
166 } as unknown as Electron.DownloadItem;
167 // Before the server sets a directory, Electron keeps its own handling.
168 expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false);
169 yield* host.handleCommandLine(
170 encodeJson({
171 type: "cdp",
172 ...key,
173 message: encodeJson({
174 id: 1,
175 method: "Browser.setDownloadBehavior",
176 params: { behavior: "allowAndName", downloadPath: "/srv/downloads" },
177 }),
178 }),
179 );
180 debuggee.emit("Browser.downloadWillBegin", { guid: "guid-1", suggestedFilename: "r.csv" });
181 expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(true);
182 expect(paths).toEqual(["/srv/downloads/guid-1"]);
183 }),
184 );
185
186 it.effect("tells a download the person clicked from one the agent's input started", () =>
187 Effect.gen(function* () {
188 const host = yield* DesktopBrowserHost.make;
189 const debuggee = makeDebuggee();
190 host.attach(key, debuggee.tab);
191 // Reading the page is not acting on it.
192 yield* host.handleCommandLine(
193 encodeJson({
194 type: "cdp",
195 ...key,
196 message: encodeJson({ id: 1, method: "DOM.getDocument", params: {} }),
197 }),
198 );
199 expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(true);
200 yield* host.handleCommandLine(
201 encodeJson({
202 type: "cdp",
203 ...key,
204 message: encodeJson({
205 id: 2,
206 method: "Input.dispatchMouseEvent",
207 params: { type: "mousePressed", x: 1, y: 1 },
208 }),
209 }),
210 );
211 expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(false);
212 }),
213 );
214});