The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { describe, expect, it, vi } from "vite-plus/test"; |
| 2 | |
| 3 | import { |
| 4 | createCdpRelayConnection, |
| 5 | type CdpRelayConnection, |
| 6 | type CdpRelayTarget, |
| 7 | } from "./CdpRelay.ts"; |
| 8 | |
| 9 | const makeTarget = ( |
| 10 | send: CdpRelayTarget["send"], |
| 11 | setDownloadDirectory: CdpRelayTarget["setDownloadDirectory"] = () => {}, |
| 12 | ackScreencastFrame: CdpRelayTarget["ackScreencastFrame"] = () => {}, |
| 13 | ): CdpRelayTarget => ({ |
| 14 | send, |
| 15 | targetId: async () => "GUEST-TARGET", |
| 16 | url: () => "http://localhost:4719/", |
| 17 | title: () => "Fixture", |
| 18 | userAgent: () => "Electron", |
| 19 | setDownloadDirectory, |
| 20 | receivesScreencast: () => true, |
| 21 | ackScreencastFrame, |
| 22 | }); |
| 23 | |
| 24 | const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) => |
| 25 | createCdpRelayConnection(target, write, () => {}); |
| 26 | |
| 27 | // Each relay reply resolves after a few microtasks; one macrotask lets them all land. |
| 28 | // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time |
| 29 | const settle = () => new Promise<void>((resolve) => setImmediate(resolve)); |
| 30 | |
| 31 | describe("CDP relay", () => { |
| 32 | it("announces only the tab's page, under its real target id", async () => { |
| 33 | const written: Array<Record<string, unknown>> = []; |
| 34 | const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw))); |
| 35 | relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); |
| 36 | relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} })); |
| 37 | await settle(); |
| 38 | const attach = written.findIndex((message) => message["id"] === 1); |
| 39 | expect(written.slice(attach, attach + 2)).toEqual([ |
| 40 | { id: 1, result: {} }, |
| 41 | { |
| 42 | method: "Target.attachedToTarget", |
| 43 | params: expect.objectContaining({ |
| 44 | sessionId: "t3-preview-page", |
| 45 | targetInfo: expect.objectContaining({ targetId: "GUEST-TARGET", type: "page" }), |
| 46 | }), |
| 47 | }, |
| 48 | ]); |
| 49 | expect(written).toContainEqual({ |
| 50 | id: 2, |
| 51 | error: expect.objectContaining({ message: expect.stringContaining("createTarget") }), |
| 52 | }); |
| 53 | }); |
| 54 | |
| 55 | it("forwards page commands to the tab and lets a slow one finish last", async () => { |
| 56 | const pending: Array<() => void> = []; |
| 57 | const send = vi.fn( |
| 58 | (method: string) => |
| 59 | new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))), |
| 60 | ); |
| 61 | const written: Array<Record<string, unknown>> = []; |
| 62 | const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); |
| 63 | relay.receive( |
| 64 | JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }), |
| 65 | ); |
| 66 | relay.receive(JSON.stringify({ id: 6, method: "DOM.enable", sessionId: "iframe-session" })); |
| 67 | pending[1]!(); |
| 68 | await settle(); |
| 69 | expect(written).toEqual([ |
| 70 | { id: 6, result: { method: "DOM.enable" }, sessionId: "iframe-session" }, |
| 71 | ]); |
| 72 | pending[0]!(); |
| 73 | await settle(); |
| 74 | expect(send).toHaveBeenNthCalledWith(1, "Page.captureScreenshot", {}, undefined, undefined); |
| 75 | expect(send).toHaveBeenNthCalledWith(2, "DOM.enable", {}, "iframe-session", undefined); |
| 76 | expect(written.at(-1)).toEqual({ |
| 77 | id: 5, |
| 78 | result: { method: "Page.captureScreenshot" }, |
| 79 | sessionId: "t3-preview-page", |
| 80 | }); |
| 81 | }); |
| 82 | |
| 83 | it("resumes paused child frames, so cross-site iframes run", async () => { |
| 84 | const send = vi.fn(async () => ({})); |
| 85 | const relay = makeRelay(makeTarget(send), () => {}); |
| 86 | relay.receive( |
| 87 | JSON.stringify({ |
| 88 | id: 1, |
| 89 | method: "Runtime.runIfWaitingForDebugger", |
| 90 | sessionId: "t3-preview-page", |
| 91 | }), |
| 92 | ); |
| 93 | relay.receive( |
| 94 | JSON.stringify({ |
| 95 | id: 2, |
| 96 | method: "Runtime.runIfWaitingForDebugger", |
| 97 | sessionId: "iframe-session", |
| 98 | }), |
| 99 | ); |
| 100 | await settle(); |
| 101 | expect(send.mock.calls).toEqual([ |
| 102 | ["Runtime.runIfWaitingForDebugger", {}, "iframe-session", undefined], |
| 103 | ]); |
| 104 | }); |
| 105 | |
| 106 | // Playwright enables focus emulation on every page it connects to, and Chromium then |
| 107 | // counts the guest as captured: a preview the panel hides keeps its timers unthrottled. |
| 108 | it("acknowledges Playwright's focus emulation without forcing it onto the guest", async () => { |
| 109 | const send = vi.fn(async () => ({})); |
| 110 | const written: Array<Record<string, unknown>> = []; |
| 111 | const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); |
| 112 | relay.receive( |
| 113 | JSON.stringify({ |
| 114 | id: 1, |
| 115 | method: "Emulation.setFocusEmulationEnabled", |
| 116 | params: { enabled: true }, |
| 117 | sessionId: "t3-preview-page", |
| 118 | }), |
| 119 | ); |
| 120 | await settle(); |
| 121 | expect(written).toEqual([{ id: 1, result: {}, sessionId: "t3-preview-page" }]); |
| 122 | expect(send).not.toHaveBeenCalled(); |
| 123 | }); |
| 124 | |
| 125 | it("routes tab events to the page session once the page is announced", async () => { |
| 126 | const written: Array<Record<string, unknown>> = []; |
| 127 | const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw))); |
| 128 | relay.event("Page.loadEventFired", {}, undefined); |
| 129 | expect(written).toEqual([]); |
| 130 | relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); |
| 131 | await settle(); |
| 132 | relay.event("Page.loadEventFired", { timestamp: 1 }, ""); |
| 133 | relay.event("Runtime.consoleAPICalled", {}, "iframe-session"); |
| 134 | expect(written.slice(-2)).toEqual([ |
| 135 | { method: "Page.loadEventFired", params: { timestamp: 1 }, sessionId: "t3-preview-page" }, |
| 136 | { method: "Runtime.consoleAPICalled", params: {}, sessionId: "iframe-session" }, |
| 137 | ]); |
| 138 | }); |
| 139 | }); |
| 140 | |
| 141 | describe("CDP relay extra sessions", () => { |
| 142 | it("gives a second page session the page's commands and events", async () => { |
| 143 | const send = vi.fn<CdpRelayTarget["send"]>(async () => ({})); |
| 144 | const written: Array<Record<string, unknown>> = []; |
| 145 | const nativeAcks: Array<number> = []; |
| 146 | const relay = makeRelay( |
| 147 | makeTarget(send, undefined, (frameId) => nativeAcks.push(frameId)), |
| 148 | (raw) => written.push(JSON.parse(raw)), |
| 149 | ); |
| 150 | relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); |
| 151 | relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" })); |
| 152 | await settle(); |
| 153 | const browserSession = (written.find((m) => m["id"] === 2)!["result"] as { sessionId: string }) |
| 154 | .sessionId; |
| 155 | relay.receive( |
| 156 | JSON.stringify({ |
| 157 | id: 3, |
| 158 | method: "Target.attachToTarget", |
| 159 | params: { targetId: "GUEST-TARGET", flatten: true }, |
| 160 | sessionId: browserSession, |
| 161 | }), |
| 162 | ); |
| 163 | relay.receive( |
| 164 | JSON.stringify({ |
| 165 | id: 4, |
| 166 | method: "Target.attachToTarget", |
| 167 | params: { targetId: "SOMETHING-ELSE" }, |
| 168 | sessionId: browserSession, |
| 169 | }), |
| 170 | ); |
| 171 | await settle(); |
| 172 | const extra = (written.find((m) => m["id"] === 3)!["result"] as { sessionId: string }) |
| 173 | .sessionId; |
| 174 | expect(written.find((m) => m["id"] === 4)).toHaveProperty("error"); |
| 175 | relay.receive(JSON.stringify({ id: 5, method: "Page.startScreencast", sessionId: extra })); |
| 176 | await settle(); |
| 177 | expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined, extra); |
| 178 | written.length = 0; |
| 179 | const frame = (frameId: number) => |
| 180 | relay.event("Page.screencastFrame", { data: "x", sessionId: frameId }, undefined); |
| 181 | const ack = (sessionId: string, frameId: number) => |
| 182 | relay.receive( |
| 183 | JSON.stringify({ |
| 184 | id: 6, |
| 185 | method: "Page.screencastFrameAck", |
| 186 | params: { sessionId: frameId }, |
| 187 | sessionId, |
| 188 | }), |
| 189 | ); |
| 190 | const delivered = () => { |
| 191 | const frames = written |
| 192 | .filter((m) => m["method"]) |
| 193 | .map((m) => [m["sessionId"], (m["params"] as { sessionId?: number }).sessionId]); |
| 194 | written.length = 0; |
| 195 | return frames; |
| 196 | }; |
| 197 | frame(1); |
| 198 | expect(delivered()).toEqual([ |
| 199 | ["t3-preview-page", 1], |
| 200 | [extra, 1], |
| 201 | ]); |
| 202 | // A session that has not acknowledged its frame gets only the newest one, on its ack. |
| 203 | for (let i = 2; i < 100; i++) frame(i); |
| 204 | expect(delivered()).toEqual([]); |
| 205 | // Frames every session is busy for stay unacknowledged, so Chromium pauses at its in-flight limit. |
| 206 | expect(nativeAcks).toEqual([1]); |
| 207 | ack(extra, 1); |
| 208 | await settle(); |
| 209 | expect(delivered()).toEqual([[extra, 99]]); |
| 210 | // Each consumer ack lets Chromium send one more frame. |
| 211 | expect(nativeAcks).toEqual([1, 2]); |
| 212 | ack(extra, 99); |
| 213 | await settle(); |
| 214 | expect(delivered()).toEqual([]); |
| 215 | expect(nativeAcks).toEqual([1, 2, 3]); |
| 216 | frame(100); |
| 217 | expect(delivered()).toEqual([[extra, 100]]); |
| 218 | ack(extra, 99); |
| 219 | await settle(); |
| 220 | frame(101); |
| 221 | expect(delivered()).toEqual([]); |
| 222 | expect(send.mock.calls.some(([method]) => method === "Page.screencastFrameAck")).toBe(false); |
| 223 | // A restart keeps the unacknowledged frame's slot until its own acknowledgement. |
| 224 | relay.receive(JSON.stringify({ id: 7, method: "Page.stopScreencast", sessionId: extra })); |
| 225 | relay.receive(JSON.stringify({ id: 8, method: "Page.startScreencast", sessionId: extra })); |
| 226 | await settle(); |
| 227 | delivered(); |
| 228 | frame(102); |
| 229 | expect(delivered()).toEqual([]); |
| 230 | ack(extra, 100); |
| 231 | await settle(); |
| 232 | expect(delivered()).toEqual([[extra, 102]]); |
| 233 | // Other events still reach a session while its frame is unacknowledged. |
| 234 | relay.event("Page.loadEventFired", { timestamp: 1 }, undefined); |
| 235 | expect(delivered().map(([session]) => session)).toEqual(["t3-preview-page", extra]); |
| 236 | }); |
| 237 | }); |
| 238 | |
| 239 | describe("CDP relay downloads", () => { |
| 240 | it("captures preview downloads without changing the default browser context", async () => { |
| 241 | const send = vi.fn(async () => ({})); |
| 242 | const directories: Array<string | null> = []; |
| 243 | const written: Array<Record<string, unknown>> = []; |
| 244 | const relay = makeRelay( |
| 245 | makeTarget(send, (directory) => directories.push(directory)), |
| 246 | (raw) => written.push(JSON.parse(raw)), |
| 247 | ); |
| 248 | relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); |
| 249 | relay.receive( |
| 250 | JSON.stringify({ |
| 251 | id: 2, |
| 252 | method: "Browser.setDownloadBehavior", |
| 253 | params: { |
| 254 | behavior: "allowAndName", |
| 255 | browserContextId: "t3-preview", |
| 256 | downloadPath: "/srv/artifacts", |
| 257 | eventsEnabled: true, |
| 258 | }, |
| 259 | }), |
| 260 | ); |
| 261 | await settle(); |
| 262 | expect(directories).toEqual(["/srv/artifacts"]); |
| 263 | expect(send.mock.calls).toEqual([ |
| 264 | ["Page.setDownloadBehavior", { behavior: "default" }, undefined], |
| 265 | ]); |
| 266 | written.length = 0; |
| 267 | relay.event("Page.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, ""); |
| 268 | relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, ""); |
| 269 | expect(written).toEqual([ |
| 270 | { method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } }, |
| 271 | { method: "Browser.downloadProgress", params: { guid: "g1", state: "completed" } }, |
| 272 | ]); |
| 273 | }); |
| 274 | |
| 275 | it("keeps denial scoped to the preview and restores Electron's save handling when allowed", async () => { |
| 276 | const send = vi.fn(async () => ({})); |
| 277 | const directories: Array<string | null> = []; |
| 278 | const relay = makeRelay( |
| 279 | makeTarget(send, (directory) => directories.push(directory)), |
| 280 | () => {}, |
| 281 | ); |
| 282 | for (const [id, behavior] of ["deny", "allowAndName"].entries()) { |
| 283 | relay.receive( |
| 284 | JSON.stringify({ |
| 285 | id, |
| 286 | method: "Browser.setDownloadBehavior", |
| 287 | params: { behavior, downloadPath: "/srv/artifacts" }, |
| 288 | }), |
| 289 | ); |
| 290 | await settle(); |
| 291 | } |
| 292 | expect(directories).toEqual([null, "/srv/artifacts"]); |
| 293 | expect(send.mock.calls).toEqual([ |
| 294 | ["Page.setDownloadBehavior", { behavior: "deny" }, undefined], |
| 295 | ["Page.setDownloadBehavior", { behavior: "default" }, undefined], |
| 296 | ]); |
| 297 | }); |
| 298 | |
| 299 | it("does not publish download events when the connection has disabled them", async () => { |
| 300 | const written: Array<Record<string, unknown>> = []; |
| 301 | const relay = makeRelay(makeTarget(vi.fn(async () => ({}))), (raw) => |
| 302 | written.push(JSON.parse(raw)), |
| 303 | ); |
| 304 | relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); |
| 305 | relay.receive( |
| 306 | JSON.stringify({ |
| 307 | id: 2, |
| 308 | method: "Browser.setDownloadBehavior", |
| 309 | params: { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: false }, |
| 310 | }), |
| 311 | ); |
| 312 | await settle(); |
| 313 | written.length = 0; |
| 314 | relay.event("Page.downloadWillBegin", { guid: "g1" }, ""); |
| 315 | relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, ""); |
| 316 | expect(written).toEqual([]); |
| 317 | }); |
| 318 | |
| 319 | it.each([false, true])( |
| 320 | "keeps the previous download configuration (events enabled: %s) when configuration fails", |
| 321 | async (enabled) => { |
| 322 | const send = vi |
| 323 | .fn(async () => ({})) |
| 324 | .mockResolvedValueOnce({}) |
| 325 | .mockRejectedValueOnce(new Error("Page command rejected")); |
| 326 | const written: Array<Record<string, unknown>> = []; |
| 327 | let directory: string | null = null; |
| 328 | const relay = makeRelay( |
| 329 | makeTarget(send, (value) => { |
| 330 | directory = value; |
| 331 | }), |
| 332 | (raw) => written.push(JSON.parse(raw)), |
| 333 | ); |
| 334 | relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); |
| 335 | for (const [id, eventsEnabled] of [enabled, !enabled].entries()) { |
| 336 | relay.receive( |
| 337 | JSON.stringify({ |
| 338 | id: id + 2, |
| 339 | method: "Browser.setDownloadBehavior", |
| 340 | params: { |
| 341 | behavior: id === 1 && enabled ? "deny" : "allowAndName", |
| 342 | downloadPath: id === 0 ? "/srv/artifacts" : "/srv/new-artifacts", |
| 343 | eventsEnabled, |
| 344 | }, |
| 345 | }), |
| 346 | ); |
| 347 | await settle(); |
| 348 | } |
| 349 | expect(written).toContainEqual({ |
| 350 | id: 3, |
| 351 | error: { code: -32000, message: "Page command rejected" }, |
| 352 | }); |
| 353 | expect(directory).toBe("/srv/artifacts"); |
| 354 | written.length = 0; |
| 355 | relay.event("Page.downloadWillBegin", { guid: "g1" }, ""); |
| 356 | relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, ""); |
| 357 | expect(written).toEqual( |
| 358 | enabled |
| 359 | ? [ |
| 360 | { method: "Browser.downloadWillBegin", params: { guid: "g1" } }, |
| 361 | { method: "Browser.downloadProgress", params: { guid: "g1", state: "completed" } }, |
| 362 | ] |
| 363 | : [], |
| 364 | ); |
| 365 | }, |
| 366 | ); |
| 367 | }); |
| 368 | |
| 369 | describe("CDP relay payload budget", () => { |
| 370 | // 2,048 references to one 40 KiB string: about 80 MiB once serialized, little memory here. |
| 371 | const oversized = Array(2048).fill("x".repeat(40 * 1024)); |
| 372 | |
| 373 | it("fails only an oversized reply and still returns a large screenshot", async () => { |
| 374 | const screenshot = "A".repeat(16 * 1024 * 1024); |
| 375 | const send = vi.fn(async (method: string) => |
| 376 | method === "DOM.getDocument" ? { nodes: oversized } : { data: screenshot }, |
| 377 | ); |
| 378 | const written: Array<Record<string, unknown>> = []; |
| 379 | const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); |
| 380 | relay.receive( |
| 381 | JSON.stringify({ id: 1, method: "DOM.getDocument", sessionId: "t3-preview-page" }), |
| 382 | ); |
| 383 | relay.receive( |
| 384 | JSON.stringify({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }), |
| 385 | ); |
| 386 | await settle(); |
| 387 | |
| 388 | const replies = written.map(({ id, error, result }) => ({ |
| 389 | id, |
| 390 | error, |
| 391 | size: (result as { data?: string } | undefined)?.data?.length, |
| 392 | })); |
| 393 | expect(replies).toEqual([ |
| 394 | { id: 1, error: { code: -32000, message: "CDP payload too large" }, size: undefined }, |
| 395 | { id: 2, error: undefined, size: screenshot.length }, |
| 396 | ]); |
| 397 | }); |
| 398 | |
| 399 | it.each([ |
| 400 | { args: oversized }, |
| 401 | { args: "\u0001".repeat(12 * 1024 * 1024) }, |
| 402 | { args: Array(2_700_000).fill(-0.0000010000000000000002) }, |
| 403 | ])("closes instead of dropping an oversized event (%#)", async ({ args }) => { |
| 404 | const written: Array<Record<string, unknown>> = []; |
| 405 | const close = vi.fn(); |
| 406 | const relay = createCdpRelayConnection( |
| 407 | makeTarget(vi.fn()), |
| 408 | (raw) => written.push(JSON.parse(raw)), |
| 409 | close, |
| 410 | ); |
| 411 | relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); |
| 412 | await settle(); |
| 413 | written.length = 0; |
| 414 | |
| 415 | relay.event("Runtime.consoleAPICalled", { args }, ""); |
| 416 | relay.event("Page.loadEventFired", { timestamp: 1 }, ""); |
| 417 | |
| 418 | relay.receive(JSON.stringify({ id: 2, method: "Target.setAutoAttach" })); |
| 419 | expect(close).toHaveBeenCalledOnce(); |
| 420 | expect(written.map((message) => message["method"])).toEqual([]); |
| 421 | }); |
| 422 | }); |
| 423 | |
| 424 | describe("CDP relay reconnects", () => { |
| 425 | it("reports the page's default execution context to every connection", async () => { |
| 426 | // Electron keeps one debugger attached, so Runtime stays enabled after a client drops, |
| 427 | // and the native Runtime.enable announces contexts again only after Runtime.disable. |
| 428 | let runtimeEnabled = false; |
| 429 | let current: CdpRelayConnection | undefined; |
| 430 | const context = { |
| 431 | context: { id: 1, origin: "null", name: "", auxData: { isDefault: true, frameId: "F" } }, |
| 432 | }; |
| 433 | const send = vi.fn(async (method: string) => { |
| 434 | if (method === "Runtime.disable") runtimeEnabled = false; |
| 435 | if (method === "Runtime.enable" && !runtimeEnabled) { |
| 436 | runtimeEnabled = true; |
| 437 | current!.event("Runtime.executionContextCreated", context, ""); |
| 438 | } |
| 439 | return {}; |
| 440 | }); |
| 441 | const connect = async () => { |
| 442 | const written: Array<Record<string, unknown>> = []; |
| 443 | current = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); |
| 444 | current.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); |
| 445 | await settle(); |
| 446 | current.receive( |
| 447 | JSON.stringify({ id: 2, method: "Runtime.enable", sessionId: "t3-preview-page" }), |
| 448 | ); |
| 449 | await settle(); |
| 450 | return written.filter((m) => m["method"] === "Runtime.executionContextCreated"); |
| 451 | }; |
| 452 | const expected = [ |
| 453 | { |
| 454 | method: "Runtime.executionContextCreated", |
| 455 | params: context, |
| 456 | sessionId: "t3-preview-page", |
| 457 | }, |
| 458 | ]; |
| 459 | expect(await connect()).toEqual(expected); |
| 460 | expect(await connect()).toEqual(expected); |
| 461 | }); |
| 462 | }); |