The best way to control Claude Code, Codex and more from any computer or phone
fix(preview): reserve capacity before opening browser tabs (#25028)
Co-authored-by: Alex Southwell <4596216+saphid@users.noreply.github.com> Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>
maria committed
Oct 30, 2026 at 21:45 UTC
52b0ab2d6ff6107a3c42991041302091da28861b
2 files changed
+239
-29
apps/server/src/preview/ServerBrowser.test.ts
+161
@@ -1952,3 +1952,164 @@ it.live("profiles reported by one client survive another client's report", () =>
1952
}),
1953
).pipe(Effect.provide(layer)),
1954
);
1955
+
1956
+it.live.each([
1957
+ { budget: "agent", limit: 8 },
1958
+ { budget: "server", limit: 32 },
1959
+])("opens and popups reserve the $budget budget before session creation", ({ budget, limit }) =>
1960
+ Effect.scoped(
1961
+ Effect.gen(function* () {
1962
+ const { broker, browser, tabId } = yield* ready;
1963
+ const manager = yield* Manager.PreviewManager;
1964
+ const open = (target = scope) =>
1965
+ broker.invoke<PreviewAutomationStatus>({
1966
+ scope: target,
1967
+ operation: "open",
1968
+ input: { reuseExistingTab: false, show: false },
1969
+ });
1970
+ for (let index = 1; index < limit - 3; index++) {
1971
+ yield* open(budget === "agent" ? scope : asSession(`other-${Math.floor(index / 8)}`));
1972
+ }
1973
+
1974
+ const sessionGate = Promise.withResolvers<void>();
1975
+ const launchGate = (contextGate = Promise.withResolvers<void>());
1976
+ const sessionStarted = Promise.withResolvers<void>();
1977
+ const realOpen = manager.open;
1978
+ const delayedOpen = vi.spyOn(manager, "open").mockImplementation((input) =>
1979
+ Effect.promise(() => {
1980
+ sessionStarted.resolve();
1981
+ return sessionGate.promise;
1982
+ }).pipe(Effect.andThen(realOpen(input))),
1983
+ );
1984
+ yield* Effect.addFinalizer(() =>
1985
+ Effect.sync(() => {
1986
+ sessionGate.resolve();
1987
+ launchGate.resolve();
1988
+ delayedOpen.mockRestore();
1989
+ }),
1990
+ );
1991
+ const events = yield* manager.subscribeEvents;
1992
+ const first = yield* open().pipe(Effect.result, Effect.forkScoped);
1993
+ yield* Effect.promise(() => sessionStarted.promise);
1994
+ const popup = makeContext();
1995
+ const resized = Promise.withResolvers<void>();
1996
+ const setViewportSize = popup.page.setViewportSize;
1997
+ popup.page.setViewportSize = vi.fn(async (size) => {
1998
+ await setViewportSize(size);
1999
+ if (size?.width === 900) resized.resolve();
2000
+ });
2001
+ const newCDPSession = popup.newCDPSession;
2002
+ popup.newCDPSession = async (target) => {
2003
+ await launchGate.promise;
2004
+ return newCDPSession(target);
2005
+ };
2006
+ contexts[0]!.page.emit("popup", popup.page);
2007
+ const last = yield* open().pipe(Effect.result, Effect.forkScoped);
2008
+ const overflow = yield* open().pipe(Effect.result, Effect.forkScoped);
2009
+ // The host processes this after the opens, while manager creation is blocked.
2010
+ const reused = yield* broker.invoke<PreviewAutomationStatus>({
2011
+ scope,
2012
+ tabId,
2013
+ operation: "open",
2014
+ input: { show: false },
2015
+ });
2016
+ expect(reused.tabId).toBe(tabId);
2017
+ expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength(
2018
+ limit - 3,
2019
+ );
2020
+
2021
+ sessionGate.resolve();
2022
+ for (let count = 0; count < 3; count++) {
2023
+ let event = yield* PubSub.take(events);
2024
+ while (event.type !== "opened") event = yield* PubSub.take(events);
2025
+ yield* manager.resize({
2026
+ threadId: scope.thread.threadId,
2027
+ tabId: event.tabId,
2028
+ viewport: { _tag: "freeform", width: 900, height: 700 },
2029
+ });
2030
+ }
2031
+ // The same slots must stay reserved after publication, while pages are still opening.
2032
+ const duringLaunch = yield* open().pipe(Effect.result, Effect.forkScoped);
2033
+ const rejectedPopup = makeContext();
2034
+ contexts[0]!.page.emit("popup", rejectedPopup.page);
2035
+ yield* broker.invoke({ scope, tabId, operation: "status", input: {} });
2036
+ launchGate.resolve();
2037
+
2038
+ expect((yield* Fiber.join(first))._tag).toBe("Success");
2039
+ expect((yield* Fiber.join(last))._tag).toBe("Success");
2040
+ for (const fiber of [overflow, duringLaunch]) {
2041
+ expect(yield* Fiber.join(fiber)).toMatchObject({
2042
+ _tag: "Failure",
2043
+ failure: { _tag: "PreviewAutomationControlInterruptedError", reason: "tabLimit" },
2044
+ });
2045
+ }
2046
+ yield* Effect.promise(() => resized.promise);
2047
+ const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
2048
+ for (const session of sessions)
2049
+ yield* browser.attachViewer(viewerInput(session.tabId, false));
2050
+ expect(sessions).toHaveLength(limit);
2051
+ expect(popup.page.isClosed()).toBe(false);
2052
+ expect(rejectedPopup.page.isClosed()).toBe(true);
2053
+ const status = yield* broker.invoke<PreviewAutomationStatus>({
2054
+ scope,
2055
+ tabId,
2056
+ operation: "status",
2057
+ input: {},
2058
+ });
2059
+ expect(status.tabs).toHaveLength(limit);
2060
+ }),
2061
+ ).pipe(Effect.provide(layer)),
2062
+);
2063
+
2064
+it.live("failed session and browser launches release capacity, as does closing a tab", () =>
2065
+ Effect.scoped(
2066
+ Effect.gen(function* () {
2067
+ const { broker, tabId } = yield* ready;
2068
+ const manager = yield* Manager.PreviewManager;
2069
+ const open = broker.invoke<PreviewAutomationStatus>({
2070
+ scope,
2071
+ operation: "open",
2072
+ input: { reuseExistingTab: false, show: false },
2073
+ });
2074
+ for (let count = 1; count < 7; count++) yield* open;
2075
+ const failSession = vi
2076
+ .spyOn(manager, "open")
2077
+ .mockImplementationOnce(() => Effect.die(new Error("session creation failed")));
2078
+ yield* Effect.addFinalizer(() => Effect.sync(() => failSession.mockRestore()));
2079
+ expect(yield* open.pipe(Effect.result)).toMatchObject({ _tag: "Failure" });
2080
+ failSession.mockRestore();
2081
+ const events = yield* manager.subscribeEvents;
2082
+ contextFailure = new Error("Chromium launch failed");
2083
+ expect(yield* open.pipe(Effect.result)).toMatchObject({ _tag: "Failure" });
2084
+ let failedSession = yield* PubSub.take(events);
2085
+ while (failedSession.type !== "opened") failedSession = yield* PubSub.take(events);
2086
+ // A failed launch must not leave a session a viewer can relaunch past the budget.
2087
+ expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength(7);
2088
+ contextFailure = null;
2089
+ expect((yield* open).available).toBe(true);
2090
+ expect(yield* open.pipe(Effect.flip)).toMatchObject({ reason: "tabLimit" });
2091
+ expect(
2092
+ yield* broker
2093
+ .invoke<PreviewAutomationStatus>({
2094
+ scope,
2095
+ tabId: PreviewTabId.make(failedSession.tabId),
2096
+ operation: "open",
2097
+ input: { show: false },
2098
+ })
2099
+ .pipe(Effect.flip),
2100
+ ).toMatchObject({ _tag: "PreviewAutomationTabNotFoundError" });
2101
+ const browser = yield* ServerBrowser.ServerBrowser;
2102
+ expect(
2103
+ yield* browser.attachViewer(viewerInput(failedSession.tabId, false)).pipe(Effect.flip),
2104
+ ).toMatchObject({ _tag: "ServerBrowserTabNotFoundError" });
2105
+ yield* broker.invoke({ scope, tabId, operation: "close", input: {} });
2106
+ expect((yield* open).available).toBe(true);
2107
+ const status = yield* broker.invoke<PreviewAutomationStatus>({
2108
+ scope,
2109
+ operation: "status",
2110
+ input: {},
2111
+ });
2112
+ expect(status.tabs).toHaveLength(8);
2113
+ }),
2114
+ ).pipe(Effect.provide(layer)),
2115
+);
apps/server/src/preview/ServerBrowser.ts
+78
-29
@@ -474,7 +474,10 @@ const make = Effect.gen(function* () {
474
const launchersDir = NodePath.join(config.stateDir, "server-browser", "launchers");
475
476
const tabs = new Map<string, ServerTab>();
477
- const pendingTabs = new Map<string, Promise<ServerTab>>();
477
+ const pendingTabs = new Map<
478
+ string,
479
+ { readonly agentId: string | null; promise?: Promise<ServerTab> }
480
+ >();
481
482
const closedPendingTabs = new Set<string>();
483
const adoptedPages = new Map<string, { readonly page: Page; readonly openerTabId: string }>();
@@ -1292,8 +1295,7 @@ const make = Effect.gen(function* () {
1295
};
1296
1297
const adoptPopup = async (opener: ServerTab, popup: Page) => {
1295
- const agentId = opener.control.agentId;
1296
- if (opener.closing || (agentId !== null && atTabLimit(agentId))) {
1298
+ if (opener.closing) {
1299
await popup.close().catch(constVoid);
1300
return;
1301
}
@@ -1303,7 +1305,7 @@ const make = Effect.gen(function* () {
1305
(viewer) => viewer.id === opener.control.controller,
1306
);
1307
await runPromise(
1306
- manager.open({
1308
+ openTab({
1309
threadId: opener.threadId,
1310
...(/^https?:/i.test(url) ? { url } : {}),
1311
runtime: "server",
@@ -1318,9 +1320,8 @@ const make = Effect.gen(function* () {
1320
}),
1321
}),
1322
).then(
1321
- (snapshot) => {
1322
- if (opener.control.agentId === null)
1323
- controller?.push({ _tag: "popup", tabId: snapshot.tabId });
1323
+ (tab) => {
1324
+ if (opener.control.agentId === null) controller?.push({ _tag: "popup", tabId: tab.tabId });
1325
},
1326
async () => {
1327
await popup.close().catch(constVoid);
@@ -1331,7 +1332,7 @@ const make = Effect.gen(function* () {
1332
const ensureTab = (snapshot: PreviewSessionSnapshot): Promise<ServerTab> => {
1333
const key = tabKey(snapshot.threadId, snapshot.tabId);
1334
const pending = pendingTabs.get(key);
1334
- if (pending) return pending;
1335
+ if (pending?.promise) return pending.promise;
1336
const existing = tabs.get(key);
1337
if (existing) return Promise.resolve(existing);
1338
const opening = createTab(snapshot)
@@ -1348,7 +1349,7 @@ const make = Effect.gen(function* () {
1349
pendingTabs.delete(key);
1350
closedPendingTabs.delete(key);
1351
});
1351
- pendingTabs.set(key, opening);
1352
+ pendingTabs.set(key, { agentId: snapshot.automationOwner ?? null, promise: opening });
1353
return opening;
1354
};
1355
@@ -1366,10 +1367,15 @@ const make = Effect.gen(function* () {
1367
});
1368
});
1369
1369
- const atTabLimit = (agentSessionId: string) =>
1370
- tabs.size + pendingTabs.size >= SERVER_TAB_LIMIT ||
1371
- [...tabs.values()].filter((tab) => tab.control.agentId === agentSessionId).length >=
1372
- AGENT_TAB_LIMIT;
1370
+ const atTabLimit = (agentSessionId: string) => {
1371
+ const opening = [...pendingTabs.entries()].filter(([key]) => !tabs.has(key));
1372
+ return (
1373
+ tabs.size + opening.length >= SERVER_TAB_LIMIT ||
1374
+ [...tabs.values()].filter((tab) => tab.control.agentId === agentSessionId).length +
1375
+ opening.filter(([, pending]) => pending.agentId === agentSessionId).length >=
1376
+ AGENT_TAB_LIMIT
1377
+ );
1378
+ };
1379
1380
const assertTabCapacity = (agentSessionId: string) => {
1381
if (atTabLimit(agentSessionId))
@@ -1379,6 +1385,52 @@ const make = Effect.gen(function* () {
1385
);
1386
};
1387
1388
+ // A Playwright launch must settle before its capacity can be released.
1389
+ const openTab = Effect.fn("ServerBrowser.openTab")(function* (
1390
+ input: Parameters<typeof manager.open>[0],
1391
+ ) {
1392
+ let key: string = NodeCrypto.randomUUID();
1393
+ const reservation = { agentId: input.automationOwner ?? null };
1394
+ return yield* Effect.acquireUseRelease(
1395
+ Effect.try({
1396
+ try: () => {
1397
+ if (input.automationOwner !== undefined) assertTabCapacity(input.automationOwner);
1398
+ pendingTabs.set(key, reservation);
1399
+ },
1400
+ catch: ServerBrowserPage.toOperationError,
1401
+ }),
1402
+ () =>
1403
+ manager
1404
+ .open({
1405
+ ...input,
1406
+ beforePublish: (snapshot) => {
1407
+ pendingTabs.delete(key);
1408
+ key = tabKey(snapshot.threadId, snapshot.tabId);
1409
+ pendingTabs.set(key, reservation);
1410
+ input.beforePublish?.(snapshot);
1411
+ },
1412
+ })
1413
+ .pipe(
1414
+ Effect.flatMap((snapshot) =>
1415
+ Effect.tryPromise({
1416
+ try: () => ensureTab(snapshot),
1417
+ catch: ServerBrowserPage.toOperationError,
1418
+ }).pipe(
1419
+ Effect.onError(() =>
1420
+ manager
1421
+ .close({ threadId: ThreadId.make(snapshot.threadId), tabId: snapshot.tabId })
1422
+ .pipe(Effect.ignore),
1423
+ ),
1424
+ ),
1425
+ ),
1426
+ ),
1427
+ () =>
1428
+ Effect.sync(() => {
1429
+ pendingTabs.delete(key);
1430
+ }),
1431
+ );
1432
+ }, Effect.uninterruptible);
1433
+
1434
// Desktop browsing bypasses streamed viewers and server input tracking,
1435
// so these idle signals only apply to headless tabs.
1436
const closeIdleAgentTabs = () => {
@@ -1917,23 +1969,18 @@ const make = Effect.gen(function* () {
1969
: undefined;
1970
const navigationTimeout = Math.min(request.timeoutMs, NAVIGATION_TIMEOUT_MS);
1971
const profileId = existing ? undefined : resolveOpenProfile(open.profileId);
1920
- if (!existing) {
1921
- closeIdleAgentTabs();
1922
- assertTabCapacity(request.agentSessionId);
1923
- }
1972
+ if (!existing) closeIdleAgentTabs();
1973
const tab =
1974
existing ??
1926
- (await ensureTab(
1927
- await runPromise(
1928
- manager.open({
1929
- threadId: request.threadId,
1930
- ...(url ? { url } : {}),
1931
- ...(profileId === undefined ? {} : { profileId }),
1932
- runtime: "server",
1933
- reveal: false,
1934
- automationOwner: request.agentSessionId,
1935
- }),
1936
- ),
1975
+ (await runPromise(
1976
+ openTab({
1977
+ threadId: request.threadId,
1978
+ ...(url ? { url } : {}),
1979
+ ...(profileId === undefined ? {} : { profileId }),
1980
+ runtime: "server",
1981
+ reveal: false,
1982
+ automationOwner: request.agentSessionId,
1983
+ }),
1984
));
1985
if (existing?.dialog)
1986
throw new BrowserControlInterrupted(
@@ -2195,7 +2242,9 @@ const make = Effect.gen(function* () {
2242
const mirrorManagerEvent = (event: PreviewEvent) =>
2243
Effect.promise(async () => {
2244
if (event.type === "opened" && event.snapshot.runtime === "server") {
2198
- await ensureTab(event.snapshot).catch(constVoid);
2245
+ const key = tabKey(event.snapshot.threadId, event.snapshot.tabId);
2246
+ if (event.snapshot.automationOwner === undefined || pendingTabs.has(key) || tabs.has(key))
2247
+ await ensureTab(event.snapshot).catch(constVoid);
2248
return;
2249
}
2250
const key = tabKey(event.threadId, event.tabId);