Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-ssh): 解锁/连接时正确解析私钥路径并区分缺失文件错误 (#1837) (#2024)
yan66fc9ba6e455
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.tsnew file mode 100644index 0000000000..024d2c5f87--- /dev/null+++ b/apps/desktop/src/main/remote-ssh/__tests__/connectFailure.test.ts@@ -0,0 +1,37 @@+/**+ * classifyConnectFailure unit tests.+ * Covers: ENOENT-code classification, remote-forged message rejection,+ * auth-failure passthrough, and fallback to SSH_CONNECT_FAILED.+ */++import { describe, expect, it } from 'vitest';+import { KEY_FILE_NOT_FOUND_CODE } from '@cindy/maker-remote-ssh';++import { classifyConnectFailure } from '../connect-failure.js';++describe('classifyConnectFailure', () => {+ it('classifies the resolveAuth ENOENT error as SSH_KEY_FILE_NOT_FOUND via its stable local code', () => {+ const err = new Error(`identity file not found: C:\\Users\\someone\\.ssh\\id_ed25519`);+ (err as { code?: string }).code = KEY_FILE_NOT_FOUND_CODE;+ const { code, msg } = classifyConnectFailure(err);+ expect(code).toBe('SSH_KEY_FILE_NOT_FOUND');+ expect(msg).toBe('identity file not found: C:\\Users\\someone\\.ssh\\id_ed25519');+ });++ it('does NOT classify a remote-forged message that merely looks like a key-file error', () => {+ // 远端 SSH 服务端可以注入 message 文本,但永远无法设置我们本地打的 code。+ const forged = new Error('identity file not found: C:\\Users\\someone\\.ssh\\id_ed25519');+ expect(classifyConnectFailure(forged).code).toBe('SSH_CONNECT_FAILED');+ });++ it('still classifies auth-shaped failures as SSH_AUTH_FAILED', () => {+ expect(classifyConnectFailure(new Error('Permission denied (publickey)')).code).toBe('SSH_AUTH_FAILED');+ expect(classifyConnectFailure(new Error('All configured authentication methods failed')).code).toBe('SSH_AUTH_FAILED');+ });++ it('falls back to SSH_CONNECT_FAILED for network/handshake errors', () => {+ expect(classifyConnectFailure(new Error('connect ETIMEDOUT 10.0.0.5:22')).code).toBe('SSH_CONNECT_FAILED');+ expect(classifyConnectFailure('connection closed before ready').code).toBe('SSH_CONNECT_FAILED');+ expect(classifyConnectFailure(undefined).code).toBe('SSH_CONNECT_FAILED');+ });+});diff --git a/apps/desktop/src/main/remote-ssh/__tests__/sshKeysAddKeyToAgent.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/sshKeysAddKeyToAgent.test.tsnew file mode 100644index 0000000000..18d98dfa87--- /dev/null+++ b/apps/desktop/src/main/remote-ssh/__tests__/sshKeysAddKeyToAgent.test.ts@@ -0,0 +1,55 @@+/**+ * addKeyToAgent — 私钥路径不存在时稳定归类为 no_such_file (#1837)。+ * 只测缺失路径分支(不会真跑 ssh-add),覆盖 Windows 路径形态。+ */++import { describe, expect, it, vi, afterEach } from 'vitest';++// mock execFile 以便断言"缺失路径时 ssh-add 不会被调用"(copilot review 指出的+// 测试意图与覆盖不一致问题)。ssh-keys.ts 用 promisify(execFile) 封装,只能在+// 模块加载前 mock node:child_process。+const execFileMock = vi.hoisted(() => vi.fn());+vi.mock('node:child_process', () => ({+ execFile: execFileMock,+}));++import { addKeyToAgent } from '../ssh-keys.js';++afterEach(() => {+ execFileMock.mockClear();+});++describe('addKeyToAgent — missing private key path', () => {+ // 注意:不含 UNC 路径——fs.access 对 `\\nas\...` 会真实解析网络主机,测试环境+ // 可能慢/挂起。UNC 的纯字符串形态由 maker-remote-ssh 的 expandHome 单测覆盖。+ it.each([+ ['windows-drive', String.raw`C:\Users\someone\.ssh\id_ed25519`],+ ['with-space', String.raw`C:\Users\my name\Documents\ssh keys\id_ed25519`],+ ['chinese', String.raw`D:\密钥\我的密钥\id_ed25519`],+ ])('%s', async (_label, path) => {+ const result = await addKeyToAgent({ privateKeyPath: path });+ expect(result.success).toBe(false);+ expect(result.failureReason).toBe('no_such_file');+ // 真实路径必须出现在 hint 里,UI 才能显示"是哪个路径找不到"。+ expect(result.errorHint).toContain(path);+ expect(result.errorHint).toContain('not found');+ });++ it('classifies a missing path as no_such_file even with a passphrase', async () => {+ // 带 passphrase 走 SSH_ASKPASS 分支;缺失文件同样应在 ssh-add 之前被拦截。+ const missing = String.raw`C:\Users\someone\.ssh\id_ed25519`;+ const result = await addKeyToAgent({ privateKeyPath: missing, passphrase: 'secret' });+ expect(result.success).toBe(false);+ expect(result.failureReason).toBe('no_such_file');+ expect(result.errorHint).toContain(missing);+ });++ it('does not spawn ssh-add for a missing file (pre-check short-circuits)', async () => {+ const missing = String.raw`C:\Users\someone\.ssh\id_ed25519`;+ const result = await addKeyToAgent({ privateKeyPath: missing });+ expect(result.success).toBe(false);+ expect(result.failureReason).toBe('no_such_file');+ // 关键断言:缺失路径在 fs.access 就返回,execFile(ssh-add) 不被调用。+ expect(execFileMock).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/remote-ssh/connect-failure.ts b/apps/desktop/src/main/remote-ssh/connect-failure.tsnew file mode 100644index 0000000000..cd8553decf--- /dev/null+++ b/apps/desktop/src/main/remote-ssh/connect-failure.ts@@ -0,0 +1,35 @@+/**+ * connect-failure — 连接阶段失败 → IPC code 分类。+ * 独立成纯模块是为了可单测(index.ts import electron)。+ */++import { isAuthFailure, KEY_FILE_NOT_FOUND_CODE } from '@cindy/maker-remote-ssh';++export type ConnectFailureClass =+ | 'SSH_AUTH_FAILED'+ | 'SSH_KEY_FILE_NOT_FOUND'+ | 'SSH_CONNECT_FAILED';++/**+ * Classify a connect-phase failure into the IPC code the renderer can act on.+ *+ * Auth-shaped failures keep their existing `SSH_AUTH_FAILED` (actionable+ * ssh-copy-id hint). A *local* identity-file read failure (fs ENOENT from+ * `resolveAuth`) is a path problem — the configured private key doesn't exist+ * on disk — and must NOT be swallowed into the generic `SSH_CONNECT_FAILED`.+ * Everything else (network / handshake / server) stays `SSH_CONNECT_FAILED`.+ *+ * Classification keys off the error's stable local `.code` (set by+ * `resolveAuth`), NOT the message text — the message can originate from the+ * remote SSH server (e.g. a forged SSH_MSG_DISCONNECT description) and must+ * never drive classification. Returns the message too so callers can pass it+ * through without re-extracting it.+ */+export function classifyConnectFailure(err: unknown): { code: ConnectFailureClass; msg: string } {+ const msg = String((err as Error)?.message ?? err);+ if ((err as { code?: unknown } | null)?.code === KEY_FILE_NOT_FOUND_CODE) {+ return { code: 'SSH_KEY_FILE_NOT_FOUND', msg };+ }+ if (isAuthFailure(msg)) return { code: 'SSH_AUTH_FAILED', msg };+ return { code: 'SSH_CONNECT_FAILED', msg };+}diff --git a/apps/desktop/src/main/remote-ssh/index.ts b/apps/desktop/src/main/remote-ssh/index.tsindex f3e9671c00..3fcc26e4e7 100644--- a/apps/desktop/src/main/remote-ssh/index.ts+++ b/apps/desktop/src/main/remote-ssh/index.ts@@ -23,7 +23,6 @@ import os from 'node:os';import {ConnectionPool,- isAuthFailure,readSshConfig,upsertHost,updateHostFields,@@ -33,6 +32,7 @@ import {uninstallRemoteAgent,checkRemoteCodexAuth,pushRemoteCodexAuth,+ expandHome,FileHostKeyStore,RemoteHost,type AddHostInput,@@ -47,6 +47,7 @@ import { createLogger } from '../logger.js';import { throwIpcError, requireString, requireObject, requireEnum } from '../utils/ipcValidate.js';import { getRemoteClaudeEnv } from './claude-env.js';import { serializeEnvBlock } from './env-block.js';+import { classifyConnectFailure } from './connect-failure.js';import {addKeyToAgent,buildInstallCommand,@@ -268,8 +269,7 @@ export async function ensureRemoteHostReady(id: string): Promise<void> {try {await pool.connect(id);} catch (err) {- const msg = String((err as Error)?.message ?? err);- const code = isAuthFailure(msg) ? 'SSH_AUTH_FAILED' : 'SSH_CONNECT_FAILED';+ const { code, msg } = classifyConnectFailure(err);throwIpcError(code, msg);}}@@ -576,7 +576,7 @@ function normalizeAddInput(raw: unknown): AddHostInput & { agentProxy?: SshHostA// agent → optional, when set it pins the agent to that one key// (FilteredAgent — solves MaxAuthTries with busy agents)const identityFile = typeof obj.identityFile === 'string' && obj.identityFile.trim()- ? obj.identityFile.trim()+ ? expandHome(obj.identityFile.trim()): undefined;if (authMethod === 'key' && !identityFile) {throwIpcError('INVALID_PARAMS', 'identityFile required when authMethod is "key"');@@ -764,14 +764,11 @@ export function registerRemoteSshIpc(): void {try {await getPool().connect(id);} catch (err) {- const msg = String((err as Error)?.message ?? err);- // Classify auth-shaped failures distinctly so renderer can show- // "fix your key/agent" UX vs "check network/host". RemoteHost has- // already rewritten the message to actionable text (ssh-copy-id hint)- // when the underlying ssh2 error matched isAuthFailure — we pass it- // through verbatim so the toast surfaces the same hint as the- // host-row subtitle.- const code = isAuthFailure(msg) ? 'SSH_AUTH_FAILED' : 'SSH_CONNECT_FAILED';+ // classifyConnectFailure produces SSH_AUTH_FAILED | SSH_KEY_FILE_NOT_FOUND+ // | SSH_CONNECT_FAILED. RemoteHost rewrites auth failures to actionable+ // text (ssh-copy-id hint) verbatim so the toast matches the host-row+ // subtitle; a local identityFile ENOENT is classified off `.code`.+ const { code, msg } = classifyConnectFailure(err);throwIpcError(code, msg);}diff --git a/apps/desktop/src/main/remote-ssh/ssh-keys.ts b/apps/desktop/src/main/remote-ssh/ssh-keys.tsindex 84ba106c65..9c8d54e688 100644--- a/apps/desktop/src/main/remote-ssh/ssh-keys.ts+++ b/apps/desktop/src/main/remote-ssh/ssh-keys.ts@@ -220,6 +220,29 @@ export async function addKeyToAgent(opts: {}): Promise<AddKeyToAgentResult> {const { privateKeyPath, passphrase } = opts;+ // Deterministic pre-flight: confirm the private key actually exists BEFORE+ // handing the path to ssh-add. ssh-add's failure mode for a missing file is+ // inconsistent across platforms — on Windows OpenSSH it prints+ // "No such file or directory" (→ no_such_file), but a Git Bash / MSYS+ // ssh-add can emit "Could not open a connection to your authentication+ // agent" instead (→ agent_unavailable), sending the user down the wrong+ // remediation path. We classify the path problem ourselves and carry the+ // real path in the hint so the UI can say "key file not found at <path>".+ try {+ await fs.access(privateKeyPath);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ return {+ success: false,+ failureReason: 'no_such_file',+ errorHint: `private key file not found: ${privateKeyPath}`,+ stderr: String((err as Error).message),+ };+ }+ // Non-ENOENT IO error (permissions etc.) — fall through so ssh-add+ // attempts the key and buildFailure classifies its stderr downstream.+ }+// No passphrase = key is unencrypted; ssh-add doesn't need to prompt// and we can skip the askpass dance entirely.if (!passphrase) {@@ -327,6 +350,9 @@ function classifyAgentFailure(err: unknown): { reason: AgentFailureReason; hint:if (/incorrect|bad passphrase|wrong passphrase/i.test(msg)) {return { reason: 'bad_passphrase', hint: 'passphrase rejected by ssh-add' };}+ // Note: addKeyToAgent's fs.access pre-flight now handles the missing-key-file+ // case before ssh-add runs, so this branch only catches post-spawn "no such+ // file" errors (ssh-add runtime dependency missing, etc.).if (/no such file|enoent/i.test(msg)) {return { reason: 'no_such_file', hint: 'private key file not found at expected path' };}diff --git a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx b/apps/desktop/src/renderer/components/settings/RemoteSection.tsxindex 0b3a611524..a5cd114083 100644--- a/apps/desktop/src/renderer/components/settings/RemoteSection.tsx+++ b/apps/desktop/src/renderer/components/settings/RemoteSection.tsx@@ -953,6 +953,14 @@ export function RemoteSection({ showTitle = true }: { showTitle?: boolean } = {}const ipc = extractIpcError(err);if (ipc?.code === 'SSH_AUTH_FAILED') {toast.error(ipc.message);+ } else if (ipc?.code === 'SSH_KEY_FILE_NOT_FOUND') {+ // Local key-path problem (fs ENOENT on the configured identityFile),+ // NOT a network/host failure. Show the actual path + how to fix it so+ // the user isn't sent down the "check the network" path.+ // Strip the English raw-error prefix ("identity file not found: ") so+ // localized copy doesn't end up bilingual / double-saying "not found".+ const detail = ipc.message.replace(/^identity file not found:\s*/, '');+ toast.error(t('settings.remote.toast.connectKeyFileMissing', { detail }));} else {toast.error(t(mapIpcErrorToI18nKey(err, { fallback: 'settings.remote.toast.connectFailed' })));}diff --git a/apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx b/apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsxindex a60cb41d62..ddd5bd7a5d 100644--- a/apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx@@ -1116,6 +1116,19 @@ function AgentTroubleDialog({ state, onClose }: AgentTroubleDialogProps) {</div>)}+ {/* Path problem (no_such_file): no platform commands help — the+ configured key path itself is wrong. Give an explicit fix+ direction (re-select the key / edit the host's Identity file+ path) instead of the generic "use a terminal" fallback below. */}+ {state.reason === 'no_such_file' && (+ <p+ className="text-12 leading-relaxed"+ style={{ color: 'var(--settings-integration-subtitle)' }}+ >+ {t('settings.remote.keys.agentTrouble.noSuchFileFix')}+ </p>+ )}+{/* Fallback: skip the agent entirely and rely on ~/.ssh/config +IdentityFile. Spelled out so the user knows they're explicitlyopting into "no agent, type passphrase per connect" mode. */}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex cb6297e4ca..80516d4d23 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -252,7 +252,8 @@"listAgent": "List currently loaded keys:","linuxStart": "Start a user-local ssh-agent (add this line to ~/.bashrc / ~/.zshrc to persist):","win32Enable": "Enable the ssh-agent service (run as Administrator in PowerShell):"- }+ },+ "noSuchFileFix": "This path does not exist on disk. Go back to the host settings and re-select the correct private key, or double-check the Identity file path (the ~/.ssh/… form is supported and expands to your home directory)."}},"add": {@@ -370,7 +371,8 @@"codexSyncDone": "Codex credentials pushed to remote","codexSyncDoneDaemonRestartFailed": "Codex credentials pushed, but the old daemon did not restart — reconnect to the remote / restart the daemon before retrying","codexSyncFailed": "Codex credentials sync failed",- "codexSyncNoLocal": "No local Codex credentials found — log in to Codex in {{appName}} first"+ "codexSyncNoLocal": "No local Codex credentials found — log in to Codex in {{appName}} first",+ "connectKeyFileMissing": "Private key file not found or unreadable: {{detail}}. Check the path, or re-select the key in the host settings."},"silentInstall": {"starting": "Installing {{agent}} on remote {{hostId}}…",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 00f335790c..7552f0bdf9 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -252,7 +252,8 @@"listAgent": "agent に現在登録されている鍵を一覧表示:","linuxStart": "ユーザーローカルの ssh-agent を起動(永続化したい場合は ~/.bashrc / ~/.zshrc に追記):","win32Enable": "ssh-agent サービスを有効化(管理者 PowerShell で実行):"- }+ },+ "noSuchFileFix": "このパスはディスク上に存在しません。ホスト設定に戻って正しい秘密鍵を選び直すか、「Identity file パス」の入力を確認してください(~/.ssh/… 形式に対応し、ホームディレクトリに展開されます)。"}},"add": {@@ -370,7 +371,8 @@"codexSyncDone": "Codex 認証情報をリモートに送りました","codexSyncDoneDaemonRestartFailed": "Codex 認証情報はリモートに送信されましたが、古い daemon が再起動されませんでした — リモートに再接続してから再試行してください","codexSyncFailed": "Codex 認証情報の同期に失敗",- "codexSyncNoLocal": "ローカルに Codex 認証情報が見つかりません — まず {{appName}} で Codex にログインしてください"+ "codexSyncNoLocal": "ローカルに Codex 認証情報が見つかりません — まず {{appName}} で Codex にログインしてください",+ "connectKeyFileMissing": "秘密鍵ファイルが見つからないか読み込めません: {{detail}}。パスを確認するか、ホスト設定で鍵を選び直してください。"},"silentInstall": {"starting": "リモート {{hostId}} に {{agent}} をインストール中…",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 85368fe626..fd246553ad 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -252,7 +252,8 @@"listAgent": "현재 agent 에 로드된 키 목록:","linuxStart": "사용자 로컬 ssh-agent 시작(영구 적용은 ~/.bashrc / ~/.zshrc 에 추가):","win32Enable": "ssh-agent 서비스 활성화(관리자 PowerShell 에서 실행):"- }+ },+ "noSuchFileFix": "이 경로는 디스크에 존재하지 않습니다. 호스트 설정으로 돌아가 올바른 개인 키를 다시 선택하거나, Identity file 경로 입력을 확인하세요 (~/.ssh/… 형식이 지원되며 홈 디렉터리로 확장됩니다)."}},"add": {@@ -370,7 +371,8 @@"codexSyncDone": "Codex 자격 증명을 원격에 푸시했습니다","codexSyncDoneDaemonRestartFailed": "Codex 자격 증명이 원격에 푸시되었지만 이전 daemon이 재시작되지 않았습니다 — 원격에 다시 연결한 후 재시도하세요","codexSyncFailed": "Codex 자격 증명 동기화 실패",- "codexSyncNoLocal": "로컬에 Codex 자격 증명이 없습니다 — 먼저 {{appName}} 에서 Codex 에 로그인하세요"+ "codexSyncNoLocal": "로컬에 Codex 자격 증명이 없습니다 — 먼저 {{appName}} 에서 Codex 에 로그인하세요",+ "connectKeyFileMissing": "개인 키 파일을 찾을 수 없거나 읽을 수 없습니다: {{detail}}. 경로를 확인하거나 호스트 설정에서 키를 다시 선택하세요."},"silentInstall": {"starting": "원격 {{hostId}} 에 {{agent}} 설치 중…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex a3a14d4fb9..6c0f2ad5bd 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -252,7 +252,8 @@"listAgent": "查看 agent 当前加载了哪些密钥:","linuxStart": "启动一个用户级 ssh-agent(把这行加到 ~/.bashrc / ~/.zshrc 让它持久):","win32Enable": "启用 ssh-agent 服务(在管理员 PowerShell 里执行):"- }+ },+ "noSuchFileFix": "这个路径在磁盘上找不到。请回到主机设置重新选择正确的私钥,或核对“私钥文件路径”是否填写正确(支持 ~/.ssh/… 写法,会自动展开到你的用户目录)。"}},"add": {@@ -370,7 +371,8 @@"codexSyncDone": "已把 Codex 凭证推送到远端","codexSyncDoneDaemonRestartFailed": "Codex 凭证已推送到远端,但旧 daemon 没重启 — 请重连远端 / 重启 daemon 后再用","codexSyncFailed": "Codex 凭证同步失败",- "codexSyncNoLocal": "本机找不到 Codex 凭证 — 先在 {{appName}} 里登录 Codex"+ "codexSyncNoLocal": "本机找不到 Codex 凭证 — 先在 {{appName}} 里登录 Codex",+ "connectKeyFileMissing": "私钥文件不存在或无法读取:{{detail}}。请检查路径,或在主机设置里重新选择密钥。"},"silentInstall": {"starting": "正在远端 {{hostId}} 安装 {{agent}}…",diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex 5854a85fff..94666599c3 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -63,6 +63,10 @@ export type IpcErrorCode =| 'SSH_AUTH_FAILED'| 'SSH_CONFIG_IO_FAILED'| 'SSH_HOST_NOT_FOUND'+ // remote-ssh:配置的私钥文件在磁盘上不存在/不可读。与 SSH_CONNECT_FAILED 分开——+ // 这是本机路径问题(缺失 / ~ 未展开 / 路径被改写),不是网络或服务器错误,renderer+ // 据此显示明确的路径错误并允许重新选择密钥 / 编辑主机。+ | 'SSH_KEY_FILE_NOT_FOUND'// remote-ssh:远端 agent 阶段| 'SSH_NOT_CONNECTED'| 'SSH_INSTALL_FAILED'@@ -220,6 +224,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['SSH_AUTH_FAILED','SSH_CONFIG_IO_FAILED','SSH_HOST_NOT_FOUND',+ 'SSH_KEY_FILE_NOT_FOUND','SSH_NOT_CONNECTED','SSH_INSTALL_FAILED','SSH_EXEC_FAILED',diff --git a/packages/lizi-mcps/src/ssh/_shared.ts b/packages/lizi-mcps/src/ssh/_shared.tsindex bea704ebae..3a2a26eba2 100644--- a/packages/lizi-mcps/src/ssh/_shared.ts+++ b/packages/lizi-mcps/src/ssh/_shared.ts@@ -43,6 +43,7 @@ export type SshErrorCode =| 'HOST_NOT_FOUND'| 'AMBIGUOUS_HOST'| 'SSH_AUTH_FAILED'+ | 'SSH_KEY_FILE_NOT_FOUND'| 'SSH_CONNECT_FAILED'| 'EXEC_TIMEOUT'| 'PLUGIN_DISABLED'@@ -180,6 +181,14 @@ export function classifySshError(err: unknown): ClassifiedSshError {errorCode: 'SSH_AUTH_FAILED',hint: `SSH 认证失败(确定性错误,重试无效,请把提示转告用户处理):${detail}`,};+ case 'SSH_KEY_FILE_NOT_FOUND':+ return {+ errorCode: 'SSH_KEY_FILE_NOT_FOUND',+ // Strip the raw-error prefix (identity file not found: ) so the hint+ // doesn't mix an English prefix into the localized message — same+ // treatment the renderer toast applies.+ hint: `配置的私钥文件在本机磁盘上不存在/不可读(本机路径问题,不是网络或服务端错误):${detail.replace(/^identity file not found:\s*/, '')}。请到「设置 → 远程连接」重新选择私钥或编辑主机的 Identity file 路径。`,+ };default:return {errorCode: 'SSH_CONNECT_FAILED',diff --git a/packages/maker-remote-ssh/src/RemoteHost.ts b/packages/maker-remote-ssh/src/RemoteHost.tsindex 75ea890973..c48e35ea63 100644--- a/packages/maker-remote-ssh/src/RemoteHost.ts+++ b/packages/maker-remote-ssh/src/RemoteHost.ts@@ -274,6 +274,15 @@ export class RemoteHost {private cfg: HostConfig;private status: RemoteStatus = 'disconnected';private lastError: string | undefined;+ /**+ * The last error thrown by `resolveAuth` during connect, kept as the full+ * Error object. Only set on the local-auth-failure path — where the error+ * carries the synthetic `KEY_FILE_NOT_FOUND_CODE` that `classifyConnectFailure`+ * relies on. The concurrent-join path (connect() while connecting) rethrows+ * this so the structured code survives instead of being flattened into a bare+ * `lastError` string and downgraded to SSH_CONNECT_FAILED.+ */+ private lastAuthError: Error | null = null;/*** Human-readable label for the credential that succeeded on the most* recent successful connect, e.g. "ssh-agent" or "key:id_ed25519".@@ -363,6 +372,9 @@ export class RemoteHost {// narrowing, so we re-read through `getStatus()`.await this.waitForTerminal();if (this.getStatus() === 'ready') return;+ // Prefer the last resolveAuth error so the structured `.code` survives+ // (classifyConnectFailure needs it); fall back to the string otherwise.+ if (this.lastAuthError) throw this.lastAuthError;throw new Error(this.lastError ?? 'connect failed');}@@ -1020,6 +1032,7 @@ export class RemoteHost {private async doConnect(): Promise<void> {this.setStatus('connecting');this.hostKeyError = null;+ this.lastAuthError = null;let auth;try {@@ -1027,6 +1040,9 @@ export class RemoteHost {} catch (err) {const msg = (err as Error).message;this.lastError = msg;+ // Keep the full error so concurrent connect() joiners can rethrow it+ // with its structured `.code` intact (see lastAuthError + connect()).+ this.lastAuthError = err instanceof Error ? err : new Error(msg);this.setStatus('failed');throw err;}diff --git a/packages/maker-remote-ssh/src/__tests__/credentials.test.ts b/packages/maker-remote-ssh/src/__tests__/credentials.test.tsnew file mode 100644index 0000000000..fbbe0b29c5--- /dev/null+++ b/packages/maker-remote-ssh/src/__tests__/credentials.test.ts@@ -0,0 +1,62 @@+/**+ * resolveAuth — identityFile path-resolution regression (#1837).+ *+ * 背景:用户配了 LAN 主机 + 私钥路径,直接连接正常,但解锁/连接时报+ * "找不到私钥文件"。根因之一是 `~` 展开在 ADD/UPDATE 边界缺失(connect+ * 用 fs.readFile 读配置里的 identityFile,而 Node 不会展开 `~`),另一个是+ * fs ENOENT 被吞成笼统的 SSH_CONNECT_FAILED。+ *+ * 这里固定两条不变量:+ * 1. identityFile 指向不存在的文件 → resolveAuth 抛 `identity file not+ * found: <path>`(可被 connect IPC 分类为 SSH_KEY_FILE_NOT_FOUND,而不是+ * 泛化的 SSH_CONNECT_FAILED)。+ * 2. 其它 IO 错误仍保留原有 "failed to read identityFile" 包装。+ */++import { describe, expect, it } from 'vitest';++import { KEY_FILE_NOT_FOUND_CODE, resolveAuth } from '../credentials.js';+import type { HostConfig } from '../types.js';++function keyHost(over: Partial<HostConfig> & Pick<HostConfig, 'identityFile'>): HostConfig {+ return {+ id: 'lan-host',+ hostname: '10.0.0.5',+ port: 22,+ user: 'admin',+ authMethod: 'key',+ source: 'manual',+ ...over,+ };+}++describe('resolveAuth key-mode identityFile handling', () => {+ it('throws a distinguishable error when the private key file is missing (ENOENT)', async () => {+ const missing = String.raw`C:\Users\someone\.ssh\id_ed25519`;+ await expect(resolveAuth(keyHost({ identityFile: missing }))).rejects.toThrow(+ `identity file not found: ${missing}`,+ );+ });++ it('tags the ENOENT error with the stable KEY_FILE_NOT_FOUND_CODE so classification never pattern-matches the message', async () => {+ const missing = String.raw`C:\Users\someone\.ssh\id_ed25519`;+ try {+ await resolveAuth(keyHost({ identityFile: missing }));+ expect.unreachable('should have thrown');+ } catch (err) {+ expect((err as { code?: string }).code).toBe(KEY_FILE_NOT_FOUND_CODE);+ }+ });++ it('does not swallow a tilde-prefixed path into a generic message — surfaces the raw path', async () => {+ // `~` 未展开时 fs.readFile 也会 ENOENT;报错应把真实路径说清楚。+ const tilde = String.raw`~\foo\.ssh\id_ed25519`;+ await expect(resolveAuth(keyHost({ identityFile: tilde }))).rejects.toThrow(/identity file not found:/);+ });++ it('still wraps non-ENOENT read failures with the original message', async () => {+ // 指向一个目录,fs.readFile 会抛 EISDIR(而非 ENOENT)→ 保留原包装。+ const host = keyHost({ identityFile: process.cwd() });+ await expect(resolveAuth(host)).rejects.toThrow(/failed to read identityFile .*EISDIR|failed to read identityFile/);+ });+});diff --git a/packages/maker-remote-ssh/src/__tests__/remoteHostAuthErrorPreserved.test.ts b/packages/maker-remote-ssh/src/__tests__/remoteHostAuthErrorPreserved.test.tsnew file mode 100644index 0000000000..2a9bb8d5a9--- /dev/null+++ b/packages/maker-remote-ssh/src/__tests__/remoteHostAuthErrorPreserved.test.ts@@ -0,0 +1,80 @@+/**+ * RemoteHost concurrent-connect join 保留 resolveAuth 错误 code 的回归 (#1837 P1)。+ *+ * 背景:greptile review 指出,同一主机两个 connect 请求重叠时,后到的请求在+ * waitForTerminal 后从 `lastError` 字符串重新构造 Error,丢失 resolveAuth 打的+ * KEY_FILE_NOT_FOUND_CODE——导致缺失私钥错误回落为 SSH_CONNECT_FAILED,用户+ * 看不到路径修复指引。修复:RemoteHost 在 resolveAuth 失败时保留完整错误对象+ * (lastAuthError),并发 join 时 rethrow 它,让 .code 结构存活。+ */++import { describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';++// 字面量而非 import:credentials.js 被 vi.mock 覆盖,import 会取到 mock 的导出。+const KEY_FILE_NOT_FOUND_CODE = 'KEY_FILE_NOT_FOUND';++class FakeClient extends EventEmitter {+ connect(): void {}+ end(): void {+ this.emit('close');+ }+}++const h = vi.hoisted(() => ({ client: null as FakeClient | null }));++vi.mock('ssh2', () => ({+ Client: vi.fn(() => {+ h.client = new FakeClient();+ return h.client;+ }),+}));++// resolveAuth 第一次失败抛带 code 的错误(模拟 identityFile ENOENT)。+const authErr = new Error(`identity file not found: C:\\Users\\someone\\.ssh\\id_ed25519`);+(authErr as { code?: string }).code = KEY_FILE_NOT_FOUND_CODE;+vi.mock('../credentials.js', () => ({+ resolveAuth: vi.fn(async () => {+ throw authErr;+ }),+ defaultAgentEndpoint: vi.fn(() => ''),+}));++import { RemoteHost } from '../RemoteHost.js';+import type { HostConfig } from '../types.js';++const HOST_CONFIG: HostConfig = {+ id: 'auth-err-host',+ hostname: '10.0.0.1',+ port: 22,+ user: 'deploy',+ authMethod: 'key',+ identityFile: String.raw`C:\Users\someone\.ssh\id_ed25519`,+ source: 'manual',+};++const noopLogger = {+ debug: () => {},+ info: () => {},+ warn: () => {},+ error: () => {},+};++describe('RemoteHost concurrent connect preserves resolveAuth error code', () => {+ it('the concurrent joiner rethrows the last resolveAuth error with its .code intact', async () => {+ // resolveAuth 抛错(带 code),第一个 connect 让 status 进入 connecting;+ // 立刻发第二个 connect,后者走 waitForTerminal + rethrow lastAuthError。+ const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger });+ const p1 = host.connect();+ const p2 = host.connect(); // 并发 join —— resolveAuth 仍在飞,status=connecting+ const results = await Promise.allSettled([p1, p2]);+ expect(results.length).toBe(2);+ for (const r of results) {+ expect(r.status).toBe('rejected');+ if (r.status === 'rejected') {+ // 关键断言:并发 join 者拿到的错误保留了 .code,而不是被 flatten 成字符串。+ expect((r.reason as { code?: string }).code).toBe(KEY_FILE_NOT_FOUND_CODE);+ }+ }+ });+});diff --git a/packages/maker-remote-ssh/src/__tests__/sshConfig.test.ts b/packages/maker-remote-ssh/src/__tests__/sshConfig.test.tsindex 7ab3b19846..0b53a00831 100644--- a/packages/maker-remote-ssh/src/__tests__/sshConfig.test.ts+++ b/packages/maker-remote-ssh/src/__tests__/sshConfig.test.ts@@ -20,6 +20,7 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import {+ expandHome,readSshConfig,removeHost,updateHostFields,@@ -99,6 +100,44 @@ describe('readSshConfig', () => {});});+// ── expandHome — Windows 路径形态 ─────────────────────────────────────────────++describe('expandHome', () => {+ const home = os.homedir();++ it('expands a bare tilde', () => {+ expect(expandHome('~')).toBe(home);+ });++ it('expands POSIX-style ~/ prefix', () => {+ expect(expandHome('~/.ssh/id_ed25519')).toBe(path.join(home, '.ssh', 'id_ed25519'));+ });++ it('expands Windows-style ~\\ prefix', () => {+ expect(expandHome('~\\.ssh\\id_ed25519')).toBe(path.join(home, '.ssh', 'id_ed25519'));+ });++ it('leaves an already-absolute Windows drive path untouched (backslashes preserved)', () => {+ const p = String.raw`C:\Users\foo\.ssh\id_ed25519`;+ expect(expandHome(p)).toBe(p);+ });++ it('leaves forward-slash absolute paths untouched', () => {+ const p = 'C:/Users/foo/.ssh/id_ed25519';+ expect(expandHome(p)).toBe(p);+ });++ it('leaves UNC paths untouched', () => {+ const p = String.raw`\\nas\share\keys\id_ed25519`;+ expect(expandHome(p)).toBe(p);+ });++ it('leaves paths with spaces untouched', () => {+ const p = String.raw`C:\Users\my name\.ssh\id_ed25519`;+ expect(expandHome(p)).toBe(p);+ });+});+// ── upsertHost + readSshConfig round-trip ────────────────────────────────────describe('upsertHost round-trip', () => {diff --git a/packages/maker-remote-ssh/src/credentials.ts b/packages/maker-remote-ssh/src/credentials.tsindex 70b7b3147d..b6fe476215 100644--- a/packages/maker-remote-ssh/src/credentials.ts+++ b/packages/maker-remote-ssh/src/credentials.ts@@ -28,6 +28,14 @@ import type { BaseAgent } from 'ssh2';import { createFilteredAgentFromPubkey } from './filteredAgent.js';import type { HostConfig } from './types.js';+/**+ * Stable local code tagged onto the ENOENT identityFile error so the connect+ * IPC layer can classify it as SSH_KEY_FILE_NOT_FOUND WITHOUT pattern-matching+ * the message text (see resolveAuth). Only set by our own code — a remote SSH+ * server can never produce it.+ */+export const KEY_FILE_NOT_FOUND_CODE = 'KEY_FILE_NOT_FOUND';+export interface ResolvedAuth {/*** ssh2 agent option — either a socket path / pipe string (unfiltered) OR@@ -94,8 +102,15 @@ export async function resolveAuth(host: HostConfig): Promise<ResolvedAuth> {try {privateKey = await fs.readFile(host.identityFile);} catch (err) {- const msg = (err as Error).message;- throw new Error(`failed to read identityFile ${host.identityFile}: ${msg}`);+ // Tag ENOENT with KEY_FILE_NOT_FOUND_CODE so classifyConnectFailure can+ // distinguish a local path problem from network/remote errors without+ // pattern-matching the message text (see connect-failure.ts).+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ const e = new Error(`identity file not found: ${host.identityFile}`);+ (e as { code?: string }).code = KEY_FILE_NOT_FOUND_CODE;+ throw e;+ }+ throw new Error(`failed to read identityFile ${host.identityFile}: ${(err as Error).message}`);}return { privateKey, label: `key:${baseName(host.identityFile)}` };}diff --git a/packages/maker-remote-ssh/src/index.ts b/packages/maker-remote-ssh/src/index.tsindex 02a0db3013..61d7b8e8af 100644--- a/packages/maker-remote-ssh/src/index.ts+++ b/packages/maker-remote-ssh/src/index.ts@@ -82,9 +82,10 @@ export {upsertHost,updateHostFields,removeHost,+ expandHome,} from './sshConfig.js';-export { defaultAgentEndpoint, resolveAuth } from './credentials.js';+export { defaultAgentEndpoint, resolveAuth, KEY_FILE_NOT_FOUND_CODE } from './credentials.js';export type { ResolvedAuth } from './credentials.js';export type {diff --git a/packages/maker-remote-ssh/src/sshConfig.ts b/packages/maker-remote-ssh/src/sshConfig.tsindex b0f470c966..ea41a7aec5 100644--- a/packages/maker-remote-ssh/src/sshConfig.ts+++ b/packages/maker-remote-ssh/src/sshConfig.ts@@ -28,6 +28,22 @@ export function defaultSshConfigPath(): string {return path.join(os.homedir(), '.ssh', 'config');}+/**+ * Expand a leading `~` (or `~/`, `~\`) to the user's home directory.+ *+ * Exported so the ADD/UPDATE IPC boundary can normalize `identityFile` the+ * same way the config-read path does — Node never expands `~`, so a literal+ * `~/.ssh/...` stored in the pool host config would fail `fs.readFile` /+ * ssh-add. The `~\` prefix normalizes backslashes to `/` (a no-op on Windows,+ * but required on POSIX where backslash is a filename character).+ */+export function expandHome(p: string): string {+ if (p === '~') return os.homedir();+ if (p.startsWith('~/')) return path.join(os.homedir(), p.slice(2));+ if (p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2).replace(/\\/g, '/'));+ return p;+}+interface SshConfigSection {type?: number;before?: string;@@ -398,9 +414,3 @@ function parseIntSafe(value: string | undefined, fallback: number): number {const n = parseInt(value, 10);return Number.isFinite(n) ? n : fallback;}--function expandHome(p: string): string {- if (p === '~') return os.homedir();- if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2));- return p;-}