The best way to control Claude Code, Codex and more from any computer or phone
fix(server): closing preview tabs runs beforeunload handlers (#23537)
Julius Marminge committed
Nov 11, 2026 at 16:00 UTC
d9805b2ca667be7caec8c9035950564ab96704c3
2 files changed
+210
-7
apps/server/src/preview/ServerBrowser.test.ts
+162
-5
@@ -68,8 +68,9 @@ vi.mock("./ServerBrowserContexts.ts", () => ({
68
async connectDesktopPage(endpoint: string) {
69
const context = makeContext(undefined, desktopPageUrl);
70
context.page.viewportSize.mockReturnValue(null);
71
- desktopConnections.push({ endpoint, context });
72
- return { browser: { close: async () => {} }, page: context.page as unknown as Page };
71
+ const browser = { close: vi.fn(async () => {}) };
72
+ desktopConnections.push({ endpoint, context, browser });
73
+ return { browser, page: context.page as unknown as Page };
74
}
75
async close() {
76
for (const context of contexts) await context.close();
@@ -228,11 +229,50 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = "
229
throw new Error("Unexpected locator action");
230
}),
231
isClosed: () => closed,
231
- close: vi.fn(async () => {
232
- if (!closed) {
232
+ // Models Playwright: unload handlers always run, but `beforeunload` only with
233
+ // `runBeforeUnload`, and a guarding page stays open behind a `beforeunload` dialog.
234
+ beforeUnload: "none" as "none" | "listen" | "guard",
235
+ unloadEvents: [] as string[],
236
+ beforeUnloadDialog: null as null | {
237
+ accept: ReturnType<typeof vi.fn>;
238
+ dismiss: ReturnType<typeof vi.fn>;
239
+ },
240
+ // Set to hold the page open after `beforeunload` until resolved, as Playwright's
241
+ // `runBeforeUnload` close resolves before the page actually closes.
242
+ unloadGate: null as PromiseWithResolvers<void> | null,
243
+ removed: false,
244
+ pagehideBinding: null as (() => void) | null,
245
+ pagehideWatched: Promise.withResolvers<void>(),
246
+ exposeFunction: vi.fn(async (_name: string, callback: () => void) => {
247
+ page.pagehideBinding = callback;
248
+ page.pagehideWatched.resolve();
249
+ }),
250
+ close: vi.fn(async (options?: { runBeforeUnload?: boolean }) => {
251
+ if (closed) return;
252
+ const finish = () => {
253
+ if (closed || page.removed) return;
254
+ page.unloadEvents.push("pagehide");
255
+ page.pagehideBinding?.();
256
+ page.unloadEvents.push("visibilitychange");
257
closed = true;
258
events.emit("close");
259
+ };
260
+ if (!options?.runBeforeUnload || page.beforeUnload === "none") return finish();
261
+ page.unloadEvents.push("beforeunload");
262
+ if (page.beforeUnload === "listen" && page.unloadGate) {
263
+ void page.unloadGate.promise.then(finish);
264
+ return;
265
}
266
+ if (page.beforeUnload === "listen") return finish();
267
+ const dialog = {
268
+ type: () => "beforeunload",
269
+ message: () => "",
270
+ defaultValue: () => "",
271
+ accept: vi.fn(async () => finish()),
272
+ dismiss: vi.fn(async () => {}),
273
+ };
274
+ page.beforeUnloadDialog = dialog;
275
+ events.emit("dialog", dialog);
276
}),
277
};
278
const context = {
@@ -249,9 +289,11 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = "
289
sessions.push(session);
290
return session;
291
},
292
+ closing: Promise.withResolvers<void>(),
293
close: vi.fn(async () => {
294
if (contextClosed) return;
295
contextClosed = true;
296
+ context.closing.resolve();
297
await page.close();
298
onClose?.(context as unknown as BrowserContext);
299
}),
@@ -366,7 +408,11 @@ const shownDesktopTabs = new Set<string>();
408
const releasedDesktopTabs: Array<string> = [];
409
const desktopLoadFailures = new Map<string, PreviewAutomationLoadError>();
410
const desktopTurns = new NodeEvents.EventEmitter();
369
-const desktopConnections: Array<{ endpoint: string; context: ReturnType<typeof makeContext> }> = [];
411
+const desktopConnections: Array<{
412
+ endpoint: string;
413
+ context: ReturnType<typeof makeContext>;
414
+ browser: { close: ReturnType<typeof vi.fn> };
415
+}> = [];
416
const testThread = {
417
threadId: ThreadId.make("browser-test-thread"),
418
providerSessionId: "agent-a",
@@ -1179,6 +1225,117 @@ it.live("reports a pending dialog without evaluating the page and resolves it ex
1225
).pipe(Effect.provide(layer)),
1226
);
1227
1228
+it.live("closing an isolated tab closes its context only after the page closes", () =>
1229
+ Effect.scoped(
1230
+ Effect.gen(function* () {
1231
+ const { broker, tabId } = yield* ready;
1232
+ const context = contexts[0]!;
1233
+ const page = context.page;
1234
+ page.beforeUnload = "listen";
1235
+ page.unloadGate = Promise.withResolvers<void>();
1236
+ yield* broker.invoke({ scope, tabId, operation: "close", input: {} });
1237
+ expect(context.close).not.toHaveBeenCalled();
1238
+ expect(page.isClosed()).toBe(false);
1239
+ page.unloadGate.resolve();
1240
+ yield* Effect.promise(() => context.closing.promise);
1241
+ expect(page.isClosed()).toBe(true);
1242
+ expect(page.unloadEvents).toEqual(["beforeunload", "pagehide", "visibilitychange"]);
1243
+ }),
1244
+ ).pipe(Effect.provide(layer)),
1245
+);
1246
+
1247
+it.live("closing a tab force-closes a page that never finishes unloading", () =>
1248
+ Effect.scoped(
1249
+ Effect.gen(function* () {
1250
+ const { broker, tabId } = yield* ready;
1251
+ const context = contexts[0]!;
1252
+ const page = context.page;
1253
+ page.beforeUnload = "listen";
1254
+ page.unloadGate = Promise.withResolvers<void>();
1255
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
1256
+ yield* broker.invoke({ scope, tabId, operation: "close", input: {} });
1257
+ vi.advanceTimersByTime(4_999);
1258
+ expect(page.isClosed()).toBe(false);
1259
+ expect(context.close).not.toHaveBeenCalled();
1260
+ vi.advanceTimersByTime(1);
1261
+ expect(page.isClosed()).toBe(true);
1262
+ yield* Effect.promise(() => context.closing.promise);
1263
+ expect(vi.getTimerCount()).toBe(0);
1264
+ }).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers()))),
1265
+ ).pipe(Effect.provide(layer)),
1266
+);
1267
+
1268
+it.live("closing a desktop tab waits for its page to unload before the desktop removes it", () =>
1269
+ Effect.scoped(
1270
+ Effect.gen(function* () {
1271
+ const { broker } = yield* ready;
1272
+ const manager = yield* Manager.PreviewManager;
1273
+ desktopRendersNext = true;
1274
+ const opened = yield* broker.invoke<PreviewAutomationStatus>({
1275
+ scope,
1276
+ operation: "open",
1277
+ input: { reuseExistingTab: false, open: false },
1278
+ });
1279
+ const tabId = PreviewTabId.make(opened.tabId!);
1280
+ const { context, browser } = desktopConnections[0]!;
1281
+ const page = context.page;
1282
+ // The desktop removes the webview once the session closes, dropping an unload in progress.
1283
+ const events = yield* manager.subscribeEvents;
1284
+ const sessionClosed = Promise.withResolvers<void>();
1285
+ yield* Effect.gen(function* () {
1286
+ while ((yield* PubSub.take(events)).type !== "closed");
1287
+ page.removed = true;
1288
+ sessionClosed.resolve();
1289
+ }).pipe(Effect.forkScoped);
1290
+ page.beforeUnload = "listen";
1291
+ page.unloadGate = Promise.withResolvers<void>();
1292
+ const closing = yield* broker
1293
+ .invoke({ scope, tabId, operation: "close", input: {} })
1294
+ .pipe(Effect.forkScoped);
1295
+ // The page finishes unloading once the server listens for it, or too late if it never does.
1296
+ yield* Effect.promise(() =>
1297
+ Promise.race([page.pagehideWatched.promise, sessionClosed.promise]),
1298
+ );
1299
+ expect(browser.close).not.toHaveBeenCalled();
1300
+ page.unloadGate.resolve();
1301
+ yield* Fiber.join(closing);
1302
+ expect(page.unloadEvents).toEqual(["beforeunload", "pagehide", "visibilitychange"]);
1303
+ expect(browser.close).toHaveBeenCalledTimes(1);
1304
+ }),
1305
+ ).pipe(Effect.provide(layer)),
1306
+);
1307
+
1308
+it.live("closing a tab with an unsaved-changes guard still closes it", () =>
1309
+ Effect.scoped(
1310
+ Effect.gen(function* () {
1311
+ const browser = yield* ServerBrowser.ServerBrowser;
1312
+ const broker = yield* Broker.PreviewAutomationBroker;
1313
+ yield* Effect.yieldNow;
1314
+ // A profile context is shared, so closing the tab cannot fall back to closing its context.
1315
+ const reportProfiles = yield* browser.profileReporter;
1316
+ yield* reportProfiles({
1317
+ profiles: [{ id: "profile-work", name: "Work", kind: "persistent" }],
1318
+ defaultProfileId: "profile-work",
1319
+ });
1320
+ const opened = yield* broker.invoke<PreviewAutomationStatus>({
1321
+ scope,
1322
+ operation: "open",
1323
+ input: { reuseExistingTab: false, show: false, profileId: "profile-work" },
1324
+ });
1325
+ const tabId = PreviewTabId.make(opened.tabId!);
1326
+ expect(contextRequests).toEqual([{ profileId: "profile-work", isolated: false }]);
1327
+ const page = contexts[0]!.page;
1328
+ page.beforeUnload = "guard";
1329
+ yield* broker.invoke({ scope, tabId, operation: "close", input: {} });
1330
+ // The mock raises the dialog inside `close`, so an unanswered guard leaves the page open here.
1331
+ expect(page.beforeUnloadDialog).not.toBeNull();
1332
+ expect(page.beforeUnloadDialog!.accept).toHaveBeenCalledTimes(1);
1333
+ expect(page.isClosed()).toBe(true);
1334
+ expect(page.unloadEvents).toEqual(["beforeunload", "pagehide", "visibilitychange"]);
1335
+ }),
1336
+ ).pipe(Effect.provide(layer)),
1337
+);
1338
+
1339
it.live("a tab opened to a file the browser cannot show reports the file to download", () =>
1340
Effect.scoped(
1341
Effect.gen(function* () {
apps/server/src/preview/ServerBrowser.ts
+48
-2
@@ -389,6 +389,7 @@ const IDLE_SWEEP_INTERVAL = "1 minute";
389
390
const DOWNLOAD_LIMIT = 20;
391
const ABORTED_NAVIGATION_DOWNLOAD_WAIT_MS = 5_000;
392
+const PAGE_CLOSE_GRACE_MS = 5_000;
393
const DOWNLOAD_MAX_BYTES = 1024 * 1024 * 1024;
394
395
const tabKey = (threadId: string, tabId: string) => `${threadId}\u0000${tabId}`;
@@ -765,6 +766,28 @@ const make = Effect.gen(function* () {
766
767
const sessionOpen = (tab: ServerTab) => !closedSessions.has(tabKey(tab.threadId, tab.tabId));
768
769
+ // Closing the session makes the desktop destroy its webview, which drops an unload still in
770
+ // progress, and `runBeforeUnload` resolves before it runs. So wait for the page's `pagehide`.
771
+ const unloadDesktopPage = async (page: Page) => {
772
+ const unloaded = Promise.withResolvers<void>();
773
+ const timeout = setTimeout(unloaded.resolve, PAGE_CLOSE_GRACE_MS);
774
+ const binding = `__t3PreviewUnloaded${NodeCrypto.randomUUID().replaceAll("-", "")}`;
775
+ void (async () => {
776
+ await page.exposeFunction(binding, unloaded.resolve);
777
+ await page.evaluate((name) => {
778
+ const target = globalThis as unknown as {
779
+ addEventListener: (type: string, listener: () => void) => void;
780
+ };
781
+ target.addEventListener("pagehide", () =>
782
+ Reflect.apply(Reflect.get(target, name), target, []),
783
+ );
784
+ }, binding);
785
+ await page.close({ runBeforeUnload: true });
786
+ })().catch(unloaded.resolve);
787
+ await unloaded.promise;
788
+ clearTimeout(timeout);
789
+ };
790
+
791
const dropTab = (tab: ServerTab, closeSession: boolean) => {
792
const key = tabKey(tab.threadId, tab.tabId);
793
if (tabs.get(key) !== tab) return;
@@ -777,8 +800,22 @@ const make = Effect.gen(function* () {
800
for (const viewer of tab.viewers) viewer.push({ _tag: end });
801
void tab.control.close().catch(constVoid);
802
if (tab.desktop) void tab.desktop.close().catch(constVoid);
780
- else void tab.page.close().catch(constVoid);
781
- if (tab.isolatedContext) void tab.page.context().close().catch(constVoid);
803
+ else {
804
+ const page = tab.page;
805
+ // `runBeforeUnload` returns before the page closes, so closing an isolated context
806
+ // must wait for it. A pending dialog would block `beforeunload` from running at all.
807
+ const closed = page.isClosed()
808
+ ? Promise.resolve()
809
+ : new Promise<void>((resolve) => page.once("close", () => resolve()));
810
+ // A renderer that never finishes unloading would outlive its tab, so force it closed.
811
+ const forceClose = setTimeout(() => void page.close().catch(constVoid), PAGE_CLOSE_GRACE_MS);
812
+ void closed.then(() => clearTimeout(forceClose));
813
+ void page
814
+ .close({ runBeforeUnload: tab.dialog === null })
815
+ .catch(() => page.close())
816
+ .catch(constVoid);
817
+ if (tab.isolatedContext) void closed.then(() => page.context().close()).catch(constVoid);
818
+ }
819
void tab.recording?.encoder.close().catch(constVoid);
820
void NodeFSP.rm(downloadDir(tab), { recursive: true, force: true }).catch(constVoid);
821
reportLiveTabs();
@@ -1036,6 +1073,11 @@ const make = Effect.gen(function* () {
1073
});
1074
});
1075
page.on("dialog", (dialog) => {
1076
+ // Closing is already decided, so an unsaved-changes guard must not keep the page open.
1077
+ if (tab.closing && dialog.type() === "beforeunload") {
1078
+ void dialog.accept().catch(constVoid);
1079
+ return;
1080
+ }
1081
tab.dialog = dialog;
1082
broadcastControl(tab);
1083
});
@@ -2243,6 +2285,10 @@ const make = Effect.gen(function* () {
2285
reason: "humanControl",
2286
});
2287
void tab.control.close().catch(constVoid);
2288
+ if (tab.desktop && tab.dialog === null) {
2289
+ tab.closing = true;
2290
+ await unloadDesktopPage(tab.page);
2291
+ }
2292
await runPromise(manager.close({ threadId: tab.threadId, tabId: tab.tabId }));
2293
dropTab(tab, false);
2294
return {};