Skip to content

Commit c2041f2

Browse files
committed
fix(opencode): bridge web-child WebSocket upgrades via ws noServer handoff
Bun swallows every socket.write on a node:http upgrade socket (oven-sh/bun#9882, anomalyco#35325): the upgrade event fires, writes report success, and no byte reaches the wire. Raw-byte tunnels through the parent listener can therefore never answer a browser's 101, and the workbench DSH surface stays in its reconnect loop. Terminate the browser handshake with the ws package's noServer handleUpgrade (Bun's ws shim uses the native handoff and does reach the wire), then bridge frames through a native WebSocket client dialed at the child loopback port. Update the DESIGN isolation paragraph to name the constraint.
1 parent 880ca42 commit c2041f2

3 files changed

Lines changed: 85 additions & 125 deletions

File tree

‎docs/DESIGN.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ PluginInput 通过可选 `wopalSpaceRoot` 字段接收当前 instance 的空间
446446
- **Hot replay**:只重放配置/patch,不更换进程模块图。
447447
- **Cold reload**:代码或包版本变化时,按 `drain → dispose → build → verify → publish → notify` 重建对应单元。这里的单元 revision 只用于重载事件,不是 DSH `closureVersion`。
448448

449-
**隔离边界**:进程内重挂载复用同 URL 的已求值模块(原生 `import()` 与内部 loader 均按 URL 缓存),插件版本升级不生效;冷重载依赖新进程边界来重置模块图,与内部 loader 无关。`dsh:web` 的 build 在独立可重启子进程中完成,宿主以 loopback HTTP 承接并稳定转发 `/dsh` 前缀。Desktop 复用 `utilityProcess`(现有 sidecar 已是同款);bun standalone serve 以全新 bun 子进程承载 web 容器、宿主经 loopback TCP 隧道转发 `/dsh`(HTTP 与 WebSocket upgrade 一律原始字节双向转发;不用 `node:http` 的 `upgrade` 事件——Bun 不触发该事件,事件式代理会让浏览器 WS 全部挂起)。`dsh:tools` 是无会话的 per-call 执行,默认 in-process,必要时升级为同款隔离。`--expose-internals` 服务于官方 node-hmr,在 Electron 中当前不可用,是本设计的非依赖项;普通 Node 22 与 bun 子进程均可分载 web 容器并返回认证首页、宿主代理转发 200(已 spike)。
449+
**隔离边界**:进程内重挂载复用同 URL 的已求值模块(原生 `import()` 与内部 loader 均按 URL 缓存),插件版本升级不生效;冷重载依赖新进程边界来重置模块图,与内部 loader 无关。`dsh:web` 的 build 在独立可重启子进程中完成,宿主以 loopback HTTP 承接并稳定转发 `/dsh` 前缀。Desktop 复用 `utilityProcess`(现有 sidecar 已是同款);bun standalone serve 以全新 bun 子进程承载 web 容器,宿主经 loopback 代理转发 `/dsh`:HTTP 走 `node:http` 请求代理;WebSocket upgrade 在宿主以 `ws` noServer 终结(Bun 对 `ws` 握手走原生通道),再以原生 WebSocket 客户端桥接子进程——禁止在宿主 upgrade socket 上直接 `socket.write`(Bun 吞掉全部字节,oven-sh/bun#9882/#35325)。`dsh:tools` 是无会话的 per-call 执行,默认 in-process,必要时升级为同款隔离。`--expose-internals` 服务于官方 node-hmr,在 Electron 中当前不可用,是本设计的非依赖项;普通 Node 22 与 bun 子进程均可分载 web 容器并返回认证首页、宿主代理转发 200(已 spike)。
450450

451451
**触发定域**:按状态源变化定单元,不做固定组合——web profile 变 → `dsh:web`;tools profile 变 → `dsh:tools`;共享 dsh-base 配置变 → web+tools;产品闭包变更由产品重启与 Home 协议接管;全局 provider/config 变 → `global` 与各 `instance:*`,不牵动 dsh。单元用 `invalidatedBy` 声明依赖边;当前 global 不依赖任何 dsh 单元,未来做集中配置管理只需增补一条边。
452452

‎packages/opencode/src/cli/cmd/dsh-web-child.ts‎

Lines changed: 39 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
* proxy target without remounting, so the browser-facing URL never changes.
1818
*/
1919
import { request as httpRequest, type IncomingMessage, type ServerResponse } from "node:http"
20-
import net from "node:net"
20+
import { WebSocketServer, WebSocket } from "ws"
2121
import { spawn as nodeSpawn } from "node:child_process"
2222
import type { Duplex } from "node:stream"
2323
import type { ColdRebuildContainer } from "@wopal/ellamaka-cordis/runtime/web-cold-reload"
@@ -64,6 +64,8 @@ export interface WebChildContainer extends ColdRebuildContainer {
6464
* for tests and reuse; `spawnWebChildContainer` composes it with the spawn.
6565
*/
6666
export function webChildProxyContainer(child: { port: number; authPath?: string }): WebChildContainer {
67+
// One noServer acceptor per container generation; dispose drops it.
68+
const socketWss = new WebSocketServer({ noServer: true })
6769
const proxyRequest = (req: IncomingMessage, res: ServerResponse): void => {
6870
const upstream = httpRequest(
6971
{
@@ -85,35 +87,45 @@ export function webChildProxyContainer(child: { port: number; authPath?: string
8587
if (typeof (req as { pipe?: unknown }).pipe === "function") req.pipe(upstream)
8688
else upstream.end()
8789
}
88-
// Raw-TCP tunnel, not node:http `request().on("upgrade")`: Bun never emits
89-
// that event, which left every browser WebSocket through this proxy hanging
90-
// until the client gave up (the "连接中断" retry loop). Writing the upgrade
91-
// request bytes straight at the loopback socket and piping both directions
92-
// is transport-agnostic — Node and Bun behave identically — and the bytes
93-
// are exactly what the dispatcher already received (headers preserved, so
94-
// the child's token/cookie fence sees the original request).
90+
// Bun swallows every socket.write() on a node:http upgrade socket
91+
// (oven-sh/bun#9882, #35325): the `upgrade` event fires, writes report
92+
// success, and no byte ever reaches the wire — so raw-byte tunnels can
93+
// never answer a browser's 101. The `ws` package's noServer handleUpgrade
94+
// takes Bun's native handoff and DOES reach the wire (that is also why the
95+
// child's own WS works). Terminate the browser's handshake with `ws`, dial
96+
// the child with Bun's native WebSocket client, and bridge frames.
9597
const proxyUpgrade = (req: IncomingMessage, socket: Duplex, head: Buffer): void => {
96-
const upstream = net.connect({ host: "127.0.0.1", port: child.port }, () => {
97-
const headers = [`${req.method ?? "GET"} ${req.url ?? "/"} HTTP/1.1`]
98-
for (const [key, value] of Object.entries(req.headers)) {
99-
if (Array.isArray(value)) for (const entry of value) headers.push(`${key}: ${entry}`)
100-
else if (value !== undefined) headers.push(`${key}: ${value}`)
98+
socketWss.handleUpgrade(req, socket, head, (clientWs) => {
99+
const upstream = new WebSocket(`ws://127.0.0.1:${child.port}${req.url ?? "/"}`)
100+
upstream.binaryType = "arraybuffer"
101+
let upstreamReady = false
102+
const pendingOnOpen: (string | Uint8Array)[] = []
103+
clientWs.on("message", (data) => {
104+
if (upstreamReady) upstream.send(data)
105+
else pendingOnOpen.push(data as string | Uint8Array)
106+
})
107+
upstream.on("open", () => {
108+
upstreamReady = true
109+
for (const frame of pendingOnOpen) upstream.send(frame)
110+
pendingOnOpen.length = 0
111+
})
112+
upstream.on("message", (data) => clientWs.send(data))
113+
const closeBoth = () => {
114+
try {
115+
clientWs.close()
116+
} catch {
117+
// already closing/closed
118+
}
119+
try {
120+
upstream.close()
121+
} catch {
122+
// already closing/closed
123+
}
101124
}
102-
upstream.write(`${headers.join("\r\n")}\r\n\r\n`)
103-
// Headers already drained from the incoming socket by Node arrive here;
104-
// forward them so the child sees a byte-identical stream.
105-
if (head.length > 0) upstream.write(head)
125+
clientWs.on("close", closeBoth)
126+
upstream.on("close", closeBoth)
127+
upstream.on("error", closeBoth)
106128
})
107-
upstream.on("data", (chunk) => socket.write(chunk))
108-
socket.on("data", (chunk) => upstream.write(chunk))
109-
const teardown = () => {
110-
upstream.destroy()
111-
socket.destroy()
112-
}
113-
upstream.on("error", teardown)
114-
socket.on("error", teardown)
115-
upstream.on("close", () => socket.destroy())
116-
socket.on("close", () => upstream.destroy())
117129
}
118130
return {
119131
port: child.port,

‎packages/opencode/test/cli/serve/dsh-web-child.test.ts‎

Lines changed: 45 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
22
import { createServer, request as httpRequest, type Server } from "node:http"
3-
import net from "node:net"
4-
import { PassThrough } from "node:stream"
3+
import { WebSocketServer, WebSocket } from "ws"
54
import { DshWebColdReload } from "@wopal/ellamaka-cordis/runtime/web-cold-reload"
65
import {
76
spawnWebChildContainer,
@@ -26,43 +25,6 @@ import {
2625
let fakeChild: Server
2726
let fakePort = 0
2827

29-
/**
30-
* Minimal duplex socket pair standing in for the dispatcher boundary: writing
31-
* to one end is readable from the other, which is all `handleUpgrade` needs.
32-
* (Bun has no `net.createPair`; a real loopback socket pair would need an
33-
* extra listener and adds no contract value here.)
34-
*/
35-
function socketPair(): [net.Socket, net.Socket] {
36-
const make = (): { sock: net.Socket; feed: (chunk: Buffer) => void } => {
37-
const source = new PassThrough()
38-
const sink = new PassThrough()
39-
const sock = source as unknown as net.Socket
40-
// Cross-wire: writes to `sock` surface on the peer's readable side.
41-
const peer = { feed: (chunk: Buffer) => source.write(chunk) }
42-
void sink
43-
sock.write = ((chunk: Buffer, _enc?: unknown, cb?: () => void) => {
44-
peer.feed(chunk)
45-
cb?.()
46-
return true
47-
}) as net.Socket["write"]
48-
return { sock, feed: (chunk) => source.push(chunk) }
49-
}
50-
const a = make()
51-
const b = make()
52-
// a.write → readable on b; b.write → readable on a
53-
a.sock.write = ((chunk: Buffer, _enc?: unknown, cb?: () => void) => {
54-
b.feed(chunk)
55-
cb?.()
56-
return true
57-
}) as net.Socket["write"]
58-
b.sock.write = ((chunk: Buffer, _enc?: unknown, cb?: () => void) => {
59-
a.feed(chunk)
60-
cb?.()
61-
return true
62-
}) as net.Socket["write"]
63-
return [a.sock, b.sock]
64-
}
65-
6628
beforeEach(async () => {
6729
fakeChild = createServer((req, res) => {
6830
res.writeHead(200, { "content-type": "text/plain" })
@@ -98,71 +60,57 @@ describe("dsh:web child host builder", () => {
9860
expect(() => container.handleRequest({}, { writeHead() {}, end() {} })).not.toThrow()
9961
})
10062

101-
test("webChildProxyContainer forwards WebSocket upgrades to the child (101 handshake completes)", async () => {
102-
// Regression (Bun runtime): the previous proxyUpgrade relied on
103-
// node:http's `upgrade` event, which Bun does not emit — every browser
104-
// WebSocket through the parent hung until the client gave up ("连接中断"
105-
// retry loop). The contract is now end-to-end: a real upgrade request
106-
// through `handleUpgrade` must reach the child and complete the 101
107-
// handshake within a bounded time.
108-
// The fake child is a RAW TCP server, matching the real child's upgrade
109-
// path (cordis VirtualWebServer answers upgrades on the raw socket; Bun's
110-
// node:http `upgrade` event fires but swallows socket bytes, so a plain
111-
// createServer() cannot stand in for the child here).
112-
const upgradeServer = net.createServer((socket) => {
113-
socket.once("data", () => {
114-
socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n")
115-
socket.end()
116-
})
117-
})
118-
await new Promise<void>((resolve) => upgradeServer.listen(0, "127.0.0.1", resolve))
119-
const address: unknown = upgradeServer.address()
63+
test("webChildProxyContainer bridges WebSocket upgrades to the child (101 handshake + message round-trip)", async () => {
64+
// Regression (Bun runtime): Bun swallows every socket.write() on a
65+
// node:http upgrade socket (oven-sh/bun#9882, #35325), so raw-byte tunnels
66+
// can never answer a browser's 101. The proxy must terminate the upgrade
67+
// with the `ws` noServer path (Bun's ws shim uses the native handoff) and
68+
// bridge frames to a native WebSocket dialed at the child. The contract is
69+
// end-to-end: handshake completes AND one frame round-trips.
70+
const childHttp = createServer()
71+
const childWss = new WebSocketServer({ noServer: true })
72+
childHttp.on("upgrade", (req, sock, head) =>
73+
childWss.handleUpgrade(req, sock, head, (ws) => {
74+
ws.on("message", (m) => ws.send(`echo:${String(m)}`))
75+
}),
76+
)
77+
await new Promise<void>((resolve) => childHttp.listen(0, "127.0.0.1", resolve))
78+
const address: unknown = childHttp.address()
12079
expect(address).toHaveProperty("port")
12180
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- expect guard above pins the shape
122-
const upgradePort = (address as { port: number }).port
81+
const childPort = (address as { port: number }).port
12382

124-
const container = webChildProxyContainer({ port: upgradePort })
125-
// A client-side socket pair whose "server side" IS the proxy: we feed the
126-
// raw upgrade request into `handleUpgrade` (the dispatcher's entry) and
127-
// read the child's answer back from the paired client — the exact parent
128-
// path without needing a real listening socket in between.
129-
const [client, serverSide] = socketPair()
130-
const raw = client
131-
container.handleUpgrade(
132-
{
133-
method: "GET",
134-
url: "/api/remote.mux",
135-
headers: {
136-
host: "127.0.0.1",
137-
upgrade: "websocket",
138-
connection: "Upgrade",
139-
"sec-websocket-key": "dGhlIHNhbXBsZSBub25jZQ==",
140-
"sec-websocket-version": "13",
141-
},
142-
},
143-
serverSide,
144-
Buffer.alloc(0),
145-
)
146-
// The proxy must answer with the child's 101 within 5s; a hang is the
147-
// exact Bun regression this test pins.
148-
const response = await new Promise<string>((resolve) => {
149-
let data = ""
150-
const timer = setTimeout(() => resolve("TIMEOUT"), 5000)
151-
raw.on("data", (chunk) => {
152-
data += chunk.toString("latin1")
153-
if (data.includes("\r\n\r\n")) {
154-
clearTimeout(timer)
155-
resolve(data)
156-
}
83+
const container = webChildProxyContainer({ port: childPort })
84+
// The dispatcher boundary: feed an upgrade request into handleUpgrade with
85+
// a fake duplex pair, then use a native WebSocket against a loopback
86+
// listener that forwards into the container's socket side.
87+
const relay = createServer((req: unknown, res: { writeHead(n: number): unknown; end(): unknown }) => {
88+
res.writeHead(500)
89+
res.end()
90+
})
91+
relay.on("upgrade", (req, sock, head) => container.handleUpgrade(req, sock, head))
92+
await new Promise<void>((resolve) => relay.listen(0, "127.0.0.1", resolve))
93+
const relayAddress: unknown = relay.address()
94+
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- expect guard pins shape
95+
const relayPort = (relayAddress as { port: number }).port
96+
97+
const probe = new WebSocket(`ws://127.0.0.1:${relayPort}/api/remote.mux`)
98+
const roundTrip = new Promise<string>((resolve, reject) => {
99+
const timer = setTimeout(() => reject(new Error("ws round-trip timed out")), 5000)
100+
probe.on("open", () => probe.send("ping"))
101+
probe.on("message", (m) => {
102+
clearTimeout(timer)
103+
resolve(String(m))
157104
})
158-
raw.on("error", () => {
105+
probe.on("error", (e) => {
159106
clearTimeout(timer)
160-
resolve("ERROR")
107+
reject(e)
161108
})
162109
})
163-
expect(response).toContain("101 Switching Protocols")
164-
raw.destroy()
165-
await new Promise<void>((resolve) => upgradeServer.close(() => resolve()))
110+
expect(await roundTrip).toBe("echo:ping")
111+
probe.close()
112+
await new Promise<void>((resolve) => relay.close(() => resolve()))
113+
await new Promise<void>((resolve) => childHttp.close(() => resolve()))
166114
})
167115

168116
test("spawnWebChildContainer resolves after the ready line and proxies HTTP; dispose kills the child", async () => {

0 commit comments

Comments
 (0)