@devries-cameron20 / t3code Mirror · read-only / commits / 5df5b44309
Fork 0

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 21, 16:00 UTC

fix(server): a server browser tab survives a renderer crash, and a service worker badge call no longer causes one (#36389)

Julius Marminge committed Nov 13, 2026 at 13:47 UTC 5df5b44309c014cd452f0788a4fe8032135b550b
3 files changed +151 -8
apps/server/src/preview/ServerBrowser.test.ts
+28
@@ -1806,6 +1806,34 @@ it.effect("closing a tab with an unsaved-changes guard still closes it", () =>
1806 ).pipe(Effect.provide(layer)),
1807 );
1808
1809 +it.effect("a tab whose renderer crashes stays open instead of vanishing", () =>
1810 + Effect.scoped(
1811 + Effect.gen(function* () {
1812 + const { browser, broker, tabId } = yield* ready;
1813 + const url = `https://example.com/app?${"a".repeat(3000)}`;
1814 + contexts[0]!.page.commit(url);
1815 + yield* Effect.promise(() => contexts[0]!.page.emitAsync("crash"));
1816 + const status = yield* broker.invoke<PreviewAutomationStatus>({
1817 + scope,
1818 + tabId,
1819 + operation: "status",
1820 + input: {},
1821 + });
1822 + expect(status.tabId).toBe(tabId);
1823 + expect(status.loadError).toEqual({
1824 + url: url.slice(0, 2048),
1825 + code: -2,
1826 + description: "Page crashed",
1827 + });
1828 + // The crashed page cannot load anything again, so Reload goes to the page that replaced it.
1829 + const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
1830 + yield* viewer.input({ type: "takeControl" });
1831 + yield* viewer.input({ type: "reload" });
1832 + expect(contexts[1]!.page.goto).toHaveBeenCalledWith(url, expect.anything());
1833 + }),
1834 + ).pipe(Effect.provide(layer)),
1835 +);
1836 +
1837 it.effect("a tab opened to a file the browser cannot show reports the file to download", () =>
1838 Effect.scoped(
1839 Effect.gen(function* () {
apps/server/src/preview/ServerBrowser.ts
+82 -7
@@ -377,6 +377,10 @@ interface ServerTab {
377 desktopResize: PromiseWithResolvers<void>;
378 loading: boolean;
379 loadError: PreviewAutomationLoadError | undefined;
380 + /** The renderer crash this page died of, or the one the page it replaced died of. */
381 + crash: PreviewAutomationLoadError | undefined;
382 + /** What Reload loads after a crash; the reported URL is shortened and drops data payloads. */
383 + crashedUrl: string | undefined;
384 closing: boolean;
385 recording: Recording | null;
386 initialNavigation: Promise<void> | null;
@@ -586,6 +590,51 @@ const make = Effect.gen(function* () {
590 },
591 });
592
593 + // Playwright cannot reload a crashed page, so a fresh page takes over its tab.
594 + const reopenCrashedTab = async (tab: ServerTab) => {
595 + if (tab.desktop) return dropTab(tab, true);
596 + const key = tabKey(tab.threadId, tab.tabId);
597 + if (tabs.get(key) !== tab) return;
598 + const crash = {
599 + url: ServerBrowserPage.withoutDataPayload(tab.page.url()).slice(0, 2048),
600 + code: -2,
601 + description: "Page crashed",
602 + };
603 + tab.crash = crash;
604 + const reopening = (async () => {
605 + // The session must name the crash before a new page reads it, or it would load the URL again.
606 + await runPromise(
607 + manager
608 + .reportStatus({
609 + threadId: tab.threadId,
610 + tabId: tab.tabId,
611 + serverControlled: true,
612 + navStatus: { _tag: "LoadFailed", title: "", ...crash },
613 + canGoBack: false,
614 + canGoForward: false,
615 + })
616 + .pipe(Effect.ignore),
617 + );
618 + dropTab(tab, false, true);
619 + // A context that is still closing would take the new page down with it.
620 + if (tab.isolatedContext) await tab.page.context().close().catch(constVoid);
621 + const { sessions } = await runPromise(manager.list({ threadId: tab.threadId }));
622 + const snapshot = sessions.find(
623 + (session) => session.tabId === tab.tabId && session.runtime === "server",
624 + );
625 + if (!snapshot) {
626 + throw new ServerBrowserTabNotFoundError({ threadId: tab.threadId, tabId: tab.tabId });
627 + }
628 + return createTab(snapshot, tab.page.url());
629 + })().finally(() => {
630 + pendingTabs.delete(key);
631 + closedPendingTabs.delete(key);
632 + });
633 + // Reserved before the dead page leaves, so a lookup in between waits for its replacement.
634 + pendingTabs.set(key, { agentId: tab.control.agentId, promise: reopening });
635 + await reopening.catch(constVoid);
636 + };
637 +
638 const dialogStatus = (tab: ServerTab) =>
639 tab.dialog
640 ? {
@@ -638,6 +687,8 @@ const make = Effect.gen(function* () {
687 .send("Page.getNavigationHistory")
688 .catch(() => null)
689 .then((history) => {
690 + // A status the dead page still had in flight must not replace the crash.
691 + if (tab.crash) return;
692 const index = history?.currentIndex ?? 0;
693 const count = history?.entries.length ?? 0;
694 runFork(
@@ -832,7 +883,7 @@ const make = Effect.gen(function* () {
883 clearTimeout(timeout);
884 };
885
835 - const dropTab = (tab: ServerTab, closeSession: boolean) => {
886 + const dropTab = (tab: ServerTab, closeSession: boolean, reopening = false) => {
887 const key = tabKey(tab.threadId, tab.tabId);
888 if (tabs.get(key) !== tab) return;
889 tabs.delete(key);
@@ -840,7 +891,8 @@ const make = Effect.gen(function* () {
891 tab.viewerAttached?.resolve();
892 clearAbortedNavigation(tab);
893 // A desktop page outlives the connection unless its session closed with it.
843 - const end = tab.desktop && !closeSession && sessionOpen(tab) ? "reconnect" : "gone";
894 + const end =
895 + (tab.desktop || reopening) && !closeSession && sessionOpen(tab) ? "reconnect" : "gone";
896 for (const viewer of tab.viewers) viewer.push({ _tag: end });
897 void tab.control.close().catch(constVoid);
898 if (tab.desktop) void tab.desktop.close().catch(constVoid);
@@ -855,7 +907,8 @@ const make = Effect.gen(function* () {
907 const forceClose = setTimeout(() => void page.close().catch(constVoid), PAGE_CLOSE_GRACE_MS);
908 void closed.then(() => clearTimeout(forceClose));
909 void page
858 - .close({ runBeforeUnload: tab.dialog === null })
910 + // A crashed page never answers `beforeunload`, so that close would not finish.
911 + .close({ runBeforeUnload: tab.dialog === null && tab.crash === undefined })
912 .catch(() => page.close())
913 .catch(constVoid);
914 if (tab.isolatedContext) void closed.then(() => page.context().close()).catch(constVoid);
@@ -907,10 +960,13 @@ const make = Effect.gen(function* () {
960 }
961 };
962
910 - const createTab = async (snapshot: PreviewSessionSnapshot): Promise<ServerTab> => {
963 + const createTab = async (
964 + snapshot: PreviewSessionSnapshot,
965 + crashedUrl?: string,
966 + ): Promise<ServerTab> => {
967 const opened: Array<() => Promise<void>> = [];
968 try {
913 - return await setUpTab(snapshot, opened);
969 + return await setUpTab(snapshot, opened, crashedUrl);
970 } catch (cause) {
971 // An unpublished tab is in no list, so nothing else would ever close it.
972 for (const close of opened.reverse()) await close().catch(constVoid);
@@ -921,6 +977,7 @@ const make = Effect.gen(function* () {
977 const setUpTab = async (
978 snapshot: PreviewSessionSnapshot,
979 opened: Array<() => Promise<void>>,
980 + crashedUrl: string | undefined,
981 ): Promise<ServerTab> => {
982 const adopted = adoptedPages.get(tabKey(snapshot.threadId, snapshot.tabId));
983 adoptedPages.delete(tabKey(snapshot.threadId, snapshot.tabId));
@@ -1009,6 +1066,16 @@ const make = Effect.gen(function* () {
1066 desktopResize: Promise.withResolvers<void>(),
1067 loading: false,
1068 loadError: undefined,
1069 + // The page a crash left behind is blank; the session still names what crashed.
1070 + crash:
1071 + !desktop && !adopted && snapshot.navStatus._tag === "LoadFailed"
1072 + ? {
1073 + url: snapshot.navStatus.url,
1074 + code: snapshot.navStatus.code,
1075 + description: snapshot.navStatus.description,
1076 + }
1077 + : undefined,
1078 + crashedUrl,
1079 closing: false,
1080 recording: null,
1081 recordingStart: null,
@@ -1060,6 +1127,8 @@ const make = Effect.gen(function* () {
1127 clearAbortedNavigation(tab);
1128 tab.loading = true;
1129 tab.loadError = undefined;
1130 + tab.crash = undefined;
1131 + tab.crashedUrl = undefined;
1132 if (stoppedInitialRequest) {
1133 tab.stoppedGeneration = tab.navigationGeneration;
1134 settleStoppedNavigation(tab, tab.navigationGeneration);
@@ -1158,14 +1227,13 @@ const make = Effect.gen(function* () {
1227 updateFileChooserInterception(tab);
1228 // Popups become tabs and keep `window.opener`, so sign-in popups can report back.
1229 page.on("popup", (popup) => void adoptPopup(tab, popup));
1161 - // Playwright cannot reload a crashed page, so it must leave the tab list.
1230 const key = tabKey(tab.threadId, tab.tabId);
1231 if (closedPendingTabs.delete(key)) {
1232 await control.close().catch(constVoid);
1233 throw new ServerBrowserTabNotFoundError({ threadId: tab.threadId, tabId: tab.tabId });
1234 }
1235 page.on("close", () => dropTab(tab, true));
1168 - page.on("crash", () => dropTab(tab, true));
1236 + page.on("crash", () => reopenCrashedTab(tab));
1237 tabs.set(key, tab);
1238 reportLiveTabs();
1239 // A desktop page navigates on its own and can finish loading before these listeners attach.
@@ -1828,6 +1896,7 @@ const make = Effect.gen(function* () {
1896 };
1897
1898 const loadErrorOf = (tab: ServerTab): PreviewAutomationLoadError | undefined => {
1899 + if (tab.crash) return tab.crash;
1900 if (!tab.page.url().startsWith("chrome-error://")) return undefined;
1901 // A desktop failure from before CDP attached is superseded by any navigation we observe.
1902 if (tab.loadError || !tab.desktop || tab.navigationGeneration > 0) return tab.loadError;
@@ -2908,6 +2977,12 @@ const make = Effect.gen(function* () {
2977 }
2978 case "reload":
2979 tab.pendingInitialRequestUrl = null;
2980 + if (tab.crash) {
2981 + tab.control.trackUntilHandoff(
2982 + tab.page.goto(tab.crashedUrl ?? tab.crash.url, VIEWER_NAVIGATION_OPTIONS),
2983 + );
2984 + return;
2985 + }
2986 if (message.ignoreCache === true) {
2987 await session.send("Page.reload", { ignoreCache: true });
2988 return;
apps/server/src/preview/ServerBrowserContexts.ts
+41 -1
@@ -14,6 +14,43 @@ 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>;
@@ -127,6 +164,7 @@ export class ServerBrowserContexts {
164 const browser = await this.launch(executable, (executablePath) =>
165 chromium.launch({ ...options, executablePath }),
166 );
167 + stubWorkerBadges(browser);
168 browser.on("disconnected", () => {
169 if (this.browser === launched) this.browser = undefined;
170 });
@@ -207,13 +245,15 @@ export class ServerBrowserContexts {
245 await NodeFSP.mkdir(directory, { recursive: true });
246 const { executable, ...options } = await this.launchOptions();
247 const { chromium } = loadPlaywright();
210 - return this.launch(executable, (executablePath) =>
248 + const context = await this.launch(executable, (executablePath) =>
249 chromium.launchPersistentContext(directory, {
250 ...options,
251 ...contextOptions,
252 executablePath,
253 }),
254 );
255 + stubWorkerBadges(context);
256 + return context;
257 }
258
259 private profileDirectory(profileId: string) {