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, 17:15 UTC
fix(server): preview_navigate returns the committed page when load is slow (#26127)
Co-authored-by: Elliot Drel <elliotdrel@gmail.com>
Julius Marminge committed
Nov 12, 2026 at 20:32 UTC
67d91a0390d0cc189b783187a081d792fe3a731f
2 files changed
+167
-18
apps/server/src/preview/ServerBrowser.test.ts
+129
-2
@@ -204,12 +204,15 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = "
204
mainFrame: () => page,
205
frames: () => [page],
206
url: () => url,
207
+ commit: (next: string) => {
208
+ url = next;
209
+ },
210
title: vi.fn(async () => "test page"),
211
viewportSize: vi.fn(() => viewport),
212
setViewportSize: vi.fn(async (size: typeof viewport) => {
213
viewport = size;
214
}),
212
- goto: vi.fn(async (next: string) => {
215
+ goto: vi.fn(async (next: string, _options?: { timeout?: number; waitUntil?: string }) => {
216
url = next;
217
events.emit("load");
218
const pending = initialNavigation;
@@ -220,7 +223,7 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = "
223
goForward: vi.fn(async () => {}),
224
reload: vi.fn(async () => {}),
225
emulateMedia: vi.fn(async () => {}),
223
- waitForLoadState: vi.fn(async () => {}),
226
+ waitForLoadState: vi.fn(async (_state?: string, _options?: { timeout?: number }) => {}),
227
evaluate: vi.fn(async () => ({
228
url,
229
title: "test page",
@@ -693,6 +696,130 @@ it.live("an initial download stays available after preview_open reports the navi
696
).pipe(Effect.provide(layer)),
697
);
698
699
+it.effect.each([
700
+ { renderer: "idle", title: "Heavy page" },
701
+ { renderer: "busy", title: null },
702
+])(
703
+ "navigate returns the committed page while its load event is still pending ($renderer renderer)",
704
+ ({ renderer, title }) =>
705
+ Effect.scoped(
706
+ Effect.gen(function* () {
707
+ const { broker, tabId } = yield* ready;
708
+ const page = contexts[0]!.page;
709
+ const titleRequested = Promise.withResolvers<void>();
710
+ // A busy main thread never answers title(); drive its native deadline explicitly.
711
+ page.title.mockImplementation(() => {
712
+ titleRequested.resolve();
713
+ return renderer === "busy"
714
+ ? new Promise<string>(() => {})
715
+ : Promise.resolve("Heavy page");
716
+ });
717
+ const heavy = "http://localhost:5173/heavy";
718
+ const timedOut = (method: string, timeout: number | undefined) =>
719
+ Object.assign(new Error(`${method}: Timeout ${timeout}ms exceeded.`), {
720
+ name: "TimeoutError",
721
+ });
722
+ // The document commits and parses, but a stalled subresource holds back `load`.
723
+ page.goto.mockImplementation(async (next, options) => {
724
+ page.commit(next);
725
+ page.emit("request", {
726
+ url: () => next,
727
+ isNavigationRequest: () => true,
728
+ frame: () => page,
729
+ });
730
+ if (options?.waitUntil === "load") throw timedOut("page.goto", options.timeout);
731
+ });
732
+ page.waitForLoadState.mockImplementation(async (state, options) => {
733
+ if (state === undefined || state === "load") {
734
+ throw timedOut("page.waitForLoadState", options?.timeout);
735
+ }
736
+ });
737
+
738
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
739
+ const result = yield* broker
740
+ .invoke<PreviewAutomationStatus>({
741
+ scope,
742
+ tabId,
743
+ operation: "navigate",
744
+ input: { url: heavy, timeoutMs: 4_000 },
745
+ })
746
+ .pipe(Effect.forkScoped);
747
+ const titleRead = yield* Effect.raceFirst(
748
+ Effect.promise(() => titleRequested.promise).pipe(Effect.as(true)),
749
+ Fiber.await(result).pipe(Effect.as(false)),
750
+ );
751
+ if (titleRead && renderer === "busy") {
752
+ yield* Effect.promise(() => vi.advanceTimersByTimeAsync(250));
753
+ }
754
+ const status = yield* Fiber.join(result);
755
+
756
+ expect(status).toMatchObject({ url: heavy, title, loading: true });
757
+ }),
758
+ ).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers())), Effect.provide(layer)),
759
+);
760
+
761
+it.effect("a desktop status answers with the last viewport while the renderer cannot measure", () =>
762
+ Effect.scoped(
763
+ Effect.gen(function* () {
764
+ const { broker } = yield* ready;
765
+ desktopRendersNext = true;
766
+ const opened = yield* broker.invoke<PreviewAutomationStatus>({
767
+ scope,
768
+ operation: "open",
769
+ input: { url: "https://example.com/", reuseExistingTab: false, show: false },
770
+ });
771
+ const measuring = Promise.withResolvers<void>();
772
+ desktopSizeAnswer = () => {
773
+ measuring.resolve();
774
+ return new Promise(() => {});
775
+ };
776
+ // A resize makes the next status measure again.
777
+ yield* Effect.promise(() =>
778
+ desktopConnections[0]!.context.sessions[0]!.emitAsync("Page.frameResized"),
779
+ );
780
+
781
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
782
+ const result = yield* broker
783
+ .invoke<PreviewAutomationStatus>({
784
+ scope,
785
+ tabId: opened.tabId!,
786
+ operation: "status",
787
+ input: {},
788
+ })
789
+ .pipe(Effect.forkScoped);
790
+ yield* Effect.promise(() => measuring.promise);
791
+ yield* Effect.promise(() => vi.advanceTimersByTimeAsync(250));
792
+ const status = yield* Fiber.join(result);
793
+
794
+ expect(status.viewport).toEqual({ width: 1920, height: 1080 });
795
+ }),
796
+ ).pipe(Effect.ensuring(Effect.sync(() => vi.useRealTimers())), Effect.provide(layer)),
797
+);
798
+
799
+it.live("navigate fails when the page never commits within its timeout", () =>
800
+ Effect.scoped(
801
+ Effect.gen(function* () {
802
+ const { broker, tabId } = yield* ready;
803
+ contexts[0]!.page.goto.mockImplementation(async () => {
804
+ throw Object.assign(new Error("page.goto: Timeout 4000ms exceeded."), {
805
+ name: "TimeoutError",
806
+ });
807
+ });
808
+
809
+ const error = yield* broker
810
+ .invoke<PreviewAutomationStatus>({
811
+ scope,
812
+ tabId,
813
+ operation: "navigate",
814
+ input: { url: "http://10.255.255.1/", timeoutMs: 4_000 },
815
+ })
816
+ .pipe(Effect.flip);
817
+
818
+ expect(error).toMatchObject({ _tag: "PreviewAutomationTimeoutError", timeoutMs: 4_000 });
819
+ }),
820
+ ).pipe(Effect.provide(layer)),
821
+);
822
+
823
it.live.each(["desktop" as const, undefined])(
824
"explicit desktop targets ($0 runtime) fail without creating a server tab",
825
(runtime) =>
apps/server/src/preview/ServerBrowser.ts
+38
-16
@@ -160,6 +160,8 @@ const EDITABLE_AT_POINT_SCRIPT = `(x, y) => {
160
}`;
161
const UNATTACHED_FILL_VIEWPORT = { width: 1280, height: 800 } as const;
162
const NAVIGATION_TIMEOUT_MS = 15_000;
163
+// Status reads run in the renderer; a busy page must not hold a status past the broker's grace.
164
+const STATUS_READ_MS = 250;
165
const VIEWER_NAVIGATION_OPTIONS = { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS } as const;
166
const ACTION_TIMELINE_LIMIT = 50;
167
@@ -1823,6 +1825,14 @@ const make = Effect.gen(function* () {
1825
}
1826
};
1827
1828
+ const withinStatusDeadline = <A>(read: Promise<A>, late: () => A): Promise<A> => {
1829
+ let timer: ReturnType<typeof setTimeout> | undefined;
1830
+ const deadline = new Promise<A>((resolve) => {
1831
+ timer = setTimeout(() => resolve(late()), STATUS_READ_MS);
1832
+ });
1833
+ return Promise.race([read, deadline]).finally(() => clearTimeout(timer));
1834
+ };
1835
+
1836
const statusWithTitle = async (
1837
tab: ServerTab | undefined,
1838
agentSessionId?: string,
@@ -1839,14 +1849,26 @@ const make = Effect.gen(function* () {
1849
};
1850
}
1851
const url = ServerBrowserPage.withoutDataPayload(tab.page.url());
1842
- const viewport = tab.desktop ? await desktopStatusViewport(tab) : tab.page.viewportSize();
1852
const loadError = loadErrorOf(tab);
1844
- const status = {
1853
+ const statusUrl = loadError?.url ?? (url === "about:blank" ? null : url);
1854
+ const [viewport, title] = await Promise.all([
1855
+ // A late measurement still lands in desktopViewport for the next status.
1856
+ tab.desktop
1857
+ ? withinStatusDeadline(desktopStatusViewport(tab), () => tab.desktopViewport)
1858
+ : tab.page.viewportSize(),
1859
+ statusUrl === null || tab.dialog
1860
+ ? null
1861
+ : withinStatusDeadline(
1862
+ tab.page.title().catch(() => ""),
1863
+ () => "",
1864
+ ).then((title) => title || null),
1865
+ ]);
1866
+ return {
1867
available: true,
1868
visible: isVisible(tab),
1869
tabId: tab.tabId,
1848
- url: loadError?.url ?? (url === "about:blank" ? null : url),
1849
- title: null,
1870
+ url: statusUrl,
1871
+ title,
1872
loading: tab.loading,
1873
...(loadError ? { loadError } : {}),
1874
control: {
@@ -1884,8 +1906,6 @@ const make = Effect.gen(function* () {
1906
completedAt,
1907
})),
1908
};
1887
- if (status.url === null || tab.dialog) return status;
1888
- return { ...status, title: (await tab.page.title().catch(() => "")) || null };
1909
};
1910
1911
const resolveNavigationUrl = (input: PreviewAutomationNavigateInput) => {
@@ -1903,20 +1923,22 @@ const make = Effect.gen(function* () {
1923
readiness: "load" | "domContentLoaded" | "none",
1924
timeout: number,
1925
) => {
1906
- const navigation = tab.page.goto(url, {
1907
- timeout,
1908
- waitUntil:
1909
- readiness === "domContentLoaded"
1910
- ? "domcontentloaded"
1911
- : readiness === "none"
1912
- ? "commit"
1913
- : "load",
1914
- });
1926
+ const startedAt = performance.now();
1927
+ const navigation = tab.page.goto(url, { timeout, waitUntil: "commit" });
1928
if (readiness === "none") {
1929
tab.control.track(navigation);
1930
return;
1931
}
1919
- await navigation.catch((cause: unknown) => {
1932
+ // Once the target commits, a stalled subresource only delays readiness; report the loading tab.
1933
+ const ready = () =>
1934
+ tab.page
1935
+ .waitForLoadState(readiness === "domContentLoaded" ? "domcontentloaded" : "load", {
1936
+ timeout: Math.max(1, timeout - (performance.now() - startedAt)),
1937
+ })
1938
+ .catch((cause: unknown) => {
1939
+ if (!(cause instanceof Error && cause.name === "TimeoutError")) throw cause;
1940
+ });
1941
+ await navigation.then(ready).catch((cause: unknown) => {
1942
const message = cause instanceof Error ? cause.message : String(cause);
1943
if (message.includes("Download is starting")) {
1944
throw new ServerBrowserPage.ServerBrowserOperationError({