diff --git a/packages/app/component-tests/ssh-reconnect.spec.ts b/packages/app/component-tests/ssh-reconnect.spec.ts index c2afa5a84e72..193dd94990ea 100644 --- a/packages/app/component-tests/ssh-reconnect.spec.ts +++ b/packages/app/component-tests/ssh-reconnect.spec.ts @@ -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 ")).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() diff --git a/packages/cli/src/commands/commands.ts b/packages/cli/src/commands/commands.ts index 5ca37aa79454..3041007dc607 100644 --- a/packages/cli/src/commands/commands.ts +++ b/packages/cli/src/commands/commands.ts @@ -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 = { @@ -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", { diff --git a/packages/cli/src/commands/handlers/service/restart.ts b/packages/cli/src/commands/handlers/service/restart.ts index fbd2c3b98269..d4a92de930c5 100644 --- a/packages/cli/src/commands/handlers/service/restart.ts +++ b/packages/cli/src/commands/handlers/service/restart.ts @@ -1,5 +1,5 @@ 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" @@ -7,8 +7,8 @@ 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) diff --git a/packages/cli/src/commands/handlers/service/start.ts b/packages/cli/src/commands/handlers/service/start.ts index 6adb647a02c6..1856fd8f85c0 100644 --- a/packages/cli/src/commands/handlers/service/start.ts +++ b/packages/cli/src/commands/handlers/service/start.ts @@ -1,5 +1,5 @@ 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" @@ -7,8 +7,9 @@ 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) }), ) diff --git a/packages/cli/src/server-process.ts b/packages/cli/src/server-process.ts index 1c40512d2724..6addeccd596d 100644 --- a/packages/cli/src/server-process.ts +++ b/packages/cli/src/server-process.ts @@ -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 ` and start the service again.", { cause: error }, ), diff --git a/packages/cli/src/services/port-owner.ts b/packages/cli/src/services/port-owner.ts index 539632e6d835..5474acde842a 100644 --- a/packages/cli/src/services/port-owner.ts +++ b/packages/cli/src/services/port-owner.ts @@ -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) => appProcess @@ -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 ` 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((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 diff --git a/packages/cli/src/services/service-config.ts b/packages/cli/src/services/service-config.ts index 483db314c400..39cba837f954 100644 --- a/packages/cli/src/services/service-config.ts +++ b/packages/cli/src/services/service-config.ts @@ -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)]), + ], } }) diff --git a/packages/cli/test/port-owner.test.ts b/packages/cli/test/port-owner.test.ts new file mode 100644 index 000000000000..ff0c0efa4a7f --- /dev/null +++ b/packages/cli/test/port-owner.test.ts @@ -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", + ) +}) diff --git a/packages/cli/test/service-lifecycle.test.ts b/packages/cli/test/service-lifecycle.test.ts index 4af0a73c03df..4870bfb9ba80 100644 --- a/packages/cli/test/service-lifecycle.test.ts +++ b/packages/cli/test/service-lifecycle.test.ts @@ -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 () => { @@ -175,10 +237,10 @@ serviceTest( type Home = Awaited> type Snapshot = Awaited> -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. @@ -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, ...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, ...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(), diff --git a/packages/gui-plugins/src/ssh/bootstrap.test.ts b/packages/gui-plugins/src/ssh/bootstrap.test.ts index 4e3a9cf1c64e..edb3b5cba0b3 100644 --- a/packages/gui-plugins/src/ssh/bootstrap.test.ts +++ b/packages/gui-plugins/src/ssh/bootstrap.test.ts @@ -1,7 +1,26 @@ import { expect, test } from "bun:test" -import { binaryPath, parseRegistration } from "./bootstrap" +import { NodeServices } from "@effect/platform-node" +import { Effect, Layer } from "effect" +import { FetchHttpClient } from "effect/http" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { testEffect } from "../../../core/test/lib/effect" +import { binaryPath, bootstrap, parseRegistration } from "./bootstrap" +import { parseTarget, sshFailureCode, SshFailure } from "./command" import { RemoteCli } from "./remote-cli" +const it = testEffect(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)) + +// The stand-in remote runs the bootstrap scripts with `sh`, so these cases need a POSIX shell. +const bootTest = process.platform === "win32" ? it.live.skip : it.live + +const VERSION = "2.0.26" + +const URL = "http://127.0.0.1:54321" + +const FIXED_URL = "http://127.0.0.1:49374" + test("ignores stopped services and registrations that do not match the healthy endpoint", () => { const registration = { url: "http://127.0.0.1:1234", password: "secret", version: "2.0.0", pid: 42 } const frame = `OPENCODE_SSH_REGISTRATION_BEGIN\n${JSON.stringify(registration)}\nOPENCODE_SSH_REGISTRATION_END\n` @@ -22,3 +41,162 @@ test("rejects unsafe versions and platforms in remote installation paths", () => expect(() => RemoteCli.installScript({ version: '2.0.0"; whoami', source: { type: "installer" } })).toThrow() expect(() => RemoteCli.archiveUrl("linux-x64;whoami", "2.0.0")).toThrow() }) + +test("keeps a remote command failure on its own step and OpenSSH failures as connections", () => { + expect(sshFailureCode(255, "service")).toBe("connection") + expect(sshFailureCode(1, "service")).toBe("service") + expect(sshFailureCode(1)).toBe("connection") +}) + +// A stand-in remote: `ssh` runs the script it receives, and the private CLI answers +// `--version`, `service status`, and `service start` the way the shipping CLI does. +async function remote(cli: string) { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "oc-ssh-bootstrap-")) + const bin = path.join(home, "bin") + + await fs.mkdir(bin, { recursive: true }) + await fs.mkdir(path.dirname(path.join(home, ".opencode/desktop-ssh", VERSION, "opencode")), { recursive: true }) + await fs.mkdir(path.join(home, ".local/state/opencode"), { recursive: true }) + await fs.writeFile(path.join(bin, "ssh"), "#!/bin/sh\nexec sh -s\n", { mode: 0o755 }) + await fs.writeFile(path.join(home, ".opencode/desktop-ssh", VERSION, "opencode"), `#!/bin/sh\n${cli}\n`, { + mode: 0o755, + }) + + return { + home, + env: { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}` }, + } +} + +const service = `case "$2" in + status) + if [ -f "$HOME/.local/state/opencode/service.json" ]; then printf '%s\\n' "${URL}"; else printf '%s\\n' stopped; fi + ;; + start|restart) + if [ "$3" = "--port" ] && [ "$4" = "0" ]; then + printf '%s' '{"url":"${URL}","password":"secret","version":"${VERSION}","pid":7}' > "$HOME/.local/state/opencode/service.json" + printf '%s\\n' "${URL}" + else + printf '%s\\n' "OPENCODE_SERVICE_PORT_OWNER=foreign" "Managed service port 49374 on 0.0.0.0 is already in use by another process." >&2 + exit 1 + fi + ;; + *) + if [ "$1" = "--version" ]; then printf '%s\\n' "${VERSION}"; fi + ;; +esac` + +const unavailable = `if [ "$2" = "start" ] || [ "$2" = "restart" ]; then + printf '%s\\n' "OPENCODE_SERVICE_PORT_OWNER=opencode" "OPENCODE_SERVICE_PORT_OWNER_PID=999999" "Managed service port 49374 on 0.0.0.0 is already in use by another process." >&2 + exit 1 +fi +if [ "$1" = "--version" ]; then printf '%s\\n' "${VERSION}"; else printf '%s\\n' stopped; fi` + +const reclaim = `case "$2" in + status) + if [ -f "$HOME/.local/state/opencode/restarted" ]; then printf '%s\\n' "${FIXED_URL}"; else printf '%s\\n' stopped; fi + ;; + start|restart) + if [ "$3" = "--port" ] && [ "$4" = "0" ]; then + printf '%s\\n' "Free-port fallback started a second service." >&2 + exit 1 + fi + if [ -f "$HOME/.local/state/opencode/restarted" ]; then + printf '%s' '{"url":"${FIXED_URL}","password":"secret","version":"${VERSION}","pid":7}' > "$HOME/.local/state/opencode/service.json" + printf '%s\\n' "${FIXED_URL}" + else + touch "$HOME/.local/state/opencode/restarted" + printf '%s\\n' "OPENCODE_SERVICE_PORT_OWNER=opencode" "OPENCODE_SERVICE_PORT_OWNER_PID=999999" "Managed service port 49374 on 0.0.0.0 is already in use by another process." >&2 + exit 1 + fi + ;; + *) + if [ "$1" = "--version" ]; then printf '%s\\n' "${VERSION}"; fi + ;; +esac` + +bootTest( + "starts on a free port when the managed port is already taken", + Effect.gen(function* () { + const machine = yield* Effect.promise(() => remote(service)) + + try { + const endpoint = yield* bootstrap({ target: parseTarget("devbox"), version: VERSION, env: machine.env }) + expect(endpoint).toEqual({ host: "127.0.0.1", port: 54321, password: "secret" }) + } finally { + yield* Effect.promise(() => fs.rm(machine.home, { recursive: true, force: true })) + } + }), +) + +const foreignProfile = `case "$2" in + status) printf '%s\\n' stopped ;; + start|restart) + if [ "$3" = "--port" ]; then touch "$HOME/.local/state/opencode/free-port"; fi + printf '%s\\n' "OPENCODE_SERVICE_PORT_OWNER=opencode" "OPENCODE_SERVICE_PORT_OWNER_PID=999999" "Managed service port 49374 on 0.0.0.0 is already in use by another process." >&2 + exit 1 + ;; + *) + if [ "$1" = "--version" ]; then printf '%s\\n' "${VERSION}"; fi + ;; +esac` + +bootTest( + "restarts an OpenCode service that holds the managed port", + Effect.gen(function* () { + const machine = yield* Effect.promise(() => remote(reclaim)) + + try { + // An unhealthy service still leaves its registration, so the holder is this home's own. + yield* Effect.promise(() => + fs.writeFile( + path.join(machine.home, ".local/state/opencode/service.json"), + JSON.stringify({ url: FIXED_URL, password: "secret", version: VERSION, pid: 999999 }), + ), + ) + const endpoint = yield* bootstrap({ target: parseTarget("devbox"), version: VERSION, env: machine.env }) + expect(endpoint).toEqual({ host: "127.0.0.1", port: 49374, password: "secret" }) + } finally { + yield* Effect.promise(() => fs.rm(machine.home, { recursive: true, force: true })) + } + }), +) + +bootTest( + "reports an OpenCode service from another profile without touching it", + Effect.gen(function* () { + const machine = yield* Effect.promise(() => remote(foreignProfile)) + + try { + const error = yield* bootstrap({ target: parseTarget("devbox"), version: VERSION, env: machine.env }).pipe( + Effect.flip, + ) + + expect(error.code).toBe("service") + expect( + yield* Effect.promise(() => Bun.file(path.join(machine.home, ".local/state/opencode/free-port")).exists()), + ).toBe(false) + } finally { + yield* Effect.promise(() => fs.rm(machine.home, { recursive: true, force: true })) + } + }), +) + +bootTest( + "reports a remote start failure as a service error with its captured output", + Effect.gen(function* () { + const machine = yield* Effect.promise(() => remote(unavailable)) + + try { + const error = yield* bootstrap({ target: parseTarget("devbox"), version: VERSION, env: machine.env }).pipe( + Effect.flip, + ) + + expect(error).toBeInstanceOf(SshFailure) + expect(error.code).toBe("service") + expect(error.detail).toContain("already in use") + } finally { + yield* Effect.promise(() => fs.rm(machine.home, { recursive: true, force: true })) + } + }), +) diff --git a/packages/gui-plugins/src/ssh/bootstrap.ts b/packages/gui-plugins/src/ssh/bootstrap.ts index 7e38a0de574f..1ac2093483cf 100644 --- a/packages/gui-plugins/src/ssh/bootstrap.ts +++ b/packages/gui-plugins/src/ssh/bootstrap.ts @@ -16,15 +16,71 @@ for file in "\${XDG_STATE_HOME:-$HOME/.local/state}"/opencode/service*.json; do done ` -export const discoverScript = `set -eu +export function discoverScript(version: string) { + const own = binaryPath(version) + + return `set -eu ${RemoteCli.discoverScript({ fromPath: true, cache: { directory: ".opencode/desktop-ssh", prefix: "0.0.0-beta-" } })} +if [ -z "$cli" ] && [ -x "${own}" ]; then cli="${own}"; fi if [ -z "$cli" ]; then exit 0; fi ${registrationScript}` +} export function startScript(version: string, replace = false) { + const command = replace ? "restart" : "start" + + // A conflict keeps its fixed port when the holder is an OpenCode service recorded by + // a registration in this state directory, for example one left behind by a dropped + // connection: stop it and start again on the configured port. A foreign or absent + // listener (the default port sits inside the Linux ephemeral range) falls back to a + // free port. Any other OpenCode service belongs to another profile, so it is left + // untouched and the failure is reported. return `set -eu +export OPENCODE_SERVICE_PORT_OWNER_MARKER=1 cli="${binaryPath(version)}" -"$cli" service ${replace ? "restart" : "start"} +start() { "$cli" service ${command} "$@"; } +if ! output=$(start 2>&1); then + case "$output" in + *"OPENCODE_SERVICE_PORT_OWNER=opencode"*) + pid=$(printf '%s\\n' "$output" | sed -n 's/^OPENCODE_SERVICE_PORT_OWNER_PID=//p') + own= + for file in "\${XDG_STATE_HOME:-$HOME/.local/state}"/opencode/service*.json; do + if [ -f "$file" ] && grep -Eq "\\"pid\\"[[:space:]]*:[[:space:]]*$pid([^0-9]|$)" "$file"; then + own=1 + break + fi + done + if [ "$own" = 1 ]; then + verify=$(ps -o command= -p "$pid" 2>/dev/null || true) + case "$verify" in + *opencode*serve*--service*) + kill "$pid" 2>/dev/null || true + i=0 + while kill -0 "$pid" 2>/dev/null && [ "$i" -lt 5 ]; do + sleep 1 + i=$((i + 1)) + done + kill -9 "$pid" 2>/dev/null || true + ;; + esac + if ! retry=$(start 2>&1); then + printf '%s\\n%s\\n' "$output" "$retry" >&2 + exit 1 + fi + else + printf '%s\\n' "$output" >&2 + exit 1 + fi + ;; + *"OPENCODE_SERVICE_PORT_OWNER=foreign"*|*"OPENCODE_SERVICE_PORT_OWNER=none"*) + if ! retry=$(start --port 0 2>&1); then + printf '%s\\n%s\\n' "$output" "$retry" >&2 + exit 1 + fi + ;; + *) printf '%s\\n' "$output" >&2; exit 1 ;; + esac +fi ${registrationScript}` } @@ -80,14 +136,16 @@ export const bootstrap = Effect.fn("Ssh.bootstrap")(function* (input: { env: NodeJS.ProcessEnv replace?: boolean }) { - const run = (script: string) => + const run = (script: string, remoteFailure?: SshFailure["code"]) => runSsh({ args: [...sshArgs(input.target), input.target.host, "sh -l -s"], env: input.env, stdin: script, + remoteFailure, }) - const registered = parseRegistration(yield* run(discoverScript)) + const discover = yield* Effect.try({ try: () => discoverScript(input.version), catch: SshFailure.from }) + const registered = parseRegistration(yield* run(discover)) if (registered && (input.development || registered.version === input.version)) return yield* Effect.try({ @@ -108,7 +166,7 @@ export const bootstrap = Effect.fn("Ssh.bootstrap")(function* (input: { const setup = { version, directory: `.opencode/desktop-ssh/${version}` } if (!staged) { - const output = yield* run(RemoteCli.probeScript).pipe(Effect.mapError(() => new SshFailure("platform"))) + const output = yield* run(RemoteCli.probeScript, "platform") const target = output .split(/\r?\n/) @@ -146,7 +204,7 @@ export const bootstrap = Effect.fn("Ssh.bootstrap")(function* (input: { ) } - const registration = parseRegistration(yield* run(startScript(version, input.replace))) + const registration = parseRegistration(yield* run(startScript(version, input.replace), "service")) if (!registration) return yield* Effect.fail(new SshFailure("service")) diff --git a/packages/gui-plugins/src/ssh/command.ts b/packages/gui-plugins/src/ssh/command.ts index 05a1f0869217..bf286e92e475 100644 --- a/packages/gui-plugins/src/ssh/command.ts +++ b/packages/gui-plugins/src/ssh/command.ts @@ -181,6 +181,8 @@ export const runSsh = Effect.fn("Ssh.run")(function* (input: { env?: NodeJS.ProcessEnv stdin?: string | Uint8Array timeout?: number + /** The code reported when the remote command fails; OpenSSH's own failures stay `connection`. */ + remoteFailure?: SshFailure["code"] }) { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner @@ -226,12 +228,19 @@ export const runSsh = Effect.fn("Ssh.run")(function* (input: { ) if (output.code !== 0) - return yield* Effect.fail(new SshFailure("connection", commandFailureDetail(output.code, output))) + return yield* Effect.fail( + new SshFailure(sshFailureCode(output.code, input.remoteFailure), commandFailureDetail(output.code, output)), + ) return output.stdout }).pipe(Effect.scoped, Effect.timeout(input.timeout ?? 600_000), Effect.mapError(SshFailure.from)) }) +/** OpenSSH reserves 255 for its own failures; every other status came from the remote command. */ +export function sshFailureCode(code: number | null, remoteFailure: SshFailure["code"] = "connection") { + return code === 255 ? "connection" : remoteFailure +} + export function commandFailureDetail(code: number | null, output: { stdout: string; stderr: string }) { // The CLI may report failures on stdout. Never include its private bootstrap // response in diagnostic text, even if shutdown fails after printing it. diff --git a/packages/gui-plugins/src/ssh/dialog.stories.tsx b/packages/gui-plugins/src/ssh/dialog.stories.tsx index 376efa99532f..ac17b2119165 100644 --- a/packages/gui-plugins/src/ssh/dialog.stories.tsx +++ b/packages/gui-plugins/src/ssh/dialog.stories.tsx @@ -36,6 +36,16 @@ type FixtureState = { timer?: ReturnType } +const SERVICE_FAILURE = `Error: Server process exited with code 1 +Error: Managed service port 49374 on 0.0.0.0 is already in use by another process. Configure another port with \`opencode service set port \` and start the service again. + at (/repo/opencode/packages/cli/src/server-process.ts:180:19) { + [cause]: ServeError: + at onError (/repo/opencode/node_modules/@effect/platform-node/dist/NodeHttpServer.js:151:30) + at applyHandlers (node:events:64:20) + [cause]: Error: Failed to start server. Is port 49374 in use? + at serve (node:_http_server:438:35) +}` + function Fixture(props: { session?: boolean settings?: boolean @@ -45,6 +55,7 @@ function Fixture(props: { connectionDelay?: number initial?: "connecting" | "challenge" | "failure" | "required" responseDelay?: number + serviceFailure?: boolean }) { const state: FixtureState = { prompts: [], @@ -110,6 +121,8 @@ function Fixture(props: { if (props.incompatible === "version-mismatch") return update({ stage: "incompatible", error: "version" }) + if (props.serviceFailure) return update({ stage: "failed", error: "service", detail: SERVICE_FAILURE }) + if (props.initial === "failure" && state.before?.stage !== "failed") return update({ stage: "failed", error: "connection", detail: "Connection refused" }) nextChallenge() @@ -327,6 +340,8 @@ export const Confirmation = { render: () => } export const Failure = { render: () => } +export const FailureService = { render: () => } + export const AuthenticationFailureRetry = { render: () => } export const IncompatibleHost = { render: () => } diff --git a/packages/gui-plugins/src/ssh/dialog.tsx b/packages/gui-plugins/src/ssh/dialog.tsx index 3946cce5daa7..3673f0a7b82b 100644 --- a/packages/gui-plugins/src/ssh/dialog.tsx +++ b/packages/gui-plugins/src/ssh/dialog.tsx @@ -20,6 +20,22 @@ import type { SshController } from "./state" export { default as css } from "./ssh.css?inline" +/** The message lines of a failure; stack frames, cause braces, and machine markers hide the cause. */ +function failureSummary(detail: string) { + const lines = detail.split(/\r?\n/).filter((line) => line.trim()) + + const messages = lines.filter( + (line) => + line === line.trimStart() && + !/^OPENCODE_[A-Z_]+=/.test(line) && + !/^\[cause\]/.test(line) && + !/^Error: Server process exited with code \d+$/.test(line) && + !/^[}\])]+$/.test(line), + ) + + return (messages.length > 0 ? messages : lines).slice(0, 6).join("\n") +} + export function DialogSsh(props: { ssh: SshController config?: SshConfig @@ -53,6 +69,8 @@ export function DialogSsh(props: { ) const view = createMemo(() => viewSshDialog(dialogState(), snapshot())) + // The remote command's message, so an actionable cause is not hidden behind the error code. + const detail = createMemo(() => failureSummary(snapshot().item?.detail ?? "")) // One key per prompt, so typing a response never remounts and refocuses its field. const prompt = createMemo(() => view().prompt, undefined, { equals: (previous, next) => previous?.id === next?.id }) @@ -102,9 +120,18 @@ export function DialogSsh(props: { const ConnectionError = () => ( {(error) => ( - - {plugin.t(error())} - +
+ + {plugin.t(error())} + + + {(text) => ( +
+                {text()}
+              
+ )} +
+
)}
) diff --git a/packages/gui-plugins/src/ssh/ssh.css b/packages/gui-plugins/src/ssh/ssh.css index 7cf442eb2b76..9b6779985272 100644 --- a/packages/gui-plugins/src/ssh/ssh.css +++ b/packages/gui-plugins/src/ssh/ssh.css @@ -1,3 +1,14 @@ +.ssh-error-detail { + white-space: pre-wrap; + overflow-wrap: anywhere; + font-family: var(--font-family-mono); + font-size: 12px; + line-height: var(--line-height-compact); + max-height: 200px; + overflow: auto; + user-select: text; +} + /* The same rules as the app's server dialog in settings.css, which may not be loaded when the palette opens this one. */ [data-component="dialog-v2"].settings-server-dialog [data-slot="dialog-content"] { align-items: stretch; diff --git a/services/site/src/docs/content/cli/commands.mdx b/services/site/src/docs/content/cli/commands.mdx index 2b69c2a779f8..dbd165e89be4 100644 --- a/services/site/src/docs/content/cli/commands.mdx +++ b/services/site/src/docs/content/cli/commands.mdx @@ -440,7 +440,13 @@ Manages the background server. See [Web](/cli/web). $ opencode service start ``` -Restart it. +Use a different port for this run only. `0` asks the operating system for a free port; the saved setting stays the same. + +```bash +$ opencode service start --port 0 +``` + +Restart it. It accepts the same `--port` flag. ```bash $ opencode service restart