Skip to content

Fix CDP Page.printToPDF support - #7044

Merged
nwparker merged 7 commits into
stablyai:mainfrom
AvichalDwivedi2205:fix/cdp-print-to-pdf
Jul 3, 2026
Merged

nwparker merged 7 commits into
stablyai:mainfrom
AvichalDwivedi2205:fix/cdp-print-to-pdf

Conversation

@AvichalDwivedi2205

@AvichalDwivedi2205 AvichalDwivedi2205 commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #7032.

Adds Page.printToPDF support to Orca's per-tab CDP websocket proxy (CdpWsProxy). Before this change, a CDP client (Playwright/Puppeteer) calling page.pdf() against an Orca browser tab got Protocol error (Page.printToPDF): 'Page.printToPDF' wasn't found, because the proxy forwarded the command to webContents.debugger.sendCommand, and Electron webview guests do not implement Page.printToPDF over the debugger.

The proxy now handles Page.printToPDF natively via Electron's webContents.printToPDF, exactly mirroring how the existing Page.captureScreenshot handler already bypasses the debugger for the same class of webview-guest limitation. It supports both response shapes:

  • Direct base64 ({ data: <base64> }) when transferMode is omitted.
  • Streamed ({ data: "", stream: <handle> } + IO.read / IO.close) when transferMode: "ReturnAsStream" — the path Playwright's page.pdf() uses.

