dsh-git-push 0.0.0-stage → 2.8.6

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.
Files changed (279) hide show
  1. package/.auditignore +30 -0
  2. package/.gitignore +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1486 -2
  5. package/cli.mjs +360 -0
  6. package/cordis.patch.yml +14 -0
  7. package/lib/ARCHITECTURE.md +34 -0
  8. package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
  9. package/lib/app/apply.js +275 -0
  10. package/lib/app/audit-api.js +158 -0
  11. package/lib/app/command-registry.js +266 -0
  12. package/lib/app/constants.js +16 -0
  13. package/lib/app/handlers/account.js +166 -0
  14. package/lib/app/handlers/clone.js +168 -0
  15. package/lib/app/handlers/http-constants.js +9 -0
  16. package/lib/app/handlers/identity-rewrite.js +94 -0
  17. package/lib/app/handlers/meta.js +175 -0
  18. package/lib/app/handlers/npm.js +169 -0
  19. package/lib/app/handlers/repo-actions.js +143 -0
  20. package/lib/app/handlers/repos.js +231 -0
  21. package/lib/app/handlers/settings.js +62 -0
  22. package/lib/app/host-doc-checks.js +25 -0
  23. package/lib/app/http-handlers.js +131 -0
  24. package/lib/app/index.js +30 -0
  25. package/lib/app/inject-text.js +192 -0
  26. package/lib/app/scan-root.js +23 -0
  27. package/lib/app/schema.js +150 -0
  28. package/lib/app/settings-bridge.js +167 -0
  29. package/lib/app/slash-commands.js +395 -0
  30. package/lib/app/slot-stats.js +35 -0
  31. package/lib/app/tool-call.js +672 -0
  32. package/lib/app/tools.js +34 -0
  33. package/lib/ast/brace.js +105 -0
  34. package/lib/ast/callgraph.js +135 -0
  35. package/lib/ast/code-lines.js +114 -0
  36. package/lib/ast/consts.js +12 -0
  37. package/lib/ast/control-flow.js +461 -0
  38. package/lib/ast/credential.js +199 -0
  39. package/lib/ast/dataflow.js +274 -0
  40. package/lib/ast/dup-code.js +165 -0
  41. package/lib/ast/index.js +36 -0
  42. package/lib/ast/io-risk-const.js +95 -0
  43. package/lib/ast/io-risk-fn.js +208 -0
  44. package/lib/ast/io-risk-loop.js +308 -0
  45. package/lib/ast/io-risk.js +314 -0
  46. package/lib/ast/lang.js +156 -0
  47. package/lib/ast/line-count.js +52 -0
  48. package/lib/ast/magic-number.js +272 -0
  49. package/lib/ast/naming.js +284 -0
  50. package/lib/ast/perf.js +472 -0
  51. package/lib/ast/scope.js +241 -0
  52. package/lib/ast/shell.js +131 -0
  53. package/lib/ast/size.js +378 -0
  54. package/lib/ast/symbol-index.js +399 -0
  55. package/lib/ast/tokenizer.js +341 -0
  56. package/lib/audit/analysis-coverage.js +98 -0
  57. package/lib/audit/audit-file.js +182 -0
  58. package/lib/audit/checks.js +17 -0
  59. package/lib/audit/client-entry.js +93 -0
  60. package/lib/audit/collector.js +477 -0
  61. package/lib/audit/ext-runner.js +80 -0
  62. package/lib/audit/file-context.js +138 -0
  63. package/lib/audit/finding.js +50 -0
  64. package/lib/audit/gitignore-match.js +113 -0
  65. package/lib/audit/glob.js +63 -0
  66. package/lib/audit/history-report.js +100 -0
  67. package/lib/audit/history.js +126 -0
  68. package/lib/audit/ignore-blind.js +101 -0
  69. package/lib/audit/index.js +33 -0
  70. package/lib/audit/orchestrate.js +476 -0
  71. package/lib/audit/public.js +24 -0
  72. package/lib/audit/repo-level.js +30 -0
  73. package/lib/audit/report-yaml.js +86 -0
  74. package/lib/audit/slot.js +65 -0
  75. package/lib/audit-defaults.js +18 -0
  76. package/lib/audit-rules/audit-rules-comment.yml +247 -0
  77. package/lib/audit-rules/audit-rules-cpp.yml +22 -0
  78. package/lib/audit-rules/audit-rules-docs.yml +32 -0
  79. package/lib/audit-rules/audit-rules-dsh.yml +162 -0
  80. package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
  81. package/lib/audit-rules/audit-rules-folder.yml +99 -0
  82. package/lib/audit-rules/audit-rules-frontend.yml +335 -0
  83. package/lib/audit-rules/audit-rules-go.yml +22 -0
  84. package/lib/audit-rules/audit-rules-i18n.yml +45 -0
  85. package/lib/audit-rules/audit-rules-java.yml +105 -0
  86. package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
  87. package/lib/audit-rules/audit-rules-npm.yml +187 -0
  88. package/lib/audit-rules/audit-rules-paths.yml +92 -0
  89. package/lib/audit-rules/audit-rules-performance.yml +215 -0
  90. package/lib/audit-rules/audit-rules-php.yml +22 -0
  91. package/lib/audit-rules/audit-rules-private.yml +24 -0
  92. package/lib/audit-rules/audit-rules-python.yml +106 -0
  93. package/lib/audit-rules/audit-rules-robustness.yml +27 -0
  94. package/lib/audit-rules/audit-rules-rust.yml +22 -0
  95. package/lib/audit-rules/audit-rules-structure.yml +159 -0
  96. package/lib/audit-rules/audit-rules-swift.yml +22 -0
  97. package/lib/audit-rules/audit-rules-template.yml +108 -0
  98. package/lib/checks/button-bind.js +276 -0
  99. package/lib/checks/common.js +170 -0
  100. package/lib/checks/credential-file.js +43 -0
  101. package/lib/checks/dataflow.js +40 -0
  102. package/lib/checks/dispatch.js +112 -0
  103. package/lib/checks/dup-code.js +69 -0
  104. package/lib/checks/dup-const.js +232 -0
  105. package/lib/checks/file-health.js +150 -0
  106. package/lib/checks/filter.js +137 -0
  107. package/lib/checks/folder.js +173 -0
  108. package/lib/checks/hardcoded-path.js +98 -0
  109. package/lib/checks/index.js +46 -0
  110. package/lib/checks/io.js +66 -0
  111. package/lib/checks/magic-number.js +42 -0
  112. package/lib/checks/npm-json.js +273 -0
  113. package/lib/checks/private.js +63 -0
  114. package/lib/checks/regex.js +256 -0
  115. package/lib/checks/semantic.js +134 -0
  116. package/lib/checks/structural.js +274 -0
  117. package/lib/cli/commands-account.mjs +107 -0
  118. package/lib/cli/commands-audit.mjs +144 -0
  119. package/lib/cli/commands-doc.mjs +127 -0
  120. package/lib/cli/commands-vcs.mjs +175 -0
  121. package/lib/client/index.js +162 -0
  122. package/lib/client-parts/00-loader.js +33 -0
  123. package/lib/client-parts/01-const.js +207 -0
  124. package/lib/client-parts/02-utils.js +62 -0
  125. package/lib/client-parts/03-icons.js +12 -0
  126. package/lib/client-parts/10-account.js +83 -0
  127. package/lib/client-parts/11-browser.js +95 -0
  128. package/lib/client-parts/20-repo.js +374 -0
  129. package/lib/client-parts/21-audit.js +301 -0
  130. package/lib/client-parts/22-settings.js +146 -0
  131. package/lib/client-parts/23-npm.js +383 -0
  132. package/lib/client-parts/30-page.js +56 -0
  133. package/lib/client-parts/40-controller.js +1092 -0
  134. package/lib/client-parts/41-actions.js +279 -0
  135. package/lib/client-parts/99-apply.js +72 -0
  136. package/lib/client.js +3195 -0
  137. package/lib/commit-push.js +148 -0
  138. package/lib/context/index.js +363 -0
  139. package/lib/core/atomic-json.js +98 -0
  140. package/lib/core/config.js +40 -0
  141. package/lib/core/credentials.js +274 -0
  142. package/lib/core/endpoints.js +109 -0
  143. package/lib/core/exec.js +162 -0
  144. package/lib/exempt/index.js +292 -0
  145. package/lib/fs/edit-after-read.js +103 -0
  146. package/lib/fsx.js +87 -0
  147. package/lib/git/account-status.js +140 -0
  148. package/lib/git/account.js +233 -0
  149. package/lib/git/api.js +136 -0
  150. package/lib/git/atomic-json.js +6 -0
  151. package/lib/git/browse.js +38 -0
  152. package/lib/git/clone-download.js +397 -0
  153. package/lib/git/clone-history-mode.js +143 -0
  154. package/lib/git/clone-history.js +175 -0
  155. package/lib/git/clone-jobs.js +250 -0
  156. package/lib/git/clone-replay-io.js +172 -0
  157. package/lib/git/clone-replay.js +275 -0
  158. package/lib/git/clone.js +445 -0
  159. package/lib/git/cloud.js +46 -0
  160. package/lib/git/commit-message.js +141 -0
  161. package/lib/git/config.js +6 -0
  162. package/lib/git/cred-env.js +88 -0
  163. package/lib/git/credentials.js +6 -0
  164. package/lib/git/endpoints.js +6 -0
  165. package/lib/git/exec.js +6 -0
  166. package/lib/git/identity-rewrite.js +297 -0
  167. package/lib/git/identity.js +150 -0
  168. package/lib/git/ignore.js +69 -0
  169. package/lib/git/index.js +41 -0
  170. package/lib/git/module-splitter.js +47 -0
  171. package/lib/git/post-push.js +101 -0
  172. package/lib/git/push-diagnose.js +142 -0
  173. package/lib/git/push.js +476 -0
  174. package/lib/git/remote-resolve.js +146 -0
  175. package/lib/git/remote.js +128 -0
  176. package/lib/git/repo-index.js +512 -0
  177. package/lib/git/repos.js +235 -0
  178. package/lib/git/scan-runner.js +159 -0
  179. package/lib/git/sensitive.js +134 -0
  180. package/lib/git/transport.js +430 -0
  181. package/lib/git/visibility.js +35 -0
  182. package/lib/git/wrapped-git.js +68 -0
  183. package/lib/http/index.js +170 -0
  184. package/lib/index.js +24 -0
  185. package/lib/link-check/index.js +187 -0
  186. package/lib/npm/account.js +64 -0
  187. package/lib/npm/install.js +211 -0
  188. package/lib/npm/npmrc.js +56 -0
  189. package/lib/npm/publish.js +171 -0
  190. package/lib/npm/registry.js +168 -0
  191. package/lib/plugin/auto-detect.js +92 -0
  192. package/lib/plugin/auto-push.js +154 -0
  193. package/lib/plugin/index.js +250 -0
  194. package/lib/readme-templates/readme.yml +38 -0
  195. package/lib/rule/compilers/credential.js +62 -0
  196. package/lib/rule/compilers/dataflow.js +38 -0
  197. package/lib/rule/compilers/file-health.js +75 -0
  198. package/lib/rule/compilers/frontend.js +86 -0
  199. package/lib/rule/compilers/func.js +35 -0
  200. package/lib/rule/compilers/helpers.js +71 -0
  201. package/lib/rule/compilers/index.js +29 -0
  202. package/lib/rule/compilers/link-semantic.js +45 -0
  203. package/lib/rule/compilers/list-kinds.js +12 -0
  204. package/lib/rule/compilers/numeric-kinds.js +66 -0
  205. package/lib/rule/compilers/regex.js +78 -0
  206. package/lib/rule/compilers/structure.js +80 -0
  207. package/lib/rule/compilers.js +17 -0
  208. package/lib/rule/homoglyph.js +45 -0
  209. package/lib/rule/loader.js +270 -0
  210. package/lib/rule/registry.js +115 -0
  211. package/lib/rule/scope.js +67 -0
  212. package/lib/score/docs-score.js +166 -0
  213. package/lib/score/index.js +140 -0
  214. package/lib/self/index.js +196 -0
  215. package/lib/skip-dirs.js +64 -0
  216. package/lib/tool-probes.json +50 -0
  217. package/lib/user-requirements.json +14 -0
  218. package/lib/vendor/js-yaml/LICENSE +21 -0
  219. package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
  220. package/package.json +95 -4
  221. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  222. package/scripts/audit-ext/_example-readme-present.mjs +34 -0
  223. package/scripts/audit-ext/variable-min-length.mjs +102 -0
  224. package/scripts/audit-runner.mjs +35 -0
  225. package/scripts/audit-runtime-check.mjs +129 -0
  226. package/scripts/browser-page-probe.mjs +271 -0
  227. package/scripts/build-client.mjs +119 -0
  228. package/scripts/check.mjs +88 -0
  229. package/scripts/clean-date-comments.py +102 -0
  230. package/scripts/cpu-sample.mjs +188 -0
  231. package/scripts/doc-drift.mjs +200 -0
  232. package/scripts/doc-func.mjs +212 -0
  233. package/scripts/doc-tree.mjs +456 -0
  234. package/scripts/doc-version.mjs +220 -0
  235. package/scripts/frontend-preview-check.mjs +124 -0
  236. package/scripts/hot-path-probe-cjs.cjs +71 -0
  237. package/scripts/hot-path-probe-fs-shim.mjs +28 -0
  238. package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
  239. package/scripts/hot-path-probe.mjs +153 -0
  240. package/scripts/module-splitter.py +800 -0
  241. package/scripts/platform-scan.mjs +168 -0
  242. package/scripts/preview-gen.mjs +489 -0
  243. package/scripts/preview-local-runner.mjs +55 -0
  244. package/scripts/preview-server-direct.mjs +116 -0
  245. package/scripts/preview-server.mjs +305 -0
  246. package/scripts/preview-slot-data.mjs +123 -0
  247. package/scripts/probe-recheck.mjs +47 -0
  248. package/scripts/readme-gen.mjs +268 -0
  249. package/scripts/rename-locator.mjs +97 -0
  250. package/scripts/rule-switch.mjs +97 -0
  251. package/scripts/rules-solo-audit.mjs +173 -0
  252. package/scripts/scan-file-io.mjs +713 -0
  253. package/scripts/scan-hardcoded-paths.mjs +125 -0
  254. package/scripts/scan-repos.mjs +167 -0
  255. package/scripts/scan-version.mjs +122 -0
  256. package/scripts/scrub-user-wording.mjs +420 -0
  257. package/scripts/symbol-index.mjs +85 -0
  258. package/scripts/sync-plugin-install.mjs +223 -0
  259. package/scripts/sync-plugin.mjs +279 -0
  260. package/scripts/verify-prestep.mjs +100 -0
  261. package/skills/dev/audit-rule-authoring.md +58 -0
  262. package/skills/dev/dsh-git-push.md +323 -0
  263. package/skills/dev/git-push-live-fix.md +45 -0
  264. package/skills/dsh-repo-index.md +35 -0
  265. package/skills/guide/guide-audit.md +167 -0
  266. package/skills/guide/guide-cli-scripts.md +104 -0
  267. package/skills/guide/guide-clone-repos.md +173 -0
  268. package/skills/guide/guide-commit-push.md +156 -0
  269. package/skills/guide/guide-inject-ui.md +166 -0
  270. package/skills/guide/guide-slash-completion.md +118 -0
  271. package/skills/workflow/README.md +21 -0
  272. package/skills/workflow/git-commit-discipline.md +68 -0
  273. package/skills/workflow/git-project-startup.md +85 -0
  274. package/skills/workflow/git-rebuild-process.md +57 -0
  275. package/skills/workflow/github-operations.md +91 -0
  276. package/skills/workflow/readme-sync-git-md.md +28 -0
  277. package/skills/workflow/task-completion-report.md +73 -0
  278. package/skills/workflow/tool-json-add-ask.md +35 -0
  279. package/skills/workflow/versioning-rule.md +211 -0
