The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 03:15 UTC
perf(server): the headless browser closes after five idle minutes (517 MiB → 1.6 MiB median) (#30306)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Andrei committed
Nov 6, 2026 at 12:23 UTC
93dbf53db31387e18866ac64bf4488e8994ad86d
3 files changed
+78
-8
apps/server/src/preview/ServerBrowser.ts
+1
@@ -501,6 +501,7 @@ const make = Effect.gen(function* () {
501
502
const contexts = new ServerBrowserContexts({
503
profilesDir: NodePath.join(config.stateDir, "server-browser", "profiles"),
504
+ idleBrowserMs: 5 * 60_000,
505
executable: () => runPromise(previewBrowser.executable),
506
// An agent scope keeps Chrome out of the server's memory protection and OOM score.
507
launcher: async (executable) => {
apps/server/src/preview/ServerBrowserContexts.test.ts
+38
-4
@@ -22,6 +22,8 @@ const makeContext = () => {
22
return {
23
on: vi.fn((event: string, listener: () => void) => events.on(event, listener)),
24
pages: vi.fn(() => []),
25
+ newPage: vi.fn(async () => ({ once: vi.fn() })),
26
+ isClosed: () => closed,
27
close: vi.fn(async () => {
28
if (!closed) {
29
closed = true;
@@ -35,7 +37,8 @@ const makeBrowser = () => {
37
const events = new NodeEvents.EventEmitter();
38
const contexts: ReturnType<typeof makeContext>[] = [];
39
return {
38
- contexts,
40
+ created: contexts,
41
+ contexts: () => contexts.filter((context) => !context.isClosed()),
42
on: vi.fn((event: string, listener: () => void) => events.on(event, listener)),
43
newContext: vi.fn(async () => {
44
const context = makeContext();
@@ -74,6 +77,37 @@ beforeEach(() => {
77
});
78
79
describe("ServerBrowserContexts", () => {
80
+ it("closes the shared browser only after it holds no context for the idle period", async () => {
81
+ vi.useFakeTimers();
82
+ try {
83
+ const first = makeBrowser();
84
+ const second = makeBrowser();
85
+ launches.launch
86
+ .mockResolvedValueOnce(first as unknown as Browser)
87
+ .mockResolvedValueOnce(second as unknown as Browser);
88
+ const pool = new ServerBrowserContexts({ ...options(), idleBrowserMs: 10 });
89
+ const agent = await pool.contextFor("default", "agent");
90
+ await pool.scratchPage();
91
+ await agent.close();
92
+ await vi.advanceTimersByTimeAsync(10);
93
+ expect(first.close).not.toHaveBeenCalled();
94
+ await first.created[1]!.close();
95
+ await vi.advanceTimersByTimeAsync(9);
96
+ const next = await pool.contextFor("default", "next");
97
+ await vi.advanceTimersByTimeAsync(10);
98
+ expect(first.close).not.toHaveBeenCalled();
99
+ await next.close();
100
+ await vi.advanceTimersByTimeAsync(10);
101
+ expect(first.close).toHaveBeenCalledOnce();
102
+ await pool.contextFor("default", "later");
103
+ expect(launches.launch).toHaveBeenCalledTimes(2);
104
+ expect(second.newContext).toHaveBeenCalledOnce();
105
+ await pool.close();
106
+ } finally {
107
+ vi.useRealTimers();
108
+ }
109
+ });
110
+
111
it("lazily shares one browser across concurrent isolated sessions and reuses each context", async () => {
112
const browser = makeBrowser();
113
const launch = Promise.withResolvers<Browser>();
@@ -107,7 +141,7 @@ describe("ServerBrowserContexts", () => {
141
});
142
await pool.close();
143
expect(browser.close).toHaveBeenCalledTimes(1);
110
- for (const context of browser.contexts) expect(context.close).toHaveBeenCalled();
144
+ for (const context of browser.created) expect(context.close).toHaveBeenCalled();
145
});
146
147
it("keeps human profiles persistent without sharing their storage with agents", async () => {
@@ -172,7 +206,7 @@ describe("ServerBrowserContexts", () => {
206
force: true,
207
});
208
expect(await pool.contextFor("work/team", "agent")).toBe(agent);
175
- expect(browser.contexts[0]?.close).not.toHaveBeenCalled();
209
+ expect(browser.created[0]?.close).not.toHaveBeenCalled();
210
launches.persistent.mockResolvedValue(makeContext() as unknown as BrowserContext);
211
expect(await pool.contextFor("work/team")).not.toBe(persistent);
212
await pool.clearProfile("never-opened");
@@ -291,6 +325,6 @@ describe("ServerBrowserContexts", () => {
325
await expect(pool.contextFor("default", "agent")).rejects.toThrow("closed");
326
await pool.close();
327
expect(browser.close).toHaveBeenCalledTimes(1);
294
- expect(browser.contexts[0]?.close).toHaveBeenCalled();
328
+ expect(browser.created[0]?.close).toHaveBeenCalled();
329
});
330
});
apps/server/src/preview/ServerBrowserContexts.ts
+39
-4
@@ -1,4 +1,4 @@
1
-// @effect-diagnostics nodeBuiltinImport:off - Owns Playwright resources outside the Effect runtime.
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";
@@ -26,6 +26,8 @@ interface Options {
26
) => Promise<{ readonly path: string; readonly release: () => Promise<void> } | undefined>;
27
readonly diagnose?: (executable: string, cause: unknown) => Promise<unknown>;
28
readonly env?: NodeJS.ProcessEnv;
29
+ /** Closes the shared browser once it has held no context for this long. */
30
+ readonly idleBrowserMs?: number;
31
readonly onContextClose?: (context: BrowserContext) => void;
32
}
33
@@ -80,6 +82,8 @@ export class ServerBrowserContexts {
82
private readonly clearing = new Map<string, Promise<void>>();
83
private browser: Promise<Browser> | undefined;
84
private closing: Promise<void> | undefined;
85
+ private idleTimer: ReturnType<typeof setTimeout> | undefined;
86
+ private pendingSharedContexts = 0;
87
88
constructor(options: Options) {
89
this.options = options;
@@ -136,6 +140,37 @@ export class ServerBrowserContexts {
140
return this.browser;
141
}
142
143
+ private async sharedContext(options?: Parameters<Browser["newContext"]>[0]) {
144
+ clearTimeout(this.idleTimer);
145
+ this.pendingSharedContexts++;
146
+ const launched = this.sharedBrowser();
147
+ try {
148
+ const context = await (await launched).newContext(options);
149
+ context.on("close", () => this.retireWhenIdle(launched));
150
+ return context;
151
+ } finally {
152
+ this.pendingSharedContexts--;
153
+ this.retireWhenIdle(launched);
154
+ }
155
+ }
156
+
157
+ private retireWhenIdle(launched: Promise<Browser>) {
158
+ const delay = this.options.idleBrowserMs;
159
+ if (delay === undefined || this.closing || this.pendingSharedContexts > 0) return;
160
+ clearTimeout(this.idleTimer);
161
+ this.idleTimer = setTimeout(() => void this.retire(launched), delay);
162
+ this.idleTimer.unref();
163
+ }
164
+
165
+ private async retire(launched: Promise<Browser>) {
166
+ const browser = await launched.catch(() => undefined);
167
+ if (!browser || this.browser !== launched || this.pendingSharedContexts > 0) return;
168
+ if (browser.contexts().length > 0) return;
169
+ // Cleared first, so a request during the close launches a fresh browser.
170
+ this.browser = undefined;
171
+ await browser.close().catch(constVoid);
172
+ }
173
+
174
contextFor(profileId: string, isolationKey?: string): Promise<BrowserContext> {
175
if (this.closing) return Promise.reject(new Error("The preview browser is closed."));
176
const key = JSON.stringify([profileId, isolationKey ?? null]);
@@ -166,8 +201,7 @@ export class ServerBrowserContexts {
201
private async createContext(profileId: string, isolationKey?: string) {
202
const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 };
203
if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) {
169
- const browser = await this.sharedBrowser();
170
- return browser.newContext(contextOptions);
204
+ return this.sharedContext(contextOptions);
205
}
206
const directory = this.profileDirectory(profileId);
207
await NodeFSP.mkdir(directory, { recursive: true });
@@ -192,7 +226,7 @@ export class ServerBrowserContexts {
226
227
async scratchPage() {
228
if (this.closing) throw new Error("The preview browser is closed.");
195
- const context = await (await this.sharedBrowser()).newContext();
229
+ const context = await this.sharedContext();
230
const page = await context.newPage();
231
page.once("close", () => void context.close().catch(constVoid));
232
return page;
@@ -237,6 +271,7 @@ export class ServerBrowserContexts {
271
}
272
273
private async dispose() {
274
+ clearTimeout(this.idleTimer);
275
await Promise.allSettled(
276
[...this.contexts.values()].map(async (pending) => (await pending).close()),
277
);