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

ServerBrowserContexts.test.ts

296 lines11.7 KB

1import * as NodeEvents from "node:events";
2​
3import { INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts";
4import { chromium, type Browser, type BrowserContext, type BrowserType } from "playwright-core";
5import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
6​
7import { ServerBrowserContexts } from "./ServerBrowserContexts.ts";
8​
9const launches = vi.hoisted(() => ({
10 launch: vi.fn<BrowserType["launch"]>(),
11 persistent: vi.fn<BrowserType["launchPersistentContext"]>(),
12 mkdir: vi.fn().mockResolvedValue(undefined),
13 rm: vi.fn().mockResolvedValue(undefined),
14}));
15vi.spyOn(chromium, "launch").mockImplementation(launches.launch);
16vi.spyOn(chromium, "launchPersistentContext").mockImplementation(launches.persistent);
17vi.mock("node:fs/promises", () => ({ mkdir: launches.mkdir, rm: launches.rm }));
18​
19const makeContext = () => {
20 const events = new NodeEvents.EventEmitter();
21 let closed = false;
22 return {
23 on: vi.fn((event: string, listener: () => void) => events.on(event, listener)),
24 pages: vi.fn(() => []),
25 close: vi.fn(async () => {
26 if (!closed) {
27 closed = true;
28 events.emit("close");
29 }
30 }),
31 };
32};
33​
34const makeBrowser = () => {
35 const events = new NodeEvents.EventEmitter();
36 const contexts: ReturnType<typeof makeContext>[] = [];
37 return {
38 contexts,
39 on: vi.fn((event: string, listener: () => void) => events.on(event, listener)),
40 newContext: vi.fn(async () => {
41 const context = makeContext();
42 contexts.push(context);
43 return context as unknown as BrowserContext;
44 }),
45 close: vi.fn(async () => {
46 for (const context of contexts) await context.close();
47 events.emit("disconnected");
48 }),
49 };
50};
51​
52const options = () => ({
53 profilesDir: "/test/profiles",
54 executable: vi.fn(async () => "/test/chromium"),
55 env: {},
56});
57​
58const withLauncher = () => {
59 const release = vi.fn(async () => {});
60 return {
61 release,
62 configuration: {
63 ...options(),
64 launcher: vi.fn(async (executable: string) => ({ path: `${executable}-launcher`, release })),
65 },
66 };
67};
68​
69beforeEach(() => {
70 launches.launch.mockReset();
71 launches.persistent.mockReset();
72 launches.mkdir.mockClear();
73 launches.rm.mockClear();
74});
75​
76describe("ServerBrowserContexts", () => {
77 it("lazily shares one browser across concurrent isolated sessions and reuses each context", async () => {
78 const browser = makeBrowser();
79 const launch = Promise.withResolvers<Browser>();
80 const started = Promise.withResolvers<void>();
81 launches.launch.mockImplementation(() => {
82 started.resolve();
83 return launch.promise;
84 });
85 const { configuration, release } = withLauncher();
86 const pool = new ServerBrowserContexts(configuration);
87 expect(configuration.executable).not.toHaveBeenCalled();
88 const first = pool.contextFor("default", "agent-a");
89 const again = pool.contextFor("default", "agent-a");
90 const second = pool.contextFor("default", "agent-b");
91 const incognito = pool.contextFor(INCOGNITO_BROWSER_PROFILE_ID);
92 await started.promise;
93 // Playwright may retry the same path until the launch settles.
94 expect(release).not.toHaveBeenCalled();
95 launch.resolve(browser as unknown as Browser);
96 const [a, reused, b, privateContext] = await Promise.all([first, again, second, incognito]);
97 expect(release).toHaveBeenCalledTimes(1);
98 expect(a).toBe(reused);
99 expect(new Set([a, b, privateContext]).size).toBe(3);
100 expect(launches.launch).toHaveBeenCalledExactlyOnceWith(
101 expect.objectContaining({ executablePath: "/test/chromium-launcher" }),
102 );
103 expect(launches.persistent).not.toHaveBeenCalled();
104 expect(browser.newContext).toHaveBeenCalledWith({
105 viewport: { width: 1280, height: 800 },
106 deviceScaleFactor: 2,
107 });
108 await pool.close();
109 expect(browser.close).toHaveBeenCalledTimes(1);
110 for (const context of browser.contexts) expect(context.close).toHaveBeenCalled();
111 });
112​
113 it("keeps human profiles persistent without sharing their storage with agents", async () => {
114 const human = makeContext();
115 const browser = makeBrowser();
116 launches.persistent.mockResolvedValue(human as unknown as BrowserContext);
117 launches.launch.mockResolvedValue(browser as unknown as Browser);
118 const { configuration, release } = withLauncher();
119 const pool = new ServerBrowserContexts(configuration);
120 const persistent = await pool.contextFor("work/team");
121 expect(await pool.contextFor("work/team")).toBe(persistent);
122 expect(await pool.contextFor("work/team", "agent")).not.toBe(persistent);
123 expect(launches.persistent).toHaveBeenCalledExactlyOnceWith(
124 "/test/profiles/work%2Fteam",
125 expect.objectContaining({ chromiumSandbox: true, executablePath: "/test/chromium-launcher" }),
126 );
127 expect(release).toHaveBeenCalledTimes(2);
128 expect(launches.mkdir).toHaveBeenCalledWith("/test/profiles/work%2Fteam", { recursive: true });
129 await pool.close();
130 expect(human.close).toHaveBeenCalledTimes(1);
131 });
132​
133 it("diagnoses a launcher failure against the real executable", async () => {
134 const diagnosed = new Error("diagnosed");
135 const diagnose = vi.fn(async () => diagnosed);
136 const pool = new ServerBrowserContexts({
137 ...options(),
138 diagnose,
139 launcher: vi.fn(async () => {
140 throw new Error("EACCES");
141 }),
142 });
143 await expect(pool.contextFor("default", "agent")).rejects.toBe(diagnosed);
144 expect(diagnose).toHaveBeenCalledExactlyOnceWith("/test/chromium", expect.any(Error));
145 expect(launches.launch).not.toHaveBeenCalled();
146 });
147​
148 it("creates no launcher for a profile whose storage cannot be created", async () => {
149 launches.mkdir.mockRejectedValueOnce(new Error("EACCES"));
150 const { configuration } = withLauncher();
151 const pool = new ServerBrowserContexts(configuration);
152 await expect(pool.contextFor("work/team")).rejects.toThrow("EACCES");
153 expect(configuration.launcher).not.toHaveBeenCalled();
154 });
155​
156 it("clears a profile by closing its open context before deleting its storage", async () => {
157 const human = makeContext();
158 const browser = makeBrowser();
159 launches.persistent.mockResolvedValue(human as unknown as BrowserContext);
160 launches.launch.mockResolvedValue(browser as unknown as Browser);
161 const onContextClose = vi.fn();
162 const pool = new ServerBrowserContexts({ ...options(), onContextClose });
163 const persistent = await pool.contextFor("work/team");
164 const agent = await pool.contextFor("work/team", "agent");
165 launches.rm.mockImplementationOnce(async () => {
166 expect(human.close).toHaveBeenCalledTimes(1);
167 });
168 await pool.clearProfile("work/team");
169 expect(onContextClose).toHaveBeenCalledExactlyOnceWith(persistent);
170 expect(launches.rm).toHaveBeenCalledExactlyOnceWith("/test/profiles/work%2Fteam", {
171 recursive: true,
172 force: true,
173 });
174 expect(await pool.contextFor("work/team", "agent")).toBe(agent);
175 expect(browser.contexts[0]?.close).not.toHaveBeenCalled();
176 launches.persistent.mockResolvedValue(makeContext() as unknown as BrowserContext);
177 expect(await pool.contextFor("work/team")).not.toBe(persistent);
178 await pool.clearProfile("never-opened");
179 expect(launches.rm).toHaveBeenLastCalledWith("/test/profiles/never-opened", {
180 recursive: true,
181 force: true,
182 });
183 await pool.close();
184 });
185​
186 it("waits for the context to close when the same profile is cleared concurrently", async () => {
187 const human = makeContext();
188 const closed = Promise.withResolvers<void>();
189 human.close.mockImplementation(async () => closed.promise);
190 launches.persistent.mockResolvedValue(human as unknown as BrowserContext);
191 const pool = new ServerBrowserContexts(options());
192 await pool.contextFor("work/team");
193​
194 const first = pool.clearProfile("work/team");
195 const second = pool.clearProfile("work/team");
196 const deletionsBeforeClose = launches.rm.mock.calls.length;
197 closed.resolve();
198 await Promise.all([first, second]);
199​
200 expect(deletionsBeforeClose).toBe(0);
201 expect(human.close).toHaveBeenCalledTimes(1);
202 expect(launches.rm).toHaveBeenCalledExactlyOnceWith("/test/profiles/work%2Fteam", {
203 recursive: true,
204 force: true,
205 });
206 await pool.close();
207 });
208​
209 it("opens a profile requested during its clear only after the storage is deleted", async () => {
210 launches.persistent.mockImplementation(async () => makeContext() as unknown as BrowserContext);
211 const configuration = options();
212 const pool = new ServerBrowserContexts(configuration);
213 await pool.contextFor("work/team");
214 const removing = Promise.withResolvers<void>();
215 const removed = Promise.withResolvers<void>();
216 let deleted = false;
217 launches.rm.mockImplementationOnce(async () => {
218 removing.resolve();
219 await removed.promise;
220 deleted = true;
221 });
222 const launchedAfterDelete: Array<boolean> = [];
223 configuration.executable.mockImplementation(async () => {
224 launchedAfterDelete.push(deleted);
225 return "/test/chromium";
226 });
227 const clearing = pool.clearProfile("work/team");
228 const reopening = pool.contextFor("work/team");
229 await removing.promise;
230 removed.resolve();
231 await Promise.all([clearing, reopening]);
232 expect(launchedAfterDelete).toEqual([true]);
233 await pool.close();
234 });
235​
236 it.each([undefined, "default"])(
237 "never retries a failed %s launch with the sandbox disabled",
238 async (profile) => {
239 const launch = profile ? launches.persistent : launches.launch;
240 launch.mockRejectedValue(new Error("sandbox unavailable"));
241 const pool = new ServerBrowserContexts(options());
242 await expect(pool.contextFor(profile ?? INCOGNITO_BROWSER_PROFILE_ID)).rejects.toThrow(
243 "sandbox unavailable",
244 );
245 expect(launch).toHaveBeenCalledTimes(1);
246 expect(
247 profile ? launches.persistent.mock.calls[0]?.[1] : launches.launch.mock.calls[0]?.[0],
248 ).toMatchObject({ chromiumSandbox: true });
249 await pool.close();
250 },
251 );
252​
253 it("allows only an explicit sandbox opt-out", async () => {
254 const browser = makeBrowser();
255 launches.launch.mockResolvedValue(browser as unknown as Browser);
256 const pool = new ServerBrowserContexts({
257 ...options(),
258 env: { T3CODE_SERVER_BROWSER_SANDBOX: "0" },
259 });
260 await pool.contextFor(INCOGNITO_BROWSER_PROFILE_ID);
261 expect(launches.launch).toHaveBeenCalledWith(
262 expect.objectContaining({ chromiumSandbox: false }),
263 );
264 await pool.close();
265 });
266​
267 it("retries a failed startup on a later request with sandboxing still enabled", async () => {
268 const browser = makeBrowser();
269 launches.launch
270 .mockRejectedValueOnce(new Error("executable unavailable"))
271 .mockResolvedValue(browser as unknown as Browser);
272 const pool = new ServerBrowserContexts(options());
273 await expect(pool.contextFor("default", "agent")).rejects.toThrow("executable unavailable");
274 await pool.contextFor("default", "agent");
275 expect(launches.launch).toHaveBeenCalledTimes(2);
276 expect(launches.launch).toHaveBeenLastCalledWith(
277 expect.objectContaining({ chromiumSandbox: true }),
278 );
279 await pool.close();
280 });
281​
282 it("cleans up a browser whose launch finishes during shutdown and rejects future work", async () => {
283 const browser = makeBrowser();
284 const launch = Promise.withResolvers<Browser>();
285 launches.launch.mockReturnValue(launch.promise);
286 const pool = new ServerBrowserContexts(options());
287 const opening = expect(pool.contextFor("default", "agent")).rejects.toThrow("closed");
288 const closing = pool.close();
289 launch.resolve(browser as unknown as Browser);
290 await Promise.all([opening, closing]);
291 await expect(pool.contextFor("default", "agent")).rejects.toThrow("closed");
292 await pool.close();
293 expect(browser.close).toHaveBeenCalledTimes(1);
294 expect(browser.contexts[0]?.close).toHaveBeenCalled();
295 });
296});