Skip to content

Commit 9d42473

Browse files
only21milcodexclaudemaria-rcks
authored
fix(desktop): oversized preview events no longer take down the app (#23461)
Co-authored-by: GPT-6.1 Sol <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent f8768d6 commit 9d42473

4 files changed

Lines changed: 201 additions & 20 deletions

File tree

‎apps/desktop/src/preview/CdpRelay.test.ts‎

Lines changed: 65 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,17 @@ const makeTarget = (
1414
setDownloadDirectory,
1515
});
1616

17+
const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) =>
18+
createCdpRelayConnection(target, write, () => {});
19+
1720
// Each relay reply resolves after a few microtasks; one macrotask lets them all land.
1821
// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
1922
const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
2023

2124
describe("CDP relay", () => {
2225
it("announces only the tab's page, under its real target id", async () => {
2326
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)));
2728
relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
2829
relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
2930
await settle();
@@ -51,9 +52,7 @@ describe("CDP relay", () => {
5152
new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))),
5253
);
5354
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)));
5756
relay.receive(
5857
JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
5958
);
@@ -76,7 +75,7 @@ describe("CDP relay", () => {
7675

7776
it("resumes paused child frames, so cross-site iframes run", async () => {
7877
const send = vi.fn(async () => ({}));
79-
const relay = createCdpRelayConnection(makeTarget(send), () => {});
78+
const relay = makeRelay(makeTarget(send), () => {});
8079
relay.receive(
8180
JSON.stringify({
8281
id: 1,
@@ -102,9 +101,7 @@ describe("CDP relay", () => {
102101
it("acknowledges Playwright's focus emulation without forcing it onto the guest", async () => {
103102
const send = vi.fn(async () => ({}));
104103
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)));
108105
relay.receive(
109106
JSON.stringify({
110107
id: 1,
@@ -120,9 +117,7 @@ describe("CDP relay", () => {
120117

121118
it("routes tab events to the page session once the page is announced", async () => {
122119
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)));
126121
relay.event("Page.loadEventFired", {}, undefined);
127122
expect(written).toEqual([]);
128123
relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
@@ -140,9 +135,7 @@ describe("CDP relay extra sessions", () => {
140135
it("gives a second page session the page's commands and events", async () => {
141136
const send = vi.fn(async () => ({}));
142137
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)));
146139
relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
147140
relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
148141
await settle();
@@ -182,7 +175,7 @@ describe("CDP relay downloads", () => {
182175
const send = vi.fn(async () => ({}));
183176
const directories: Array<string | null> = [];
184177
const written: Array<Record<string, unknown>> = [];
185-
const relay = createCdpRelayConnection(
178+
const relay = makeRelay(
186179
makeTarget(send, (directory) => directories.push(directory)),
187180
(raw) => written.push(JSON.parse(raw)),
188181
);
@@ -213,3 +206,58 @@ describe("CDP relay downloads", () => {
213206
]);
214207
});
215208
});
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‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,29 @@ const isCommand = (value: unknown): value is CdpCommand =>
3636
typeof (value as { id?: unknown }).id === "number" &&
3737
typeof (value as { method?: unknown }).method === "string";
3838

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+
3962
const BROWSER_CONTEXT_ID = "t3-preview";
4063
const ANNOUNCE = Symbol("announce");
4164
const PAGE_SESSION_ID = "t3-preview-page";
@@ -50,8 +73,30 @@ const ACKNOWLEDGED = new Set([
5073
export function createCdpRelayConnection(
5174
target: CdpRelayTarget,
5275
write: (message: string) => void,
76+
close: () => void,
5377
): 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+
};
55100
let attached = false;
56101
/** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
57102
const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);
@@ -151,6 +196,7 @@ export function createCdpRelayConnection(
151196

152197
return {
153198
receive: (raw) => {
199+
if (closed) return;
154200
let command: unknown;
155201
try {
156202
command = JSON.parse(raw);

‎apps/desktop/src/preview/DesktopBrowserHost.test.ts‎

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// @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";
33
import { DesktopBrowserEvent } from "@t3tools/contracts";
44
import * as Effect from "effect/Effect";
55
import * as Fiber from "effect/Fiber";
@@ -968,4 +968,73 @@ describe("DesktopBrowserHost", () => {
968968
expect(host.humanStartedDownload(debuggee.tab.webContents)).toBe(false);
969969
}),
970970
);
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+
);
9711040
});

‎apps/desktop/src/preview/DesktopBrowserHost.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ export const make = Effect.gen(function* () {
329329
const forward = (current?: () => boolean) => {
330330
const change = tab.focusChange;
331331
const run = () =>
332-
current === undefined || current()
332+
tab.relay === relay && (current === undefined || current())
333333
? send(method, params, sessionId)
334334
: Promise.reject(new Error("The page this screenshot was for has moved on."));
335335
return change === null ? run() : change.then(run);
@@ -372,6 +372,24 @@ export const make = Effect.gen(function* () {
372372
emit({ type: "cdp", ...tab.key, message });
373373
}
374374
},
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+
},
375393
);
376394
tab.relay = relay;
377395
return relay;

0 commit comments

Comments
 (0)