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, 04:30 UTC
fix(server): idle agent tabs free a slot when the server's 32-tab browser limit is full (#24186)
Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
shivam committed
Nov 5, 2026 at 06:41 UTC
2ef6435f5092a9aa3dfe19a7ef9a98d8c1ecc945
13 files changed
+316
-30
apps/desktop/src/ipc/channels.ts
+1
@@ -90,6 +90,7 @@ export const PREVIEW_SET_ZOOM_FACTOR_CHANNEL = "desktop:preview-set-zoom-factor"
90
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
91
export const PREVIEW_SET_COLOR_SCHEME_CHANNEL = "desktop:preview-set-color-scheme";
92
export const PREVIEW_SET_AUDIO_MUTED_CHANNEL = "desktop:preview-set-audio-muted";
93
+export const PREVIEW_SET_SHOWN_CHANNEL = "desktop:preview-set-shown";
94
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
95
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
96
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
apps/desktop/src/ipc/methods/preview.ts
+11
@@ -9,6 +9,7 @@ import {
9
DesktopPreviewRegisterWebviewInputSchema,
10
DesktopPreviewScreenshotArtifactSchema,
11
DesktopPreviewSetAudioMutedInputSchema,
12
+ DesktopPreviewSetShownInputSchema,
13
DesktopPreviewSetColorSchemeInputSchema,
14
DesktopPreviewSetZoomFactorInputSchema,
15
BrowserImportResult,
@@ -193,6 +194,15 @@ const setAudioMuted = DesktopIpc.makeIpcMethod({
194
yield* manager.setAudioMuted(tabId, audioMuted);
195
}),
196
});
197
+const setShown = DesktopIpc.makeIpcMethod({
198
+ channel: IpcChannels.PREVIEW_SET_SHOWN_CHANNEL,
199
+ payload: DesktopPreviewSetShownInputSchema,
200
+ result: Schema.Void,
201
+ handler: Effect.fn("desktop.ipc.preview.setShown")(function* ({ tabId, shown }) {
202
+ const manager = yield* PreviewManager.PreviewManager;
203
+ yield* manager.setShown(tabId, shown);
204
+ }),
205
+});
206
const openDevTools = tabMethod(
207
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
208
"desktop.ipc.preview.openDevTools",
@@ -432,6 +442,7 @@ export const methods = [
442
setColorScheme,
443
setZoomFactor,
444
setAudioMuted,
445
+ setShown,
446
openDevTools,
447
clearCookies,
448
clearCache,
apps/desktop/src/preload.ts
+2
@@ -348,6 +348,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
348
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, { tabId, colorScheme }),
349
setAudioMuted: (tabId, audioMuted) =>
350
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_AUDIO_MUTED_CHANNEL, { tabId, audioMuted }),
351
+ setShown: (tabId, shown) =>
352
+ ipcRenderer.invoke(IpcChannels.PREVIEW_SET_SHOWN_CHANNEL, { tabId, shown }),
353
openDevTools: (tabId) =>
354
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
355
listBrowserImportSources: () => ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL),
apps/desktop/src/preview/DesktopBrowserHost.test.ts
+38
@@ -144,6 +144,44 @@ describe("DesktopBrowserHost", () => {
144
}),
145
);
146
147
+ it.effect("re-sends shown to a backend that starts later and when a tab attaches again", () =>
148
+ Effect.gen(function* () {
149
+ const host = yield* DesktopBrowserHost.make;
150
+ host.attach(key, makeDebuggee().tab);
151
+ host.setShown(key, true);
152
+ const reader = yield* takeEvents(host, 5).pipe(Effect.forkScoped);
153
+
154
+ yield* Effect.yieldNow;
155
+ host.detach(key);
156
+ host.attach(key, makeDebuggee().tab);
157
+
158
+ expect(yield* Fiber.join(reader)).toEqual([
159
+ { type: "attached", ...key },
160
+ { type: "shown", ...key, shown: true },
161
+ { type: "detached", ...key },
162
+ { type: "attached", ...key },
163
+ { type: "shown", ...key, shown: true },
164
+ ]);
165
+ }),
166
+ );
167
+
168
+ it.effect("replays an explicit hidden report before announcing another tab", () =>
169
+ Effect.gen(function* () {
170
+ const host = yield* DesktopBrowserHost.make;
171
+ const other = { ...key, tabId: "tab-2" };
172
+ host.setShown(key, false);
173
+ host.attach(key, makeDebuggee().tab);
174
+ host.setShown(other, true);
175
+ host.attach(other, makeDebuggee().tab);
176
+
177
+ expect(yield* takeEvents(host, 3)).toEqual([
178
+ { type: "attached", ...key },
179
+ { type: "shown", ...key, shown: false },
180
+ { type: "attached", ...other },
181
+ ]);
182
+ }),
183
+ );
184
+
185
it.effect("drops replies from a relay the server released", () =>
186
Effect.gen(function* () {
187
const host = yield* DesktopBrowserHost.make;
apps/desktop/src/preview/DesktopBrowserHost.ts
+26
-1
@@ -87,6 +87,7 @@ export class DesktopBrowserHost extends Context.Service<
87
readonly handleCommandLine: (line: string) => Effect.Effect<void>;
88
readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void;
89
readonly detach: (key: DesktopBrowserTabKey) => void;
90
+ readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void;
91
readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
92
readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
93
readonly pointers: Stream.Stream<{
@@ -119,6 +120,9 @@ export const make = Effect.gen(function* () {
120
const tabs = new Map<string, AttachedTab>();
121
/** Threads whose agent turn runs, by the server's account. */
122
const agentTurns = new Set<string>();
123
+ // Kept apart from attachment: the renderer can show a webview before its debugger attaches,
124
+ // and the server forgets `shown` on detach, for example while DevTools holds the debugger.
125
+ const shownTabs = new Map<string, boolean>();
126
const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
127
128
const nextScreenshot = (tab: AttachedTab) => {
@@ -456,6 +460,19 @@ export const make = Effect.gen(function* () {
460
debuggee.debugger.on("message", tab.onMessage);
461
debuggee.webContents.on("did-navigate", tab.onNewDocument);
462
emit({ type: "attached", ...key });
463
+ const shown = shownTabs.get(id);
464
+ if (shown !== undefined) emit({ type: "shown", ...key, shown });
465
+ };
466
+
467
+ const setShown = (key: DesktopBrowserTabKey, shown: boolean | undefined) => {
468
+ const id = keyOf(key);
469
+ if (shown === undefined) {
470
+ shownTabs.delete(id);
471
+ return;
472
+ }
473
+ if (shownTabs.get(id) === shown) return;
474
+ shownTabs.set(id, shown);
475
+ if (tabs.has(id)) emit({ type: "shown", ...key, shown });
476
};
477
478
const handleCommandLine = (line: string) =>
@@ -494,7 +511,14 @@ export const make = Effect.gen(function* () {
511
[...tabs.values()],
512
(tab) => {
513
dropRelay(tab);
497
- return PubSub.publish(outbox, { type: "attached", ...tab.key });
514
+ const shown = shownTabs.get(keyOf(tab.key));
515
+ return PubSub.publish(outbox, { type: "attached", ...tab.key }).pipe(
516
+ Effect.andThen(
517
+ shown !== undefined
518
+ ? PubSub.publish(outbox, { type: "shown", ...tab.key, shown })
519
+ : Effect.void,
520
+ ),
521
+ );
522
},
523
{ discard: true },
524
);
@@ -514,6 +538,7 @@ export const make = Effect.gen(function* () {
538
handleCommandLine,
539
attach,
540
detach,
541
+ setShown,
542
placeDownload,
543
humanStartedDownload,
544
});
apps/desktop/src/preview/Manager.ts
+20
@@ -1685,6 +1685,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
1685
});
1686
if (Option.isNone(tab)) return;
1687
const closedTab = tab.value;
1688
+ if (closedTab.serverTab) browserHost.setShown(closedTab.serverTab, undefined);
1689
if (closedTab.webContentsId != null) {
1690
yield* Effect.all(
1691
[
@@ -1893,6 +1894,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
1894
yield* rendererHistory.register(wc, { surface: "preview" });
1895
const webContentsId = wc.id;
1896
wc.once("destroyed", () => {
1897
+ runFork(hideDestroyedGuest(webContentsId));
1898
runFork(detachControlSession(webContentsId));
1899
});
1900
yield* ensureControlSession(wc).pipe(
@@ -2346,6 +2348,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2348
yield* applyColorScheme(tabId, wc, colorScheme);
2349
});
2350
2351
+ const setShown = Effect.fn("PreviewManager.setShown")(function* (tabId: string, shown: boolean) {
2352
+ const serverTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.serverTab;
2353
+ if (serverTab) browserHost.setShown(serverTab, shown);
2354
+ });
2355
+
2356
+ // A window reload or guest crash destroys the guest without the renderer reporting it hidden.
2357
+ // The renderer reports again once a new guest registers.
2358
+ const hideDestroyedGuest = Effect.fnUntraced(function* (webContentsId: number) {
2359
+ for (const tab of (yield* SynchronizedRef.get(tabsRef)).values()) {
2360
+ if (tab.webContentsId === webContentsId && tab.serverTab) {
2361
+ browserHost.setShown(tab.serverTab, false);
2362
+ }
2363
+ }
2364
+ });
2365
+
2366
const setAudioMuted = Effect.fn("PreviewManager.setAudioMuted")(function* (
2367
tabId: string,
2368
audioMuted: boolean,
@@ -3307,6 +3324,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
3324
setAnnotationTheme,
3325
setAnnotationSendEnabled,
3326
setAudioMuted,
3327
+ setShown,
3328
setColorScheme,
3329
setMainWindow,
3330
setForwardedShortcuts: (shortcuts: ReadonlyArray<PreviewForwardedShortcut>) =>
@@ -3512,6 +3530,7 @@ export class PreviewManager extends Context.Service<
3530
tabId: string,
3531
audioMuted: boolean,
3532
) => Effect.Effect<void, PreviewManagerError>;
3533
+ readonly setShown: (tabId: string, shown: boolean) => Effect.Effect<void>;
3534
readonly openDevTools: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
3535
readonly clearCookies: (
3536
partitions?: ReadonlyArray<string>,
@@ -3652,6 +3671,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
3671
setColorScheme: operations.setColorScheme,
3672
setZoomFactor: operations.setZoomFactor,
3673
setAudioMuted: operations.setAudioMuted,
3674
+ setShown: operations.setShown,
3675
openDevTools: operations.openDevTools,
3676
clearCookies: Effect.fn("PreviewManager.clearCookies")(function* (partitions) {
3677
yield* browserSession
apps/server/src/preview/DesktopBrowserChannel.test.ts
new
+67
@@ -0,0 +1,67 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import * as NodeStream from "@effect/platform-node/NodeStream";
3
+import { expect, it } from "@effect/vitest";
4
+import * as Effect from "effect/Effect";
5
+import * as Layer from "effect/Layer";
6
+import * as Queue from "effect/Queue";
7
+import * as Stream from "effect/Stream";
8
+import { vi } from "vite-plus/test";
9
+
10
+import * as ServerConfig from "../config.ts";
11
+import * as DesktopBrowserChannel from "./DesktopBrowserChannel.ts";
12
+
13
+vi.mock("@effect/platform-node/NodeStream", () => ({ fromReadable: vi.fn() }));
14
+vi.mock("node:net", () => ({
15
+ Socket: class {
16
+ destroy() {}
17
+ },
18
+}));
19
+
20
+it.effect("protects unknown desktop visibility until an explicit hidden report arrives", () =>
21
+ Effect.gen(function* () {
22
+ const input = yield* Queue.unbounded<Uint8Array>();
23
+ vi.mocked(NodeStream.fromReadable).mockReturnValue(Stream.fromQueue(input));
24
+ const config = yield* ServerConfig.ServerConfig;
25
+ yield* Effect.gen(function* () {
26
+ const channel = yield* DesktopBrowserChannel.DesktopBrowserChannel;
27
+ const key = { threadId: "thread-1", tabId: "tab-1" };
28
+ const send = (event: object) =>
29
+ Queue.offer(input, new TextEncoder().encode(`${JSON.stringify(event)}\n`));
30
+
31
+ expect(channel.isShown(key)).toBe(true);
32
+ yield* send({ type: "attached", ...key });
33
+ yield* channel.awaitAttached(key, "5 seconds");
34
+ expect(channel.isShown(key)).toBe(true);
35
+
36
+ yield* send({ type: "shown", ...key, shown: false });
37
+ yield* send({ type: "attached", threadId: key.threadId, tabId: "sentinel-1" });
38
+ yield* channel.awaitAttached({ threadId: key.threadId, tabId: "sentinel-1" }, "5 seconds");
39
+ expect(channel.isShown(key)).toBe(false);
40
+
41
+ yield* send({ type: "shown", ...key, shown: true });
42
+ yield* send({ type: "attached", threadId: key.threadId, tabId: "sentinel-2" });
43
+ yield* channel.awaitAttached({ threadId: key.threadId, tabId: "sentinel-2" }, "5 seconds");
44
+ expect(channel.isShown(key)).toBe(true);
45
+
46
+ yield* send({ type: "shown", ...key, shown: false });
47
+ yield* send({ type: "detached", ...key });
48
+ yield* send({ type: "attached", threadId: key.threadId, tabId: "sentinel-3" });
49
+ yield* channel.awaitAttached({ threadId: key.threadId, tabId: "sentinel-3" }, "5 seconds");
50
+ expect(channel.isShown(key)).toBe(true);
51
+ }).pipe(
52
+ Effect.provide(
53
+ DesktopBrowserChannel.layer.pipe(
54
+ Layer.provide(
55
+ ServerConfig.layer({ ...config, desktopBrowserFd: 41, desktopBrowserControlFd: 42 }),
56
+ ),
57
+ ),
58
+ ),
59
+ );
60
+ }).pipe(
61
+ Effect.provide(
62
+ ServerConfig.layerTest(process.cwd(), { prefix: "desktop-browser-channel-" }).pipe(
63
+ Layer.provide(NodeServices.layer),
64
+ ),
65
+ ),
66
+ ),
67
+);
apps/server/src/preview/DesktopBrowserChannel.ts
+11
@@ -44,6 +44,8 @@ export class DesktopBrowserChannel extends Context.Service<
44
readonly detached: Stream.Stream<DesktopTabKey>;
45
readonly attached: Stream.Stream<DesktopTabKey>;
46
readonly isAttached: (key: DesktopTabKey) => Effect.Effect<boolean>;
47
+ /** Whether a desktop window draws the tab on screen, which no streamed viewer counts. */
48
+ readonly isShown: (key: DesktopTabKey) => boolean;
49
readonly endpoint: (key: DesktopTabKey) => Effect.Effect<string, never, Scope.Scope>;
50
readonly pointer: (
51
key: DesktopTabKey,
@@ -60,6 +62,8 @@ const make = Effect.gen(function* () {
62
const controlFd = config.desktopBrowserControlFd;
63
const changes = yield* PubSub.unbounded<{ key: DesktopTabKey; attached: boolean }>();
64
const attachedTabs = new Set<string>();
65
+ // Missing reports protect desktop tabs until the renderer explicitly marks them hidden.
66
+ const shownTabs = new Map<string, boolean>();
67
const inbound = new Map<string, Queue.Queue<string>>();
68
const writeLock = yield* Semaphore.make(1);
69
@@ -83,6 +87,7 @@ const make = Effect.gen(function* () {
87
pointer: Effect.fn("DesktopBrowserChannel.pointer")(function () {
88
return Effect.void;
89
}),
90
+ isShown: () => false,
91
});
92
}
93
@@ -123,14 +128,19 @@ const make = Effect.gen(function* () {
128
return PubSub.publish(changes, { key, attached: true });
129
case "detached": {
130
attachedTabs.delete(id);
131
+ shownTabs.delete(id);
132
const queue = inbound.get(id);
133
return (queue ? Queue.shutdown(queue) : Effect.void).pipe(
134
Effect.andThen(PubSub.publish(changes, { key, attached: false })),
135
);
136
}
137
+ case "shown":
138
+ shownTabs.set(id, event.shown);
139
+ return Effect.void;
140
}
141
}),
142
Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })),
143
+ Effect.ensuring(Effect.sync(() => shownTabs.clear())),
144
Effect.forkScoped,
145
);
146
@@ -221,6 +231,7 @@ const make = Effect.gen(function* () {
231
isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function (key) {
232
return Effect.sync(() => attachedTabs.has(keyOf(key)));
233
}),
234
+ isShown: (key) => shownTabs.get(keyOf(key)) ?? true,
235
endpoint,
236
turn: Effect.fn("DesktopBrowserChannel.turn")(function (threadId, active) {
237
return command({ type: "turn", threadId, active });
apps/server/src/preview/ServerBrowser.test.ts
+73
@@ -321,6 +321,7 @@ const desktopRenders = (tabId: string) => {
321
}
322
return desktopTabs.has(tabId);
323
};
324
+const shownDesktopTabs = new Set<string>();
325
const releasedDesktopTabs: Array<string> = [];
326
const desktopTurns = new NodeEvents.EventEmitter();
327
const desktopConnections: Array<{ endpoint: string; context: ReturnType<typeof makeContext> }> = [];
@@ -379,10 +380,12 @@ const dependencies = Layer.mergeAll(
380
),
381
),
382
isAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)),
383
+ isShown: (key) => shownDesktopTabs.has(key.tabId),
384
endpoint: (key) =>
385
Effect.acquireRelease(Effect.succeed(`ws://desktop/${key.tabId}`), () =>
386
Effect.sync(() => {
387
releasedDesktopTabs.push(key.tabId);
388
+ desktopDetaches.emit("release", key.tabId);
389
desktopReleased.resolve();
390
}),
391
),
@@ -455,6 +458,7 @@ beforeEach(() => {
458
keyCopy = "";
459
focusedFrame = null;
460
desktopTabs.clear();
461
+ shownDesktopTabs.clear();
462
desktopRendersNext = false;
463
desktopPageUrl = "about:blank";
464
desktopSizeAnswer = null;
@@ -2326,3 +2330,72 @@ it.live("failed session and browser launches release capacity, as does closing a
2330
}),
2331
).pipe(Effect.provide(layer)),
2332
);
2333
+
2334
+it.live("a full server takes back the slot of the longest idle agent tab nobody views", () =>
2335
+ Effect.scoped(
2336
+ Effect.gen(function* () {
2337
+ const broker = yield* Broker.PreviewAutomationBroker;
2338
+ const manager = yield* Manager.PreviewManager;
2339
+ yield* ServerBrowser.ServerBrowser;
2340
+ yield* Effect.yieldNow;
2341
+ const now = vi.spyOn(Date, "now").mockReturnValue(0);
2342
+ yield* Effect.addFinalizer(() => Effect.sync(() => now.mockRestore()));
2343
+ const open = (providerSessionId: string) => {
2344
+ desktopRendersNext = true;
2345
+ return broker.invoke<PreviewAutomationStatus>({
2346
+ scope: asSession(providerSessionId),
2347
+ operation: "open",
2348
+ input: { reuseExistingTab: false, open: false },
2349
+ });
2350
+ };
2351
+ const opened: Array<string> = [];
2352
+ for (let index = 0; index < 32; index++) {
2353
+ now.mockReturnValue(index);
2354
+ opened.push((yield* open(`agent-${Math.floor(index / 8)}`)).tabId!);
2355
+ }
2356
+
2357
+ now.mockReturnValue(100);
2358
+ yield* broker.invoke<PreviewAutomationStatus>({
2359
+ scope: asSession("agent-observer"),
2360
+ operation: "status",
2361
+ tabId: PreviewTabId.make(opened[0]!),
2362
+ input: {},
2363
+ });
2364
+
2365
+ // Inside the idle window every desktop tab keeps its slot.
2366
+ now.mockReturnValue(29 * 60 * 1000);
2367
+ expect(yield* open("agent-new").pipe(Effect.flip)).toMatchObject({ reason: "tabLimit" });
2368
+ expect(releasedDesktopTabs).toEqual([]);
2369
+
2370
+ now.mockReturnValue(31 * 60 * 1000);
2371
+ // A session at its own limit couldn't use a freed slot, so nothing closes for it.
2372
+ expect(yield* open("agent-3").pipe(Effect.flip)).toMatchObject({ reason: "tabLimit" });
2373
+ expect(releasedDesktopTabs).toEqual([]);
2374
+ // Tabs a desktop window shows keep their slots however long they sit idle.
2375
+ for (const tabId of opened) shownDesktopTabs.add(tabId);
2376
+ expect(yield* open("agent-new").pipe(Effect.flip)).toMatchObject({ reason: "tabLimit" });
2377
+ expect(releasedDesktopTabs).toEqual([]);
2378
+ shownDesktopTabs.clear();
2379
+ shownDesktopTabs.add(opened[1]!);
2380
+ const events = yield* manager.subscribeEvents;
2381
+ const releases = yield* Queue.unbounded<string>();
2382
+ const recordRelease = (tabId: string) => Queue.offerUnsafe(releases, tabId);
2383
+ desktopDetaches.on("release", recordRelease);
2384
+ yield* Effect.addFinalizer(() =>
2385
+ Effect.sync(() => desktopDetaches.off("release", recordRelease)),
2386
+ );
2387
+ const fresh = yield* open("agent-new");
2388
+ expect(fresh.tabId).toBeDefined();
2389
+ expect(yield* Queue.take(releases)).toBe(opened[2]);
2390
+ yield* Stream.fromSubscription(events).pipe(
2391
+ Stream.filter((event) => event.type === "closed" && event.tabId === opened[2]),
2392
+ Stream.runHead,
2393
+ );
2394
+ expect(releasedDesktopTabs).toEqual([opened[2]]);
2395
+ const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
2396
+ expect(sessions.map((session) => session.tabId).toSorted()).toEqual(
2397
+ [...opened.filter((tabId) => tabId !== opened[2]), fresh.tabId!].toSorted(),
2398
+ );
2399
+ }),
2400
+ ).pipe(Effect.provide(layer)),
2401
+);
apps/server/src/preview/ServerBrowser.ts
+46
-28
@@ -1394,15 +1394,15 @@ const make = Effect.gen(function* () {
1394
});
1395
});
1396
1397
- const atTabLimit = (agentSessionId: string) => {
1398
- const opening = [...pendingTabs.entries()].filter(([key]) => !tabs.has(key));
1399
- return (
1400
- tabs.size + opening.length >= SERVER_TAB_LIMIT ||
1401
- [...tabs.values()].filter((tab) => tab.control.agentId === agentSessionId).length +
1402
- opening.filter(([, pending]) => pending.agentId === agentSessionId).length >=
1403
- AGENT_TAB_LIMIT
1404
- );
1405
- };
1397
+ const openingReservations = () =>
1398
+ [...pendingTabs.entries()].filter(([key]) => !tabs.has(key)).map(([, pending]) => pending);
1399
+ const serverAtTabLimit = () => tabs.size + openingReservations().length >= SERVER_TAB_LIMIT;
1400
+ const agentAtTabLimit = (agentSessionId: string) =>
1401
+ [...tabs.values()].filter((tab) => tab.control.agentId === agentSessionId).length +
1402
+ openingReservations().filter((pending) => pending.agentId === agentSessionId).length >=
1403
+ AGENT_TAB_LIMIT;
1404
+ const atTabLimit = (agentSessionId: string) =>
1405
+ serverAtTabLimit() || agentAtTabLimit(agentSessionId);
1406
1407
const assertTabCapacity = (agentSessionId: string) => {
1408
if (atTabLimit(agentSessionId))
@@ -1412,16 +1412,40 @@ const make = Effect.gen(function* () {
1412
);
1413
};
1414
1415
+ // The desktop draws its tabs in its own webview, so they never get a streamed viewer.
1416
+ const isVisible = (tab: ServerTab) =>
1417
+ tab.viewers.size > 0 || (tab.desktop !== null && desktopChannel.isShown(tab));
1418
+
1419
+ const idleAgentTabs = () => {
1420
+ const cutoff = Date.now() - AGENT_TAB_IDLE_MS;
1421
+ return [...tabs.values()].filter(
1422
+ (tab) => tab.control.agentId !== null && !isVisible(tab) && tab.usedAt < cutoff,
1423
+ );
1424
+ };
1425
+
1426
+ // The desktop app renders every server tab, so idle desktop agent tabs would otherwise
1427
+ // hold the server's budget forever. Hidden ones give up their slots, longest idle first,
1428
+ // only when an agent needs one and has room for it.
1429
+ const freeIdleAgentSlot = (agentSessionId: string) => {
1430
+ if (!serverAtTabLimit() || agentAtTabLimit(agentSessionId)) return;
1431
+ const longestIdle = idleAgentTabs().sort((left, right) => left.usedAt - right.usedAt)[0];
1432
+ if (longestIdle) dropTab(longestIdle, true);
1433
+ };
1434
+
1435
// A Playwright launch must settle before its capacity can be released.
1436
const openTab = Effect.fn("ServerBrowser.openTab")(function* (
1437
input: Parameters<typeof manager.open>[0],
1438
+ options: { readonly reclaimIdleSlot?: boolean } = {},
1439
) {
1440
let key: string = NodeCrypto.randomUUID();
1441
const reservation = { agentId: input.automationOwner ?? null };
1442
return yield* Effect.acquireUseRelease(
1443
Effect.try({
1444
try: () => {
1424
- if (input.automationOwner !== undefined) assertTabCapacity(input.automationOwner);
1445
+ if (input.automationOwner !== undefined) {
1446
+ if (options.reclaimIdleSlot) freeIdleAgentSlot(input.automationOwner);
1447
+ assertTabCapacity(input.automationOwner);
1448
+ }
1449
pendingTabs.set(key, reservation);
1450
},
1451
catch: ServerBrowserPage.toOperationError,
@@ -1461,16 +1485,7 @@ const make = Effect.gen(function* () {
1485
// Desktop browsing bypasses streamed viewers and server input tracking,
1486
// so these idle signals only apply to headless tabs.
1487
const closeIdleAgentTabs = () => {
1464
- const cutoff = Date.now() - AGENT_TAB_IDLE_MS;
1465
- for (const tab of tabs.values()) {
1466
- if (
1467
- tab.control.agentId !== null &&
1468
- tab.desktop === null &&
1469
- tab.viewers.size === 0 &&
1470
- tab.usedAt < cutoff
1471
- )
1472
- dropTab(tab, true);
1473
- }
1488
+ for (const tab of idleAgentTabs()) if (tab.desktop === null) dropTab(tab, true);
1489
};
1490
1491
const latestThreadTab = (threadId: string, agentSessionId?: string) => {
@@ -2003,14 +2018,17 @@ const make = Effect.gen(function* () {
2018
const tab =
2019
existing ??
2020
(await runPromise(
2006
- openTab({
2007
- threadId: request.threadId,
2008
- ...(url ? { url } : {}),
2009
- ...(profileId === undefined ? {} : { profileId }),
2010
- runtime: "server",
2011
- reveal: false,
2012
- automationOwner: request.agentSessionId,
2013
- }),
2021
+ openTab(
2022
+ {
2023
+ threadId: request.threadId,
2024
+ ...(url ? { url } : {}),
2025
+ ...(profileId === undefined ? {} : { profileId }),
2026
+ runtime: "server",
2027
+ reveal: false,
2028
+ automationOwner: request.agentSessionId,
2029
+ },
2030
+ { reclaimIdleSlot: true },
2031
+ ),
2032
));
2033
if (existing?.dialog)
2034
throw new BrowserControlInterrupted(
apps/web/src/browser/HostedBrowserWebview.tsx
+12
-1
@@ -135,6 +135,9 @@ export function HostedBrowserWebview(props: {
135
136
const [webviewGeneration, setWebviewGeneration] = useState(0);
137
const [recoverySrc, setRecoverySrc] = useState(initialSrc);
138
+ const active = presentation.visible && presentation.rect !== null;
139
+ const shown = active || pictureInPicture;
140
+ const reportedShown = useEffectEvent(() => serverDriven && shown);
141
const remountCrashedWebview = useEffectEvent(() => {
142
setRecoverySrc(initialUrl ?? initialSrc);
143
setWebviewGeneration((generation) => generation + 1);
@@ -162,6 +165,7 @@ export function HostedBrowserWebview(props: {
165
const webContentsId = webview.getWebContentsId();
166
if (Number.isInteger(webContentsId) && webContentsId > 0) {
167
await bridge.registerWebview(runtimeTabId, webContentsId);
168
+ withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, reportedShown()));
169
}
170
} catch {}
171
})();
@@ -203,7 +207,6 @@ export function HostedBrowserWebview(props: {
207
webviewGeneration,
208
]);
209
206
- const active = presentation.visible && presentation.rect !== null;
210
const lastRect = presentation.rect;
211
const layoutZoomFactor = useBrowserLayoutZoomFactor(zoomFactor);
212
const viewportWidth = viewport._tag === "fill" ? null : viewport.width;
@@ -289,6 +292,14 @@ export function HostedBrowserWebview(props: {
292
viewportWidth,
293
]);
294
295
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Report the mounted webview's visibility to the desktop host.
296
+ useEffect(() => {
297
+ const bridge = window.desktopBridge?.preview;
298
+ if (!clientSettingsHydrated || !bridge || !serverDriven) return;
299
+ withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, shown));
300
+ return () => withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, false));
301
+ }, [clientSettingsHydrated, runtimeTabId, serverDriven, shown]);
302
+
303
if (!clientSettingsHydrated || !config) return null;
304
305
const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
packages/contracts/src/desktopBrowser.ts
+2
@@ -12,6 +12,8 @@ export const DesktopBrowserEvent = Schema.Union([
12
/** Its `<webview>` went away: closed, crashed, swapped, or devtools took the debugger. */
13
Schema.Struct({ type: Schema.Literal("detached"), ...TabKey }),
14
Schema.Struct({ type: Schema.Literal("cdp"), ...TabKey, message: Schema.String }),
15
+ /** Its `<webview>` started or stopped being on screen in a desktop window. */
16
+ Schema.Struct({ type: Schema.Literal("shown"), ...TabKey, shown: Schema.Boolean }),
17
]);
18
export type DesktopBrowserEvent = typeof DesktopBrowserEvent.Type;
19
packages/contracts/src/ipc.ts
+7
@@ -993,6 +993,11 @@ export const DesktopPreviewSetAudioMutedInputSchema = Schema.Struct({
993
audioMuted: Schema.Boolean,
994
});
995
996
+export const DesktopPreviewSetShownInputSchema = Schema.Struct({
997
+ tabId: DesktopPreviewTabIdSchema,
998
+ shown: Schema.Boolean,
999
+});
1000
+
1001
export const DesktopPreviewAnnotationThemeInputSchema = Schema.Struct({
1002
theme: DesktopPreviewAnnotationThemeSchema,
1003
});
@@ -1165,6 +1170,8 @@ export interface DesktopPreviewBridge {
1170
hardReload: (tabId: string) => Promise<void>;
1171
setColorScheme: (tabId: string, colorScheme: DesktopPreviewColorScheme) => Promise<void>;
1172
setAudioMuted: (tabId: string, audioMuted: boolean) => Promise<void>;
1173
+ /** Tells the tab's server whether its webview is on screen. */
1174
+ setShown: (tabId: string, shown: boolean) => Promise<void>;
1175
openDevTools: (tabId: string) => Promise<void>;
1176
clearCookies: (environmentId: EnvironmentId, profileId?: string) => Promise<void>;
1177
clearCache: (environmentId: EnvironmentId, profileId?: string) => Promise<void>;