dsh-config-manager 0.8.2 → 0.9.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.
Files changed (345) hide show
  1. package/lib/adapters/mcp.js +42 -13
  2. package/lib/adapters/messages.d.ts +1 -0
  3. package/lib/adapters/messages.js +2 -0
  4. package/lib/adapters/patch-key-guard.d.ts +23 -0
  5. package/lib/adapters/patch-key-guard.js +13 -0
  6. package/lib/adapters/plugin-data.d.ts +19 -5
  7. package/lib/adapters/plugin-data.js +76 -22
  8. package/lib/adapters/plugins.d.ts +14 -1
  9. package/lib/adapters/plugins.js +147 -4
  10. package/lib/cli/actions.d.ts +7 -105
  11. package/lib/cli/actions.js +16 -172
  12. package/lib/cli/control-state.d.ts +54 -0
  13. package/lib/cli/control-state.js +107 -0
  14. package/lib/cli/index.js +14 -0
  15. package/lib/cli/write-gates.d.ts +61 -0
  16. package/lib/cli/write-gates.js +110 -0
  17. package/lib/client.d.ts +104 -49
  18. package/lib/client.js +12536 -12006
  19. package/lib/core/backup.d.ts +0 -4
  20. package/lib/core/backup.js +21 -4
  21. package/lib/core/boot-rescue.d.ts +1 -1
  22. package/lib/core/boot-rescue.js +12 -1
  23. package/lib/core/boot-safety.js +37 -2
  24. package/lib/core/conflict-decisions.js +2 -1
  25. package/lib/core/exporter.js +22 -1
  26. package/lib/core/journal.d.ts +54 -4
  27. package/lib/core/journal.js +158 -35
  28. package/lib/core/local-plugin-host.d.ts +29 -0
  29. package/lib/core/local-plugin-host.js +55 -48
  30. package/lib/core/messages.d.ts +7 -0
  31. package/lib/core/messages.js +14 -0
  32. package/lib/core/migration-history.js +16 -9
  33. package/lib/core/model-tools.d.ts +2 -2
  34. package/lib/core/model-tools.js +14 -2
  35. package/lib/core/patch-secret-guard.d.ts +49 -0
  36. package/lib/core/patch-secret-guard.js +164 -0
  37. package/lib/core/reconcile.d.ts +8 -0
  38. package/lib/core/reconcile.js +18 -3
  39. package/lib/core/reinstall.d.ts +2 -0
  40. package/lib/core/reinstall.js +6 -2
  41. package/lib/core/restore.js +31 -6
  42. package/lib/core/section-sanitize.d.ts +32 -0
  43. package/lib/core/section-sanitize.js +13 -0
  44. package/lib/core/snapshot-diff.d.ts +30 -0
  45. package/lib/core/snapshot-diff.js +56 -20
  46. package/lib/core/startup-barrier.js +8 -2
  47. package/lib/core/types.d.ts +22 -0
  48. package/lib/core/update-check.js +51 -2
  49. package/lib/foreign/kernel.js +9 -2
  50. package/lib/foreign/read-claude-plugins.js +29 -11
  51. package/lib/foreign/read-dsh.js +31 -2
  52. package/lib/foreign/session-ir.js +50 -9
  53. package/lib/foreign/session-read.d.ts +8 -0
  54. package/lib/foreign/session-read.js +26 -0
  55. package/lib/index.d.ts +1 -1
  56. package/lib/index.js +1 -1
  57. package/lib/profiles/dsh-profile-io.d.ts +20 -0
  58. package/lib/profiles/dsh-profile-io.js +27 -0
  59. package/lib/profiles/dsh-profile-manager.d.ts +27 -0
  60. package/lib/profiles/dsh-profile-manager.js +45 -4
  61. package/lib/profiles/dsh-profile-runtime.d.ts +5 -1
  62. package/lib/profiles/dsh-profile-runtime.js +16 -3
  63. package/lib/profiles/process-control.d.ts +18 -1
  64. package/lib/profiles/process-control.js +25 -1
  65. package/lib/routes/profiles.js +2 -1
  66. package/lib/routes/sync.js +13 -1
  67. package/lib/schema/types.d.ts +11 -0
  68. package/lib/security/redaction.js +22 -6
  69. package/lib/sync/autosync-repeat.d.ts +27 -0
  70. package/lib/sync/autosync-repeat.js +23 -0
  71. package/lib/sync/autosync-scheduler.d.ts +34 -1
  72. package/lib/sync/autosync-scheduler.js +151 -43
  73. package/lib/sync/baseline-heal.js +7 -0
  74. package/lib/sync/baseline-record.d.ts +67 -0
  75. package/lib/sync/baseline-record.js +74 -0
  76. package/lib/sync/blob-store.js +13 -0
  77. package/lib/sync/content-diff.d.ts +39 -0
  78. package/lib/sync/content-diff.js +46 -0
  79. package/lib/sync/git/git-transport.d.ts +32 -1
  80. package/lib/sync/git/git-transport.js +146 -26
  81. package/lib/sync/github-auth.d.ts +17 -1
  82. package/lib/sync/github-auth.js +37 -1
  83. package/lib/sync/merge-apply-plan.d.ts +38 -0
  84. package/lib/sync/merge-apply-plan.js +76 -0
  85. package/lib/sync/messages.d.ts +1 -0
  86. package/lib/sync/messages.js +2 -0
  87. package/lib/sync/pending-merge.d.ts +34 -0
  88. package/lib/sync/pending-merge.js +53 -0
  89. package/lib/sync/s3/s3-transport.d.ts +14 -2
  90. package/lib/sync/s3/s3-transport.js +72 -48
  91. package/lib/sync/sync-engine.d.ts +23 -40
  92. package/lib/sync/sync-engine.js +115 -132
  93. package/lib/sync/sync-history.d.ts +7 -0
  94. package/lib/sync/sync-state.d.ts +28 -0
  95. package/lib/sync/sync-state.js +20 -0
  96. package/lib/sync/transport.d.ts +12 -3
  97. package/lib/sync/transport.js +13 -4
  98. package/lib/sync/webdav/webdav-transport.d.ts +19 -2
  99. package/lib/sync/webdav/webdav-transport.js +81 -40
  100. package/lib/ui/commands.js +5 -11
  101. package/lib/ui/dsh-profiles-view.d.ts +8 -3
  102. package/lib/ui/dsh-profiles-view.js +9 -5
  103. package/lib/ui/i18n.d.ts +2 -1
  104. package/lib/ui/i18n.js +4 -2
  105. package/lib/ui/menu-placement.js +1 -1
  106. package/lib/ui/migration-consult-view.d.ts +11 -0
  107. package/lib/ui/migration-consult-view.js +15 -0
  108. package/lib/ui/overview-view.d.ts +7 -0
  109. package/lib/ui/overview-view.js +3 -0
  110. package/lib/ui/report.d.ts +9 -0
  111. package/lib/ui/report.js +17 -4
  112. package/lib/ui/selection-model.d.ts +8 -0
  113. package/lib/ui/selection-model.js +16 -0
  114. package/lib/utils/patch-yaml.d.ts +39 -1
  115. package/lib/utils/patch-yaml.js +82 -2
  116. package/lib/utils/paths.d.ts +13 -0
  117. package/lib/utils/paths.js +35 -0
  118. package/lib/utils/workdir-lock.js +18 -3
  119. package/package.json +2 -1
  120. package/src/adapters/mcp.test.ts +29 -0
  121. package/src/adapters/mcp.ts +43 -12
  122. package/src/adapters/messages.ts +2 -0
  123. package/src/adapters/patch-key-guard.ts +29 -0
  124. package/src/adapters/plugin-data.test.ts +126 -0
  125. package/src/adapters/plugin-data.ts +97 -26
  126. package/src/adapters/plugins.test.ts +288 -0
  127. package/src/adapters/plugins.ts +141 -4
  128. package/src/cli/actions.test.ts +74 -1
  129. package/src/cli/actions.ts +27 -246
  130. package/src/cli/control-state.ts +143 -0
  131. package/src/cli/index.ts +18 -0
  132. package/src/cli/web/web.test.ts +27 -0
  133. package/src/cli/write-gates.ts +149 -0
  134. package/src/client/about/AboutPanel.tsx +7 -6
  135. package/src/client/about/release-notes-view.test.ts +17 -0
  136. package/src/client/about/release-notes-view.ts +49 -24
  137. package/src/client/chat/ChatEntryView.tsx +2 -2
  138. package/src/client/chat/rollback-entry-view.ts +6 -1
  139. package/src/client/common/CommandPalette.tsx +6 -3
  140. package/src/client/common/ConfirmDialog.tsx +29 -12
  141. package/src/client/common/ContentPicker.tsx +13 -12
  142. package/src/client/common/Modal.tsx +12 -5
  143. package/src/client/common/MoreMenu.tsx +4 -1
  144. package/src/client/common/RunsCenter.tsx +103 -32
  145. package/src/client/common/Select.tsx +2 -2
  146. package/src/client/common/floating-bounds.ts +1 -1
  147. package/src/client/common/floating-units.test.ts +1 -2
  148. package/src/client/common/plan-text-redaction.test.ts +188 -3
  149. package/src/client/common/runs-center-guard.test.ts +60 -0
  150. package/src/client/common/runs-center-view.test.ts +128 -0
  151. package/src/client/common/runs-center-view.ts +96 -0
  152. package/src/client/common/section-title-action.test.ts +66 -0
  153. package/src/client/common/ui.tsx +93 -30
  154. package/src/client/config-manager.module.css +1507 -272
  155. package/src/client/consult/ConsultCard.tsx +7 -6
  156. package/src/client/environment/EnvironmentPanel.tsx +20 -21
  157. package/src/client/environment/maintenance/DiskUsageCard.tsx +65 -91
  158. package/src/client/environment/profiles-incomplete-ui.test.ts +8 -8
  159. package/src/client/export/ExportView.tsx +7 -16
  160. package/src/client/history/HistoryPanel.tsx +88 -28
  161. package/src/client/history/history-locales.ts +3 -3
  162. package/src/client/home/BackupScheduleCard.tsx +35 -30
  163. package/src/client/home/HomePanel.tsx +45 -10
  164. package/src/client/import/ConflictList.tsx +13 -13
  165. package/src/client/import/ForeignImportView.tsx +7 -6
  166. package/src/client/import/ImportWizardView.tsx +2 -3
  167. package/src/client/import/PathMappingForm.tsx +4 -4
  168. package/src/client/import/PathPickerDialog.tsx +2 -1
  169. package/src/client/import/import-wizard-steps.tsx +51 -39
  170. package/src/client/import/use-import-wizard-controller.test.ts +129 -0
  171. package/src/client/import/use-import-wizard-controller.ts +116 -22
  172. package/src/client/library/ArtifactRow.tsx +2 -2
  173. package/src/client/library/BackupInspectView.tsx +19 -15
  174. package/src/client/library/LibraryActions.tsx +56 -16
  175. package/src/client/library/LibraryPanel.tsx +7 -7
  176. package/src/client/library/RestorePlanView.tsx +13 -8
  177. package/src/client/locales/about.ts +0 -2
  178. package/src/client/locales/backup.ts +10 -12
  179. package/src/client/locales/common.ts +2 -0
  180. package/src/client/locales/export.ts +5 -12
  181. package/src/client/locales/foreign.ts +2 -2
  182. package/src/client/locales/import.ts +3 -2
  183. package/src/client/locales/overview.ts +4 -0
  184. package/src/client/locales/profiles.ts +32 -4
  185. package/src/client/locales/restore.ts +0 -2
  186. package/src/client/locales/sessions.ts +0 -2
  187. package/src/client/locales/shell.ts +2 -2
  188. package/src/client/market/MarketPanel.tsx +38 -20
  189. package/src/client/market/MyConfigsList.tsx +34 -32
  190. package/src/client/market/MyConfigsLoginCard.tsx +12 -15
  191. package/src/client/market/MyConfigsView.tsx +5 -5
  192. package/src/client/market/MyConfigsWizard.tsx +7 -12
  193. package/src/client/market/market-locales.ts +0 -6
  194. package/src/client/market/my-configs-split.test.ts +2 -1
  195. package/src/client/nav-menu-clip-guard.test.ts +52 -0
  196. package/src/client/recovery/IncompleteCopiesSection.tsx +1 -3
  197. package/src/client/recovery/RecoveryPanel.tsx +31 -16
  198. package/src/client/recovery/RollbackCard.tsx +58 -16
  199. package/src/client/recovery/RollbackFileChanges.tsx +40 -27
  200. package/src/client/recovery/SessionHealthCard.tsx +2 -2
  201. package/src/client/recovery/SessionHealthDialog.tsx +5 -7
  202. package/src/client/recovery/SessionLayoutSection.tsx +3 -5
  203. package/src/client/recovery/recovery-locales.ts +12 -8
  204. package/src/client/run-store.test.ts +30 -0
  205. package/src/client/run-store.ts +21 -1
  206. package/src/client/sync/AddChannelCard.tsx +65 -0
  207. package/src/client/sync/AutosyncCard.tsx +182 -108
  208. package/src/client/sync/ChannelClearConfirmDialog.tsx +5 -1
  209. package/src/client/sync/ChannelConfigDialog.tsx +27 -48
  210. package/src/client/sync/MergePreviewView.tsx +3 -5
  211. package/src/client/sync/PushReportSections.tsx +35 -0
  212. package/src/client/sync/SyncChannelEntryCard.tsx +33 -24
  213. package/src/client/sync/SyncConfirmView.tsx +3 -3
  214. package/src/client/sync/SyncLogList.tsx +16 -5
  215. package/src/client/sync/SyncPanel.tsx +153 -159
  216. package/src/client/sync/SyncProbeRow.tsx +5 -7
  217. package/src/client/sync/SyncRepositoryPicker.tsx +17 -4
  218. package/src/client/sync/SyncSecuritySection.tsx +157 -0
  219. package/src/client/sync/SyncSettingsDialog.tsx +304 -0
  220. package/src/client/sync/SyncSettingsView.test.ts +26 -8
  221. package/src/client/sync/WorkDirCard.tsx +2 -4
  222. package/src/client/sync/config-clear-guard.test.ts +94 -0
  223. package/src/client/sync/config-clear-guard.ts +98 -0
  224. package/src/client/sync/config-dirty.test.ts +91 -0
  225. package/src/client/sync/config-dirty.ts +88 -0
  226. package/src/client/sync/history-model.test.ts +2 -0
  227. package/src/client/sync/history-model.ts +3 -0
  228. package/src/client/sync/merge-request.ts +20 -0
  229. package/src/client/sync/sync-api.ts +12 -0
  230. package/src/client/sync/sync-locales.ts +87 -47
  231. package/src/client/sync/sync-panel-clear.test.ts +44 -0
  232. package/src/client/sync/sync-view.test.ts +20 -0
  233. package/src/client/sync/sync-view.ts +42 -4
  234. package/src/core/backup.test.ts +61 -1
  235. package/src/core/backup.ts +21 -4
  236. package/src/core/boot-rescue.test.ts +35 -0
  237. package/src/core/boot-rescue.ts +13 -2
  238. package/src/core/boot-safety.test.ts +25 -0
  239. package/src/core/boot-safety.ts +37 -2
  240. package/src/core/conflict-decisions.ts +2 -1
  241. package/src/core/exporter.ts +21 -1
  242. package/src/core/journal.test.ts +183 -0
  243. package/src/core/journal.ts +163 -25
  244. package/src/core/local-plugin-host.test.ts +68 -2
  245. package/src/core/local-plugin-host.ts +31 -4
  246. package/src/core/messages.ts +14 -0
  247. package/src/core/migration-history.test.ts +27 -0
  248. package/src/core/migration-history.ts +12 -4
  249. package/src/core/model-tools.test.ts +67 -0
  250. package/src/core/model-tools.ts +16 -4
  251. package/src/core/patch-secret-guard.test.ts +110 -0
  252. package/src/core/patch-secret-guard.ts +176 -0
  253. package/src/core/reconcile.ts +32 -4
  254. package/src/core/reinstall.ts +8 -2
  255. package/src/core/restore.ts +32 -7
  256. package/src/core/section-sanitize.ts +37 -0
  257. package/src/core/snapshot-diff.test.ts +73 -1
  258. package/src/core/snapshot-diff.ts +66 -21
  259. package/src/core/startup-barrier.test.ts +64 -0
  260. package/src/core/startup-barrier.ts +8 -2
  261. package/src/core/types.ts +27 -1
  262. package/src/core/update-check.test.ts +40 -0
  263. package/src/core/update-check.ts +53 -2
  264. package/src/foreign/claude-code.test.ts +5 -0
  265. package/src/foreign/claude-plugins.test.ts +57 -0
  266. package/src/foreign/claude-sessions-bytes.test.ts +7 -1
  267. package/src/foreign/dsh.test.ts +23 -0
  268. package/src/foreign/kernel.ts +9 -2
  269. package/src/foreign/read-claude-plugins.ts +32 -11
  270. package/src/foreign/read-dsh.ts +33 -2
  271. package/src/foreign/session-ir.test.ts +67 -0
  272. package/src/foreign/session-ir.ts +54 -14
  273. package/src/foreign/session-read.ts +23 -0
  274. package/src/index.ts +1 -1
  275. package/src/profiles/dsh-profile-copy-rollback.test.ts +58 -4
  276. package/src/profiles/dsh-profile-io.ts +29 -0
  277. package/src/profiles/dsh-profile-manager.test.ts +30 -0
  278. package/src/profiles/dsh-profile-manager.ts +53 -5
  279. package/src/profiles/dsh-profile-runtime.test.ts +29 -7
  280. package/src/profiles/dsh-profile-runtime.ts +17 -3
  281. package/src/profiles/process-control.test.ts +97 -0
  282. package/src/profiles/process-control.ts +28 -1
  283. package/src/routes/profiles.ts +2 -1
  284. package/src/routes/sync.ts +13 -1
  285. package/src/schema/types.ts +16 -1
  286. package/src/security/redaction.test.ts +31 -0
  287. package/src/security/redaction.ts +23 -6
  288. package/src/sync/autosync-repeat.test.ts +58 -0
  289. package/src/sync/autosync-repeat.ts +55 -0
  290. package/src/sync/autosync-scheduler.test.ts +417 -0
  291. package/src/sync/autosync-scheduler.ts +154 -41
  292. package/src/sync/baseline-heal.ts +6 -0
  293. package/src/sync/baseline-record.ts +135 -0
  294. package/src/sync/blob-store.test.ts +16 -0
  295. package/src/sync/blob-store.ts +13 -0
  296. package/src/sync/content-diff.test.ts +95 -0
  297. package/src/sync/content-diff.ts +79 -0
  298. package/src/sync/git/git-transport.test.ts +151 -4
  299. package/src/sync/git/git-transport.ts +143 -27
  300. package/src/sync/github-auth.test.ts +26 -1
  301. package/src/sync/github-auth.ts +37 -1
  302. package/src/sync/merge-apply-plan.ts +117 -0
  303. package/src/sync/messages.ts +2 -0
  304. package/src/sync/pending-merge.ts +77 -0
  305. package/src/sync/s3/s3-delete-and-blob-index.test.ts +249 -0
  306. package/src/sync/s3/s3-transport.ts +76 -42
  307. package/src/sync/sync-config.test.ts +39 -12
  308. package/src/sync/sync-device-identity.test.ts +3 -0
  309. package/src/sync/sync-engine.test.ts +465 -12
  310. package/src/sync/sync-engine.ts +130 -135
  311. package/src/sync/sync-history.ts +7 -0
  312. package/src/sync/sync-state.ts +48 -0
  313. package/src/sync/transport.test.ts +13 -1
  314. package/src/sync/transport.ts +12 -4
  315. package/src/sync/webdav/webdav-delete-and-blob-index.test.ts +249 -0
  316. package/src/sync/webdav/webdav-transport.ts +86 -34
  317. package/src/ui/commands.test.ts +11 -0
  318. package/src/ui/commands.ts +5 -14
  319. package/src/ui/dsh-profiles-view.test.ts +16 -0
  320. package/src/ui/dsh-profiles-view.ts +11 -5
  321. package/src/ui/i18n.ts +4 -2
  322. package/src/ui/menu-placement.ts +1 -1
  323. package/src/ui/migration-consult-view.test.ts +20 -1
  324. package/src/ui/migration-consult-view.ts +17 -0
  325. package/src/ui/overview-view.ts +10 -0
  326. package/src/ui/report.test.ts +25 -1
  327. package/src/ui/report.ts +15 -4
  328. package/src/ui/selection-model.test.ts +15 -1
  329. package/src/ui/selection-model.ts +18 -0
  330. package/src/utils/js-yaml4.d.ts +35 -0
  331. package/src/utils/patch-yaml.test.ts +207 -1
  332. package/src/utils/patch-yaml.ts +98 -2
  333. package/src/utils/paths.test.ts +14 -1
  334. package/src/utils/paths.ts +35 -0
  335. package/src/utils/workdir-lock.test.ts +69 -0
  336. package/src/utils/workdir-lock.ts +17 -3
  337. package/lib/ui/path-mapping.d.ts +0 -38
  338. package/lib/ui/path-mapping.js +0 -75
  339. package/src/client/common/InfoHint.tsx +0 -289
  340. package/src/client/common/info-hint-guard.test.ts +0 -1119
  341. package/src/client/sync/DecryptPasswordCard.tsx +0 -48
  342. package/src/client/sync/SecurityOptionsCard.tsx +0 -97
  343. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -213
  344. package/src/ui/path-mapping.test.ts +0 -67
  345. package/src/ui/path-mapping.ts +0 -103
