Skip to content

feat(wsl): orcad host transport over wsl.exe (WSL-via-orcad C1) - #27792

Merged
nwparker merged 2 commits into
mainfrom
nwparker/wsl-c1-wsl-orcad-host-transport
Oct 13, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/wsl-c1-wsl-orcad-host-transport

Conversation

@nwparker

@nwparker nwparker commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​313 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​313
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​468 $\color{#cf222e}{\Huge{\mathbf{−}}}$​52 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​416

ELI5

Orca can already install and run its background server (orcad) on SSH machines. This PR adds the piece that lets the same install code reach a WSL Linux distro on the same Windows PC. It runs commands with wsl.exe and copies files in. Nothing calls it yet.

What Changed

  • New WslOrcadHostTransport (src/main/wsl/wsl-orcad-host-transport.ts). It implements the same OrcadHostTransport contract that SSH connections implement:
    • exec(command) starts %SystemRoot%\System32\wsl.exe -d <distro> --exec sh -c <command> through @orca/process-host (hidden window, no shell). It uses the absolute wsl.exe path, buildWslExecArgs, and WSL_UTF8=1.
    • The child process is wrapped as a RemoteCommandChannel (wsl-command-channel.ts). Reading the channel gives stdout and writing it feeds stdin, with backpressure. exit is always emitted before close. close() kills wsl.exe, and on a real host that also ends the Linux process.
    • Like SSH channel open, an already-aborted signal or a wsl.exe that fails to start rejects exec itself. Mid-run aborts work the same as on SSH: execCommand calls close().
    • No login shell runs between wsl.exe and sh -c, so stdout carries no banner. execCommand's usual fence still applies.
    • writeFile reuses the existing exec-stdin writer (writeStringViaExecStdin). It writes a partial file, checks the byte count, then renames it into place.
    • uploadDirectory (wsl-directory-upload.ts) has two ways in:
      • If the source is on a drive letter (C:\... becomes /mnt/c/...), or is a \\wsl.localhost\<same distro>\ path, the distro copies it directly with cp -R into a hidden stage directory inside the destination.
      • If the source has no mount, or /mnt is missing (for example automount is off), Orca streams a tar over stdin into the same stage.
      • Either way, the staged files are checked against SHA-256 digests computed on the Windows side. They are then renamed into place one at a time, under flock when it exists, and the stage is removed.
      • Executable modes are kept. On Windows every file gets 0755, which is what a /mnt copy produces anyway.
    • usesSystemSshTransport() returns false. getConnectGeneration() is constant for the life of the transport.
  • getTarget() now returns OrcadHostTarget = SshTarget | WslOrcadHostTarget. The WSL variant is { kind: 'wsl', id, distro, label }. id and distro match C2's WSL deployment record (environmentId, distro); label is the environment's name. isWslOrcadHostTarget tells the two apart because SshTarget has no kind. The only code that needed changes was the Windows-host branch of the stdio bridge, which now narrows to SSH explicitly. SSH behavior, persisted data, and wire formats are unchanged.
  • The ustar header writer moved out of skill-package-tar.ts into src/main/ustar-entry-header.ts, so skills and WSL uploads share one writer. Skill error codes are unchanged.

Why

This is step C1 of the WSL-via-orcad plan (design D1/D2). Implementing the existing transport contract lets later steps reuse orcad deploy, activation and the stdio bridge as they are, instead of building a parallel WSL install path. A per-command wsl.exe --exec avoids WSL's $var expansion of arguments and needs no networking. Copying through /mnt needs no extra encoding. The tar fallback covers sources the distro can't see. A single tar stream is used rather than one exec per file, because every wsl.exe start costs about 100 ms or more.

Remaining coupling: OrcadRemoteContext.target and resolveOrcadRemoteContext still take an SshTarget. Widening those touches about 26 SSH-path sites, so it belongs with the deploy step (C4).

Linked Issue

None. Part of the WSL-via-orcad plan (step C1).

Visual Proof

N/A. This adds a main-process transport with no UI and no production caller yet.

Testing

  • Unit tests with a fake child process: exit before close, stdin piping and EOF, nonzero exit with stderr, pre-abort with no spawn, abort kills the child, spawn failure, 20 MB stdout under backpressure, and identity.

  • Upload tests that run the generated scripts through a real POSIX shell standing in for the distro: the tar path, the guest-copy path, falling back when the mount is missing, merging into an existing destination, rejecting on a digest mismatch (destination untouched, stage removed), and writeFile.

  • Real Windows 11 host (WSL 2.7.10) with a throwaway non-systemd Alpine distro. The transport was bundled with esbuild and run under the installed Orca with ELECTRON_RUN_AS_NODE=1. All 17 checks passed:

    • Exec echo was byte-exact, including quotes, $HOME and backticks passed through --exec.
    • 20 MB binary stdin to stdout was byte-exact in 416 ms, and the SHA-256 computed inside the distro matched.
    • Exit codes came through (7, and 3 with stderr).
    • close() and an AbortSignal both killed the Linux process (confirmed with kill -0).
    • writeFile round-tripped.
    • uploadDirectory of a 20 MB tree with 205 files matched SHA-256 inside the distro for all three paths: via /mnt in 1.6 s, via tar in 0.97 s, and missing mount falling back to tar in 1.1 s. Empty directories and 0755 executables were kept, and re-uploading overwrote in place.
    • The probe distro and temp files were removed afterwards.
  • Ran pnpm tc, the src/main/ssh + src/main/wsl + src/main/skills suites, oxlint, anti-slop, check:code-quality:changed, and the ratchet/reliability/process-host checks.

  • I manually tested these changes locally

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

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • SSH: unchanged. SshConnection still returns SshTarget, which is a member of the wider union.
  • Cross-platform: the transport is only built on Windows. The tests that drive real shell scripts skip on win32 and on hosts without sha256sum.
  • Commands longer than the Windows command-line limit are refused with a clear error rather than split. Callers today stay far below it.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@nwparker
nwparker force-pushed the nwparker/wsl-c1-wsl-orcad-host-transport branch from 23df239 to 470ebaa Compare October 13, 2026 05:42
@nwparker
nwparker marked this pull request as ready for review October 13, 2026 05:42
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

The change adds shared USTAR header and padding utilities, then uses them in skill-package TAR generation and WSL directory uploads. It adds a WSL-backed Orcad host transport that runs commands through child processes and transfers files. Directory uploads use guest-visible paths when available or stream a TAR archive, then verify staged files before promotion. The stdio bridge rejects WSL targets that report a Windows platform.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 470eb

A cancelled WSL command may remain pending, and a directory upload may promote an unexpected file if its source changes during upload. Address these gaps before relying on the new transport.

Pre-merge checks · Passed 3 · Failed 2

Failed Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check Warning The description is detailed and covers the change, rationale, testing, compatibility, and checklist. However, the required Linked Issue section states “None,” while the template requires an actual iss… Add the actual issue reference in the Linked Issue section, such as “Fixes #12345.”
Docstring Coverage Warning Docstring coverage is 39.13% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks (3 passed)
Check name Status Explanation
Title check Passed The title clearly identifies the main change: adding an Orcad host transport over WSL.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, compatibility, and checklist. However, the required Linked Issue section states “None,” while the template requires an actual issue link.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f96b5a0f-705d-40fb-bcd5-174c3179e1a7
📥 Commits

Reviewing files that changed from the base of the PR and between 1182168 and 470ebaa.

📒 Files selected for processing (10)
  • src/main/skills/skill-package-tar.ts
  • src/main/ssh/orcad-host-transport.ts
  • src/main/ssh/orcad-stdio-bridge.ts
  • src/main/ustar-entry-header.ts
  • src/main/wsl/wsl-command-channel.ts
  • src/main/wsl/wsl-directory-upload.test.ts
  • src/main/wsl/wsl-directory-upload.ts
  • src/main/wsl/wsl-orcad-host-target.ts
  • src/main/wsl/wsl-orcad-host-transport.test.ts
  • src/main/wsl/wsl-orcad-host-transport.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +56 to +78
/** Reads the digest manifest from stdin; the stage is removed whatever the outcome. */
function verifyAndPromoteCommand(stage: string, dest: string, hasFiles: boolean): string {
return [
`stage=${shellEscape(stage)}; dest=${shellEscape(dest)}`,
`trap 'rm -rf "$stage"' EXIT`,
// GNU sha256sum rejects an empty manifest.
...(hasFiles
? [
'(cd "$stage" && sha256sum -c - >/dev/null) ||',
" { echo 'staged upload failed its digest check' >&2; exit 1; }"
]
: []),
// Serialises concurrent uploads into one destination; each rename is atomic regardless.
'if command -v flock >/dev/null 2>&1; then exec 9<"$dest" && flock 9 || exit 1; fi',
'(cd "$stage" && find . -mindepth 1 -type d) | while IFS= read -r p; do',
' mkdir -p "$dest/$p" || exit 1',
'done || exit 1',
'(cd "$stage" && find . ! -type d) | while IFS= read -r p; do',
' mv -f "$stage/$p" "$dest/$p" || exit 1',
'done || exit 1',
`echo ${WSL_UPLOAD_PROMOTED}`
].join('\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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,115p' src/main/wsl/wsl-directory-upload.ts
sed -n '164,205p' src/main/wsl/wsl-directory-upload.ts

Repository: stablyai/orca

Length of output: 6534


🏁 Script executed:

rg -n -F --glob '*.ts' -e 'uploadDirectoryIntoWsl' -e 'wslGuestSourcePath' -e 'collectLocalUploadPlan' -e 'verifyAndPromoteCommand' -e 'stageFromGuestPathCommand' src test tests 2>/dev/null || true
printf '\n--- upload plan definition and implementation ---\n'
rg -n -F --glob '*.ts' -e 'export type LocalUploadPlan' -e 'export interface LocalUploadPlan' -e 'function collectLocalUploadPlan' -e 'export async function collectLocalUploadPlan' src
printf '\n--- relevant plan and caller blocks ---\n'
python3 - <<'PY'
from pathlib import Path
for p in Path('src').rglob('*.ts'):
    s=p.read_text(errors='replace')
    if any(x in s for x in ('collectLocalUploadPlan', 'uploadDirectoryIntoWsl', 'wslGuestSourcePath')):
        print(f'\n--- {p} ---')
        lines=s.splitlines()
        for i,l in enumerate(lines,1):
            if any(x in l for x in ('collectLocalUploadPlan', 'uploadDirectoryIntoWsl', 'wslGuestSourcePath', 'LocalUploadPlan')):
                a=max(1,i-12); b=min(len(lines),i+45)
                print('\n'.join(f'{n:4} {lines[n-1]}' for n in range(a,b+1)))
PY
printf '\n--- related tests ---\n'
rg -n -F --glob '*.{ts,tsx,sh}' -e 'WSL_UPLOAD_PROMOTED' -e 'ORCA_WSL_GUEST_SOURCE_UNAVAILABLE' -e 'uploadDirectoryIntoWsl' -e 'guest source' -e 'guestSource' . 2>/dev/null || true

Repository: stablyai/orca

Length of output: 42091


🏁 Script executed:

# Read the exact relevant files and usages after the prior search, including complete logical blocks.
printf '%s\n' '--- candidate files ---'
rg --files | rg 'wsl-directory-upload|system-ssh-file-transfer|wsl.*test|directory.*upload|file-transfer'
printf '%s\n' '--- all relevant references ---'
rg -n -F --glob '*.ts' --glob '*.tsx' --glob '*.sh' -e 'uploadDirectoryIntoWsl' -e 'wslGuestSourcePath' -e 'collectLocalUploadPlan' -e 'LocalUploadPlan' src test tests scripts 2>/dev/null || true

Repository: stablyai/orca

Length of output: 14705


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- candidate files ---'
rg --files | rg 'wsl-directory-upload|system-ssh-file-transfer|wsl.*test|directory.*upload|file-transfer' || true
printf '%s\n' '--- relevant references ---'
rg -n -F --glob '*.ts' --glob '*.tsx' --glob '*.sh' \
  -e 'uploadDirectoryIntoWsl' -e 'wslGuestSourcePath' -e 'collectLocalUploadPlan' \
  -e 'LocalUploadPlan' src test tests scripts 2>/dev/null || true
printf '%s\n' '--- plan definitions ---'
rg -n -F --glob '*.ts' \
  -e 'export type LocalUploadPlan' -e 'export interface LocalUploadPlan' \
  -e 'function collectLocalUploadPlan' -e 'export async function collectLocalUploadPlan' src || true

Repository: stablyai/orca

Length of output: 14894


🏁 Script executed:

printf '%s\n' '--- WSL transport caller ---'
sed -n '1,105p' src/main/wsl/wsl-orcad-host-transport.ts
printf '%s\n' '--- WSL upload tests ---'
sed -n '1,155p' src/main/wsl/wsl-directory-upload.test.ts
printf '%s\n' '--- registration references ---'
rg -n -F --glob '*.ts' -e 'WslOrcadHostTransport' -e 'wsl-orcad-host-transport' -e 'OrcadHostTransport' src/main/wsl src/main | head -120

Repository: stablyai/orca

Length of output: 20273


Reject unplanned staged entries before promotion.

The WSL transport calls uploadDirectoryIntoWsl with a guest source when available. That command copies the complete source tree, but the manifest contains only planned files. The digest check does not reject extra entries, and the later promotion loops move every staged directory and file.

A file created after planning can therefore be promoted with mv -f, which can add an unexpected destination file or overwrite an existing one. Validate the stage against both planned files and planned directories before promotion. A promotion-time rejection is sufficient and preserves planned empty directories.

Comment on lines +35 to +65
const transport: WslOrcadHostTransport = {
// `wrapCommand` is SSH-only: there is no login shell between wsl.exe and `sh -c`.
async exec(command: string, execOptions?: SshExecOptions): Promise<RemoteCommandChannel> {
if (execOptions?.signal?.aborted) {
throw createSshOperationAbortError()
}
const program = resolveWslExecutablePath()
const args = buildWslExecArgs(target.distro, ['sh', '-c', command])
if (commandLineLength([program, ...args]) > MAX_COMMAND_LINE_CHARS) {
throw new Error('WSL command exceeds the Windows command-line limit')
}
const child = spawn({
program,
args,
cwd: resolveWslInteropSpawnCwd(),
// Why WSL_UTF8: otherwise wsl.exe writes its own errors as UTF-16LE.
env: { ...process.env, WSL_UTF8: '1' }
})
const channel = wrapWslCommandProcess(child)
// Like an SSH channel open: a child that never started rejects here, not as a stream error.
const spawnError = (error: Error): void => {
channel.destroy(error)
}
channel.on('error', spawnError)
try {
await once(child, 'spawn')
} finally {
channel.off('error', spawnError)
}
return channel
},

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '25,85p' src/main/wsl/wsl-orcad-host-transport.ts
rg -n 'waitFor.*Spawn|waitForSpawn|spawn.*signal|AbortSignal' src/main/wsl/wsl-orcad-host-transport.ts src/main/wsl/wsl-process* src/main/ssh/*exec* src/main/wsl/wsl-orcad-host-transport.test.ts

Repository: stablyai/orca

Length of output: 2697


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- transport imports and relevant references ---'
sed -n '1,40p' src/main/wsl/wsl-orcad-host-transport.ts
rg -n -F --glob '*.ts' -e 'wrapWslCommandProcess' -e 'once(child, '\''spawn'\'')' -e 'createSshOperationAbortError' -e 'interface.*RemoteCommandChannel' -e 'type.*RemoteCommandChannel' src/main
printf '%s\n' '--- WSL files ---'
rg --files src/main/wsl | sort
printf '%s\n' '--- process wrapper definitions and nearby callers ---'
rg -n -F --glob '*.ts' -e 'wrapWslCommandProcess' -e 'spawnProcess' -e 'waitForSpawn' src test tests 2>/dev/null || test "$?" -eq 1

Repository: stablyai/orca

Length of output: 44702


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- WSL channel ---'
nl -ba src/main/wsl/wsl-command-channel.ts
printf '%s\n' '--- process-host spec and spawn implementation ---'
nl -ba src/packages/process-host/src/process-spec.ts
nl -ba src/packages/process-host/src/run-process.ts
printf '%s\n' '--- WSL transport tests ---'
nl -ba src/main/wsl/wsl-orcad-host-transport.test.ts
printf '%s\n' '--- RemoteCommandChannel and SSH cancellation ---'
rg -n -F --glob '*.ts' -e 'export interface RemoteCommandChannel' -e 'export type RemoteCommandChannel' -e 'interface RemoteCommandChannel' -e 'signal.addEventListener' -e 'requestTermination(createSshOperationAbortError())' src/main/ssh

Repository: stablyai/orca

Length of output: 33328


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- remote channel contract ---'
nl -ba src/main/ssh/remote-install-transport.ts | sed -n '1,45p'
printf '%s\n' '--- execCommand complete relevant implementation ---'
nl -ba src/main/ssh/ssh-relay-exec-command.ts | sed -n '1,230p'
printf '%s\n' '--- transport interface and callers ---'
rg -n -F --glob '*.ts' -e 'exec(command' -e 'transport.exec(' -e 'execCommand(' src/main/ssh src/main/wsl

Repository: stablyai/orca

Length of output: 24322


Abort the WSL child while waiting for spawn.

execCommand installs its abort handler only after conn.exec() resolves. During the earlier interval, createWslOrcadHostTransport.exec waits on once(child, 'spawn') without the signal. An abort in this interval can leave the promise pending and wsl.exe running. The command timeout also starts only after conn.exec() resolves.

Suggested fix
       const spawnError = (error: Error): void => {
         channel.destroy(error)
       }
       channel.on('error', spawnError)
+      const onAbort = (): void => {
+        channel.close()
+      }
+      execOptions?.signal?.addEventListener('abort', onAbort, { once: true })
+      if (execOptions?.signal?.aborted) {
+        onAbort()
+      }
       try {
-        await once(child, 'spawn')
+        await once(child, 'spawn', { signal: execOptions?.signal })
       } finally {
+        execOptions?.signal?.removeEventListener('abort', onAbort)
         channel.off('error', spawnError)
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const transport: WslOrcadHostTransport = {
// `wrapCommand` is SSH-only: there is no login shell between wsl.exe and `sh -c`.
async exec(command: string, execOptions?: SshExecOptions): Promise<RemoteCommandChannel> {
if (execOptions?.signal?.aborted) {
throw createSshOperationAbortError()
}
const program = resolveWslExecutablePath()
const args = buildWslExecArgs(target.distro, ['sh', '-c', command])
if (commandLineLength([program, ...args]) > MAX_COMMAND_LINE_CHARS) {
throw new Error('WSL command exceeds the Windows command-line limit')
}
const child = spawn({
program,
args,
cwd: resolveWslInteropSpawnCwd(),
// Why WSL_UTF8: otherwise wsl.exe writes its own errors as UTF-16LE.
env: { ...process.env, WSL_UTF8: '1' }
})
const channel = wrapWslCommandProcess(child)
// Like an SSH channel open: a child that never started rejects here, not as a stream error.
const spawnError = (error: Error): void => {
channel.destroy(error)
}
channel.on('error', spawnError)
try {
await once(child, 'spawn')
} finally {
channel.off('error', spawnError)
}
return channel
},
const transport: WslOrcadHostTransport = {
// `wrapCommand` is SSH-only: there is no login shell between wsl.exe and `sh -c`.
async exec(command: string, execOptions?: SshExecOptions): Promise<RemoteCommandChannel> {
if (execOptions?.signal?.aborted) {
throw createSshOperationAbortError()
}
const program = resolveWslExecutablePath()
const args = buildWslExecArgs(target.distro, ['sh', '-c', command])
if (commandLineLength([program, ...args]) > MAX_COMMAND_LINE_CHARS) {
throw new Error('WSL command exceeds the Windows command-line limit')
}
const child = spawn({
program,
args,
cwd: resolveWslInteropSpawnCwd(),
// Why WSL_UTF8: otherwise wsl.exe writes its own errors as UTF-16LE.
env: { ...process.env, WSL_UTF8: '1' }
})
const channel = wrapWslCommandProcess(child)
// Like an SSH channel open: a child that never started rejects here, not as a stream error.
const spawnError = (error: Error): void => {
channel.destroy(error)
}
channel.on('error', spawnError)
const onAbort = (): void => {
channel.close()
}
execOptions?.signal?.addEventListener('abort', onAbort, { once: true })
if (execOptions?.signal?.aborted) {
onAbort()
}
try {
await once(child, 'spawn', { signal: execOptions?.signal })
} finally {
execOptions?.signal?.removeEventListener('abort', onAbort)
channel.off('error', spawnError)
}
return channel
},

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