dsh-dock 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,8 @@ export const DSH_TOOL_GROUPS = [
50
50
  key: 'gitPanel',
51
51
  name: 'Git仓库操作',
52
52
  description: '打开后:右侧抽屉里多一个「Git仓库操作」页签(默认当前会话目录的仓库,可看提交历史与工作区、提交与推送);「工作区文件」的目录与文件右键多一条「查看 Git 历史」。不需要系统目录选择弹窗,服务器部署同样可用。',
53
- default: false,
53
+ // 用户要求:装好即可用,默认勾选;不想要的人可以主动取消。
54
+ default: true,
54
55
  },
55
56
  ],
56
57
  },
@@ -14,8 +14,14 @@
14
14
  // POST /diff { repo, sha?|staged?|untracked?, path? } → { files:[...] }
15
15
  // POST /file { repo, path, sha? } → { path, content, truncated }
16
16
  // POST /stage { repo, paths, unstage?, confirm:true }
17
+ // POST /stage-hunks { repo, path, hunks:[索引], confirm:true } → { stagedHunks, totalHunks }
18
+ // POST /restore-hunks { repo, path, hunks:[索引], confirm:true } → { restoredHunks, totalHunks }(局部还原)
17
19
  // POST /create-commit { repo, message, paths?, confirm:true } → { commit }
20
+ // POST /diagnose { repo } → { env, files, remote, checks[] }(排查推送失败)
21
+ // POST /unpushed { repo } → { upstream, branch, commits[], reason }
18
22
  // POST /push { repo, remote?, branch?, confirm:true } → { output }
23
+ // POST /pull { repo, strategy?: 'ours'|'theirs', confirm:true } → { pulled, conflict, conflictFiles, ... }
24
+ // POST /abort-merge { repo, confirm:true } → { aborted }(冲突弹窗选取消时回滚合并)
19
25
  //
20
26
  // 安全约定:
21
27
  // - 只接受绝对路径,拒绝含 NUL 的串;路径必须真实存在且是目录。
@@ -66,11 +72,138 @@ const US = '\u001f'
66
72
  /** 提交列表的 pretty 格式:哈希 / 短哈希 / 作者 / 邮箱 / 作者时间 / 提交者 / 提交者时间 / 父提交 / 引用 / 标题 / 正文。 */
67
73
  const LOG_FORMAT = ['%H', '%h', '%an', '%ae', '%aI', '%cn', '%cI', '%P', '%D', '%s', '%b'].join('%x1f') + '%x1e'
68
74
 
