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

ServerBrowserContexts.test.ts

273 lines10.9 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("opens a profile requested during its clear only after the storage is deleted", async () => {
187 launches.persistent.mockImplementation(async () => makeContext() as unknown as BrowserContext);
188 const configuration = options();
189 const pool = new ServerBrowserContexts(configuration);
190 await pool.contextFor("work/team");
191 const removing = Promise.withResolvers<void>();
192 const removed = Promise.withResolvers<void>();
193 let deleted = false;
194 launches.rm.mockImplementationOnce(async () => {
195 removing.resolve();
196 await removed.promise;
197 deleted = true;
198 });
199 const launchedAfterDelete: Array<boolean> = [];
200 configuration.executable.mockImplementation(async () => {
201 launchedAfterDelete.push(deleted);
202 return "/test/chromium";
203 });
204 const clearing = pool.clearProfile("work/team");
205 const reopening = pool.contextFor("work/team");
206 await removing.promise;
207 removed.resolve();
208 await Promise.all([clearing, reopening]);
209 expect(launchedAfterDelete).toEqual([true]);
210 await pool.close();
211 });
212​
213 it.each([undefined, "default"])(
214 "never retries a failed %s launch with the sandbox disabled",
215 async (profile) => {
216 const launch = profile ? launches.persistent : launches.launch;
217 launch.mockRejectedValue(new Error("sandbox unavailable"));
218 const pool = new ServerBrowserContexts(options());
219 await expect(pool.contextFor(profile ?? INCOGNITO_BROWSER_PROFILE_ID)).rejects.toThrow(
220 "sandbox unavailable",
221 );
222 expect(launch).toHaveBeenCalledTimes(1);
223 expect(
224 profile ? launches.persistent.mock.calls[0]?.[1] : launches.launch.mock.calls[0]?.[0],
225 ).toMatchObject({ chromiumSandbox: true });
226 await pool.close();
227 },
228 );
229​
230 it("allows only an explicit sandbox opt-out", async () => {
231 const browser = makeBrowser();
232 launches.launch.mockResolvedValue(browser as unknown as Browser);
233 const pool = new ServerBrowserContexts({
234 ...options(),
235 env: { T3CODE_SERVER_BROWSER_SANDBOX: "0" },
236 });
237 await pool.contextFor(INCOGNITO_BROWSER_PROFILE_ID);
238 expect(launches.launch).toHaveBeenCalledWith(
239 expect.objectContaining({ chromiumSandbox: false }),
240 );
241 await pool.close();
242 });
243​
244 it("retries a failed startup on a later request with sandboxing still enabled", async () => {
245 const browser = makeBrowser();
246 launches.launch
247 .mockRejectedValueOnce(new Error("executable unavailable"))
248 .mockResolvedValue(browser as unknown as Browser);
249 const pool = new ServerBrowserContexts(options());
250 await expect(pool.contextFor("default", "agent")).rejects.toThrow("executable unavailable");
251 await pool.contextFor("default", "agent");
252 expect(launches.launch).toHaveBeenCalledTimes(2);
253 expect(launches.launch).toHaveBeenLastCalledWith(
254 expect.objectContaining({ chromiumSandbox: true }),
255 );
256 await pool.close();
257 });
258​
259 it("cleans up a browser whose launch finishes during shutdown and rejects future work", async () => {
260 const browser = makeBrowser();
261 const launch = Promise.withResolvers<Browser>();
262 launches.launch.mockReturnValue(launch.promise);
263 const pool = new ServerBrowserContexts(options());
264 const opening = expect(pool.contextFor("default", "agent")).rejects.toThrow("closed");
265 const closing = pool.close();
266 launch.resolve(browser as unknown as Browser);
267 await Promise.all([opening, closing]);
268 await expect(pool.contextFor("default", "agent")).rejects.toThrow("closed");
269 await pool.close();
270 expect(browser.close).toHaveBeenCalledTimes(1);
271 expect(browser.contexts[0]?.close).toHaveBeenCalled();
272 });
273});