Skip to content

refactor(browser): send only CDP commands with registered result schemas - #10666

Merged
morluto merged 6 commits into
mainfrom
refactor/typed-cdp-final-commands
Nov 15, 2026
Merged

morluto merged 6 commits into
mainfrom
refactor/typed-cdp-final-commands

Conversation

@morluto

@morluto morluto commented Nov 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Last slice of typed CDP command replies, stacked on #10657 (base branch refactor/typed-cdp-optional-malformed; retarget as the stack below merges).

  • Registers result schemas for the last four commands REA sends: Target.getTargets, Browser.getVersion, Runtime.evaluate and Target.sendMessageToTarget. The untyped-command count is now 0.
  • CdpConnection.send, admitCdpReply, optionalCdpCommand, the runtime session, the scenario storage and service-worker senders, and the fakeCdpSend fixture now accept only CdpCommand. A command without a registered schema does not compile. The CdpSendParams/CdpSendResult fallbacks for unregistered names are removed.
  • Playwright CDP sessions are opened only through newPlaywrightCdpSession (src/browser/PlaywrightCdpSession.ts), whose send accepts only CdpCommand and admits each reply with its schema, like CdpConnection.send. PlaywrightScenarioBrowser (target discovery and the attached-environment owner) and PlaywrightScenarioStorage now hold this session instead of Playwright's CDPSession; the storage root and nested transports each admit their own replies once. A new lint rule, rea/no-raw-cdp-session, rejects newCDPSession/newBrowserCDPSession in src/** production files other than the owner (tests and scripts/ e2e harnesses are exempt). This replaces the repository-wide coverage the deleted text guard gave for direct Playwright sends.
  • Deletes the text-matching guard (CdpCommands.guard.test.ts) and its JSON baseline; the compiler now enforces what it counted.
  • Adds CdpCommands.types.test.ts, which npm run typecheck compiles as a negative test. It uses @ts-expect-error on sending an unregistered command, plus expectTypeOf checks for CdpDomainWith<verb> and the parsed result type. If either check stops holding, the typecheck fails.

Refs #4330

Problem and expected behavior

  • Browser-socket discovery read Target.getTargets through recordValue(...)?.targetInfos and validated Browser.getVersion with a local schema. Now both replies are parsed at the transport. A malformed reply is translated to invalid_endpoint_response (detail: "CDP returned a malformed result at : ..."), so HTTP and browser-socket discovery give the same answer to the same question. Target rows are still admitted one by one by parseCdpDiscoveryTargets.
  • Worker inventories (page and Electron): a malformed Target.getTargets reply is still an invalid_protocol_value gap with count: null; "method not found" is still unavailable. Both now come from the typed optionalCdpCommand outcome instead of re-reading the raw reply.
  • Service-worker policy restoration (Runtime.evaluate): a reply whose value is neither null nor "policy_owned" used to throw a raw ZodError. It now fails as BrowserObservationError protocol_error, matching the Playwright-frame restoration path beside it. A thrown evaluation has no value, so it takes the same path.

Change and scope

User-visible changes:

  1. Browser-socket discovery: a malformed Browser.getVersion or Target.getTargets reply is still invalid_endpoint_response. Its detail now names the command and the JSON pointer.
  2. capture_browser_scenario cleanup: an unexpected restoration result is protocol_error instead of an untyped ZodError.
  3. capture_browser_scenario attached environment: a non-object reply to an Emulation.* override or reset is now protocol_error (it was ignored).

Transport tests rewritten: cdpConnection.test.ts used Runtime.evaluate as the example of an unregistered command that returns raw replies. Correlation of concurrent replies, invalid UTF-8 rejection and payload budgets now use Storage.getStorageKey, a registered command whose storageKey string carries the test payload. The correlation test now also asserts each command's parameters. The "unmodeled fake command" rejection tests use Storage.getStorageKey, which the fake browser does not model, instead of a made-up method name.

Not included: CDP event payload schemas (next W11 slice) and the page-generation/target_changed owner. Electron capture isolation is unchanged (D7 pending).

Contribution scope: ordinary refactor within existing boundaries. It follows the approved W11 decisions: malformed protocol data is protocol_error at the CDP boundary, and endpoint discovery keeps invalid_endpoint_response on both paths.

Contract and boundary impact

  • Semantic owner and earliest changed stage: CdpCommands.ts (the reply table is now also the set of sendable commands). Consumers: CdpEndpoint, CdpPageCaptureWorkers, CdpElectronWorkers, PlaywrightScenarioServiceWorkers, PlaywrightScenarioStorage, CdpRuntimeSession, CdpConnection, CdpOptionalCommand.
  • Contribution scope fit and linked maintainer decision: W11 decisions above.
  • CLI and MCP/tool-catalog contract: no schema change; error detail and classification as listed.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: none.
  • Target selection, authority, upstream behavior, and cleanup details: commands, parameters and order on the wire are unchanged.
  • Generated metadata, package, or installation impact: none.

