Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Owns Playwright resources outside the Effect runtime.
2import { INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts";
3import { constVoid } from "effect/Function";
4import * as NodeFSP from "node:fs/promises";
5import * as NodeModule from "node:module";
6import * as NodePath from "node:path";
7import type { Browser, BrowserContext } from "playwright-core";
8
9import { sandboxDisabled } from "./PreviewBrowserHost.ts";
10
11// Playwright needs its files on disk. createRequire also resolves it from a Node SEA executable.
12const requirePlaywright = NodeModule.createRequire(import.meta.url);
13const loadPlaywright = () =>
14 requirePlaywright("playwright-core") as typeof import("playwright-core");
15
16interface Options {
17 readonly profilesDir: string;
18 /** The shared headless browser's executable, installing it on first use. */
19 readonly executable: () => Promise<string>;
20 /** Replaces a failed launch's error with the host setup it is missing, if any. */
21 readonly diagnose?: (executable: string, cause: unknown) => Promise<unknown>;
22 readonly env?: NodeJS.ProcessEnv;
23 readonly onContextClose?: (context: BrowserContext) => void;
24}
25
26/** Persistent human profiles keep their storage; isolated agents share a browser, never a context. */
27export class ServerBrowserContexts {
28 private readonly options: Options;
29 private readonly contexts = new Map<string, Promise<BrowserContext>>();
30 /** Profile clears in progress; a context for that profile opens after its storage is gone. */
31 private readonly clearing = new Map<string, Promise<void>>();
32 private browser: Promise<Browser> | undefined;
33 private closing: Promise<void> | undefined;
34
35 constructor(options: Options) {
36 this.options = options;
37 }
38
39 private async launchOptions() {
40 const executablePath = await this.options.executable();
41 const env = this.options.env ?? process.env;
42 return {
43 executablePath,
44 env,
45 args: ["--disable-gpu", "--force-device-scale-factor=2"],
46 headless: true,
47 // Only an explicit operator opt-out disables sandboxing. Launch errors never do.
48 chromiumSandbox: !sandboxDisabled(env),
49 };
50 }
51
52 private async launch<A>(options: { readonly executablePath: string }, start: () => Promise<A>) {
53 try {
54 return await start();
55 } catch (cause) {
56 throw (await this.options.diagnose?.(options.executablePath, cause)) ?? cause;
57 }
58 }
59
60 private sharedBrowser() {
61 if (!this.browser) {
62 const launched = this.launchOptions().then(async (options) => {
63 const { chromium } = loadPlaywright();
64 const browser = await this.launch(options, () => chromium.launch(options));
65 browser.on("disconnected", () => {
66 if (this.browser === launched) this.browser = undefined;
67 });
68 return browser;
69 });
70 this.browser = launched;
71 void launched.catch(() => {
72 if (this.browser === launched) this.browser = undefined;
73 });
74 }
75 return this.browser;
76 }
77
78 contextFor(profileId: string, isolationKey?: string): Promise<BrowserContext> {
79 if (this.closing) return Promise.reject(new Error("The preview browser is closed."));
80 const key = JSON.stringify([profileId, isolationKey ?? null]);
81 const cached = this.contexts.get(key);
82 if (cached) return cached;
83 const cleared = this.clearing.get(key)?.catch(constVoid) ?? Promise.resolve();
84 const pending = cleared
85 .then(() => this.createContext(profileId, isolationKey))
86 .then(async (context) => {
87 context.on("close", () => {
88 if (this.contexts.get(key) === pending) this.contexts.delete(key);
89 this.options.onContextClose?.(context);
90 });
91 for (const page of context.pages()) await page.close().catch(constVoid);
92 if (this.closing) {
93 await context.close().catch(constVoid);
94 throw new Error("The preview browser is closed.");
95 }
96 return context;
97 });
98 this.contexts.set(key, pending);
99 void pending.catch(() => {
100 if (this.contexts.get(key) === pending) this.contexts.delete(key);
101 });
102 return pending;
103 }
104
105 private async createContext(profileId: string, isolationKey?: string) {
106 const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 };
107 if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) {
108 const browser = await this.sharedBrowser();
109 return browser.newContext(contextOptions);
110 }
111 const directory = this.profileDirectory(profileId);
112 const options = await this.launchOptions();
113 const { chromium } = loadPlaywright();
114 await NodeFSP.mkdir(directory, { recursive: true });
115 return this.launch(options, () =>
116 chromium.launchPersistentContext(directory, { ...options, ...contextOptions }),
117 );
118 }
119
120 private profileDirectory(profileId: string) {
121 const encoded = encodeURIComponent(profileId);
122 return NodePath.join(
123 this.options.profilesDir,
124 profileId === "." || profileId === ".." ? encoded.replaceAll(".", "%2E") : encoded,
125 );
126 }
127
128 /** A throwaway page in the shared browser, for work that must not touch a tab's own storage. */
129 async scratchPage() {
130 if (this.closing) throw new Error("The preview browser is closed.");
131 const context = await (await this.sharedBrowser()).newContext();
132 const page = await context.newPage();
133 page.once("close", () => void context.close().catch(constVoid));
134 return page;
135 }
136
137 /**
138 * Drives a page the desktop app renders, through the CDP endpoint its relay
139 * serves. The page keeps the desktop's storage, size, and window.
140 */
141 async connectDesktopPage(endpoint: string) {
142 const { chromium } = loadPlaywright();
143 const browser = await chromium.connectOverCDP(endpoint, { timeout: 15_000 });
144 const page = browser.contexts().flatMap((context) => context.pages())[0];
145 if (!page) {
146 await browser.close().catch(constVoid);
147 throw new Error("The desktop tab has no page.");
148 }
149 return { browser, page };
150 }
151
152 /** Closes a human profile's persistent context, ending its tabs, then deletes its storage. */
153 async clearProfile(profileId: string) {
154 if (profileId === INCOGNITO_BROWSER_PROFILE_ID) return;
155 const key = JSON.stringify([profileId, null]);
156 const clearing = (async () => {
157 const pending = this.contexts.get(key);
158 if (pending) {
159 this.contexts.delete(key);
160 const context = await pending.catch(() => undefined);
161 await context?.close();
162 }
163 await NodeFSP.rm(this.profileDirectory(profileId), { recursive: true, force: true });
164 })();
165 this.clearing.set(key, clearing);
166 try {
167 await clearing;
168 } finally {
169 if (this.clearing.get(key) === clearing) this.clearing.delete(key);
170 }
171 }
172
173 close() {
174 this.closing ??= this.dispose();
175 return this.closing;
176 }
177
178 private async dispose() {
179 await Promise.allSettled(
180 [...this.contexts.values()].map(async (pending) => (await pending).close()),
181 );
182 const browser = await this.browser?.catch(() => undefined);
183 await browser?.close().catch(constVoid);
184 this.contexts.clear();
185 }
186}