75
+ /** 缓存下来的可用家目录(只探一次,避免每条命令都去 stat)。 */
76
+ let cachedSshHome = null
77
+
78
+ /** 私钥文件名:id_* 且不是 .pub(rsa / ed25519 / ecdsa / dsa 及 _sk 变体)。 */
79
+ const IDENTITY_KEY_RE = /^id_[^/\\]+$/
80
+
81
+ /**
82
+ * 给候选家目录打分:0 = 没有 .ssh;1 = 有 .ssh 目录;
83
+ * 有私钥 +2、有 known_hosts +1、有 ssh config +1。
84
+ *
85
+ * 为什么不能只看「.ssh 存在」:DSH 会把 HOME 重定向到工作目录,
86
+ * 那里常常只有一个 known_hosts(甚至只记着别的服务器的指纹),私钥仍在用户目录。
87
+ * 只看存在性就会选中这个空壳:面板里的 git 自带 ssh 认 HOME,读它就报
88
+ * `Host key verification failed`;而诊断用系统自带 ssh(认用户目录)却显示连通。
89
+ *
90
+ * @param {string} dir 候选家目录
91
+ * @returns {Promise<number>} 分数,0 表示不可用
92
+ */
93
+ async function scoreSshHome(dir) {
94
+ if (!dir) return 0
95
+ const sshDir = join(dir, '.ssh')
96
+ let info
97
+ try {
98
+ info = await fsp.stat(sshDir)
99
+ } catch {
100
+ return 0
101
+ }
102
+ if (!info.isDirectory()) return 0
103
+ let entries = []
104
+ try {
105
+ entries = await fsp.readdir(sshDir)
106
+ } catch {
107
+ entries = []
108
+ }
109
+ let score = 1
110
+ if (entries.some((name) => IDENTITY_KEY_RE.test(name) && !name.endsWith('.pub'))) score += 2
111
+ if (entries.includes('known_hosts')) score += 1
112
+ if (entries.includes('config')) score += 1
113
+ return score
114
+ }
115
+
116
+ /**
117
+ * 从候选目录里挑一个最适合做 SSH 家目录的:分数最高者,同分按传入顺序。
118
+ * 单独导出是为了让测试能直接锁住「别选中只有 known_hosts 的空壳」这条规则。
119
+ *
120
+ * @param {string[]} candidates 候选目录(按优先级)
121
+ * @returns {Promise<string>} 选中的目录,一个都没有时返回空串
122
+ */
123
+ export async function pickSshHome(candidates) {
124
+ const seen = new Set()
125
+ let best = ''
126
+ let bestScore = 0
127
+ for (const raw of candidates || []) {
128
+ if (typeof raw !== 'string' || raw.length === 0) continue
129
+ // Windows 路径大小写不敏感;其它平台按原样去重
130
+ const key = process.platform === 'win32' ? raw.toLowerCase() : raw
131
+ if (seen.has(key)) continue
132
+ seen.add(key)
133
+ const score = await scoreSshHome(raw)
134
+ if (score > bestScore) {
135
+ best = raw
136
+ bestScore = score
137
+ }
138
+ }
139
+ return best
140
+ }
141
+
142
+ /**
143
+ * 候选家目录(按优先级):Windows 先看用户目录,其它平台先看 HOME。
144
+ *
145
+ * Windows 上 OpenSSH 用的是用户目录(USERPROFILE),git 自带 ssh 认 HOME。
146
+ * DSH 重定向的 HOME 可能是个空壳,先看用户目录才能拿到真正的密钥。
147
+ */
148
+ function sshHomeCandidates() {
149
+ const env = process.env
150
+ const list = []
151
+ if (process.platform === 'win32') {
152
+ list.push(env.USERPROFILE || '', homedir(), env.HOME || '', env.DSH_REAL_HOME || '')
153
+ } else {
154
+ list.push(env.HOME || '', env.DSH_REAL_HOME || '', homedir(), '/root')
155
+ const user = env.USER || env.USERNAME || ''
156
+ if (user) list.push('/home/' + user, '/Users/' + user)
157
+ }
158
+ return list.filter(Boolean)
159
+ }
160
+
161
+ /**
162
+ * 找出一个「真的有 SSH 配置」的家目录。
163
+ *
164
+ * 背景:本机(以及不少部署)把 HOME 重定向到了工作目录,那里没有私钥;
165
+ * 而 git 自带的 ssh 认 HOME,于是推送报 `Host key verification failed`,
166
+ * 系统自带 ssh 却走用户目录、一切正常——诊断因此会误导人。
167
+ *
168
+ * 规则:在候选目录里按「有私钥 > 有 known_hosts > 有 config」打分选一个。
169
+ * 找到就缓存;都找不到返回空串,让 git 用它自己的默认行为。
170
+ *
171
+ * @returns {Promise<string>} 可用的 HOME,或空串
172
+ */
173
+ async function resolveSshHome() {
174
+ if (cachedSshHome !== null) return cachedSshHome
175
+ cachedSshHome = await pickSshHome(sshHomeCandidates())
176
+ return cachedSshHome
177
+ }
178
+
179
+ /**
180
+ * 构造 git 子进程的环境变量。
181
+ *
182
+ * 关键点:把 HOME 换成 resolveSshHome() 选出的那个家目录——git 自带的 ssh 认 HOME,
183
+ * 而 DSH 可能把 HOME 重定向到工作目录(那里没有私钥)。不换就会报
184
+ * `Host key verification failed` 或 `Permission denied (publickey)`。
185
+ *
186
+ * 注意 `SSH_AUTH_SOCK` 要保留——ssh-agent 的路径与 HOME 无关,丢了反而连不上。
187
+ */
188
+ function buildGitEnv() {
189
+ const base = {
190
+ ...process.env,
191
+ GIT_TERMINAL_PROMPT: '0',
192
+ GIT_PAGER: 'cat',
193
+ GIT_OPTIONAL_LOCKS: '0',
194
+ LC_ALL: 'C',
195
+ }
196
+ if (cachedSshHome) {
197
+ base.HOME = cachedSshHome
198
+ base.USERPROFILE = cachedSshHome
199
+ }
200
+ return base
201
+ }
69
202
  /**
70
203
  * 跑一条 git 命令。
71
204
  * @param {string} cwd 仓库目录(作为 -C 的目标)
72
205
  * @param {string[]} args git 子命令与参数
73
- * @param {{ timeout?: number, allowFail?: boolean }} [options]
206
+ * @param {{ timeout?: number, allowFail?: boolean, input?: string }} [options] input 会写入 stdin(如 git apply)
74
207
  * @returns {Promise<string>} 标准输出(已去尾空白)
75
208
  */