@@ -0,0 +1,1092 @@
1
+ /* ─────────────────── [10] Controller(状态机 + 数据加载 + 动作注入) ─────────────────── */
2
+ class dshgp_Controller {
3
+ constructor(scope) {
4
+ this.scope = scope;
5
+ this.text = '';
6
+ this.sshPub = '';
7
+ this.sshEmail = '';
8
+ this.saving = false;
9
+ this.failed = false;
10
+ this.savedMsg = '';
11
+ this.savedTimer = null;
12
+ this.auditEnabled = false;
13
+ this.injectRequirements = false;
14
+ // 注入总开关(默认开;新增, 扩展为系统提示词+上下文)
15
+ this.injectSystemPrompt = true;
16
+ // 审计扫描范围(diff|full)——设置持久化走 host HTTP,前端本地字段镜像
17
+ this.auditScanScope = 'diff';
18
+ this.ruleOrder = [];
19
+ this.slotMeta = {};
20
+ this.weightValues = {};
21
+ // 补齐:以下键此前只有 schema 声明与 HTTP 白名单,前端**没有 UI 控件**
22
+ // (只能看不能改)→ 设置「基本都没真正保存」的根源。这里补状态镜像 + 提交 + 回读。
23
+ this.maxScanFiles = 3000; // 全量审计文件数上限(0=不限)
24
+ this.pushMethod = 'ssh'; // ssh | api | auto
25
+ this.pushGate = false; // 推送门禁(开启后 push 需显式放行)
26
+ // defaultScanRoot/commitMessage 设置移除——默认扫描路径复用本地仓库
27
+ // 列表选择路径(localStorage dshgp-scan-path),提交信息留空由调用方/AI 生成。
28
+ // 禁用态不再前端变量存储,以 yml 顶层 disabled 为准(listRuleSlots 解析)
29
+ this.statusMsg = '';
30
+ this.statusTimer = null;
31
+ // 账号信息(纯展示)
32
+ this.tokenConfigured = false;
33
+ this.sshConfigured = false;
34
+ // 凭据有效性快照(token/ssh 各自 valid/login/checkedAt)——来自 account-status.json
35
+ this.tokenStatus = null;
36
+ this.sshStatus = null;
37
+ this.accountBlock = '';
38
+ this.accountLoggedIn = false;
39
+ this.accountLoading = false;
40
+ // npm 账号态(与 GitHub 账号态**同构**:离线快照 + 在线校验两段式;包列表同源刷新)
41
+ this.npmAccountBlock = '';
42
+ this.npmAccountLoggedIn = false;
43
+ this.npmAccountLoading = false;
44
+ this.npmAccountUser = '';
45
+ this.npmConfigured = false; // 后端返回的「凭据文件里有没有 npm token」(唯一真源,不从块文案反推)
46
+ this.npmOwned = [];
47
+ this.npmOwnedLoading = false;
48
+ this.npmOwnedError = '';
49
+ this.npmInstallBusy = ''; // 正在安装的包名('' = 空闲)
50
+ this.npmInstallResult = null; // 最近一次安装回执(含日志路径与输出摘要)
51
+ // 安装流程(照 GitHub 克隆四段):选择对话框 + 进度轮询
52
+ this.npmInstallDialog = null; // { name } = 正在选安装位置
53
+ this.npmInstallProgress = null;// 轮询到的进度(state/lines/tail)
54
+ this.npmInstallTimer = null; // 轮询定时器(终态后清理)
55
+ // API 配额(token 的 /rate_limit 快照):quotaLoading 防重复请求;quotaError 记后端
56
+ // 写快照失败的原因(此前该失败被静默丢弃,UI 看不出「查了但没落盘」)
57
+ this.apiQuota = null;
58
+ this.quotaLoading = false;
59
+ this.quotaError = '';
60
+ // 账号卡片:本地/云端(本地扫描 / 云端列表)
61
+ this.localPath = '';
62
+ this.localRepos = [];
63
+ this.localLoading = false;
64
+ this.localScanning = false; // 独立进程扫描进行中(按钮禁用,不可重复扫描)
65
+ this.localMsg = '';
66
+ this.cloudRepos = [];
67
+ this.cloudLoading = false;
68
+ this.cloudMsg = '';
69
+ this.repoBusy = '';
70
+ this.cloneProgress = null; // 进行中的 clone 进度(轮询填充)
71
+ this._cloneResumeTimer = null; // 后台克隆接续轮询句柄(后台化配套)
72
+ this.clonePreview = null; // 待确认的 clone 预览
73
+ this.cloneHistory = null; // 预览框「带真实历史」勾选:null=未表态(跟随后端默认 true)、true/false=用户显式选择
74
+ this.clonePending = { repo: '', dir: '' }; // 预览后待确认的上下文
75
+ this.visConfirm = null; // 1.5.4:待确认的可见性切换({fullName, target, cur},命中则弹独立确认面板)
76
+ this.maxCloneFileMB = 10; // clone 单文件体积上限(MB);0=不限
77
+ this.cloneConcurrency = 6; // clone 并发下载数
78
+ this.repoFeedback = {}; // { path: {ok, msg} } push 结果反馈(成功绿/失败红)
79
+ // 规则包加载
80
+ this.slotLoading = false;
81
+ this.slotError = '';
82
+ // 统一刷新入口 refresh() 的部分级错误记录(单个部分失败不阻断其余部分)
83
+ this.refreshError = '';
84
+ this.genKeying = false;
85
+ this.genKeyError = '';
86
+ // 本次编辑会话已触达的设置键集合——loadSettingsFromHttp 的异步 GET
87
+ // 返回旧值时跳过这些键,防止「点开关被初始化响应弹回」(回弹根因:GET 发出后
88
+ // 点击发生,POST 未落盘前 GET 旧值先把本地覆盖回去)
89
+ this.editedKeys = new Set();
90
+ this.store = store.createSnapshotStore(this.project());
91
+ this.unsubscribe = scope.subscribe(() => {
92
+ const snap = this.scope.getSnapshot();
93
+ if (snap && snap.value) {
94
+ // 重构:设置/凭据状态全链路统一走 HTTP(settings-get + account-check,
95
+ // 真源 = config.json + 凭据文件),**scope 快照不再参与任何状态判定**——
96
+ // 公共 settings.yaml 已零写入(scope.set 全移除),snap.value 里这些键恒缺省,
97
+ // 此前把 sshConfigured 覆盖成 !!snap.value.sshPub(恒 false)导致「配置了却显示
98
+ // 未配置」,且每次 scope 发布都弹回,与 loadSettingsFromHttp 拉回的真值互相打架。
99
+ // 修复「规则包统计全是 0」:slotMeta 与 ruleOrder 同理,也不再从 scope 覆盖。
100
+ // snap.value.ruleSlotMeta 是 schema 里声明为「host 启动填充」的字段,但**宿主从未写入**,
101
+ // 于是每次 scope 发布都把它(空对象)赋给 slotMeta,刚由 loadSlots() 拉到的真实统计被清空,
102
+ // 所有规则包行回退到 {blocker:0,warning:0,pass:0,total:0} 兜底值 → 列表里数字全是 0。
103
+ // 权威来源 = loadSlots() 的后端结果(动态发现全部 yml 并带 stats);启停的即时反馈由
104
+ // toggleDisabled 自己改 slotMeta、随后 loadSlots 对账。
105
+ }
106
+ this.publish();
107
+ });
108
+ // 重构:scope 快照只作「无 HTTP 时的初值兜底」(typeof 守卫保证 yaml 零写入
109
+ // 时 undefined 不会覆盖;仅单测显式传值才生效)。凭据标志 tokenConfigured/sshConfigured
110
+ // 不再从快照取——公共 yaml 已零写入,snap 里恒缺省只会种出 false,统一由
111
+ // refreshAccount(/account-check 读凭据文件真源)与 loadSettingsFromHttp 刷新。
112
+ const snap0 = this.scope.getSnapshot();
113
+ if (snap0 && snap0.value) {
114
+ if (typeof snap0.value.auditEnabled === 'boolean') this.auditEnabled = snap0.value.auditEnabled;
115
+ if (typeof snap0.value.injectRequirements === 'boolean') this.injectRequirements = snap0.value.injectRequirements;
116
+ if (typeof snap0.value.injectSystemPrompt === 'boolean') this.injectSystemPrompt = snap0.value.injectSystemPrompt;
117
+ if (typeof snap0.value.auditScanScope === 'string') this.auditScanScope = snap0.value.auditScanScope;
118
+ const wo0 = String(snap0.value.weightOverrides || '');
119
+ if (wo0.trim()) { try { this.weightValues = JSON.parse(wo0) || {}; } catch { /* 忽略 */ } }
120
+ }
121
+ // 若 loadSlots 尚未返回,先用已发现的槽位做占位显示(不含 private/template)
122
+ if (!this.ruleOrder.length && Object.keys(this.slotMeta).length) {
123
+ this.ruleOrder = Object.keys(this.slotMeta).filter((s) => s !== 'private' && s !== 'template');
124
+ }
125
+ // 改走统一刷新入口(一次调用刷设置与槽位;账号仍按需在页面 mount 时刷)
126
+ void this.refresh(['settings', 'slots']);
127
+ // 账号状态改由「首次打开账号信息页」时(dshgp_AccountTab 的 mount effect)
128
+ // 触发 refreshAccount,避免构造阶段与页面打开重复拉取;此处不再自动刷新。
129
+ // 设置持久化走 HTTP 读宿主 scope(绕开 client isLoopback=memory 陷阱——
130
+ // 反代访问时 scope 快照恒 unavailable,从宿主侧读已落盘设置,重启后开关保持勾选)
131
+ // 该读取已并入上方 this.refresh(['settings','slots']),此处不再重复请求。
132
+ }
133
+ project() {
134
+ // 恒可用/恒可写:数据与写入全走 HTTP(settings-get/settings-set/account-check/rule-slots),
135
+ // client scope 快照只作初值兜底(见构造处注释)。宿主按 isLoopback 决定 scope 的
136
+ // persistence——反代/非 loopback 访问时恒 memory 模式、status 恒 unavailable、
137
+ // writable 恒 false(isLoopback=memory 陷阱)。若仍以快照判 available,设置侧边栏
138
+ // 在反代访问下会整页空白(SectionPage return null)且输入框全禁用,故绕开快照判定。
139
+ return {
140
+ available: true,
141
+ writable: true,
142
+ text: this.text,
143
+ sshPub: this.sshPub,
144
+ sshEmail: this.sshEmail,
145
+ auditEnabled: this.auditEnabled,
146
+ injectRequirements: this.injectRequirements,
147
+ injectSystemPrompt: this.injectSystemPrompt,
148
+ auditScanScope: this.auditScanScope,
149
+ ruleOrder: this.ruleOrder,
150
+ slotMeta: this.slotMeta,
151
+ weightValues: this.weightValues,
152
+ // 补齐:审计进阶 / 推送默认值状态镜像(供 UI 渲染)
153
+ maxScanFiles: this.maxScanFiles,
154
+ pushMethod: this.pushMethod,
155
+ pushGate: this.pushGate, // 推送门禁(开启后 push 需显式放行)
156
+ // defaultScanRoot/commitMessage 状态镜像移除(设置已删除)
157
+ tokenConfigured: this.tokenConfigured,
158
+ sshConfigured: this.sshConfigured,
159
+ // 凭据有效性快照(account-check → account-status.json 的 token/ssh 分项),
160
+ // 供账号卡片渲染各自 ✅有效/❌无效 徽标 + 登录名。
161
+ tokenStatus: this.tokenStatus,
162
+ sshStatus: this.sshStatus,
163
+ accountBlock: this.accountBlock,
164
+ accountLoggedIn: this.accountLoggedIn,
165
+ accountLoading: this.accountLoading,
166
+ npmAccountBlock: this.npmAccountBlock,
167
+ npmAccountLoggedIn: this.npmAccountLoggedIn,
168
+ npmAccountLoading: this.npmAccountLoading,
169
+ npmAccountUser: this.npmAccountUser,
170
+ npmConfigured: this.npmConfigured,
171
+ npmOwned: this.npmOwned,
172
+ npmOwnedLoading: this.npmOwnedLoading,
173
+ npmOwnedError: this.npmOwnedError,
174
+ npmInstallBusy: this.npmInstallBusy,
175
+ npmInstallResult: this.npmInstallResult,
176
+ npmInstallDialog: this.npmInstallDialog,
177
+ npmInstallProgress: this.npmInstallProgress,
178
+ slotLoading: this.slotLoading,
179
+ slotError: this.slotError,
180
+ refreshError: this.refreshError, // 统一刷新入口的部分级错误
181
+ statusMsg: this.statusMsg,
182
+ genKeying: this.genKeying,
183
+ genKeyError: this.genKeyError,
184
+ localPath: this.localPath,
185
+ localRepos: this.localRepos,
186
+ localLoading: this.localLoading,
187
+ localScanning: this.localScanning, // 独立进程扫描中(按钮禁用)
188
+ localMsg: this.localMsg,
189
+ cloudRepos: this.cloudRepos,
190
+ cloudLoading: this.cloudLoading,
191
+ cloudMsg: this.cloudMsg,
192
+ repoBusy: this.repoBusy,
193
+ cloneProgress: this.cloneProgress,
194
+ clonePreview: this.clonePreview,
195
+ cloneHistory: this.cloneHistory,
196
+ visConfirm: this.visConfirm,
197
+ maxCloneFileMB: this.maxCloneFileMB,
198
+ cloneConcurrency: this.cloneConcurrency,
199
+ repoFeedback: this.repoFeedback,
200
+ dirty: this.text.trim().length > 0 || this.sshPub.trim().length > 0,
201
+ saving: this.saving,
202
+ failed: this.failed,
203
+ savedMsg: this.savedMsg,
204
+ };
205
+ }
206
+ flashSaved(msg) {
207
+ this.savedMsg = String(msg || '');
208
+ if (this.savedTimer) clearTimeout(this.savedTimer);
209
+ this.savedTimer = setTimeout(() => {
210
+ this.savedMsg = '';
211
+ this.publish();
212
+ }, dshgp_SAVED_MSG_MS);
213
+ this.publish();
214
+ }
215
+ publish() { this.store.set(this.project()); }
216
+
217
+ /**
218
+ * 从宿主读已落盘设置(/settings-get,host scope.get 快照)。
219
+ * 背景:非 loopback 访问(反代)时 client settingsScope 恒 unavailable(memory 模式),
220
+ * 插件直读 scope 拿不到任何已保存值 → 打开设置页时开关全回默认(现象:重启后勾选丢失,
221
+ * 需重新打开)。host 侧 scope 才是真源,经 HTTP 读回后覆盖前端字段、保持勾选状态。
222
+ * 追加:**用户已编辑过的键跳过**(this.editedKeys)——本请求是异步的,
223
+ * 若用户在响应回来前点了开关,GET 返回的是 host 旧值,直接覆盖会把刚点的勾选弹回。
224
+ */
225
+ /**
226
+ * 统一刷新入口:**一个函数 + 一个参数**控制刷新设置侧边栏的哪部分,
227
+ * 取代此前散落在多个 useEffect / 按钮回调里各自 fetch 的写法。
228
+ *
229
+ * @param {string|string[]} [parts='all'] 要刷新的部分,可传单个字符串、数组、或 'all':
230
+ * · 'settings' —— 设置(/settings-get 读宿主 scope 已落盘值,覆盖前端字段)
231
+ * · 'account' —— 账号信息(/account-status 离线读凭据真源 + 徽标)
232
+ * · 'repos' —— 本地仓库列表(/repos-local 读 dsh-repo-index.json;可配 path/rebuild)
233
+ * · 'cloud' —— 云端仓库列表(/repos-cloud 走 token 列账号名下仓库)
234
+ * · 'slots' —— 规则槽位(/rule-slots 动态发现 yml + 统计)
235
+ * · 'all' —— 以上全部(默认)
236
+ * @param {object} [opts]
237
+ * · path —— 仅 'repos' 用:扫描根路径(空=沿用上次)
238
+ * · rebuild —— 仅 'repos' 用:true 先离线重建索引再读回
239
+ * · silent —— true 时不置 loading 态(用于后台静默刷新,避免界面闪烁)
240
+ * @returns {Promise<void>}
241
+ *
242
+ * 用法:
243
+ * await this.refresh(); // 全部刷新
244
+ * await this.refresh('account'); // 只刷账号信息
245
+ * await this.refresh(['settings','slots']); // 只刷设置与槽位
246
+ * await this.refresh('repos', { rebuild: true }); // 重建索引后刷本地列表
247
+ */
248
+ async refresh(parts = 'all', opts = {}) {
249
+ const PARTS = ['settings', 'account', 'npm', 'repos', 'cloud', 'slots'];
250
+ let list;
251
+ if (parts === 'all' || parts === undefined || parts === null) list = PARTS.slice();
252
+ else list = (Array.isArray(parts) ? parts : [parts])
253
+ .map((p) => String(p || '').trim().toLowerCase())
254
+ .filter((p) => PARTS.includes(p));
255
+ if (!list.length) return;
256
+
257
+ // 顺序执行而非并行:repos 依赖索引、account 影响徽标,串行可保证先后关系稳定,
258
+ // 也避免多个请求同时 publish 造成界面连续重排。
259
+ for (const p of list) {
260
+ try {
261
+ if (p === 'settings') await this.loadSettingsFromHttp();
262
+ else if (p === 'account') await this.refreshAccount({ silent: opts.silent });
263
+ else if (p === 'npm') {
264
+ // npm 与 GitHub 同构:先读离线账号态,再拉账号名下的包列表(未登录时列表给可读提示)
265
+ await this.refreshNpmAccount({ silent: opts.silent });
266
+ await this.loadNpmOwned({ silent: opts.silent });
267
+ }
268
+ else if (p === 'repos') await this.scanLocalRepos(opts.path, opts.rebuild, { silent: opts.silent });
269
+ else if (p === 'cloud') await this.loadCloudRepos({ silent: opts.silent });
270
+ else if (p === 'slots') await this.loadSlots({ silent: opts.silent });
271
+ } catch (e) {
272
+ // 单个部分失败不影响其余部分:记录到统一错误位,继续刷下一个
273
+ this.refreshError = `${p}: ` + (e && e.message || e);
274
+ }
275
+ }
276
+ // 克隆改为后台 job 后,任务不再随 HTTP 请求存活——
277
+ // 刷新/重开页面时后端可能仍在下载。这里主动探一次,把「正在跑的克隆」
278
+ // 重新接回进度条与轮询,避免用户以为任务没了而重复发起(会被互斥拒绝)。
279
+ void this.resumeCloneIfRunning();
280
+ }
281
+
282
+ /**
283
+ * 页面加载/刷新后接续**仍在后台跑的克隆**(克隆后台化配套)。
284
+ *
285
+ * 只在 idle/done 之外做动作:running → 恢复进度条并重启轮询;
286
+ * done → 如实回显终态(说明上次任务已结束);idle → 什么都不做。
287
+ */
288
+ async resumeCloneIfRunning() {
289
+ if (this.repoBusy) return; // 已有交互在进行(含本页面自己发起的 clone),不抢
290
+ let st;
291
+ try {
292
+ st = await dshgp_postJson('/api/git-push/clone-progress', {});
293
+ } catch { return; /* 探测失败静默:下次刷新再试 */ }
294
+ if (!st || st.state !== 'running' || !st.progress) return;
295
+ const p = st.progress;
296
+ this.cloneProgress = p;
297
+ this.repoBusy = dshgp_BUSY_CLONE + (p.target || '');
298
+ this.cloudMsg = '⏳ 后台克隆进行中:' + (p.target || '') + ' → ' + (p.dest || '');
299
+ this.publish();
300
+ // 重启轮询直到终态(与 cloneConfirmed 同一收敛逻辑,故此处只做等待)
301
+ if (this._cloneResumeTimer) clearInterval(this._cloneResumeTimer);
302
+ this._cloneResumeTimer = setInterval(async () => {
303
+ try {
304
+ const s2 = await dshgp_postJson('/api/git-push/clone-progress', {});
305
+ if (s2 && s2.state === 'running' && s2.progress) {
306
+ this.cloneProgress = s2.progress;
307
+ this.publish();
308
+ return;
309
+ }
310
+ if (s2 && s2.state === 'done') {
311
+ const fin = await dshgp_postJson('/api/git-push/clone-progress', { consume: true });
312
+ const res = (fin && fin.result) || (s2 && s2.result) || null;
313
+ this.cloudMsg = res && res.ok
314
+ ? '✅ 已克隆 ' + (p.target || '') + ' → ' + (res.dest || p.dest || '')
315
+ : '❌ ' + ((res && res.error) || '克隆失败');
316
+ } else if (s2 && s2.state === 'idle') {
317
+ this.cloudMsg = '⚠️ 克隆任务已不存在(可能插件进程重启过),请重新发起';
318
+ } else {
319
+ return; // 未知态:继续轮询,不误判
320
+ }
321
+ clearInterval(this._cloneResumeTimer);
322
+ this._cloneResumeTimer = null;
323
+ this.cloneProgress = null;
324
+ this.repoBusy = '';
325
+ this.publish();
326
+ } catch { /* 轮询失败不中断 */ }
327
+ }, 1000);
328
+ }
329
+
330
+ async loadSettingsFromHttp() {
331
+ try {
332
+ const settingsRes = await dshgp_getJson('/api/git-push/settings-get');
333
+ if (!settingsRes || !settingsRes.ok || !settingsRes.settings) return;
334
+ const v = settingsRes.settings;
335
+ if (typeof v.auditEnabled === 'boolean' && !this.editedKeys.has('auditEnabled')) this.auditEnabled = v.auditEnabled;
336
+ if (typeof v.injectRequirements === 'boolean' && !this.editedKeys.has('injectRequirements')) this.injectRequirements = v.injectRequirements;
337
+ if (typeof v.injectSystemPrompt === 'boolean' && !this.editedKeys.has('injectSystemPrompt')) this.injectSystemPrompt = v.injectSystemPrompt;
338
+ if (typeof v.auditScanScope === 'string' && !this.editedKeys.has('auditScanScope')) this.auditScanScope = v.auditScanScope;
339
+ // 补齐回读:新增 UI 的 7 键(advanced),重启后从 config.json 恢复勾选/取值
340
+ if (typeof v.maxScanFiles === 'number' && !this.editedKeys.has('maxScanFiles')) this.maxScanFiles = v.maxScanFiles;
341
+ if (typeof v.maxCloneFileMB === 'number' && !this.editedKeys.has('maxCloneFileMB')) this.maxCloneFileMB = v.maxCloneFileMB;
342
+ if (typeof v.cloneConcurrency === 'number' && !this.editedKeys.has('cloneConcurrency')) this.cloneConcurrency = v.cloneConcurrency;
343
+ if (typeof v.pushMethod === 'string' && !this.editedKeys.has('pushMethod')) this.pushMethod = v.pushMethod;
344
+ // 补漏:pushGate(推送门禁)此前**不在回读列表**——构造函数默认 false,
345
+ // 打开/刷新设置页时不被宿主真值覆盖,界面永远显示未勾选(实测:勾了门禁、重开页面又变未勾选)。
346
+ if (typeof v.pushGate === 'boolean' && !this.editedKeys.has('pushGate')) this.pushGate = v.pushGate;
347
+ // defaultScanRoot/commitMessage 不再作为设置键回读(已在 UI/白名单移除)
348
+ if (typeof v.weightOverrides === 'string' && v.weightOverrides.trim() && !this.editedKeys.has('weightOverrides')) {
349
+ try { this.weightValues = JSON.parse(v.weightOverrides) || {}; } catch { /* 忽略 */ }
350
+ }
351
+ // 凭据布尔位不受编辑守卫影响:只读派生标记,无回弹风险
352
+ if (typeof v.tokenConfigured === 'boolean') this.tokenConfigured = v.tokenConfigured;
353
+ if (typeof v.sshConfigured === 'boolean') this.sshConfigured = v.sshConfigured;
354
+ this.publish();
355
+ } catch (_e) { /* 端点不可用/未注册时沿用 scope 兜底 */ }
356
+ }
357
+
358
+ /** 加载规则包清单(/rule-slots,动态发现 yml)。 */
359
+ // 重构:原 loadCredentialFlags(/status 只刷 tokenConfigured)删除——
360
+ // 凭据标志统一由 refreshAccount(/account-check,读凭据文件真源)刷新,避免第三条链路打架。
361
+ async loadSlots({ silent = false } = {}) {
362
+ if (!silent) { this.slotLoading = true; }
363
+ this.slotError = '';
364
+ this.publish();
365
+ try {
366
+ const slotsRes = await dshgp_getJson('/api/git-push/rule-slots');
367
+ if (slotsRes && slotsRes.ok && slotsRes.slots) {
368
+ const meta = slotsRes.slots.meta || {};
369
+ // 用后端返回的生效顺序;private 恒末尾
370
+ const list = Array.isArray(slotsRes.slots.order) ? slotsRes.slots.order : [];
371
+ const order = list.filter((s) => s !== 'template');
372
+ const forced = Array.isArray(slotsRes.slots.forced) ? slotsRes.slots.forced : [];
373
+ this.slotMeta = meta;
374
+ this.ruleOrder = order;
375
+ if (forced.includes('private') && !this.ruleOrder.includes('private')) this.ruleOrder.push('private');
376
+ } else {
377
+ this.slotError = (slotsRes && slotsRes.message) || '规则包加载失败';
378
+ }
379
+ } catch (e) {
380
+ this.slotError = '规则包加载失败: ' + (e && e.message || e);
381
+ }
382
+ this.slotLoading = false;
383
+ this.publish();
384
+ }
385
+
386
+ /** 离线读 npm 账号态(/npm-account,秒级不联网);与 refreshAccount 完全同构。 */
387
+ async refreshNpmAccount({ silent = false } = {}) {
388
+ if (!silent) { this.npmAccountLoading = true; }
389
+ this.publish();
390
+ try {
391
+ const res = await dshgp_getJson('/api/git-push/npm-account');
392
+ this.npmAccountBlock = (res && res.block) || '(无 npm 账号记录,点「刷新」在线校验)';
393
+ this.npmAccountLoggedIn = !!(res && res.loggedIn);
394
+ this.npmAccountUser = (res && res.user) || '';
395
+ this.npmConfigured = !!(res && res.configured);
396
+ } catch (e) {
397
+ this.npmAccountBlock = '读取失败: ' + ((e && e.message) || e);
398
+ this.npmAccountLoggedIn = false;
399
+ this.npmAccountUser = '';
400
+ }
401
+ this.npmAccountLoading = false;
402
+ this.publish();
403
+ }
404
+
405
+ /** 在线校验 npm 登录态并写快照(/npm-check);与 recheckAccount 完全同构。 */
406
+ async recheckNpmAccount() {
407
+ if (this.npmAccountLoading) return;
408
+ this.npmAccountLoading = true;
409
+ this.publish();
410
+ try {
411
+ const res = await dshgp_postJson('/api/git-push/npm-check', {});
412
+ if (res && res.block) this.npmAccountBlock = res.block;
413
+ this.npmAccountLoggedIn = !!(res && res.loggedIn);
414
+ this.npmAccountUser = (res && res.user) || '';
415
+ this.npmConfigured = !!(res && res.configured);
416
+ } catch (e) {
417
+ this.npmAccountBlock = '⏳ 在线校验失败(网络超时或未配置),可稍后重试:' + ((e && e.message) || e);
418
+ this.npmAccountLoggedIn = false;
419
+ }
420
+ this.npmAccountLoading = false;
421
+ this.publish();
422
+ // 校验成功后顺带刷新「账号名下的包」列表(与 GitHub push 后重读云端列表同一节奏)
423
+ if (this.npmAccountLoggedIn) await this.loadNpmOwned({ silent: true });
424
+ }
425
+
426
+ /** 安装流程第一段(入口):点列表行「安装」⇒ 弹选择(目录 / 全局),与 GitHub 克隆同款入口。 */
427
+ openInstallFlow(pkg) {
428
+ const name = String(pkg || '').trim();
429
+ if (!name) return;
430
+ this.npmInstallDialog = { name };
431
+ this.npmInstallResult = null;
432
+ this.publish();
433
+ }
434
+
435
+ /** 取消选择对话框。 */
436
+ cancelInstallDialog() {
437
+ this.npmInstallDialog = null;
438
+ this.publish();
439
+ }
440
+
441
+ /** 选择段①:打开目录选择器(与 clone 同款 dshgp_browseOpen(input, onPick)),选完即开始安装。 */
442
+ chooseInstallDir() {
443
+ const name = (this.npmInstallDialog && this.npmInstallDialog.name) || '';
444
+ if (!name) return;
445
+ if (typeof dshgp_browseOpen !== 'function') {
446
+ this.npmInstallResult = { ok: false, error: '目录选择器不可用' };
447
+ this.npmInstallDialog = null;
448
+ this.publish();
449
+ return;
450
+ }
451
+ dshgp_browseOpen(null, (picked) => { void this.startInstallTo({ name, dir: String(picked || '') }); });
452
+ }
453
+
454
+ /** 选择段②:确认全局安装(-g,会影响宿主 node 环境)。 */
455
+ confirmInstallGlobal() {
456
+ const name = (this.npmInstallDialog && this.npmInstallDialog.name) || '';
457
+ if (!name) return;
458
+ void this.startInstallTo({ name, global: true });
459
+ }
460
+
461
+ /** 起安装(异步)+ 开始轮询进度;启动失败直接落回执。 */
462
+ async startInstallTo({ name = '', dir = '', global = false } = {}) {
463
+ const pkg = String(name || '').trim();
464
+ if (!pkg) return;
465
+ this.npmInstallDialog = null;
466
+ this.npmInstallBusy = pkg;
467
+ this.npmInstallProgress = { state: 'running', name: pkg, lines: [], startedAt: Date.now() };
468
+ this.publish();
469
+ try {
470
+ const res = await dshgp_postJson('/api/git-push/npm-install', {
471
+ names: [pkg], dest: global ? '' : dir, global, ignoreScripts: true, confirm: true, async: true,
472
+ });
473
+ if (!res || res.ok === false || res.started !== true) {
474
+ this.npmInstallResult = res || { ok: false, error: '启动安装失败' };
475
+ this.npmInstallBusy = '';
476
+ this.npmInstallProgress = null;
477
+ this.publish();
478
+ return;
479
+ }
480
+ this.pollInstallProgress();
481
+ } catch (e) {
482
+ this.npmInstallResult = { ok: false, error: String((e && e.message) || e) };
483
+ this.npmInstallBusy = '';
484
+ this.npmInstallProgress = null;
485
+ }
486
+ this.publish();
487
+ }
488
+
489
+ /** 进度段:轮询 /npm-install-progress(对应 clone 的轮询),终态取回执并清表。 */
490
+ pollInstallProgress() {
491
+ if (this.npmInstallTimer) return;
492
+ const tick = async () => {
493
+ try {
494
+ const st = await dshgp_postJson('/api/git-push/npm-install-progress', {});
495
+ const p = st && st.progress;
496
+ if (!p) return;
497
+ this.npmInstallProgress = p;
498
+ if (p.state !== 'running') {
499
+ this.clearInstallTimer();
500
+ this.npmInstallBusy = '';
501
+ this.npmInstallResult = {
502
+ ok: p.state === 'done', state: p.state, tail: p.tail || '',
503
+ lines: p.lines || [], logPath: p.logPath || '', error: p.error || '',
504
+ };
505
+ await this.loadNpmOwned({ silent: true }); // 安装后同源刷新(与 clone 完成后重读同一节奏)
506
+ await this.refresh('repos');
507
+ }
508
+ this.publish();
509
+ } catch { /* 单次轮询失败不致命,下一拍重试 */ }
510
+ };
511
+ this.npmInstallTimer = setInterval(() => { void tick(); }, 1200);
512
+ void tick();
513
+ }
514
+
515
+ /** 清理进度轮询定时器(终态必须调,防定时器泄漏)。 */
516
+ clearInstallTimer() {
517
+ if (this.npmInstallTimer) {
518
+ clearInterval(this.npmInstallTimer);
519
+ this.npmInstallTimer = null;
520
+ }
521
+ }
522
+
523
+ /**
524
+ * 安装一个包(/npm-install)。二次确认由 UI 负责;此处固定安全默认:
525
+ * 默认不执行安装脚本(ignoreScripts)、默认非全局(除非 UI 显式传 global:true)。
526
+ * 失败不抛错,回执写进 npmInstallResult 供 UI 展示(含日志路径)。
527
+ */
528
+ async installNpmPackage({ name = '', dest = '', global = false, ignoreScripts = true } = {}) {
529
+ const pkg = String(name || '').trim();
530
+ if (!pkg || this.npmInstallBusy) return;
531
+ this.npmInstallBusy = pkg;
532
+ this.publish();
533
+ try {
534
+ const res = await dshgp_postJson('/api/git-push/npm-install', {
535
+ names: [pkg], dest: String(dest || ''), global: !!global, ignoreScripts: !!ignoreScripts, confirm: true,
536
+ }, 320000);
537
+ this.npmInstallResult = res || null;
538
+ // 包安装到工作区依赖后,本地面板同源重读(与 GitHub push 后重读云端列表同一节奏)
539
+ if (res && res.ok) await this.refresh('repos');
540
+ } catch (e) {
541
+ this.npmInstallResult = { ok: false, error: String((e && e.message) || e) };
542
+ }
543
+ this.npmInstallBusy = '';
544
+ this.publish();
545
+ }
546
+
547
+ /** 拉取登录账号名下的包(/npm-owned);未登录或失败 ⇒ 空列表 + 可读提示(不抛错)。 */
548
+ async loadNpmOwned({ silent = false } = {}) {
549
+ if (!silent) { this.npmOwnedLoading = true; this.publish(); }
550
+ try {
551
+ const res = await dshgp_getJson('/api/git-push/npm-owned');
552
+ this.npmOwned = (res && Array.isArray(res.results)) ? res.results : [];
553
+ this.npmOwnedError = (res && res.error) || '';
554
+ } catch (e) {
555
+ this.npmOwned = [];
556
+ this.npmOwnedError = String((e && e.message) || e);
557
+ }
558
+ this.npmOwnedLoading = false;
559
+ this.publish();
560
+ }
561
+
562
+ /** 刷新账号信息(/account-check,读凭据文件真源;同时刷新凭据徽标)。 */
563
+ /** 离线读账号状态(秒级,不触发任何网络):读 account-status.json 快照 + 凭据文件。
564
+ * 插件启动 / push 后重读 / 账号卡片渲染全用它。「重新检测」才走在线(recheckAccount)。 */
565
+ async refreshAccount({ silent = false } = {}) {
566
+ if (!silent) { this.accountLoading = true; }
567
+ this.publish();
568
+ try {
569
+ const accountRes = await dshgp_getJson('/api/git-push/account-status');
570
+ this.accountBlock = (accountRes && accountRes.block) || '(无账号状态记录,点击「重新检测」在线校验)';
571
+ this.accountLoggedIn = !!(accountRes && accountRes.loggedIn);
572
+ this.tokenConfigured = !!(accountRes && accountRes.tokenConfigured);
573
+ this.sshConfigured = !!(accountRes && accountRes.sshConfigured);
574
+ this.tokenStatus = (accountRes && accountRes.tokenStatus) || null;
575
+ this.sshStatus = (accountRes && accountRes.sshStatus) || null;
576
+ this.apiQuota = (accountRes && accountRes.apiQuota) || null;
577
+ } catch (e) {
578
+ this.accountBlock = '读取失败: ' + (e && e.message || e);
579
+ this.accountLoggedIn = false;
580
+ }
581
+ this.accountLoading = false;
582
+ this.publish();
583
+ // token 配额刷新(异步、不阻塞凭据显示):查 /api-quota(后端写回快照)→ 按
584
+ // statusUpdated 标志重读 account-status,使凭据块 Token 行出现「(配额剩余 N/h)」。
585
+ // 查询本身失败不影响凭据展示;落盘失败由 quotaError 记录(不再静默)。
586
+ this.refreshApiQuota();
587
+ }
588
+
589
+ // 刷新 token 的 GitHub API 配额(异步):查 /api/git-push/api-quota → 按收口标志重读快照。
590
+ // 后端 60 秒缓存 + 进行中防抖,避免打开设置页时反复打 GitHub。
591
+ // 收口约定:后端写 account-status 成功后回 statusUpdated=true;命中缓存回 cached=true
592
+ // (表示此前已落盘)——只有这两种情况才重读 account-status(不再无条件拉)。
593
+ // 写失败回 statusError 时如实记到 quotaError,同时仍用本次返回值渲染(配额是增强信息,
594
+ // 不因落盘失败就不显示,但也不再静默吞掉失败原因)。
595
+ async refreshApiQuota() {
596
+ if (this.quotaLoading) return;
597
+ this.quotaLoading = true;
598
+ try {
599
+ const quotaResp = await dshgp_getJson('/api/git-push/api-quota');
600
+ if (quotaResp && quotaResp.ok) {
601
+ // 本次响应就是最新配额(落盘失败也照常展示)
602
+ this.apiQuota = { core: quotaResp.core, search: quotaResp.search, graphql: quotaResp.graphql, codeSearch: quotaResp.codeSearch, checkedAt: quotaResp.fetchedAt };
603
+ this.quotaError = quotaResp.statusError ? String(quotaResp.statusError) : '';
604
+ if (quotaResp.statusUpdated || quotaResp.cached) {
605
+ const res = await dshgp_getJson('/api/git-push/account-status');
606
+ if (res && res.block) this.accountBlock = res.block;
607
+ }
608
+ this.publish();
609
+ }
610
+ } catch { /* 配额查询失败静默(凭据块仍正常显示) */ }
611
+ this.quotaLoading = false;
612
+ }
613
+
614
+ /** 「重新检测」:在线校验 token/SSH → 写 account-status.json → 再离线读回最新。
615
+ * 仅手动点按钮触发(在线有网络耗时 1~4s),读取端仍走离线 refreshAccount。 */
616
+ async recheckAccount() {
617
+ // 防抖:连点会连发在线请求(GitHub /user 有速率限制),
618
+ // 触发限流后反而更容易超时,表现为「点了没反应」。进行中直接忽略重复点击。
619
+ if (this.accountLoading) return;
620
+ this.accountLoading = true;
621
+ this.publish();
622
+ try {
623
+ const res = await dshgp_postJson('/api/git-push/account-check', { checkSsh: true, confirm: false });
624
+ // 超时 ≠ 失效:网络没测成时如实说明可重试,不写成「检测失败」吓人
625
+ const ts = (res && res.tokenStatus) || {};
626
+ const ss = (res && res.sshStatus) || {};
627
+ if (!ts.valid && ts.timeout) {
628
+ this.accountBlock = '⏳ 在线校验未完成(网络超时,可稍后重试);SSH 状态:' + (ss.valid ? '✅ 可用' : '未验证');
629
+ }
630
+ } catch (e) {
631
+ this.accountBlock = '在线检测失败: ' + (e && e.message || e);
632
+ }
633
+ await this.refreshAccount(); // 离线读回在线校验落盘的 json
634
+ }
635
+
636
+ /** 扫描本地仓库(列表只从 dsh-repo-index.json 读取)。
637
+ * rebuild=true:**离线重建索引**(扫描本地 .git,author 与离线账号 json 一致的登记,
638
+ * 含本地新增,全程不联网)后再读回;缺省:直接读索引返回(不复扫、不联网)。 */
639
+ async scanLocalRepos(path, rebuild, { silent = false } = {}) {
640
+ if (!silent) { this.localLoading = true; }
641
+ this.localMsg = '';
642
+ this.publish();
643
+ try {
644
+ const p = String(path || '').trim();
645
+ dshgp_localSet('dshgp-scan-path', p);
646
+ const qs = '?rebuild=' + (rebuild ? '1' : '0') + (p ? '&path=' + encodeURIComponent(p) : '');
647
+ const localRes = await dshgp_getJson('/api/git-push/repos-local' + qs);
648
+ if (localRes && localRes.ok) {
649
+ this.localPath = localRes.root || p;
650
+ this.localRepos = Array.isArray(localRes.repos) ? localRes.repos : [];
651
+ this.localMsg = this.localRepos.length
652
+ ? (rebuild ? '已重建索引,读取到 ' : '读取到 ') + this.localRepos.length + ' 个仓库(' + (localRes.root || '') + ')'
653
+ : '索引中没有本账号仓库: ' + (localRes.root || '');
654
+ } else {
655
+ this.localRepos = [];
656
+ this.localMsg = '❌ ' + ((localRes && localRes.error) || '读取失败');
657
+ }
658
+ } catch (e) {
659
+ this.localRepos = [];
660
+ this.localMsg = '❌ 读取失败: ' + (e && e.message || e);
661
+ }
662
+ this.localLoading = false;
663
+ this.publish();
664
+ // 读取/扫描收尾后**自动补查未知远端状态**——列表里 liveSkipped(本地列表预算/
665
+ // 熔断导致 SSH 探测跳过)的仓库,串行向后端补查(SSH 真源),结果追加写回索引,
666
+ // 同时刷新本地列表的远端状态(remoteHead/ahead/behind/remoteHeadAt/synced)。
667
+ void this.refreshUnknownRemote();
668
+ }
669
+
670
+ /** 自动补查 liveSkipped(未知远端状态)仓库:串行走 /repos-local-refresh,更新列表条目。 */
671
+ async refreshUnknownRemote() {
672
+ if (this.refreshingRemote) return; // 防重入
673
+ const skips = (this.localRepos || []).filter((r) => r.liveSkipped === true && r.path);
674
+ if (!skips.length) return;
675
+ this.refreshingRemote = true;
676
+ try {
677
+ const body = { repos: skips.map((r) => ({ name: r.name, path: r.path, branch: r.branch || '' })) };
678
+ const res = await dshgp_postJson('/api/git-push/repos-local-refresh', body);
679
+ const refreshed = (res && Array.isArray(res.refreshed)) ? res.refreshed : [];
680
+ if (refreshed.length) {
681
+ // 把补查结果合并进本地列表(按 name 匹配)
682
+ const byName = new Map(refreshed.filter((r) => r.ok).map((r) => [r.name, r.remoteState || {}]));
683
+ if (byName.size) {
684
+ this.localRepos = (this.localRepos || []).map((r) => {
685
+ const st = byName.get(r.name);
686
+ if (!st) return r;
687
+ return Object.assign({}, r, {
688
+ remoteHead: st.remoteHead ?? r.remoteHead,
689
+ ahead: st.ahead ?? r.ahead,
690
+ behind: st.behind ?? r.behind,
691
+ remoteHeadAt: st.remoteHeadAt ?? r.remoteHeadAt,
692
+ synced: st.synced ?? r.synced,
693
+ liveSkipped: false, // 补查完成,不再是未知
694
+ });
695
+ });
696
+ this.publish();
697
+ }
698
+ }
699
+ } catch { /* 补查失败静默(下次读取再补) */ }
700
+ this.refreshingRemote = false;
701
+ }
702
+
703
+ /** 手动「扫描」= 独立进程后台离线扫描 + 只读新增 diff。
704
+ * 流程:① POST repos-local-scan 让后端 spawn 独立进程(扫描中按钮禁用,不可重复点);
705
+ * ② 循环 POST repos-local-scan-wait 等待「有新仓库」(非轮询,文件变化才唤醒);
706
+ * ③ 每次只把新增仓库**追加**进列表(不全量重读),直到扫描 done;
707
+ * ④ done 后恢复按钮,最后按索引读一次对齐(收尾)。 */
708
+ async startScan(path) {
709
+ if (this.localScanning) return; // 扫描中不可重复点
710
+ const p = String(path || '').trim();
711
+ dshgp_localSet('dshgp-scan-path', p);
712
+ this.localScanning = true;
713
+ this.localMsg = '⏳ 扫描中…(后台独立进程,扫到一个追加一个)';
714
+ this.publish();
715
+ let seen = this.localRepos.length;
716
+ try {
717
+ const started = await dshgp_postJson('/api/git-push/repos-local-scan', { path: p });
718
+ if (started && started.running && started.ok === false) {
719
+ this.localMsg = '⚠️ ' + (started.error || '扫描进行中,不能重复扫描');
720
+ return;
721
+ }
722
+ // 循环等待新增:每次 wait 挂起直到独立进程写了新进度(非轮询)
723
+ for (let i = 0; i < dshgp_SCAN_WAIT_MAX_ROUNDS; i += 1) {
724
+ const waitRes = await dshgp_postJson('/api/git-push/repos-local-scan-wait', { from: seen });
725
+ const newest = (waitRes && waitRes.newest) || [];
726
+ if (newest.length) {
727
+ // 只追加新增:从索引取这几条详情(不全量重读列表)
728
+ await this.appendScannedRepos(newest);
729
+ seen += newest.length;
730
+ this.localMsg = '⏳ 扫描中… 已发现 ' + seen + ' 个仓库';
731
+ this.publish();
732
+ }
733
+ if (waitRes && waitRes.done) break;
734
+ if (!waitRes || waitRes.running === false) break;
735
+ }
736
+ } catch (e) {
737
+ this.localMsg = '❌ 扫描失败: ' + (e && e.message || e);
738
+ }
739
+ this.localScanning = false;
740
+ // 收尾:按索引读一次对齐(保证领先/落后等字段完整)
741
+ await this.scanLocalRepos(p, false);
742
+ this.localMsg = '✅ 扫描完成,读取到 ' + this.localRepos.length + ' 个仓库';
743
+ this.publish();
744
+ }
745
+
746
+ /** 只把「新增仓库名」对应的条目追加进列表(增量,不全量重建)。 */
747
+ async appendScannedRepos(names) {
748
+ try {
749
+ const indexRes = await dshgp_getJson('/api/git-push/repos-local');
750
+ const all = (indexRes && Array.isArray(indexRes.repos)) ? indexRes.repos : [];
751
+ const have = new Set(this.localRepos.map((r) => r.name));
752
+ for (const n of names) {
753
+ if (have.has(n)) continue;
754
+ const hit = all.find((r) => r.name === n);
755
+ if (hit) { this.localRepos = this.localRepos.concat([hit]); have.add(n); }
756
+ }
757
+ } catch { /* 读取失败保留已追加 */ }
758
+ }
759
+
760
+ /** 拉取云端仓库列表(/repos-cloud,token 列账号名下仓库)。 */
761
+ async loadCloudRepos({ silent = false } = {}) {
762
+ if (!silent) { this.cloudLoading = true; }
763
+ this.cloudMsg = '';
764
+ this.publish();
765
+ try {
766
+ const cloudRes = await dshgp_getJson('/api/git-push/repos-cloud');
767
+ if (cloudRes && cloudRes.ok) {
768
+ this.cloudRepos = Array.isArray(cloudRes.repos) ? cloudRes.repos : [];
769
+ // 云端扫描同时写索引(后端 mergeCloudReposIntoIndex),提示已刷新条数
770
+ const idxHint = cloudRes.indexUpdated ? ',索引已刷新 ' + cloudRes.indexUpdated + ' 条' : '';
771
+ this.cloudMsg = '共 ' + this.cloudRepos.length + ' 个仓库(按最近更新排序)' + idxHint;
772
+ // 云端获取后**重新读索引刷新本地列表**——后端已把云端仓库(含
773
+ // defaultBranch/pushedAt/visibility 云端真源)写进 dsh-repo-index.json,
774
+ // 侧边栏本地面板的远端状态(默认分支/云端更新/仅云端标记)随之更新。
775
+ void this.scanLocalRepos(this.localPath, false);
776
+ } else {
777
+ this.cloudRepos = [];
778
+ this.cloudMsg = '❌ ' + ((data && data.error) || '拉取失败');
779
+ }
780
+ } catch (e) {
781
+ this.cloudRepos = [];
782
+ this.cloudMsg = '❌ 拉取失败: ' + (e && e.message || e);
783
+ }
784
+ this.cloudLoading = false;
785
+ this.publish();
786
+ }
787
+
788
+ /** 本地仓库手动 push(领先 + 工作树干净才允许,后端校验)。 */
789
+ async pushLocalRepo(path) {
790
+ this.repoBusy = dshgp_BUSY_PUSH + path;
791
+ this.publish();
792
+ let ok = false;
793
+ let msg = '';
794
+ try {
795
+ const pushRes = await dshgp_postJson('/api/git-push/repo-push', { path, confirm: true });
796
+ ok = !!(pushRes && pushRes.ok);
797
+ if (ok) {
798
+ msg = '✅ 推送成功 ' + path;
799
+ } else {
800
+ // 显示详细错误信息(含 ahead/behind)
801
+ const err = (pushRes && (pushRes.error || (pushRes.push && pushRes.push.reason))) || '推送失败';
802
+ const extra = [];
803
+ if (pushRes && pushRes.ahead > 0) extra.push('领先 ' + pushRes.ahead);
804
+ if (pushRes && pushRes.behind > 0) extra.push('落后 ' + pushRes.behind);
805
+ msg = '⚠️ ' + err + (extra.length ? '(' + extra.join(',') + ')' : '');
806
+ }
807
+ this.localMsg = msg;
808
+ } catch (e) {
809
+ msg = '❌ 推送失败: ' + (e && e.message || e);
810
+ this.localMsg = msg;
811
+ }
812
+ // push 反馈:行内绿/红醒目提示(成功/失败)
813
+ this.repoFeedback = Object.assign({}, this.repoFeedback, { [path]: { ok, msg } });
814
+ this.repoBusy = '';
815
+ // 推送后自动刷新——本地仓库索引(后端维护 + 前列回读)与账号状态
816
+ // (推送到云端后凭据有效性/登录关系可能变化,一并刷新)。
817
+ void this.scanLocalRepos(this.localPath); // 刷新领先/落后状态
818
+ if (ok) void this.refresh('account'); // push 后刷新账号信息
819
+ this.publish();
820
+ }
821
+
822
+ /** 本地仓库手动 commit(只提交不推送)——复用提交推送的本地提交审计。
823
+ * 弹窗输入 commit message → POST /repo-commit → commitWithAudit(push:false)。
824
+ * 精简返回:blocker → 「审计拦截」;warning → 附警告数;成功 → 「已提交 sha」。
825
+ * @param {string} path 仓库绝对路径
826
+ */
827
+ async commitLocalRepo(path) {
828
+ const message = window.prompt('输入 commit message(本地提交;审计门禁通过才提交):', '');
829
+ if (message === null || !String(message).trim()) return; // 用户取消
830
+ this.repoBusy = 'commit:' + path;
831
+ this.publish();
832
+ let ok = false;
833
+ let msg = '';
834
+ try {
835
+ const res = await dshgp_postJson('/api/git-push/repo-commit', { path, message: String(message).trim(), confirm: true });
836
+ // post 封装返回 {data, msg...} 或直出 body;data.ok 为准
837
+ const resp = (res && res.ok !== undefined) ? res : (res && res.data ? res.data : res);
838
+ if (resp && resp.ok) {
839
+ ok = true;
840
+ const warnCount = resp.warningCount || 0;
841
+ msg = '✅ 已提交' + (resp.commitSha ? ' ' + resp.commitSha : '') + (warnCount ? '(⚠️ ' + warnCount + ' 条 warning,见审计)' : '');
842
+ } else if (resp && resp.blocked) {
843
+ const list = (resp.blockers && resp.blockers.length ? resp.blockers.slice(0, 2).join(';') : (resp.error || '审计拦截'));
844
+ msg = '🚫 审计拦截:' + list;
845
+ } else {
846
+ msg = '⚠️ ' + (resp && resp.error ? resp.error : '提交失败');
847
+ }
848
+ this.localMsg = msg;
849
+ } catch (e) {
850
+ msg = '❌ 提交失败: ' + (e && e.message || e);
851
+ this.localMsg = msg;
852
+ }
853
+ this.repoFeedback = Object.assign({}, this.repoFeedback, { [path]: { ok, msg } });
854
+ this.repoBusy = '';
855
+ void this.scanLocalRepos(this.localPath); // 提交后未提交数变化,刷新列表
856
+ this.publish();
857
+ }
858
+
859
+ /**
860
+ * 1.5.4:请求切换可见性——只记录待确认目标并弹**独立确认面板**(不直接调用后端)。
861
+ * 真正切由 confirmVisSwitch 在用户点了「确认切换」后执行。
862
+ * @param {string} fullName owner/repo
863
+ * @param {string} target public | private
864
+ */
865
+ requestVisSwitch(fullName, target) {
866
+ if (this.repoBusy) return; // 已有交互(clone/push/切换)进行中,不弹
867
+ const cur = this.cloudRepos.find((x) => String(x.fullName || '') === fullName);
868
+ this.visConfirm = { fullName, target, cur: cur && cur.private ? 'private' : 'public' };
869
+ this.publish();
870
+ }
871
+
872
+ /** 1.5.4:弹窗「确认切换」——按 visConfirm 记录执行切换,结束后关闭面板。 */
873
+ async confirmVisSwitch() {
874
+ const v = this.visConfirm;
875
+ if (!v) return { ok: false, error: '无待确认的切换' };
876
+ const res = await this.switchVisibility(v.fullName, v.target);
877
+ this.visConfirm = null;
878
+ this.publish();
879
+ return res;
880
+ }
881
+
882
+ /** 1.5.4:弹窗「取消 / 关闭」——丢弃待确认目标。 */
883
+ cancelVisSwitch() {
884
+ if (this.visConfirm) {
885
+ this.visConfirm = null;
886
+ this.publish();
887
+ }
888
+ }
889
+
890
+ /**
891
+ * 云端仓库私有/公开切换:POST repo-visibility(confirm 前置后端校验)。
892
+ * 成功后就地更新列表该项(云端真源返回值)。
893
+ * @param {string} fullName owner/repo
894
+ * @param {string} target public | private
895
+ * @returns {Promise<object>} 后端响应({ok, visibility} 或 {ok:false, error})
896
+ */
897
+ async switchVisibility(fullName, target) {
898
+ const parts = String(fullName || '').split('/');
899
+ const owner = (parts[0] || '').trim();
900
+ const repo = (parts[1] || '').trim();
901
+ if (!owner || !repo) return { ok: false, error: '仓库名格式应为 owner/repo' };
902
+ this.repoBusy = dshgp_BUSY_VIS + fullName;
903
+ this.publish();
904
+ let res;
905
+ try {
906
+ res = await dshgp_postJson('/api/git-push/repo-visibility', { owner, repo, visibility: target, confirm: true });
907
+ } catch (e) {
908
+ res = { ok: false, error: (e && e.message) || '请求失败' };
909
+ }
910
+ this.repoBusy = '';
911
+ if (res && res.ok) {
912
+ // 就地更新列表该项(新数组引用触发订阅重渲染)
913
+ const arr = Array.isArray(this.cloudRepos) ? this.cloudRepos.slice() : [];
914
+ for (const repo of arr) {
915
+ if (String(repo.fullName || '') === fullName) repo.private = res.visibility === 'private';
916
+ }
917
+ this.cloudRepos = arr;
918
+ this.cloudMsg = '✅ 已切换为' + (res.visibility === 'private' ? '私有' : '公开') + ':' + fullName;
919
+ } else {
920
+ this.cloudMsg = '❌ 切换失败:' + ((res && res.error) || '未知错误') + '(' + fullName + ')';
921
+ }
922
+ this.publish();
923
+ return res;
924
+ }
925
+
926
+ /** 云端仓库 clone:先弹目录选择器选目标目录,再预览,确认后才真正开始。 */
927
+ cloneFlow(repo) {
928
+ dshgp_browseOpen(null, (dir) => { void this.cloneCloudRepo(repo, dir); });
929
+ }
930
+
931
+ /**
932
+ * 第一步:预览(不下载任何文件)。
933
+ *
934
+ * 此前点 clone 直接开下:用户既不知道总量(无从判断要等多久),也不知道
935
+ * 体积守卫会跳过哪些文件。改为先预览、再确认。
936
+ */
937
+ async cloneCloudRepo(repo, dir) {
938
+ this.clonePending = { repo, dir };
939
+ this.cloudMsg = '正在读取仓库信息…';
940
+ this.repoBusy = dshgp_BUSY_CLONE + repo;
941
+ this.publish();
942
+ try {
943
+ // 把目标目录一并交给后端:后端据此回报 partial(「已存在且不完整」= 有进行中标记且无有效提交),
944
+ // 前端才能在确认框里提示「续传 / 重来」。不传 dir 时 partial 恒为 false(后端不猜目录)。
945
+ const pv = await dshgp_postJson('/api/git-push/clone-preview', { target: repo, dir });
946
+ if (pv && pv.ok) {
947
+ this.cloudMsg = '';
948
+ this.clonePreview = pv;
949
+ } else {
950
+ this.cloudMsg = '❌ ' + ((pv && pv.error) || '预览失败');
951
+ this.clonePending = null;
952
+ }
953
+ } catch (e) {
954
+ this.cloudMsg = '❌ 预览失败: ' + (e && e.message || e);
955
+ this.clonePending = null;
956
+ }
957
+ this.repoBusy = '';
958
+ this.publish();
959
+ }
960
+
961
+ /** 第二步:点「开始克隆」后真正下载,并轮询进度直到结束。 */
962
+ /**
963
+ * 取消 clone 预览确认框(点「取消」)。
964
+ *
965
+ * 只清预览态与待办态,不做任何远端/磁盘操作——此时尚未开始下载。
966
+ * 放在 Controller 而非组件里,是为了让「取消」也能顺带清 clonePending,
967
+ * 否则残留的 clonePending 会让「确认其它仓库」拿到上一次的目标目录。
968
+ */
969
+ cancelPreview() {
970
+ this.clonePreview = null;
971
+ this.clonePending = null;
972
+ this.publish();
973
+ }
974
+
975
+ async cloneConfirmed(restart = false) {
976
+ const pend = this.clonePending;
977
+ if (!pend) return;
978
+ this.clonePreview = null;
979
+ const { repo, dir } = pend;
980
+ this.repoBusy = dshgp_BUSY_CLONE + repo;
981
+ this.publish();
982
+ // 克隆改为**后台 job**——repo-clone 立即返回 202 {async:true, jobId},
983
+ // 下载在后端继续跑。故此处不再 await 整个克隆,而是:
984
+ // ① 提交任务(拿 jobId;预检/互斥失败会同步回错,照实显示)
985
+ // ② 轮询 /clone-progress 驱动进度,直到 state 变 done 取终态
986
+ // 判「卡死」仍看进度是否停滞(大文件慢传不该被杀),不用绝对超时。
987
+ let pollTimer = null;
988
+ const stopPoll = () => { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } };
989
+ // 终态收敛:把后端 cloneJobStatus() 的 done.result 转成用户文案。
990
+ // 成败与成因仍由后端结构化给出(clone.js 的 cause/retriable),前端不猜文案。
991
+ const renderResult = (res) => {
992
+ if (res && res.ok) {
993
+ // 如实报告被跳过的文件:否则用户以为克隆完整
994
+ const skipped = res.skippedCount || 0;
995
+ this.cloudMsg = '✅ 已克隆 ' + repo + ' → ' + (res.dest || dir)
996
+ + (skipped > 0 ? '(已跳过 ' + skipped + ' 个超大文件)' : '');
997
+ } else {
998
+ const msg = (res && res.error) || '克隆失败';
999
+ const extra = res && res.cleaned && res.retriable === true
1000
+ ? '(半成品已自动清理,可直接重试)'
1001
+ : '';
1002
+ this.cloudMsg = '❌ ' + msg + extra;
1003
+ }
1004
+ };
1005
+ // 轮询:① 更新进度条 ② 检测终态(running → done)后收尾。
1006
+ // consume=true 让后端取走终态,避免下次打开面板读到上次结果。
1007
+ const poll = async () => {
1008
+ try {
1009
+ const st = await dshgp_postJson('/api/git-push/clone-progress', {});
1010
+ if (st && st.state === 'running' && st.progress) {
1011
+ this.cloneProgress = st.progress;
1012
+ this.publish();
1013
+ } else if (st && st.state === 'done') {
1014
+ // 任务已结束:先取终态再 consume 清掉(顺序反了会读到空)
1015
+ const fin = await dshgp_postJson('/api/git-push/clone-progress', { consume: true });
1016
+ stopPoll();
1017
+ renderResult(fin && fin.result ? fin.result : (st.result || null));
1018
+ this.cloneProgress = null;
1019
+ this.clonePending = null;
1020
+ this.repoBusy = '';
1021
+ this.publish();
1022
+ } else if (st && st.state === 'idle') {
1023
+ // 既非 running 也非 done:任务已消失(进程重启等)——不能永远转圈
1024
+ stopPoll();
1025
+ this.cloudMsg = '⚠️ 克隆任务已不存在(可能插件进程重启过),请重新发起';
1026
+ this.cloneProgress = null;
1027
+ this.clonePending = null;
1028
+ this.repoBusy = '';
1029
+ this.publish();
1030
+ }
1031
+ } catch { /* 轮询失败不中断克隆本身 */ }
1032
+ };
1033
+ pollTimer = setInterval(() => { void poll(); }, 1000);
1034
+ void poll();
1035
+ try {
1036
+ // 提交即返回(很快);超时不必再放到 30 分钟——提交本身不下载。
1037
+ // SUBMIT_TIMEOUT_MS 是「提交请求」的超时(不是下载超时):提交只建后台任务,
1038
+ // 故远小于下载/轮询类超时;提取为命名常量以免被当作裸魔数。
1039
+ const SUBMIT_TIMEOUT_MS = 60_000;
1040
+ // history:勾选框的值(null=未表态则不传字段,跟随后端默认 true;取消勾选 ⇒ 显式传 false 退回整树快照)
1041
+ const submit = await dshgp_postJson('/api/git-push/repo-clone', { target: repo, dir, confirm: true, history: this.cloneHistory === false ? false : true, restart: restart === true }, SUBMIT_TIMEOUT_MS);
1042
+ if (submit && submit.async === true) {
1043
+ // 已转后台:进度与终态交给轮询,这里只提示「已开始」
1044
+ this.cloudMsg = '⏳ 克隆已在后台运行:' + repo + ' → ' + (submit.dest || dir);
1045
+ this.publish();
1046
+ } else {
1047
+ // 未转后台 = 提交阶段就失败(预检/互斥/参数)——同步回错,照实显示并收尾。
1048
+ // 兼容后端降级为同步返回(老版本/未来改动)的情形。
1049
+ stopPoll();
1050
+ renderResult(submit);
1051
+ this.cloneProgress = null;
1052
+ this.clonePending = null;
1053
+ this.repoBusy = '';
1054
+ this.publish();
1055
+ }
1056
+ } catch (e) {
1057
+ stopPoll();
1058
+ this.cloudMsg = '❌ 克隆失败: ' + (e && e.message || e) + '(可直接重试——半成品已自动清理)';
1059
+ this.cloneProgress = null;
1060
+ this.clonePending = null;
1061
+ this.repoBusy = '';
1062
+ this.publish();
1063
+ }
1064
+ }
1065
+
1066
+ /** 单击规则包行:切换禁用/启用(改为写 yml 顶层 disabled,不存 scope 变量)。 */
1067
+ async toggleDisabled(slot) {
1068
+ if (slot === 'nodejs' || slot === 'private') {
1069
+ this.setStatus('⚠️ nodejs/private 安全红线槽位不可禁用');
1070
+ return;
1071
+ }
1072
+ const meta = (this.slotMeta && this.slotMeta[slot]) || {};
1073
+ const nowDisabled = !!(meta.disabled);
1074
+ // 即时反馈:先本地翻转(行绿/红 + 顶部提示),不等后端响应
1075
+ this.slotMeta = { ...(this.slotMeta || {}), [slot]: { ...meta, disabled: !nowDisabled } };
1076
+ this.setStatus(!nowDisabled ? '✅ 已禁用 ' + slot + '(该槽位规则不再加载)' : '✅ 已启用 ' + slot);
1077
+ this.publish();
1078
+ try {
1079
+ const toggleRes = await dshgp_postJson('/api/git-push/toggle-rule', { slot, disabled: !nowDisabled });
1080
+ if (toggleRes && toggleRes.ok) {
1081
+ void this.loadSlots(); // 后台重载对账(yml 解析结果)
1082
+ } else {
1083
+ this.setStatus('❌ 切换失败:' + ((toggleRes && toggleRes.error) || '未知错误'));
1084
+ this.loadSlots();
1085
+ }
1086
+ } catch (e) {
1087
+ this.setStatus('❌ 切换失败:' + (e && e.message || e));
1088
+ void this.loadSlots(); // 恢复 yml 真实状态
1089
+ }
1090
+ }
1091
+
1092
+ /** 审计 tab 顶部即时反馈(区别于设置 tab 的 flashSaved)。 */