Skip to content

feat(ssh): plain SSH terminals and SFTP browsing when no Orca runtime can run - #24147

Merged
OrcaWin merged 3 commits into
mainfrom
OrcaWin/node-rt-p2-plainssh
Oct 1, 2026
Merged

OrcaWin merged 3 commits into
mainfrom
OrcaWin/node-rt-p2-plainssh

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​822 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​822
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​992 $\color{#cf222e}{\Huge{\mathbf{−}}}$​10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​982

ELI5

When no Orca runtime can run on a host (for example, the home directory is mounted noexec), Orca now still connects. You get plain SSH terminals and SFTP file browsing, with the reason shown, instead of a failed connection.

What Changed

  • ssh-plain-shell-pty-provider.ts: each terminal is an ssh2 session channel with pty-req and shell. Resize uses setWindow, output is decoded as UTF-8, and cwd is applied with cd.
    • A shell counts as exited only after the host sends an exit status. Transport loss makes it unverifiable.
    • Reattaching starts a fresh shell and reports the old session as expired.
  • ssh-sftp-filesystem-provider.ts (SFTP only): list, stat, read, write, rename, delete and download.
  • Unavailable in plain mode: git, search, quick open, the watcher, copy and recursive delete. Each refuses with the classified reason.
  • Connect flow: when the ladder ends at rung D, the session enters plain mode. The target card and the terminal show the reason.
  • Fixed in review:
    • A reconnect race when the connection is stale.
    • Waking from sleep no longer reconnects forever.
    • ~/ paths now expand in cd.
    • Folder download now works in plain mode.

Why

Design D6: "degraded, not dead". A hardened host should still give you a shell.

Linked Issue

Part of the Node runtime plan (Phase 2). Stacked on OrcaWin/node-rt-p2-integration.

Visual Proof

To add: a screenshot of the target card showing the plain-mode reason, and of a plain terminal. The existing e2e harness can capture these.

Testing

  • Unit tests cover the shell provider (exit, unverifiable, resize, UTF-8 split across chunks, cwd), the SFTP provider, and the session mode switch.

  • Not done:

    • Hosts reached through system SSH (no ssh2) still fail at rung D.
    • Plain terminals don't persist across reconnects.
    • The reason isn't yet shown in the sidebar, composer or reconnect overlay.
    • Windows hosts in plain mode don't apply cwd.
  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 3/5

[Critical risk] Replaces the Bun runtime with Node and adds SSH terminal support.

The PR does not appear safe to merge while SFTP-restricted hosts can lose relay installation and plain-mode resume can still close working shells.

Findings

  1. P1 SFTP failure closes working shells. ▶
  2. P2 File reads ignore caller limits. ▶
  3. P2 Signal exits report wrong code. ▶

Summary

The PR adds plain SSH terminals and SFTP browsing when the remote runtime ladder is exhausted. Changes since the prior review also alter remote runtime installation and cleanup, relay assignment and drain handling, and mobile navigation and release workflows.

  • Plain SSH mode registers terminal and filesystem providers while reporting why the runtime is unavailable.
  • The recent removal of the exec-stdin upload fallback breaks installation on some SFTP-restricted hosts; removed stale-stage cleanup can leave remote upload archives behind.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[SSH connection] --> B{Runtime ladder succeeds?}
  B -->|Yes| C[Orca relay session]
  B -->|No: classified runtime refusal| D[Plain SSH session]
  D --> E[SSH shell channels]
  D --> F[SFTP filesystem provider]
  A --> G[Relay install transfer]
  G --> H{SFTP available?}
  H -->|Yes| C
  H -->|No| I[Installation error]
Loading

Reviews (3) · Last reviewed commit: "docs(ssh): rung D now means plain SSH mo..."

Comment on lines +121 to +126
return await Promise.race([
this.realpath('.').then(
() => true,
() => false
),
timeout

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 SFTP failure closes working shells. If a host allows SSH shells but has no SFTP subsystem, plain mode can connect, yet every resume probe fails because it checks only SFTP. After two failures, the resume handler reconnects the SSH transport and ends working shells. An unavailable SFTP subsystem should not be treated as proof that the SSH connection has died.

Comment on lines +180 to +192
async readFile(filePath: string, _limits?: FileReadLimits): Promise<FileReadResult> {
const path = toSftpPath(filePath)
return this.run(async (sftp) => {
const stats = await statViaSftp(sftp, path)
const mimeType = PREVIEW_MIME_TYPES[extname(filePath).toLowerCase()]
const sizeLimit = mimeType ? MAX_PREVIEWABLE_BINARY_SIZE : MAX_TEXT_FILE_SIZE
if (stats.size > sizeLimit) {
throw new Error(
`File too large: ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds ${sizeLimit / 1024 / 1024}MB limit`
)
}
const buffer = await new Promise<Buffer>((resolve, reject) =>
sftp.readFile(path, (err, data) => (err ? reject(err) : resolve(data)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 File reads ignore caller limits. The file-explorer preview requests a 512 KB text limit, but this provider ignores it and can transfer and buffer a 5 MB text file before the caller rejects it. Enforcing the supplied limit before reading would avoid that unnecessary transfer and allocation.

Comment on lines +125 to +127
shell.channel.on('exit', (code: number | null) => {
shell.exitCode = typeof code === 'number' ? code : SIGNALLED_EXIT_CODE
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Signal exits report wrong code. Every shell terminated by a remote signal is reported with exit code 129. For example, SIGTERM is shown as 129 rather than 143, so terminal consumers receive an incorrect termination result. Use the signal supplied by the channel’s exit event to determine the code.

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

Important

Two filesystem methods diverge from the relay provider they stand in for: createDir is neither recursive nor idempotent, and non-append base64 writes truncate instead of creating exclusively. Both break real plain-mode flows.

Reviewed changes

  • Plain SSH PTY provider — one ssh2 shell channel per terminal with pty-req, UTF-8-decoded output, resize, POSIX cd, and an exited-vs-unverifiable verdict; reattach starts a fresh shell.
  • SFTP filesystem provider — read/list/stat/write/rename/delete/download over one reused channel; relay-only features refuse with the classified reason.
  • Plain-mode session wiring — SshPlainSshModeSession registers the providers and feeds output/exit through the existing intake; SshRelaySession falls back at rung D and clears the mode on teardown.
  • Connect / sleep handling — a live plain session is treated as a refresh, and host resume probes the SFTP transport before reconnecting.
  • Surface — plainSsh on SshConnectionState, field-by-field admission, and the target card label + reason.

ℹ️ Nitpicks

  • SshSftpFilesystemProvider.readFile ignores its limits argument and uses hardcoded 10/50 MB caps, throwing a generic Error rather than FileReadCapExceededError (src/main/providers/ssh-sftp-filesystem-provider.ts:180). The callers I traced re-check size, so impact is contained, but it is not contract-faithful to the relay reader.
  • SshPlainSshModeSession.leave() clears the module-global plain mode unconditionally, while the provider unregistrations directly below it are identity-guarded (src/main/ssh/ssh-plain-ssh-session.ts:112). I could not construct an interleaving that reaches it today, but clearing only when getSshPlainSshMode(targetId) === this.mode would remove the asymmetry.
  • SshPlainShellPtyProvider.spawn re-checks this.disposed but not opts.signal?.aborted after openShell resolves (src/main/providers/ssh-plain-shell-pty-provider.ts:86-90), so a spawn cancelled while the channel opens still registers a live shell.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +295 to +297
async createDir(dirPath: string): Promise<void> {
await this.call((sftp, cb) => sftp.mkdir(toSftpPath(dirPath), cb))
}

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.

createDir is neither recursive nor idempotent, unlike the relay path it replaces: createRelayDir runs mkdir(dirPath, { recursive: true }), and callers invoke createDir unconditionally on directories that commonly already exist. On a plain-SSH target where .orca is present, sftp.mkdir returns SFTP Failure and the flow fails with a raw error.

Technical details
# `createDir` must match `mkdir -p` semantics

## Affected sites
- `src/main/providers/ssh-sftp-filesystem-provider.ts:295-297` — single non-recursive `sftp.mkdir`, fails when the path or a parent is missing/exists
- `src/main/runtime/runtime-repository-issue-command.ts:90` — `createDir(joinWorktreeRelativePath(repo.path, '.orca'))`, unconditional
- `src/main/ipc/hooks/register-worktree-hook-file-handlers.ts:115` — same unconditional `.orca` create
- `src/main/ipc/filesystem-import-ssh.ts:262,270`, `src/main/ipc/repos/remote-repo-clone.ts:85`, `src/main/ipc/worktree-remote.ts:1498` — same pattern
- `src/relay/fs-path-mutation-requests.ts:49-52` — relay equivalent is idempotent and recursive

## Required outcome
- `createDir` succeeds when the directory (and parents) already exist.
- `createDirNoClobber` (`:299-301`) keeps fail-on-exists semantics, so it must no longer delegate to the idempotent `createDir`.

## Suggested approach
- SFTP has no recursive MKDIR: walk the path components and `mkdir` each, swallowing `SSH_FX_FAILURE`/already-exists for the created ancestors (or the final component for `createDir`). Keep `createDirNoClobber` on a plain single `sftp.mkdir`.

## Open questions for the human
- `filesystem-mutations.ts:77` (user "New Folder") currently inherits relay's silent success on an existing dir; confirm the intended error behavior once `createDir` is idempotent.

Comment on lines +229 to +238
async writeFileBase64Chunk(
filePath: string,
contentBase64: string,
append: boolean
): Promise<void> {
const data = Buffer.from(contentBase64, 'base64')
const path = toSftpPath(filePath)
await this.call((sftp, cb) =>
append ? sftp.appendFile(path, data, cb) : sftp.writeFile(path, data, cb)
)

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.

Non-append chunks are written with sftp.writeFile, which truncates/creates, but both peer implementations create exclusively when !append: the relay path passes exclusive: !append to uploadBuffer (flags 'wx'), and the local runtime uses flag: 'wx'. Plain mode therefore silently overwrites an existing remote file where relay/local refuse, and writeFileBase64 (:224-227) inherits this.

Technical details
# Non-append base64 writes must create exclusively

## Affected sites
- `src/main/providers/ssh-sftp-filesystem-provider.ts:224-227` — `writeFileBase64` calls `sftp.writeFile`
- `src/main/providers/ssh-sftp-filesystem-provider.ts:229-238` — non-append branch uses `sftp.writeFile`
- `src/main/providers/ssh-filesystem-provider.ts:196-216` — relay uses `uploadBuffer(..., { append, exclusive: !append })`
- `src/main/ssh/sftp-upload.ts:127-128` — `exclusive ? 'wx' : 'w'`
- `src/main/runtime/runtime-file-commands-write-file-explorer-file.ts:104` — local uses `flag: append ? 'a' : 'wx'`

## Required outcome
- A non-append write must fail (as `EEXIST`) rather than clobber an existing path, matching relay and local behavior.

## Suggested approach
- For `append === false`, `sftp.open(path, 'wx', ...)` then write/close (or a create-write-stream with `flags: 'wx'`); for `append === true` keep `appendFile`.

Comment on lines +125 to +127
shell.channel.on('exit', (code: number | null) => {
shell.exitCode = typeof code === 'number' ? code : SIGNALLED_EXIT_CODE
})

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 exit handler reads only code and reports 129 for every signalled shell, but ssh2 emits 'exit' as (null, 'SIG<name>', coreDumped, message) on exit-signal (node_modules/ssh2/lib/client.js:673-678). A SIGINT-killed shell should surface as 130, SIGTERM as 143, etc., so this misreports the termination and contradicts the 128+n comment on line 33-34.

Technical details
# Map signalled exits to their real code

## Affected sites
- `src/main/providers/ssh-plain-shell-pty-provider.ts:34` — single `SIGNALLED_EXIT_CODE = 129`
- `src/main/providers/ssh-plain-shell-pty-provider.ts:125-127` — handler discards the signal argument
- `node_modules/ssh2/lib/client.js:673-678` — exit-signal emits `(null, 'SIG<name>', ...)`

## Required outcome
- Report `128 + signo` for the common signals (`SIGHUP` 129, `SIGINT` 130, `SIGQUIT` 131, `SIGABRT` 134, `SIGKILL` 137, `SIGTERM` 143), or a single explicit "signalled" sentinel if the code cannot be derived — never a fabricated 129.

## Suggested approach
- Change the signature to `(code: number | null, signal: string | null)` and map `signal` through a small `SIGNAL_EXIT_CODES` record; fall back to a sentinel for unknown signals.

m4air added 2 commits October 1, 2026 02:36
…the host

Runtime ladder rung D (design D6): instead of failing the connect, register an
ssh2 shell-channel PTY provider and an SFTP-only filesystem provider and publish
the classified reason on the SSH connection state.
…and tilde cwd

- Only the current connect or reconnect attempt may enter plain SSH mode; a superseded
  reconnect whose ladder ends at rung D no longer registers a second provider set.
- Host-sleep resume probes a plain session over SFTP instead of always reconnecting,
  which ended every open plain shell.
- A home-relative cwd keeps its tilde outside the quotes so the shell expands it.
- The SFTP provider implements folder download, which the connect state advertises.
@OrcaWin
OrcaWin force-pushed the OrcaWin/node-rt-p2-plainssh branch from 69a9da6 to 638902a Compare October 1, 2026 09:37
@OrcaWin
OrcaWin changed the base branch from OrcaWin/node-rt-p2-integration to main October 1, 2026 09:40
@OrcaWin OrcaWin closed this Oct 1, 2026
@OrcaWin OrcaWin reopened this Oct 1, 2026
@greptile-apps

greptile-apps Bot commented Oct 1, 2026

Copy link
Copy Markdown

Comments Outside Diff

These findings could not be posted inline.

  • P2 Interrupted uploads accumulate src/main/ssh/remote-node-runtime-store-gc.ts:145 ▶

    Interrupted uploads accumulate. Runtime collection no longer sweeps stale .stage-node-* directories, while an unconfirmed pinned-Node transfer deliberately leaves its stage behind. Repeated interrupted uploads can therefore leave archives on remote hosts indefinitely, consuming disk space until someone removes them.

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

ℹ️ No new issues in this commit set — the plain-SSH hardening is clean and well covered. This is not an approval: the three earlier review threads on createDir, non-append base64 writes and the signalled-exit code are unchanged here and remain open.

Reviewed changes

This run re-reviewed the delta since the prior pullfrog review. The branch was rebased, so the previously reviewed feature commit now appears as 746a563120 (same content) and the new work is the hardening commit 638902aa.

  • Only the current attempt enters plain SSH — deployRelayOrEnterPlainSsh now takes an isAttemptCurrent predicate; establish passes _state === 'deploying' and reconnect passes its AbortController identity, so a superseded reconnect that ends at rung D rethrows instead of registering a second provider set.
  • Host-sleep resume probes the plain transport — isRelayLinkAliveAfterResume asks SshPlainSshModeSession.probeTransport (one SFTP realpath('.') round trip per attempt, two attempts) instead of treating the absent mux as dead, so waking from sleep no longer tears down every open plain shell.
  • Home-relative cd expands — posixCdTarget leaves the leading ~ outside the quotes (~ → ~, ~/x → ~/'x') so the shell expands it, while absolute paths stay fully quoted.
  • Folder download in plain mode — SshSftpFilesystemProvider.downloadFolder delegates to downloadFolderViaSftp with the host's windowsRemotePaths, matching the relay provider it stands in for.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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.

1 participant