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, 22:15 UTC
fix(server,desktop): browser tools report why a page failed to load (#18588)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Robert Nisipeanu committed
Nov 11, 2026 at 21:58 UTC
f796df8fd2f04d7d5971055139166abc3887206e
8 files changed
+329
-20
apps/desktop/src/preview/DesktopBrowserHost.ts
+7
@@ -4,6 +4,7 @@ import {
4
DesktopBrowserCommand,
5
DesktopBrowserEvent,
6
type DesktopBrowserEvent as DesktopBrowserEventType,
7
+ type PreviewAutomationLoadError,
8
} from "@t3tools/contracts";
9
import * as Context from "effect/Context";
10
import * as NodePath from "node:path";
@@ -93,6 +94,7 @@ export class DesktopBrowserHost extends Context.Service<
94
readonly handleCommandLine: (line: string) => Effect.Effect<void>;
95
readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void;
96
readonly detach: (key: DesktopBrowserTabKey) => void;
97
+ readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void;
98
readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void;
99
readonly humanStartedDownload: (source: Electron.WebContents) => boolean;
100
readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean;
@@ -523,6 +525,10 @@ export const make = Effect.gen(function* () {
525
if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown });
526
};
527
528
+ const loadFailed: DesktopBrowserHost["Service"]["loadFailed"] = (key, failure) => {
529
+ if (tabs.has(keyOf(key))) emit({ type: "loadFailed", ...key, ...failure });
530
+ };
531
+
532
const handleCommandLine = (line: string) =>
533
Effect.sync(() => {
534
const command = decodeCommand(line);
@@ -588,6 +594,7 @@ export const make = Effect.gen(function* () {
594
handleCommandLine,
595
attach,
596
detach,
597
+ loadFailed,
598
setShown,
599
placeDownload,
600
humanStartedDownload,
apps/desktop/src/preview/Manager.test.ts
+92
@@ -616,6 +616,7 @@ describe("PreviewManager", () => {
616
attach: () => {},
617
detach: () => {},
618
setShown: () => {},
619
+ loadFailed: () => {},
620
humanStartedDownload: () => true,
621
placeDownload: () => true,
622
}),
@@ -2116,6 +2117,97 @@ describe("PreviewManager", () => {
2117
}).pipe(Effect.provide(managerLayer()), Effect.scoped),
2118
);
2119
2120
+ effectIt.effect("reports early and subsequent load failures for the current guest", () =>
2121
+ Effect.gen(function* () {
2122
+ const host = yield* DesktopBrowserHost.DesktopBrowserHost;
2123
+ const serverTab = { threadId: "thread-1", tabId: "server-tab-1" };
2124
+ const lines = yield* Queue.unbounded<string>();
2125
+ yield* host.events.pipe(
2126
+ Stream.runForEach((line) => Queue.offer(lines, new TextDecoder().decode(line))),
2127
+ Effect.forkScoped({ startImmediately: true }),
2128
+ );
2129
+ const makeGuest = (id: number) => {
2130
+ const listeners = new Map<string, Array<(...args: unknown[]) => void>>();
2131
+ const wc = Object.assign(
2132
+ makeTestPreviewWebContents(
2133
+ async () => ({
2134
+ toJPEG: () => Buffer.from("jpeg"),
2135
+ getSize: () => ({ width: 100, height: 80 }),
2136
+ }),
2137
+ id,
2138
+ ),
2139
+ {
2140
+ isDevToolsOpened: () => false,
2141
+ getUserAgent: () => "Electron",
2142
+ once: vi.fn(),
2143
+ on: (event: string, listener: (...args: unknown[]) => void) => {
2144
+ listeners.set(event, [...(listeners.get(event) ?? []), listener]);
2145
+ },
2146
+ },
2147
+ );
2148
+ const emit = (event: string, ...args: unknown[]) => {
2149
+ for (const listener of listeners.get(event) ?? []) listener(...args);
2150
+ };
2151
+ return {
2152
+ wc,
2153
+ emit,
2154
+ fail: (url: string) =>
2155
+ emit("did-fail-load", {}, -202, "ERR_CERT_AUTHORITY_INVALID", url, true),
2156
+ };
2157
+ };
2158
+ const initial = makeGuest(42);
2159
+ const replacement = makeGuest(43);
2160
+ const manager = yield* PreviewManager.PreviewManager;
2161
+ const statuses: PreviewManager.PreviewNavStatus[] = [];
2162
+ yield* manager.subscribeStateChanges((_tabId, state) =>
2163
+ Effect.sync(() => {
2164
+ statuses.push(state.navStatus);
2165
+ }),
2166
+ );
2167
+ yield* manager.createTab("tab_1", { serverTab });
2168
+ yield* manager.prepareWebview(initial.wc);
2169
+ yield* manager.prepareWebview(replacement.wc);
2170
+ initial.fail("https://first.local/");
2171
+ initial.emit("did-start-navigation", { isMainFrame: false, isSameDocument: false });
2172
+ initial.emit("did-start-loading");
2173
+ replacement.fail("https://second.local/");
2174
+ const failure = (url: string) => ({
2175
+ type: "loadFailed",
2176
+ ...serverTab,
2177
+ url,
2178
+ code: -202,
2179
+ description: "ERR_CERT_AUTHORITY_INVALID",
2180
+ });
2181
+
2182
+ fromId.mockReturnValue(initial.wc);
2183
+ yield* manager.registerWebview("tab_1", 42);
2184
+ expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab });
2185
+ expect(JSON.parse(yield* Queue.take(lines))).toEqual(failure("https://first.local/"));
2186
+
2187
+ fromId.mockReturnValue(replacement.wc);
2188
+ yield* manager.registerWebview("tab_1", 43);
2189
+ expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "detached", ...serverTab });
2190
+ expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab });
2191
+ expect(JSON.parse(yield* Queue.take(lines))).toEqual(failure("https://second.local/"));
2192
+
2193
+ // A callback queued by the old guest must not report a failure for its replacement.
2194
+ initial.fail("https://stale.local/");
2195
+ replacement.fail("https://current.local/");
2196
+ expect(JSON.parse(yield* Queue.take(lines))).toEqual(failure("https://current.local/"));
2197
+ expect(statuses).not.toContainEqual(expect.objectContaining({ url: "https://stale.local/" }));
2198
+
2199
+ const retried = makeGuest(44);
2200
+ yield* manager.prepareWebview(retried.wc);
2201
+ retried.fail("https://retry.local/");
2202
+ retried.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false });
2203
+ fromId.mockReturnValue(retried.wc);
2204
+ yield* manager.registerWebview("tab_1", 44);
2205
+ expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "detached", ...serverTab });
2206
+ expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab });
2207
+ expect(statuses.at(-1)?.kind).toBe("Success");
2208
+ }).pipe(Effect.provide(managerLayer()), Effect.scoped),
2209
+ );
2210
+
2211
effectIt.effect("discards a screenshot that resolves after its guest is replaced", () =>
2212
withManager((manager) =>
2213
Effect.gen(function* () {
apps/desktop/src/preview/Manager.ts
+64
-11
@@ -24,6 +24,7 @@ import type {
24
DesktopPreviewScreenshotArtifact,
25
DesktopPreviewTabDefaults,
26
PreviewForwardedShortcut,
27
+ PreviewAutomationLoadError,
28
} from "@t3tools/contracts";
29
import * as HostProcess from "@t3tools/shared/HostProcess";
30
import { matchesKeybindingShortcut } from "@t3tools/shared/keybindings";
@@ -604,6 +605,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
605
{ readonly semaphore: Semaphore.Semaphore; users: number }
606
>();
607
const tabLifecycleGenerations = new Map<string, number>();
608
+ // A guest can fail its first load before registerWebview installs its tab listeners.
609
+ const guestLoadFailures = new Map<number, PreviewAutomationLoadError>();
610
611
const attempt = <A>(errorContext: PreviewOperationContext, evaluate: () => A) =>
612
Effect.try({
@@ -1398,16 +1401,39 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
1401
validatedUrl: string,
1402
isMainFrame: boolean,
1403
): void => {
1401
- if (code === -3 || !isMainFrame) return;
1404
+ if (code === -3 || !isMainFrame || wc.isDestroyed()) return;
1405
+ const url = validatedUrl || wc.getURL();
1406
runFork(
1403
- update(tabId, {
1404
- navStatus: {
1405
- kind: "LoadFailed",
1406
- url: validatedUrl || wc.getURL(),
1407
- title: wc.getTitle(),
1408
- code,
1409
- description,
1410
- },
1407
+ Effect.gen(function* () {
1408
+ const updatedAt = yield* currentIso;
1409
+ const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
1410
+ const current = tabs.get(tabId);
1411
+ if (
1412
+ !current ||
1413
+ current.webContentsId !== wc.id ||
1414
+ wc.isDestroyed() ||
1415
+ webContents.fromId(wc.id) !== wc
1416
+ ) {
1417
+ return [Option.none<PreviewTabState>(), tabs] as const;
1418
+ }
1419
+ const state: PreviewTabState = {
1420
+ ...current,
1421
+ navStatus: { kind: "LoadFailed", url, title: wc.getTitle(), code, description },
1422
+ updatedAt,
1423
+ };
1424
+ return [
1425
+ Option.some(state),
1426
+ replaceMap(tabs, (copy) => copy.set(tabId, state)),
1427
+ ] as const;
1428
+ });
1429
+ if (Option.isNone(next)) return;
1430
+ const current = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
1431
+ if (current?.webContentsId !== wc.id || current.navStatus !== next.value.navStatus)
1432
+ return;
1433
+ if (current.serverTab) {
1434
+ browserHost.loadFailed(current.serverTab, { url, code, description });
1435
+ }
1436
+ yield* emitIfCurrent(tabId, next.value);
1437
}),
1438
);
1439
};
@@ -1887,11 +1913,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
1913
] as const;
1914
}
1915
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
1916
+ const failure = guestLoadFailures.get(webContentsId);
1917
const { favicon: _favicon, ...currentWithoutFavicon } = current;
1918
const next: PreviewTabState = {
1919
...currentWithoutFavicon,
1920
webContentsId,
1894
- navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
1921
+ navStatus:
1922
+ failure && (pendingUrl === null || pendingUrl === failure.url)
1923
+ ? { kind: "LoadFailed", title: wc.getTitle(), ...failure }
1924
+ : pendingUrl === null
1925
+ ? computeNavStatus(wc)
1926
+ : current.navStatus,
1927
canGoBack: wc.navigationHistory.canGoBack(),
1928
canGoForward: wc.navigationHistory.canGoForward(),
1929
audible: attachedAudible,
@@ -1959,7 +1991,19 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
1991
) {
1992
yield* rendererHistory.register(wc, { surface: "preview" });
1993
const webContentsId = wc.id;
1994
+ wc.on("did-start-navigation", (event) => {
1995
+ if (event.isMainFrame && !event.isSameDocument) guestLoadFailures.delete(webContentsId);
1996
+ });
1997
+ wc.on("did-fail-load", (_event, code, description, validatedUrl, isMainFrame) => {
1998
+ if (code === -3 || !isMainFrame) return;
1999
+ guestLoadFailures.set(webContentsId, {
2000
+ url: validatedUrl || wc.getURL(),
2001
+ code,
2002
+ description,
2003
+ });
2004
+ });
2005
wc.once("destroyed", () => {
2006
+ guestLoadFailures.delete(webContentsId);
2007
runFork(hideDestroyedGuest(webContentsId));
2008
runFork(detachControlSession(webContentsId));
2009
});
@@ -2421,14 +2465,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2465
const beforeAttach = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
2466
if (beforeAttach?.webContentsId !== wc.id) return;
2467
const control = yield* ensureControlSession(wc);
2468
+ if (beforeAttach.serverTab) yield* listenToBrowserHost;
2469
const afterAttach = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
2470
if (afterAttach?.webContentsId !== wc.id) {
2471
yield* detachControlSession(wc.id);
2472
return;
2473
}
2474
if (afterAttach.serverTab) {
2430
- yield* listenToBrowserHost;
2475
browserHost.attach(afterAttach.serverTab, { webContents: wc, debugger: control.debugger });
2476
+ // CDP cannot recover a failure that happened before it attached.
2477
+ const { navStatus } = afterAttach;
2478
+ if (navStatus.kind === "LoadFailed") {
2479
+ browserHost.loadFailed(afterAttach.serverTab, {
2480
+ url: navStatus.url,
2481
+ code: navStatus.code,
2482
+ description: navStatus.description,
2483
+ });
2484
+ }
2485
}
2486
if (afterAttach.colorScheme !== "system") {
2487
yield* attemptPromise({ operation: "applyColorScheme", tabId, webContentsId: wc.id }, () =>
apps/server/src/preview/DesktopBrowserChannel.ts
+20
-1
@@ -6,6 +6,7 @@ import {
6
DesktopBrowserCommand,
7
DesktopBrowserEvent,
8
type DesktopBrowserCommand as DesktopBrowserCommandType,
9
+ type PreviewAutomationLoadError,
10
} from "@t3tools/contracts";
11
import * as Context from "effect/Context";
12
import * as Duration from "effect/Duration";
@@ -46,6 +47,8 @@ export class DesktopBrowserChannel extends Context.Service<
47
readonly isAttached: (key: DesktopTabKey) => Effect.Effect<boolean>;
48
/** Whether a desktop window draws the tab on screen, which no streamed viewer counts. */
49
readonly isShown: (key: DesktopTabKey) => boolean;
50
+ /** A load failure the desktop saw, possibly before the server connected to the tab. */
51
+ readonly loadFailure: (key: DesktopTabKey) => PreviewAutomationLoadError | undefined;
52
readonly endpoint: (key: DesktopTabKey) => Effect.Effect<string, never, Scope.Scope>;
53
readonly pointer: (
54
key: DesktopTabKey,
@@ -64,6 +67,7 @@ const make = Effect.gen(function* () {
67
const attachedTabs = new Set<string>();
68
// Missing reports protect desktop tabs until the renderer explicitly marks them hidden.
69
const shownTabs = new Map<string, boolean>();
70
+ const loadFailures = new Map<string, PreviewAutomationLoadError>();
71
const inbound = new Map<string, Queue.Queue<string>>();
72
const writeLock = yield* Semaphore.make(1);
73
@@ -88,6 +92,7 @@ const make = Effect.gen(function* () {
92
return Effect.void;
93
}),
94
isShown: () => false,
95
+ loadFailure: () => undefined,
96
});
97
}
98
@@ -126,9 +131,17 @@ const make = Effect.gen(function* () {
131
case "attached":
132
attachedTabs.add(id);
133
return PubSub.publish(changes, { key, attached: true });
134
+ case "loadFailed":
135
+ loadFailures.set(id, {
136
+ url: event.url.slice(0, 2048),
137
+ code: event.code,
138
+ description: event.description,
139
+ });
140
+ return Effect.void;
141
case "detached": {
142
attachedTabs.delete(id);
143
shownTabs.delete(id);
144
+ loadFailures.delete(id);
145
const queue = inbound.get(id);
146
return (queue ? Queue.shutdown(queue) : Effect.void).pipe(
147
Effect.andThen(PubSub.publish(changes, { key, attached: false })),
@@ -140,7 +153,12 @@ const make = Effect.gen(function* () {
153
}
154
}),
155
Effect.catchCause((cause) => Effect.logWarning("desktop browser channel stopped", { cause })),
143
- Effect.ensuring(Effect.sync(() => shownTabs.clear())),
156
+ Effect.ensuring(
157
+ Effect.sync(() => {
158
+ shownTabs.clear();
159
+ loadFailures.clear();
160
+ }),
161
+ ),
162
Effect.forkScoped,
163
);
164
@@ -232,6 +250,7 @@ const make = Effect.gen(function* () {
250
return Effect.sync(() => attachedTabs.has(keyOf(key)));
251
}),
252
isShown: (key) => shownTabs.get(keyOf(key)) ?? true,
253
+ loadFailure: (key) => loadFailures.get(keyOf(key)),
254
endpoint,
255
turn: Effect.fn("DesktopBrowserChannel.turn")(function (threadId, active) {
256
return command({ type: "turn", threadId, active });
apps/server/src/preview/ServerBrowser.test.ts
+105
@@ -13,6 +13,7 @@ import {
13
PreviewTabId,
14
ProviderInstanceId,
15
ThreadId,
16
+ type PreviewAutomationLoadError,
17
type PreviewAutomationSnapshot,
18
type PreviewAutomationStatus,
19
} from "@t3tools/contracts";
@@ -330,6 +331,7 @@ let desktopAttachesLate = false;
331
let desktopAttachWaiting = Promise.withResolvers<void>();
332
const shownDesktopTabs = new Set<string>();
333
const releasedDesktopTabs: Array<string> = [];
334
+const desktopLoadFailures = new Map<string, PreviewAutomationLoadError>();
335
const desktopTurns = new NodeEvents.EventEmitter();
336
const desktopConnections: Array<{ endpoint: string; context: ReturnType<typeof makeContext> }> = [];
337
const testThread = {
@@ -411,6 +413,7 @@ const dependencies = Layer.mergeAll(
413
),
414
isAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)),
415
isShown: (key) => shownDesktopTabs.has(key.tabId),
416
+ loadFailure: (key) => desktopLoadFailures.get(key.tabId),
417
endpoint: (key) =>
418
Effect.acquireRelease(Effect.succeed(`ws://desktop/${key.tabId}`), () =>
419
Effect.sync(() => {
@@ -489,6 +492,7 @@ beforeEach(() => {
492
focusedFrame = null;
493
desktopTabs.clear();
494
shownDesktopTabs.clear();
495
+ desktopLoadFailures.clear();
496
desktopRendersNext = false;
497
desktopAttachesLate = false;
498
desktopAttachWaiting = Promise.withResolvers<void>();
@@ -2611,3 +2615,104 @@ it.live("a full server takes back the slot of the longest idle agent tab nobody
2615
}),
2616
).pipe(Effect.provide(layer)),
2617
);
2618
+
2619
+const certificateError = {
2620
+ url: "https://device.local/",
2621
+ code: -202,
2622
+ description: "ERR_CERT_AUTHORITY_INVALID",
2623
+};
2624
+const dataUrl = `data:text/html,${"PAYLOAD".repeat(300)}`;
2625
+
2626
+it.live("reports why a page failed to load while the tab shows the error page", () =>
2627
+ Effect.scoped(
2628
+ Effect.gen(function* () {
2629
+ const { broker, tabId } = yield* ready;
2630
+ const page = contexts[0]!.page;
2631
+ const request = {
2632
+ url: () => certificateError.url,
2633
+ method: () => "GET",
2634
+ isNavigationRequest: () => true,
2635
+ frame: () => page,
2636
+ failure: () => ({ errorText: "net::ERR_CERT_AUTHORITY_INVALID" }),
2637
+ };
2638
+ const status = () =>
2639
+ broker.invoke<PreviewAutomationStatus>({ scope, tabId, operation: "status", input: {} });
2640
+ const snapshot = () =>
2641
+ broker.invoke<PreviewAutomationSnapshot>({
2642
+ scope,
2643
+ tabId,
2644
+ operation: "snapshot",
2645
+ input: {},
2646
+ });
2647
+ expect(yield* status()).not.toHaveProperty("loadError");
2648
+ expect(yield* snapshot()).not.toHaveProperty("loadError");
2649
+ page.emit("request", request);
2650
+ page.emit("requestfailed", request);
2651
+ page.url = () => "chrome-error://chromewebdata/";
2652
+ expect((yield* status()).loadError).toEqual(certificateError);
2653
+ expect((yield* snapshot()).loadError).toEqual(certificateError);
2654
+
2655
+ const subframeRequest = {
2656
+ ...request,
2657
+ url: () => "https://frame.local/",
2658
+ frame: () => ({}),
2659
+ };
2660
+ page.emit("request", subframeRequest);
2661
+ page.emit("requestfailed", subframeRequest);
2662
+ expect((yield* status()).loadError).toEqual(certificateError);
2663
+
2664
+ // Clearing must happen before the next navigation replaces the error page.
2665
+ page.emit("request", { ...request, url: () => "https://device.local/login" });
2666
+ expect(yield* status()).not.toHaveProperty("loadError");
2667
+ expect(yield* snapshot()).not.toHaveProperty("loadError");
2668
+
2669
+ const dataRequest = { ...request, url: () => dataUrl };
2670
+ page.emit("request", dataRequest);
2671
+ page.emit("requestfailed", dataRequest);
2672
+ expect((yield* status()).loadError?.url).toBe("data:text/html,…");
2673
+ }),
2674
+ ).pipe(Effect.provide(layer)),
2675
+);
2676
+
2677
+it.live("reports a desktop tab's load failure from before the server connected", () =>
2678
+ Effect.scoped(
2679
+ Effect.gen(function* () {
2680
+ const browser = yield* ServerBrowser.ServerBrowser;
2681
+ const broker = yield* Broker.PreviewAutomationBroker;
2682
+ const manager = yield* Manager.PreviewManager;
2683
+ yield* Effect.yieldNow;
2684
+ desktopRendersNext = true;
2685
+ const opened = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" });
2686
+ desktopLoadFailures.set(opened.tabId, certificateError);
2687
+ yield* browser.attachViewer(viewerInput(opened.tabId, false));
2688
+ const page = desktopConnections[0]!.context.page;
2689
+ page.url = () => "chrome-error://chromewebdata/";
2690
+ const status = () =>
2691
+ broker.invoke<PreviewAutomationStatus>({
2692
+ scope,
2693
+ operation: "status",
2694
+ input: {},
2695
+ tabId: PreviewTabId.make(opened.tabId),
2696
+ });
2697
+ const snapshot = () =>
2698
+ broker.invoke<PreviewAutomationSnapshot>({
2699
+ scope,
2700
+ operation: "snapshot",
2701
+ input: {},
2702
+ tabId: PreviewTabId.make(opened.tabId),
2703
+ });
2704
+ expect((yield* status()).loadError).toEqual(certificateError);
2705
+ expect((yield* snapshot()).loadError).toEqual(certificateError);
2706
+ desktopLoadFailures.set(opened.tabId, { ...certificateError, url: dataUrl });
2707
+ expect((yield* status()).loadError?.url).toBe("data:text/html,…");
2708
+ // A navigation the server sees supersedes it, even before the error page goes.
2709
+ page.emit("request", {
2710
+ url: () => "https://device.local/retry",
2711
+ isNavigationRequest: () => true,
2712
+ frame: () => page,
2713
+ });
2714
+ expect(yield* status()).not.toHaveProperty("loadError");
2715
+ expect(yield* snapshot()).not.toHaveProperty("loadError");
2716
+ }),
2717
+ ).pipe(Effect.provide(layer)),
2718
+);
apps/server/src/preview/ServerBrowser.ts
+20
-8
@@ -21,6 +21,7 @@ import {
21
type PreviewAutomationDragInput,
22
type PreviewAutomationEvaluateInput,
23
type PreviewAutomationHoverInput,
24
+ type PreviewAutomationLoadError,
25
type PreviewAutomationNavigateInput,
26
type PreviewAutomationNetworkEntry,
27
type PreviewAutomationOpenInput,
@@ -333,6 +334,7 @@ interface ServerTab {
334
/** A read queued behind `desktopViewportRead`, shared by every caller that waits for it. */
335
desktopViewportNext: Promise<ServerTab["desktopViewport"]> | null;
336
loading: boolean;
337
+ loadError: PreviewAutomationLoadError | undefined;
338
closing: boolean;
339
recording: Recording | null;
340
initialNavigation: Promise<void> | null;
@@ -903,6 +905,7 @@ const make = Effect.gen(function* () {
905
desktopViewportRead: Promise.resolve(null),
906
desktopViewportNext: null,
907
loading: false,
908
+ loadError: undefined,
909
closing: false,
910
recording: null,
911
recordingStart: null,
@@ -939,6 +942,7 @@ const make = Effect.gen(function* () {
942
navigationGenerations.set(request, ++tab.navigationGeneration);
943
clearAbortedNavigation(tab);
944
tab.loading = true;
945
+ tab.loadError = undefined;
946
report(tab, {
947
_tag: "Loading",
948
url: ServerBrowserPage.withoutDataPayload(request.url()).slice(0, 2048),
@@ -994,13 +998,9 @@ const make = Effect.gen(function* () {
998
}
999
tab.loading = false;
1000
const { code, description } = ServerBrowserPage.parseNetError(errorText);
997
- report(tab, {
998
- _tag: "LoadFailed",
999
- url: ServerBrowserPage.withoutDataPayload(request.url()).slice(0, 2048),
1000
- title: "",
1001
- code,
1002
- description,
1003
- });
1001
+ const url = ServerBrowserPage.withoutDataPayload(request.url()).slice(0, 2048);
1002
+ tab.loadError = { url, code, description };
1003
+ report(tab, { _tag: "LoadFailed", url, title: "", code, description });
1004
});
1005
page.on("response", (response) => {
1006
pushBounded(tab.networkEntries, {
@@ -1616,6 +1616,14 @@ const make = Effect.gen(function* () {
1616
});
1617
};
1618
1619
+ const loadErrorOf = (tab: ServerTab): PreviewAutomationLoadError | undefined => {
1620
+ if (!tab.page.url().startsWith("chrome-error://")) return undefined;
1621
+ // A desktop failure from before CDP attached is superseded by any navigation we observe.
1622
+ if (tab.loadError || !tab.desktop || tab.navigationGeneration > 0) return tab.loadError;
1623
+ const reported = desktopChannel.loadFailure({ threadId: tab.threadId, tabId: tab.tabId });
1624
+ return reported && { ...reported, url: ServerBrowserPage.withoutDataPayload(reported.url) };
1625
+ };
1626
+
1627
const statusWithTitle = async (
1628
tab: ServerTab | undefined,
1629
agentSessionId?: string,
@@ -1633,6 +1641,7 @@ const make = Effect.gen(function* () {
1641
}
1642
const url = ServerBrowserPage.withoutDataPayload(tab.page.url());
1643
const viewport = tab.desktop ? await layoutSize(tab) : tab.page.viewportSize();
1644
+ const loadError = loadErrorOf(tab);
1645
const status = {
1646
available: true,
1647
visible: isVisible(tab),
@@ -1640,6 +1649,7 @@ const make = Effect.gen(function* () {
1649
url: url === "about:blank" ? null : url,
1650
title: null,
1651
loading: tab.loading,
1652
+ ...(loadError ? { loadError } : {}),
1653
control: {
1654
owner: tabOwner(tab),
1655
ownedByCaller: tab.control.agentId === agentSessionId,
@@ -2252,13 +2262,15 @@ const make = Effect.gen(function* () {
2262
return { tabId: tab.tabId, colorScheme };
2263
}
2264
case "snapshot": {
2255
- return withScreencastsPaused(tab, () =>
2265
+ const snapshot = await withScreencastsPaused(tab, () =>
2266
ServerBrowserPage.snapshot({
2267
...tab,
2268
renderScale: tab.desktop ? "display" : RENDER_SCALE,
2269
fullScreenshot: (input as PreviewAutomationSnapshotInput | undefined)?.fullScreenshot,
2270
}),
2271
);
2272
+ const loadError = loadErrorOf(tab);
2273
+ return loadError ? { ...snapshot, loadError } : snapshot;
2274
}
2275
case "click": {
2276
const clickInput = input as PreviewAutomationClickInput;
packages/contracts/src/desktopBrowser.ts
+11
@@ -12,6 +12,17 @@ export const DesktopBrowserEvent = Schema.Union([
12
/** Its `<webview>` went away: closed, crashed, swapped, or devtools took the debugger. */
13
Schema.Struct({ type: Schema.Literal("detached"), ...TabKey }),
14
Schema.Struct({ type: Schema.Literal("cdp"), ...TabKey, message: Schema.String }),
15
+ /**
16
+ * The tab's page failed to load. The desktop starts a tab's first load before
17
+ * the server connects, so the server cannot always observe the failure itself.
18
+ */
19
+ Schema.Struct({
20
+ type: Schema.Literal("loadFailed"),
21
+ ...TabKey,
22
+ url: Schema.String,
23
+ code: Schema.Int,
24
+ description: Schema.String,
25
+ }),
26
/** Its `<webview>` started or stopped being on screen in a desktop window. */
27
Schema.Struct({ type: Schema.Literal("shown"), ...TabKey, shown: Schema.Boolean }),
28
]);
packages/contracts/src/previewAutomation.ts
+10
@@ -71,6 +71,14 @@ export const PreviewAutomationProfile = Schema.Struct({
71
});
72
export type PreviewAutomationProfile = typeof PreviewAutomationProfile.Type;
73
74
+/** Why the tab shows the browser's error page instead of the page it tried to load. */
75
+export const PreviewAutomationLoadError = Schema.Struct({
76
+ url: Schema.String,
77
+ code: Schema.Int,
78
+ description: Schema.String,
79
+});
80
+export type PreviewAutomationLoadError = typeof PreviewAutomationLoadError.Type;
81
+
82
export const PreviewAutomationStatus = Schema.Struct({
83
available: Schema.Boolean,
84
visible: Schema.Boolean,
@@ -78,6 +86,7 @@ export const PreviewAutomationStatus = Schema.Struct({
86
url: Schema.NullOr(Schema.String),
87
title: Schema.NullOr(Schema.String),
88
loading: Schema.Boolean,
89
+ loadError: Schema.optional(PreviewAutomationLoadError),
90
control: Schema.optional(
91
Schema.Struct({
92
owner: PreviewAutomationTabOwner,
@@ -535,6 +544,7 @@ export const PreviewAutomationSnapshot = Schema.Struct({
544
url: Schema.String,
545
title: Schema.String,
546
loading: Schema.Boolean,
547
+ loadError: Schema.optional(PreviewAutomationLoadError),
548
visibleText: Schema.String,
549
interactiveElements: Schema.Array(PreviewAutomationElement),
550
accessibilityTree: Schema.Unknown,