Skip to content

refactor(browser): stream proxy traffic over binary WebSockets - #55528

Closed
dbpolito wants to merge 3 commits into
anomalyco:devfrom
dbpolito:browser-websocket
Closed

dbpolito wants to merge 3 commits into
anomalyco:devfrom
dbpolito:browser-websocket

Conversation

@dbpolito

@dbpolito dbpolito commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Issue for this PR

No linked issue.

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

Tip

Over a remote connection with ~140 ms RTT, the 6 MiB image test went from ~70 s to ~4 s (roughly 18× faster, using rounded estimates). An uncached load of the OpenCode docs went from 3.91 s to 1.48 s (2.6× faster).

What does this PR do?

I was seeing very slow page loads in the desktop browser when connected to a remote server.

The proxy sends traffic through JSON RPC in chunks of up to 64 KiB, waiting for a response before sending or requesting more. That gets expensive over a high-latency connection, especially for images and JS bundles. The bytes also have to be Base64 encoded.

This replaces those calls with one binary WebSocket per TCP connection. A bounded sliding window controls buffering without waiting for a round trip after every chunk. Browser commands still use RPC.

Authentication, origin checks, attachment ownership, connection limits, and TCP half-close are preserved.

Warning

Desktop and server must be updated together. The old transport is removed, and reverse proxies must allow WebSocket upgrades.

How did you verify your code works?

I tested both versions from the same desktop against the same remote server, with about 140 ms round-trip latency.

The image test loads an uncompressed 6 MiB image with caching disabled:

Measurement Before After
Approximate image load time ~70 s ~4 s

Load times varied between runs. The ~4 s figure is a rounded estimate, not a calculated average.

I also tested an uncached load of https://opencode.ai/v2/docs, transferring approximately 130 KiB across 6 requests:

Measurement Before After
First byte 1.63 s 0.75 s
First visible content 2.31 s 1.08 s
Full page load 3.91 s 1.48 s

These page timings are individual uncached loads, not averaged results.

Tests cover transfers larger than the flow-control window, paused consumers, half-close, cancellation, malformed frames, authentication, and attachment ownership. Pre-push lint and typechecks pass. Four failures in the broader client tests also reproduce on the unchanged base.

To repeat the image test, save the script below as example.js on the remote machine, run node example.js, and open http://localhost:1337 in the desktop browser pane. Use matching desktop/server versions for each comparison.

The script runs five uncached loads and reports their average.

Reproduction script: example.js

No dependencies or supporting files are needed.

async function main() {
  const { createServer } = await import("node:http")
  const { randomFillSync } = await import("node:crypto")
  const port = Number(process.env.PORT || 1337)
  const image = Buffer.alloc(54 + 2048 * 1024 * 3)
  image.write("BM")
  image.writeUInt32LE(image.length, 2)
  image.writeUInt32LE(54, 10)
  image.writeUInt32LE(40, 14)
  image.writeInt32LE(2048, 18)
  image.writeInt32LE(1024, 22)
  image.writeUInt16LE(1, 26)
  image.writeUInt16LE(24, 28)
  image.writeUInt32LE(image.length - 54, 34)
  randomFillSync(image, 54)

  const html = Buffer.from(`<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Browser tunnel benchmark</title>
<style>
  :root { color-scheme: dark; font-family: system-ui, sans-serif; }
  body { max-width: 800px; margin: 40px auto; padding: 0 20px; }
  button { padding: 10px 16px; font: inherit; cursor: pointer; }
  #result { font-size: 24px; font-variant-numeric: tabular-nums; }
  img { display: block; width: 100%; margin-top: 24px; }
</style>
<h1>Browser tunnel benchmark</h1>
<p>Five uncached loads of a generated 6 MiB image. Run with each matching desktop/server
version against the same remote server. The timer ends at the image load event, not painting.</p>
<button id="start">Run five loads again</button>
<p id="result" role="status" aria-live="polite"></p>
<ol id="runs"></ol>
<img id="image" alt="Random pixels used to measure image loading">
<script>
  const button = document.querySelector("#start")
  const result = document.querySelector("#result")
  const runs = document.querySelector("#runs")
  const image = document.querySelector("#image")

  async function benchmark() {
    button.disabled = true
    runs.replaceChildren()
    const times = []
    for (let run = 1; run <= 5; run++) {
      result.textContent = "Loading " + run + "/5…"
      const started = performance.now()
      await new Promise((resolve, reject) => {
        image.onload = resolve
        image.onerror = () => reject(new Error("Image failed to load"))
        image.src = "/heavy.bmp?run=" + Date.now() + "-" + Math.random()
      })
      const seconds = (performance.now() - started) / 1000
      times.push(seconds)
      const item = document.createElement("li")
      item.textContent = seconds.toFixed(2) + " s"
      runs.append(item)
    }
    const average = times.reduce((sum, seconds) => sum + seconds, 0) / times.length
    result.textContent = "Average: " + average.toFixed(2) + " s over 5 loads"
    button.disabled = false
  }
  const start = () => benchmark().catch((error) => {
    result.textContent = error.message
    button.disabled = false
  })
  button.addEventListener("click", start)
  start()
</script>
</html>`)

  createServer((request, response) => {
    const path = new URL(request.url, "http://localhost").pathname
    const body = path === "/" ? html : path === "/heavy.bmp" ? image : undefined
    if (!body) {
      response.writeHead(404)
      response.end("Not found")
      return
    }
    response.writeHead(200, {
      "content-type": path === "/" ? "text/html; charset=utf-8" : "image/bmp",
      "content-length": body.length,
      "cache-control": "no-store",
    })
    response.end(body)
  }).listen(port, "127.0.0.1", () => {
    console.log("Browser benchmark: http://localhost:" + port)
  })
}

