The best way to control Claude Code, Codex and more from any computer or phone
fix(desktop): oversized preview events no longer take down the app (#23461)
Co-authored-by: GPT-6.1 Sol <noreply@openai.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>
Victor Vogel committed
Oct 30, 2026 at 15:50 UTC
9d42473d5c61531456f2adb86f2af2a823e15750
4 files changed
+201
-20
apps/desktop/src/preview/CdpRelay.test.ts
+65
-17
@@ -14,6 +14,9 @@ const makeTarget = (
14
setDownloadDirectory,
15
});
16
17
+const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) =>
18
+ createCdpRelayConnection(target, write, () => {});
19
+
20
// Each relay reply resolves after a few microtasks; one macrotask lets them all land.
21
// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
22
const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
@@ -21,9 +24,7 @@ const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
24
describe("CDP relay", () => {
25
it("announces only the tab's page, under its real target id", async () => {
26
const written: Array<Record<string, unknown>> = [];
24
- const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
25
- written.push(JSON.parse(raw)),
26
- );
27
+ const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw)));
28
relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
29
relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
30
await settle();
@@ -51,9 +52,7 @@ describe("CDP relay", () => {
52
new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))),
53
);
54
const written: Array<Record<string, unknown>> = [];
54
- const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
55
- written.push(JSON.parse(raw)),
56
- );
55
+ const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
56
relay.receive(
57
JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
58
);
@@ -76,7 +75,7 @@ describe("CDP relay", () => {
75
76
it("resumes paused child frames, so cross-site iframes run", async () => {
77
const send = vi.fn(async () => ({}));
79
- const relay = createCdpRelayConnection(makeTarget(send), () => {});
78
+ const relay = makeRelay(makeTarget(send), () => {});
79
relay.receive(
80
JSON.stringify({
81
id: 1,
@@ -102,9 +101,7 @@ describe("CDP relay", () => {
101
it("acknowledges Playwright's focus emulation without forcing it onto the guest", async () => {
102
const send = vi.fn(async () => ({}));
103
const written: Array<Record<string, unknown>> = [];
105
- const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
106
- written.push(JSON.parse(raw)),
107
- );
104
+ const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
105
relay.receive(
106
JSON.stringify({
107
id: 1,
@@ -120,9 +117,7 @@ describe("CDP relay", () => {
117
118
it("routes tab events to the page session once the page is announced", async () => {
119
const written: Array<Record<string, unknown>> = [];
123
- const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
124
- written.push(JSON.parse(raw)),
125
- );
120
+ const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw)));
121
relay.event("Page.loadEventFired", {}, undefined);
122
expect(written).toEqual([]);
123
relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
@@ -140,9 +135,7 @@ describe("CDP relay extra sessions", () => {
135
it("gives a second page session the page's commands and events", async () => {
136
const send = vi.fn(async () => ({}));
137
const written: Array<Record<string, unknown>> = [];
143
- const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
144
- written.push(JSON.parse(raw)),
145
- );
138
+ const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
139
relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
140
relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
141
await settle();
@@ -182,7 +175,7 @@ describe("CDP relay downloads", () => {
175
const send = vi.fn(async () => ({}));
176
const directories: Array<string | null> = [];
177
const written: Array<Record<string, unknown>> = [];
185
- const relay = createCdpRelayConnection(
178
+ const relay = makeRelay(
179
makeTarget(send, (directory) => directories.push(directory)),
180
(raw) => written.push(JSON.parse(raw)),
181
);
@@ -213,3 +206,58 @@ describe("CDP relay downloads", () => {
206
]);
207
});
208
});
209
+
210
+describe("CDP relay payload budget", () => {
211
+ // 2,048 references to one 40 KiB string: about 80 MiB once serialized, little memory here.
212
+ const oversized = Array(2048).fill("x".repeat(40 * 1024));
213
+
214
+ it("fails only an oversized reply and still returns a large screenshot", async () => {
215
+ const screenshot = "A".repeat(16 * 1024 * 1024);
216
+ const send = vi.fn(async (method: string) =>
217
+ method === "DOM.getDocument" ? { nodes: oversized } : { data: screenshot },
218
+ );
219
+ const written: Array<Record<string, unknown>> = [];
220
+ const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
221
+ relay.receive(
222
+ JSON.stringify({ id: 1, method: "DOM.getDocument", sessionId: "t3-preview-page" }),
223
+ );
224
+ relay.receive(
225
+ JSON.stringify({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
226
+ );
227
+ await settle();
228
+
229
+ const replies = written.map(({ id, error, result }) => ({
230
+ id,
231
+ error,
232
+ size: (result as { data?: string } | undefined)?.data?.length,
233
+ }));
234
+ expect(replies).toEqual([
235
+ { id: 1, error: { code: -32000, message: "CDP payload too large" }, size: undefined },
236
+ { id: 2, error: undefined, size: screenshot.length },
237
+ ]);
238
+ });
239
+
240
+ it.each([
241
+ { args: oversized },
242
+ { args: "\u0001".repeat(12 * 1024 * 1024) },
243
+ { args: Array(2_700_000).fill(-0.0000010000000000000002) },
244
+ ])("closes instead of dropping an oversized event (%#)", async ({ args }) => {
245
+ const written: Array<Record<string, unknown>> = [];
246
+ const close = vi.fn();
247
+ const relay = createCdpRelayConnection(
248
+ makeTarget(vi.fn()),
249
+ (raw) => written.push(JSON.parse(raw)),
250
+ close,
251
+ );
252
+ relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
253
+ await settle();
254
+ written.length = 0;
255
+
256
+ relay.event("Runtime.consoleAPICalled", { args }, "");
257
+ relay.event("Page.loadEventFired", { timestamp: 1 }, "");
258
+
259
+ relay.receive(JSON.stringify({ id: 2, method: "Target.setAutoAttach" }));
260
+ expect(close).toHaveBeenCalledOnce();
261
+ expect(written.map((message) => message["method"])).toEqual([]);
262
+ });
263
+});
apps/desktop/src/preview/CdpRelay.ts
+47
-1
@@ -36,6 +36,29 @@ const isCommand = (value: unknown): value is CdpCommand =>
36
typeof (value as { id?: unknown }).id === "number" &&
37
typeof (value as { method?: unknown }).method === "string";
38
39
+// CDP values are plain JSON data, so their serialized size can be bounded before
40
+// JSON.stringify allocates it. A string counts at its length unless it holds a
41
+// character JSON may escape, which can take six code units.
42
+const MAX_CDP_PAYLOAD_SIZE = 64 * 1024 * 1024;
43
+const MAY_ESCAPE = /[^\x20\x21\x23-\x5b\x5d-\ud7ff\ue000-\uffff]/;
44
+const serializedSize = (text: string) =>
45
+ (MAY_ESCAPE.test(text) ? text.length * 6 : text.length) + 3;
46
+
47
+const fitsPayloadBudget = (message: unknown) => {
48
+ let remaining = MAX_CDP_PAYLOAD_SIZE;
49
+ const visit = (value: unknown): boolean => {
50
+ remaining -= typeof value === "string" ? serializedSize(value) : 26;
51
+ if (remaining < 0) return false;
52
+ if (typeof value !== "object" || value === null) return true;
53
+ if (Array.isArray(value)) return value.every(visit);
54
+ return Object.entries(value).every(([key, item]) => {
55
+ remaining -= serializedSize(key);
56
+ return visit(item);
57
+ });
58
+ };
59
+ return visit(message);
60
+};
61
+
62
const BROWSER_CONTEXT_ID = "t3-preview";
63
const ANNOUNCE = Symbol("announce");
64
const PAGE_SESSION_ID = "t3-preview-page";
@@ -50,8 +73,30 @@ const ACKNOWLEDGED = new Set([
73
export function createCdpRelayConnection(
74
target: CdpRelayTarget,
75
write: (message: string) => void,
76
+ close: () => void,
77
): CdpRelayConnection {
54
- const send = (message: Record<string, unknown>) => write(JSON.stringify(message));
78
+ let closed = false;
79
+ const send = (message: Record<string, unknown>) => {
80
+ if (closed) return;
81
+ if (fitsPayloadBudget(message)) {
82
+ write(JSON.stringify(message));
83
+ return;
84
+ }
85
+ // An error reply fails only that command. A dropped event would leave
86
+ // Playwright out of step with the page, so the relay closes instead.
87
+ if (typeof message["id"] === "number") {
88
+ write(
89
+ JSON.stringify({
90
+ id: message["id"],
91
+ error: { code: -32000, message: "CDP payload too large" },
92
+ ...(message["sessionId"] === undefined ? {} : { sessionId: message["sessionId"] }),
93
+ }),
94
+ );
95
+ return;
96
+ }
97
+ closed = true;
98
+ close();
99
+ };
100
let attached = false;
101
/** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
102
const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);
@@ -151,6 +196,7 @@ export function createCdpRelayConnection(
196
197
return {
198
receive: (raw) => {
199
+ if (closed) return;
200
let command: unknown;
201
try {
202
command = JSON.parse(raw);
apps/desktop/src/preview/DesktopBrowserHost.test.ts
+70
-1
@@ -1,5 +1,5 @@
1
// @effect-diagnostics nodeBuiltinImport:off - Stands in for an Electron debugger.
2
-import { describe, expect, it } from "@effect/vitest";
2
+import { describe, expect, it, vi } from "@effect/vitest";
3
import { DesktopBrowserEvent } from "@t3tools/contracts";
4
import * as Effect from "effect/Effect";
5
import * as Fiber from "effect/Fiber";
@@ -968,4 +968,73 @@ describe("DesktopBrowserHost", () => {
968
expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(false);
969
}),
970
);
971
+
972
+ it.effect("detaches only the tab whose CDP event is too large to relay", () =>
973
+ Effect.gen(function* () {
974
+ const host = yield* DesktopBrowserHost.make;
975
+ const tabs = [makeDebuggee({ deferFocus: true }), makeDebuggee()];
976
+ const send = vi.spyOn(tabs[0]!.tab.debugger, "sendCommand");
977
+ const keys = [key, { threadId: "thread-2", tabId: "tab-2" }];
978
+ const events = yield* Queue.unbounded<DesktopBrowserEvent>();
979
+ yield* host.events.pipe(
980
+ Stream.runForEach((line) =>
981
+ Queue.offer(events, decodeEvent(new TextDecoder().decode(line))),
982
+ ),
983
+ Effect.forkScoped,
984
+ );
985
+ for (const [index, tabKey] of keys.entries()) {
986
+ host.attach(tabKey, tabs[index]!.tab);
987
+ expect(yield* Queue.take(events)).toEqual({ type: "attached", ...tabKey });
988
+ yield* host.handleCommandLine(
989
+ encodeJson({
990
+ type: "cdp",
991
+ ...tabKey,
992
+ message: encodeJson({ id: 1, method: "Target.setAutoAttach" }),
993
+ }),
994
+ );
995
+ // The command's reply and the page announcement.
996
+ yield* Queue.takeN(events, 2);
997
+ }
998
+
999
+ yield* host.handleCommandLine(
1000
+ encodeJson({
1001
+ type: "cdp",
1002
+ ...key,
1003
+ message: encodeJson({
1004
+ id: 2,
1005
+ method: "Target.setAutoAttach",
1006
+ params: { autoAttach: true, waitForDebuggerOnStart: true, flatten: true },
1007
+ sessionId: "t3-preview-page",
1008
+ }),
1009
+ }),
1010
+ );
1011
+ yield* command(host, 3, "Page.startScreencast");
1012
+ tabs[0]!.emit("Runtime.consoleAPICalled", {
1013
+ args: Array(2048).fill("x".repeat(40 * 1024)),
1014
+ });
1015
+ tabs[1]!.emit("Page.loadEventFired", { timestamp: 1 });
1016
+ const [detached, next] = yield* Queue.takeN(events, 2);
1017
+
1018
+ const { type, threadId, tabId } = detached!;
1019
+ expect({ type, threadId, tabId }).toEqual({ type: "detached", ...key });
1020
+ expect(send).toHaveBeenCalledWith("Target.setAutoAttach", {
1021
+ autoAttach: false,
1022
+ waitForDebuggerOnStart: false,
1023
+ flatten: true,
1024
+ });
1025
+ tabs[0]!.settleFocus();
1026
+ yield* settle;
1027
+ expect(send).not.toHaveBeenCalledWith("Target.setAutoAttach", {
1028
+ autoAttach: true,
1029
+ waitForDebuggerOnStart: true,
1030
+ flatten: true,
1031
+ });
1032
+ expect(send).toHaveBeenCalledWith("Page.stopScreencast");
1033
+ expect(tabs[0]!.focusEmulation).toEqual([true, false]);
1034
+ expect(next).toMatchObject({ type: "cdp", ...keys[1] });
1035
+ expect(JSON.parse((next as { message: string }).message)).toMatchObject({
1036
+ method: "Page.loadEventFired",
1037
+ });
1038
+ }).pipe(Effect.scoped),
1039
+ );
1040
});
apps/desktop/src/preview/DesktopBrowserHost.ts
+19
-1
@@ -329,7 +329,7 @@ export const make = Effect.gen(function* () {
329
const forward = (current?: () => boolean) => {
330
const change = tab.focusChange;
331
const run = () =>
332
- current === undefined || current()
332
+ tab.relay === relay && (current === undefined || current())
333
? send(method, params, sessionId)
334
: Promise.reject(new Error("The page this screenshot was for has moved on."));
335
return change === null ? run() : change.then(run);
@@ -372,6 +372,24 @@ export const make = Effect.gen(function* () {
372
emit({ type: "cdp", ...tab.key, message });
373
}
374
},
375
+ // Announcing the tab again would reconnect Playwright, and the page could
376
+ // replay the same oversized event, so the tab stays detached.
377
+ () => {
378
+ if (tab.relay !== relay || tabs.get(keyOf(tab.key)) !== tab) return;
379
+ // Disabling auto-attach detaches child sessions and releases their debugger pauses.
380
+ void debuggee
381
+ .sendCommand("Target.setAutoAttach", {
382
+ autoAttach: false,
383
+ waitForDebuggerOnStart: false,
384
+ flatten: true,
385
+ })
386
+ .catch(() => {});
387
+ if (tab.screencasts.size > 0) {
388
+ void debuggee.sendCommand("Page.stopScreencast").catch(() => {});
389
+ }
390
+ setFocusEmulation(tab, false);
391
+ detach(tab.key);
392
+ },
393
);
394
tab.relay = relay;
395
return relay;