Expected effects: none checked; no change to what REA does to a target.

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • New: CdpEndpoint.test.ts, a malformed browser-socket Browser.getVersion is invalid_endpoint_response with a detail naming the command. New: CdpCommands.types.test.ts (compile-time).
  • Base reproduction: with this PR's CdpEndpoint.ts change reverted (other changes kept), 8 CdpEndpoint.test.ts cases failed (the 7 existing malformed-target-list cases and the new version case reported protocol_error), 14 passed.
  • Negative type test checked: changing the unregistered name in the type test to "Runtime.enable" made tsc fail with TS2578 ("Unused '@ts-expect-error' directive") and the not.toExtend assertion (reverted).
  • CdpPageCaptureWorkers.test.ts now admits replies through fakeCdpSend, as the real connection does.
  • Remaining proof gaps: no real Chrome/Electron run. The service-worker restoration change has no dedicated test; its fake-browser coverage would need a scenario-browser fixture.

Validation performed

  • npx tsc -p tsconfig.json --noEmit: passed.

  • npm run check:fast: passed.

  • npm run test:local -- <55 src/browser test files>: 1048 passed, 2 failed (CdpPageCaptureWorkers.test.ts fake bypassed admission). After fixing the fake, npm run test:local -- CdpPageCaptureWorkers.test, CdpEndpoint.test, CdpDiscoveryTargets.test, CdpCommands.types.test: 58 passed. CdpEndpoint.test: 22 passed after adding the version case.

  • npm run test:focused -- cdpConnection, cdpTargetDeadlines, cdpBrowserProvider.browserSocket, cdpBrowserProvider.targetInventory, cdpWorkerAttachmentProtocol, cdpElectronProvider: 171 passed.

  • Base reproduction and negative type check as above.

  • Pre-commit and pre-push hooks ran normally.

  • Greptile follow-up (direct Playwright sends): npm run typecheck: passed. npx oxlint src reports no no-raw-cdp-session finding. npm run test:local -- PlaywrightScenarioBrowser.test, PlaywrightScenarioStorage.test, CdpCommands.types.test: 67 passed (the attached-environment fake now acknowledges Emulation commands with {} as Chromium does; one-argument clearDeviceMetricsOverride assertions now match the forwarded undefined params). npm run test:focused -- tests/evaluation/noRawCdpSessionRule.test.ts: 7 passed. npm run test:focused -- <10 tests/boundary/browser files>: 404 passed.

  • Rebased onto the current stack after refactor(browser): register target, storage and acknowledgement CDP replies #10630/fix(browser): report malformed script source and coverage replies as protocol errors #10638 merged; pushed with --no-verify (typecheck, oxlint and the tests above were run by hand).

  • Greptile follow-up (override restore obligation, d614d04): the new PlaywrightScenarioBrowser.test.ts case for a malformed success reply failed on the previous head and passes now; npm run test:local -- src/browser/PlaywrightScenarioBrowser.test.ts: 45 passed; npm run check:fast: passed.

  • Codex follow-up (JavaScript verifier commands, 9244f80): npm run test:focused -- tests/evaluation/verifierCdpCommands.test.ts tests/boundary/browser/cdpConnection.test.ts: 33 passed; npm run check:fast: passed. Real-browser verifiers not run. Child branches were rebased onto this commit; their pushes used --no-verify after npm run check:fast passed on the stack top.

  • Review follow-up (Target.closeTarget success, 6dc4280): npm run test:focused -- tests/evaluation/verifierCdpCommands.test.ts: 3 passed. Stack rebased onto main after fix(browser): record malformed optional CDP replies as section gaps #10657 merged (conflict in scripts/verify/architecture-guards.mjs resolved by keeping main's wall-clock guard); npm run check:fast and node scripts/verify/architecture-guards.mjs passed on the stack top. Pushes ran the pre-push hook.

Compatibility, safety, and release

  • Breaking changes or migration steps: none for users. Internally, send no longer accepts unregistered names.
  • Real Hopper/Ghidra, browser, or OS coverage: none; fake CDP browser only, macOS.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no change to commands sent or their parameters.

Author readiness

Human owner:

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T05:48:42.769917Z 6dc4280 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: apex

[Medium impact] The PR appears safe to merge; no blocking issue was found.

Summary

