The best way to control Claude Code, Codex and more from any computer or phone

main
ts 351 lines 13.3 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off globalTimers:off -- Owns Playwright resources and their idle timer outside the Effect runtime.
2 import { INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts";
3 import { constVoid } from "effect/Function";
4 import * as NodeFSP from "node:fs/promises";
5 import * as NodeModule from "node:module";
6 import * as NodeOS from "node:os";
7 import * as NodePath from "node:path";
8 import type { Browser, BrowserContext, CDPSession } from "playwright-core";
9
10 import { sandboxDisabled } from "./PreviewBrowserHost.ts";
11
12 // Playwright needs its files on disk. createRequire also resolves it from a Node SEA executable.
13 const requirePlaywright = NodeModule.createRequire(import.meta.url);
14 const loadPlaywright = () =>
15 requirePlaywright("playwright-core") as typeof import("playwright-core");
16
17 const BADGE_STUB = `if (typeof WorkerNavigator === "function") for (const name of ["setAppBadge", "clearAppBadge"]) WorkerNavigator.prototype[name] = () => Promise.resolve();`;
18
19 interface CdpSession {
20 send(method: string, params?: object): Promise<unknown>;
21 createChildSession(...args: ReadonlyArray<unknown>): CdpSession;
22 }
23
24 // The headless shell binds no BadgeService for service workers and kills the renderer of a
25 // worker that calls navigator.setAppBadge. Playwright resumes each worker itself, so the stub
26 // can only go in ahead of that resume through its in-process session; without it nothing is stubbed.
27 const stubWorkerBadges = (client: Browser | BrowserContext) => {
28 const { _connection: connection } = client as unknown as {
29 readonly _connection?: {
30 readonly toImpl?: (
31 client: unknown,
32 ) =>
33 | { readonly _session?: CdpSession; readonly _browser?: { readonly _session?: CdpSession } }
34 | undefined;
35 };
36 };
37 const impl = connection?.toImpl?.(client);
38 const root = impl?._browser?._session ?? impl?._session;
39 if (!root) return;
40 const createChildSession = root.createChildSession.bind(root);
41 root.createChildSession = (...args) => {
42 const session = createChildSession(...args);
43 const send = session.send.bind(session);
44 session.send = (method, params) => {
45 if (method === "Runtime.runIfWaitingForDebugger") {
46 void send("Runtime.evaluate", { expression: BADGE_STUB }).catch(constVoid);
47 }
48 return send(method, params);
49 };
50 return session;
51 };
52 };
53
54 interface Options {
55 readonly profilesDir: string;
56 readonly executable: () => Promise<string>;
57 /**
58 * A path that starts `executable`, such as one that moves Chrome out of the server's cgroup.
59 * Released after the whole launch call, since Playwright retries the same path after a glibc race.
60 */
61 readonly launcher?: (
62 executable: string,
63 ) => Promise<{ readonly path: string; readonly release: () => Promise<void> } | undefined>;
64 readonly diagnose?: (executable: string, cause: unknown) => Promise<unknown>;
65 readonly env?: NodeJS.ProcessEnv;
66 /** Names Chrome in the browser's own user agent, which is all a service worker ever sends. */
67 readonly chrome: { readonly version: string; readonly platform: NodeJS.Platform };
68 /** Closes the shared browser once it has held no context for this long. */
69 readonly idleBrowserMs?: number;
70 readonly onContextClose?: (context: BrowserContext) => void;
71 }
72
73 const UA_PLATFORMS: Partial<Record<NodeJS.Platform, string>> = {
74 darwin: "macOS",
75 linux: "Linux",
76 win32: "Windows",
77 };
78
79 // Chrome froze its user agent apart from the major version.
80 const UA_SYSTEMS: Partial<Record<NodeJS.Platform, string>> = {
81 darwin: "Macintosh; Intel Mac OS X 10_15_7",
82 linux: "X11; Linux x86_64",
83 win32: "Windows NT 10.0; Win64; x64",
84 };
85
86 const chromeToken = (major: string) => `Chrome/${major}.0.0.0`;
87
88 const chromeUserAgent = (chrome: Options["chrome"]) => {
89 const major = /^\d+/.exec(chrome.version)?.[0];
90 const system = UA_SYSTEMS[chrome.platform];
91 return major && system
92 ? `Mozilla/5.0 (${system}) AppleWebKit/537.36 (KHTML, like Gecko) ${chromeToken(major)} Safari/537.36`
93 : null;
94 };
95
96 /** Change user agent and Sec-CH-UA together; sites block mismatches. */
97 const chromeIdentity = (
98 browser: { readonly product: string; readonly userAgent: string },
99 host: { readonly platform: NodeJS.Platform; readonly arch: string; readonly release: string },
100 ) => {
101 // A launch that already named Chrome in the user agent still reports the headless product.
102 const version = /^(?:Headless)?Chrome\/((\d+)[\d.]*)/.exec(browser.product);
103 const fullVersion = version?.[1];
104 const major = version?.[2];
105 if (!version || !fullVersion || !major) return null;
106 const brands = (names: (version: string) => string) => [
107 { brand: "Chromium", version: names(major) },
108 { brand: "Google Chrome", version: names(major) },
109 { brand: "Not A(Brand", version: names("99") },
110 ];
111 return {
112 userAgent: browser.userAgent.replace(/HeadlessChrome\/[\d.]+/, chromeToken(major)),
113 userAgentMetadata: {
114 brands: brands((value) => value),
115 fullVersionList: brands((value) => (value === major ? fullVersion : `${value}.0.0.0`)),
116 platform: UA_PLATFORMS[host.platform] ?? "Unknown",
117 platformVersion: host.platform === "linux" ? host.release : "",
118 architecture: host.arch.startsWith("arm") ? "arm" : "x86",
119 bitness: host.arch.endsWith("64") ? "64" : "32",
120 model: "",
121 mobile: false,
122 wow64: false,
123 },
124 };
125 };
126
127 export const presentAsChrome = async (
128 cdp: CDPSession,
129 host: { readonly platform: NodeJS.Platform; readonly arch: string },
130 ) => {
131 const browser = await cdp.send("Browser.getVersion");
132 const identity = chromeIdentity(browser, { ...host, release: NodeOS.release() });
133 if (identity) await cdp.send("Emulation.setUserAgentOverride", identity);
134 };
135
136 export class ServerBrowserContexts {
137 private readonly options: Options;
138 private readonly contexts = new Map<string, Promise<BrowserContext>>();
139 private readonly clearing = new Map<string, Promise<void>>();
140 private browser: Promise<Browser> | undefined;
141 private closing: Promise<void> | undefined;
142 private idleTimer: ReturnType<typeof setTimeout> | undefined;
143 private pendingSharedContexts = 0;
144
145 constructor(options: Options) {
146 this.options = options;
147 }
148
149 private async launchOptions() {
150 const executable = await this.options.executable();
151 const env = this.options.env ?? process.env;
152 // A page's override never reaches its workers, so the browser itself must name Chrome.
153 const userAgent = chromeUserAgent(this.options.chrome);
154 return {
155 executable,
156 env,
157 args: [
158 "--disable-gpu",
159 "--force-device-scale-factor=2",
160 "--disable-blink-features=AutomationControlled",
161 ...(userAgent ? [`--user-agent=${userAgent}`] : []),
162 ],
163 ignoreDefaultArgs: ["--enable-automation"],
164 headless: true,
165 // Only an explicit operator opt-out disables sandboxing. Launch errors never do.
166 chromiumSandbox: !sandboxDisabled(env),
167 };
168 }
169
170 private async launch<A>(executable: string, start: (executablePath: string) => Promise<A>) {
171 let release: (() => Promise<void>) | undefined;
172 try {
173 const launcher = await this.options.launcher?.(executable);
174 release = launcher?.release;
175 return await start(launcher?.path ?? executable);
176 } catch (cause) {
177 throw (await this.options.diagnose?.(executable, cause)) ?? cause;
178 } finally {
179 await release?.().catch(constVoid);
180 }
181 }
182
183 private sharedBrowser() {
184 if (!this.browser) {
185 const launched = this.launchOptions().then(async ({ executable, ...options }) => {
186 const { chromium } = loadPlaywright();
187 const browser = await this.launch(executable, (executablePath) =>
188 chromium.launch({ ...options, executablePath }),
189 );
190 stubWorkerBadges(browser);
191 browser.on("disconnected", () => {
192 if (this.browser === launched) this.browser = undefined;
193 });
194 return browser;
195 });
196 this.browser = launched;
197 void launched.catch(() => {
198 if (this.browser === launched) this.browser = undefined;
199 });
200 }
201 return this.browser;
202 }
203
204 private async sharedContext(options?: Parameters<Browser["newContext"]>[0]) {
205 clearTimeout(this.idleTimer);
206 this.pendingSharedContexts++;
207 const launched = this.sharedBrowser();
208 try {
209 const context = await (await launched).newContext(options);
210 context.on("close", () => this.retireWhenIdle(launched));
211 return context;
212 } finally {
213 this.pendingSharedContexts--;
214 this.retireWhenIdle(launched);
215 }
216 }
217
218 private retireWhenIdle(launched: Promise<Browser>) {
219 const delay = this.options.idleBrowserMs;
220 if (delay === undefined || this.closing || this.pendingSharedContexts > 0) return;
221 clearTimeout(this.idleTimer);
222 this.idleTimer = setTimeout(() => void this.retire(launched), delay);
223 this.idleTimer.unref();
224 }
225
226 private async retire(launched: Promise<Browser>) {
227 const browser = await launched.catch(() => undefined);
228 if (!browser || this.browser !== launched || this.pendingSharedContexts > 0) return;
229 if (browser.contexts().length > 0) return;
230 // Cleared first, so a request during the close launches a fresh browser.
231 this.browser = undefined;
232 await browser.close().catch(constVoid);
233 }
234
235 contextFor(profileId: string, isolationKey?: string): Promise<BrowserContext> {
236 if (this.closing) return Promise.reject(new Error("The preview browser is closed."));
237 const key = JSON.stringify([profileId, isolationKey ?? null]);
238 const cached = this.contexts.get(key);
239 if (cached) return cached;
240 const cleared = this.clearing.get(key)?.catch(constVoid) ?? Promise.resolve();
241 const pending = cleared
242 .then(() => this.createContext(profileId, isolationKey))
243 .then(async (context) => {
244 context.on("close", () => {
245 if (this.contexts.get(key) === pending) this.contexts.delete(key);
246 this.options.onContextClose?.(context);
247 });
248 for (const page of context.pages()) await page.close().catch(constVoid);
249 if (this.closing) {
250 await context.close().catch(constVoid);
251 throw new Error("The preview browser is closed.");
252 }
253 return context;
254 });
255 this.contexts.set(key, pending);
256 void pending.catch(() => {
257 if (this.contexts.get(key) === pending) this.contexts.delete(key);
258 });
259 return pending;
260 }
261
262 private async createContext(profileId: string, isolationKey?: string) {
263 const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 };
264 if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) {
265 return this.sharedContext(contextOptions);
266 }
267 const directory = this.profileDirectory(profileId);
268 await NodeFSP.mkdir(directory, { recursive: true });
269 const { executable, ...options } = await this.launchOptions();
270 const { chromium } = loadPlaywright();
271 const context = await this.launch(executable, (executablePath) =>
272 chromium.launchPersistentContext(directory, {
273 ...options,
274 ...contextOptions,
275 executablePath,
276 }),
277 );
278 stubWorkerBadges(context);
279 return context;
280 }
281
282 private profileDirectory(profileId: string) {
283 const encoded = encodeURIComponent(profileId);
284 return NodePath.join(
285 this.options.profilesDir,
286 profileId === "." || profileId === ".." ? encoded.replaceAll(".", "%2E") : encoded,
287 );
288 }
289
290 async scratchPage() {
291 if (this.closing) throw new Error("The preview browser is closed.");
292 const context = await this.sharedContext();
293 try {
294 const page = await context.newPage();
295 page.once("close", () => void context.close().catch(constVoid));
296 return page;
297 } catch (cause) {
298 await context.close().catch(constVoid);
299 throw cause;
300 }
301 }
302
303 async connectDesktopPage(endpoint: string) {
304 const { chromium } = loadPlaywright();
305 // Only a same-machine desktop backend gets the browser channel, so uploads can pass file paths.
306 const browser = await chromium.connectOverCDP(endpoint, { isLocal: true, timeout: 15_000 });
307 const page = browser.contexts().flatMap((context) => context.pages())[0];
308 if (!page) {
309 await browser.close().catch(constVoid);
310 throw new Error("The desktop tab has no page.");
311 }
312 return { browser, page };
313 }
314
315 async clearProfile(profileId: string) {
316 if (profileId === INCOGNITO_BROWSER_PROFILE_ID) return;
317 const key = JSON.stringify([profileId, null]);
318 const existing = this.clearing.get(key);
319 if (existing) return existing;
320 const clearing = (async () => {
321 const pending = this.contexts.get(key);
322 if (pending) {
323 this.contexts.delete(key);
324 const context = await pending.catch(() => undefined);
325 await context?.close();
326 }
327 await NodeFSP.rm(this.profileDirectory(profileId), { recursive: true, force: true });
328 })();
329 this.clearing.set(key, clearing);
330 try {
331 await clearing;
332 } finally {
333 if (this.clearing.get(key) === clearing) this.clearing.delete(key);
334 }
335 }
336
337 close() {
338 this.closing ??= this.dispose();
339 return this.closing;
340 }
341
342 private async dispose() {
343 clearTimeout(this.idleTimer);
344 await Promise.allSettled(
345 [...this.contexts.values()].map(async (pending) => (await pending).close()),
346 );
347 const browser = await this.browser?.catch(() => undefined);
348 await browser?.close().catch(constVoid);
349 this.contexts.clear();
350 }
351 }