Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(ssh): route SSH projects through the native transport on Windows

enes3678d5929994
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 8e8876451..f3d69c5d9 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -48,6 +48,8 @@ import {
type RemoteNodeOwnerResolver
} from './remote-end'
import { RemoteSessionIndex, type SessionVerdict } from './remote-ssh/remote-session-index'
+import { isSshProgram, nativeExecFileAsync, nativeMux, useNativeSsh } from './remote-ssh/native/native-runtime'
+import { NativeSshPty } from './remote-ssh/native/native-pty'
import { remotePtySpawnGate, type SpawnSlot } from './remote-ssh/pty-spawn-gate'
import type { SshConnection } from '../shared/ssh'
import { recordPendingRemoteKill, type PendingRemoteKill } from './pending-remote-kills'
@@ -213,10 +215,17 @@ const PROBE_TIMEOUT_MS = 6_000
* just as invisible. Callers may still pass their own `timeout` for the rare op that needs longer.
*/
const runAsync = ((file: string, args: readonly string[], opts?: object) =>
- execFileAsync(file, args as string[], {
- timeout: PROC_TIMEOUT_MS,
- ...(opts ?? {})
- } as never)) as unknown as typeof execFileAsync
+ // An ssh side-call on the native transport (Windows; see remote-ssh/native/native-mux.ts) runs
+ // over the project's one connection instead of spawning an ssh that cannot multiplex there.
+ // Same result and error shape as execFile, so no caller below changes.
+ isSshProgram(file) && useNativeSsh()
+ ? nativeExecFileAsync(args, {
+ timeout: ((opts as { timeout?: number } | undefined)?.timeout ?? PROC_TIMEOUT_MS)
+ })
+ : execFileAsync(file, args as string[], {
+ timeout: PROC_TIMEOUT_MS,
+ ...(opts ?? {})
+ } as never)) as unknown as typeof execFileAsync
/** Narrow child-process seam for strict tmux probes/confirmed teardown. Production delegates to
* the same bounded runner above; focused tests inject a stateful fake so hidden dual-backend
@@ -241,6 +250,9 @@ type ConfirmedProcessRun = (
* would take the main process down instead of failing this one call.
*/
function runWithStdin(file: string, args: readonly string[], input: string): Promise<unknown> {
+ if (isSshProgram(file) && useNativeSsh()) {
+ return nativeExecFileAsync(args, { timeout: PROC_TIMEOUT_MS, input })
+ }
const p = execFileAsync(file, args as string[], { timeout: PROC_TIMEOUT_MS } as never)
const child = (p as unknown as { child: import('child_process').ChildProcess }).child
const stdin = child.stdin
@@ -3582,13 +3594,22 @@ export class PtyManager {
)) as unknown as pty.IPty
} else {
try {
- proc = pty.spawn(file, args, {
- name: 'xterm-256color',
- cols: options.cols,
- rows: options.rows,
- cwd,
- env
- })
+ proc =
+ !!(options.sshRemote && options.persistKey && remoteSsh) && useNativeSsh()
+ ? // The remote terminal as a pty CHANNEL on the project's one native connection: no ssh
+ // process (it could not multiplex on Windows). See remote-ssh/native/native-pty.ts.
+ (new NativeSshPty(nativeMux(), args, {
+ cols: options.cols,
+ rows: options.rows,
+ name: 'xterm-256color'
+ }) as unknown as pty.IPty)
+ : pty.spawn(file, args, {
+ name: 'xterm-256color',
+ cols: options.cols,
+ rows: options.rows,
+ cwd,
+ env
+ })
} catch (err) {
// node-pty surfaces the underlying failure as a bare "posix_spawnp failed." with no errno.
// Two different field causes wear that same message, so BOTH are measured before anything is
diff --git a/src/core/remote-ssh/native/native-invoke.test.ts b/src/core/remote-ssh/native/native-invoke.test.ts
index eff48f5e1..5e32a3ba5 100644
--- a/src/core/remote-ssh/native/native-invoke.test.ts
+++ b/src/core/remote-ssh/native/native-invoke.test.ts
@@ -5,7 +5,7 @@ import net, { type AddressInfo } from 'net'
import path from 'path'
import { Server, utils, type Connection } from 'ssh2'
import { NativeMux } from './native-mux'
-import { runSshArgv, startNativeMaster, useNativeSsh } from './native-invoke'
+import { runSshArgv, spawnSshArgvStream, startNativeMaster, useNativeSsh } from './native-invoke'
import {
checkMasterArgs,
childArgs,
@@ -103,7 +103,7 @@ describe('native-invoke', () => {
const m = mux()
expect((await runSshArgv(m, checkMasterArgs(conn(), CP()))).code).toBe(255)
const master = startNativeMaster(m, masterArgs(conn(), CP()))
- const exitCode = new Promise<number | null>((r) => master.on('exit', r))
+ const exitCode = new Promise<number | null>((r) => master.on('exit', (c) => r(c as number | null)))
for (let i = 0; i < 100 && (await runSshArgv(m, checkMasterArgs(conn(), CP()))).code !== 0; i++) {
await new Promise((r) => setTimeout(r, 20))
}
@@ -153,6 +153,25 @@ describe('native-invoke', () => {
}
})
+ it('a streaming child (the setup runner): output as it arrives, then close with the status', async () => {
+ const child = spawnSshArgvStream(mux(), childArgs(conn(), CP(), 'setup.sh'))
+ let out = ''
+ let err = ''
+ child.stdout.on('data', (d: Buffer) => (out += d.toString()))
+ child.stderr.on('data', (d: Buffer) => (err += d.toString()))
+ const code = await new Promise<number>((r) => child.on('close', r))
+ expect(err).toBe('')
+ expect(code).toBe(0)
+ expect(out).toBe('ran: setup.sh\n')
+ })
+
+ it('a streaming child killed before it opens closes with 255 and runs nothing', async () => {
+ const child = spawnSshArgvStream(mux(), childArgs(conn(), CP(), 'setup.sh'))
+ child.kill('SIGKILL')
+ const code = await new Promise<number>((r) => child.on('close', r))
+ expect(code).toBe(255)
+ })
+
it('an argv the parser refuses is a named exit 255, not a guess', async () => {
const r = await runSshArgv(mux(), ['-L', '1:h:2', '[email protected]'])
expect(r.code).toBe(255)
diff --git a/src/core/remote-ssh/native/native-invoke.ts b/src/core/remote-ssh/native/native-invoke.ts
index 820301b63..292a1d9a7 100644
--- a/src/core/remote-ssh/native/native-invoke.ts
+++ b/src/core/remote-ssh/native/native-invoke.ts
@@ -9,10 +9,11 @@
// desktop. It is read at call time, never cached, so a test can flip it.
import { EventEmitter } from 'events'
+import { PassThrough } from 'stream'
import fs from 'fs'
import path from 'path'
import type { SFTPWrapper } from 'ssh2'
-import { NativeMux, noMasterMessage, type ExecResult } from './native-mux'
+import { NativeMux, channelExit, noMasterMessage, type ExecResult } from './native-mux'
import { parseScpArgv, parseSshArgv, type ParsedSsh } from './ssh-argv'
export function useNativeSsh(
@@ -66,7 +67,7 @@ export async function runSshArgv(
/** What SshProjectManager watches for a spawned master process (Runners.spawnMaster). */
export interface NativeMasterHandle {
kill(): void
- on(event: 'exit', cb: (code: number | null) => void): void
+ on(event: string, cb: (...a: unknown[]) => void): void
stderr(): string
exited(): boolean
pid(): number | undefined
@@ -104,7 +105,9 @@ export function startNativeMaster(mux: NativeMux, argv: string[]): NativeMasterH
kill: () => {
if (controlPath) void mux.exit(controlPath)
},
- on: (_ev, cb) => void events.on('exit', cb),
+ on: (ev, cb) => {
+ if (ev === 'exit') events.on('exit', cb)
+ },
stderr: () => stderr,
exited: () => exited,
// No OS process. The manager only uses the pid to correlate askpass prompts, which the native
@@ -173,3 +176,68 @@ function promisify<T>(fn: (cb: (err: Error | null | undefined, v: T) => void) =>
function result(code: number, stdout: string, stderr: string): ExecResult {
return { code, signal: null, stdout: Buffer.from(stdout), stderr: Buffer.from(stderr), timedOut: false }
}
+
+/** What a streaming caller uses of a ChildProcess (the setup runner): pipes, `close`, `error`, kill. */
+export interface NativeStreamChild extends EventEmitter {
+ stdout: PassThrough
+ stderr: PassThrough
+ kill(signal?: string): boolean
+}
+
+/**
+ * `spawn(ssh, argv, {stdio: ['ignore','pipe','pipe']})` over the native transport. Emits `close`
+ * with the remote exit status (255 when the channel is cut off or cannot be opened, ssh's code);
+ * `kill` closes the channel — the same thing killing the local mux client did.
+ */
+export function spawnSshArgvStream(mux: NativeMux, argv: string[]): NativeStreamChild {
+ const child = new EventEmitter() as NativeStreamChild
+ child.stdout = new PassThrough()
+ child.stderr = new PassThrough()
+ let closeChannel: (() => void) | null = null
+ let killed = false
+ let done = false
+ const finish = (code: number): void => {
+ if (done) return
+ done = true
+ child.stdout.end()
+ child.stderr.end()
+ child.emit('close', code)
+ }
+ child.kill = () => {
+ killed = true
+ // Asynchronously, as a real child reports its exit: a caller may attach 'close' after kill().
+ if (closeChannel) closeChannel()
+ else queueMicrotask(() => finish(255))
+ return true
+ }
+ let p: ParsedSsh
+ try {
+ p = parseSshArgv(argv)
+ if (p.kind !== 'exec') throw new Error('native ssh transport: not a command argv')
+ } catch (e) {
+ queueMicrotask(() => {
+ child.stderr.write(`${(e as Error).message}\n`)
+ finish(255)
+ })
+ return child
+ }
+ mux.channel(p).then(
+ (ch) => {
+ if (killed) {
+ ch.close()
+ return
+ }
+ closeChannel = () => ch.close()
+ ch.pipe(child.stdout, { end: false })
+ ch.stderr.pipe(child.stderr, { end: false })
+ ch.on('close', () => finish(channelExit(ch).code ?? 255))
+ ch.on('error', () => {})
+ ch.end()
+ },
+ (e: Error) => {
+ child.stderr.write(`${e.message}\n`)
+ finish(255)
+ }
+ )
+ return child
+}
diff --git a/src/core/remote-ssh/native/native-mux.ts b/src/core/remote-ssh/native/native-mux.ts
index 6a0b33f9c..ce310c5ff 100644
--- a/src/core/remote-ssh/native/native-mux.ts
+++ b/src/core/remote-ssh/native/native-mux.ts
@@ -44,8 +44,9 @@ export interface ExecResult {
export interface NativeMuxDeps {
/** Effective config for a destination (`ssh -G`; see ssh-config.ts). */
resolveHost(target: SshTarget): Promise<ResolvedHost>
- /** Ask the user for a key's passphrase; null = cancelled. Absent = never prompt. */
- askPassphrase?(identityFile: string): Promise<string | null>
+ /** Ask the user for a key's passphrase; null = cancelled (or nobody answered). Absent = never
+ * prompt. `retry`: the previous answer was wrong. `target`: `user@host`, for the dialog. */
+ askPassphrase?(identityFile: string, req: { retry: boolean; target: string }): Promise<string | null>
/** Default agent when the config names none (`SSH_AUTH_SOCK` / Windows' openssh-ssh-agent pipe). */
defaultAgent?(): string | undefined
readFile?(p: string): Buffer | null
@@ -181,6 +182,17 @@ export class NativeMux {
async shell(
p: Extract<ParsedSsh, { kind: 'exec' }>,
pty: { cols: number; rows: number; term?: string }
+ ): Promise<ClientChannel> {
+ return this.channel(p, pty)
+ }
+
+ /**
+ * A channel for `p`'s command, with a pty or without — the streaming form of `exec` for a caller
+ * that reads output as it arrives (the setup runner). Same master rules as `exec`.
+ */
+ async channel(
+ p: Extract<ParsedSsh, { kind: 'exec' }>,
+ pty?: { cols: number; rows: number; term?: string }
): Promise<ClientChannel> {
const cp = p.options.controlPath
if (!cp) throw new Error('ssh: a pty needs a ControlPath')
@@ -190,9 +202,17 @@ export class NativeMux {
}
const conn = this.conns.get(cp)!
await conn.ready
- const ptyOpts = { cols: pty.cols, rows: pty.rows, term: pty.term ?? 'xterm-256color' }
return new Promise((resolve, reject) => {
- const cb = (err: Error | undefined, ch: ClientChannel): void => (err ? reject(err) : resolve(ch))
+ const cb = (err: Error | undefined, ch: ClientChannel): void => {
+ if (err) return reject(err)
+ recordExit(ch)
+ resolve(ch)
+ }
+ if (!pty) {
+ conn.client.exec(p.command ?? '', cb)
+ return
+ }
+ const ptyOpts = { cols: pty.cols, rows: pty.rows, term: pty.term ?? 'xterm-256color' }
if (p.command) conn.client.exec(p.command, { pty: ptyOpts }, cb)
else conn.client.shell(ptyOpts, cb)
})
@@ -336,7 +356,8 @@ export class NativeMux {
const sock = await (this.deps.connectSocket ?? defaultConnectSocket)(host.hostname, host.port, timeoutMs)
const knownAs = host.hostKeyAlias ?? target.host
let hostKeyRefusal = ''
- const auth = this.authPlan(target, host, options, mode)
+ const cancelled = { value: false }
+ const auth = this.authPlan(target, host, options, mode, cancelled)
const cfg: ConnectConfig = {
sock,
username: host.user,
@@ -373,6 +394,9 @@ export class NativeMux {
client.removeListener('ready', onReady)
if (hostKeyRefusal) return reject(new Error(hostKeyRefusal))
if (e.level === 'client-authentication') {
+ // A passphrase the user declined is the reason, not a denial by the server; say so the
+ // way the POSIX path does (SshProjectManager's cancelled message).
+ if (cancelled.value) return reject(new Error('SSH connection cancelled: this key needs its passphrase.'))
return reject(new Error(`${target.user}@${target.host}: Permission denied (publickey).`))
}
reject(new Error(`ssh: ${e.message}`))
@@ -392,7 +416,8 @@ export class NativeMux {
target: SshTarget,
host: ResolvedHost,
options: SshOptions,
- mode: { interactive: boolean }
+ mode: { interactive: boolean },
+ cancelled: { value: boolean }
): { next(): Promise<unknown> } {
const username = host.user
const identitiesOnly = options.identitiesOnly ?? host.identitiesOnly
@@ -423,8 +448,11 @@ export class NativeMux {
if (!mode.interactive || options.batchMode || !this.deps.askPassphrase) return null
// Up to three tries, like ssh's NumberOfPasswordPrompts default.
for (let i = 0; i < 3 && key instanceof Error; i++) {
- const pass = await this.deps.askPassphrase(file)
- if (pass === null) return null
+ const pass = await this.deps.askPassphrase(file, { retry: i > 0, target: `${target.user}@${target.host}` })
+ if (pass === null) {
+ cancelled.value = true
+ return null
+ }
key = utils.parseKey(data, pass)
}
}
@@ -491,6 +519,29 @@ function filteredAgent(agentPath: string, pubFiles: Buffer[]): ReturnType<typeof
return base
}
+const exits = new WeakMap<ClientChannel, { code: number | null; signal: string | null }>()
+
+/**
+ * Record a channel's exit status the moment it is opened, synchronously. The open confirmation and
+ * the exit-status can arrive in ONE TCP read (a fast command, a pty whose remote side exits at
+ * once); ssh2 parses both in the same tick, so a listener attached after `await`ing the channel
+ * misses `exit`, and a clean remote exit would read as 255 — "the transport dropped", which sends
+ * the reconnector after a terminal that simply ended.
+ */
+function recordExit(ch: ClientChannel): void {
+ const rec = { code: null as number | null, signal: null as string | null }
+ exits.set(ch, rec)
+ ch.on('exit', (code: number | null, signal?: string) => {
+ rec.code = code
+ rec.signal = signal ?? null
+ })
+}
+
+/** The exit status recorded for a channel from `channel()` / `shell()` (null until it arrives). */
+export function channelExit(ch: ClientChannel): { code: number | null; signal: string | null } {
+ return exits.get(ch) ?? { code: null, signal: null }
+}
+
function fail(e: unknown): ExecResult {
const msg = e instanceof Error ? e.message : String(e)
return { code: 255, signal: null, stdout: Buffer.alloc(0), stderr: Buffer.from(msg + '\n'), timedOut: false }
diff --git a/src/core/remote-ssh/native/native-pty.test.ts b/src/core/remote-ssh/native/native-pty.test.ts
new file mode 100644
index 000000000..330a63d32
--- /dev/null
+++ b/src/core/remote-ssh/native/native-pty.test.ts
@@ -0,0 +1,154 @@
+import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import type { AddressInfo } from 'net'
+import { Server, utils, type Connection, type ServerChannel } from 'ssh2'
+import { NativeMux } from './native-mux'
+import { NativeSshPty } from './native-pty'
+import { remoteTmuxPtyArgs } from '../control-master'
+import type { SshConnection } from '../../../shared/ssh'
+
+const hostKey = utils.generateKeyPairSync('ed25519')
+const clientKey = utils.generateKeyPairSync('ed25519')
+let dir: string
+let server: Server
+let port: number
+let clients: Connection[] = []
+/** The server side of the last pty channel, and the window sizes it was told. */
+let serverCh: ServerChannel | null = null
+const windows: string[] = []
+
+beforeAll(async () => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-native-pty-'))
+ fs.writeFileSync(path.join(dir, 'id'), clientKey.private)
+ server = new Server({ hostKeys: [hostKey.private] }, (client) => {
+ clients.push(client)
+ client.on('authentication', (ctx) => (ctx.method === 'publickey' ? ctx.accept() : ctx.reject(['publickey'])))
+ client.on('ready', () =>
+ client.on('session', (accept) => {
+ const session = accept()
+ session.on('pty', (a, _r, info) => {
+ windows.push(`${info.cols}x${info.rows}`)
+ a?.()
+ })
+ session.on('window-change', (a, _r, info) => {
+ windows.push(`${info.cols}x${info.rows}`)
+ a?.()
+ })
+ session.on('exec', (a) => {
+ const ch = a()
+ serverCh = ch
+ ch.write('ready\r\n')
+ ch.on('data', (d: Buffer) => {
+ const s = d.toString()
+ if (s.includes('exit')) {
+ ch.exit(7)
+ ch.end()
+ } else ch.write(`echo:${s}`)
+ })
+ })
+ })
+ )
+ client.on('error', () => {})
+ })
+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()))
+ port = (server.address() as AddressInfo).port
+})
+afterAll(() => {
+ server.close()
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+const muxes: NativeMux[] = []
+afterEach(() => {
+ for (const m of muxes.splice(0)) m.exitAll()
+ for (const c of clients.splice(0)) c.end()
+ windows.length = 0
+ serverCh = null
+})
+
+function mux(): NativeMux {
+ const m = new NativeMux({
+ defaultAgent: () => undefined,
+ resolveHost: async () => ({
+ hostname: '127.0.0.1',
+ port,
+ user: 'dev',
+ identityFiles: [path.join(dir, 'id')],
+ identitiesOnly: true,
+ userKnownHostsFiles: [path.join(dir, 'known_hosts')],
+ globalKnownHostsFiles: [],
+ strictHostKeyChecking: 'ask'
+ })
+ })
+ muxes.push(m)
+ return m
+}
+const conn = (): SshConnection => ({ user: 'dev', host: '127.0.0.1', port, identityFile: path.join(dir, 'id') })
+const argv = (): string[] => remoteTmuxPtyArgs(conn(), path.join(dir, 'cm.sock'), 'nt-x', '~')
+const until = async (f: () => boolean): Promise<void> => {
+ for (let i = 0; i < 200 && !f(); i++) await new Promise((r) => setTimeout(r, 10))
+}
+
+describe('NativeSshPty (the IPty PtyManager holds for a remote terminal)', () => {
+ it('queues writes made before the channel opens, relays both ways, resizes, and exits with the remote status', async () => {
+ const p = new NativeSshPty(mux(), argv(), { cols: 100, rows: 30 })
+ let out = ''
+ let exit: number | null = null
+ p.onData((d) => (out += d))
+ p.onExit((e) => (exit = e.exitCode))
+ p.write('early') // before the channel is open
+ await until(() => out.includes('echo:early'))
+ expect(out).toContain('ready')
+ expect(out).toContain('echo:early')
+ p.resize(120, 40)
+ await until(() => windows.includes('120x40'))
+ expect(windows[0]).toBe('100x30')
+ expect(windows).toContain('120x40')
+ p.write('exit')
+ await until(() => exit !== null)
+ expect(exit).toBe(7)
+ })
+
+ it('a dropped connection exits 255 — what SshReconnector reads as a transport drop', async () => {
+ const p = new NativeSshPty(mux(), argv(), { cols: 80, rows: 24 })
+ let exit: number | null = null
+ p.onExit((e) => (exit = e.exitCode))
+ await until(() => serverCh !== null)
+ for (const c of clients) c.end()
+ await until(() => exit !== null)
+ expect(exit).toBe(255)
+ })
+
+ it('a connection that cannot come up prints the reason into the terminal and exits 255', async () => {
+ const m = new NativeMux({
+ defaultAgent: () => undefined,
+ resolveHost: async () => {
+ throw new Error('ssh -G failed for dev@nowhere: boom')
+ }
+ })
+ muxes.push(m)
+ const p = new NativeSshPty(m, argv(), { cols: 80, rows: 24 })
+ let out = ''
+ let exit: number | null = null
+ p.onData((d) => (out += d))
+ p.onExit((e) => (exit = e.exitCode))
+ await until(() => exit !== null)
+ expect(exit).toBe(255)
+ expect(out).toMatch(/ssh -G failed/)
+ })
+
+ it('decodes a multi-byte character split across packets', async () => {
+ const p = new NativeSshPty(mux(), argv(), { cols: 80, rows: 24 })
+ let out = ''
+ p.onData((d) => (out += d))
+ await until(() => serverCh !== null && out.includes('ready'))
+ const bytes = Buffer.from('ğ', 'utf8')
+ serverCh!.write(bytes.subarray(0, 1))
+ await new Promise((r) => setTimeout(r, 20))
+ serverCh!.write(bytes.subarray(1))
+ await until(() => out.includes('ğ'))
+ expect(out).toContain('ğ')
+ expect(out).not.toContain('�')
+ })
+})
diff --git a/src/core/remote-ssh/native/native-pty.ts b/src/core/remote-ssh/native/native-pty.ts
new file mode 100644
index 000000000..18b1187a8
--- /dev/null
+++ b/src/core/remote-ssh/native/native-pty.ts
@@ -0,0 +1,128 @@
+// A remote terminal over the native transport, shaped like the node-pty IPty PtyManager holds.
+//
+// On POSIX a remote terminal is `ssh -t … tmux …` run as a local pty program, and the local pty
+// only relays bytes. Over the native transport there is no ssh process: the pty is a channel on
+// the project's one connection (the remote side allocates the tty), and this adapter is the object
+// PtyManager keeps in `session.proc`. The same precedent as SessionHostPty: PtyManager uses only
+// onData / onExit / write / resize / kill / pause / resume.
+//
+// Behaviour is the ssh client's, so nothing downstream learns a new failure shape:
+// - bytes written before the channel is open are queued, not dropped (a node types its launch
+// line as soon as create() resolves);
+// - a connection that cannot be brought up prints ssh's reason into the terminal and exits 255;
+// - the channel closing (remote exit, dropped connection) exits with the remote status, else 255 —
+// the code SshReconnector reads as "the transport dropped".
+
+import { EventEmitter } from 'events'
+import { StringDecoder } from 'string_decoder'
+import type { ClientChannel } from 'ssh2'
+import { channelExit, type NativeMux } from './native-mux'
+import { parseSshArgv } from './ssh-argv'
+
+interface Disposable {
+ dispose(): void
+}
+
+export class NativeSshPty {
+ readonly pid = 0
+ readonly process = 'ssh'
+ handleFlowControl = false
+ cols: number
+ rows: number
+ private events = new EventEmitter()
+ private channel: ClientChannel | null = null
+ private queue: (string | Buffer)[] = []
+ private exited = false
+ private killed = false
+ private paused = false
+
+ constructor(mux: NativeMux, argv: string[], opts: { cols: number; rows: number; name?: string }) {
+ this.cols = opts.cols
+ this.rows = opts.rows
+ let parsed
+ try {
+ parsed = parseSshArgv(argv)
+ if (parsed.kind !== 'exec' || !parsed.tty) throw new Error('native ssh transport: not a pty argv')
+ } catch (e) {
+ queueMicrotask(() => this.fail((e as Error).message))
+ return
+ }
+ mux.shell(parsed, { cols: this.cols, rows: this.rows, term: opts.name }).then(
+ (ch) => {
+ if (this.killed) {
+ ch.close()
+ return
+ }
+ this.channel = ch
+ // One decoder per stream: a multi-byte character split across two packets must not become
+ // two replacement characters.
+ const out = new StringDecoder('utf8')
+ const err = new StringDecoder('utf8')
+ ch.on('data', (d: Buffer) => this.emitData(out.write(d)))
+ ch.stderr.on('data', (d: Buffer) => this.emitData(err.write(d)))
+ ch.on('close', () => this.exit(channelExit(ch).code ?? 255))
+ ch.on('error', () => {})
+ if (this.paused) ch.pause()
+ for (const q of this.queue.splice(0)) ch.write(q)
+ // A resize that arrived while the channel was opening.
+ ch.setWindow(this.rows, this.cols, 0, 0)
+ },
+ (e: Error) => this.fail(e.message)
+ )
+ }
+
+ onData(listener: (data: string) => void): Disposable {
+ this.events.on('data', listener)
+ return { dispose: () => this.events.off('data', listener) }
+ }
+
+ onExit(listener: (e: { exitCode: number; signal?: number }) => void): Disposable {
+ this.events.on('exit', listener)
+ return { dispose: () => this.events.off('exit', listener) }
+ }
+
+ write(data: string | Buffer): void {
+ if (this.exited) return
+ if (this.channel) this.channel.write(data)
+ else this.queue.push(data)
+ }
+
+ resize(cols: number, rows: number): void {
+ this.cols = cols
+ this.rows = rows
+ this.channel?.setWindow(rows, cols, 0, 0)
+ }
+
+ kill(): void {
+ this.killed = true
+ if (this.channel) this.channel.close()
+ else this.exit(255)
+ }
+
+ pause(): void {
+ this.paused = true
+ this.channel?.pause()
+ }
+
+ resume(): void {
+ this.paused = false
+ this.channel?.resume()
+ }
+
+ clear(): void {}
+
+ private emitData(s: string): void {
+ if (s) this.events.emit('data', s)
+ }
+
+ private fail(message: string): void {
+ this.events.emit('data', `${message}\r\n`)
+ this.exit(255)
+ }
+
+ private exit(code: number): void {
+ if (this.exited) return
+ this.exited = true
+ this.events.emit('exit', { exitCode: code })
+ }
+}
diff --git a/src/core/remote-ssh/native/native-runtime.ts b/src/core/remote-ssh/native/native-runtime.ts
new file mode 100644
index 000000000..aae53645f
--- /dev/null
+++ b/src/core/remote-ssh/native/native-runtime.ts
@@ -0,0 +1,118 @@
+// The one NativeMux of this process, and the helpers every runner uses to reach it.
+//
+// ONE instance for the whole process for the same reason SshChildGate and remotePtySpawnGate are
+// module-level: every seam (SshProjectManager's runners, pty-manager's execs, remote-git, the
+// setup runner, the terminal adapter) addresses a project's connection by its ControlPath, and two
+// instances would mean two connections to one host — the thing this transport exists to prevent.
+
+import { execFile } from 'child_process'
+import fs from 'fs'
+import path from 'path'
+import { findExecutableSync } from '../../exec-path'
+import { NativeMux, WINDOWS_OPENSSH_AGENT_PIPE, type ExecResult } from './native-mux'
+import { parseSshG, sshGArgs } from './ssh-config'
+import type { SshTarget } from './ssh-argv'
+import { runSshArgv, useNativeSsh } from './native-invoke'
+
+export { useNativeSsh }
+
+let instance: NativeMux | null = null
+type PassphrasePrompt = (identityFile: string, req: { retry: boolean; target: string }) => Promise<string | null>
+let passphrasePrompt: PassphrasePrompt | null = null
+
+/** Main installs its passphrase dialog here (the same one the askpass relay raises on POSIX). */
+export function setNativePassphrasePrompt(fn: PassphrasePrompt | null): void {
+ passphrasePrompt = fn
+}
+
+/** The ssh binary, used only for `ssh -G` (config evaluation), never as a transport here. */
+function sshForConfig(): string {
+ return (
+ findExecutableSync('ssh', ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh']) ??
+ (process.platform === 'win32'
+ ? path.join(process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe')
+ : 'ssh')
+ )
+}
+
+function resolveHost(t: SshTarget) {
+ return new Promise<ReturnType<typeof parseSshG>>((resolve, reject) => {
+ execFile(sshForConfig(), sshGArgs(t), { timeout: 5_000, windowsHide: true }, (err, stdout) => {
+ if (err && !stdout) {
+ return reject(new Error(`ssh -G failed for ${t.user}@${t.host}: ${err.message}`))
+ }
+ try {
+ resolve(parseSshG(stdout))
+ } catch (e) {
+ reject(e)
+ }
+ })
+ })
+}
+
+/** Windows: the OpenSSH agent service's pipe when it exists. POSIX: the app agent, else the ambient one. */
+function defaultAgent(): string | undefined {
+ if (process.platform === 'win32') {
+ try {
+ return fs.existsSync(WINDOWS_OPENSSH_AGENT_PIPE) ? WINDOWS_OPENSSH_AGENT_PIPE : undefined
+ } catch {
+ return undefined
+ }
+ }
+ return process.env.NODETERM_APP_AGENT_SOCK || process.env.SSH_AUTH_SOCK || undefined
+}
+
+export function nativeMux(): NativeMux {
+ if (!instance) {
+ instance = new NativeMux({
+ resolveHost,
+ defaultAgent,
+ askPassphrase: (f, req) => (passphrasePrompt ? passphrasePrompt(f, req) : Promise.resolve(null)),
+ log: (line) => console.warn(line)
+ })
+ }
+ return instance
+}
+
+/** Test-only: forget the instance (and its connections). */
+export function resetNativeMuxForTests(): void {
+ instance?.exitAll()
+ instance = null
+}
+
+/** Is this program the ssh client (as every runner resolves it: absolute path or bare name)? */
+export function isSshProgram(file: string): boolean {
+ const base = path.basename(file).toLowerCase()
+ return base === 'ssh' || base === 'ssh.exe'
+}
+
+/** execFile's error shape for a non-zero native result, so callers' catch blocks read it unchanged. */
+export class NativeExecError extends Error {
+ code: number | null
+ signal: string | null
+ killed: boolean
+ stdout: string
+ stderr: string
+ constructor(r: ExecResult, argv: readonly string[]) {
+ const stderr = r.stderr.toString('utf8')
+ super(`Command failed: ssh ${argv.join(' ')}\n${stderr}`)
+ this.code = r.code
+ this.signal = r.signal
+ this.killed = r.timedOut
+ this.stdout = r.stdout.toString('utf8')
+ this.stderr = stderr
+ }
+}
+
+/**
+ * `execFileAsync(ssh, args, opts)` over the native transport: resolves `{stdout, stderr}` on exit
+ * 0, rejects a NativeExecError otherwise — the contract every promisified-execFile caller has.
+ */
+export async function nativeExecFileAsync(
+ args: readonly string[],
+ opts: { timeout?: number; input?: string | Buffer } = {}
+): Promise<{ stdout: string; stderr: string }> {
+ const r = await runSshArgv(nativeMux(), [...args], { stdin: opts.input, timeoutMs: opts.timeout })
+ if (r.code === 0 && !r.timedOut) return { stdout: r.stdout.toString('utf8'), stderr: r.stderr.toString('utf8') }
+ throw new NativeExecError(r, args)
+}
diff --git a/src/core/remote-ssh/remote-git.ts b/src/core/remote-ssh/remote-git.ts
index 3c2e871e1..adcd3a55e 100644
--- a/src/core/remote-ssh/remote-git.ts
+++ b/src/core/remote-ssh/remote-git.ts
@@ -6,6 +6,7 @@
import { execFile } from 'child_process'
import { promisify } from 'util'
import { childArgs } from './control-master'
+import { nativeExecFileAsync, useNativeSsh } from './native/native-runtime'
import { findExecutableSync, shellPathNow } from '../exec-path'
import { posixQuote, quoteRemotePath, type SshConnection } from '../../shared/ssh'
@@ -53,7 +54,11 @@ export async function runRemoteGit(
const env = process.env.NODETERM_APP_AGENT_SOCK
? { ...process.env, SSH_AUTH_SOCK: process.env.NODETERM_APP_AGENT_SOCK }
: process.env
- const { stdout } = await run(ssh, remoteGitArgs(ref.conn, ref.controlPath, cwd, args), { maxBuffer, env })
+ const argv = remoteGitArgs(ref.conn, ref.controlPath, cwd, args)
+ // Native transport (Windows): the project's one connection, not an ssh that cannot multiplex.
+ const { stdout } = useNativeSsh()
+ ? await nativeExecFileAsync(argv, { timeout: 60_000 })
+ : await run(ssh, argv, { maxBuffer, env })
return { ok: true, out: stdout.replace(/\n$/, ''), err: '' }
} catch (e) {
const err = e as { stdout?: string; stderr?: string; message?: string }
diff --git a/src/main/index.ts b/src/main/index.ts
index de78adbea..4428b2ab5 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -19,6 +19,7 @@ import { IPC } from '../shared/ipc'
// in-memory and redacted at its push boundary; the panel/IPC side is gated on the setting.
const logBuffer = new LogBuffer()
installLogSink(logBuffer)
+import { nativeMux, useNativeSsh } from '../core/remote-ssh/native/native-runtime'
import { writeFilesToClipboard } from './clipboard-files'
import { pickProjectIcon } from './project-icon-upload'
import { allowGuestNavigation } from './webview-nav'
@@ -4718,7 +4719,10 @@ app.whenReady().then(async () => {
hasLiveRef: (projectId) => !!mgr.refForProject(projectId),
busy: (projectId) => inFlight.has(projectId),
// Reuse-only gate: no socket file ⇒ no master to adopt ⇒ this project is left alone.
- hasControlSocket: (projectId) => existsSync(controlPathFor(projectId))
+ // Native transport (Windows): there is no socket FILE, and a connection never outlives the
+ // app run — ask the transport whether it holds one for this path.
+ hasControlSocket: (projectId) =>
+ useNativeSsh() ? nativeMux().check(controlPathFor(projectId)) : existsSync(controlPathFor(projectId))
})
for (const projectId of plan.poll) {
inFlight.add(projectId)
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 34167f7dd..8b80b57db 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -1,3 +1,5 @@
+import { nativeMux, setNativePassphrasePrompt, useNativeSsh } from '../../core/remote-ssh/native/native-runtime'
+import { runScpArgv, runSshArgv, startNativeMaster } from '../../core/remote-ssh/native/native-invoke'
import { promises as fs } from 'fs'
import path from 'path'
import { createHash, randomUUID } from 'crypto'
@@ -2748,9 +2750,19 @@ export function initSshProject(
ipcMain.handle(IPC.sshPassphraseSubmit, (_e, requestId: string, value: string | null) =>
resolvePassphrasePrompt(requestId, value)
)
+ // WINDOWS (and NODETERM_NATIVE_SSH=1): OpenSSH cannot multiplex there, so every runner below is
+ // served by the in-process transport instead (core/remote-ssh/native/). The manager does not
+ // know: it still builds OpenSSH argv and reads OpenSSH-shaped answers. Decided ONCE here, at
+ // boot, so a single app run never mixes the two transports for one ControlPath.
+ const native = useNativeSsh()
+ if (native) {
+ setNativePassphrasePrompt(async (identityFile, req) =>
+ (await promptForPassphrase({ identityFile, retry: req.retry, target: req.target })) ?? null
+ )
+ }
const mgr = new SshProjectManager({
userDataDir: app.getPath('userData'),
- spawnMaster: (args, env) => {
+ spawnMaster: native ? (args) => startNativeMaster(nativeMux(), args) : (args, env) => {
// Capture the master's stderr (stdin/stdout stay ignored) so a failed connect can report the
// real ssh error instead of a generic timeout. Buffer is capped so a chatty host can't grow it
// unbounded; the master is long-lived and mostly silent, so this holds only the connect-time
@@ -2788,7 +2800,9 @@ export function initSshProject(
...(askpassScriptPath ? askpassServer.envFor(identityFile, askpassScriptPath) : {}),
...appSshAgent.env()
}),
- ensureAgent: () => appSshAgent.start(),
+ // No app-private ssh-agent on the native transport: Windows' ssh-agent is a service and has no
+ // `-a <socket>`, and the native transport authenticates in-process (agent pipe, then key files).
+ ensureAgent: native ? async () => {} : () => appSshAgent.start(),
// The `ssh -G` probe that honors a config-level `IdentityAgent SSH_AUTH_SOCK` (issue #427):
// shared with the pty spawn path in core, so the master and the fallback children can never
// disagree about which agent a host is routed at.
@@ -2798,10 +2812,13 @@ export function initSshProject(
// real project connects).
onIdle: () => appSshAgent.scheduleStop(),
onTunnelVerified,
- askpassWasCancelled: (masterPid) => askpassServer.wasCancelledBy(masterPid),
- askpassIsPrompting: () => askpassServer.isPromptingAny(),
- askpassAsked: (masterPid) => askpassServer.askedBy(masterPid),
- runSync: (args) => {
+ // Native: a declined passphrase is reported in the master's own error text (native-mux.ts), and
+ // the "key held only in your system agent" hint is about the app-private agent, which the
+ // native transport does not use — so answer "asked" to keep that hint off.
+ askpassWasCancelled: native ? () => false : (masterPid) => askpassServer.wasCancelledBy(masterPid),
+ askpassIsPrompting: native ? () => false : () => askpassServer.isPromptingAny(),
+ askpassAsked: native ? () => true : (masterPid) => askpassServer.askedBy(masterPid),
+ runSync: native ? (args) => void runSshArgv(nativeMux(), args) : (args) => {
// Quit path only (disconnectAll). Bounded hard: `before-quit` is blocked while this runs, and
// an unreachable host must not add seconds to every quit.
try {
@@ -2817,7 +2834,14 @@ export function initSshProject(
// Mux control commands and the terminals themselves are never queued (see ssh-child-gate.ts).
run: (args, stdin) =>
sshChildGate.run(args, () =>
- new Promise<{ code: number; stdout: string }>((resolve) => {
+ native
+ ? // Still gated: sshd's MaxSessions bounds channels on ONE connection just as it bounds
+ // mux clients on a ControlMaster.
+ runSshArgv(nativeMux(), args, { stdin, timeoutMs: 15000 }).then((r) => ({
+ code: r.timedOut ? 1 : (r.code ?? 1),
+ stdout: r.stdout.toString('utf-8')
+ }))
+ : new Promise<{ code: number; stdout: string }>((resolve) => {
// 16 MB ceiling: remote transcript reads pull up to REMOTE_TRANSCRIPT_CAP (5 MB) via
// RemoteFile; the default 1 MB maxBuffer would kill the child and silently break the
// remote context meter / subagent transcript / content search for large transcripts.
@@ -2848,7 +2872,9 @@ export function initSshProject(
// Deliberately NOT through `sshChildGate`: after a sleep the gate is typically full of children
// hung on the very master this probes, and queueing behind them would time the queue.
probe: (args, timeoutMs) =>
- new Promise((resolve) => {
+ native
+ ? runSshArgv(nativeMux(), args, { timeoutMs }).then((r) => (r.timedOut ? 'timeout' : 'answered'))
+ : new Promise((resolve) => {
execFile(
ssh,
args,
@@ -2857,7 +2883,9 @@ export function initSshProject(
)
}),
runScp: (args) =>
- new Promise((resolve) => {
+ native
+ ? runScpArgv(nativeMux(), args).then((r) => ({ code: r.code }))
+ : new Promise((resolve) => {
// Same reason as `run`: scp re-authenticates when the master socket is gone.
execFile(scp, args, { maxBuffer: 1024 * 1024, env: { ...process.env, ...appSshAgent.env() } }, (err) =>
resolve({ code: err ? 1 : 0 })
diff --git a/src/main/remote-ssh/ssh-setup-runner.ts b/src/main/remote-ssh/ssh-setup-runner.ts
index 9b633cfc4..ad824eaae 100644
--- a/src/main/remote-ssh/ssh-setup-runner.ts
+++ b/src/main/remote-ssh/ssh-setup-runner.ts
@@ -1,3 +1,5 @@
+import { nativeMux, useNativeSsh } from '../../core/remote-ssh/native/native-runtime'
+import { spawnSshArgvStream } from '../../core/remote-ssh/native/native-invoke'
import { spawn } from 'node:child_process'
import { childArgs } from '../../core/remote-ssh/control-master'
import { findExecutableSync } from '../../core/exec-path'
@@ -181,11 +183,16 @@ export function makeSshSetupRunner(
const remote = buildSetupRemoteCommand(cwd, env, script)
let child: ReturnType<typeof spawn>
try {
- child = spawn(sshPath(), childArgs(ref.conn, ref.controlPath, remote), {
- stdio: ['ignore', 'pipe', 'pipe'],
- windowsHide: true,
- env: { ...process.env, ...agentEnv() }
- })
+ const argv = childArgs(ref.conn, ref.controlPath, remote)
+ // Native transport (Windows): a channel on the project's one connection, shaped like the
+ // child this code already drives (pipes, close, error, kill).
+ child = useNativeSsh()
+ ? (spawnSshArgvStream(nativeMux(), argv) as unknown as ReturnType<typeof spawn>)
+ : spawn(sshPath(), argv, {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ windowsHide: true,
+ env: { ...process.env, ...agentEnv() }
+ })
} catch (e) {
// `spawn` throws SYNCHRONOUSLY for a malformed invocation (a NUL byte in an argument, a bad
// option object) — only ENOENT & co. arrive as an `error` event. Same reported shape either way.