This PR limits CDP senders to registered commands and checks replies at both transport boundaries.

  • CDP senders now accept only commands with registered reply schemas.
  • Browser discovery and worker inventories now use checked CDP replies.
  • Playwright CDP callers now use one session owner that checks replies.
  • Service-worker restoration now reports unexpected evaluation results as protocol errors.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  C["CdpConnection.send"] --> A["admitCdpReply"]
  P["PlaywrightCdpSession.send"] --> A
  A --> V{"Reply matches schema?"}
  V -->|Yes| R["Parsed reply"]
  V -->|No| E["CdpMalformedReply"]
  E --> D["Discovery: invalid_endpoint_response"]
  E --> O["Optional command: coverage gap"]
  E --> F["Required command: protocol_error"]
Loading

Reviews (6) · Last reviewed commit: "fix(browser): keep Target.closeTarget's ..." · Reviewed by Greptile

@morluto
morluto force-pushed the refactor/typed-cdp-optional-malformed branch from a2ec940 to 3098f02 Compare November 15, 2026 00:27
@morluto
morluto force-pushed the refactor/typed-cdp-final-commands branch from 51410c8 to cb69202 Compare November 15, 2026 00:27
@morluto

morluto commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

Greptile Issue 1 (direct Playwright sends escape checks): valid. Root cause: Playwright's CDPSession.send takes any protocol name, and PlaywrightScenarioBrowser/PlaywrightScenarioStorage held raw sessions, so the compile-time restriction covered only CdpConnection.send. Fix (cb69202): one owner, src/browser/PlaywrightCdpSession.ts, opens Playwright CDP sessions and exposes a send restricted to CdpCommand that admits each reply with its schema. Both Playwright files now hold that session (the storage root/nested transports admit once each). Guard: lint rule rea/no-raw-cdp-session rejects newCDPSession/newBrowserCDPSession in src/** production code other than the owner; CdpCommands.types.test.ts also asserts an unregistered command does not compile on the Playwright session. Validation: typecheck passed; npx oxlint src clean for the rule; Playwright scenario + types tests 67 passed; rule test 7 passed; 10 boundary browser files 404 passed. Remaining: scripts/lib/*-e2e.mjs harnesses still open raw sessions (test harnesses, out of src).

@morluto

morluto commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

@greptileai review — the earlier finding (direct Playwright sends) is addressed by cb69202; please re-score the current head.

Comment thread src/browser/PlaywrightCdpSession.ts Resolved
@morluto
morluto force-pushed the refactor/typed-cdp-optional-malformed branch from 3098f02 to 3f55dc4 Compare November 15, 2026 01:45
@morluto
morluto force-pushed the refactor/typed-cdp-final-commands branch from d614d04 to 37e5133 Compare November 15, 2026 01:45
@morluto
morluto force-pushed the refactor/typed-cdp-optional-malformed branch from 3f55dc4 to dc0e007 Compare November 15, 2026 02:20

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 487d1250a4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/browser/protocol/CdpCommands.ts Resolved
@morluto
morluto force-pushed the refactor/typed-cdp-final-commands branch from 487d125 to c31aed9 Compare November 15, 2026 02:21
Comment thread src/browser/protocol/CdpCommands.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9244f80f1f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/browser/protocol/CdpCommands.ts Resolved
Comment thread src/browser/protocol/CdpCommands.ts Resolved
@morluto
morluto changed the base branch from refactor/typed-cdp-optional-malformed to main November 15, 2026 05:42
…h a malformed reply

A schema-rejected success reply means the browser applied the Emulation
override, so the attached environment owner records the reset obligation
before reporting the protocol error. Only a rejected or unanswered command
leaves no obligation.
The verifier scripts send Browser.close, Page.createIsolatedWorld, Page.navigate, Page.reload, Target.activateTarget, Target.closeTarget and Target.createTarget through CdpConnection, which now admits every reply through its command's result schema. Register those schemas, refuse an unregistered run-time name as a typed malformed reply instead of a TypeError, and check script send literals against the registry.
@morluto
morluto force-pushed the refactor/typed-cdp-final-commands branch from 9244f80 to 6dc4280 Compare November 15, 2026 05:46
@morluto

morluto commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

Issue 1 (Target.closeTarget schema) is fixed in 6dc4280: z.object({ success: z.boolean() }), with tests/evaluation/verifierCdpCommands.test.ts asserting the members the verifiers read. @greptileai review

@morluto
morluto merged commit 254bb21 into main Nov 15, 2026
52 of 54 checks passed
@morluto
morluto deleted the refactor/typed-cdp-final-commands branch November 15, 2026 06:49
@morluto morluto added the area: cli CLI adapter and one-shot commands label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: cli CLI adapter and one-shot commands

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant