fix(browser): auto-connect provisioned sessions

Closed
MA
4mo ago
+276-17

Summary

  • auto-connect a disconnected process-scoped Session before browser_execute runs a snippet when BU_CDP_WS or BU_CDP_URL is configured
  • deduplicate concurrent first calls with one per-Session in-flight connection promise
  • preserve explicit-connect behavior when neither provisioned endpoint variable is present
  • propagate the original connection failure instead of wrapping it as a snippet exception

Why

V4 provisions the browser and sets BU_CDP_WS, but a fresh worker still begins with a disconnected in-process Session. In a recent ordered production cohort, all 28 exact Not connected. Call session.connect(...) first. snippets reached CDP before executing a connection; 26/28 later recovered with successful browser calls. Initialization should be deterministic instead of model-dependent.

Semantics and tradeoffs

  • auto-connect runs only at the tool-call boundary; a snippet that closes its socket mid-execution still controls and must perform any same-snippet reconnect itself
  • an already-connected explicit replacement endpoint is left untouched
  • after an explicit close, a later tool call reconnects the fixed provisioned endpoint unless the snippet explicitly reconnects first within the same call
  • an expired or rejected provisioned endpoint is not retried or replaced here; its real WebSocket/endpoint error is returned
  • without BU_CDP_WS/BU_CDP_URL, local BrowserCode behavior is unchanged

Tests

  • first raw CDP snippet auto-connects and subsequent snippets reuse one socket
  • both BU_CDP_WS and BU_CDP_URL trigger the behavior
  • parallel first calls share one connection attempt
  • explicit close plus explicit reconnect remains under snippet control
  • non-cloud sessions still fail raw CDP until explicitly connected
  • failed auto-connect surfaces the original connection error and never runs the snippet

Validation:

  • cd packages/bcode-browser && bun typecheck
  • cd packages/bcode-browser && bun test — 23 passed, 8 live/smoke tests skipped, 0 failed
  • root filtered bun run typecheck — 16 packages passed
  • targeted oxlint — 0 errors; 5 pre-existing warnings in browser-execute.ts

Summary by cubic

Auto-connects provisioned cloud sessions in browser_execute when BU_CDP_WS or BU_CDP_URL is set, eliminating "Not connected" errors. Deduplicates concurrent first connections, keeps local sessions explicit-connect, and returns the original connect error on failure.

  • Bug Fixes
    • Connect the process-scoped Session before a snippet runs when a provisioned endpoint is present; reuse one socket across calls.
    • Share one in-flight connect per Session to avoid race conditions.
    • Leave already-connected or local sessions unchanged; do not retry or mask endpoint errors.