Skip to content

fix(desktop): ssh recover when the remote service port is taken - #63542

Open
ai-nikolai wants to merge 8 commits into
anomalyco:devfrom
ai-nikolai:ssh-reconnect-port
Open

ai-nikolai wants to merge 8 commits into
anomalyco:devfrom
ai-nikolai:ssh-reconnect-port

Conversation

@ai-nikolai

@ai-nikolai ai-nikolai commented Nov 12, 2026 •

Copy link
Copy Markdown

Issue for this PR

Closes #54059

Type of change

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

What does this PR do?

After the SSH connection dropped, reconnecting could fail with "Could not establish the SSH connection" even when SSH itself was working. The remote opencode service start failure was being reported as an SSH transport failure, and the managed port (49374 by default) can be occupied by an unrelated process because it sits inside the Linux ephemeral port range.

Changes:

  • Remote command failures now keep their own step (service, platform, install, …). OpenSSH's reserved exit code 255 still maps to connection, so real transport failures are unchanged.
  • The remote start script retries service start/service restart once with --port 0 when the CLI reports the port is already in use. The registration file then records the actual URL, so discovery and the tunnel continue to work.
  • opencode service start/restart accepts --port as a one-off override (0 = OS-chosen). It does not modify the saved port setting.
  • The SSH dialog now shows the remote command's captured stderr under the error, so the cause is visible instead of only the generic message.

I chose to move the remote server to a free port rather than reuse the occupied one because the process holding the port does not belong to OpenCode.

How did you verify your code works?

  • bun run check
  • bun test src/ssh in packages/gui-plugins — 55 pass
  • bun test test/service-lifecycle.test.ts test/service.test.ts in packages/cli — 37 pass. The new lifecycle test occupies the configured port, confirms service start fails with "already in use", then confirms service start --port 0 registers and serves on a different port.
  • ssh-reconnect.spec.ts component tests — 8 pass. The new dialog test fails when the detail rendering is reverted.
  • bun run lint:changed

Screenshots / recordings

No screenshot present of the fix.

Checklist

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

Added by the opencode bot (AI-generated).

Related: #62891, #50672, #54267, #56708

Public API: adds an optional --port flag to opencode service start/restart and an opt-in OPENCODE_SERVICE_PORT_OWNER_MARKER env var (backwards compatible)

@opencodejr opencodejr 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 change fixes the reported problem. I checked it with a version of the #54059 reproduction: a stand-in ssh, the source CLI staged where Desktop installs it, and the managed port held by an unrelated socket. On the base, bootstrap() fails with connection and the real cause is only in the hidden detail. With this PR it succeeds on an OS-chosen port. bun test src/ssh passes (55). The new lifecycle test's port-override assertions pass, but its stopped() cleanup step fails in my sandbox, and an existing lifecycle test fails the same way, so that looks environmental.

Public API: adds an optional --port <0-65535> flag to opencode service start and opencode service restart (documented). This is backwards compatible: without the flag the behaviour is unchanged and the saved port setting is never modified.

Concerns (details inline):

  • The --port 0 fallback runs whenever the CLI says the port is in use, including when the holder is an orphaned or unregistered OpenCode service, so two services could end up running against the same data.
  • The dialog now shows the CLI's full stack trace.
  • discoverScript now also falls back to the binary Desktop installed on the remote (~/.opencode/desktop-ssh/<version>/opencode). This looks reasonable for reconnecting, but the description doesn't mention it. Please add it so reviewers know it's intended.

The dialog change is only visible in the desktop app. Could you attach before/after screenshots of the SSH dialog with this error?

Related: #62891, #50672, #54267, #59610

"$cli" service ${replace ? "restart" : "start"}
if ! output=$("$cli" service ${command} 2>&1); then
case "$output" in
*"already in use"*)

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 retries on any "already in use", but the CLI error names the owner (PortOwner.describe), and the holder can be OpenCode itself. The reconnect case in #54059's comments is like that: a previous service that is orphaned, or registered under another state dir (see #54267 / #56708). In that case --port 0 starts a second service with the same database and config while the old one keeps running, and nothing cleans that up later. Could the fallback be limited to holders that aren't OpenCode? Alternatively, the CLI could signal the condition in a structured way (e.g. a distinct exit code) instead of the script matching the English message text.

