Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/app/component-tests/ssh-reconnect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,22 @@ story("updating an incompatible connection continues authentication in the same
await expect(component.getByText("Session connected")).toBeVisible()
})

story("a failed connection shows the remote command's own output", async ({ mount, page }) => {
await mount("app-dialog-ssh--failure")
const dialog = page.getByRole("dialog")
await expect(dialog.getByRole("alert")).toContainText("Could not establish the SSH connection")
await expect(dialog.getByText("Connection refused")).toBeVisible()
})

story("a failed remote start shows the cause without the CLI stack", async ({ mount, page }) => {
await mount("app-dialog-ssh--failure-service")
const dialog = page.getByRole("dialog")
await expect(dialog.getByRole("alert")).toContainText("SSH connected, but the OpenCode server did not become ready")
await expect(dialog.getByText(/Managed service port 49374 .* already in use/)).toBeVisible()
await expect(dialog.getByText("at <anonymous>")).toHaveCount(0)
await expect(dialog.getByText(/\[cause\]/)).toHaveCount(0)
})

story("key-based reconnect completes without opening an authentication dialog", async ({ mount, page }) => {
const component = await mount("app-dialog-ssh--key-reconnect")
await component.getByRole("button", { name: "Reconnect", exact: true }).click()
Expand Down
11 changes: 9 additions & 2 deletions packages/cli/src/commands/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ export const Server = GlobalFlag.Setting("server")({

const ServerFlags = [Standalone, Server] as const

/** A one-off service port for this start; 0 lets the OS choose a free one. */
const ServicePort = Flag.Int("port").pipe(
Flag.withDescription("Bind the background server to this port; 0 chooses a free port"),
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 65_535 }))),
Flag.optional,
)

declare const OPENCODE_CLI_NAME: string | undefined

