Skip to content

The agent that grows with you

fix(desktop): resolve the Windows ssh client instead of hard-coding System32 OpenSSH

Austin Picketta35f600b8aa4
diff --git a/apps/desktop/electron/backend-start-failure.test.ts b/apps/desktop/electron/backend-start-failure.test.ts
index 8a991101ba0..e23eca48be7 100644
--- a/apps/desktop/electron/backend-start-failure.test.ts
+++ b/apps/desktop/electron/backend-start-failure.test.ts
@@ -7,11 +7,14 @@ import {
isHostKeyChangedBootFailure,
isRetryableRemoteBootFailure,
isSshAuthFailedBootFailure,
+ isSshClientFailedBootFailure,
shouldHoldBootProgressForReauth,
shouldLatchBackendStartFailure,
shouldLatchHostKeyChangedFailure,
shouldLatchRemoteReauthFailure,
- shouldLatchSshAuthFailure
+ shouldLatchSshAuthFailure,
+ shouldLatchSshClientFailure,
+ sshClientFailedError
} from './backend-start-failure'
import { SshConnection } from './ssh-connection'
@@ -211,3 +214,42 @@ test('FIX #95701: with no reauth latch every boot-progress update flows as befor
assert.equal(shouldHoldBootProgressForReauth(latch, { error: 'Desktop boot failed: spawn ENOENT' }), false)
}
})
+
+test('FIX #103288: a failed local `ssh -G` probe latches and is never auto-retried', () => {
+ const error = sshClientFailedError(
+ 'C:\\Windows\\System32\\OpenSSH\\ssh.exe',
+ new Error('Command failed: ssh.exe -G -- box'),
+ 'win32'
+ )
+
+ assert.equal(isSshClientFailedBootFailure(error), true)
+ assert.match(error.message, /System32\\OpenSSH\\ssh\.exe/)
+ assert.match(error.message, /Command failed/)
+ assert.match(error.message, /desktop\.ssh_path/)
+
+ const context = { attemptedRemote: true, isReauth: false, isSshClientFailed: true }
+
+ assert.equal(shouldLatchSshClientFailure(context), true)
+ assert.equal(isRetryableRemoteBootFailure(context), false)
+
+ // Ordinary remote faults keep retrying; local boots never take this latch.
+ const unreachable = new Error('ssh: connect to host box port 22: Connection timed out')
+
+ assert.equal(isSshClientFailedBootFailure(unreachable), false)
+ assert.equal(
+ isRetryableRemoteBootFailure({
+ attemptedRemote: true,
+ isReauth: false,
+ isSshClientFailed: isSshClientFailedBootFailure(unreachable)
+ }),
+ true
+ )
+ assert.equal(shouldLatchSshClientFailure({ attemptedRemote: false, isReauth: false, isSshClientFailed: true }), false)
+})
+
+test('FIX #103288: the desktop.ssh_path hint is Windows-only', () => {
+ const error = sshClientFailedError('ssh', new Error('boom'), 'darwin')
+
+ assert.equal(isSshClientFailedBootFailure(error), true)
+ assert.doesNotMatch(error.message, /ssh_path/)
+})
diff --git a/apps/desktop/electron/backend-start-failure.ts b/apps/desktop/electron/backend-start-failure.ts
index 58441409e7a..f41a9386a1e 100644
--- a/apps/desktop/electron/backend-start-failure.ts
+++ b/apps/desktop/electron/backend-start-failure.ts
@@ -102,6 +102,13 @@ export interface RemoteBootRetryContext {
* ssh-agent or fixes the connection settings: terminal, not connectivity.
*/
isSshAuthFailed?: boolean
+ /**
+ * True when the LOCAL ssh client failed (`ssh -G` could not run or exited
+ * non-zero). `-G` never touches the network, so a retry re-runs the same
+ * doomed probe: terminal until the user fixes the client or sets
+ * `desktop.ssh_path` (#103288).
+ */
+ isSshClientFailed?: boolean
}
/**
@@ -143,6 +150,46 @@ export function isSshAuthFailedBootFailure(error: unknown): boolean {
)
}
+export const SSH_CLIENT_FAILED = 'ssh-client-failed'
+
+/**
+ * Wrap a failed local `ssh -G` probe as a terminal, tagged boot failure that
+ * names the client binary. On Windows the message points at
+ * `desktop.ssh_path`, the only way past a broken in-box OpenSSH (#103288).
+ */
+export function sshClientFailedError(sshBinary: string, cause: unknown, platform: string = process.platform): Error {
+ const detail = cause instanceof Error ? cause.message : String(cause ?? '')
+
+ const hint =
+ platform === 'win32'
+ ? " Set desktop.ssh_path in config.yaml to a working ssh.exe (for example Git for Windows' usr\\bin\\ssh.exe) and retry."
+ : ''
+
+ const error = new Error(
+ `The local SSH client (${sshBinary}) failed to resolve the connection config: ${detail}.${hint}`
+ ) as Error & {
+ kind: string
+ }
+
+ error.kind = SSH_CLIENT_FAILED
+
+ return error
+}
+
+/** A failed local ssh client probe, tagged by sshClientFailedError. */
+export function isSshClientFailedBootFailure(error: unknown): boolean {
+ return (error as { kind?: string } | null | undefined)?.kind === SSH_CLIENT_FAILED
+}
+
+/**
+ * Whether a failed remote boot should latch because the local ssh client
+ * itself failed. Same rationale as the credential latch: unlatched, every
+ * api call re-drives boot and the overlay never holds still (#103288).
+ */
+export function shouldLatchSshClientFailure(context: RemoteBootRetryContext): boolean {
+ return context.attemptedRemote && context.isSshClientFailed === true
+}
+
/**
* Whether a failed remote boot should latch (into `backendStartFailure`)
* because SSH rejected the credentials (#72698). Unlatched, every
@@ -188,7 +235,8 @@ export function isRetryableRemoteBootFailure(context: RemoteBootRetryContext): b
context.attemptedRemote &&
!context.isReauth &&
context.isHostKeyChanged !== true &&
- context.isSshAuthFailed !== true
+ context.isSshAuthFailed !== true &&
+ context.isSshClientFailed !== true
)
}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index d60f8e03968..c40109bb787 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -91,11 +91,14 @@ import {
isHostKeyChangedBootFailure,
isRetryableRemoteBootFailure,
isSshAuthFailedBootFailure,
+ isSshClientFailedBootFailure,
shouldHoldBootProgressForReauth,
shouldLatchBackendStartFailure,
shouldLatchHostKeyChangedFailure,
shouldLatchRemoteReauthFailure,
- shouldLatchSshAuthFailure
+ shouldLatchSshAuthFailure,
+ shouldLatchSshClientFailure,
+ sshClientFailedError
} from './backend-start-failure'
import { describeBootstrapFailure } from './bootstrap-failure-copy'
import {
@@ -533,6 +536,7 @@ import { ensureLoginShellPath } from './shell-path'
import { removeStaleSingletonLock } from './singleton-lock'
import { createSourcePythonBackend, resolveSourceInstallationBackend, type SourceBackend } from './source-backend'
import { resolveSourcePython } from './source-python'
+import { resolveSshBinary } from './ssh-binary'
import { createBootstrapCoordinator, sshConfigFingerprint } from './ssh-bootstrap-coordinator'
import { collectSshConfigHosts, parseSshGOutput } from './ssh-config'
import { createSshProbeConnection, pickLocalPort, redactSecrets, SshConnection } from './ssh-connection'
@@ -1093,6 +1097,10 @@ const HERMES_HOME: string = resolveDesktopHermesHome({
// Start-menu / .desktop entry ran with no `--js-flags` at all. Apply them here
// from config.yaml, before `ready` — Chromium copies `js-flags` to renderer
// processes only from the browser's pre-launch command line.
+// `desktop.ssh_path` (#103288) rides the same pre-window read: an explicit
+// Windows ssh client for when the in-box OpenSSH is missing or broken.
+let desktopSshPathOverride = ''
+
{
let desktopLaunchYaml: string = ''
@@ -1103,6 +1111,7 @@ const HERMES_HOME: string = resolveDesktopHermesHome({
}
const desktopLaunchConfig = readDesktopLaunchConfig(desktopLaunchYaml)
+ desktopSshPathOverride = desktopLaunchConfig.sshPath || ''
// `desktop.renderer_accessibility: false` must reach packaged launches too,
// not only the `hermes desktop` launcher's env bridge (#118271).
@@ -10264,11 +10273,25 @@ async function reachablePreviewUrl(webContentsId: number, rawUrl: string): Promi
}
}
+// The ssh client every desktop spawn uses (#103288): `desktop.ssh_path`, then
+// the in-box System32 OpenSSH, then Git for Windows' ssh.exe, then PATH.
+// Bare `ssh` on every other platform.
+function desktopSshBinary(): string {
+ return resolveSshBinary({
+ platform: process.platform,
+ override: desktopSshPathOverride,
+ env: {
+ systemRoot: process.env.SystemRoot || process.env.windir || 'C:\\Windows',
+ localAppData: process.env.LOCALAPPDATA || '',
+ programFiles: process.env['ProgramFiles'] || 'C:\\Program Files',
+ programFilesX86: process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)'
+ },
+ fs: { existsSync: fileExists, readdirSync: dir => fs.readdirSync(dir) }
+ })
+}
+
async function effectiveSshConfigFingerprint(sshConfig) {
- const ssh =
- process.platform === 'win32'
- ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe')
- : 'ssh'
+ const ssh = desktopSshBinary()
const args = ['-G']
@@ -10281,7 +10304,17 @@ async function effectiveSshConfigFingerprint(sshConfig) {
}
args.push('--', sshConfig.user ? `${sshConfig.user}@${sshConfig.host}` : sshConfig.host)
- const output = await execText(ssh, args, { timeout: 10_000 })
+ let output: string
+
+ try {
+ output = await execText(ssh, args, { timeout: 10_000 })
+ } catch (error) {
+ // `ssh -G` only parses local config, so a failure here is the local client
+ // itself (missing, broken, or a bad ssh_config) and retrying cannot fix
+ // it. Tag it terminal so boot lands on the failure overlay instead of
+ // re-driving the same probe every ~2s (#103288).
+ throw sshClientFailedError(ssh, error)
+ }
return crypto.createHash('sha256').update(output).digest('hex')
}
@@ -10404,6 +10437,7 @@ async function bootstrapSshConnectionInner(profile, sshConfig, reuseToken, sourc
{ host: sshConfig.host, user: sshConfig.user, port: sshConfig.port, keyPath: sshConfig.keyPath },
{
rememberLog: sshRememberLog,
+ sshBinary: desktopSshBinary(),
ownershipId: sshOwnershipKey(profile),
scope,
effectiveConfigFingerprint: sshConfig.effectiveConfigFingerprint
@@ -10867,7 +10901,7 @@ async function testDesktopConnectionConfig(input: any = {}) {
const ssh = createSshProbeConnection(
{ host: sshConfig.host, user: sshConfig.user, port: sshConfig.port, keyPath: sshConfig.keyPath },
- { rememberLog: sshRememberLog }
+ { rememberLog: sshRememberLog, sshBinary: desktopSshBinary() }
)
try {
@@ -11845,7 +11879,7 @@ async function openManagedSshUpdateTransport(
const ssh = createSshProbeConnection(
{ host: config.host, user: config.user, port: config.port, keyPath: config.keyPath },
- { rememberLog: sshRememberLog }
+ { rememberLog: sshRememberLog, sshBinary: desktopSshBinary() }
)
await ssh.open()
@@ -13615,6 +13649,7 @@ async function runHermesStart({ supervisorRecovery = false }: { supervisorRecove
const message = error instanceof Error ? error.message : String(error)
const hostKeyChanged = isHostKeyChangedBootFailure(error)
const sshAuthFailed = isSshAuthFailedBootFailure(error)
+ const sshClientFailed = isSshClientFailedBootFailure(error)
// Carry structured Cloud-down metadata through the boot-progress / IPC
// boundary when present, so the renderer overlay can key on it rather than
@@ -13656,6 +13691,14 @@ async function runHermesStart({ supervisorRecovery = false }: { supervisorRecove
backendStartFailure = error instanceof Error ? error : new Error(message)
}
+ // A dead local ssh client (`ssh -G` failed) is terminal too (#103288):
+ // every retry re-runs the same local probe, so boot looped every ~2s and
+ // the user never reached Settings. Latch it so the overlay holds still;
+ // reset/repair/apply-config release it (desktop.ssh_path needs a restart).
+ if (shouldLatchSshClientFailure({ attemptedRemote, isReauth: false, isSshClientFailed: sshClientFailed })) {
+ backendStartFailure = error instanceof Error ? error : new Error(message)
+ }
+
// A confirmed reauth rejection latches separately: it can't self-heal, and
// leaving it unlatched hides the overlay's "Sign in" button on every retry.
if (shouldLatchRemoteReauthFailure({ attemptedRemote, isReauth: isReauthRequiredError(error) })) {
@@ -13678,7 +13721,8 @@ async function runHermesStart({ supervisorRecovery = false }: { supervisorRecove
attemptedRemote,
isReauth: isReauthRequiredError(error),
isHostKeyChanged: hostKeyChanged,
- isSshAuthFailed: sshAuthFailed
+ isSshAuthFailed: sshAuthFailed,
+ isSshClientFailed: sshClientFailed
}),
running: false,
statusCode: Number.isInteger(statusCode) ? statusCode : undefined
@@ -16106,10 +16150,7 @@ ipcMain.handle('hermes:ssh-config:resolve', async (_event, host) => {
throw new Error('SSH host is required.')
}
- const ssh =
- process.platform === 'win32'
- ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe')
- : 'ssh'
+ const ssh = desktopSshBinary()
return new Promise((resolve, reject) => {
const child = spawn(ssh, ['-G', '--', value], hiddenWindowsChildOptions({ stdio: ['ignore', 'pipe', 'pipe'] }))
@@ -16371,7 +16412,7 @@ async function probeSshProfileInventory(connection) {
const ssh = createSshProbeConnection(
{ host: sshConfig.host, user: sshConfig.user, port: sshConfig.port, keyPath: sshConfig.keyPath },
- { rememberLog: sshRememberLog }
+ { rememberLog: sshRememberLog, sshBinary: desktopSshBinary() }
)
try {
@@ -18519,6 +18560,7 @@ const terminalIpc = registerTerminalIpc({
findOnPath,
rememberLog,
activeSshTerminalTarget,
+ sshBinary: desktopSshBinary,
ensureBackend: webContentsId => ensureTerminalBackend(webContentsId),
getSshConnectionState: scope => sshConnections.get(scope)
})
diff --git a/apps/desktop/electron/renderer-heap-flags.test.ts b/apps/desktop/electron/renderer-heap-flags.test.ts
index b942ad49465..d3eeedfda8f 100644
--- a/apps/desktop/electron/renderer-heap-flags.test.ts
+++ b/apps/desktop/electron/renderer-heap-flags.test.ts
@@ -89,4 +89,15 @@ describe('renderer heap flags', () => {
warn.mockRestore()
})
+
+ it('#103288: reads desktop.ssh_path as plain, single-quoted, and YAML double-quoted scalars', () => {
+ const read = (value: string) =>
+ readDesktopLaunchConfig(['desktop:', ` ssh_path: ${value}`, 'terminal:', ' ssh_path: nope'].join('\n')).sshPath
+
+ expect(read('C:\\Program Files\\Git\\usr\\bin\\ssh.exe')).toBe('C:\\Program Files\\Git\\usr\\bin\\ssh.exe')
+ expect(read("'C:\\Git\\usr\\bin\\ssh.exe' # Git's client")).toBe('C:\\Git\\usr\\bin\\ssh.exe')
+ expect(read('"C:\\\\Git\\\\usr\\\\bin\\\\ssh.exe"')).toBe('C:\\Git\\usr\\bin\\ssh.exe')
+ expect(read('""')).toBeUndefined()
+ expect(readDesktopLaunchConfig('terminal:\n ssh_path: C:\\x.exe').sshPath).toBeUndefined()
+ })
})
diff --git a/apps/desktop/electron/renderer-heap-flags.ts b/apps/desktop/electron/renderer-heap-flags.ts
index fa0b0a17682..85cbbbc57e4 100644
--- a/apps/desktop/electron/renderer-heap-flags.ts
+++ b/apps/desktop/electron/renderer-heap-flags.ts
@@ -13,6 +13,8 @@ export interface DesktopLaunchConfig {
rendererMaxOldSpaceMb: number
/** `desktop.renderer_accessibility`; unset when the key is absent or unreadable. */
rendererAccessibility?: boolean
+ /** `desktop.ssh_path`: explicit Windows ssh client (#103288); unset when absent. */
+ sshPath?: string
}
export interface PlannedSwitch {
@@ -64,7 +66,16 @@ export function readDesktopLaunchConfig(yamlText: string): DesktopLaunchConfig {
const [, key, rawValue] = keyed
const value = rawValue.replace(/\s+#.*$/, '')
- if (key === 'renderer_accessibility') {
+ if (key === 'ssh_path') {
+ // YAML double quotes escape backslashes ("C:\\Git\\usr\\bin\\ssh.exe");
+ // plain and single-quoted scalars keep them literally.
+ const doubleQuoted = /^"(.*)"$/.exec(value)
+ const sshPath = doubleQuoted ? doubleQuoted[1].replace(/\\\\/g, '\\') : unquote(value)
+
+ if (sshPath) {
+ out.sshPath = sshPath
+ }
+ } else if (key === 'renderer_accessibility') {
const word = unquote(value).toLowerCase()
if (['0', 'false', 'no', 'off', 'disabled'].includes(word)) {
diff --git a/apps/desktop/electron/ssh-binary.test.ts b/apps/desktop/electron/ssh-binary.test.ts
new file mode 100644
index 00000000000..72333c4ef5c
--- /dev/null
+++ b/apps/desktop/electron/ssh-binary.test.ts
@@ -0,0 +1,128 @@
+// #103288: one resolver picks the ssh client for every desktop spawn. Platform,
+// env and filesystem are passed as data; nothing touches process.platform.
+import { describe, expect, it } from 'vitest'
+
+import { gitForWindowsSshCandidates, resolveSshBinary, system32OpenSsh, type WindowsSshEnv } from './ssh-binary'
+
+const ENV: WindowsSshEnv = {
+ systemRoot: 'C:\\Windows',
+ localAppData: 'C:\\Users\\me\\AppData\\Local',
+ programFiles: 'C:\\Program Files',
+ programFilesX86: 'C:\\Program Files (x86)'
+}
+
+const SYSTEM32_SSH = 'C:\\Windows\\System32\\OpenSSH\\ssh.exe'
+const PROGRAM_FILES_GIT_SSH = 'C:\\Program Files\\Git\\usr\\bin\\ssh.exe'
+const PORTABLE_GIT_SSH = 'C:\\Users\\me\\AppData\\Local\\hermes\\git\\usr\\bin\\ssh.exe'
+
+// Compare on win32 separators whatever the host OS joins with.
+const norm = (p: string) => p.replace(/\//g, '\\')
+
+function fakeFs(files: string[], dirs: Record<string, string[]> = {}) {
+ const present = new Set(files.map(norm))
+ const probed: string[] = []
+
+ return {
+ probed,
+ fs: {
+ existsSync: (candidate: string) => {
+ probed.push(norm(candidate))
+
+ return present.has(norm(candidate))
+ },
+ readdirSync: (dir: string) => {
+ const entries = dirs[norm(dir)]
+
+ if (!entries) {
+ throw Object.assign(new Error(`ENOENT: ${dir}`), { code: 'ENOENT' })
+ }
+
+ return entries
+ }
+ }
+ }
+}
+
+describe('resolveSshBinary', () => {
+ it('keeps bare ssh on non-Windows platforms, ignores the override, and never probes the filesystem', () => {
+ for (const platform of ['darwin', 'linux', 'freebsd']) {
+ const { fs, probed } = fakeFs([SYSTEM32_SSH])
+
+ expect(resolveSshBinary({ platform, override: '/opt/ssh', env: ENV, fs })).toBe('ssh')
+ expect(probed).toEqual([])
+ }
+ })
+
+ it('returns an explicit desktop.ssh_path override verbatim, even when it does not exist', () => {
+ const { fs, probed } = fakeFs([SYSTEM32_SSH])
+
+ expect(resolveSshBinary({ platform: 'win32', override: ' D:\\tools\\ssh.exe ', env: ENV, fs })).toBe(
+ 'D:\\tools\\ssh.exe'
+ )
+ expect(probed).toEqual([])
+ })
+
+ it('prefers the in-box System32 OpenSSH when no override is set', () => {
+ const { fs } = fakeFs([SYSTEM32_SSH, PROGRAM_FILES_GIT_SSH])
+
+ expect(norm(resolveSshBinary({ platform: 'win32', override: '', env: ENV, fs }))).toBe(SYSTEM32_SSH)
+ })
+
+ it('honours a non-default SystemRoot', () => {
+ const { fs } = fakeFs(['D:\\Win\\System32\\OpenSSH\\ssh.exe'])
+
+ expect(norm(resolveSshBinary({ platform: 'win32', env: { ...ENV, systemRoot: 'D:\\Win' }, fs }))).toBe(
+ 'D:\\Win\\System32\\OpenSSH\\ssh.exe'
+ )
+ })
+
+ it("falls back to Git for Windows' ssh.exe when System32 OpenSSH is missing", () => {
+ const { fs } = fakeFs([PROGRAM_FILES_GIT_SSH])
+
+ expect(norm(resolveSshBinary({ platform: 'win32', env: ENV, fs }))).toBe(PROGRAM_FILES_GIT_SSH)
+ })
+
+ it('prefers the Hermes PortableGit ssh over a system Git install, matching resolveGitBinary order', () => {
+ const { fs } = fakeFs([PORTABLE_GIT_SSH, PROGRAM_FILES_GIT_SSH])
+
+ expect(norm(resolveSshBinary({ platform: 'win32', env: ENV, fs }))).toBe(PORTABLE_GIT_SSH)
+ })
+
+ it('falls back to bare ssh (PATH lookup) when no candidate exists', () => {
+ const { fs } = fakeFs([])
+
+ expect(resolveSshBinary({ platform: 'win32', env: ENV, fs })).toBe('ssh')
+ })
+})
+
+describe('gitForWindowsSshCandidates', () => {
+ it('maps every resolveGitBinary install root to usr\\bin\\ssh.exe, deduped and in order', () => {
+ const ugitRoot = 'C:\\Users\\me\\AppData\\Local\\UGit'
+ const ugitGit = `${ugitRoot}\\app-5.50.1\\resources\\app\\git\\cmd\\git.exe`
+ const { fs } = fakeFs([ugitGit], { [ugitRoot]: ['app-5.50.1'] })
+
+ expect(gitForWindowsSshCandidates(ENV, fs).map(norm)).toEqual([
+ PORTABLE_GIT_SSH,
+ `${ugitRoot}\\app-5.50.1\\resources\\app\\git\\usr\\bin\\ssh.exe`,
+ PROGRAM_FILES_GIT_SSH,
+ 'C:\\Program Files (x86)\\Git\\usr\\bin\\ssh.exe',
+ 'C:\\Users\\me\\AppData\\Local\\Programs\\Git\\usr\\bin\\ssh.exe'
+ ])
+ })
+
+ it('skips per-user candidates when LOCALAPPDATA is unset', () => {
+ const { fs } = fakeFs([])
+
+ expect(gitForWindowsSshCandidates({ ...ENV, localAppData: '' }, fs).map(norm)).toEqual([
+ PROGRAM_FILES_GIT_SSH,
+ 'C:\\Program Files (x86)\\Git\\usr\\bin\\ssh.exe'
+ ])
+ })
+})
+
+describe('system32OpenSsh', () => {
+ it('matches the path the desktop hard-coded before #103288', () => {
+ expect(system32OpenSsh('C:\\Windows')).toBe(SYSTEM32_SSH)
+ expect(system32OpenSsh('')).toBe(SYSTEM32_SSH)
+ })
+})
diff --git a/apps/desktop/electron/ssh-binary.ts b/apps/desktop/electron/ssh-binary.ts
new file mode 100644
index 00000000000..dbd31584135
--- /dev/null
+++ b/apps/desktop/electron/ssh-binary.ts
@@ -0,0 +1,77 @@
+// Which ssh client the desktop spawns (#103288).
+//
+// Windows used to hard-code %SystemRoot%\System32\OpenSSH\ssh.exe for the
+// `ssh -G` probes and the SSH terminal, while SshConnection spawned a bare
+// `ssh` off PATH. When the in-box OpenSSH component is missing or broken
+// (component-store corruption after an update makes every native ssh.exe exit
+// 255 with no output), no config could point the desktop at a working client
+// such as Git for Windows' bundled `usr\bin\ssh.exe`.
+//
+// Every ssh spawn now resolves through resolveSshBinary. It is pure: platform,
+// env slice and filesystem probe are injected so vitest can drive each branch.
+// Non-Windows always gets bare `ssh`, exactly as before.
+
+import path from 'node:path'
+
+import { type GitCandidateFs, windowsGitCandidates } from './git-binary-candidates'
+
+/** Windows env slice the resolver reads (injectable for tests). */
+export interface WindowsSshEnv {
+ localAppData: string
+ programFiles: string
+ programFilesX86: string
+ systemRoot: string
+}
+
+export interface SshBinaryInputs {
+ platform: string
+ /** `desktop.ssh_path` from config.yaml; empty when unset. Windows only. */
+ override?: string
+ env: WindowsSshEnv
+ fs: GitCandidateFs
+}
+
+/** The in-box Windows OpenSSH client under a Windows root. */
+export function system32OpenSsh(systemRoot: string): string {
+ return path.win32.join(systemRoot || 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe')
+}
+
+/**
+ * Git-for-Windows ssh.exe candidates, derived from the same install list
+ * resolveGitBinary uses (Hermes PortableGit, UGit, Program Files, per-user).
+ * Git ships its MSYS OpenSSH at `<git root>\usr\bin\ssh.exe`, and every git
+ * candidate is `<git root>\{cmd,bin}\git.exe`.
+ */
+export function gitForWindowsSshCandidates(env: WindowsSshEnv, fs: GitCandidateFs): string[] {
+ const roots = windowsGitCandidates(env, fs).map(gitExe => path.win32.dirname(path.win32.dirname(gitExe)))
+
+ return [...new Set(roots)].map(root => path.win32.join(root, 'usr', 'bin', 'ssh.exe'))
+}
+
+/**
+ * The ssh executable to spawn.
+ *
+ * Windows, in order: an explicit `desktop.ssh_path` (returned as-is so a typo
+ * fails loudly with its own path instead of silently using another client),
+ * then the in-box System32 OpenSSH, then Git for Windows' bundled ssh.exe,
+ * then bare `ssh` for PATH lookup. Every other platform: bare `ssh`.
+ */
+export function resolveSshBinary({ platform, override, env, fs }: SshBinaryInputs): string {
+ if (platform !== 'win32') {
+ return 'ssh'
+ }
+
+ const explicit = String(override ?? '').trim()
+
+ if (explicit) {
+ return explicit
+ }
+
+ const inbox = system32OpenSsh(env.systemRoot)
+
+ if (fs.existsSync(inbox)) {
+ return inbox
+ }
+
+ return gitForWindowsSshCandidates(env, fs).find(candidate => fs.existsSync(candidate)) || 'ssh'
+}
diff --git a/apps/desktop/electron/ssh-connection.test.ts b/apps/desktop/electron/ssh-connection.test.ts
index edaa965dbd7..8c3702a6073 100644
--- a/apps/desktop/electron/ssh-connection.test.ts
+++ b/apps/desktop/electron/ssh-connection.test.ts
@@ -1600,3 +1600,28 @@ test('a failed open releases its claim so the remaining holder can still close t
await live.close()
assert.equal(state.exits, 1, 'the failed opener left no phantom claim behind')
})
+
+test('#103288: every spawn uses the injected sshBinary; the default stays bare ssh', async () => {
+ const commands: string[] = []
+
+ const spawnFn: any = (cmd: string) => {
+ commands.push(cmd)
+
+ return fakeChild({ code: 0 })
+ }
+
+ const custom = createSshProbeConnection(
+ { host: 'box', user: 'me' },
+ { spawnFn, sshBinary: 'C:\\Program Files\\Git\\usr\\bin\\ssh.exe' }
+ )
+
+ await custom.open()
+ await custom.exec('true')
+ assert.ok(commands.length >= 2, 'open + exec both spawned')
+ assert.deepEqual([...new Set(commands)], ['C:\\Program Files\\Git\\usr\\bin\\ssh.exe'])
+
+ commands.length = 0
+ const plain = createSshProbeConnection({ host: 'box', user: 'me' }, { spawnFn })
+ await plain.open()
+ assert.deepEqual([...new Set(commands)], ['ssh'])
+})
diff --git a/apps/desktop/electron/ssh-connection.ts b/apps/desktop/electron/ssh-connection.ts
index 527d0d6e7b9..60545532ca5 100644
--- a/apps/desktop/electron/ssh-connection.ts
+++ b/apps/desktop/electron/ssh-connection.ts
@@ -494,8 +494,9 @@ function sshErrorMessage(kind, conn, stderr?) {
// Resolves { code, signal, stdout, stderr }. `signal` is Node's close signal
// (null on a normal exit). On timeout the child is SIGKILLed and the promise
-// rejects with err.kind = TIMEOUT. `spawnFn` is injectable for tests.
-function runSsh(args, { timeoutMs, spawnFn = spawn, stdin = 'ignore', stdinData, signal }: any = {}) {
+// rejects with err.kind = TIMEOUT. `spawnFn` is injectable for tests; `command`
+// is the ssh client binary (resolveSshBinary; bare `ssh` by default).
+function runSsh(args, { timeoutMs, spawnFn = spawn, command = 'ssh', stdin = 'ignore', stdinData, signal }: any = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
const error: any = new Error('SSH operation was cancelled.')
@@ -509,7 +510,7 @@ function runSsh(args, { timeoutMs, spawnFn = spawn, stdin = 'ignore', stdinData,
let child
try {
- child = spawnFn('ssh', args, { stdio: [useStdinPipe ? 'pipe' : 'ignore', 'pipe', 'pipe'] })
+ child = spawnFn(command, args, { stdio: [useStdinPipe ? 'pipe' : 'ignore', 'pipe', 'pipe'] })
} catch (error) {
reject(error)
@@ -671,6 +672,8 @@ class SshConnection {
port: number
keyPath: string
controlPath: string
+ /** ssh client binary every spawn uses (resolveSshBinary; bare `ssh` by default). */
+ sshBinary: string
_spawnFn: any
_log: (msg: string) => void
_connectTimeoutMs: number
@@ -719,6 +722,7 @@ class SshConnection {
this._forwardedSpecs = new Set()
this._spawnFn = opts.spawnFn || spawn
+ this.sshBinary = opts.sshBinary || 'ssh'
this._log = typeof opts.rememberLog === 'function' ? opts.rememberLog : () => {}
this._connectTimeoutMs = opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS
@@ -862,6 +866,7 @@ class SshConnection {
result = await runSsh(buildExecArgs(this, 'exit 0', this._connectTimeoutMs), {
timeoutMs: this._connectTimeoutMs,
spawnFn: this._spawnFn,
+ command: this.sshBinary,
signal
})
} catch (error) {
@@ -883,7 +888,12 @@ class SshConnection {
let result
try {
- result = await runSsh(args, { timeoutMs: this._connectTimeoutMs, spawnFn: this._spawnFn, signal })
+ result = await runSsh(args, {
+ timeoutMs: this._connectTimeoutMs,
+ spawnFn: this._spawnFn,
+ command: this.sshBinary,
+ signal
+ })
} catch (error) {
throw this._connectFailed(error)
}
@@ -908,7 +918,12 @@ class SshConnection {
: buildExecArgs(this, 'exit 0', this._connectTimeoutMs)
try {
- const result: any = await runSsh(args, { timeoutMs: this._connectTimeoutMs, spawnFn: this._spawnFn, signal })
+ const result: any = await runSsh(args, {
+ timeoutMs: this._connectTimeoutMs,
+ spawnFn: this._spawnFn,
+ command: this.sshBinary,
+ signal
+ })
return sshCloseOk(result)
} catch (error: any) {
@@ -953,6 +968,7 @@ class SshConnection {
const result: any = await runSsh(buildExecArgs(this, 'exit 0', this._connectTimeoutMs), {
timeoutMs: this._connectTimeoutMs,
spawnFn: this._spawnFn,
+ command: this.sshBinary,
signal
})
@@ -974,7 +990,8 @@ class SshConnection {
try {
await runSsh(buildControlArgs(this, 'exit', [], this._connectTimeoutMs), {
timeoutMs: this._connectTimeoutMs,
- spawnFn: this._spawnFn
+ spawnFn: this._spawnFn,
+ command: this.sshBinary
})
} catch {
void 0
@@ -999,6 +1016,7 @@ class SshConnection {
result = await runSsh(args, {
timeoutMs: timeoutMs ?? this._execTimeoutMs,
spawnFn: this._spawnFn,
+ command: this.sshBinary,
...(stdinData != null ? { stdinData } : {})
})
} catch (error) {
@@ -1022,7 +1040,7 @@ class SshConnection {
// cascaded into SIGTERM of a healthy backend (#96266).
_startNoMuxTunnelChild(tunnel: any, spec: string, args: string[], localPort: number | string) {
return new Promise<void>((resolve, reject) => {
- const child = this._spawnFn('ssh', args, { stdio: ['ignore', 'ignore', 'pipe'] })
+ const child = this._spawnFn(this.sshBinary, args, { stdio: ['ignore', 'ignore', 'pipe'] })
tunnel.child = child
let stderr = ''
let readyConfirmed = false
@@ -1194,7 +1212,11 @@ class SshConnection {
let result
try {
- result = await runSsh(args, { timeoutMs: this._forwardTimeoutMs, spawnFn: this._spawnFn })
+ result = await runSsh(args, {
+ timeoutMs: this._forwardTimeoutMs,
+ spawnFn: this._spawnFn,
+ command: this.sshBinary
+ })
} catch (error) {
throw this._fail(error)
}
@@ -1235,7 +1257,7 @@ class SshConnection {
const args = buildControlArgs(this, 'cancel', ['-L', spec], this._connectTimeoutMs)
try {
- await runSsh(args, { timeoutMs: this._forwardTimeoutMs, spawnFn: this._spawnFn })
+ await runSsh(args, { timeoutMs: this._forwardTimeoutMs, spawnFn: this._spawnFn, command: this.sshBinary })
this._logLine(`cancelled forward 127.0.0.1:${localPort}`)
} catch (error: any) {
this._logLine(`cancelForward failed (ignored): ${error.message}`)
@@ -1293,7 +1315,11 @@ class SshConnection {
const args = buildControlArgs(this, 'exit', [], this._connectTimeoutMs)
try {
- const result: any = await runSsh(args, { timeoutMs: this._connectTimeoutMs, spawnFn: this._spawnFn })
+ const result: any = await runSsh(args, {
+ timeoutMs: this._connectTimeoutMs,
+ spawnFn: this._spawnFn,
+ command: this.sshBinary
+ })
if (!sshCloseOk(result)) {
throw this._fail(result)
diff --git a/apps/desktop/electron/terminal-ipc.ts b/apps/desktop/electron/terminal-ipc.ts
index 3bf6efe8486..0a57231511a 100644
--- a/apps/desktop/electron/terminal-ipc.ts
+++ b/apps/desktop/electron/terminal-ipc.ts
@@ -22,6 +22,8 @@ export interface TerminalIpcDeps {
findOnPath: (command: string) => null | string
rememberLog: (line: string) => void
activeSshTerminalTarget: (webContentsId: number) => unknown
+ /** The ssh client to spawn for remote terminals (resolveSshBinary). */
+ sshBinary: () => string
ensureBackend: (webContentsId: number) => Promise<unknown>
getSshConnectionState: (scope: string) => undefined | { remotePlatform?: string }
}
@@ -52,6 +54,7 @@ export function registerTerminalIpc({
findOnPath,
rememberLog,
activeSshTerminalTarget,
+ sshBinary,
ensureBackend,
getSshConnectionState
}: TerminalIpcDeps): TerminalIpcApi {
@@ -321,9 +324,7 @@ export function registerTerminalIpc({
const ptyProcess = remote
? nodePty.spawn(
- process.platform === 'win32'
- ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe')
- : 'ssh',
+ sshBinary(),
buildInteractiveSshArgs(sshTarget.ssh, String(payload?.cwd || '').trim(), undefined, remoteCommand),
{ cols, cwd: app.getPath('home'), env: terminalShellEnv(), name: 'xterm-256color', rows }
)
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index db159a52e8d..1196da7252d 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -2656,6 +2656,11 @@ DEFAULT_CONFIG = {
# locally rebuilt apps so the Designated Requirement — and thus TCC grants — survives
# updates. Empty = default ad-hoc identifier-pinned signing.
"macos_signing_identity": "",
+ # Windows only: explicit ssh client for SSH connections, the -G config probe and SSH
+ # terminals, e.g. "C:\\Program Files\\Git\\usr\\bin\\ssh.exe" when the in-box OpenSSH is
+ # missing or broken. Empty = System32 OpenSSH, then Git for Windows' ssh.exe, then PATH.
+ # Read by the app before its first window; restart to apply. Ignored off-Windows.
+ "ssh_path": "",
# Auto-continue a turn killed by a crash: resuming re-submits the interrupted prompt if
# fresh; a stale one just shows the recovered partial transcript.
"auto_continue": {
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index ca9030d2206..66d03f7659e 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -695,6 +695,17 @@ damaged application files, repair through the
tccutil reset Microphone com.nousresearch.hermes
```
+### Windows: the SSH client is missing or broken
+
+On Windows the app runs SSH through the built-in OpenSSH client (`%SystemRoot%\System32\OpenSSH\ssh.exe`). If that client is not installed, it falls back to Git for Windows' bundled `usr\bin\ssh.exe` and then to whatever `ssh` is on `PATH`. If the built-in client is installed but broken (for example, every `ssh.exe` exits with code 255 after a Windows update), boot stops on an error naming the client instead of retrying. To use a different client, set it in `config.yaml` and restart the app:
+
+```yaml
+desktop:
+ ssh_path: 'C:\Program Files\Git\usr\bin\ssh.exe'
+```
+
+Use single quotes or no quotes so the backslashes stay literal. The key goes two spaces under `desktop:`, like the launch keys above. It has no effect on macOS or Linux.
+
### "The host key has CHANGED since you last connected" (SSH remote)
If your SSH remote was reinstalled or its host key rotated, SSH fails closed