Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Hands a real file on disk to a real desktop browser.
2import * as NodeEvents from "node:events";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6
7import { INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts";
8import { chromium, type Browser, type BrowserContext, type BrowserType } from "playwright-core";
9import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
10
11import { ServerBrowserContexts } from "./ServerBrowserContexts.ts";
12
13const launches = vi.hoisted(() => ({
14 launch: vi.fn<BrowserType["launch"]>(),
15 persistent: vi.fn<BrowserType["launchPersistentContext"]>(),
16 mkdir: vi.fn().mockResolvedValue(undefined),
17 rm: vi.fn().mockResolvedValue(undefined),
18}));
19const launchPersistentChromium = chromium.launchPersistentContext.bind(chromium);
20vi.spyOn(chromium, "launch").mockImplementation(launches.launch);
21vi.spyOn(chromium, "launchPersistentContext").mockImplementation(launches.persistent);
22vi.mock("node:fs/promises", () => ({ mkdir: launches.mkdir, rm: launches.rm }));
23
24const makeContext = () => {
25 const events = new NodeEvents.EventEmitter();
26 let closed = false;
27 return {
28 on: vi.fn((event: string, listener: () => void) => events.on(event, listener)),
29 pages: vi.fn(() => []),
30 newPage: vi.fn(async () => ({ once: vi.fn() })),
31 isClosed: () => closed,
32 close: vi.fn(async () => {
33 if (!closed) {
34 closed = true;
35 events.emit("close");
36 }
37 }),
38 };
39};
40
41const makeBrowser = () => {
42 const events = new NodeEvents.EventEmitter();
43 const contexts: ReturnType<typeof makeContext>[] = [];
44 return {
45 created: contexts,
46 contexts: () => contexts.filter((context) => !context.isClosed()),
47 on: vi.fn((event: string, listener: () => void) => events.on(event, listener)),
48 newContext: vi.fn(async () => {
49 const context = makeContext();
50 contexts.push(context);
51 return context as unknown as BrowserContext;
52 }),
53 close: vi.fn(async () => {
54 for (const context of contexts) await context.close();
55 events.emit("disconnected");
56 }),
57 };
58};
59
60const options = () => ({
61 profilesDir: "/test/profiles",
62 executable: vi.fn(async () => "/test/chromium"),
63 env: {},
64});
65
66const withLauncher = () => {
67 const release = vi.fn(async () => {});
68 return {
69 release,
70 configuration: {
71 ...options(),
72 launcher: vi.fn(async (executable: string) => ({ path: `${executable}-launcher`, release })),
73 },
74 };
75};
76
77beforeEach(() => {
78 launches.launch.mockReset();
79 launches.persistent.mockReset();
80 launches.mkdir.mockClear();
81 launches.rm.mockClear();
82});
83
84describe("ServerBrowserContexts", () => {
85 it("closes the shared browser only after it holds no context for the idle period", async () => {
86 vi.useFakeTimers();
87 try {
88 const first = makeBrowser();
89 const second = makeBrowser();
90 launches.launch
91 .mockResolvedValueOnce(first as unknown as Browser)
92 .mockResolvedValueOnce(second as unknown as Browser);
93 const pool = new ServerBrowserContexts({ ...options(), idleBrowserMs: 10 });
94 const agent = await pool.contextFor("default", "agent");
95 await pool.scratchPage();
96 await agent.close();
97 await vi.advanceTimersByTimeAsync(10);
98 expect(first.close).not.toHaveBeenCalled();
99 await first.created[1]!.close();
100 await vi.advanceTimersByTimeAsync(9);
101 const next = await pool.contextFor("default", "next");
102 await vi.advanceTimersByTimeAsync(10);
103 expect(first.close).not.toHaveBeenCalled();
104 await next.close();
105 await vi.advanceTimersByTimeAsync(10);
106 expect(first.close).toHaveBeenCalledOnce();
107 await pool.contextFor("default", "later");
108 expect(launches.launch).toHaveBeenCalledTimes(2);
109 expect(second.newContext).toHaveBeenCalledOnce();
110 await pool.close();
111 } finally {
112 vi.useRealTimers();
113 }
114 });
115
116 it("closes a scratch context when creating its page fails", async () => {
117 const browser = makeBrowser();
118 launches.launch.mockResolvedValue(browser as unknown as Browser);
119 const pool = new ServerBrowserContexts(options());
120 const peer = await pool.contextFor("default", "peer");
121 const context = await browser.newContext();
122 const failure = new Error("newPage failed");
123 browser.created[1]!.newPage.mockRejectedValueOnce(failure);
124 browser.newContext.mockResolvedValueOnce(context);
125 try {
126 await expect(pool.scratchPage()).rejects.toBe(failure);
127 expect(context.close).toHaveBeenCalledOnce();
128 expect(browser.contexts()).toEqual([peer]);
129 expect(peer.close).not.toHaveBeenCalled();
130 expect(browser.close).not.toHaveBeenCalled();
131 } finally {
132 await pool.close();
133 }
134 });
135
136 it("lazily shares one browser across concurrent isolated sessions and reuses each context", async () => {
137 const browser = makeBrowser();
138 const launch = Promise.withResolvers<Browser>();
139 const started = Promise.withResolvers<void>();
140 launches.launch.mockImplementation(() => {
141 started.resolve();
142 return launch.promise;
143 });
144 const { configuration, release } = withLauncher();
145 const pool = new ServerBrowserContexts(configuration);
146 expect(configuration.executable).not.toHaveBeenCalled();
147 const first = pool.contextFor("default", "agent-a");
148 const again = pool.contextFor("default", "agent-a");
149 const second = pool.contextFor("default", "agent-b");
150 const incognito = pool.contextFor(INCOGNITO_BROWSER_PROFILE_ID);
151 await started.promise;
152 // Playwright may retry the same path until the launch settles.
153 expect(release).not.toHaveBeenCalled();
154 launch.resolve(browser as unknown as Browser);
155 const [a, reused, b, privateContext] = await Promise.all([first, again, second, incognito]);
156 expect(release).toHaveBeenCalledTimes(1);
157 expect(a).toBe(reused);
158 expect(new Set([a, b, privateContext]).size).toBe(3);
159 expect(launches.launch).toHaveBeenCalledExactlyOnceWith(
160 expect.objectContaining({ executablePath: "/test/chromium-launcher" }),
161 );
162 expect(launches.persistent).not.toHaveBeenCalled();
163 expect(browser.newContext).toHaveBeenCalledWith({
164 viewport: { width: 1280, height: 800 },
165 deviceScaleFactor: 2,
166 });
167 await pool.close();
168 expect(browser.close).toHaveBeenCalledTimes(1);
169 for (const context of browser.created) expect(context.close).toHaveBeenCalled();
170 });
171
172 it("keeps human profiles persistent without sharing their storage with agents", async () => {
173 const human = makeContext();
174 const browser = makeBrowser();
175 launches.persistent.mockResolvedValue(human as unknown as BrowserContext);
176 launches.launch.mockResolvedValue(browser as unknown as Browser);
177 const { configuration, release } = withLauncher();
178 const pool = new ServerBrowserContexts(configuration);
179 const persistent = await pool.contextFor("work/team");
180 expect(await pool.contextFor("work/team")).toBe(persistent);
181 expect(await pool.contextFor("work/team", "agent")).not.toBe(persistent);
182 expect(launches.persistent).toHaveBeenCalledExactlyOnceWith(
183 "/test/profiles/work%2Fteam",
184 expect.objectContaining({ chromiumSandbox: true, executablePath: "/test/chromium-launcher" }),
185 );
186 expect(release).toHaveBeenCalledTimes(2);
187 expect(launches.mkdir).toHaveBeenCalledWith("/test/profiles/work%2Fteam", { recursive: true });
188 await pool.close();
189 expect(human.close).toHaveBeenCalledTimes(1);
190 });
191
192 it("diagnoses a launcher failure against the real executable", async () => {
193 const diagnosed = new Error("diagnosed");
194 const diagnose = vi.fn(async () => diagnosed);
195 const pool = new ServerBrowserContexts({
196 ...options(),
197 diagnose,
198 launcher: vi.fn(async () => {
199 throw new Error("EACCES");
200 }),
201 });
202 await expect(pool.contextFor("default", "agent")).rejects.toBe(diagnosed);
203 expect(diagnose).toHaveBeenCalledExactlyOnceWith("/test/chromium", expect.any(Error));
204 expect(launches.launch).not.toHaveBeenCalled();
205 });
206
207 it("creates no launcher for a profile whose storage cannot be created", async () => {
208 launches.mkdir.mockRejectedValueOnce(new Error("EACCES"));
209 const { configuration } = withLauncher();
210 const pool = new ServerBrowserContexts(configuration);
211 await expect(pool.contextFor("work/team")).rejects.toThrow("EACCES");
212 expect(configuration.launcher).not.toHaveBeenCalled();
213 });
214
215 it("clears a profile by closing its open context before deleting its storage", async () => {
216 const human = makeContext();
217 const browser = makeBrowser();
218 launches.persistent.mockResolvedValue(human as unknown as BrowserContext);
219 launches.launch.mockResolvedValue(browser as unknown as Browser);
220 const onContextClose = vi.fn();
221 const pool = new ServerBrowserContexts({ ...options(), onContextClose });
222 const persistent = await pool.contextFor("work/team");
223 const agent = await pool.contextFor("work/team", "agent");
224 launches.rm.mockImplementationOnce(async () => {
225 expect(human.close).toHaveBeenCalledTimes(1);
226 });
227 await pool.clearProfile("work/team");
228 expect(onContextClose).toHaveBeenCalledExactlyOnceWith(persistent);
229 expect(launches.rm).toHaveBeenCalledExactlyOnceWith("/test/profiles/work%2Fteam", {
230 recursive: true,
231 force: true,
232 });
233 expect(await pool.contextFor("work/team", "agent")).toBe(agent);
234 expect(browser.created[0]?.close).not.toHaveBeenCalled();
235 launches.persistent.mockResolvedValue(makeContext() as unknown as BrowserContext);
236 expect(await pool.contextFor("work/team")).not.toBe(persistent);
237 await pool.clearProfile("never-opened");
238 expect(launches.rm).toHaveBeenLastCalledWith("/test/profiles/never-opened", {
239 recursive: true,
240 force: true,
241 });
242 await pool.close();
243 });
244
245 it("waits for the context to close when the same profile is cleared concurrently", async () => {
246 const human = makeContext();
247 const closed = Promise.withResolvers<void>();
248 human.close.mockImplementation(async () => closed.promise);
249 launches.persistent.mockResolvedValue(human as unknown as BrowserContext);
250 const pool = new ServerBrowserContexts(options());
251 await pool.contextFor("work/team");
252
253 const first = pool.clearProfile("work/team");
254 const second = pool.clearProfile("work/team");
255 const deletionsBeforeClose = launches.rm.mock.calls.length;
256 closed.resolve();
257 await Promise.all([first, second]);
258
259 expect(deletionsBeforeClose).toBe(0);
260 expect(human.close).toHaveBeenCalledTimes(1);
261 expect(launches.rm).toHaveBeenCalledExactlyOnceWith("/test/profiles/work%2Fteam", {
262 recursive: true,
263 force: true,
264 });
265 await pool.close();
266 });
267
268 it("opens a profile requested during its clear only after the storage is deleted", async () => {
269 launches.persistent.mockImplementation(async () => makeContext() as unknown as BrowserContext);
270 const configuration = options();
271 const pool = new ServerBrowserContexts(configuration);
272 await pool.contextFor("work/team");
273 const removing = Promise.withResolvers<void>();
274 const removed = Promise.withResolvers<void>();
275 let deleted = false;
276 launches.rm.mockImplementationOnce(async () => {
277 removing.resolve();
278 await removed.promise;
279 deleted = true;
280 });
281 const launchedAfterDelete: Array<boolean> = [];
282 configuration.executable.mockImplementation(async () => {
283 launchedAfterDelete.push(deleted);
284 return "/test/chromium";
285 });
286 const clearing = pool.clearProfile("work/team");
287 const reopening = pool.contextFor("work/team");
288 await removing.promise;
289 removed.resolve();
290 await Promise.all([clearing, reopening]);
291 expect(launchedAfterDelete).toEqual([true]);
292 await pool.close();
293 });
294
295 it.each([undefined, "default"])(
296 "never retries a failed %s launch with the sandbox disabled",
297 async (profile) => {
298 const launch = profile ? launches.persistent : launches.launch;
299 launch.mockRejectedValue(new Error("sandbox unavailable"));
300 const pool = new ServerBrowserContexts(options());
301 await expect(pool.contextFor(profile ?? INCOGNITO_BROWSER_PROFILE_ID)).rejects.toThrow(
302 "sandbox unavailable",
303 );
304 expect(launch).toHaveBeenCalledTimes(1);
305 expect(
306 profile ? launches.persistent.mock.calls[0]?.[1] : launches.launch.mock.calls[0]?.[0],
307 ).toMatchObject({ chromiumSandbox: true });
308 await pool.close();
309 },
310 );
311
312 it("allows only an explicit sandbox opt-out", async () => {
313 const browser = makeBrowser();
314 launches.launch.mockResolvedValue(browser as unknown as Browser);
315 const pool = new ServerBrowserContexts({
316 ...options(),
317 env: { T3CODE_SERVER_BROWSER_SANDBOX: "0" },
318 });
319 await pool.contextFor(INCOGNITO_BROWSER_PROFILE_ID);
320 expect(launches.launch).toHaveBeenCalledWith(
321 expect.objectContaining({ chromiumSandbox: false }),
322 );
323 await pool.close();
324 });
325
326 it("retries a failed startup on a later request with sandboxing still enabled", async () => {
327 const browser = makeBrowser();
328 launches.launch
329 .mockRejectedValueOnce(new Error("executable unavailable"))
330 .mockResolvedValue(browser as unknown as Browser);
331 const pool = new ServerBrowserContexts(options());
332 await expect(pool.contextFor("default", "agent")).rejects.toThrow("executable unavailable");
333 await pool.contextFor("default", "agent");
334 expect(launches.launch).toHaveBeenCalledTimes(2);
335 expect(launches.launch).toHaveBeenLastCalledWith(
336 expect.objectContaining({ chromiumSandbox: true }),
337 );
338 await pool.close();
339 });
340
341 it("cleans up a browser whose launch finishes during shutdown and rejects future work", async () => {
342 const browser = makeBrowser();
343 const launch = Promise.withResolvers<Browser>();
344 launches.launch.mockReturnValue(launch.promise);
345 const pool = new ServerBrowserContexts(options());
346 const opening = expect(pool.contextFor("default", "agent")).rejects.toThrow("closed");
347 const closing = pool.close();
348 launch.resolve(browser as unknown as Browser);
349 await Promise.all([opening, closing]);
350 await expect(pool.contextFor("default", "agent")).rejects.toThrow("closed");
351 await pool.close();
352 expect(browser.close).toHaveBeenCalledTimes(1);
353 expect(browser.created[0]?.close).toHaveBeenCalled();
354 });
355
356 it("uploads a file over 50 MB to a desktop tab, which shares the server's filesystem", async () => {
357 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-desktop-upload-"));
358 const userDataDir = NodePath.join(directory, "profile");
359 const pool = new ServerBrowserContexts(options());
360 try {
361 const desktop = await launchPersistentChromium(userDataDir, {
362 headless: true,
363 args: ["--remote-debugging-port=0"],
364 });
365 try {
366 const [port] = NodeFS.readFileSync(
367 NodePath.join(userDataDir, "DevToolsActivePort"),
368 "utf8",
369 ).split("\n");
370 const { browser, page } = await pool.connectDesktopPage(`http://127.0.0.1:${port}`);
371 try {
372 const file = NodePath.join(directory, "large.bin");
373 NodeFS.writeFileSync(file, "");
374 NodeFS.truncateSync(file, 51 * 1024 * 1024);
375 await page.setContent(`<input type="file">`);
376 await page.locator("input").setInputFiles(file);
377 expect(
378 await page.$eval("input", (input) =>
379 Array.from(
380 (input as unknown as { files: ArrayLike<{ name: string; size: number }> }).files,
381 ({ name, size }) => ({ name, size }),
382 ),
383 ),
384 ).toEqual([{ name: "large.bin", size: 51 * 1024 * 1024 }]);
385 } finally {
386 await browser.close();
387 }
388 } finally {
389 await pool.close();
390 await desktop.close();
391 }
392 } finally {
393 NodeFS.rmSync(directory, { recursive: true, force: true });
394 }
395 });
396});