Repository navigation
feat(browser): reuse admitted browser-socket transport and allow discovery_timeout_ms - #9203
Conversation
[Medium impact] The PR appears safe to merge; no new blocking issue was found. SummaryThe PR retains healthy browser sockets across passive calls and adds optional
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Passive browser call] --> B[Normalize endpoint URL]
B --> C{Healthy socket available?}
C -->|Yes| D[Lease shared socket]
C -->|No| E[Share one pending handshake]
E --> D
D --> F[Discover and authorize target]
F --> G[Attach separate target session]
G --> H[Run operation]
H --> I{Detach confirmed?}
I -->|Yes| J[Release lease and retain socket]
I -->|No| K[Evict and close socket]
J --> L[Provider shutdown closes retained sockets]
Reviews (10) · Last reviewed commit: "test(browser): verify distinct browser s..." · Reviewed by Greptile |
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
…nd join before mock restore
There was a problem hiding this comment.
TL;DR: This is a code read. I ran nothing from the PR, and CI has not run on this head yet. The socket cleanup fixes look right to me. The rebase needs one extra change, and I have one design question about shared sockets.
Edit (7 Nov): I ran this PR at head 3abe2e1 in a VM, and the results are here.
I read the PR head 0494d14 against its merge base 48f5f30. Main is now 99db80a.
Worth a look
-
The rebase needs the new decimal wrapper. The conflict is with 99db80a (#9178), which touched the same three files:
src/cli/browserAdvancedCommands.ts,src/cli/browserCommands.tsandsrc/cliObservationOptions.ts. That commit wraps every number option incliDecimalField, so0x10and1e3are refused. The newdiscoveryTimeoutMs: browserDiscoveryTimeoutSchema(headcliObservationOptions.tsline 46) has no wrapper. Its schema is a plainz.number()fromoptionalBrowserDeadlineMs(mainbrowserDeadline.tslines 21 to 28). Main'stests/boundary/cli/cliDecimalArguments.test.tschecks the number options of every registered command (line 78). So I expect it to flag--discovery-timeout-msafter the rebase. Main's own line is the model:commandTimeoutMs: cliDecimalField(webRuntimeCommandTimeoutSchema)(maincliObservationOptions.tsline 25). -
One call's failure closes the socket for everyone.
evictBrowserSocketpasses a cleanup that returns false (CdpTargetSessionOwner.tsline 227). ThenreleaseBrowserSocketcloses the socket at once, even while other calls hold it (lines 196 to 209). Eviction runs when discovery fails on a reused socket (CdpTargetSession.tslines 134 to 141, thenfailCdpOpenAfterCleanupat line 219). It also runs after an attach attempt (CdpBrowserProvider.tslines 499 to 501). Closing is the safe move when attach state is unknown. But a discovery timeout is different. One caller's shortdiscovery_timeout_msthen ends every call on that browser. Is that on purpose? If so, a line in the tool text would help.
Nit
- Two calls that start together each open their own socket.
acquireBrowserSocketdoes not share a connect that is still in flight (lines 88 to 125), andadmitBrowserSocketthen evicts the second socket (lines 142 to 154). So a cold start with parallel calls still shows two Chrome prompts. A pending connect per URL would avoid that.
Looks good
- Failed cleanup blocks new calls.
acquireBrowserSocketretries pending failures first (line 82). It reuses a socket only whenfailureis unset (line 93). - A detach that fails closes the socket.
releaseBrowserSocketkeeps the socket only when the cleanup returns true, and closes it otherwise (lines 188 to 209). - Events stay apart. Each passive tool's listener skips events from any other session. See
CdpPageCapture.tsline 83,CdpScreenshot.tsline 101,CdpWebMcpDiscovery.tsline 100 andCdpObservationSession.tsline 115. So a shared socket does not mix their events. - Defaults hold. If
discovery_timeout_msis left out, it stays out of Evidence parameters (BrowserEvidence.tsline 168). So old calls keep their evidence ids. - Reuse is opt-in. Only two call sites pass
reuseBrowserSocket: true(CdpBrowserProvider.tslines 153 and 434).
Not run
- No build, no typecheck, no tests. The decimal test result after the rebase is my reading of the code, not a run.
- I did not check how the reuse key is normalized, so I can't say whether
127.0.0.1and[::1]spellings of one browser share a socket. - I did not test against a real Chrome 136+ consent prompt.
🤖 Written with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊
…cket-reuse-and-deadline # Conflicts: # src/cli/browserAdvancedCommands.ts # src/cliObservationOptions.ts
…te fake CDP sessions
…rent session test
|
TL;DR: At 3abe2e1, all three points from my review above look addressed. The 7 test files pass on Node 22, 24 and 26. CI has not run on this head yet. Edit (7 Nov): I ran this PR again at head 96685a1 in a VM, and the results are here. They cover the reuse-key spelling; a real Chrome 136+ and a merge with the current main are still not run. Thanks, saariuslystoned, for all three of the fixes you made. Results
Six files are the PR's changed tests. The seventh is main's Nothing listens on port 9. So 16 got past argument parsing and failed at the connection. That is expected. My three points
Not run
Test setupCommands
The scratch script exited 0. The three 🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊 |
|
TL;DR: At 96685a1, the 8 test files I ran pass on Node 22, 24 and 26 (92 tests each). The decimal fix survived your merge of main (21feb95). A socket URL with no port is refused. A scratch probe shows two different socket ids stay two sockets. But no test in the PR checks that. Still not run: a real Chrome, and a merge with the current main. Edit (8 Nov): I ran the new head, 69f6099, in a VM, and the results are here. Results
Seven files are the PR's changed tests. The eighth is main's Only Greptile Review and Validate author declaration ran on this head. No test workflow ran, so these runs are the test results for it. What I checked since my review above
Still not run
Test setupCommands
The eight files: 🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊 |
|
TL;DR: I ran head 69f6099 in a VM, and the PR's 7 changed test files pass on Node 22, 24 and 26. A new test covers the gap from my review above: two different socket ids now stay two sockets. The new test is
The file CI on 69f6099: CI, Not run
Test setupCommandsnpm ci --offline
npm run test:prepare
xvfb-run -a npm run test:focused -- src/domain/browserObservation.test.ts src/domain/webDeadlineControls.test.ts tests/boundary/browser/cdpBrowserProvider.browserSocket.test.ts tests/boundary/browser/cdpTargetDeadlines.test.ts tests/boundary/browser/cdpTargetSessionOwner.test.ts tests/boundary/browser/webDeadlineBehavior.test.ts tests/boundary/mcp/browserMcp.test.ts🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊 |
Summary
Reuse an admitted, healthy loopback browser-socket CDP transport (
ws://127.0.0.1:<port>/devtools/browser/<id>/ws://[::1]:<port>/devtools/browser/<id>) across passive browser operations on the sameCdpBrowserProviderinstance, and add optional per-calldiscovery_timeout_ms(--discovery-timeout-ms, default10000ms) across the six passive browser tools so operators have configurable headroom when approving browser-level consent prompts.Problem and expected behavior
On Chrome 136+ using
chrome://inspect/#remote-debugging(DevToolsActivePort) without/json/versionHTTP discovery:list_browser_targets,inspect_web_page,analyze_web_bundle,observe_web_session,discover_webmcp_tools,capture_web_screenshot) previously opened a brand-new WebSocket connection tows://127.0.0.1:<port>/devtools/browser/<id>and closed it when that single call finished. In Chrome 136+, each new browser-level WebSocket upgrade triggers a fresh modal"Allow remote debugging?"consent prompt, turning a multi-step MCP session into repeated modal prompts.CDP_DISCOVERY_RESPONSE_TIMEOUT_MS = 10_000), so human operators reading and approving Chrome's modal consent dialog could exceed the discovery deadline with no caller parameter to extend it.Expected behavior:
CdpBrowserProvider(such as an active MCP server session), once a directbrowser_websocketendpoint completes handshake and discovery (Browser.getVersion,Target.getTargets), retain and reuse that healthy browser WebSocket keyed by exact normalized URL across subsequent calls.Target.detachFromTargeton completion, evicting and closing the shared browser socket if detachment is unconfirmed or the transport drops/fails, and deterministically closing retained sockets onCdpBrowserProvider.close().discovery_timeout_ms(1..2147483647, default10000when omitted) on the six passive browser tools and CLI commands, record explicit selections in Evidenceparameterswhile keeping omitted defaults absent, and namediscovery_timeout_ms/--discovery-timeout-msin timeout recovery only on operations that accept it.Change and scope
Follow the contribution scope.
CdpConnection,CdpTargetSessionOwner,CdpTargetSession,CdpBrowserProvider):CdpConnectionover an internalCdpTransportCorewithwithOperation(operation, commandTimeoutMs)so sequential or concurrent operations sharing one browser WebSocket isolate their operation identity,command_timeout_ms, and pending command tracking while sharingtransportRootcleanup ownership.acquireBrowserSocket,admitBrowserSocket,releaseBrowserSocket, andevictBrowserSocketonCdpTargetSessionOwner, coalescing concurrent cold-startacquireBrowserSocketcalls on the same normalized URL onto one shared in-flight WebSocket handshake (aborting the handshake only if all waiting callers abort). Retain only directbrowser_websocketendpoints that complete discovery; keep HTTP/json/version(http_discovery) per-call open/close behavior unchanged, and keepPlaywrightScenarioServiceWorkerssingle-shot ownership unchanged.cleanupCdpTargetCommands: ifTarget.detachFromTargetfails (other than an already-detached session rejection) or times out, or ifTarget.attachToTargetfails after being sent, immediately evict and close the browser WebSocket (even when a concurrent operation holds a shared lease) so transport close remains the definitive target-session boundary, whereas a caller's own pre-attach discovery deadline or cancellation releases only its lease when transport state remains clean; also evict/close idle retained sockets on fatal protocol errors as well as disconnects.browserDeadline.ts, passive browser schemas, CLI,CdpEndpoint.ts,BrowserEvidence.ts,docs/guides/web/browser-observation.md):browserDiscoveryTimeoutSchema,selectedCdpDiscoveryTimeoutMs,cdpDiscoveryTimeoutIsSelectable, andcdpDiscoveryTimeoutRecoveryinsrc/domain/browserDeadline.ts(wrapped withcliDecimalFieldon CLI--discovery-timeout-ms), keepingCDP_DISCOVERY_RESPONSE_TIMEOUT_MS = 10_000as the default and clamping handshake timer headroom atMAX_BROWSER_DEADLINE_MS(2147483647) so maximum deadlines never overflow Node's 32-bit timer range.discovery_timeout_ms/--discovery-timeout-msthroughlist_browser_targets,inspect_web_page,analyze_web_bundle,observe_web_session,discover_webmcp_tools, andcapture_web_screenshot, without advertisingdiscovery_timeout_mson non-passive CDP callers (observe_web_execution,inspect_web_event_listeners, Electron, or scenario capture).Contract and boundary impact
src/domain/browserDeadline.tsand passive browser input schemas (src/domain/browserObservation.ts,src/domain/browserSession.ts,src/domain/webMcpDiscovery.ts,src/domain/webScreenshot.ts) owndiscovery_timeout_ms;src/browser/CdpTargetSessionOwner.ts,src/browser/CdpTargetSession.ts,src/browser/CdpConnection.ts, andsrc/browser/CdpBrowserProvider.tsown browser-socket transport retention, per-call operation scoping, detachment verification, and provider shutdown cleanup.CdpBrowserProviderboundary; no new target execution, injection, or mutation).list_browser_targets,inspect_web_page,analyze_web_bundle,observe_web_session,discover_webmcp_tools, andcapture_web_screenshotaccept optionaldiscovery_timeout_ms(1..2147483647, omitted default10000); corresponding CLI commands accept--discovery-timeout-ms. Both default and compact MCP input schema profiles remain within budget.browser_websocketendpoints reuse an admitted socket across calls on the sameCdpBrowserProviderinstance;http_discoveryendpoints and direct page sockets retain existing per-call connection behavior. One-shot CLI invocations close their provider at command exit.createBrowserEvidencerecordsdiscovery_timeout_msinparametersonly when explicitly supplied and omits it when left at the default; browser-socket URLs remain redacted asws://127.0.0.1:<port>/devtools/browser/[REDACTED].sessionIdattachment/detachment run on every call; unconfirmedTarget.detachFromTargetor failedTarget.attachToTargetevicts and closes the browser WebSocket;CdpBrowserProvider.close()closes retained idle sockets after active operations settle and preservesAnalysisCleanupLeaseretry semantics.docs/public/product-catalog.json), package, or installation impact: none committed;npm run metadata:check,npm run mcp-catalog:check, andnpm run docs:checkpass cleanly.Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.
Evidence and regression coverage
tests/boundary/browser/cdpBrowserProvider.browserSocket.test.tsandsrc/domain/browserObservation.test.ts: verify sequentiallistTargets->inspectPage->captureScreenshotoverws://127.0.0.1:<port>/devtools/browser/fakeperform a single WebSocket upgrade (openedConnectionCount === 1), normalize scheme case, uncompressed IPv6 loopback spellings, and leading port zeros onto one reuse key while keeping127.0.0.1and[::1]separate sockets, coalesce concurrent cold-start calls onto a single WebSocket handshake (keeping the handshake alive for longer-deadline peers when a short-deadline waiter times out), keep an admitted shared socket alive for concurrent peers when one caller hitsdiscovery_timeout_msor cancels during pre-attach discovery, sendTarget.detachFromTargetper target call, retain the socket across missing-target authorization errors, evict and reconnect cleanly when the server drops or sends malformed protocol frames on an idle browser socket (preserving pending cleanup lease failure if close fails), immediately close the shared socket whenTarget.detachFromTargetfails even alongside a concurrent activeobserveSession(or surfacecleanupIncompletebound to the socket lease if forced close fails), retainAnalysisCleanupLeaseownership onfinish()callback rejection, preserve per-callcommand_timeout_msand operation identity afterlist_browser_targets, and release the socket onprovider.close().tests/boundary/browser/cdpTargetDeadlines.test.ts: verifies customdiscovery_timeout_msgoverns both browser-socket discovery (Target.getTargetsstall) and HTTP discovery (/json/versionstall) independently ofcommand_timeout_ms, clamps handshake timers atMAX_BROWSER_DEADLINE_MS(2147483647) without 32-bit timer overflow, and projectsprovider_timeoutwith--discovery-timeout-msremediation.src/domain/webDeadlineControls.test.tsandtests/boundary/browser/webDeadlineBehavior.test.ts: verify schema bounds (1..2147483647), selectable vs non-selectable discovery timeout remediation text, and explicit-only Evidenceparameters.discovery_timeout_msrecording.tests/boundary/mcp/browserMcp.test.ts: verifies end-to-end MCPlist_browser_targets(withdiscovery_timeout_ms) followed byinspect_web_pageover a browser WebSocket reuses one WebSocket connection across bothfullandcompactMCP profiles while redacting the socket path.FakeCdpBrowserHTTP/WebSocket fixture (openedConnectionCount()previously incremented per call onbrowserWebSocketUrl, andlistBrowserTargetsInputSchemarejecteddiscovery_timeout_ms).CDP browser-socket discovery exceeded its <N> ms discovery_timeout_ms deadline (deadlineExpired)(orCDP discovery response exceeded...) with remediation namingdiscovery_timeout_msand--discovery-timeout-ms, while keeping byte budgets explicitly marked as having no runtime override.Google Chrome 156.0.8078.80DevToolsActivePortsingle-TCP-socket reuse across sequential MCP operations (lsof-confirmed); manual desktop GUI interaction with Chrome's headed"Allow remote debugging?"modal dialog remains human UI verification.For evidence-bearing changes:
Validation performed
npx vitest run src/browser/*.test.ts src/domain/webDeadlineControls.test.ts tests/boundary/browser/*.test.ts tests/boundary/mcp/browserMcp.test.ts tests/boundary/mcp/compactInputSchemaMcp.test.ts tests/boundary/mcp/webBundleContainmentMcp.test.ts tests/boundary/cli/browserCli.test.ts— passed (136 passed | 1 skippedtest files,2281 passed | 6 skippedtests).npx vitest run tests/boundary/browser/cdpBrowserProvider.browserSocket.test.ts tests/boundary/browser/cdpTargetSessionOwner.test.ts— passed (20 passed+7 passed=27 passedtests, including distinct per-attachmentsessionIdisolation andunhandledRejection-free cold-handshake cleanup failure handling).npx vitest run tests/boundary/cli/cliDecimalArguments.test.ts— passed (1 passedtest across all registered CLI numeric options).npx vitest run tests/boundary/browser/cdpTargetDeadlines.test.ts— passed (25 passedtests).npm run check:fast— passed (typecheckandlintsucceeded,0errors).npx oxfmt . && npx oxfmt --check .— passed (All matched files use the correct format).npm run verify:architecture-guards— passed (Architecture guards passed across 2519 source files).npm run verify:test-discovery— passed (Discovered all 3157 test files exactly once).npm run scan:todos— passed (No tech-debt markers found).npm run jscpd— passed (0threshold violations).npm run knip && npm run knip:production— passed (Knip found no issues).npm run lint:typed— passed (6585 files, 0 errors).npm run metadata:check && npm run mcp-catalog:check && npm run docs:check— passed (6/6tasks +tests/conformance/readmeConsistency.test.ts9/9passed).main(08637b0c2) + multi-Node matrix (v22.23.4,v24.22.2,v26.13.0): clean merge (0conflicts),npm run check:fastpassed, and all8changed/focused test files (93/93tests) passed across Nodev22.23.4,v24.22.2, andv26.13.0.Google Chrome 156.0.8078.80DevToolsActivePort+rea mcpsocket-reuse verification (v24.22.2): sequentiallist_browser_targets->inspect_web_page(WS://127.0.0.1:052525/...normalized) ->capture_web_screenshot(discovery_timeout_ms: 15000) ->update_analysis_settings->list_browser_targetsreused a single OS TCP connection (lsof-verified), confirmed per-call target detachment (attached: false), and redacted the browser socket path ([REDACTED]).Compatibility, safety, and release
discovery_timeout_msis optional and defaults to the existing10000ms deadline; callers ofCdpBrowserProvidercontinue to callawait provider.close()as already required for bundle-analyzer and transport cleanup.v22.23.4,v24.22.2, andv26.13.0against wire-level loopback fixtures and liveGoogle Chrome 156.0.8078.80(--remote-debugging-port=0DevToolsActivePortbrowser WebSocket); headed desktop modal consent click remains manual UI verification.metadata:check,mcp-catalog:check, anddocs:checkpass without tracked metadata diffs).[REDACTED]), origin authorization runs per operation, fixed 8 MiB HTTP discovery and 64 MiB WebSocket message byte caps remain non-overridable, and unconfirmed session detachment closes REA's WebSocket rather than reusing an ambiguous session state.Author readiness
Human owner: @saariuslystoned
Before merge
type(scope): outcome.