Comment thread packages/gui-plugins/src/ssh/dialog.tsx Outdated
</span>
<Show when={detail()}>
{(text) => (
<pre class="ssh-prompt" dir="auto">

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.

detail is the raw output from commandFailureDetail. For this failure it includes the CLI's whole stack trace: at <anonymous> (.../server-process.ts:180:19), nested [cause] blocks, and node internals, about 20 lines. Shown as-is in the dialog, that hides the one useful line. Consider showing just the Error: lines, or keeping the full text behind a collapsed or copyable section.

@opencodejr opencodejr 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 new commit addresses both earlier points. The bootstrap now acts on a structured OPENCODE_SERVICE_PORT_OWNER marker instead of the English message, and --port 0 is only used for foreign or absent listeners. The dialog now shows only the message lines. I re-ran the #54059 repro with the port number taken but not listening: bootstrap now succeeds on a free port. With a real listener and no lsof (as in my sandbox, and on many minimal servers) the owner is unknown, so the failure is reported as a service error rather than recovered. bun test src/ssh (56) and test/port-owner.test.ts (3) pass.

Public API: unchanged since the last review apart from the stderr marker below. The --port flag on service start / service restart is still backwards compatible.

New concerns (inline): the start script now kills an OpenCode service that isn't this home's registered one, and the machine marker is printed in user-facing CLI/TUI errors.

start() { "$cli" service ${command} "$@"; }
if ! output=$(start 2>&1); then
case "$output" in
*"OPENCODE_SERVICE_PORT_OWNER=opencode"*)

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.

By the time this branch runs, Service.ensure has already decided the holder is not the service registered in this state directory (it found no healthy incumbent at the configured URL for about 15s). So an opencode serve --service here is a live service from another profile or XDG_STATE_HOME (#56708, #58141), or one that is stalled but still working (#54181). The script stops it, then sends kill -9 after 5s, and that service's sessions and running tools are cut off without warning. Please only stop it when it is clearly this home's own leftover, e.g. the PID recorded in this home's registration file. Otherwise report the conflict (or fall back to a free port) instead of killing it.

Comment thread packages/cli/src/server-process.ts Outdated
const owner = port === undefined ? { kind: "unknown" as const } : yield* PortOwner.inspect(port, hostname)
// The SSH bootstrap reads this marker to decide whether a free port is safe. Keep it
// separate from the message, which stays readable for CLI users.
yield* Effect.sync(() => process.stderr.write(PortOwner.marker(owner) + "\n"))

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 marker goes to the server's stderr on every port conflict, not only for the SSH bootstrap. Service.ensure surfaces that stderr, so CLI and TUI users now see OPENCODE_SERVICE_PORT_OWNER=unknown between Server process exited with code 1 and the real message (I reproduced this with opencode service start). Could it only be printed when the caller asks for it, e.g. through an env var the start script sets, or could the client strip it before showing the error?

@ai-nikolai

Copy link
Copy Markdown
Author

Issue for this PR

Closes #54059

Type of change

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

What does this PR do?

After the SSH connection dropped, reconnecting could fail with "Could not establish the SSH connection" even when SSH itself was working. The remote opencode service start failure was reported as an SSH transport failure, and the managed port (49374 by default) can be occupied by an unrelated process because it sits inside the Linux ephemeral port range.

Changes:

  • Remote command failures now keep their own step (service, platform, install, …). OpenSSH's reserved exit code 255 still maps to connection.
  • The CLI writes stable owner markers on a port conflict. The SSH bootstrap then:
    • stops an orphaned OpenCode service after verifying its command line and restarts it on the configured fixed port;
    • falls back to a free port only when the holder is foreign or absent;
    • reports the failure without starting a second service when the holder cannot be identified.
  • opencode service start/restart accepts --port as a one-off override (0 = OS-chosen). It does not modify the saved port setting.
  • The SSH dialog shows the remote command's message lines under the error, without the CLI stack trace.
  • Discovery also checks the exact private binary Desktop installed for this version, so a reconnect finds it without relying only on 0.0.0-beta-* cache entries.

I picked the fixed-port restart for OpenCode holders because a second service would share the same database and config while the old one keeps running. Foreign holders cannot be reclaimed, so those move to a free port and the registration records the address.

How did you verify your code works?

  • bun run check
  • bun run lint:changed
  • bun test src/ssh in packages/gui-plugins — 56 pass
  • bun test test/port-owner.test.ts test/service.test.ts in packages/cli — 32 pass
  • bun test test/service-lifecycle.test.ts in packages/cli — 8 pass
  • ssh-reconnect.spec.ts component tests — 9 pass; the new dialog test fails when the detail rendering is reverted
  • The bootstrap suite covers the occupied-port fallback and the fixed-port OpenCode restart with a stand-in ssh

Screenshots / recordings

Before: only the generic connection error.
ssh-dialog-before

After: the failing step is identified and the remote cause is shown.
ssh-dialog-after

Checklist

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

@opencodejr opencodejr 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.

This push only adds a CLI lifecycle test, so the two open threads still stand. The test shows that a plain opencode service start leaves another home's OpenCode service running. The kill in question is done by the SSH start script in bootstrap.ts, which still stops that service and sends kill -9 after 5s when it sees OPENCODE_SERVICE_PORT_OWNER=opencode. So the test's name describes the CLI behaviour, not what the Desktop SSH flow does. The test's regex also expects the marker in the error that service start shows users, so it locks in that behaviour; if that changes, the assertion will need to change too.

Public API: unchanged by this push. The PR still adds an optional --port flag to service start / service restart (backwards compatible).

@opencodejr opencodejr 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.

This push is a rebase onto newer dev. The SSH bootstrap, CLI and test changes are the same as before, so the two open threads still apply. The only real change is in the dialog: the error detail now sits in dev's new ConnectionError block, styled by its own .ssh-error-detail, and it still shows only the message lines. I re-ran the #54059 reproduction (port number taken, nothing listening): it still recovers on a free port, and bun test src/ssh passes (56).

Public API: unchanged by this push; the PR still adds an optional --port flag to service start / service restart (backwards compatible).

Because the dialog layout moved, before/after screenshots of the SSH dialog with a service failure would help, since I can't run the desktop app here.

@ai-nikolai

Copy link
Copy Markdown
Author

New screenshots:
ssh-dialog-after
ssh-dialog-before

@ai-nikolai

Copy link
Copy Markdown
Author

Issue for this PR

Closes #54059

Type of change

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

What does this PR do?

After the SSH connection dropped, reconnecting could fail with "Could not establish the SSH connection" even though SSH was working. Remote opencode service start failures were reported as SSH transport errors, and the managed port (49374 by default) can be held by an unrelated process because it sits inside the Linux ephemeral port range.

Changes:

  • Remote command failures keep their own step (service, platform, install, …). OpenSSH's reserved exit code 255 stays connection.
  • On a port conflict, the CLI emits owner markers only when the SSH start script asks for them (OPENCODE_SERVICE_PORT_OWNER_MARKER=1), so normal CLI/TUI output is unchanged.
  • The start script stops and restarts on the fixed port only when the holder PID is recorded by a registration in this state directory. An OpenCode service from another profile is left running and the conflict is reported. A foreign or absent listener falls back to a free port, recorded in the registration.
  • opencode service start/restart accepts --port as a one-off override (0 = OS-chosen). It does not modify the saved port setting.
  • The SSH dialog shows the remote command's message lines under the error, without the CLI stack trace.
  • Discovery also checks the exact private binary Desktop installed for this version, so a reconnect finds it without relying only on 0.0.0-beta-* cache entries.

I did not stop another profile's service because that would cut off its sessions and running tools. I also avoided starting a second service against the same data.

How did you verify your code works?

  • bun run check
  • bun run lint:changed
  • bun test src/ssh in packages/gui-plugins — 57 pass
  • bun test test/service-lifecycle.test.ts in packages/cli — 9 pass; covers marker-off and marker-on failures, the free-port override, and another OpenCode service owning the port
  • bun test test/port-owner.test.ts in packages/cli — 3 pass
  • ssh-reconnect.spec.ts component tests (cold cache) — 9 pass; the dialog test fails when the detail rendering is reverted

Screenshots / recordings

Before: generic connection error, no remote cause.

After: the failing step plus the actionable remote message.

Checklist

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

@ai-nikolai

Copy link
Copy Markdown
Author

@Hona @Brendonovich - please approve checks for this PR.

@opencodejr opencodejr 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.

Both remaining points are addressed. The start script now only stops an OpenCode holder whose PID is recorded in a registration in this state directory. Another profile's service is left alone and the failure is reported, and the new bootstrap test covers that. The OPENCODE_SERVICE_PORT_OWNER marker is only printed when OPENCODE_SERVICE_PORT_OWNER_MARKER=1 is set, which only the SSH start script does, so plain CLI/TUI errors no longer contain it. I re-ran the #54059 reproduction (port number taken, nothing listening): it still recovers on a free port, and bun test src/ssh (57) and test/port-owner.test.ts (3) pass.

Public API: adds an optional --port flag to opencode service start / opencode service restart, and an internal opt-in env var OPENCODE_SERVICE_PORT_OWNER_MARKER that adds machine-readable lines to stderr on a port conflict. Both are backwards compatible.

No new concerns. Before/after screenshots of the SSH dialog with a service failure would still help, since I can't run the desktop app here.

@ai-nikolai

Copy link
Copy Markdown
Author

@Hona @Brendonovich - PR seems to be clean to merge.

@opencodejr opencodejr 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.

This push only merges dev; the PR's own changes are identical to the previous head. bun test src/ssh still passes, and the #54059 reproduction (port number taken, nothing listening) still recovers on a free port. No new concerns.

Public API: adds an optional --port flag to opencode service start / opencode service restart, and an opt-in OPENCODE_SERVICE_PORT_OWNER_MARKER env var used by the SSH start script. Both are backwards compatible.

Before/after screenshots of the SSH dialog with a service failure would still help, since I can't run the desktop app here.

@opencodejr opencodejr 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.

This push only merges dev; the PR's own changes are identical to the previous head. bun test src/ssh still passes, and the #54059 reproduction (port number taken, nothing listening) still recovers on a free port. No new concerns.

Public API: adds an optional --port flag to opencode service start / opencode service restart, and an opt-in OPENCODE_SERVICE_PORT_OWNER_MARKER env var used by the SSH start script. Both are backwards compatible.

Before/after screenshots of the SSH dialog with a service failure would still help, since I can't run the desktop app here.

@ai-nikolai

Copy link
Copy Markdown
Author

@palmamartin

@opencodejr opencodejr 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.

This push only merges dev; the PR's own changes are identical to the previous head. bun test src/ssh still passes, and the #54059 reproduction (port number taken, nothing listening) still recovers on a free port. No new concerns.

Public API: adds an optional --port flag to opencode service start / opencode service restart, and an opt-in OPENCODE_SERVICE_PORT_OWNER_MARKER env var used by the SSH start script. Both are backwards compatible.

Before/after screenshots of the SSH dialog with a service failure would still help, since I can't run the desktop app here.

@ai-nikolai

Copy link
Copy Markdown
Author

@Hona @Brendonovich

@ai-nikolai ai-nikolai changed the title fix(ssh): recover when the remote service port is taken fix(desktop): ssh recover when the remote service port is taken Nov 17, 2026

@opencodejr opencodejr 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.

This push only merges dev; the PR's own changes are identical to the previous head. bun test src/ssh still passes, and the #54059 reproduction (port number taken, nothing listening) still recovers on a free port. All four earlier review points are addressed by the code as it stands (structured owner marker, trimmed dialog detail, reclaiming only this profile's registered service, marker gated behind an opt-in env var). No new concerns.

Public API: adds an optional --port flag to opencode service start / opencode service restart, and an opt-in OPENCODE_SERVICE_PORT_OWNER_MARKER env var used by the SSH start script. Both are backwards compatible.

Before/after screenshots of the SSH dialog with a service failure would still help, since I can't run the desktop app here.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

desktop: SSH remote service start failure reported as "failed to establish SSH connection"

1 participant