main().catch((error) => {
  console.error(error)
  process.exitCode = 1
})

Screenshots / recordings

Before:

Before: 6 MiB image loaded in 70.57 seconds

After:

After: browser tunnel image benchmark

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

Added by the opencode bot (AI-generated).

Public API: adds GET /api/rpc/:rpcID/:method/socket and websocket: true RPC methods; removes the experimental.browser tunnel.* RPC methods (desktop and server must match)

@github-actions

Copy link
Copy Markdown
Contributor

The following comment was made by an LLM, it may be inaccurate:

@dbpolito

dbpolito commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

@Hona could you take a look at this one?

@opencode-agent opencode-agent 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.

The transport change looks sound. I couldn't reproduce the speedup because it needs the Electron desktop app and a remote server. The new tests in plugin-browser, server and core pass, and all eight changed packages type-check.

I found no security regression on the new route. Origin, authentication, method and input are checked before the connection is upgraded, and the upgrade is lazy, so ownership checks and an unreachable target still fail as normal HTTP errors. The sliding window limits what the receiver buffers, half-close passes through pipe, and TCP errors end the tunnel through raceFirst.

Public API impact:

  • Added: HTTP endpoint GET /api/rpc/:rpcID/:method/socket (rpc.connect, marked x-websocket).
  • Added: optional websocket?: true on Rpc.Method in @opencode/schema/rpc; PortableMethod forbids it.
  • Changed: RpcCallContext in the plugin API goes from an interface to a conditional type and gains socket for websocket methods.
  • Added: connect on core Rpc.Interface.
  • Changed: typed RPC clients now skip websocket methods.
  • Removed: experimental.browser methods tunnel.open, tunnel.read, tunnel.write and tunnel.close, replaced by the websocket method tunnel. The attach/control version goes from 4 to 5.
  • Added: a rpc.connect method in the generated promise and effect clients (see the inline comment).

The additions are backwards compatible for existing plugins and SDK users. The browser plugin change is deliberately breaking: a desktop and server on different versions fail when attaching (schema mismatch on version). That seems acceptable for an experimental plugin, but reverse proxies now also have to allow WebSocket upgrades on this route.

Main concern: the generated SDK gets a rpc.connect that can't work (inline).

),
)
.add(
HttpApiEndpoint.get("rpc.connect", "/api/rpc/:rpcID/:method/socket", {

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.

This endpoint ends up in the generated clients: both packages/client/src/promise/generated/client.ts and packages/client/src/effect/generated/client.ts now expose rpc.connect as a plain GET with no upgrade, which can't work. pty.connect and persistentPty.connect avoid this through promiseOmitEndpoints / effectOmitEndpoints in packages/protocol/src/client.ts. Could you add rpc.connect there and regenerate, so the SDK doesn't ship a method that is broken?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in dbpolito@ecdcee961b: added rpc.connect to both omit lists and regenerated the clients. No replacement HTTP method or extra abstraction. Pre-push lint and all 36 typecheck tasks passed; 53 browser tests and the socket-route test passed. The broader client test files still report three failures outside this RPC surface.

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.

Thanks, I checked ecdcee961b. rpc.connect is now in both omit lists, and the regenerated promise and effect clients and RpcApi no longer expose the broken connect method. That resolves this thread. The only other new commit is a merge of dev, which doesn't touch the files this PR changes.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@lexuzieel

Copy link
Copy Markdown

hi, sorry for bumping this, but i also just stumbled upon this issue. any ETA or blockers? as it seems to involve both client and server upgrade

@dbpolito

Copy link
Copy Markdown
Contributor Author

maybe @Hona could take a look on this one?

i didn't look into the conflicts, not sure something changed on upstream regarding this, but i can definitely update this if we're moving forward with it.

@github-actions

Copy link
Copy Markdown
Contributor

Automated PR Cleanup

Thank you for contributing to opencode.

Due to the high volume of PRs from users and AI agents, we periodically close older PRs using automated criteria so maintainers can focus review time on the most active and community-supported contributions.

This PR was closed because it matched the following cleanup criteria:

  • The PR was created more than 1 month ago
  • The PR had fewer than 2 positive reactions
  • Positive reactions are counted as thumbs-up, heart, celebration, or rocket reactions on the PR

PRs created within the last month are not affected by this cleanup.

If you believe this PR was closed incorrectly, or if you are still actively working on it, please leave a comment explaining why it should be reopened. A maintainer can review and reopen it if appropriate.

Thanks again for taking the time to contribute.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants