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 22, 18:15 UTC
fix(desktop): reduce app crashes when a preview tab's renderer dies during agent screenshots (#24056)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
shivam committed
Oct 23, 2026 at 17:13 UTC
cccb78c459a9cabb8dcdc647f7264bd0042b4296
2 files changed
+161
-6
apps/desktop/src/preview/DesktopBrowserHost.test.ts
+106
-3
@@ -3,6 +3,7 @@ import { describe, expect, it } from "@effect/vitest";
3
import { DesktopBrowserEvent } from "@t3tools/contracts";
4
import * as Effect from "effect/Effect";
5
import * as Fiber from "effect/Fiber";
6
+import * as Queue from "effect/Queue";
7
import * as Schema from "effect/Schema";
8
import * as Stream from "effect/Stream";
9
import * as NodeEvents from "node:events";
@@ -15,32 +16,54 @@ const decodeCdpReply = Schema.decodeUnknownSync(
16
Schema.fromJsonString(Schema.Struct({ id: Schema.Number })),
17
);
18
const key = { threadId: "thread-1", tabId: "tab-1" };
19
+/** Sends a page command whose id the fake debugger records as it receives it. */
20
+const command = (
21
+ host: DesktopBrowserHost.DesktopBrowserHost["Service"],
22
+ id: number,
23
+ method: string,
24
+) =>
25
+ host.handleCommandLine(
26
+ encodeJson({
27
+ type: "cdp",
28
+ ...key,
29
+ message: encodeJson({ id, method, params: { id }, sessionId: "t3-preview-page" }),
30
+ }),
31
+ );
32
33
const makeDebuggee = () => {
34
const emitter = new NodeEvents.EventEmitter();
35
const pending: Array<() => void> = [];
36
+ const sent: Array<unknown> = [];
37
+ const sendWaiters: Array<() => void> = [];
38
const debuggee = Object.assign(emitter, {
23
- sendCommand: (method: string) =>
39
+ sendCommand: (method: string, params?: { id?: number }) =>
40
new Promise((resolve) => {
41
if (method === "Target.getTargetInfo") {
42
resolve({ targetInfo: { targetId: "GUEST" } });
43
return;
44
}
45
+ sent.push(params?.id);
46
pending.push(() => resolve({ method }));
47
+ sendWaiters.shift()?.();
48
}),
49
});
32
- const webContents = {
50
+ const webContents = Object.assign(new NodeEvents.EventEmitter(), {
51
getURL: () => "http://localhost/",
52
getTitle: () => "Page",
53
getUserAgent: () => "Electron",
36
- };
54
+ });
55
return {
56
tab: {
57
webContents: webContents as unknown as Electron.WebContents,
58
debugger: debuggee as unknown as Electron.Debugger,
59
},
60
emit: (method: string, params: unknown) => emitter.emit("message", {}, method, params, ""),
61
+ navigate: () => webContents.emit("did-navigate"),
62
+ /** Ids of the commands the debugger received, in order. */
63
+ sent,
64
+ nextSend: () => new Promise<void>((resolve) => sendWaiters.push(resolve)),
65
release: () => pending.splice(0).forEach((resolve) => resolve()),
66
+ releaseFirst: () => pending.shift()?.(),
67
};
68
};
69
@@ -51,6 +74,25 @@ const takeEvents = (host: DesktopBrowserHost.DesktopBrowserHost["Service"], coun
74
Effect.map((lines) => lines.map((line) => decodeEvent(new TextDecoder().decode(line)))),
75
);
76
77
+/**
78
+ * Ids of the replies the host sends, in order. A screenshot's reply leaves after its turn
79
+ * has passed on, so by then the next waiting screenshot, if any, has been sent. Subscribe
80
+ * before sending commands: a new subscriber releases the tab's relay.
81
+ */
82
+const watchReplies = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) =>
83
+ Effect.gen(function* () {
84
+ const replies = yield* Queue.unbounded<number>();
85
+ yield* host.events.pipe(
86
+ Stream.map((line) => decodeEvent(new TextDecoder().decode(line))),
87
+ Stream.runForEach((event) =>
88
+ event.type === "cdp" ? Queue.offer(replies, decodeCdpReply(event.message).id) : Effect.void,
89
+ ),
90
+ Effect.forkScoped,
91
+ );
92
+ yield* Effect.yieldNow;
93
+ return replies;
94
+ });
95
+
96
describe("DesktopBrowserHost", () => {
97
it.effect("announces tabs already attached to a backend that starts later", () =>
98
Effect.gen(function* () {
@@ -89,6 +131,67 @@ describe("DesktopBrowserHost", () => {
131
}).pipe(Effect.scoped),
132
);
133
134
+ it.effect("sends a page one screenshot at a time", () =>
135
+ Effect.gen(function* () {
136
+ const host = yield* DesktopBrowserHost.make;
137
+ const debuggee = makeDebuggee();
138
+ host.attach(key, debuggee.tab);
139
+ const replies = yield* watchReplies(host);
140
+
141
+ yield* command(host, 1, "Page.captureScreenshot");
142
+ yield* command(host, 2, "Page.captureScreenshot");
143
+ yield* command(host, 3, "DOM.enable");
144
+ expect(debuggee.sent).toEqual([1, 3]);
145
+
146
+ debuggee.releaseFirst();
147
+ expect(yield* Queue.take(replies)).toBe(1);
148
+ expect(debuggee.sent).toEqual([1, 3, 2]);
149
+ }).pipe(Effect.scoped),
150
+ );
151
+
152
+ it.effect("stops waiting on a screenshot the page navigated away from", () =>
153
+ Effect.gen(function* () {
154
+ const host = yield* DesktopBrowserHost.make;
155
+ const debuggee = makeDebuggee();
156
+ host.attach(key, debuggee.tab);
157
+ const replies = yield* watchReplies(host);
158
+
159
+ yield* command(host, 1, "Page.captureScreenshot");
160
+ yield* command(host, 2, "Page.captureScreenshot");
161
+ yield* command(host, 3, "Page.captureScreenshot");
162
+ debuggee.navigate();
163
+ expect(debuggee.sent).toEqual([1, 2]);
164
+
165
+ // The superseded screenshot answering late must not start a third beside the second.
166
+ debuggee.releaseFirst();
167
+ expect(yield* Queue.take(replies)).toBe(1);
168
+ expect(debuggee.sent).toEqual([1, 2]);
169
+
170
+ debuggee.releaseFirst();
171
+ expect(yield* Queue.take(replies)).toBe(2);
172
+ expect(debuggee.sent).toEqual([1, 2, 3]);
173
+ }).pipe(Effect.scoped),
174
+ );
175
+
176
+ it.effect("drops screenshots a released relay left waiting", () =>
177
+ Effect.gen(function* () {
178
+ const host = yield* DesktopBrowserHost.make;
179
+ const debuggee = makeDebuggee();
180
+ host.attach(key, debuggee.tab);
181
+
182
+ yield* command(host, 1, "Page.captureScreenshot");
183
+ yield* command(host, 2, "Page.captureScreenshot");
184
+ yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
185
+ yield* command(host, 3, "Page.captureScreenshot");
186
+ expect(debuggee.sent).toEqual([1]);
187
+
188
+ const sent = debuggee.nextSend();
189
+ debuggee.release();
190
+ yield* Effect.promise(() => sent);
191
+ expect(debuggee.sent).toEqual([1, 3]);
192
+ }),
193
+ );
194
+
195
it.effect("saves a server tab's download under its CDP guid where the server asked", () =>
196
Effect.gen(function* () {
197
const host = yield* DesktopBrowserHost.make;
apps/desktop/src/preview/DesktopBrowserHost.ts
+55
-3
@@ -43,6 +43,8 @@ interface AttachedTab {
43
readonly key: DesktopBrowserTabKey;
44
readonly debuggee: DesktopBrowserTabDebugger;
45
relay: CdpRelayConnection | null;
46
+ screenshotTurn: object | null;
47
+ readonly waitingScreenshots: Array<() => void>;
48
downloadDirectory: string | null;
49
pendingDownloadGuid: string | null;
50
agentInputAt: number;
@@ -52,6 +54,7 @@ interface AttachedTab {
54
params: unknown,
55
sessionId: string,
56
) => void;
57
+ readonly onNewDocument: () => void;
58
}
59
60
export class DesktopBrowserHost extends Context.Service<
@@ -84,15 +87,54 @@ export const make = Effect.gen(function* () {
87
const tabs = new Map<string, AttachedTab>();
88
const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event));
89
90
+ const nextScreenshot = (tab: AttachedTab) => {
91
+ tab.screenshotTurn = null;
92
+ tab.waitingScreenshots.shift()?.();
93
+ };
94
+
95
+ /**
96
+ * Chromium below 157 crashes the whole app when a guest's renderer exits with a
97
+ * screenshot copy in flight (crbug.com/567321049). Overlapping screenshots make that
98
+ * far likelier, and one the server gave up on stays pending in Chromium, so each guest
99
+ * gets one at a time. One queued by a relay released since then is dropped unsent.
100
+ */
101
+ const takeScreenshot = (
102
+ tab: AttachedTab,
103
+ relay: CdpRelayConnection,
104
+ capture: () => Promise<unknown>,
105
+ ) =>
106
+ new Promise<unknown>((resolve, reject) => {
107
+ const start = () => {
108
+ if (tab.relay !== relay) {
109
+ reject(new Error("The preview connection that asked for this screenshot closed."));
110
+ nextScreenshot(tab);
111
+ return;
112
+ }
113
+ const turn = {};
114
+ tab.screenshotTurn = turn;
115
+ capture()
116
+ .finally(() => {
117
+ if (tab.screenshotTurn === turn) nextScreenshot(tab);
118
+ })
119
+ .then(resolve, reject);
120
+ };
121
+ if (tab.screenshotTurn === null) start();
122
+ else tab.waitingScreenshots.push(start);
123
+ });
124
+
125
const relayFor = (tab: AttachedTab) => {
126
if (tab.relay) return tab.relay;
127
const { webContents, debugger: debuggee } = tab.debuggee;
128
+ const send = (method: string, params: Record<string, unknown>, sessionId?: string) =>
129
+ sessionId === undefined
130
+ ? sendPageCommand(webContents, debuggee, method, params)
131
+ : debuggee.sendCommand(method, params, sessionId);
132
const relay: CdpRelayConnection = createCdpRelayConnection(
133
{
134
send: (method, params, sessionId) =>
93
- sessionId === undefined
94
- ? sendPageCommand(webContents, debuggee, method, params)
95
- : debuggee.sendCommand(method, params, sessionId),
135
+ method === "Page.captureScreenshot"
136
+ ? takeScreenshot(tab, relay, () => send(method, params, sessionId))
137
+ : send(method, params, sessionId),
138
targetId: () =>
139
debuggee
140
.sendCommand("Target.getTargetInfo")
@@ -133,7 +175,9 @@ export const make = Effect.gen(function* () {
175
const tab = tabs.get(id);
176
if (!tab) return;
177
tabs.delete(id);
178
+ tab.relay = null;
179
tab.debuggee.debugger.off("message", tab.onMessage);
180
+ tab.debuggee.webContents.off("did-navigate", tab.onNewDocument);
181
emit({ type: "detached", ...key });
182
};
183
@@ -145,6 +189,8 @@ export const make = Effect.gen(function* () {
189
key,
190
debuggee,
191
relay: null,
192
+ screenshotTurn: null,
193
+ waitingScreenshots: [],
194
downloadDirectory: null,
195
pendingDownloadGuid: null,
196
agentInputAt: Number.NEGATIVE_INFINITY,
@@ -155,9 +201,15 @@ export const make = Effect.gen(function* () {
201
}
202
tab.relay?.event(method, params, sessionId);
203
},
204
+ // A screenshot pending when the page loads a new document, a reload included, can
205
+ // stay unanswered. A crashed page lands here once it reloads, well after its renderer died.
206
+ onNewDocument: () => {
207
+ if (tab.screenshotTurn !== null) nextScreenshot(tab);
208
+ },
209
};
210
tabs.set(id, tab);
211
debuggee.debugger.on("message", tab.onMessage);
212
+ debuggee.webContents.on("did-navigate", tab.onNewDocument);
213
emit({ type: "attached", ...key });
214
};
215