Skip to content

Commit 763cecd

Browse files
engineerclaude
andcommitted
fix(serve): surface the real bind error instead of "Unexpected error / ServeError"
Every bind failure in `opencode serve` printed the same two useless lines: $ opencode serve --hostname 100.68.120.26 --port 4096 Error: Unexpected error ServeError No port, no hostname, no errno. A busy port, an unavailable address, and a privileged port were indistinguishable. Two independent causes: 1. Effect's `HttpServerError.ServeError` is a `Data.TaggedError` whose `message` is empty — the real failure sits on `.cause`. `errorMessage()` never read `.cause`, so it fell through to `error.name` and printed "ServeError". 2. Under Bun, `node:http` `listen()` reports *every* failure as `EADDRINUSE` ("Failed to start server. Is port N in use?"). Node returns EADDRNOTAVAIL / EACCES for the same binds. So errno dispatch alone cannot tell a busy port from a hostname that is not on this machine. Fixes: - `errorMessage()` now falls back to `cause` before the bare name. This helps every tagged error, not just this one. - New `server/bind.ts`. `assertBindable()` checks a literal-IP hostname against `os.networkInterfaces()` before binding, where an exact answer is available — this is what works around (2). `bindError()` walks the cause chain and translates the errno, treating EADDRINUSE below port 1024 as a privilege problem since Bun folds EACCES into it. - `serve` raises a `CliError` so the message prints on its own rather than behind "Unexpected error". Before / after: --hostname 100.68.120.26 --port 4096 (interface down) was: Unexpected error / ServeError now: Cannot bind to 100.68.120.26: it is not an address on any local network interface. Available: 127.0.0.1, ::1, 192.168.0.40, ... Use 0.0.0.0 to listen on every interface, or bring the interface up first (e.g. start Tailscale/VPN). --hostname 127.0.0.1 --port 4096 (port busy) was: Unexpected error / ServeError now: Address 127.0.0.1:4096 is already in use. Choose a different --port, use --port 0 to pick a free one, or stop the process holding it. --hostname 127.0.0.1 --port 80 was: Unexpected error / ServeError now: Cannot bind 127.0.0.1:80: ports below 1024 are privileged. Use a port >= 1024, or run with elevated privileges. Valid binds (0.0.0.0, 127.0.0.1, a real LAN address, --port 0) are unchanged. Closes anomalyco#38738 Closes anomalyco#38739 Refs anomalyco#37718 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01E2b7v7smJX7nby2ZmsqXsp
1 parent bd27913 commit 763cecd

6 files changed

Lines changed: 259 additions & 3 deletions

File tree

‎packages/opencode/src/cli/cmd/serve.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { Flag } from "@opencode-ai/core/flag/flag"
22
import { Effect } from "effect"
3-
import { effectCmd } from "../effect-cmd"
3+
import { CliError, effectCmd } from "../effect-cmd"
44
import { resolveNetworkOptions, withNetworkOptions } from "../network"
5+
import { errorMessage } from "@/util/error"
56