76
209
  function git(cwd, args, options = {}) {
@@ -83,13 +216,9 @@ function git(cwd, args, options = {}) {
83
216
  timeout,
84
217
  maxBuffer: GIT_MAX_BUFFER,
85
218
  windowsHide: true,
86
- env: {
87
- ...process.env,
88
- GIT_TERMINAL_PROMPT: '0',
89
- GIT_PAGER: 'cat',
90
- GIT_OPTIONAL_LOCKS: '0',
91
- LC_ALL: 'C',
92
- },
219
+ // 需要往 stdin 喂数据的场景(git apply --cached 打补丁)
220
+ ...(typeof options.input === 'string' ? { input: options.input } : {}),
221
+ env: buildGitEnv(),
93
222
  },
94
223
  (error, stdout, stderr) => {
95
224
  if (error) {
@@ -592,11 +721,13 @@ async function readDiff(repo, options) {
592
721
  args.push('--first-parent', sha + '^!')
593
722
  target = sha
594
723
  } else if (untracked) {
595
- // 未跟踪文件:用 --no-index 对空文件比,得到整份内容作为新增
724
+ // 未跟踪文件:用 --no-index 对空文件比,得到整份内容作为新增。
725
+ // 必须用**相对路径**调用:传绝对路径时 git 会把整个路径当成文件名,
726
+ // 解析出来的 path 变成 'Users/xxx/repo/file' 这种,界面上就显示错了。
596
727
  const path = assertRepoPath(options.path)
597
- const full = join(repo, path)
598
- const raw = await git(repo, ['diff', '--no-color', '--no-ext-diff', '--no-index', '--', '/dev/null', full], { allowFail: true })
599
- return { target: path, source: 'untracked', truncated: false, files: parseDiff(raw).files }
728
+ const raw = await git(repo, ['diff', '--no-color', '--no-ext-diff', '--no-index', '--', '/dev/null', path], { allowFail: true })
729
+ const parsed = parseDiff(raw)
730
+ return { target: path, source: 'untracked', truncated: parsed.truncated, files: parsed.files }
600
731
  } else {
601
732
  if (staged) args.push('--cached')
602
733
  target = staged ? 'staged' : 'worktree'
@@ -678,10 +809,187 @@ async function pushRepo(repo, options) {
678
809
  const args = ['push']
679
810
  if (remote) args.push(remote)
680
811
  if (branch) args.push(branch)
681
- const output = await git(top, args, { timeout: GIT_PUSH_TIMEOUT_MS, allowFail: true })
812
+ // 不能用 allowFail:推送失败时 git 往 stderr 写原因、退出码非 0,
813
+ // allowFail 会把失败当成功返回,界面只显示「已推送」或干脆没反应。
814
+ // 这里让失败抛出来,由路由层转成 500,客户端才能显示真正的原因。
815
+ const output = await git(top, args, { timeout: GIT_PUSH_TIMEOUT_MS })
682
816
  return { repo: top, remote: remote || '(默认)', branch: branch || '(当前分支)', output: output.trim() }
683
817
  }
684
818
 
819
+ /**
820
+ * 更新代码:fetch 后把当前分支快进到上游。
821
+ *
822
+ * 只做 `--ff-only`:本地有未合并的提交时直接失败并说明原因,
823
+ * 不生成合并提交——面板上点一下「更新」就产生一个 merge commit 太意外了。
824
+ * 工作区有未提交改动时也拒绝:git 自己会拦,但提前说清楚更好懂。
825
+ */
826
+ /**
827
+ * 更新代码,带冲突策略。
828
+ *
829
+ * 三种策略(用户要求冲突时三选一):
830
+ * - `merge`:正常合并(`git pull --no-ff`),冲突留在工作区让人手动解决
831
+ * - `ours`:接受本地(`-X ours`),冲突处保留本地版本
832
+ * - `theirs`:接受远端(`-X theirs`),冲突处采用远端版本
833
+ *
834
+ * 先用 `pull --ff-only` 试一次:能快进就不必产生合并提交。
835
+ * 快进失败(本地有提交 / 已分叉)时才按策略走,这样「只是落后」的常见情况仍然干净。
836
+ */
837
+ async function pullRepo(repo, options) {
838
+ const top = await assertRepo(repo)
839
+ if (options.confirm !== true) throw new Error('写操作需要 confirm: true')
840
+ const strategy = typeof options.strategy === 'string' ? options.strategy : ''
841
+ const branch = (await git(top, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim()
842
+ if (!branch || branch === 'HEAD') throw new Error('当前处于分离头指针状态,无法更新')
843
+ const upstream = (await git(top, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], { allowFail: true })).trim()
844
+ if (!upstream) throw new Error('当前分支没有上游分支,无法更新(先设置 upstream 或手动推送一次)')
845
+ await git(top, ['fetch', '--prune'], { timeout: GIT_PUSH_TIMEOUT_MS, allowFail: true })
846
+ const counts = (await git(top, ['rev-list', '--left-right', '--count', 'HEAD...@{u}'], { allowFail: true })).trim()
847
+ const [aheadN, behindN] = counts.split(/\s+/).map((n) => Number(n) || 0)
848
+ if (behindN === 0) {
849
+ return { repo: top, branch, upstream, pulled: false, ahead: aheadN, behind: 0, conflict: false, output: '已是最新版本' }
850
+ }
851
+ // 本地没有分叉 → 直接快进,最干净
852
+ if (aheadN === 0) {
853
+ const out = await git(top, ['merge', '--ff-only', '@{u}'], { allowFail: true })
854
+ return { repo: top, branch, upstream, pulled: true, ahead: 0, behind: behindN, conflict: false, output: out.trim() }
855
+ }
856
+ // 已分叉:必须合并,按策略处理冲突
857
+ const args = ['merge', '--no-edit']
858
+ if (strategy === 'ours') args.push('-X', 'ours')
859
+ else if (strategy === 'theirs') args.push('-X', 'theirs')
860
+ args.push('@{u}')
861
+ const out = await git(top, args, { allowFail: true })
862
+ // 合并后检查是否留下未解决冲突
863
+ const conflicts = (await git(top, ['diff', '--name-only', '--diff-filter=U'], { allowFail: true })).trim()
864
+ const conflictFiles = conflicts ? conflicts.split('\n').filter(Boolean) : []
865
+ if (conflictFiles.length > 0) {
866
+ return {
867
+ repo: top, branch, upstream, pulled: false, ahead: aheadN, behind: behindN,
868
+ conflict: true, conflictFiles, strategy: strategy || '',
869
+ output: out.trim(),
870
+ }
871
+ }
872
+ return { repo: top, branch, upstream, pulled: true, ahead: 0, behind: behindN, conflict: false, strategy: strategy || '', output: out.trim() }
873
+ }
874
+
875
+ /** 放弃正在进行的合并(冲突弹窗里选「取消」时用)。 */
876
+ async function abortMerge(repo, options) {
877
+ const top = await assertRepo(repo)
878
+ if (options.confirm !== true) throw new Error('写操作需要 confirm: true')
879
+ const out = await git(top, ['merge', '--abort'], { allowFail: true })
880
+ return { repo: top, aborted: true, output: out.trim() }
881
+ }
882
+ /**
883
+ * 按片段暂存:只把指定的 hunk 加入暂存区。
884
+ *
885
+ * 做法是把选中的 hunk 重新拼成一份 patch,再 `git apply --cached` 打进索引——
886
+ * 这是 git 本身支持的做法(`git add -p` 内部就是这么干的),不依赖交互式终端。
887
+ *
888
+ * 关键细节:
889
+ * - patch 的 `diff --git` / `---` / `+++` 头必须完整,否则 apply 会拒绝。
890
+ * - hunk 头里的行号是**原文件**的坐标,不能改;只取我们选中的那几个 hunk。
891
+ * - 只暂存一部分 hunk 时,`--cached` 应用后索引里就是「部分改动」,工作区不变。
892
+ */
893
+ /**
894
+ * 把「选中的 hunk」拼成一份补丁。
895
+ *
896
+ * 暂存与还原都需要同一份拼装逻辑,抽出来避免两处各写一遍(错一处就难查)。
897
+ * 返回的 patch 是标准 unified diff,可直接喂给 git apply。
898
+ */
899
+ async function buildHunkPatch(top, path, wanted) {
900
+ const raw = await git(top, ['diff', '--no-color', '--no-ext-diff', '--patch', '--', path], { allowFail: true })
901
+ if (!raw.trim()) throw new Error('这个文件没有可处理的改动')
902
+ const lines = raw.split('\n')
903
+ const header = []
904
+ const hunks = []
905
+ let cur = null
906
+ for (const line of lines) {
907
+ if (line.startsWith('@@')) {
908
+ if (cur) hunks.push(cur)
909
+ cur = { header: line, body: [] }
910
+ continue
911
+ }
912
+ if (cur) cur.body.push(line)
913
+ else header.push(line)
914
+ }
915
+ if (cur) hunks.push(cur)
916
+ const picked = hunks.filter((_, i) => wanted.includes(i))
917
+ if (picked.length === 0) throw new Error('选中的片段不存在(文件可能已变化,刷新后重试)')
918
+ const patchLines = header.slice()
919
+ for (const h of picked) {
920
+ patchLines.push(h.header)
921
+ patchLines.push(...h.body)
922
+ }
923
+ return { patch: patchLines.join('\n').replace(/\n+$/, '\n'), picked: picked.length, total: hunks.length }
924
+ }
925
+ async function stageHunks(repo, options) {
926
+ const top = await assertRepo(repo)
927
+ if (options.confirm !== true) throw new Error('写操作需要 confirm: true')
928
+ const path = assertRepoPath(options.path)
929
+ const wanted = Array.isArray(options.hunks) ? options.hunks.map(Number) : []
930
+ if (wanted.length === 0) throw new Error('至少选择一个片段')
931
+ const { patch, picked, total } = await buildHunkPatch(top, path, wanted)
932
+ // --cached 只写索引;--unidiff-zero 容忍零上下文(某些 diff 会这样)
933
+ const out = await git(top, ['apply', '--cached', '--unidiff-zero', '--whitespace=nowarn', '-'], {
934
+ input: patch,
935
+ allowFail: true,
936
+ })
937
+ if (out && /error|fatal/i.test(out)) throw new Error(out.trim())
938
+ return { repo: top, path, stagedHunks: picked, totalHunks: total }
939
+ }
940
+ /**
941
+ * 还原选中的片段:把这些改动从工作区丢弃(`git checkout -p` 的非交互版本)。
942
+ *
943
+ * 用户要求「像 PhpStorm 这样,局部代码还原」。做法是把选中的 hunk **反向**应用:
944
+ * 生成补丁后用 `git apply -R` 回退工作区里的这几段,其余改动不受影响。
945
+ *
946
+ * 只对未暂存的改动有效——已暂存的改动要先 unstage 才能还原,这里不代劳,
947
+ * 否则用户会以为「还原了」其实索引里还留着。
948
+ */
949
+ async function restoreHunks(repo, options) {
950
+ const top = await assertRepo(repo)
951
+ if (options.confirm !== true) throw new Error('写操作需要 confirm: true')
952
+ const path = assertRepoPath(options.path)
953
+ const wanted = Array.isArray(options.hunks) ? options.hunks.map(Number) : []
954
+ if (wanted.length === 0) throw new Error('至少选择一个片段')
955
+ const { patch, picked, total } = await buildHunkPatch(top, path, wanted)
956
+ // -R 反向应用 = 撤销这几段改动;--unidiff-zero 容忍零上下文
957
+ const out = await git(top, ['apply', '-R', '--unidiff-zero', '--whitespace=nowarn', '-'], {
958
+ input: patch,
959
+ allowFail: true,
960
+ })
961
+ if (out && /error|fatal/i.test(out)) throw new Error(out.trim())
962
+ return { repo: top, path, restoredHunks: picked, totalHunks: total }
963
+ }
964
+
965
+ /**
966
+ * 读取未推送的提交(`@{u}..HEAD`)。
967
+ *
968
+ * 推送弹窗要列出「这次会推什么」,用户才能决定逐个推还是全推。
969
+ * 没有上游分支时返回空列表并带上原因——不是错误,只是没法列出。
970
+ */
971
+ async function readUnpushed(repo, options) {
972
+ const top = await assertRepo(repo)
973
+ const upstream = (await git(top, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], { allowFail: true })).trim()
974
+ if (!upstream) {
975
+ return { repo: top, upstream: '', branch: '', commits: [], reason: '当前分支没有上游分支,无法列出未推送记录' }
976
+ }
977
+ const branch = (await git(top, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim()
978
+ const raw = await git(top, ['log', '--no-color', '--pretty=format:' + LOG_FORMAT, '@{u}..HEAD'], { allowFail: true })
979
+ const commits = []
980
+ for (const rec of raw.split(RS)) {
981
+ if (!rec.trim()) continue
982
+ const p = rec.split(US)
983
+ if (p.length < 10) continue
984
+ commits.push({
985
+ sha: p[0], shortSha: p[1], author: p[2], authorEmail: p[3], authorDate: p[4],
986
+ committer: p[5], committerDate: p[6], parents: p[7] ? p[7].split(' ').filter(Boolean) : [],
987
+ refs: p[8], subject: p[9], body: (p[10] || '').trim(),
988
+ })
989
+ }
990
+ return { repo: top, upstream, branch, commits, reason: '' }
991
+ }
992
+
685
993
  /** 读取 git 版本(面板用来提示环境是否就绪)。 */
686
994
  async function gitVersion() {
687
995
  try {
@@ -696,6 +1004,176 @@ function fail(res, status, message, code) {
696
1004
  sendJson(res, status, { ok: false, error: { code: code || 'git-error', message } })
697
1005
  }
698
1006
 
1007
+ /**
1008
+ * 把常见的 git 报错翻译成可操作的中文说明。
1009
+ *
1010
+ * 原始报错对使用者几乎没有帮助:`Host key verification failed` 这种话,
1011
+ * 不说清「是什么问题、在哪台机器上、怎么修」,用户只能猜。
1012
+ *
1013
+ * 只翻译**确定**的几种;认不出来就原样返回,不要瞎猜。
1014
+ * 原文保留在末尾——排查时仍然需要看得到 git 的原话。
1015
+ *
1016
+ * @param {string} message 原始错误
1017
+ * @returns {string} 便于操作的解释(含原文)
1018
+ */
1019
+ export function explainGitError(message) {
1020
+ const raw = String(message || '').trim()
1021
+ if (!raw) return raw
1022
+ const withRaw = (hint) => hint + '\n\n原始报错:' + raw
1023
+ if (/Host key verification failed/i.test(raw)) {
1024
+ return withRaw(
1025
+ '这台机器还没信任远端的 SSH 主机指纹,git 拒绝连接。\n' +
1026
+ '先点面板上的「诊断」:它会显示 git 实际使用的 known_hosts 路径,以及主机指纹是否在里面。\n' +
1027
+ '确认指纹后,在运行本面板的那台机器上执行(把主机换成你的 git 服务器,路径用诊断里显示的那个):\n' +
1028
+ ' ssh-keyscan -H <git 主机> >> <known_hosts 路径>\n' +
1029
+ '或者先用 ssh 连一次那个地址,按提示输入 yes。\n' +
1030
+ '注意:面板里的 git 可能和系统自带 ssh 用的家目录不同,别把指纹写进另一个文件。\n' +
1031
+ '如果用的是 HTTPS 地址,则不需要这一步。'
1032
+ )
1033
+ }
1034
+ if (/Permission denied \(publickey/i.test(raw)) {
1035
+ return withRaw(
1036
+ '远端拒绝了这台机器的 SSH 公钥。\n' +
1037
+ '把本机的 ~/.ssh/id_rsa.pub(或 id_ed25519.pub)加到 git 账号的 SSH 公钥里,\n' +
1038
+ '并确认 ssh-agent 已加载对应私钥(ssh-add -l 可以看到)。'
1039
+ )
1040
+ }
1041
+ if (/Could not read from remote repository/i.test(raw)) {
1042
+ return withRaw(
1043
+ '读不到远端仓库:地址不对、仓库不存在,或这台机器没有访问权限。\n' +
1044
+ '先用 git remote -v 核对地址,再确认该账号在这个仓库上有写权限。'
1045
+ )
1046
+ }
1047
+ if (/non-fast-forward|fetch first|\[rejected\]/i.test(raw)) {
1048
+ return withRaw(
1049
+ '远端有你本地没有的提交,直接推送会被拒绝。\n' +
1050
+ '先点「更新」把远端改动拉下来(遇到冲突会提示你选择处理方式),再推送。'
1051
+ )
1052
+ }
1053
+ if (/failed to push some refs/i.test(raw)) {
1054
+ return withRaw('推送被远端拒绝。常见原因见下面的原始报错。')
1055
+ }
1056
+ if (/Authentication failed|could not read Username|terminal prompts disabled/i.test(raw)) {
1057
+ return withRaw(
1058
+ '远端要求登录,但这台机器上没有可用的凭据。\n' +
1059
+ 'HTTPS 地址需要配置凭据(如 ~/.git-credentials 或 credential.helper),\n' +
1060
+ '或者把远端换成 SSH 地址。'
1061
+ )
1062
+ }
1063
+ if (/does not appear to be a git repository/i.test(raw)) {
1064
+ return withRaw('这个地址不是 git 仓库,或仓库已被删除/改名。')
1065
+ }
1066
+ return raw
1067
+ }
1068
+ /**
1069
+ * 判断某个主机条目是否已在 known_hosts 里。
1070
+ *
1071
+ * 用 `ssh-keygen -F`:它能处理 HashKnownHosts 生成的哈希条目,纯文本匹配做不到。
1072
+ * 返回 null 表示这台机器没有 ssh-keygen、无法判断(不误报失败)。
1073
+ *
1074
+ * @param {string} entry 查询键:默认端口是 host,非默认端口是 [host]:port
1075
+ * @param {string} knownHosts known_hosts 文件路径
1076
+ * @returns {Promise<boolean|null>}
1077
+ */
1078
+ function hostKeyTrusted(entry, knownHosts) {
1079
+ return new Promise((resolve) => {
1080
+ execFile(
1081
+ 'ssh-keygen',
1082
+ ['-F', entry, '-f', knownHosts],
1083
+ { timeout: 8000, windowsHide: true },
1084
+ (error, stdout) => {
1085
+ // 没装 ssh-keygen:无法判断,别当成失败
1086
+ if (error && error.code === 'ENOENT') { resolve(null); return }
1087
+ // 查不到时 ssh-keygen 退出码非 0 但没有输出;查到了才有输出
1088
+ resolve(String(stdout || '').trim().length > 0)
1089
+ },
1090
+ )
1091
+ })
1092
+ }
1093
+
1094
+ /**
1095
+ * 诊断远端连通性:把「推送为什么失败」的每一环都检查一遍。
1096
+ *
1097
+ * 用户的真实场景:同一台机器上 AI 能推送、面板不能,说明 SSH 本身通。
1098
+ * 差别只可能在**执行环境**——宿主进程的 HOME、SSH_AUTH_SOCK、known_hosts 位置。
1099
+ * 这个函数把这些都列出来,用户一眼能看到哪一环断了,不用猜。
1100
+ *
1101
+ * 关键修正:连通性必须走 git 自己那条路(git ls-remote),不能用 PATH 里的 ssh。
1102
+ * Windows 上系统自带 ssh 与 git 自带 ssh 认的不是同一个家目录——之前诊断显示
1103
+ * 「连通」而推送报 Host key verification failed,就是这个假阳性。
1104
+ *
1105
+ * 只读,不改任何配置。
1106
+ */
1107
+ export async function diagnoseRemote(repo) {
1108
+ const top = await assertRepo(repo)
1109
+ const env = process.env
1110
+ const rawHome = env.HOME || env.USERPROFILE || ''
1111
+ // 报告 git 实际会用的家目录:pickSshHome 选出的那个(可能是用户目录而不是进程 HOME),
1112
+ // 诊断必须反映真实情况,否则修好了也显示失败。
1113
+ const effectiveHome = await resolveSshHome()
1114
+ const home = effectiveHome || rawHome
1115
+ const out = {
1116
+ repo: top,
1117
+ env: {
1118
+ HOME: home || '(未设置)',
1119
+ HOME_原始: rawHome || '(未设置)',
1120
+ USERPROFILE: env.USERPROFILE || '(未设置)',
1121
+ SSH_AUTH_SOCK: env.SSH_AUTH_SOCK || '(未设置)',
1122
+ GIT_TERMINAL_PROMPT: env.GIT_TERMINAL_PROMPT || '(未设置)',
1123
+ },
1124
+ files: {},
1125
+ remote: '',
1126
+ checks: [],
1127
+ }
1128
+ const add = (name, ok, detail) => out.checks.push({ name, ok, detail })
1129
+ const sshDir = home ? join(home, '.ssh') : ''
1130
+ const hasDir = sshDir ? await fsp.stat(sshDir).then((s) => s.isDirectory()).catch(() => false) : false
1131
+ add('宿主进程的 HOME 下有 .ssh 目录', hasDir, hasDir ? sshDir : '找不到 ' + (sshDir || '(HOME 未设置)'))
1132
+ const knownHosts = sshDir ? join(sshDir, 'known_hosts') : ''
1133
+ const hasKnown = knownHosts ? await fsp.stat(knownHosts).then(() => true).catch(() => false) : false
1134
+ add('known_hosts 存在', hasKnown, hasKnown ? knownHosts : '找不到 ' + (knownHosts || '(HOME 未设置)'))
1135
+ add('SSH_AUTH_SOCK 已设置', !!env.SSH_AUTH_SOCK, env.SSH_AUTH_SOCK || '未设置:用密钥文件而非 ssh-agent 时不影响')
1136
+ if (hasDir) {
1137
+ const entries = await fsp.readdir(sshDir).catch(() => [])
1138
+ out.files[sshDir] = entries.filter((n) => !n.endsWith('.pub')).slice(0, 12)
1139
+ }
1140
+ try {
1141
+ out.remote = (await git(top, ['remote', 'get-url', 'origin'])).trim()
1142
+ } catch {
1143
+ out.remote = '(没有 origin)'
1144
+ }
1145
+ const sshRemote = /^ssh:\/\//.test(out.remote) || /^[^/]+@[^:]+:/.test(out.remote)
1146
+ if (!sshRemote) {
1147
+ add('远端地址类型', true, '非 SSH 地址(HTTPS 等),不需要 SSH 配置')
1148
+ return out
1149
+ }
1150
+ const m = /^(?:ssh:\/\/)?([^@/]+)@([^:/]+)(?::(\d+))?/.exec(out.remote)
1151
+ const host = m ? m[2] : ''
1152
+ const port = (m && m[3]) || '22'
1153
+ // 主机指纹到底在不在 git 会读的那个 known_hosts 里:这一项直接对应推送报错
1154
+ if (host && hasKnown) {
1155
+ const entry = port === '22' ? host : '[' + host + ']:' + port
1156
+ const trusted = await hostKeyTrusted(entry, knownHosts)
1157
+ if (trusted === null) {
1158
+ add('主机指纹在 known_hosts 中', true, '无法自动确认(这台机器没有 ssh-keygen):先用 ssh 连一次远端确认')
1159
+ } else {
1160
+ add(
1161
+ '主机指纹在 known_hosts 中',
1162
+ trusted,
1163
+ trusted ? entry + ' 已信任' : '没找到 ' + entry + ':推送会被拒绝,要把它写进上面的 known_hosts',
1164
+ )
1165
+ }
1166
+ }
1167
+ // 真正读一次远端:和推送用同一个 git、同一份环境、同一份 known_hosts。
1168
+ // 这是唯一不会骗人的判断——之前直接调 ssh 测连通,走的可能是系统里另一套 SSH 配置。
1169
+ try {
1170
+ await git(top, ['ls-remote', 'origin'], { timeout: 20000 })
1171
+ add('git 读取远端(与推送同一条路)', true, 'SSH 认证与仓库访问都正常')
1172
+ } catch (error) {
1173
+ add('git 读取远端(与推送同一条路)', false, explainGitError((error && error.message) || String(error)).slice(0, 800))
1174
+ }
1175
+ return out
1176
+ }
699
1177
  /** 路由主体:按 URL 末段分发。 */
700
1178
  async function handleGit(req, res) {
701
1179
  let url
@@ -753,8 +1231,26 @@ async function handleGit(req, res) {
753
1231
  }
754
1232
 
755
1233
  if (method === 'status') {
756
- const status = await readStatus(body && body.repo)
757
- sendJson(res, 200, { ok: true, data: status })
1234
+ // 多仓库:body.repos 数组时逐仓读,返回 results(与 commits 路由同形),
1235
+ // 让工作区也能像历史记录一样把子仓库一起看。单仓仍走 repo 字段,向后兼容。
1236
+ const list = Array.isArray(body && body.repos) ? body.repos.filter((x) => typeof x === 'string' && x) : []
1237
+ if (list.length === 0) {
1238
+ const status = await readStatus(body && body.repo)
1239
+ sendJson(res, 200, { ok: true, data: status })
1240
+ return
1241
+ }
1242
+ if (list.length > 20) { fail(res, 400, '一次最多查询 20 个仓库', 'too-many-repos'); return }
1243
+ const results = []
1244
+ for (const path of list) {
1245
+ try {
1246
+ const status = await readStatus(path)
1247
+ results.push({ repo: path, ok: true, status })
1248
+ } catch (error) {
1249
+ // 单个仓库失败不拖垮其它:标出它自己失败即可
1250
+ results.push({ repo: path, ok: false, error: error instanceof Error ? error.message : String(error) })
1251
+ }
1252
+ }
1253
+ sendJson(res, 200, { ok: true, data: { results } })
758
1254
  return
759
1255
  }
760
1256
 
@@ -778,18 +1274,54 @@ async function handleGit(req, res) {
778
1274
  return
779
1275
  }
780
1276
 
1277
+ if (method === 'stage-hunks') {
1278
+ const result = await stageHunks(body && body.repo, body || {})
1279
+ sendJson(res, 200, { ok: true, data: result })
1280
+ return
1281
+ }
1282
+
1283
+ if (method === 'restore-hunks') {
1284
+ const result = await restoreHunks(body && body.repo, body || {})
1285
+ sendJson(res, 200, { ok: true, data: result })
1286
+ return
1287
+ }
1288
+
781
1289
  if (method === 'create-commit') {
782
1290
  const result = await createCommit(body && body.repo, body || {})
783
1291
  sendJson(res, 200, { ok: true, data: result })
784
1292
  return
785
1293
  }
786
1294
 
1295
+ if (method === 'diagnose') {
1296
+ const result = await diagnoseRemote(body && body.repo)
1297
+ sendJson(res, 200, { ok: true, data: result })
1298
+ return
1299
+ }
1300
+
1301
+ if (method === 'unpushed') {
1302
+ const result = await readUnpushed(body && body.repo, body || {})
1303
+ sendJson(res, 200, { ok: true, data: result })
1304
+ return
1305
+ }
1306
+
787
1307
  if (method === 'push') {
788
1308
  const result = await pushRepo(body && body.repo, body || {})
789
1309
  sendJson(res, 200, { ok: true, data: result })
790
1310
  return
791
1311
  }
792
1312
 
1313
+ if (method === 'pull') {
1314
+ const result = await pullRepo(body && body.repo, body || {})
1315
+ sendJson(res, 200, { ok: true, data: result })
1316
+ return
1317
+ }
1318
+
1319
+ if (method === 'abort-merge') {
1320
+ const result = await abortMerge(body && body.repo, body || {})
1321
+ sendJson(res, 200, { ok: true, data: result })
1322
+ return
1323
+ }
1324
+
793
1325
  if (method === 'authors') {
794
1326
  // 提交人下拉的可选值:取最近一批提交里的作者,去重后按出现次数排序
795
1327
  const repo = body && body.repo
@@ -847,7 +1379,7 @@ async function handleGit(req, res) {
847
1379
 
848
1380
  fail(res, 404, '未知接口:' + method, 'method-not-found')
849
1381
  } catch (error) {
850
- fail(res, 500, (error && error.message) || String(error))
1382
+ fail(res, 500, explainGitError((error && error.message) || String(error)))
851
1383
  }
852
1384
  }
853
1385
 
@@ -861,6 +1393,9 @@ export const feature = {
861
1393
  setup(ctx) {
862
1394
  const webServer = ctx.get('webServer')
863
1395
  if (webServer === undefined) throw new Error('webServer 服务不可用,无法提供 Git 管理路由')
1396
+ // 启动时就探一次家目录:推送前就该知道 git 能不能找到 .ssh,
1397
+ // 而不是等用户点了推送才报一个看不懂的错。
1398
+ void resolveSshHome()
864
1399
  const dispose = webServer.register({
865
1400
  kind: 'prefix',
866
1401
  auth: 'required',