@devries-cameron20 / t3code Mirror · read-only / commits / a37715c1e7
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): preview navigation leaves a page whose script never yields (#36365)

Julius Marminge committed Nov 13, 2026 at 17:13 UTC a37715c1e7e382d95afcca73a6341f2ba39f8bd0
6 files changed +216 -7
apps/desktop/src/preview/Manager.test.ts
+68
@@ -746,6 +746,74 @@ describe("PreviewManager", () => {
746 ),
747 );
748
749 + effectIt.effect.each([
750 + "navigate",
751 + "reload",
752 + "goBack",
753 + "goForward",
754 + "refresh",
755 + "hardReload",
756 + ] as const)("%s stops a page script that never yields before it navigates", (operation) =>
757 + withManager((manager) =>
758 + Effect.gen(function* () {
759 + const preview = makeFaviconWebContents();
760 + // As in Chromium: the hung renderer answers nothing, and a terminate reaches it only
761 + // while no navigation is pending.
762 + let stopped = false;
763 + const probed = yield* Deferred.make<void>();
764 + const navigatedAfterStop: Array<boolean> = [];
765 + const navigated = () => {
766 + navigatedAfterStop.push(stopped);
767 + };
768 + const sendCommand = async (method: string) => {
769 + if (method === "Runtime.evaluate") {
770 + Deferred.doneUnsafe(probed, Effect.void);
771 + await new Promise(() => {});
772 + }
773 + if (method === "Runtime.terminateExecution") stopped = true;
774 + };
775 + Object.assign(preview.webContents, {
776 + getURL: () => "http://localhost:5173/busy",
777 + reload: navigated,
778 + reloadIgnoringCache: navigated,
779 + loadURL: async () => navigated(),
780 + navigationHistory: {
781 + canGoBack: () => true,
782 + canGoForward: () => true,
783 + goBack: navigated,
784 + goForward: navigated,
785 + },
786 + debugger: {
787 + isAttached: () => false,
788 + attach: vi.fn(),
789 + sendCommand,
790 + on: vi.fn(),
791 + off: vi.fn(),
792 + },
793 + });
794 + fromId.mockReturnValue(preview.webContents);
795 + yield* manager.createTab("tab_busy");
796 + yield* manager.registerWebview("tab_busy", 42);
797 +
798 + const leaving = yield* (
799 + operation === "navigate"
800 + ? manager.navigate("tab_busy", "http://localhost:5173/next")
801 + : operation === "reload"
802 + ? manager.navigate("tab_busy", "http://localhost:5173/busy")
803 + : manager[operation]("tab_busy")
804 + ).pipe(Effect.forkChild);
805 + const probing = yield* Effect.raceFirst(
806 + Deferred.await(probed).pipe(Effect.as(true)),
807 + Fiber.await(leaving).pipe(Effect.as(false)),
808 + );
809 + if (probing) yield* TestClock.adjust(1_000);
810 + yield* Fiber.join(leaving);
811 +
812 + expect(navigatedAfterStop).toEqual([true]);
813 + }),
814 + ),
815 + );
816 +
817 effectIt.effect("keeps mouse back and forward buttons inside the preview tab", () =>
818 withManager((manager) =>
819 Effect.gen(function* () {
apps/desktop/src/preview/Manager.ts
+38 -4
@@ -136,6 +136,7 @@ const PICTURE_IN_PICTURE_JPEG_QUALITY = 80;
136 const CAPTURE_PAGE_RETRY_ATTEMPTS = 3;
137 const CAPTURE_PAGE_RETRY_DELAY_MS = 120;
138 const CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS = 1_000;
139 +const BUSY_PAGE_PROBE_MS = 1_000;
140 const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480;
141 const PICTURE_IN_PICTURE_INITIAL_HEIGHT = 320;
142 const PICTURE_IN_PICTURE_MIN_WIDTH = 240;
@@ -2038,6 +2039,28 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2039 );
2040 });
2041
2042 + /**
2043 + * A same-site navigation reuses the renderer, so it never commits while a page script holds it.
2044 + * Runs before the navigation starts: Chromium does not deliver a terminate once one is pending.
2045 + */
2046 + const leaveBusyPage = Effect.fn("PreviewManager.leaveBusyPage")(function* (
2047 + wc: Electron.WebContents,
2048 + ) {
2049 + const control = (yield* SynchronizedRef.get(controlSessionsRef)).get(wc.id);
2050 + if (!control) return;
2051 + const answered = yield* Effect.promise(() =>
2052 + control.debugger.sendCommand("Runtime.evaluate", { expression: "0" }).then(
2053 + () => undefined,
2054 + () => undefined,
2055 + ),
2056 + ).pipe(Effect.timeoutOption(BUSY_PAGE_PROBE_MS));
2057 + if (Option.isSome(answered)) return;
2058 + // Not awaited: a renderer blocked on something other than script may never acknowledge it.
2059 + yield* Effect.sync(() => {
2060 + void control.debugger.sendCommand("Runtime.terminateExecution").catch(() => undefined);
2061 + });
2062 + });
2063 +
2064 const navigate = Effect.fn("PreviewManager.navigate")(function* (tabId: string, rawUrl: string) {
2065 const url = yield* attempt({ operation: "navigate.normalizeUrl", tabId }, () =>
2066 normalizePreviewUrl(rawUrl),
@@ -2120,6 +2143,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2143 );
2144 return;
2145 }
2146 + yield* leaveBusyPage(wc);
2147 if (wc.getURL() === url) {
2148 yield* attempt({ operation: "navigate.reload", tabId, webContentsId: wc.id }, () =>
2149 wc.reload(),
@@ -2155,18 +2179,28 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2179 yield* attempt({ operation, tabId, webContentsId: wc.id }, () => use(wc));
2180 });
2181
2182 + const leavePage = Effect.fn("PreviewManager.leavePage")(function* (
2183 + operation: string,
2184 + tabId: string,
2185 + use: (wc: Electron.WebContents) => void,
2186 + ) {
2187 + const wc = yield* requireWebContents(tabId);
2188 + yield* leaveBusyPage(wc);
2189 + yield* attempt({ operation, tabId, webContentsId: wc.id }, () => use(wc));
2190 + });
2191 +
2192 const goBack = (tabId: string) =>
2159 - withWebContents("goBack", tabId, (wc) => {
2193 + leavePage("goBack", tabId, (wc) => {
2194 if (wc.navigationHistory.canGoBack()) wc.navigationHistory.goBack();
2195 });
2196 const goForward = (tabId: string) =>
2163 - withWebContents("goForward", tabId, (wc) => {
2197 + leavePage("goForward", tabId, (wc) => {
2198 if (wc.navigationHistory.canGoForward()) wc.navigationHistory.goForward();
2199 });
2166 - const refresh = (tabId: string) => withWebContents("refresh", tabId, (wc) => wc.reload());
2200 + const refresh = (tabId: string) => leavePage("refresh", tabId, (wc) => wc.reload());
2201 const stopLoading = (tabId: string) => withWebContents("stopLoading", tabId, (wc) => wc.stop());
2202 const hardReload = (tabId: string) =>
2169 - withWebContents("hardReload", tabId, (wc) => wc.reloadIgnoringCache());
2203 + leavePage("hardReload", tabId, (wc) => wc.reloadIgnoringCache());
2204 const findInPage = (
2205 tabId: string,
2206 text: string,
apps/server/src/preview/ServerBrowser.test.ts
+68
@@ -802,6 +802,74 @@ it.effect("a desktop status answers with the last viewport while the renderer ca
802 ).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers())), Effect.provide(layer)),
803 );
804
805 +it.effect.each([
806 + { name: "an agent navigate", message: null },
807 + { name: "a viewer navigate", message: { type: "navigate", url: "http://localhost:5173/next" } },
808 + { name: "a viewer Back", message: { type: "history", delta: -1 } },
809 + { name: "a viewer Forward", message: { type: "history", delta: 1 } },
810 + { name: "a viewer Reload", message: { type: "reload" } },
811 + { name: "a viewer hard reload", message: { type: "reload", ignoreCache: true } },
812 +])("$name stops a page script that never yields before it navigates", ({ message }) =>
813 + Effect.scoped(
814 + Effect.gen(function* () {
815 + const { browser, broker, tabId } = yield* ready;
816 + const viewer = message ? yield* browser.attachViewer(viewerInput(tabId, true)) : null;
817 + if (viewer) yield* viewer.input({ type: "takeControl" });
818 + const { page, sessions } = contexts[0]!;
819 + // As in Chrome: the hung renderer answers nothing, and a terminate reaches it only while
820 + // no navigation is pending.
821 + let stopped = false;
822 + const probed = Promise.withResolvers<void>();
823 + const navigatedAfterStop: Array<boolean> = [];
824 + for (const cdp of sessions) {
825 + const send = cdp.send.getMockImplementation()!;
826 + cdp.send.mockImplementation((method, input) => {
827 + if (
828 + method === "Runtime.evaluate" &&
829 + (input as { expression: string }).expression === "0"
830 + ) {
831 + probed.resolve();
832 + return new Promise(() => {});
833 + }
834 + if (method === "Runtime.terminateExecution") stopped = true;
835 + if (method === "Page.reload") navigatedAfterStop.push(stopped);
836 + return send(method, input);
837 + });
838 + }
839 + const goto = page.goto.getMockImplementation()!;
840 + page.goto.mockImplementation(async (next, options) => {
841 + navigatedAfterStop.push(stopped);
842 + return goto(next, options);
843 + });
844 + for (const method of ["goBack", "goForward", "reload"] as const) {
845 + page[method].mockImplementation(async () => {
846 + navigatedAfterStop.push(stopped);
847 + });
848 + }
849 +
850 + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
851 + const result = yield* (
852 + viewer
853 + ? viewer.input(message)
854 + : broker.invoke<PreviewAutomationStatus>({
855 + scope,
856 + tabId,
857 + operation: "navigate",
858 + input: { url: "http://localhost:5173/next", timeoutMs: 5_000 },
859 + })
860 + ).pipe(Effect.forkScoped);
861 + const probing = yield* Effect.raceFirst(
862 + Effect.promise(() => probed.promise).pipe(Effect.as(true)),
863 + Fiber.await(result).pipe(Effect.as(false)),
864 + );
865 + if (probing) yield* Effect.promise(() => vi.advanceTimersByTimeAsync(1_000));
866 + yield* Fiber.join(result);
867 +
868 + expect(navigatedAfterStop).toEqual([true]);
869 + }),
870 + ).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers())), Effect.provide(layer)),
871 +);
872 +
873 it.live("navigate fails when the page never commits within its timeout", () =>
874 Effect.scoped(
875 Effect.gen(function* () {
apps/server/src/preview/ServerBrowser.ts
+14 -3
@@ -2017,6 +2017,10 @@ const make = Effect.gen(function* () {
2017 return `${target.protocol ?? "http"}://localhost:${target.port}${path.startsWith("/") || path === "" ? path : `/${path}`}`;
2018 };
2019
2020 + /** A pending dialog also leaves the probe unanswered, but its script is waiting, not stuck. */
2021 + const leaveBusyPage = (tab: ServerTab, cdp: CDPSession, budgetMs?: number) =>
2022 + tab.dialog ? Promise.resolve() : ServerBrowserPage.stopUnresponsiveScript(cdp, budgetMs);
2023 +
2024 const navigate = async (
2025 tab: ServerTab,
2026 url: string,
@@ -2025,7 +2029,9 @@ const make = Effect.gen(function* () {
2029 ) => {
2030 tab.pendingInitialRequestUrl = null;
2031 const startedAt = performance.now();
2028 - const navigation = tab.page.goto(url, { timeout, waitUntil: "commit" });
2032 + const remaining = () => Math.max(1, timeout - (performance.now() - startedAt));
2033 + await leaveBusyPage(tab, tab.cdp, timeout / 2);
2034 + const navigation = tab.page.goto(url, { timeout: remaining(), waitUntil: "commit" });
2035 if (readiness === "none") {
2036 tab.control.track(navigation);
2037 return;
@@ -2034,7 +2040,7 @@ const make = Effect.gen(function* () {
2040 const ready = () =>
2041 tab.page
2042 .waitForLoadState(readiness === "domContentLoaded" ? "domcontentloaded" : "load", {
2037 - timeout: Math.max(1, timeout - (performance.now() - startedAt)),
2043 + timeout: remaining(),
2044 })
2045 .catch((cause: unknown) => {
2046 if (!(cause instanceof Error && cause.name === "TimeoutError")) throw cause;
@@ -2812,6 +2818,7 @@ const make = Effect.gen(function* () {
2818 if (request?.clear === "cache") await tab.cdp.send("Network.clearBrowserCache");
2819 if (request?.hardReload) {
2820 tab.pendingInitialRequestUrl = null;
2821 + await leaveBusyPage(tab, tab.cdp);
2822 await tab.cdp.send("Page.reload", { ignoreCache: true });
2823 }
2824 })
@@ -2951,16 +2958,19 @@ const make = Effect.gen(function* () {
2958 await applySetting(tab, setting);
2959 return;
2960 }
2954 - // A stalled navigation must not block a corrected URL or further viewer input.
2961 + // A stalled navigation must not block a corrected URL or further viewer input; only the
2962 + // bounded wait for a page script that never yields comes first.
2963 case "navigate":
2964 if (typeof message.url === "string") {
2965 const url = normalizePreviewUrl(message.url);
2966 tab.pendingInitialRequestUrl = null;
2967 + await leaveBusyPage(tab, session);
2968 tab.control.trackUntilHandoff(tab.page.goto(url, VIEWER_NAVIGATION_OPTIONS));
2969 }
2970 return;
2971 case "history":
2972 tab.pendingInitialRequestUrl = null;
2973 + await leaveBusyPage(tab, session);
2974 tab.control.trackUntilHandoff(
2975 num(message.delta) < 0
2976 ? tab.page.goBack(VIEWER_NAVIGATION_OPTIONS)
@@ -2983,6 +2993,7 @@ const make = Effect.gen(function* () {
2993 );
2994 return;
2995 }
2996 + await leaveBusyPage(tab, session);
2997 if (message.ignoreCache === true) {
2998 await session.send("Page.reload", { ignoreCache: true });
2999 return;
apps/server/src/preview/ServerBrowserPage.test.ts
+8
@@ -717,6 +717,14 @@ describe("server browser evaluate", () => {
717 });
718 });
719
720 +describe("server browser unresponsive script", () => {
721 + it("leaves a page that answers alone", async () => {
722 + const send = vi.fn(async (_method: string) => ({}));
723 + await ServerBrowserPage.stopUnresponsiveScript({ send } as unknown as CDPSession);
724 + expect(send.mock.calls.map(([method]) => method)).toEqual(["Runtime.evaluate"]);
725 + });
726 +});
727 +
728 describe("server browser wait", () => {
729 it("ends at its timeout when a check never answers", async () => {
730 // As on a desktop tab whose Playwright utility world never answers.
apps/server/src/preview/ServerBrowserPage.ts
+20
@@ -953,6 +953,26 @@ export const scroll = async (page: Page, input: PreviewAutomationScrollInput) =>
953 await locator.evaluate((element, [x, y]) => element.scrollBy(x, y), delta);
954 };
955
956 +const UNRESPONSIVE_SCRIPT_PROBE_MS = 1_000;
957 +
958 +/**
959 + * A same-site navigation reuses the renderer, so it never commits while a page script holds it.
960 + * Call before starting the navigation: Chrome does not deliver a terminate once one is pending.
961 + */
962 +export const stopUnresponsiveScript = async (cdp: CDPSession, budgetMs = Infinity) => {
963 + let timer: ReturnType<typeof setTimeout> | undefined;
964 + const answered = cdp.send("Runtime.evaluate", { expression: "0" }).then(
965 + () => true,
966 + () => true,
967 + );
968 + const expired = new Promise<boolean>((resolve) => {
969 + timer = setTimeout(() => resolve(false), Math.min(budgetMs, UNRESPONSIVE_SCRIPT_PROBE_MS));
970 + });
971 + const responsive = await Promise.race([answered, expired]).finally(() => clearTimeout(timer));
972 + // Not awaited: a renderer blocked on something other than script may never acknowledge it.
973 + if (!responsive) void cdp.send("Runtime.terminateExecution").catch(constVoid);
974 +};
975 +
976 /** Terminate expired page scripts so a hung expression cannot block the tab's control queue. */
977 export const evaluate = async (
978 cdp: CDPSession,