The best way to control Claude Code, Codex and more from any computer or phone

main
ts 330 lines 12.8 KB
Raw
1 // Electron allows one debugger per webContents; share the manager's attachment.
2
3 export interface CdpRelayTarget {
4 readonly send: (
5 method: string,
6 params: Record<string, unknown>,
7 sessionId: string | undefined,
8 /** The extra session that sent it, such as a viewer's; the main connection has none. */
9 owner?: string,
10 ) => Promise<unknown>;
11 readonly sessionDetached?: (owner: string) => void;
12 /** Whether a page session, by owner as `send` names it, gets the page's screencast frames. */
13 readonly receivesScreencast: (owner: string | undefined) => boolean;
14 /** Acknowledges a native screencast frame, letting Chromium send the next one. */
15 readonly ackScreencastFrame: (frameId: number) => void;
16 /** The page's own CDP target id; Playwright keys the main frame by it. */
17 readonly targetId: () => Promise<string>;
18 readonly url: () => string;
19 readonly title: () => string;
20 readonly userAgent: () => string;
21 /** The desktop and its server share a disk; download paths need no translation. */
22 readonly setDownloadDirectory: (directory: string | null) => void;
23 }
24
25 export interface CdpRelayConnection {
26 readonly receive: (raw: string) => void;
27 readonly event: (method: string, params: unknown, sessionId: string | undefined) => void;
28 }
29
30 interface CdpCommand {
31 readonly id: number;
32 readonly method: string;
33 readonly params?: Record<string, unknown>;
34 readonly sessionId?: string;
35 }
36
37 const isCommand = (value: unknown): value is CdpCommand =>
38 typeof value === "object" &&
39 value !== null &&
40 typeof (value as { id?: unknown }).id === "number" &&
41 typeof (value as { method?: unknown }).method === "string";
42
43 // CDP values are plain JSON data, so their serialized size can be bounded before
44 // JSON.stringify allocates it. A string counts at its length unless it holds a
45 // character JSON may escape, which can take six code units.
46 const MAX_CDP_PAYLOAD_SIZE = 64 * 1024 * 1024;
47 const MAY_ESCAPE = /[^\x20\x21\x23-\x5b\x5d-\ud7ff\ue000-\uffff]/;
48 const serializedSize = (text: string) =>
49 (MAY_ESCAPE.test(text) ? text.length * 6 : text.length) + 3;
50
51 const fitsPayloadBudget = (message: unknown) => {
52 let remaining = MAX_CDP_PAYLOAD_SIZE;
53 const visit = (value: unknown): boolean => {
54 remaining -= typeof value === "string" ? serializedSize(value) : 26;
55 if (remaining < 0) return false;
56 if (typeof value !== "object" || value === null) return true;
57 if (Array.isArray(value)) return value.every(visit);
58 return Object.entries(value).every(([key, item]) => {
59 remaining -= serializedSize(key);
60 return visit(item);
61 });
62 };
63 return visit(message);
64 };
65
66 const BROWSER_CONTEXT_ID = "t3-preview";
67 const ANNOUNCE = Symbol("announce");
68 const PAGE_SESSION_ID = "t3-preview-page";
69
70 const ACKNOWLEDGED = new Set([
71 "Target.setDiscoverTargets",
72 "Browser.grantPermissions",
73 "Browser.resetPermissions",
74 "Browser.cancelDownload",
75 ]);
76
77 export function createCdpRelayConnection(
78 target: CdpRelayTarget,
79 write: (message: string) => void,
80 close: () => void,
81 ): CdpRelayConnection {
82 let closed = false;
83 const send = (message: Record<string, unknown>) => {
84 if (closed) return;
85 if (fitsPayloadBudget(message)) {
86 write(JSON.stringify(message));
87 return;
88 }
89 // An error reply fails only that command. A dropped event would leave
90 // Playwright out of step with the page, so the relay closes instead.
91 if (typeof message["id"] === "number") {
92 write(
93 JSON.stringify({
94 id: message["id"],
95 error: { code: -32000, message: "CDP payload too large" },
96 ...(message["sessionId"] === undefined ? {} : { sessionId: message["sessionId"] }),
97 }),
98 );
99 return;
100 }
101 closed = true;
102 close();
103 };
104 let attached = false;
105 let downloadEventsEnabled = false;
106 /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
107 const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);
108 // Each page session holds one unacknowledged frame and keeps the newest one skipped meanwhile.
109 const unackedFrames = new Map<string, number>();
110 const skippedFrames = new Map<string, Record<string, unknown>>();
111 // Chromium keeps a few frames in flight and reuses one frame id per run, so pacing it means
112 // leaving frames every session is busy for unacknowledged and releasing one per consumer ack.
113 const heldNativeFrames: Array<number> = [];
114 const releaseHeldFramesWithoutHolders = () => {
115 if (skippedFrames.size === 0)
116 for (const frameId of heldNativeFrames.splice(0)) target.ackScreencastFrame(frameId);
117 };
118 const sendFrame = (sessionId: string, params: Record<string, unknown>) => {
119 unackedFrames.set(sessionId, params["sessionId"] as number);
120 send({ method: "Page.screencastFrame", params, sessionId });
121 };
122 let sessionSequence = 0;
123 const newSession = (kind: "browser" | "page") => {
124 const sessionId = `t3-preview-${kind}-${++sessionSequence}`;
125 sessions.set(sessionId, kind);
126 return sessionId;
127 };
128 const targetInfo = async () => ({
129 targetId: await target.targetId(),
130 type: "page",
131 title: target.title(),
132 url: target.url(),
133 attached: true,
134 canAccessOpener: false,
135 browserContextId: BROWSER_CONTEXT_ID,
136 });
137
138 const browserCommand = async (command: CdpCommand): Promise<unknown> => {
139 if (ACKNOWLEDGED.has(command.method)) return {};
140 switch (command.method) {
141 case "Browser.setDownloadBehavior": {
142 const directory = command.params?.["downloadPath"];
143 const allowed = command.params?.["behavior"] !== "deny" && typeof directory === "string";
144 // Browser-scoped behavior targets Electron's app session; preview paths belong to will-download.
145 const result = await target.send(
146 "Page.setDownloadBehavior",
147 { behavior: command.params?.["behavior"] === "deny" ? "deny" : "default" },
148 undefined,
149 );
150 target.setDownloadDirectory(allowed ? directory : null);
151 downloadEventsEnabled = command.params?.["eventsEnabled"] === true;
152 return result;
153 }
154 case "Browser.getVersion":
155 return {
156 protocolVersion: "1.3",
157 product: "Electron",
158 revision: "",
159 userAgent: target.userAgent(),
160 jsVersion: "",
161 };
162 case "Target.getTargetInfo":
163 return {
164 targetInfo: {
165 targetId: "browser",
166 type: "browser",
167 title: "",
168 url: "",
169 attached: true,
170 canAccessOpener: false,
171 },
172 };
173 case "Target.getBrowserContexts":
174 return { browserContextIds: [] };
175 case "Target.getTargets":
176 return { targetInfos: [await targetInfo()] };
177 case "Target.attachToBrowserTarget":
178 return { sessionId: newSession("browser") };
179 case "Target.attachToTarget": {
180 const targetId = command.params?.["targetId"];
181 if (targetId !== (await target.targetId()))
182 throw new Error("Only this preview tab's page can be attached.");
183 return { sessionId: newSession("page") };
184 }
185 case "Target.detachFromTarget": {
186 const sessionId = command.params?.["sessionId"];
187 if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID) {
188 sessions.delete(sessionId);
189 unackedFrames.delete(sessionId);
190 skippedFrames.delete(sessionId);
191 releaseHeldFramesWithoutHolders();
192 target.sessionDetached?.(sessionId);
193 }
194 return {};
195 }
196 case "Target.setAutoAttach": {
197 if (attached) return {};
198 attached = true;
199 const info = await targetInfo();
200 return {
201 [ANNOUNCE]: {
202 method: "Target.attachedToTarget",
203 params: { sessionId: PAGE_SESSION_ID, targetInfo: info, waitingForDebugger: false },
204 },
205 };
206 }
207 default:
208 throw new Error(`Not supported for a desktop preview tab: ${command.method}`);
209 }
210 };
211
212 let runtimeReset: Promise<unknown> | undefined;
213
214 const pageCommand = (command: CdpCommand): Promise<unknown> => {
215 const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId;
216 const owner =
217 child === undefined && command.sessionId !== PAGE_SESSION_ID ? command.sessionId : undefined;
218 // Child frames/workers pause on auto-attach until resumed; only the main page can skip this command.
219 if (command.method === "Runtime.runIfWaitingForDebugger" && child === undefined) {
220 return Promise.resolve({});
221 }
222 // Playwright asks for this on every page; the host emulates focus only while it is in use.
223 if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({});
224 if (command.method === "Page.screencastFrameAck" && child === undefined) {
225 // A restart keeps the slot too, or restarting would let frames past an unacknowledged one.
226 const sessionId = command.sessionId!;
227 if (unackedFrames.get(sessionId) === command.params?.["sessionId"]) {
228 unackedFrames.delete(sessionId);
229 const skipped = skippedFrames.get(sessionId);
230 skippedFrames.delete(sessionId);
231 if (
232 skipped !== undefined &&
233 target.receivesScreencast(sessionId === PAGE_SESSION_ID ? undefined : sessionId)
234 )
235 sendFrame(sessionId, skipped);
236 const released = heldNativeFrames.shift();
237 if (released !== undefined) target.ackScreencastFrame(released);
238 }
239 return Promise.resolve({});
240 }
241 if (command.method === "Page.stopScreencast" && child === undefined) {
242 skippedFrames.delete(command.sessionId!);
243 releaseHeldFramesWithoutHolders();
244 }
245 // The shared debugger keeps Runtime enabled after an earlier connection, and a repeated
246 // enable reports no existing contexts; Playwright waits for them, so reset once per connection.
247 if (command.method === "Runtime.enable" && child === undefined) {
248 runtimeReset ??= target.send("Runtime.disable", {}, undefined, owner).catch(() => undefined);
249 return runtimeReset.then(() =>
250 target.send(command.method, command.params ?? {}, undefined, owner),
251 );
252 }
253 return target.send(command.method, command.params ?? {}, child, owner);
254 };
255
256 return {
257 receive: (raw) => {
258 if (closed) return;
259 let command: unknown;
260 try {
261 command = JSON.parse(raw);
262 } catch {
263 return;
264 }
265 if (!isCommand(command)) return;
266 const result =
267 command.sessionId === undefined || sessions.get(command.sessionId) === "browser"
268 ? browserCommand(command)
269 : pageCommand(command);
270 const route = command.sessionId === undefined ? {} : { sessionId: command.sessionId };
271 // Reply as commands finish so slow commands cannot block later replies.
272 void result.then(
273 (value) => {
274 const announce =
275 typeof value === "object" && value !== null && ANNOUNCE in value
276 ? (value as { [ANNOUNCE]: Record<string, unknown> })[ANNOUNCE]
277 : undefined;
278 send({ id: command.id, result: announce ? {} : (value ?? {}), ...route });
279 if (announce) send(announce);
280 },
281 (cause: unknown) =>
282 send({
283 id: command.id,
284 error: {
285 code: -32000,
286 message: cause instanceof Error ? cause.message : String(cause),
287 },
288 ...route,
289 }),
290 );
291 },
292 event: (method, params, sessionId) => {
293 if (!attached) return;
294 if (method.startsWith("Page.download")) method = method.replace("Page.", "Browser.");
295 // Download events are the browser's; Playwright listens on its root session.
296 if (method.startsWith("Browser.download")) {
297 if (downloadEventsEnabled) send({ method, params });
298 return;
299 }
300 // Electron reports the page's own events with an empty session id.
301 if (sessionId) {
302 send({ method, params, sessionId });
303 return;
304 }
305 if (method === "Page.screencastFrame") {
306 const frame = (params ?? {}) as Record<string, unknown>;
307 const frameId = frame["sessionId"];
308 if (typeof frameId !== "number") return;
309 let held = false;
310 let delivered = false;
311 for (const [id, kind] of sessions) {
312 if (kind !== "page") continue;
313 if (!target.receivesScreencast(id === PAGE_SESSION_ID ? undefined : id)) continue;
314 if (unackedFrames.has(id)) {
315 skippedFrames.set(id, frame);
316 held = true;
317 } else {
318 sendFrame(id, frame);
319 delivered = true;
320 }
321 }
322 if (held && !delivered) heldNativeFrames.push(frameId);
323 else target.ackScreencastFrame(frameId);
324 return;
325 }
326 for (const [id, kind] of sessions)
327 if (kind === "page") send({ method, params, sessionId: id });
328 },
329 };
330 }