const ServerParams = {
Expand Down Expand Up @@ -502,8 +509,8 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME
Spec.make("service", {
description: "Manage the background server",
commands: [
Spec.make("start", { description: "Start the background server" }),
Spec.make("restart", { description: "Restart the background server" }),
Spec.make("start", { description: "Start the background server", params: { port: ServicePort } }),
Spec.make("restart", { description: "Restart the background server", params: { port: ServicePort } }),
Spec.make("status", { description: "Show background server status" }),
Spec.make("stop", { description: "Stop the background server" }),
Spec.make("get", {
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/commands/handlers/service/restart.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { EOL } from "os"
import { Effect } from "effect"
import { Effect, Option } from "effect"
import { Service } from "@opencode/client/effect/service"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { ServiceConfig } from "../../../services/service-config"

export default Runtime.handler(
Commands.commands.service.commands.restart,
Effect.fn("cli.service.restart")(function* () {
const options = yield* ServiceConfig.options()
Effect.fn("cli.service.restart")(function* (input) {
const options = yield* ServiceConfig.options({ port: Option.getOrUndefined(input.port) })
// No explicit daemon shutdown: stopping without a handoff drops the daemon's owner, which stops it with its processes.
yield* Service.stop(options)
const transport = yield* Service.ensure(options)
Expand Down
7 changes: 4 additions & 3 deletions packages/cli/src/commands/handlers/service/start.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { EOL } from "os"
import { Effect } from "effect"
import { Effect, Option } from "effect"
import { Service } from "@opencode/client/effect/service"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { ServiceConfig } from "../../../services/service-config"

export default Runtime.handler(
Commands.commands.service.commands.start,
Effect.fn("cli.service.start")(function* () {
const transport = yield* Service.ensure(yield* ServiceConfig.options())
Effect.fn("cli.service.start")(function* (input) {
const options = yield* ServiceConfig.options({ port: Option.getOrUndefined(input.port) })
const transport = yield* Service.ensure(options)
process.stdout.write(transport.url + EOL)
}),
)
7 changes: 5 additions & 2 deletions packages/cli/src/server-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,13 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
const server = yield* launch.pipe(Effect.catchIf(addressInUse, () => Effect.void))
if (server !== undefined) return server
}
const owner = port === undefined ? undefined : yield* PortOwner.describe(port, hostname)
const owner = port === undefined ? { kind: "unknown" as const } : yield* PortOwner.inspect(port, hostname)
// Only the SSH bootstrap asks for this marker, so normal CLI output stays readable.
if (process.env[PortOwner.markerEnv] === "1")
yield* Effect.sync(() => process.stderr.write(PortOwner.marker(owner) + "\n"))
return yield* Effect.fail(
new Error(
`Managed service port ${port} on ${hostname} is already in use by ${owner ?? "another process"}. ` +
`Managed service port ${port} on ${hostname} is already in use by ${PortOwner.format(owner)}. ` +
"Configure another port with `opencode service set port <port>` and start the service again.",
{ cause: error },
),
Expand Down
78 changes: 69 additions & 9 deletions packages/cli/src/services/port-owner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,25 @@ import net from "node:net"

export * as PortOwner from "./port-owner"

/** Stable stderr lines for the SSH bootstrap, so it never matches the user-facing message text. */
export const markerEnv = "OPENCODE_SERVICE_PORT_OWNER_MARKER"

export function marker(owner: Owner) {
const lines = [`OPENCODE_SERVICE_PORT_OWNER=${owner.kind}`]
if (owner.kind !== "none" && owner.pid !== undefined) lines.push(`OPENCODE_SERVICE_PORT_OWNER_PID=${owner.pid}`)
return lines.join("\n")
}

export type Owner =
| { readonly kind: "none" }
| { readonly kind: "unknown"; readonly pid?: string }
| { readonly kind: "opencode" | "foreign"; readonly pid: string; readonly command: string }

// Best effort: names the process listening on a TCP port so a failed bind can say who holds it.
// Windows has no cheap equivalent of lsof, so it keeps the generic message.
export const describe = Effect.fnUntraced(function* (port: number, hostname?: string) {
if (process.platform === "win32") return undefined
// With no listener, a failed connection means only the port number is taken, for example by an
// ephemeral source port; that is safe to move away from. Windows has no cheap lsof equivalent.
export const inspect = Effect.fnUntraced(function* (port: number, hostname?: string) {
if (process.platform === "win32") return yield* unowned(port, hostname)
const appProcess = yield* AppProcess.Service
const run = (command: string, args: ReadonlyArray<string>) =>
appProcess
Expand All @@ -20,15 +35,60 @@ export const describe = Effect.fnUntraced(function* (port: number, hostname?: st
Effect.map((result) => (result.exitCode === 0 ? result.stdout.toString("utf8").trim() : "")),
Effect.orElseSucceed(() => ""),
)
const pid = listeners(yield* run("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpn"])).find((listener) =>
const found = listeners(yield* run("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpn"])).find((listener) =>
matches(listener.address, hostname),
)?.pid
if (pid === undefined) return undefined
const command = (yield* run("ps", ["-o", "command=", "-p", pid])).replace(/\s+/g, " ")
if (!command) return `PID ${pid}`
return `PID ${pid} (${command.length > 200 ? command.slice(0, 199) + "…" : command})`
)
if (found === undefined) return yield* unowned(port, hostname)
const command = (yield* run("ps", ["-o", "command=", "-p", found.pid])).replace(/\s+/g, " ").trim()
if (!command) return { kind: "unknown", pid: found.pid } satisfies Owner
const kind = isManagedService(command) ? "opencode" : "foreign"
return { kind, pid: found.pid, command } satisfies Owner
})

export const describe = Effect.fnUntraced(function* (port: number, hostname?: string) {
const owner = yield* inspect(port, hostname)
return owner.kind === "none" || (owner.kind === "unknown" && !("pid" in owner)) ? undefined : format(owner)
})

export function format(owner: Owner) {
if (owner.kind === "none") return "another process"
if (owner.kind === "unknown") return owner.pid === undefined ? "another process" : `PID ${owner.pid}`
return `PID ${owner.pid} (${owner.command.length > 200 ? owner.command.slice(0, 199) + "…" : owner.command})`
}

/** The managed service runs `<opencode binary or entrypoint> serve --service`. */
export function isManagedService(command: string) {
return (
/(^|[/\\\s])opencode(?:\.(?:js|ts))?(?=\s|$)/.test(command) &&
/(^|\s)serve(?=\s|$)/.test(command) &&
/(^|\s)--service(?=\s|$)/.test(command)
)
}

const unowned = (port: number, hostname?: string) =>
Effect.promise(async () =>
(await reachable(port, hostname)) === false ? { kind: "none" as const } : { kind: "unknown" as const },
)

function reachable(port: number, hostname?: string) {
return new Promise<boolean | undefined>((resolve) => {
const socket = net.connect({ port, host: probeHost(hostname) })
const done = (value: boolean | undefined) => {
socket.destroy()
resolve(value)
}
socket.setTimeout(300, () => done(undefined))
socket.once("connect", () => done(true))
socket.once("error", () => done(false))
})
}

function probeHost(hostname?: string) {
if (hostname === "0.0.0.0") return "127.0.0.1"
if (hostname === "::" || hostname === "[::]") return "::1"
return hostname && net.isIP(hostname) !== 0 ? hostname : "127.0.0.1"
}

function listeners(output: string) {
const found: { pid: string; address: string }[] = []
let pid: string | undefined
Expand Down
12 changes: 10 additions & 2 deletions packages/cli/src/services/service-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,22 @@ export function processEnv(env: Info["env"]) {
return rest
}

export const options = Effect.fnUntraced(function* (input: { readonly checkVersion?: boolean } = {}) {
export const options = Effect.fnUntraced(function* (
input: { readonly checkVersion?: boolean; readonly port?: number } = {},
) {
const { file, legacyRegistrationFiles } = yield* paths
yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))
return {
file,
version: input.checkVersion ? OPENCODE_VERSION : undefined,
env: processEnv((yield* read()).env),
command: [...selfCommand(), "serve", "--service"],
command: [
...selfCommand(),
"serve",
"--service",
// Only the spawned process gets the override; the user's saved port stays untouched.
...(input.port === undefined ? [] : ["--port", String(input.port)]),
],
}
})

Expand Down
31 changes: 31 additions & 0 deletions packages/cli/test/port-owner.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { expect, test } from "bun:test"
import { format, isManagedService, marker } from "../src/services/port-owner"

test("recognizes the managed service among port holders", () => {
expect(isManagedService("/home/user/.local/bin/opencode serve --service")).toBe(true)
expect(isManagedService("/home/user/.opencode/desktop-ssh/2.0.26/opencode serve --service")).toBe(true)
expect(isManagedService("/usr/bin/node /usr/lib/node_modules/opencode-ai/bin/opencode.js serve --service")).toBe(true)
expect(isManagedService("/tmp/opencode-block/opencode.ts serve --service --port 49374")).toBe(true)

expect(isManagedService("python3 -m http.server 49374 --bind 127.0.0.1")).toBe(false)
expect(isManagedService("/usr/bin/opencode-notify --service")).toBe(false)
expect(isManagedService("/opt/opencode-serve server")).toBe(false)
expect(isManagedService("/usr/bin/opencode")).toBe(false)
})

test("describes only the owners it can name", () => {
expect(format({ kind: "none" })).toBe("another process")
expect(format({ kind: "unknown" })).toBe("another process")
expect(format({ kind: "unknown", pid: "42" })).toBe("PID 42")
expect(format({ kind: "foreign", pid: "42", command: "python3 server.py" })).toBe("PID 42 (python3 server.py)")
})

test("marks the owner for the SSH bootstrap", () => {
expect(marker({ kind: "none" })).toBe("OPENCODE_SERVICE_PORT_OWNER=none")
expect(marker({ kind: "unknown", pid: "9" })).toBe(
"OPENCODE_SERVICE_PORT_OWNER=unknown\nOPENCODE_SERVICE_PORT_OWNER_PID=9",
)
expect(marker({ kind: "opencode", pid: "42", command: "opencode serve --service" })).toBe(
"OPENCODE_SERVICE_PORT_OWNER=opencode\nOPENCODE_SERVICE_PORT_OWNER_PID=42",
)
})
90 changes: 87 additions & 3 deletions packages/cli/test/service-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,68 @@ serviceTest(
120_000,
)

serviceTest(
"an occupied configured port can be bypassed for one start",
async () => {
await using home = await serviceHome()
using listener = Bun.serve({ hostname: "127.0.0.1", port: home.port, fetch: () => new Response("unrelated") })

const plain = await cliFailure(home, "service", "start")
expect(plain.message).toContain("already in use")
expect(plain.message).not.toContain("OPENCODE_SERVICE_PORT_OWNER=")

await expect(cliWithEnv(home, { OPENCODE_SERVICE_PORT_OWNER_MARKER: "1" }, "service", "start")).rejects.toThrow(
/OPENCODE_SERVICE_PORT_OWNER=foreign[\s\S]*already in use/,
)

const url = await cli(home, "service", "start", "--port", "0")
const info = await Bun.file(home.registration).json()
expect(url).toBe(info.url)
expect(info.url).not.toBe(`http://127.0.0.1:${home.port}`)
const answer = await fetch(new URL("/api/info", info.url), {
headers: Service.headers({
url: info.url,
auth: { type: "basic", username: "opencode", password: info.password },
}),
})
expect(answer.ok).toBe(true)

await listener.stop(true)
await stopped(home)
},
120_000,
)

serviceTest(
"a start leaves an OpenCode service that already owns the port alone",
async () => {
await using owner = await serviceHome()
await using contender = await serviceHome({ port: owner.port })
const server = Bun.spawn([process.execPath, owner.entry, "serve", "--service"], {
env: owner.env,
stdout: "ignore",
stderr: "ignore",
})
const before = await settled(owner)

// The contender cannot see the owner's registration, so it must not start a second service.
await expect(
cliWithEnv(contender, { OPENCODE_SERVICE_PORT_OWNER_MARKER: "1" }, "service", "start"),
).rejects.toThrow(
new RegExp(
`OPENCODE_SERVICE_PORT_OWNER=opencode\\nOPENCODE_SERVICE_PORT_OWNER_PID=${before.pid}[\\s\\S]*already in use`,
),
)
expect(await servers(owner)).toEqual([before.pid])
await until(async () => ((await servers(contender)).length === 0 ? true : undefined))
expect(await servers(contender)).toEqual([])

await stopped(owner)
await server.exited
},
120_000,
)

serviceTest(
"a damaged registration and then a crash each end with one replacement server",
async () => {
Expand Down Expand Up @@ -175,10 +237,10 @@ serviceTest(
type Home = Awaited<ReturnType<typeof serviceHome>>
type Snapshot = Awaited<ReturnType<typeof snapshot>>

async function serviceHome(options: { readonly failBoot?: boolean } = {}) {
async function serviceHome(options: { readonly failBoot?: boolean; readonly port?: number } = {}) {
// Bun resolves symlinks in the entry path, so process command lines carry the real directory.
const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-lifecycle-")))
const port = await availablePort()
const port = options.port ?? (await availablePort())
await fs.mkdir(path.join(root, "config"), { recursive: true })
await fs.writeFile(path.join(root, "config", "service-local.json"), JSON.stringify({ port }))
// A directory where the database file belongs makes boot fail after the server registers.
Expand Down Expand Up @@ -207,7 +269,29 @@ async function serviceHome(options: { readonly failBoot?: boolean } = {}) {
}

async function cli(home: Home, ...args: string[]) {
const child = Bun.spawn([process.execPath, home.entry, ...args], { env: home.env, stdout: "pipe", stderr: "pipe" })
return runCli(home, {}, ...args)
}

async function cliWithEnv(home: Home, env: Record<string, string>, ...args: string[]) {
return runCli(home, env, ...args)
}

async function cliFailure(home: Home, ...args: string[]) {
try {
await cli(home, ...args)
} catch (error) {
if (error instanceof Error) return error
throw error
}
throw new Error(`opencode ${args.join(" ")} succeeded`)
}

async function runCli(home: Home, env: Record<string, string>, ...args: string[]) {
const child = Bun.spawn([process.execPath, home.entry, ...args], {
env: { ...home.env, ...env },
stdout: "pipe",
stderr: "pipe",
})
const [code, stdout, stderr] = await Promise.all([
child.exited,
new Response(child.stdout).text(),
Expand Down
Loading
Loading