Skip to content

Commit 5df5b44

Browse files
fix(server): a server browser tab survives a renderer crash, and a service worker badge call no longer causes one (#36389)
1 parent 94aa3d7 commit 5df5b44

3 files changed

Lines changed: 151 additions & 8 deletions

File tree

‎apps/server/src/preview/ServerBrowser.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1806,6 +1806,34 @@ it.effect("closing a tab with an unsaved-changes guard still closes it", () =>
18061806
).pipe(Effect.provide(layer)),
18071807
);
18081808

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+
18091837
it.effect("a tab opened to a file the browser cannot show reports the file to download", () =>
18101838
Effect.scoped(
18111839
Effect.gen(function* () {

‎apps/server/src/preview/ServerBrowser.ts‎

Lines changed: 82 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,10 @@ interface ServerTab {
377377
desktopResize: PromiseWithResolvers<void>;
378378
loading: boolean;
379379
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;
380384
closing: boolean;
381385
recording: Recording | null;
382386
initialNavigation: Promise<void> | null;
@@ -586,6 +590,51 @@ const make = Effect.gen(function* () {
586590
},
587591
});
588592

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+
589638
const dialogStatus = (tab: ServerTab) =>
590639
tab.dialog
591640
? {
@@ -638,6 +687,8 @@ const make = Effect.gen(function* () {
638687
.send("Page.getNavigationHistory")
639688
.catch(() => null)
640689
.then((history) => {
690+
// A status the dead page still had in flight must not replace the crash.
691+
if (tab.crash) return;
641692
const index = history?.currentIndex ?? 0;
642693
const count = history?.entries.length ?? 0;
643694
runFork(
@@ -832,15 +883,16 @@ const make = Effect.gen(function* () {
832883
clearTimeout(timeout);
833884
};
834885

835-
const dropTab = (tab: ServerTab, closeSession: boolean) => {
886+
const dropTab = (tab: ServerTab, closeSession: boolean, reopening = false) => {
836887
const key = tabKey(tab.threadId, tab.tabId);
837888
if (tabs.get(key) !== tab) return;
838889
tabs.delete(key);
839890
tab.closing = true;
840891
tab.viewerAttached?.resolve();
841892
clearAbortedNavigation(tab);
842893
// 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";
844896
for (const viewer of tab.viewers) viewer.push({ _tag: end });
845897
void tab.control.close().catch(constVoid);
846898
if (tab.desktop) void tab.desktop.close().catch(constVoid);
@@ -855,7 +907,8 @@ const make = Effect.gen(function* () {
855907
const forceClose = setTimeout(() => void page.close().catch(constVoid), PAGE_CLOSE_GRACE_MS);
856908
void closed.then(() => clearTimeout(forceClose));
857909
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 })
859912
.catch(() => page.close())
860913
.catch(constVoid);
861914
if (tab.isolatedContext) void closed.then(() => page.context().close()).catch(constVoid);
@@ -907,10 +960,13 @@ const make = Effect.gen(function* () {
907960
}
908961
};
909962

910-
const createTab = async (snapshot: PreviewSessionSnapshot): Promise<ServerTab> => {
963+
const createTab = async (
964+
snapshot: PreviewSessionSnapshot,
965+
crashedUrl?: string,
966+
): Promise<ServerTab> => {
911967
const opened: Array<() => Promise<void>> = [];
912968
try {
913-
return await setUpTab(snapshot, opened);
969+
return await setUpTab(snapshot, opened, crashedUrl);
914970
} catch (cause) {
915971
// An unpublished tab is in no list, so nothing else would ever close it.
916972
for (const close of opened.reverse()) await close().catch(constVoid);
@@ -921,6 +977,7 @@ const make = Effect.gen(function* () {
921977
const setUpTab = async (
922978
snapshot: PreviewSessionSnapshot,
923979
opened: Array<() => Promise<void>>,
980+
crashedUrl: string | undefined,
924981
): Promise<ServerTab> => {
925982
const adopted = adoptedPages.get(tabKey(snapshot.threadId, snapshot.tabId));
926983
adoptedPages.delete(tabKey(snapshot.threadId, snapshot.tabId));
@@ -1009,6 +1066,16 @@ const make = Effect.gen(function* () {
10091066
desktopResize: Promise.withResolvers<void>(),
10101067
loading: false,
10111068
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,
10121079
closing: false,
10131080
recording: null,
10141081
recordingStart: null,
@@ -1060,6 +1127,8 @@ const make = Effect.gen(function* () {
10601127
clearAbortedNavigation(tab);
10611128
tab.loading = true;
10621129
tab.loadError = undefined;
1130+
tab.crash = undefined;
1131+
tab.crashedUrl = undefined;
10631132
if (stoppedInitialRequest) {
10641133
tab.stoppedGeneration = tab.navigationGeneration;
10651134
settleStoppedNavigation(tab, tab.navigationGeneration);
@@ -1158,14 +1227,13 @@ const make = Effect.gen(function* () {
11581227
updateFileChooserInterception(tab);
11591228
// Popups become tabs and keep `window.opener`, so sign-in popups can report back.
11601229
page.on("popup", (popup) => void adoptPopup(tab, popup));
1161-
// Playwright cannot reload a crashed page, so it must leave the tab list.
11621230
const key = tabKey(tab.threadId, tab.tabId);
11631231
if (closedPendingTabs.delete(key)) {
11641232
await control.close().catch(constVoid);
11651233
throw new ServerBrowserTabNotFoundError({ threadId: tab.threadId, tabId: tab.tabId });
11661234
}
11671235
page.on("close", () => dropTab(tab, true));
1168-
page.on("crash", () => dropTab(tab, true));
1236+
page.on("crash", () => reopenCrashedTab(tab));
11691237
tabs.set(key, tab);
11701238
reportLiveTabs();
11711239
// A desktop page navigates on its own and can finish loading before these listeners attach.
@@ -1828,6 +1896,7 @@ const make = Effect.gen(function* () {
18281896
};
18291897

18301898
const loadErrorOf = (tab: ServerTab): PreviewAutomationLoadError | undefined => {
1899+
if (tab.crash) return tab.crash;
18311900
if (!tab.page.url().startsWith("chrome-error://")) return undefined;
18321901
// A desktop failure from before CDP attached is superseded by any navigation we observe.
18331902
if (tab.loadError || !tab.desktop || tab.navigationGeneration > 0) return tab.loadError;
@@ -2908,6 +2977,12 @@ const make = Effect.gen(function* () {
29082977
}
29092978
case "reload":
29102979
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+
}
29112986
if (message.ignoreCache === true) {
29122987
await session.send("Page.reload", { ignoreCache: true });
29132988
return;

‎apps/server/src/preview/ServerBrowserContexts.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,43 @@ const requirePlaywright = NodeModule.createRequire(import.meta.url);
1414
const loadPlaywright = () =>
1515
requirePlaywright("playwright-core") as typeof import("playwright-core");
1616

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+
1754
interface Options {
1855
readonly profilesDir: string;
1956
readonly executable: () => Promise<string>;
@@ -127,6 +164,7 @@ export class ServerBrowserContexts {
127164
const browser = await this.launch(executable, (executablePath) =>
128165
chromium.launch({ ...options, executablePath }),
129166
);
167+
stubWorkerBadges(browser);
130168
browser.on("disconnected", () => {
131169
if (this.browser === launched) this.browser = undefined;
132170
});
@@ -207,13 +245,15 @@ export class ServerBrowserContexts {
207245
await NodeFSP.mkdir(directory, { recursive: true });
208246
const { executable, ...options } = await this.launchOptions();
209247
const { chromium } = loadPlaywright();
210-
return this.launch(executable, (executablePath) =>
248+
const context = await this.launch(executable, (executablePath) =>
211249
chromium.launchPersistentContext(directory, {
212250
...options,
213251
...contextOptions,
214252
executablePath,
215253
}),
216254
);
255+
stubWorkerBadges(context);
256+
return context;
217257
}
218258

219259
private profileDirectory(profileId: string) {

0 commit comments

Comments
 (0)