@@ -135,6 +135,75 @@ test('链上排队也计入超时:排在长任务后面的调用按时失败
135
135
  assert.equal(await slow, 'slow');
136
136
  });
137
137
 
138
+ test('fn 自身耗时不算等锁超时:拿到锁后跑多久都由调用方决定(审计 P12-1 回归)', async (t) => {
139
+ // 旧实现把 timeoutMs race 在整条链上:inspectWorkDir(lockTimeoutMs=1500 的只读自检)里的真实
140
+ // git 调用一超过 1.5 s 就被判「正被另一个同步任务占用」,文案撒谎、且隔离复跑必红。
141
+ // 新语义:timeoutMs 只约束「拿到锁」,拿到之后 fn 的耗时与锁无关。
142
+ const dir = await makeDir(t);
143
+ const t0 = Date.now();
144
+ const result = await withWorkdirLock(dir, async () => {
145
+ await new Promise((r) => setTimeout(r, 220));
146
+ return 'slow-ok';
147
+ }, { timeoutMs: 40 });
148
+ const elapsed = Date.now() - t0;
149
+ assert.equal(result, 'slow-ok', 'fn 超过 timeoutMs 仍必须返回结果,而不是伪造等锁冲突');
150
+ assert.ok(elapsed >= 200, '确实跑满了 fn 的耗时(实测 ' + String(elapsed) + 'ms)');
151
+ });
152
+
153
+ test('审计 P12-6(死线只约束等锁):无竞争 + fn 睡 200ms + timeoutMs 40ms ⇒ 成功返回', async (t) => {
154
+ // 审计条目:旧实现把 timeoutMs race 在**整条链**上(含 fn),于是一把没人竞争的锁 + 一个
155
+ // 合法慢任务(超过 timeoutMs)也会被判成「正被另一个任务占用」。这里钉住新语义:
156
+ // timeoutMs 只是「等锁预算」,拿到锁之后 fn 跑多久由调用方决定。
157
+ const dir = await makeDir(t);
158
+ const lockPath = workdirLockPath(dir);
159
+ // 预热(只为消除环境噪声,不放宽任何断言):withWorkdirLock 的**第一次**取锁会顺带触发
160
+ // 「一次性 tmpdir 清扫」——它读整个 %TEMP% 并逐条 stat,跟本次取锁抢 libuv 线程池;本机实测能把
161
+ // 无竞争的首次取锁拖到 125ms。40ms 的死线太窄,先把这两件一次性的事做掉,量的才是被测语义。
162
+ await pruneDeadWorkdirLocksOnce();
163
+ assert.equal(await withWorkdirLock(dir, async () => 'warm', { timeoutMs: 5_000 }), 'warm');
164
+ // 前提:确实没有竞争(无锁文件),否则本用例证明不了「无竞争 + 慢 fn」这一格
165
+ await assert.rejects(fs.access(lockPath), '前提:开始时不存在锁文件');
166
+
167
+ /**
168
+ * 旧语义的最小复刻(P12-1 修复前的形状):把死线与「等锁 + 执行」整体 race。
169
+ * 它只用同一对参数在内存里跑一遍,用来证明下面这条断言对旧实现**会红**,而不是空断言。
170
+ */
171
+ const legacyRaceWholeChain = async <T>(run: () => Promise<T>, timeoutMs: number): Promise<T> => {
172
+ let timer: ReturnType<typeof setTimeout> | undefined;
173
+ const deadline = new Promise<never>((_, reject) => {
174
+ timer = setTimeout(() => reject(new WorkdirLockError(dir, timeoutMs)), timeoutMs);
175
+ });
176
+ try {
177
+ return await Promise.race([run(), deadline]);
178
+ } finally {
179
+ if (timer !== undefined) clearTimeout(timer);
180
+ }
181
+ };
182
+ await assert.rejects(
183
+ legacyRaceWholeChain(async () => {
184
+ await new Promise((r) => setTimeout(r, 200));
185
+ return 'slow-ok';
186
+ }, 40),
187
+ (err: unknown) => err instanceof WorkdirLockError,
188
+ '旧语义(fn 计入预算)在同一对参数下必须失败 —— 否则本用例对它没有约束力',
189
+ );
190
+
191
+ // 现实现:同一对参数(200ms fn / 40ms timeoutMs),无竞争 ⇒ 必须成功返回 fn 的结果
192
+ const t0 = Date.now();
193
+ const result = await withWorkdirLock(dir, async () => {
194
+ await new Promise((r) => setTimeout(r, 200));
195
+ return 'slow-ok';
196
+ }, { timeoutMs: 40 });
197
+ const elapsed = Date.now() - t0;
198
+
199
+ assert.equal(result, 'slow-ok', 'fn 慢于 timeoutMs 也必须拿到结果,不得伪造等锁冲突');
200
+ assert.ok(elapsed >= 200, '确实跑满了 fn 的耗时(实测 ' + String(elapsed) + 'ms)');
201
+ assert.ok(elapsed < 3_000, '不得额外空等到别的上限(实测 ' + String(elapsed) + 'ms)');
202
+ // 收尾照旧:成功返回后锁必须释放,后续调用能立刻拿到
203
+ await assert.rejects(fs.access(lockPath), '成功路径同样要释放锁');
204
+ assert.equal(await withWorkdirLock(dir, async () => 'next', { timeoutMs: 40 }), 'next');
205
+ });
206
+
138
207
  test('异常也释放锁:fn 抛错后下一次仍能拿到锁(不会把后续同步永久卡死)', async (t) => {
139
208
  const dir = await makeDir(t);
140
209
  await assert.rejects(withWorkdirLock(dir, async () => { throw new Error('boom'); }), /boom/);
@@ -232,6 +232,15 @@ export async function withWorkdirLock<T>(
232
232
  // 上一个 300 s 的同步后面时,计时从轮到它那一刻才清零,超时上限形同失效(2026-10-27 现场)。
233
233
  const started = now();
234
234
 
235
+ /**
236
+ * 是否已经**拿到锁**(timeoutMs 只约束「等锁」,拿到之后 fn 自己的耗时不受它管)。
237
+ *
238
+ * 为什么必须分开(审计 P12-1 P1,真机 #104 复现):旧实现对整条链 race 一个 timeoutMs,
239
+ * 于是 `inspectWorkDir`(lockTimeoutMs=1500 的只读自检)里的真实 git 调用只要跑过 1.5 s,
240
+ * 就被判成「等锁超时」—— 错误文案说「正被另一个同步任务占用」,实际根本没有竞争;
241
+ * 单文件隔离复跑同样必红(30 s 处抛锁冲突)。等锁与干活是两件事,不能共用一个死线。
242
+ */
243
+ let acquired = false;
235
244
  const run = async (): Promise<T> => {
236
245
  // 排队期间调用方已超时放弃:轮到它时直接失败,**不执行 fn**,免得被遗弃的请求稍后仍去驱动工作副本
237
246
  if (now() - started >= timeoutMs) throw new WorkdirLockError(workDir, now() - started);
@@ -243,6 +252,7 @@ export async function withWorkdirLock<T>(
243
252
  await sleep(POLL_INTERVAL_MS);
244
253
  release = await tryAcquire(lockPath, workDir, staleMs, now);
245
254
  }
255
+ acquired = true;
246
256
  try {
247
257
  return await fn();
248
258
  } finally {
@@ -257,11 +267,15 @@ export async function withWorkdirLock<T>(
257
267
  chains.set(key, tail);
258
268
 
259
269
  // 硬上界:timeoutMs 是「拿到锁」的上限,不是「开始计时后」的上限。只用 run 内的计时不够 ——
260
- // 排在长任务后面的调用永远轮不到自己计时,界面就被历史任务拖着走。这里直接对链头 race,
261
- // 超时 reject;被放弃的 run 之后还会被链唤醒,但入口的过期检查让它立刻抛(不碰工作副本)。
270
+ // 排在长任务后面的调用永远轮不到自己计时,界面就被历史任务拖着走。这里对链头 race,超时 reject;
271
+ // 被放弃的 run 之后还会被链唤醒,但入口的过期检查让它立刻抛(不碰工作副本)。
272
+ // 关键:**拿到锁之后不再受这条死线约束**(见上面 acquired 的说明)。
262
273
  let rejectDeadline: ((reason: Error) => void) | undefined;
263
274
  const deadline = new Promise<never>((_, reject) => { rejectDeadline = reject; });
264
- const timer = setTimeout(() => { rejectDeadline?.(new WorkdirLockError(workDir, timeoutMs)); }, timeoutMs);
275
+ const timer = setTimeout(() => {
276
+ if (acquired) return;
277
+ rejectDeadline?.(new WorkdirLockError(workDir, timeoutMs));
278
+ }, timeoutMs);
265
279
  // unref:这个计时器不该拖住进程退出(缺省 300 s)
266
280
  if (typeof timer.unref === 'function') timer.unref();
267
281
  try {
@@ -1,38 +0,0 @@
1
- /**
2
- * 路径映射编辑器(规范 §12,m6-ui)。
3
- *
4
- * 两种形态(§12 批量映射优先):
5
- * - 单项映射:某条具体 PathIssue(如 workspace 绝对路径)→ 新路径;
6
- * - 批量前缀映射:oldPrefix → newPrefix,一次替换全部相关路径。
7
- *
8
- * 输出 core PathMapping[]:newPrefix 非空的映射才进入执行计划
9
- * (core mergePathMappings 只保留已解析映射;未解析项保留在 plan.items 供 UI 提示)。
10
- * 应用范围 appliesTo 缺省 [](全部相关分区),与 core applyMappingsToSections 语义一致。
11
- */
12
- import type { PathIssue, PathMapping } from '../core/types.ts';
13
- import type { PathMappingAppliesTo, PathMappingDraft } from './types.ts';
14
- export interface PathMappingEditorOptions {
15
- /** 从分析结果得到的路径问题 */
16
- issues?: PathIssue[];
17
- /** 预置映射(如上次导入可复用的映射) */
18
- existing?: PathMapping[];
19
- }
20
- export declare class PathMappingEditor {
21
- private readonly issues;
22
- private drafts;
23
- constructor(opts?: PathMappingEditorOptions);
24
- /** 全部草稿(含未解析) */
25
- get all(): PathMappingDraft[];
26
- /** 已解析(newPrefix 非空)的草稿 */
27
- get resolved(): PathMappingDraft[];
28
- /** 未解析的问题(UI 需提示用户选择文件夹;按「是否被已解析映射覆盖」判断,批量前缀映射一次覆盖多条) */
29
- get unresolved(): PathIssue[];
30
- /** 单项/批量设置映射(oldPrefix 已存在则更新;否则新建批量映射) */
31
- setMapping(oldPrefix: string, newPrefix: string, appliesTo?: PathMappingAppliesTo[]): void;
32
- /** 对某个具体值应用当前映射,返回替换结果(预览用;无映射则原样返回) */
33
- preview(value: string): string;
34
- /** 未解析项是否可进入执行(false = 有路径问题未解决) */
35
- get isComplete(): boolean;
36
- /** 输出 core PathMapping[](仅已解析项) */
37
- toPathMappings(): PathMapping[];
38
- }
@@ -1,75 +0,0 @@
1
- import { applyPrefixMappings } from '../utils/paths.js';
2
- export class PathMappingEditor {
3
- issues;
4
- drafts = new Map();
5
- constructor(opts = {}) {
6
- this.issues = opts.issues ?? [];
7
- for (const issue of this.issues) {
8
- this.drafts.set(issue.value, {
9
- oldPrefix: issue.value,
10
- newPrefix: issue.mappedTo ?? '',
11
- issue,
12
- appliesTo: [],
13
- });
14
- }
15
- // 批量映射按 oldPrefix 聚合(一个 oldPrefix 一条 draft)
16
- for (const m of opts.existing ?? []) {
17
- const prev = this.drafts.get(m.oldPrefix);
18
- this.drafts.set(m.oldPrefix, {
19
- oldPrefix: m.oldPrefix,
20
- newPrefix: m.newPrefix,
21
- appliesTo: [...m.appliesTo],
22
- });
23
- void prev;
24
- }
25
- }
26
- /** 全部草稿(含未解析) */
27
- get all() {
28
- return [...this.drafts.values()];
29
- }
30
- /** 已解析(newPrefix 非空)的草稿 */
31
- get resolved() {
32
- return this.all.filter((d) => d.newPrefix !== '');
33
- }
34
- /** 未解析的问题(UI 需提示用户选择文件夹;按「是否被已解析映射覆盖」判断,批量前缀映射一次覆盖多条) */
35
- get unresolved() {
36
- const mappings = this.toPathMappings();
37
- return (this.issues ?? []).filter((issue) => {
38
- const mapped = applyPrefixMappings(issue.value, mappings);
39
- return mapped === issue.value;
40
- });
41
- }
42
- /** 单项/批量设置映射(oldPrefix 已存在则更新;否则新建批量映射) */
43
- setMapping(oldPrefix, newPrefix, appliesTo = []) {
44
- const existing = this.drafts.get(oldPrefix);
45
- this.drafts.set(oldPrefix, {
46
- oldPrefix,
47
- newPrefix,
48
- appliesTo,
49
- issue: existing?.issue,
50
- });
51
- }
52
- /** 对某个具体值应用当前映射,返回替换结果(预览用;无映射则原样返回) */
53
- preview(value) {
54
- const resolved = this.resolved.map((d) => ({
55
- oldPrefix: d.oldPrefix,
56
- newPrefix: d.newPrefix,
57
- appliesTo: d.appliesTo,
58
- }));
59
- const mapped = applyPrefixMappings(value, resolved);
60
- return typeof mapped === 'string' ? mapped : value;
61
- }
62
- /** 未解析项是否可进入执行(false = 有路径问题未解决) */
63
- get isComplete() {
64
- return this.unresolved.length === 0;
65
- }
66
- /** 输出 core PathMapping[](仅已解析项) */
67
- toPathMappings() {
68
- return this.resolved.map((d) => ({
69
- oldPrefix: d.oldPrefix,
70
- newPrefix: d.newPrefix,
71
- appliesTo: d.appliesTo,
72
- }));
73
- }
74
- }
75
- //# sourceMappingURL=path-mapping.js.map
@@ -1,289 +0,0 @@
1
- /**
2
- * InfoHint —— 「说明性文案」的唯一承载体(ⓘ)。
3
- *
4
- * 分层规则(DESIGN.md §7「说明性文案分层」,逐字适用、不得自行扩大或缩小):
5
- * - **MOVE → ⓘ**:纯说明性文案(机制怎么工作 / 为什么这样设计 / 补充背景 / 边界与限制 /
6
- * 示例 / 省事提示)与输入规则类文案 —— 收进 `<InfoHint text={t('原键')} />`,删掉原来那行可见说明;
7
- * - **KEEP 常驻**:校验错误 / 失败原因、安全与不可逆操作告警、状态与等待文本、
8
- * 禁用原因(title=)、空态解释、防截断 title=、SectionTitle 副标题与 css.cellMeta、
9
- * ConfirmDialog/Modal 内的危险操作说明 —— 一律不动(渲染与文案逐字保持)。
10
- *
11
- * 交互四通道(缺一不可):
12
- * ① 鼠标悬停打开;② 键盘聚焦打开;③ 点击固定 / 再次点击取消固定;
13
- * ④ **固定态下按下任意位置(触发按钮自身除外)= 取消固定并关闭**;Esc 关闭;
14
- * 鼠标移出且未固定时关闭(聚焦或固定期间不因移出而关)。
15
- * 第 ④ 条为什么必须有(2026-10-04 用户反馈):点开后进入固定态,只有再点一次同一颗 ⓘ 才能退出 ——
16
- * 用户必须知道「同一颗图标既是开也是关」,与「点别处收起」的通用浮层预期不符。
17
- * ② 的判据(2026-10-04 用户反馈「一进弹窗就自动选中 ⓘ」):**只认用户自己把焦点移过来** ——
18
- * Radix 弹窗挂载时会把初始焦点派给容器内第一个可聚焦元素(FocusScope 的 focusFirst),
19
- * 标题行的 ⓘ 常常正是它;那次聚焦的 relatedTarget 在弹窗之外(或为空),据此忽略(见 onFocus)。
20
- *
21
- * 为什么气泡不用原生 `title`:
22
- * 原生 title 不可换行 / 不可定制 / 触屏与键盘体验不一致,且无法做边界处理。
23
- *
24
- * 渲染位置(两条硬约束,t7 评审 high 的修复):
25
- * ① **必须经 `createPortal` 渲进插件根容器**(`resolveModalRoot()`,与 Modal 共用同一份实现、
26
- * 同一条铁律:`#dsh-config-manager-root`,**绝不挂 `document.body`** —— 会被宿主 overlay
27
- * z-index:1000 盖住,并连带 body `pointer-events` 失效,本仓库有过实测事故)。
28
- * 为什么非 portal 不可:`.dialogContentCenter` 带常驻 `transform: translate(-50%,-50%)`,
29
- * 按 CSS Transforms L1 它成为后代 `position: fixed` 的**包含块** —— 裸 fixed 的气泡在 Modal 内
30
- * 会整体偏移「卡片在视口中的位移」,并被 `.dialogBody{overflow-y:auto}` 裁剪。
31
- * ② 气泡 `position: fixed` 的坐标是**视口坐标**(插件根容器自身无 transform),量测后写入内联
32
- * `top/left` —— 动态坐标无法用静态类表达,是本仓库「style 只允许极小修补」的正当例外
33
- * (与 Select 的 data-align 同源)。
34
- *
35
- * 夹紧基准 = **宿主画布**(插件根容器 = 气泡的 Portal 容器的可见矩形),**不是浏览器视口**:
36
- * 下方空间不足且上方更宽裕 → 向上翻转;左右越界 → 先右对齐再夹进画布;
37
- * 容器拿不到(未挂载 / 尺寸为 0)时才回落到窗口矩形(兜底)。画布矩形恒与窗口取交集,
38
- * 因此既不出宿主画布、也不出浏览器视口(见 DESIGN.md §7)。
39
- *
40
- * 无障碍:触发元素是 `<button type="button">`(aria-label 取字典键 `common.infoHint`;
41
- * 传入 `t` 时随当前语言,缺省回落源语言字典值);说明文本用 `aria-describedby` 关联,
42
- * 同一组件多实例的 id 由 `useId` 保证唯一。图标复用既有 `InfoIcon`(不新增图标、不新增依赖)。
43
- */
44
- import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type FocusEvent as ReactFocusEvent, type MouseEvent as ReactMouseEvent } from 'react'
45
- import { createPortal } from 'react-dom'
46
- import type { TranslateNS } from '../client-types.ts'
47
- import { zh } from '../locales.ts'
48
- import { InfoIcon } from './Icon.tsx'
49
- import { resolveModalRoot } from './Modal.tsx'
50
- import { canvasBounds, clamp, VIEWPORT_EDGE } from './floating-bounds.ts'
51
- import css from '../config-manager.module.css'
52
-
53
- /** 气泡与触发按钮之间的间距(px;与 .infoHintBubble 的视觉间距一致)。 */
54
- const BUBBLE_GAP = 6
55
- /** 边缘安全边距(px):气泡与基准矩形边缘至少留这么多,保证不出界。 */
56
- // VIEWPORT_EDGE 与 clamp / canvasBounds 同源(floating-bounds.ts),不再本地各写一份
57
-
58
- // clamp / canvasBounds 抽到 `floating-bounds.ts` —— Select 菜单需要**同一份**夹紧基准
59
- // (两处各写一份必然分叉:Select 那次跑偏正是因为直接用了视口坐标)。
60
-
61
- export interface InfoHintProps {
62
- /** 说明文本:自动折行(多行),显式换行符同样保留;**不用原生 title 承载**。 */
63
- text: string
64
- /**
65
- * 主字典翻译器(config-manager namespace)。传入时 aria-label 取当前语言的
66
- * `common.infoHint`;缺省回落源语言字典值(调用方手上有 t 时**应当**传入)。
67
- */
68
- t?: TranslateNS<'config-manager'>
69
- /** 覆盖可访问名(默认取字典键 common.infoHint)。 */
70
- label?: string
71
- }
72
-
73
- interface BubblePlacement {
74
- top: number
75
- left: number
76
- /** 实际放置方向:'bottom' = 按钮下方;'top' = 上下空间不足时向上翻转。 */
77
- side: 'top' | 'bottom'
78
- }
79
-
80
- export function InfoHint({ text, t, label }: InfoHintProps) {
81
- const reactId = useId()
82
- // React 的 useId 形如 ':r0:',冒号在 IDREF 里合法但可读性差 —— 归一化成字母数字/下划线/连字符
83
- const bubbleId = 'cm-info-hint-' + reactId.replace(/[^a-zA-Z0-9_-]/g, '')
84
- const btnRef = useRef<HTMLButtonElement | null>(null)
85
- const bubbleRef = useRef<HTMLSpanElement | null>(null)
86
- /** 悬停 / 聚焦各自记账:两条通道都可能独立成立(点击固定后再移出鼠标不得关闭)。 */
87
- const hoverRef = useRef(false)
88
- const focusRef = useRef(false)
89
- const [open, setOpen] = useState(false)
90
- const [pinned, setPinned] = useState(false)
91
- const [placement, setPlacement] = useState<BubblePlacement | null>(null)
92
- /**
93
- * Portal 容器(与 Modal 同一条铁律):`#dsh-config-manager-root`,**绝不 `document.body`**。
94
- * 渲染期惰性取一次(按钮必然已在根节点内),再以 layout effect 兜底同一次 commit 的极端情况;
95
- * 容器未知时**不渲染气泡**(宁可晚一帧,也绝不裸 fixed 渲进 Modal children 子树 / 挂 body)。
96
- */
97
- const [container, setContainer] = useState<HTMLElement | null>(resolveModalRoot)
98
- useLayoutEffect(() => { setContainer(resolveModalRoot()) }, [])
99
-
100
- const ariaLabel = label ?? (t !== undefined ? t('common.infoHint') : zh['common.infoHint'])
101
-
102
- /** Esc:关闭并取消固定(键盘用户与鼠标用户同一出口)。 */
103
- const close = useCallback((): void => {
104
- setOpen(false)
105
- setPinned(false)
106
- }, [])
107
-
108
- /**
109
- * 量测并定位气泡(渲染后调用)。
110
- * 夹紧矩形 = `canvasBounds()`(宿主画布 ∩ 窗口,**不是窗口**)**∪ 锚点矩形**(只放宽、不收紧)——
111
- * 为什么并锚点:弹窗卡片是 position:fixed(相对浏览器窗口居中),会伸出画布左缘,见下方注释。
112
- * 水平:与按钮左缘对齐,右侧放不下改右对齐;垂直:下方优先,放不下且上方更宽裕则向上翻转。
113
- * 两端都夹进夹紧矩形,因此气泡既贴得住锚点、也不越出画布(见 DESIGN.md §7「气泡边界 = 宿主画布 ∪ 锚点」)。
114
- */
115
- const reposition = useCallback((): void => {
116
- const btn = btnRef.current
117
- const bubble = bubbleRef.current
118
- if (btn === null || bubble === null) return
119
- const anchor = btn.getBoundingClientRect()
120
- const box = bubble.getBoundingClientRect()
121
- const bounds = canvasBounds()
122
- // 夹紧矩形 = 画布 ∪ 锚点(**只放宽、不收紧**):弹窗卡片是 position:fixed(相对浏览器窗口居中),
123
- // 而画布 = 插件根容器(在宿主设置弹窗里靠右,左边还有宿主导航),因此弹窗左半边的 ⓘ
124
- // 会比画布左缘更靠左;若仍严格夹进画布,气泡会被整体推进画布、与自己的 ⓘ 脱开
125
- // (2026-10-04 用户反馈「提示文字位置有偏移」)。并入锚点后气泡贴得住锚点,
126
- // 右侧 / 下方仍以画布为界(气泡不会因此跑出画布右缘或浏览器视口)。
127
- const clampBox = {
128
- left: Math.min(bounds.left, anchor.left),
129
- right: Math.max(bounds.right, anchor.right),
130
- top: Math.min(bounds.top, anchor.top),
131
- bottom: Math.max(bounds.bottom, anchor.bottom),
132
- }
133
- const minLeft = clampBox.left + VIEWPORT_EDGE
134
- const maxLeft = clampBox.right - VIEWPORT_EDGE - box.width
135
- const minTop = clampBox.top + VIEWPORT_EDGE
136
- const maxTop = clampBox.bottom - VIEWPORT_EDGE - box.height
137
- // 水平:与按钮左缘对齐;右侧放不下改右对齐,最后夹进夹紧矩形
138
- let left = anchor.left
139
- if (left + box.width > clampBox.right - VIEWPORT_EDGE) left = anchor.right - box.width
140
- left = clamp(left, minLeft, maxLeft)
141
- // 垂直:优先下方;下方不够且上方更宽裕 → 向上翻转;两端都夹紧
142
- const below = clampBox.bottom - anchor.bottom - BUBBLE_GAP
143
- const above = anchor.top - clampBox.top - BUBBLE_GAP
144
- const side: BubblePlacement['side'] = box.height > below && above > below ? 'top' : 'bottom'
145
- const rawTop = side === 'bottom' ? anchor.bottom + BUBBLE_GAP : anchor.top - BUBBLE_GAP - box.height
146
- const top = clamp(rawTop, minTop, maxTop)
147
- setPlacement({ top, left, side })
148
- }, [])
149
-
150
- // 打开后、绘制前量测(layout effect):第一帧就落在正确位置,不出现「先闪一下再跳」
151
- useLayoutEffect(() => {
152
- if (!open) {
153
- setPlacement(null)
154
- return
155
- }
156
- reposition()
157
- }, [open, reposition, text, container])
158
-
159
- // 打开期间跟随滚动 / 缩放重新定位(fixed 元素不会随内容滚动,必须自己跟)
160
- useEffect(() => {
161
- if (!open) return
162
- const onMove = (): void => { reposition() }
163
- window.addEventListener('resize', onMove)
164
- // 捕获阶段:插件在宿主设置弹窗内,滚动往往发生在外层容器而不是 window
165
- document.addEventListener('scroll', onMove, true)
166
- return () => {
167
- window.removeEventListener('resize', onMove)
168
- document.removeEventListener('scroll', onMove, true)
169
- }
170
- }, [open, reposition])
171
-
172
- // Esc 关闭(悬停打开时焦点不在按钮上,仍须响应);捕获 + stopPropagation 避免连带关掉外层 Modal / 侧滑面板
173
- useEffect(() => {
174
- if (!open) return
175
- const onKeyDown = (event: KeyboardEvent): void => {
176
- if (event.key !== 'Escape') return
177
- event.stopPropagation()
178
- close()
179
- }
180
- document.addEventListener('keydown', onKeyDown, true)
181
- return () => { document.removeEventListener('keydown', onKeyDown, true) }
182
- }, [open, close])
183
-
184
- /**
185
- * 固定态下按下任意位置 = 取消固定并关闭(第 ④ 条通道;见文件头「交互四通道」)。
186
- * 为什么用 `mousedown`:与 Select 同源 —— 比 click 早,且右键 / 拖拽结束也算一次「点了别处」;
187
- * 为什么用**捕获阶段**:ⓘ 常位于 Radix 弹窗 / 侧滑面板内,捕获保证在局部 handler 吞掉事件之前处理,
188
- * 且这里**不** stopPropagation(外层该关的弹窗照常关)。
189
- * 触发按钮自身必须放行:它的 onClick 负责第 ③ 条「再次点击取消固定」,若在这里抢先关闭,
190
- * 按钮的第二次按下会先关再开 —— 固定态反而无法用点击退出。
191
- * 气泡自身不需要排除:`.infoHintBubble{pointer-events:none}`,它根本不接收指针事件。
192
- */
193
- useEffect(() => {
194
- if (!pinned) return
195
- const onMouseDown = (event: MouseEvent): void => {
196
- const btn = btnRef.current
197
- if (btn !== null && event.target instanceof Node && btn.contains(event.target)) return
198
- close()
199
- }
200
- document.addEventListener('mousedown', onMouseDown, true)
201
- return () => { document.removeEventListener('mousedown', onMouseDown, true) }
202
- }, [pinned, close])
203
-
204
- const onMouseEnter = (): void => { hoverRef.current = true; setOpen(true) }
205
- const onMouseLeave = (): void => {
206
- hoverRef.current = false
207
- if (!pinned && !focusRef.current) setOpen(false)
208
- }
209
- /**
210
- * 聚焦通道(第 ② 条):**只认用户自己把焦点移过来**(2026-10-04 用户反馈)。
211
- * 为什么:Radix 的 FocusScope 在弹窗挂载时执行 focusFirst(...),把初始焦点派给容器内第一个
212
- * 可聚焦元素;本插件的 ⓘ 常常正是标题行里的那一个 —— 于是「一进弹窗就自动弹出 ⓘ 气泡」。
213
- * 判据 = relatedTarget(聚焦前拿着焦点的元素)是否**在同一弹窗内**:
214
- * · 弹窗初始焦点:relatedTarget 是弹窗外的触发器 / body / null → 忽略(**连焦点记账都不记**);
215
- * · 用户在弹窗内用 Tab 导航到 ⓘ:relatedTarget 必在同一 [role=dialog] 内 → 打开。
216
- * 非弹窗场景(没有 dialog 祖先)不做限制,行为与改动前一致。
217
- * 为什么程序化初始焦点连 focusRef 也不记:一旦记账,鼠标移出就不满足「未固定且未聚焦」,
218
- * 悬停一次后气泡会永久挂在屏幕上(只能靠 Esc / 点别处关)—— 这正是同一张截图里的观感。
219
- */
220
- const onFocus = (event: ReactFocusEvent<HTMLButtonElement>): void => {
221
- const dialog = event.currentTarget.closest('[role="dialog"]')
222
- if (dialog !== null) {
223
- const from = event.relatedTarget
224
- if (!(from instanceof Node) || !dialog.contains(from)) return
225
- }
226
- focusRef.current = true
227
- setOpen(true)
228
- }
229
- const onBlur = (): void => {
230
- focusRef.current = false
231
- if (!pinned && !hoverRef.current) setOpen(false)
232
- }
233
- /**
234
- * 点击 = 固定 / 取消固定;取消固定后仍悬停或仍聚焦则保持可见(悬停/聚焦通道本身仍成立)。
235
- *
236
- * **必须先 `preventDefault()`**(2026-11-04 用户反馈:悬停/点击选择框会连带作用到 ⓘ):
237
- * ⓘ 常被放在 `<label>`(或 Checkbox 的 label 区)里,而「点击 label 区域 → 激活它包裹的表单
238
- * 控件」是**点击事件的默认行为**。不掐断它,点一下 ⓘ 就会顺手切掉一个勾选框 / 打开一个下拉。
239
- * `preventDefault()` 只取消这条默认行为,不影响本组件自己的固定态逻辑,也不影响捕获阶段的
240
- * 外部按下关闭(那是 mousedown,与此处无关)。
241
- */
242
- const onClick = (event: ReactMouseEvent<HTMLButtonElement>): void => {
243
- event.preventDefault()
244
- if (pinned) {
245
- setPinned(false)
246
- setOpen(hoverRef.current || focusRef.current)
247
- } else {
248
- setPinned(true)
249
- setOpen(true)
250
- }
251
- }
252
-
253
- return (
254
- <span className={css.infoHint}>
255
- <button
256
- ref={btnRef}
257
- type="button"
258
- className={css.infoHintBtn}
259
- aria-label={ariaLabel}
260
- aria-describedby={open && container !== null ? bubbleId : undefined}
261
- data-open={open ? '' : undefined}
262
- data-pinned={pinned ? '' : undefined}
263
- onMouseEnter={onMouseEnter}
264
- onMouseLeave={onMouseLeave}
265
- onFocus={onFocus}
266
- onBlur={onBlur}
267
- onClick={onClick}
268
- >
269
- <InfoIcon size={13} />
270
- </button>
271
- {/* 气泡**必须**走 portal 渲到插件根容器(脱离 Modal 卡片的 transform 包含块与正文裁剪):
272
- 它不在本组件的 DOM 子树内,只经 id/aria-describedby 关联;容器未知时不渲染 */}
273
- {open && container !== null && createPortal(
274
- <span
275
- ref={bubbleRef}
276
- id={bubbleId}
277
- role="tooltip"
278
- className={css.infoHintBubble}
279
- data-side={placement === null ? undefined : placement.side}
280
- data-ready={placement === null ? undefined : ''}
281
- style={placement === null ? undefined : { top: placement.top + 'px', left: placement.left + 'px' }}
282
- >
283
- {text}
284
- </span>,
285
- container,
286
- )}
287
- </span>
288
- )
289
- }