67
export const ServeCommand = effectCmd({
78
command: "serve",
@@ -17,7 +18,13 @@ export const ServeCommand = effectCmd({
1718
console.log("Warning: OPENCODE_SERVER_PASSWORD is not set; server is unsecured.")
1819
}
1920
const opts = yield* resolveNetworkOptions(args)
20-
const server = yield* Effect.promise(() => Server.listen(opts))
21+
// A failed bind is a user-fixable mistake (busy port, wrong --hostname), not
22+
// a crash — surface it as a CliError so the message prints on its own instead
23+
// of behind "Unexpected error".
24+
const server = yield* Effect.tryPromise({
25+
try: () => Server.listen(opts),
26+
catch: (error) => new CliError({ message: errorMessage(error) }),
27+
})
2128
console.log(`opencode server listening on http://${server.hostname}:${server.port}`)
2229

2330
yield* Effect.scoped(
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
// Bind-failure diagnostics for `Server.listen`.
2+
//
3+
// Two problems make a failed bind undiagnosable without help:
4+
//
5+
// 1. Effect's `HttpServerError.ServeError` is a `Data.TaggedError` whose
6+
// `message` is empty — the real `listen` error is parked on `.cause`, so a
7+
// naive rethrow prints the bare string "ServeError".
8+
// 2. Bun's `node:http` shim reports *every* `listen()` failure as `EADDRINUSE`
9+
// ("Failed to start server. Is port N in use?"), discarding the real errno.
10+
// Node returns EADDRNOTAVAIL / EACCES for the same binds. So errno dispatch
11+
// alone cannot tell a busy port from a hostname that isn't on this machine.
12+
//
13+
// `assertBindable` handles (2) by checking the address before we ever call
14+
// `listen`, where an exact answer is available. `bindError` handles (1) by
15+
// walking the cause chain and translating whatever errno survives.
16+
import { isIP } from "node:net"
17+
import { networkInterfaces } from "node:os"
18+
19+
const WILDCARD_HOSTS = new Set(["0.0.0.0", "::", "localhost", "127.0.0.1", "::1"])
20+
21+
export type BindTarget = {
22+
hostname: string
23+
port: number
24+
}
25+
26+
export function localAddresses(interfaces = networkInterfaces()) {
27+
return [
28+
...new Set(
29+
Object.values(interfaces)
30+
.flatMap((entries) => entries ?? [])
31+
.map((entry) => entry.address),
32+
),
33+
]
34+
}
35+
36+
/**
37+
* Throw before binding when `hostname` is a literal IP that no local interface
38+
* owns — the common case being a VPN/Tailscale address whose interface is down.
39+
* Hostnames are left alone; `listen` resolves those.
40+
*/
41+
export function assertBindable(target: BindTarget, interfaces = networkInterfaces()) {
42+
const { hostname } = target
43+
if (WILDCARD_HOSTS.has(hostname)) return
44+
if (!isIP(hostname)) return
45+
const local = localAddresses(interfaces)
46+
// Link-local IPv6 may be written with a zone id (fe80::1%en0); compare bare.
47+
const bare = hostname.split("%")[0]
48+
if (local.some((address) => address === hostname || address.split("%")[0] === bare)) return
49+
throw new Error(
50+
`Cannot bind to ${hostname}: it is not an address on any local network interface.` +
51+
` Available: ${local.join(", ")}.` +
52+
` Use 0.0.0.0 to listen on every interface, or bring the interface up first (e.g. start Tailscale/VPN).`,
53+
)
54+
}
55+
56+
/**
57+
* Translate a failed bind into a message that names the address and the fix.
58+
* Falls back to the deepest cause message so we never print nothing.
59+
*/
60+
export function bindError(error: unknown, target: BindTarget) {
61+
const { hostname, port } = target
62+
const label = `${hostname}:${port}`
63+
const wrap = (message: string) => new Error(message, { cause: error })
64+
65+
let cause: unknown = error
66+
const seen = new Set<unknown>()
67+
let deepest: unknown = error
68+
while (cause && typeof cause === "object" && !seen.has(cause)) {
69+
seen.add(cause)
70+
deepest = cause
71+
const code = (cause as { code?: unknown }).code
72+
if (code === "EADDRINUSE") {
73+
// Bun folds EACCES into EADDRINUSE, and a privileged port is the far more
74+
// likely explanation below 1024 — say so rather than blaming a conflict.
75+
if (port > 0 && port < 1024)
76+
return wrap(
77+
`Cannot bind ${label}: ports below 1024 are privileged. Use a port >= 1024, or run with elevated privileges.`,
78+
)
79+
return wrap(
80+
`Address ${label} is already in use. Choose a different --port, use --port 0 to pick a free one,` +
81+
` or stop the process holding it.`,
82+
)
83+
}
84+
if (code === "EADDRNOTAVAIL")
85+
return wrap(
86+
`Cannot bind to ${label}: "${hostname}" is not an address on this machine.` +
87+
` Use a local interface address, 127.0.0.1, or 0.0.0.0.`,
88+
)
89+
if (code === "EACCES")
90+
return wrap(`Permission denied binding ${label}. Ports below 1024 require elevated privileges.`)
91+
cause = (cause as { cause?: unknown }).cause
92+
}
93+
94+
const detail = deepest instanceof Error && deepest.message ? `: ${deepest.message}` : ""
95+
return wrap(`Failed to start server on ${label}${detail}`)
96+
}

‎packages/opencode/src/server/server.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { ConfigProvider, Context, Effect, Exit, Layer, Scope } from "effect"
55
import { HttpRouter, HttpServer } from "effect/unstable/http"
66
import { OpenApi } from "effect/unstable/httpapi"
77
import { createServer } from "node:http"
8+
import { assertBindable, bindError } from "./bind"
89
import { MDNS } from "./mdns"
910
import { HttpApiApp } from "./routes/instance/httpapi/server"
1011
import { disposeMiddleware } from "./routes/instance/httpapi/lifecycle"
@@ -70,7 +71,10 @@ export async function openapi() {
7071
export let url: URL | undefined
7172

7273
export async function listen(opts: ListenOptions): Promise<Listener> {
73-
const listener = await Effect.runPromise(listenEffect(opts))
74+
assertBindable(opts)
75+
const listener = await Effect.runPromise(listenEffect(opts)).catch((error) => {
76+
throw bindError(error, opts)
77+
})
7478
return {
7579
hostname: listener.hostname,
7680
port: listener.port,
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
// Unit tests for bind-failure diagnostics. These exist because the two failure
2+
// modes they cover are invisible at runtime: Effect's `ServeError` has an empty
3+
// `message`, and Bun's `node:http` reports every listen error as EADDRINUSE. A
4+
// regression here degrades silently to "Unexpected error / ServeError".
5+
import { describe, expect, test } from "bun:test"
6+
import type { networkInterfaces } from "node:os"
7+
import { assertBindable, bindError, localAddresses } from "../../src/server/bind"
8+
9+
type Interfaces = ReturnType<typeof networkInterfaces>
10+
11+
// Only `address` is read; the rest of NetworkInterfaceInfo is noise here.
12+
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- partial fixture, `address` is the only field under test
13+
const INTERFACES = {
14+
lo0: [
15+
{ address: "127.0.0.1", family: "IPv4", internal: true },
16+
{ address: "::1", family: "IPv6", internal: true },
17+
],
18+
en0: [
19+
{ address: "192.168.0.40", family: "IPv4", internal: false },
20+
{ address: "fe80::1c52:8bff:fe2e:29fe", family: "IPv6", internal: false },
21+
],
22+
} as unknown as Interfaces
23+
24+
// Mirrors Effect's `HttpServerError.ServeError`: a tagged error with an empty
25+
// message that hides the real failure on `.cause`.
26+
function serveError(cause: unknown) {
27+
const error = new Error("")
28+
error.name = "ServeError"
29+
Object.assign(error, { _tag: "ServeError", cause })
30+
return error
31+
}
32+
33+
function errno(code: string, message: string) {
34+
return Object.assign(new Error(message), { code })
35+
}
36+
37+
describe("server.bind", () => {
38+
describe("assertBindable", () => {
39+
test("allows wildcard and loopback hosts", () => {
40+
for (const hostname of ["0.0.0.0", "::", "localhost", "127.0.0.1", "::1"]) {
41+
expect(() => assertBindable({ hostname, port: 4096 }, INTERFACES)).not.toThrow()
42+
}
43+
})
44+
45+
test("allows an address owned by a local interface", () => {
46+
expect(() => assertBindable({ hostname: "192.168.0.40", port: 4096 }, INTERFACES)).not.toThrow()
47+
})
48+
49+
test("rejects an IP no interface owns, and lists what is available", () => {
50+
// A Tailscale CGNAT address with the interface down — the reported case.
51+
const bind = () => assertBindable({ hostname: "100.68.120.26", port: 4096 }, INTERFACES)
52+
expect(bind).toThrow(/not an address on any local network interface/)
53+
// The message has to be actionable, not just accurate.
54+
expect(bind).toThrow(/192\.168\.0\.40/)
55+
expect(bind).toThrow(/0\.0\.0\.0/)
56+
})
57+
58+
test("ignores DNS names — listen() resolves those", () => {
59+
expect(() => assertBindable({ hostname: "example.internal", port: 4096 }, INTERFACES)).not.toThrow()
60+
})
61+
62+
test("matches link-local IPv6 written with a zone id", () => {
63+
expect(() =>
64+
assertBindable({ hostname: "fe80::1c52:8bff:fe2e:29fe%en0", port: 4096 }, INTERFACES),
65+
).not.toThrow()
66+
})
67+
})
68+
69+
test("localAddresses dedupes and flattens", () => {
70+
expect(localAddresses(INTERFACES)).toEqual(["127.0.0.1", "::1", "192.168.0.40", "fe80::1c52:8bff:fe2e:29fe"])
71+
})
72+
73+
describe("bindError", () => {
74+
const target = { hostname: "127.0.0.1", port: 4096 }
75+
76+
test("unwraps an errno buried under ServeError", () => {
77+
const error = bindError(serveError(errno("EADDRINUSE", "address already in use")), target)
78+
expect(error.message).toContain("127.0.0.1:4096 is already in use")
79+
expect(error.message).not.toContain("ServeError")
80+
})
81+
82+
test("blames privileges, not a conflict, for ports below 1024", () => {
83+
// Bun folds EACCES into EADDRINUSE, so the errno alone would mislead here.
84+
const error = bindError(serveError(errno("EADDRINUSE", "in use?")), { hostname: "127.0.0.1", port: 80 })
85+
expect(error.message).toContain("privileged")
86+
})
87+
88+
test("maps EADDRNOTAVAIL to the hostname, not the port", () => {
89+
const error = bindError(serveError(errno("EADDRNOTAVAIL", "address not available")), {
90+
hostname: "100.68.120.26",
91+
port: 4096,
92+
})
93+
expect(error.message).toContain("not an address on this machine")
94+
})
95+
96+
test("maps EACCES", () => {
97+
const error = bindError(serveError(errno("EACCES", "permission denied")), { hostname: "127.0.0.1", port: 443 })
98+
expect(error.message).toContain("Permission denied")
99+
})
100+
101+
test("falls back to the deepest cause message when the errno is unknown", () => {
102+
const error = bindError(serveError(new Error("socket exploded")), target)
103+
expect(error.message).toBe("Failed to start server on 127.0.0.1:4096: socket exploded")
104+
})
105+
106+
test("never loses the original error", () => {
107+
const original = serveError(errno("EADDRINUSE", "in use"))
108+
expect(bindError(original, target).cause).toBe(original)
109+
})
110+
111+
test("terminates on a self-referential cause chain", () => {
112+
const looped: { cause?: unknown } = {}
113+
looped.cause = looped
114+
// Would hang without the `seen` guard; reaching the assertion is the test.
115+
expect(bindError(looped, target).message).toBe("Failed to start server on 127.0.0.1:4096")
116+
})
117+
})
118+
})

‎packages/tui/src/util/error.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,12 @@ export function errorFormat(error: unknown): string {
125125
export function errorMessage(error: unknown): string {
126126
if (error instanceof Error) {
127127
if (error.message) return error.message
128+
// Tagged errors (e.g. Effect's `ServeError`) carry an empty `message` and hide
129+
// the real failure in `cause`. Printing just the name tells the user nothing.
130+
if (error.cause !== undefined && error.cause !== null) {
131+
const inner = errorMessage(error.cause)
132+
if (inner && inner !== "unknown error") return error.name ? `${error.name}: ${inner}` : inner
133+
}
128134
if (error.name) return error.name
129135
}
130136

‎packages/tui/test/util/error.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,29 @@ describe("util.error", () => {
4646
expect(data.message).toBe("ResolveMessage: Cannot resolve module")
4747
expect(String(data.formatted)).toContain("ResolveMessage")
4848
})
49+
50+
test("surfaces the cause when a tagged error has no message", () => {
51+
// Effect's `Data.TaggedError` subclasses (e.g. `ServeError`) leave `message`
52+
// empty and park the real failure on `cause`. Printing the bare name told
53+
// the user nothing.
54+
const inner = Object.assign(new Error("listen EADDRINUSE: address already in use"), { code: "EADDRINUSE" })
55+
const tagged = new Error("")
56+
tagged.name = "ServeError"
57+
Object.assign(tagged, { _tag: "ServeError", cause: inner })
58+
59+
expect(errorMessage(tagged)).toBe("ServeError: listen EADDRINUSE: address already in use")
60+
})
61+
62+
test("still falls back to the name when the cause is empty too", () => {
63+
const tagged = new Error("")
64+
tagged.name = "ServeError"
65+
Object.assign(tagged, { cause: null })
66+
67+
expect(errorMessage(tagged)).toBe("ServeError")
68+
})
69+
70+
test("prefers an explicit message over the cause", () => {
71+
const err = new Error("outer", { cause: new Error("inner") })
72+
expect(errorMessage(err)).toBe("outer")
73+
})
4974
})

0 commit comments

Comments
 (0)