CDP params are translated faithfully to Electron options: landscape, printBackground, scale, paperWidth/paperHeight → pageSize, marginTop/Bottom/Left/Right → margins (omitted sides default to CDP's 1cm), pageRanges, header/footer templates, and the tagged-PDF / outline flags. Only well-formed values are forwarded, so a malformed param can never smuggle NaN/Infinity into Electron.

This does not duplicate the existing orca pdf CLI command — that path (agent-browser-bridge.pdf()) already bypasses the proxy with a native printToPDF call and serves Orca's own tooling. This PR fills the distinct gap for external CDP clients driving the tab over the websocket endpoint.

Takeover note

This PR was adopted and finished by a maintainer (original author: @AvichalDwivedi2205). Changes on top of the original submission:

  • Extracted the PDF option mapping and the stream store into a focused cdp-print-to-pdf.ts module (buildPrintToPdfOptions + CdpPdfStreamStore), mirroring the sibling cdp-screenshot.ts. This keeps the already-over-budget proxy from growing and gives the PDF logic direct unit coverage.
  • Fixed a memory-retention bug: a ReturnAsStream print that resolved after the requesting client disconnected would register its (potentially large) buffer in the stream store after the disconnect's cleanup already ran, orphaning it until the 5-minute TTL. handlePrintToPdf now re-checks isActiveClient after the await, matching navigateWithLifecycle / reloadWithLifecycle.
  • Added a regression test for that race and a full unit suite for the new module.

Evidence

Before (origin/main) — the gap is real. A unit repro sending Page.printToPDF against the proxy shows the command is forwarded to the debugger (native printToPDF never called) and the client receives the CDP error:

Page.printToPDF -> forwarded to debugger.sendCommand -> "'Page.printToPDF' wasn't found"

The identical repro inverts on this branch — Page.printToPDF is no longer forwarded to the debugger:

AssertionError: expected [ 'Page.enable', … ] to include 'Page.printToPDF'

After — real PDF bytes through the real CDP endpoint. An Electron harness drives CdpWsProxy against a real offscreen webContents over a real websocket:

proxy endpoint: ws://127.0.0.1:51406
direct: 19544 bytes, magic="%PDF-", %PDF-? true
stream handle: orca-pdf-<uuid>-1 (data empty? true)
stream: 19544 bytes over 5 IO.read chunk(s), magic="%PDF-", %PDF-? true, closed=true
read-after-close rejected: true
RESULT: PASS — real %PDF- bytes via CDP endpoint

Both the direct and streamed paths produce byte-identical, valid PDF document, version 1.4, 1 pages output (file(1) confirmed). IO.close frees the handle; a read after close is rejected with Invalid stream handle.

Tests / checks: pnpm vitest run on both suites → 46 passed (16 new module tests + 30 proxy tests). pnpm run typecheck clean. oxlint clean on all touched files. The disconnect-mid-print regression test was confirmed to fail without the isActiveClient guard (expected "create" to not be called at all, but actually been called 1 times) and pass with it.

ELI5

Orca has a built-in browser. Robots (Playwright/Puppeteer) can drive that browser through a special socket. When a robot asked "print this page to a PDF," Orca said "I don't know that command." Now Orca hears that request, uses Electron's real printer to make the PDF, and hands the bytes back — either all at once or in small pieces, whichever the robot asked for. It also cleans up the PDF it made if the robot walks away, so memory doesn't pile up.

Trade-offs

  • Full PDF held in memory per stream. Electron's printToPDF returns the whole document as one buffer, so a ReturnAsStream handle holds the entire PDF (potentially tens of MB for a long page) until the client sends IO.close or the 5-minute TTL evicts it. This is inherent to the Electron API — there is no incremental stream to forward — and is bounded by the TTL plus eager cleanup on client disconnect. Auto-freeing at EOF was deliberately avoided because it would violate the CDP IO-stream contract (streams persist until IO.close; a client may legitimately re-read via offset).
  • No other regressions: unrelated CDP commands, including non-PDF IO.read/IO.close streams (e.g. Tracing), continue to forward through the existing debugger path unchanged.

@ghost

ghost commented Jul 1, 2026

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 3 individual chapters for you:

Title
1 Define PDF conversion utilities and types
2 Implement PDF streaming and command routing
3 Test CDP PDF generation and streaming
Open in Stage

Chapters generated by Stage for commit 06a9a44 on Jul 1, 2026 8:25pm UTC.

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds native handling of CDP Page.printToPDF requests in CdpWsProxy using webContents.printToPDF. It translates print parameters into Electron options, stores streamed PDF bytes in memory by handle, and serves IO.read/IO.close for PDF stream handles while forwarding non-PDF IO traffic unchanged. Client disconnect and close paths clear buffered PDF streams. Tests cover direct PDF output, streamed reads and closes, cleanup, default margins, and forwarding behavior.

Changes

Area Change
cdp-print-to-pdf.ts Added PDF option mapping and in-memory PDF stream storage
cdp-ws-proxy.ts Added native Page.printToPDF handling, PDF stream routing, and cleanup
cdp-ws-proxy.test.ts Added printToPDF mock plus tests for direct PDF output, streamed PDF behavior, cleanup, default margins, and non-PDF IO forwarding

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant CdpWsProxy
  participant webContents

  Client->>CdpWsProxy: Page.printToPDF (transferMode)
  CdpWsProxy->>webContents: printToPDF(buildPrintToPdfOptions)
  webContents-->>CdpWsProxy: PDF Buffer
  alt transferMode ReturnAsStream
    CdpWsProxy->>CdpWsProxy: store buffer in pdfStreams
    CdpWsProxy-->>Client: stream handle (data:'', stream)
    Client->>CdpWsProxy: IO.read(handle, offset, size)
    CdpWsProxy-->>Client: base64 chunk, eof
    Client->>CdpWsProxy: IO.close(handle)
    CdpWsProxy->>CdpWsProxy: delete stream from pdfStreams
  else direct response
    CdpWsProxy-->>Client: base64 data
  end
Loading

Related issues: None provided.

Related PRs: None provided.

Suggested labels: enhancement, testing, cdp-proxy

Suggested reviewers: None provided.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it does not follow the required template or include the explicit cross-platform review and security audit sections. Reformat it to the repo template and add Summary, Screenshots, Testing checklist, AI Review Report with macOS/Linux/Windows review, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes implement Page.printToPDF in the CDP proxy, including streamed ReturnAsStream handling and IO.read/IO.close support, matching #7032.
Out of Scope Changes check ✅ Passed The diff stays focused on PDF proxy support and its tests, with no obvious unrelated feature work or broad refactors.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding CDP Page.printToPDF support.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/main/browser/cdp-ws-proxy.test.ts (1)

386-400: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that IO.close actually invalidates the stream.

A no-op close would still pass this test. Add a read-after-close expectation for an error response to lock in cleanup behavior.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3e2ca505-6435-46f8-adbc-b057715c2308

📥 Commits

Reviewing files that changed from the base of the PR and between 8afa84a and 06a9a44.

📒 Files selected for processing (2)
  • src/main/browser/cdp-ws-proxy.test.ts
  • src/main/browser/cdp-ws-proxy.ts

Comment thread src/main/browser/cdp-ws-proxy.test.ts Resolved
Comment thread src/main/browser/cdp-ws-proxy.ts Resolved
Comment thread src/main/browser/cdp-ws-proxy.ts Resolved
Comment thread src/main/browser/cdp-ws-proxy.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/browser/cdp-ws-proxy.test.ts (1)

416-443: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Fixed sleep for disconnect-cleanup timing.

The test relies on a hardcoded setTimeout(resolve, 10) after client.close() to let disconnect cleanup run before asserting the stream is invalidated. On a loaded CI runner this could theoretically race if cleanup takes longer than 10ms, causing an intermittent false failure/pass.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6457539c-6d84-4f7c-ba42-90b2c1295574

📥 Commits

Reviewing files that changed from the base of the PR and between 06a9a44 and fc9550e.

📒 Files selected for processing (2)
  • src/main/browser/cdp-ws-proxy.test.ts
  • src/main/browser/cdp-ws-proxy.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/browser/cdp-ws-proxy.ts

AvichalDwivedi2205 and others added 4 commits July 3, 2026 15:06
…dp-print-to-pdf

Move the CDP Page.printToPDF option translation and the ReturnAsStream handle
store out of cdp-ws-proxy into a focused cdp-print-to-pdf module, mirroring the
existing cdp-screenshot sibling. Keeps the over-budget proxy from growing
further and gives the PDF logic direct unit coverage.

No behavior change: all existing proxy tests pass unmodified.

Co-authored-by: Orca <[email protected]>
A ReturnAsStream print that resolved after the requesting client
disconnected (or was replaced) registered its buffer in pdfStreams after
the disconnect's clear() already ran, orphaning a potentially large PDF
until the 5-minute TTL. Re-check isActiveClient after the await, mirroring
navigateWithLifecycle/reloadWithLifecycle.

Co-authored-by: Orca <[email protected]>
@nwparker

nwparker commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Maintainer takeover + verification

Adopted and finished this PR (thanks @AvichalDwivedi2205). Summary of what was validated and changed:

Security screen (CLEAN). This touches the CDP proxy layer, so I checked it against the PR #5035 auth hardening. No CDP auth is weakened, no new listening surface (server still binds 127.0.0.1:0), no new unauthenticated endpoints. PDF bytes never touch the filesystem — they go straight to the requesting websocket client as base64; there is no save path, so no path traversal. Stream handles carry a per-instance random UUID prefix, so a client cannot forge one or collide with a real Chromium IO stream. No dep/CI/postinstall changes.

Validity (CONFIRMED). Page.printToPDF really is unsupported on origin/main for webview guests (issue #7032). It does not duplicate the orca pdf CLI — that path bypasses the proxy with its own native call; this fills the gap for external CDP clients (Playwright page.pdf()).

Verified end-to-end. Drove the real CdpWsProxy against a real Electron webContents over a real websocket: both the direct-base64 and Playwright-style ReturnAsStream + IO.read/IO.close paths return byte-identical, valid single-page %PDF- documents (19544 bytes). Read-after-close is rejected. 46 unit tests pass, typecheck + lint clean.

Polish on top of the original: extracted the mapping + stream store into a focused cdp-print-to-pdf.ts module (mirrors cdp-screenshot.ts), and fixed a memory-retention race where a print resolving after client disconnect orphaned its buffer until the TTL (now re-checks isActiveClient after the await, with a teeth-verified regression test).

Full before/after evidence and trade-offs are in the updated PR description. Not merging — leaving that to a human reviewer.

@nwparker
nwparker merged commit 273fee7 into stablyai:main Jul 3, 2026
@nwparker

nwparker commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Merged — this passed our review bar. @AvichalDwivedi2205 thanks for the contribution! We verified it end-to-end (real websocket client, byte-valid PDFs in both direct and ReturnAsStream modes), confirmed it doesn't weaken the CDP proxy auth, extracted the PDF mapping into a focused module, and fixed a post-disconnect buffer-retention race before merging.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/browser/cdp-print-to-pdf.ts (1)

97-177: 🚀 Performance & Scalability | 🔵 Trivial

Consider a cap on concurrent buffered PDF streams.

create() has no upper bound on the number of in-flight buffers; a client that issues many ReturnAsStream prints without reading/closing them can accumulate large PDFs in memory for up to the 5-minute TTL. Given this proxy serves a single trusted local client, this is a narrow risk, but worth a note for future hardening (e.g., a max total buffered bytes/streams check in create()).


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2625ff40-f40c-4abd-8812-44501fd43636

📥 Commits

Reviewing files that changed from the base of the PR and between 277be39 and 89ee9fc.

📒 Files selected for processing (4)
  • src/main/browser/cdp-print-to-pdf.test.ts
  • src/main/browser/cdp-print-to-pdf.ts
  • src/main/browser/cdp-ws-proxy.test.ts
  • src/main/browser/cdp-ws-proxy.ts

@AvichalDwivedi2205

Copy link
Copy Markdown
Contributor Author

Thanks @nwparker appreciate the detailed review and the extra hardening before merge. Glad I could help fix #7032!

@AvichalDwivedi2205
AvichalDwivedi2205 deleted the fix/cdp-print-to-pdf branch July 3, 2026 21:09
@nwparker

nwparker commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Thank you, @AvichalDwivedi2205. Solid work wiring up Page.printToPDF for external CDP clients so Playwright's page.pdf() just works against Orca, and I like that you modeled it on the existing screenshot handler. Really appreciate the contribution — merged!

@nwparker

nwparker commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Thank you, Avichal! 🙏 printToPDF over CDP is genuinely useful for anyone driving the built-in browser with Playwright, and you mirrored the existing screenshot handler so cleanly it slotted right in. Great contribution — thanks for making it. 🐋

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* Fix CDP printToPDF proxy

* Harden CDP PDF stream handling

* Fix PDF margin units

* refactor(cdp): extract printToPDF param mapping + stream store into cdp-print-to-pdf

Move the CDP Page.printToPDF option translation and the ReturnAsStream handle
store out of cdp-ws-proxy into a focused cdp-print-to-pdf module, mirroring the
existing cdp-screenshot sibling. Keeps the over-budget proxy from growing
further and gives the PDF logic direct unit coverage.

No behavior change: all existing proxy tests pass unmodified.

Co-authored-by: Orca <[email protected]>

* fix(cdp): drop print result if client disconnected during printToPDF

A ReturnAsStream print that resolved after the requesting client
disconnected (or was replaced) registered its buffer in pdfStreams after
the disconnect's clear() already ran, orphaning a potentially large PDF
until the 5-minute TTL. Re-check isActiveClient after the await, mirroring
navigateWithLifecycle/reloadWithLifecycle.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Neil <[email protected]>
Co-authored-by: Orca <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CDP proxy: Page.printToPDF is not implemented

3 participants