dsh-config-manager 0.10.0 → 0.12.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 (233) hide show
  1. package/lib/adapters/attachment-index-cache.d.ts +33 -0
  2. package/lib/adapters/attachment-index-cache.js +114 -0
  3. package/lib/adapters/attachments.d.ts +97 -0
  4. package/lib/adapters/attachments.js +448 -0
  5. package/lib/adapters/index.d.ts +1 -0
  6. package/lib/adapters/index.js +7 -1
  7. package/lib/adapters/self.d.ts +2 -2
  8. package/lib/adapters/self.js +4 -0
  9. package/lib/adapters/sessions.d.ts +18 -1
  10. package/lib/adapters/sessions.js +193 -0
  11. package/lib/adapters/test-helpers.d.ts +7 -0
  12. package/lib/adapters/test-helpers.js +8 -1
  13. package/lib/adapters/workspaces.d.ts +0 -1
  14. package/lib/adapters/workspaces.js +244 -5
  15. package/lib/client.d.ts +170 -1
  16. package/lib/client.js +2067 -889
  17. package/lib/core/analyzer.d.ts +1 -14
  18. package/lib/core/analyzer.js +25 -67
  19. package/lib/core/backup-plan.js +4 -0
  20. package/lib/core/backup.d.ts +7 -0
  21. package/lib/core/backup.js +3 -0
  22. package/lib/core/external-failure.d.ts +18 -2
  23. package/lib/core/external-failure.js +63 -19
  24. package/lib/core/host-service.d.ts +12 -0
  25. package/lib/core/host-service.js +12 -0
  26. package/lib/core/host-session-shapes.d.ts +209 -0
  27. package/lib/core/host-session-shapes.js +134 -0
  28. package/lib/core/host-workspace-facade.d.ts +57 -0
  29. package/lib/core/host-workspace-facade.js +127 -0
  30. package/lib/core/import-planning.d.ts +15 -0
  31. package/lib/core/import-planning.js +44 -0
  32. package/lib/core/messages.d.ts +20 -0
  33. package/lib/core/messages.js +40 -0
  34. package/lib/core/phase3-host.js +2 -2
  35. package/lib/core/session-analyze.d.ts +52 -0
  36. package/lib/core/session-analyze.js +135 -0
  37. package/lib/core/session-compare.d.ts +54 -0
  38. package/lib/core/session-compare.js +154 -0
  39. package/lib/core/session-meta.d.ts +32 -0
  40. package/lib/core/session-meta.js +49 -0
  41. package/lib/core/session-verdict-plan.d.ts +2 -0
  42. package/lib/core/session-verdict-plan.js +33 -0
  43. package/lib/core/types.d.ts +153 -0
  44. package/lib/core/unit-enrichment.d.ts +19 -0
  45. package/lib/core/unit-enrichment.js +39 -0
  46. package/lib/core/workspace-root.d.ts +46 -0
  47. package/lib/core/workspace-root.js +121 -0
  48. package/lib/index.d.ts +2 -112
  49. package/lib/index.js +17 -222
  50. package/lib/profiles/dsh-profile-runtime.d.ts +54 -2
  51. package/lib/profiles/dsh-profile-runtime.js +124 -9
  52. package/lib/routes/route-support.d.ts +3 -0
  53. package/lib/routes/route-support.js +6 -0
  54. package/lib/schema/section-registry.js +15 -0
  55. package/lib/schema/types.d.ts +17 -1
  56. package/lib/sync/autosync-backoff.d.ts +40 -0
  57. package/lib/sync/autosync-backoff.js +74 -0
  58. package/lib/sync/autosync-config.d.ts +26 -41
  59. package/lib/sync/autosync-config.js +25 -26
  60. package/lib/sync/autosync-scheduler.d.ts +22 -10
  61. package/lib/sync/autosync-scheduler.js +509 -331
  62. package/lib/sync/backup-files.d.ts +3 -1
  63. package/lib/sync/backup-files.js +5 -3
  64. package/lib/sync/baseline-record.d.ts +10 -1
  65. package/lib/sync/baseline-record.js +2 -2
  66. package/lib/sync/credential-plan.d.ts +8 -0
  67. package/lib/sync/credential-plan.js +65 -0
  68. package/lib/sync/local-changes.d.ts +2 -1
  69. package/lib/sync/local-changes.js +4 -2
  70. package/lib/sync/partial-conflict-push.d.ts +39 -0
  71. package/lib/sync/partial-conflict-push.js +70 -0
  72. package/lib/sync/retention-policy.d.ts +23 -6
  73. package/lib/sync/retention-policy.js +51 -10
  74. package/lib/sync/round-export-cache.d.ts +22 -0
  75. package/lib/sync/round-export-cache.js +36 -0
  76. package/lib/sync/snapshot-zip.d.ts +9 -0
  77. package/lib/sync/snapshot-zip.js +62 -0
  78. package/lib/sync/sync-engine.d.ts +24 -30
  79. package/lib/sync/sync-engine.js +145 -157
  80. package/lib/sync/sync-history.d.ts +4 -0
  81. package/lib/sync/sync-watcher.d.ts +27 -0
  82. package/lib/sync/sync-watcher.js +80 -3
  83. package/lib/sync/transport.js +11 -2
  84. package/lib/sync/watch-scope.js +2 -1
  85. package/lib/ui/backup-schedule.d.ts +5 -1
  86. package/lib/ui/backup-schedule.js +5 -3
  87. package/lib/ui/export-flow.js +1 -0
  88. package/lib/ui/i18n.d.ts +3 -0
  89. package/lib/ui/i18n.js +6 -0
  90. package/lib/ui/import-wizard.d.ts +8 -0
  91. package/lib/ui/import-wizard.js +10 -0
  92. package/lib/ui/overview-view.d.ts +20 -7
  93. package/lib/ui/overview-view.js +31 -12
  94. package/lib/ui/selection-model.d.ts +60 -0
  95. package/lib/ui/selection-model.js +258 -2
  96. package/lib/ui/session-compare-facts.d.ts +51 -0
  97. package/lib/ui/session-compare-facts.js +82 -0
  98. package/lib/ui/sync-settings-view.d.ts +25 -0
  99. package/lib/ui/sync-settings-view.js +9 -0
  100. package/lib/ui/test-helpers.js +2 -2
  101. package/lib/utils/attachment-refs.d.ts +49 -0
  102. package/lib/utils/attachment-refs.js +169 -0
  103. package/lib/utils/shared-constants.d.ts +16 -0
  104. package/lib/utils/shared-constants.js +13 -0
  105. package/package.json +1 -1
  106. package/src/adapters/attachment-index-cache.test.ts +122 -0
  107. package/src/adapters/attachment-index-cache.ts +129 -0
  108. package/src/adapters/attachments.test.ts +358 -0
  109. package/src/adapters/attachments.ts +472 -0
  110. package/src/adapters/index.ts +8 -1
  111. package/src/adapters/self.ts +5 -1
  112. package/src/adapters/sessions.test.ts +140 -0
  113. package/src/adapters/sessions.ts +184 -1
  114. package/src/adapters/test-helpers.ts +8 -1
  115. package/src/adapters/workspaces.test.ts +254 -0
  116. package/src/adapters/workspaces.ts +234 -5
  117. package/src/client/common/ContentPicker.tsx +235 -15
  118. package/src/client/common/section-labels.test.ts +1 -1
  119. package/src/client/common/section-labels.ts +1 -0
  120. package/src/client/common/ui.tsx +17 -1
  121. package/src/client/config-manager.module.css +117 -0
  122. package/src/client/export/ExportView.tsx +15 -2
  123. package/src/client/home/BackupScheduleCard.tsx +13 -9
  124. package/src/client/home/HomePanel.tsx +28 -8
  125. package/src/client/import/ImportWizardView.tsx +8 -0
  126. package/src/client/import/PathMappingForm.tsx +49 -10
  127. package/src/client/import/import-wizard-steps.tsx +80 -3
  128. package/src/client/import/use-import-wizard-controller.ts +3 -0
  129. package/src/client/locales/backup.ts +6 -0
  130. package/src/client/locales/common.ts +2 -0
  131. package/src/client/locales/export.ts +5 -0
  132. package/src/client/locales/import.ts +6 -0
  133. package/src/client/locales/overview.ts +14 -0
  134. package/src/client/locales/sessions.ts +26 -0
  135. package/src/client/run-store-redact.ts +122 -0
  136. package/src/client/run-store.ts +13 -115
  137. package/src/client/sync/AutosyncCard.tsx +19 -8
  138. package/src/client/sync/SyncChannelEntryCard.tsx +21 -2
  139. package/src/client/sync/SyncChannelSection.tsx +23 -0
  140. package/src/client/sync/SyncChannelSkeleton.tsx +116 -0
  141. package/src/client/sync/SyncLogList.tsx +22 -2
  142. package/src/client/sync/SyncPanel.tsx +24 -25
  143. package/src/client/sync/SyncSecuritySection.tsx +7 -1
  144. package/src/client/sync/SyncSettingsDialog.tsx +22 -6
  145. package/src/client/sync/SyncSettingsView.test.ts +15 -0
  146. package/src/client/sync/history-model.test.ts +19 -1
  147. package/src/client/sync/history-model.ts +15 -0
  148. package/src/client/sync/sync-api.ts +14 -0
  149. package/src/client/sync/sync-locales.ts +28 -0
  150. package/src/client/sync/sync-view-v2.test.ts +14 -3
  151. package/src/client/sync/sync-view.test.ts +106 -4
  152. package/src/client/sync/sync-view.ts +159 -16
  153. package/src/core/analyzer.ts +38 -79
  154. package/src/core/backup-plan.ts +4 -0
  155. package/src/core/backup.ts +10 -0
  156. package/src/core/external-failure.test.ts +31 -0
  157. package/src/core/external-failure.ts +71 -21
  158. package/src/core/host-service.ts +17 -0
  159. package/src/core/host-session-shapes.ts +270 -0
  160. package/src/core/host-workspace-facade.ts +153 -0
  161. package/src/core/import-planning.ts +48 -0
  162. package/src/core/messages.ts +40 -0
  163. package/src/core/native-path-picker.test.ts +3 -2
  164. package/src/core/phase3-host.ts +2 -2
  165. package/src/core/phase3-production-integration.test.ts +73 -1
  166. package/src/core/session-analyze.ts +159 -0
  167. package/src/core/session-compare-wiring.test.ts +207 -0
  168. package/src/core/session-compare.test.ts +119 -0
  169. package/src/core/session-compare.ts +185 -0
  170. package/src/core/session-meta.test.ts +25 -2
  171. package/src/core/session-meta.ts +54 -0
  172. package/src/core/session-verdict-plan.test.ts +70 -0
  173. package/src/core/session-verdict-plan.ts +32 -0
  174. package/src/core/types.ts +161 -0
  175. package/src/core/unit-enrichment.ts +46 -0
  176. package/src/core/workspace-root.test.ts +152 -0
  177. package/src/core/workspace-root.ts +146 -0
  178. package/src/foreign/trae-sqlcipher.test.ts +13 -4
  179. package/src/index.ts +27 -355
  180. package/src/profiles/dsh-profile-runtime.test.ts +77 -3
  181. package/src/profiles/dsh-profile-runtime.ts +125 -9
  182. package/src/routes/route-support.test.ts +49 -0
  183. package/src/routes/route-support.ts +9 -0
  184. package/src/schema/manifest-schema.test.ts +1 -1
  185. package/src/schema/registry.test.ts +7 -2
  186. package/src/schema/section-registry.ts +15 -0
  187. package/src/schema/types.ts +23 -2
  188. package/src/sync/autosync-backoff.test.ts +64 -0
  189. package/src/sync/autosync-backoff.ts +88 -0
  190. package/src/sync/autosync-config.test.ts +38 -0
  191. package/src/sync/autosync-config.ts +66 -52
  192. package/src/sync/autosync-risk-tier.test.ts +5 -1
  193. package/src/sync/autosync-scheduler.test.ts +537 -4
  194. package/src/sync/autosync-scheduler.ts +252 -68
  195. package/src/sync/backup-files.ts +4 -1
  196. package/src/sync/backup-scheduler.test.ts +5 -4
  197. package/src/sync/baseline-record.ts +12 -3
  198. package/src/sync/credential-plan.ts +70 -0
  199. package/src/sync/local-changes.ts +10 -4
  200. package/src/sync/partial-conflict-push.test.ts +237 -0
  201. package/src/sync/partial-conflict-push.ts +105 -0
  202. package/src/sync/retention-age-tier.test.ts +79 -0
  203. package/src/sync/retention-policy.test.ts +101 -10
  204. package/src/sync/retention-policy.ts +57 -8
  205. package/src/sync/round-export-cache.test.ts +83 -0
  206. package/src/sync/round-export-cache.ts +53 -0
  207. package/src/sync/snapshot-zip.ts +70 -0
  208. package/src/sync/sync-engine.test.ts +35 -1
  209. package/src/sync/sync-engine.ts +145 -155
  210. package/src/sync/sync-history.ts +4 -0
  211. package/src/sync/sync-watcher.test.ts +76 -4
  212. package/src/sync/sync-watcher.ts +82 -3
  213. package/src/sync/transport.test.ts +1 -1
  214. package/src/sync/transport.ts +10 -2
  215. package/src/sync/watch-scope.test.ts +8 -0
  216. package/src/sync/watch-scope.ts +2 -1
  217. package/src/ui/backup-schedule.test.ts +13 -6
  218. package/src/ui/backup-schedule.ts +4 -2
  219. package/src/ui/export-flow.ts +1 -0
  220. package/src/ui/i18n.ts +6 -0
  221. package/src/ui/import-wizard.ts +11 -0
  222. package/src/ui/overview-view.test.ts +48 -0
  223. package/src/ui/overview-view.ts +47 -13
  224. package/src/ui/selection-model.test.ts +265 -3
  225. package/src/ui/selection-model.ts +256 -2
  226. package/src/ui/session-compare-facts.test.ts +67 -0
  227. package/src/ui/session-compare-facts.ts +122 -0
  228. package/src/ui/sync-settings-view.test.ts +60 -1
  229. package/src/ui/sync-settings-view.ts +36 -0
  230. package/src/ui/test-helpers.ts +2 -2
  231. package/src/utils/attachment-refs.test.ts +98 -0
  232. package/src/utils/attachment-refs.ts +177 -0
  233. package/src/utils/shared-constants.ts +22 -0
@@ -10,6 +10,7 @@ import test from 'node:test'
10
10
  import assert from 'node:assert/strict'
11
11
 
12
12
  import {
13
+ applySessionAttachmentCoupling, childUnitsOf, nestedChildUnitIds, sessionChildUnits,
13
14
  applyPluginPendingChecks, buildExportRequest, buildSelectedPlan, defaultSelection, samePendingChecks,
14
15
  defaultSelectionFromPlan, effectiveImportPlan, effectiveImportSelection, filterSections,
15
16
  filterPluginTree, groupPickState, groupSelectedCount, groupUnits, HIGH_RISK_ADAPTERS, isHighRiskAdapter,
@@ -310,6 +311,64 @@ test('sectionsFromPlan:宿主给的展示名/分组优先(sessions 显示会
310
311
  assert.equal(units[1]!.label, '--D-P--/u2', '缺 label → 退回 unitLabel,不编造');
311
312
  assert.equal(units[1]!.group, 'dsh-config-manager');
312
313
  })
314
+ test('sectionsFromPlan:附件的归属/真名/父会话字段原样透传(导入树靠它还原折叠与联动)', () => {
315
+ const plan: ImportPlan = {
316
+ items: [
317
+ item({
318
+ id: 'attachments:v1/objects/aa/' + 'a'.repeat(64),
319
+ unitId: 'attachments:sha256:' + 'a'.repeat(64),
320
+ adapter: 'attachments',
321
+ label: 'P-01-after.png',
322
+ detail: 'sha256:aaaaaaaa…',
323
+ parentUnitIds: ['sessions:proj-1/sess-1'],
324
+ parentSessionId: 'proj-1/sess-1',
325
+ }),
326
+ item({
327
+ id: 'attachments:v1/objects/bb/' + 'b'.repeat(64),
328
+ unitId: 'attachments:sha256:' + 'b'.repeat(64),
329
+ adapter: 'attachments',
330
+ }),
331
+ ],
332
+ globalStrategy: 'merge',
333
+ pathMappings: [],
334
+ missingSecrets: [],
335
+ needsRestart: false,
336
+ estimatedActions: {} as ImportPlan['estimatedActions'],
337
+ };
338
+ const units = sectionsFromPlan(plan)[0]!.units;
339
+ assert.equal(units[0]!.label, 'P-01-after.png');
340
+ assert.equal(units[0]!.detail, 'sha256:aaaaaaaa…');
341
+ assert.deepEqual(units[0]!.parentUnitIds, ['sessions:proj-1/sess-1'], '有归属就带上,UI 才能挂到对话下');
342
+ assert.equal(units[0]!.parentSessionId, 'proj-1/sess-1', '勾选联动认父会话');
343
+ assert.equal(units[1]!.parentUnitIds, undefined, '孤儿附件不写空数组,UI 据此按扁平渲染');
344
+ assert.equal(units[1]!.detail, undefined);
345
+ });
346
+
347
+ test('导入树:只勾对话(attachments 分区还没进 sections)⇒ 全选也要把被引用附件带上,绝不静默丢图', () => {
348
+ const plan: ImportPlan = {
349
+ items: [
350
+ item({ id: 'sessions:P/u1/session.jsonl', unitId: 'sessions:P/u1', adapter: 'sessions' }),
351
+ item({
352
+ id: 'attachments:v1/objects/aa/' + 'a'.repeat(64),
353
+ unitId: 'attachments:sha256:' + 'a'.repeat(64),
354
+ adapter: 'attachments',
355
+ parentUnitIds: ['sessions:P/u1'],
356
+ }),
357
+ ],
358
+ globalStrategy: 'merge',
359
+ pathMappings: [],
360
+ missingSecrets: [],
361
+ needsRestart: false,
362
+ estimatedActions: {} as ImportPlan['estimatedActions'],
363
+ }
364
+ const nodes = sectionsFromPlan(plan)
365
+ // 修复前的破口:全选只作用于看得见的分区,attachments 行被藏起来 ⇒ 附件项被整片滤掉
366
+ const sessionsOnly = nodes.filter((n) => n.section === 'sessions')
367
+ const after = applySessionAttachmentCoupling(selOf([], []), selectAll(sessionsOnly, true), nodes)
368
+ const kept = buildSelectedPlan(plan, after).items
369
+ assert.ok(kept.some((i) => i.adapter === 'attachments'), '勾了对话,它用过的附件必须一起进计划')
370
+ })
371
+
313
372
  test('defaultSelectionFromPlan:本地导入默认全勾;市场口径(highRiskDefaultOff)高风险不勾', () => {
314
373
  assert.deepEqual(defaultSelectionFromPlan(PLAN).sections, ['skills', 'plugins', 'credentialsStatus'])
315
374
  const market = defaultSelectionFromPlan(PLAN, { highRiskDefaultOff: true })
@@ -638,8 +697,13 @@ test('取消整个工作区分区 → 它的会话也全部取消;没有 sessi
638
697
  test('couplingInventorySections:勾了会话就必须把工作区清单一起读(否则联动没有数据可依)', () => {
639
698
  assert.deepEqual(couplingInventorySections([]), []);
640
699
  assert.deepEqual(couplingInventorySections(['settings']), ['settings']);
641
- assert.deepEqual(couplingInventorySections(['sessions']), ['sessions', 'workspaces']);
642
- assert.deepEqual(couplingInventorySections(['sessions', 'workspaces']), ['sessions', 'workspaces'], '已有就不重复加');
700
+ // G5:附件清单同理 —— 会话行下面的附件子树只能由附件分区的 parentUnitIds 渲染
701
+ assert.deepEqual(couplingInventorySections(['sessions']), ['sessions', 'workspaces', 'attachments']);
702
+ assert.deepEqual(
703
+ couplingInventorySections(['sessions', 'workspaces', 'attachments']),
704
+ ['sessions', 'workspaces', 'attachments'],
705
+ '已有就不重复加',
706
+ );
643
707
  assert.deepEqual(couplingInventorySections(['workspaces']), ['workspaces'], '反向不加:没勾会话时不需要会话清单');
644
708
  });
645
709
 
@@ -730,7 +794,7 @@ test('链式选择:旧宿主不回传 projectKey 时用 detail(工作区绝
730
794
 
731
795
  /* ---------------- 父对话 ↔ 子代理会话联动(用户需求:勾父自动勾上它的 subagent 会话) ---------------- */
732
796
 
733
- import { applySessionParentCoupling, type SelectionUnit, type SessionParentChange } from './selection-model.ts';
797
+ import { applyChildUnitParentCoupling, applySessionParentCoupling, type SelectionUnit, type SessionParentChange } from './selection-model.ts';
734
798
 
735
799
  /**
736
800
  * 会话族夹具(全部在同一个工作区目录下):
@@ -1102,3 +1166,201 @@ test('选择模型:sectionsFromPreview 透传 group 与 relatedAreas(按插
1102
1166
  assert.deepEqual(nodes[0]?.units[0]?.relatedAreas, [{ section: 'pluginData', relPath: '.alpha/runtime', role: 'config' }])
1103
1167
  assert.equal(nodes[1]?.units[0]?.relatedAreas, undefined, '没有声明的单元不得凭空带 relatedAreas')
1104
1168
  });
1169
+
1170
+ /* ==================================================================================================
1171
+ * G5:附件挂到用过它的会话下面(跨分区子行 + 勾选联动)
1172
+ *
1173
+ * 断言的三条用户可见语义:
1174
+ * 1. 索引只由 parentUnitIds 决定,渲染与联动共用同一份;
1175
+ * 2. 勾/取消会话连带它的附件,**共用附件任一处取消即不带**;
1176
+ * 3. 批量动作**也**联动(2026-11-21 起):组行有了自己的勾选框,勾「附件」组会连带父对话,
1177
+ * 而父对话一旦勾上就必须带它全部附件 —— 否则界面勾选与包内容各说各话。零翻动时零额外写入。
1178
+ * ================================================================================================ */
1179
+
1180
+ const ATT_A = 'attachments:sha256:' + 'a'.repeat(64)
1181
+ const ATT_B = 'attachments:sha256:' + 'b'.repeat(64)
1182
+ const SESS_1 = 'sessions:proj/sess-1'
1183
+ const SESS_2 = 'sessions:proj/sess-2'
1184
+
1185
+ /** 两条会话 + 两个附件:A 被两条会话共用,B 只属于 sess-1。 */
1186
+ function attachmentTree(): SelectionSection[] {
1187
+ return [
1188
+ {
1189
+ section: 'sessions', count: 2, sizeBytes: 0,
1190
+ units: [
1191
+ { id: SESS_1, label: 'S1', group: 'proj', sizeBytes: 0 },
1192
+ { id: SESS_2, label: 'S2', group: 'proj', sizeBytes: 0 },
1193
+ ],
1194
+ },
1195
+ {
1196
+ section: 'attachments', count: 2, sizeBytes: 0,
1197
+ units: [
1198
+ { id: ATT_A, label: 'image/png', parentUnitIds: [SESS_1, SESS_2], sizeBytes: 0 },
1199
+ { id: ATT_B, label: 'image/png', parentUnitIds: [SESS_1], sizeBytes: 0 },
1200
+ ],
1201
+ },
1202
+ ]
1203
+ }
1204
+
1205
+ const EMPTY: Selection = { sections: [], excluded: [] }
1206
+
1207
+ test('G5-UI-1 childUnitsOf / nestedChildUnitIds:只按 parentUnitIds 建索引', () => {
1208
+ const nodes = attachmentTree()
1209
+ const index = childUnitsOf(nodes)
1210
+ assert.deepEqual((index.get(SESS_1) ?? []).map((u) => u.id), [ATT_A, ATT_B], '共用附件在两个父行下都出现')
1211
+ assert.deepEqual((index.get(SESS_2) ?? []).map((u) => u.id), [ATT_A])
1212
+ assert.deepEqual([...nestedChildUnitIds(nodes)].sort(), [ATT_A, ATT_B], '分区自己那一排不再重复列这两个附件')
1213
+ });
1214
+
1215
+ test('G5-UI-2 勾会话 ⇒ 连带勾上它的附件(分区成员 + 未被排除)', () => {
1216
+ const nodes = attachmentTree()
1217
+ const after = toggleUnit(EMPTY, nodes, SESS_1, true)
1218
+ const out = applySessionAttachmentCoupling(EMPTY, after, nodes)
1219
+ assert.ok(out.sections.includes('attachments'))
1220
+ assert.ok(!out.excluded.includes(ATT_A))
1221
+ assert.ok(!out.excluded.includes(ATT_B))
1222
+ });
1223
+
1224
+ test('G5-UI-3 共用附件:任一处取消会话即不带(shared=each)', () => {
1225
+ const nodes = attachmentTree()
1226
+ const both = toggleUnit(toggleUnit(EMPTY, nodes, SESS_1, true), nodes, SESS_2, true)
1227
+ const withAtt = applySessionAttachmentCoupling(EMPTY, both, nodes)
1228
+ assert.ok(!withAtt.excluded.includes(ATT_A))
1229
+
1230
+ const unchecked = toggleUnit(withAtt, nodes, SESS_1, false)
1231
+ const out = applySessionAttachmentCoupling(withAtt, unchecked, nodes)
1232
+ assert.ok(out.excluded.includes(ATT_A), 'sess-1 取消 ⇒ 共用附件不再带走(第二条会话仍勾着也不救回)')
1233
+ assert.ok(out.excluded.includes(ATT_B))
1234
+ });
1235
+
1236
+ test('G5-UI-4 批量动作也联动附件:勾整个会话区 ⇒ 被引用附件一并带上', () => {
1237
+ const nodes = attachmentTree()
1238
+ const sessionsNode = nodes[0]
1239
+ assert.ok(sessionsNode !== undefined)
1240
+ const after = toggleSection(EMPTY, sessionsNode, true)
1241
+ assert.ok(!after.sections.includes('attachments'), '前置:勾会话区本身不带附件分区')
1242
+ const out = applySessionAttachmentCoupling(EMPTY, after, nodes)
1243
+ assert.ok(out.sections.includes('attachments'), '附件分区随之勾上,界面与包内容一致')
1244
+ assert.ok(!out.excluded.includes(ATT_A))
1245
+ assert.ok(!out.excluded.includes(ATT_B))
1246
+ assert.equal(applySessionAttachmentCoupling(out, out, nodes), out, '零翻动时原样返回,不做无谓拷贝')
1247
+ });
1248
+
1249
+ test('G5-UI-5 couplingInventorySections:有会话就必须同时拉附件清单', () => {
1250
+ assert.deepEqual(couplingInventorySections(['sessions']), ['sessions', 'workspaces', 'attachments'])
1251
+ assert.deepEqual(couplingInventorySections(['skills']), ['skills'], '没有会话时不多拉任何清单')
1252
+ });
1253
+
1254
+ /* ---------------- A3:勾子行连带父对话(组行可勾选后必须成立) ---------------- */
1255
+
1256
+ test('A3-1 勾附件子行 ⇒ 连带勾上父对话,并带上父对话的全部附件', () => {
1257
+ const nodes = attachmentTree()
1258
+ const after = applyChildUnitParentCoupling(toggleUnit(EMPTY, nodes, ATT_B, true), nodes, {
1259
+ unitId: ATT_B,
1260
+ checked: true,
1261
+ })
1262
+ assert.ok(after.sections.includes('sessions'), '父对话所在的会话分区被勾上')
1263
+ assert.ok(!after.excluded.includes(SESS_1), '父对话本身勾上 —— 否则导出请求推导不出这条附件的白名单')
1264
+ assert.ok(after.excluded.includes(SESS_2), '兄弟会话不被牵连:分区已选但逐条排除')
1265
+ assert.ok(!after.excluded.includes(ATT_A), '父对话被勾上就等于带它的全部附件,与「勾会话带附件」同口径')
1266
+ })
1267
+
1268
+ test('A3-2 取消子行不反向取消父对话', () => {
1269
+ const nodes = attachmentTree()
1270
+ const both = applyChildUnitParentCoupling(toggleUnit(toggleUnit(EMPTY, nodes, ATT_A, true), nodes, ATT_B, true), nodes)
1271
+ assert.ok(!both.excluded.includes(SESS_1) && !both.excluded.includes(SESS_2), '前置:共用附件把两条父会话都带上')
1272
+
1273
+ const unchecked = toggleUnit(both, nodes, ATT_B, false)
1274
+ const out = applyChildUnitParentCoupling(unchecked, nodes, { unitId: ATT_B, checked: false })
1275
+ assert.equal(out, unchecked, '取消方向零写入')
1276
+ assert.ok(!out.excluded.includes(SESS_1), '父对话仍勾着(用户明确要求取消子行不反向取消父)')
1277
+ assert.ok(out.excluded.includes(ATT_B), '被取消的子行确实不带')
1278
+ })
1279
+
1280
+ test('A3-3 组行勾选(逐条 toggle + 逐条 change)等价于把整组连父对话一起带上', () => {
1281
+ const nodes = attachmentTree()
1282
+ const groupIds = [ATT_A, ATT_B]
1283
+ const press = (state: Selection, checked: boolean): Selection => {
1284
+ let next = state
1285
+ for (const id of groupIds) {
1286
+ next = toggleUnit(next, nodes, id, checked)
1287
+ next = applyChildUnitParentCoupling(next, nodes, { unitId: id, checked })
1288
+ }
1289
+ return next
1290
+ }
1291
+ const picked = press(EMPTY, true)
1292
+ assert.ok(!picked.excluded.includes(ATT_A) && !picked.excluded.includes(ATT_B), '整组勾上')
1293
+ assert.ok(!picked.excluded.includes(SESS_1) && !picked.excluded.includes(SESS_2), '两条父会话都被带上')
1294
+
1295
+ const cleared = press(picked, false)
1296
+ assert.ok(cleared.excluded.includes(ATT_A) && cleared.excluded.includes(ATT_B), '整组取消 ⇒ 两条附件都不带')
1297
+ assert.ok(!cleared.excluded.includes(SESS_1), '取消整组不反向取消父对话')
1298
+ })
1299
+
1300
+ /* ---------------- A5:会话区里子代理缩进在父对话下面 ---------------- */
1301
+
1302
+ const SUB_1 = 'sessions:proj/sess-sub-1'
1303
+ const SUB_ORPHAN = 'sessions:proj/sess-orphan'
1304
+
1305
+ function subagentTree(): SelectionSection[] {
1306
+ return [
1307
+ {
1308
+ section: 'sessions', count: 4, sizeBytes: 0,
1309
+ units: [
1310
+ { id: SESS_1, label: '父对话', group: 'proj', sizeBytes: 0 },
1311
+ { id: SESS_2, label: '另一个父对话', group: 'proj', sizeBytes: 0 },
1312
+ { id: SUB_1, label: '子代理会话', group: 'proj', sizeBytes: 0, parentSessionId: 'sess-1' },
1313
+ // 父对话不在清单里(被搜索过滤掉 / 不属于本分区):不许凭空消失,留在顶层
1314
+ { id: SUB_ORPHAN, label: '孤儿子代理', group: 'proj', sizeBytes: 0, parentSessionId: 'sess-missing' },
1315
+ ],
1316
+ },
1317
+ {
1318
+ section: 'attachments', count: 1, sizeBytes: 0,
1319
+ units: [{ id: ATT_A, label: 'image/png', parentUnitIds: [SUB_1], sizeBytes: 0 }],
1320
+ },
1321
+ ]
1322
+ }
1323
+
1324
+ test('A5-1 sessionChildUnits:子代理会话挂到父对话行下,父行缺失时留在顶层', () => {
1325
+ const nodes = subagentTree()
1326
+ const index = sessionChildUnits(nodes)
1327
+ assert.deepEqual((index.get(SESS_1) ?? []).map((u) => u.id), [SUB_1])
1328
+ assert.equal(index.get(SESS_2), undefined)
1329
+ assert.equal(index.get(SUB_ORPHAN), undefined, '找不到父行的子会话不进索引')
1330
+ });
1331
+
1332
+ test('A5-2 nestedChildUnitIds:子代理会话与会话附件都不再出现在分区顶层', () => {
1333
+ assert.deepEqual([...nestedChildUnitIds(subagentTree())].sort(), [ATT_A, SUB_1].sort())
1334
+ });
1335
+
1336
+ /* ---------------- A6:附件随对话自动带上(分区行已从选择器删除) ---------------- */
1337
+
1338
+ test('A6-1 勾了对话 ⇒ 导出请求自动带上它的附件(只看归属,不看附件分区是否被勾选)', () => {
1339
+ const nodes = attachmentTree()
1340
+ const sessionsNode = nodes[0]
1341
+ assert.ok(sessionsNode !== undefined)
1342
+ const sel = toggleSection(EMPTY, sessionsNode, true)
1343
+ assert.ok(!sel.sections.includes('attachments'), '基线里附件分区没被勾选')
1344
+ assert.deepEqual(buildExportRequest(sel, nodes), {
1345
+ only: ['sessions', 'attachments'],
1346
+ includeItems: { attachments: [ATT_A, ATT_B] },
1347
+ })
1348
+ });
1349
+
1350
+ test('A6-2 没有对话被勾选 ⇒ 一条附件都不进导出请求(哪怕 sections 里残留 attachments)', () => {
1351
+ const nodes = attachmentTree()
1352
+ assert.deepEqual(buildExportRequest({ sections: ['attachments'], excluded: [] }, nodes), { only: [] })
1353
+ });
1354
+
1355
+ test('A6-3 单个附件被取消勾选 ⇒ 白名单里没有它,其余照旧', () => {
1356
+ const nodes = attachmentTree()
1357
+ const sel: Selection = { sections: ['sessions', 'attachments'], excluded: [ATT_B] }
1358
+ assert.deepEqual(buildExportRequest(sel, nodes).includeItems?.attachments, [ATT_A])
1359
+ });
1360
+
1361
+ test('A6-4 取消一条对话 ⇒ 只被它引用的附件随之退出请求', () => {
1362
+ const nodes = attachmentTree()
1363
+ const sel: Selection = { sections: ['sessions'], excluded: [SESS_1] }
1364
+ // ATT_A 仍被 sess-2 引用(共用),ATT_B 只属于 sess-1 ⇒ 只剩 ATT_A
1365
+ assert.deepEqual(buildExportRequest(sel, nodes).includeItems?.attachments, [ATT_A])
1366
+ });
@@ -60,6 +60,14 @@ export interface SelectionUnit {
60
60
  * 时联动整段失效 —— 界面勾了什么与包里装了什么就会不一致(真机事故:勾 2 条、包里 41 条)。
61
61
  */
62
62
  parentSessionId?: string
63
+ /**
64
+ * 本单元挂在哪些父单元下面(跨分区展示嵌套;**目前只有附件单元会带**)。
65
+ *
66
+ * 取值 = 完整单元 id(`sessions:<projectKey>/<sessionId>`)。同一附件被多条会话引用时有多个父 id,
67
+ * 于是它在每个父下面各出现一行(用户选择:一处取消勾选即不带 —— 勾选仍是同一个单元 id,不复制实体)。
68
+ * 缺省 = 不知道归属(分区里平铺渲染),**不是**空数组。
69
+ */
70
+ parentUnitIds?: string[]
63
71
  /**
64
72
  * 空白会话(从未提问过;宿主下发的**事实**,只有 sessions 分区可能有值)。
65
73
  *
@@ -206,6 +214,7 @@ export function sectionsFromPreview(
206
214
  ...(u.sessionIds !== undefined ? { sessionIds: u.sessionIds } : {}),
207
215
  ...(u.projectKey !== undefined ? { projectKey: u.projectKey } : {}),
208
216
  ...(u.parentSessionId !== undefined ? { parentSessionId: u.parentSessionId } : {}),
217
+ ...(u.parentUnitIds !== undefined && u.parentUnitIds.length > 0 ? { parentUnitIds: u.parentUnitIds } : {}),
209
218
  ...(u.blank === true ? { blank: true } : {}),
210
219
  // 「按插件看」的树骨架(宿主下发的静态区域清单;缺省 = 该插件没有已知关联)
211
220
  ...(u.relatedAreas !== undefined && u.relatedAreas.length > 0 ? { relatedAreas: u.relatedAreas } : {}),
@@ -485,6 +494,12 @@ export function buildExportRequest(sel: Selection, nodes: SelectionSection[]): E
485
494
  const includeItems: Partial<Record<SectionId, string[]>> = {}
486
495
  let partial = false
487
496
  for (const node of nodes) {
497
+ /**
498
+ * 附件分区不参与这一轮:它没有自己的勾选框,只能由「哪些对话被勾选」推导出来(见下面那段)。
499
+ * 让它照常走 `sel.sections` 的话,用户把会话整段取消之后附件仍留在 sections 里 —— 包里就会出现
500
+ * 一堆没有对话引用的图片对象,正是 A6 要消灭的那种「附件分区的独立开关」。
501
+ */
502
+ if (node.section === 'attachments') continue
488
503
  if (!sel.sections.includes(node.section)) continue
489
504
  if (node.units.length === 0) {
490
505
  only.push(node.section)
@@ -498,6 +513,37 @@ export function buildExportRequest(sel: Selection, nodes: SelectionSection[]): E
498
513
  partial = true
499
514
  }
500
515
  }
516
+ /**
517
+ * 附件没有自己的勾选框(A6:分区行已从选择器删除),它**随被勾选的对话自动带上**。
518
+ *
519
+ * 判据是「附件挂在哪条对话下」(宿主算出的 parentUnitIds)与那条对话此刻是否被勾选:
520
+ * 导出请求因此不再依赖「用户看见过附件分区」这件事 —— 分区行藏起来之后,用户勾一个对话,
521
+ * 包里仍有它的图片与文件对象,与用户对「备份这个对话」的预期一致。
522
+ *
523
+ * 只列**有对话要它**的附件:孤儿对象(没有任何勾选对话引用)一律不进来,避免把整库 596 个
524
+ * 附件一次性塞进包里(A6 的另一半语义)。用户单独取消某张图(会话行下的子行)时,它就在
525
+ * `excluded` 里,这里自然被剔掉 —— 白名单只给真正要的 id。
526
+ */
527
+ const attachmentsNode = nodes.find((n) => n.section === 'attachments')
528
+ if (attachmentsNode !== undefined && only.includes('sessions')) {
529
+ const sessionsNode = nodes.find((n) => n.section === 'sessions')
530
+ const pickedSessions = new Set(
531
+ (sessionsNode?.units ?? []).filter((u) => !sel.excluded.includes(u.id)).map((u) => u.id),
532
+ )
533
+ if (pickedSessions.size > 0) {
534
+ const ids = attachmentsNode.units
535
+ .filter((u) => !sel.excluded.includes(u.id))
536
+ .filter((u) => (u.parentUnitIds ?? []).some((parent) => pickedSessions.has(parent)))
537
+ .map((u) => u.id)
538
+ if (ids.length > 0) {
539
+ only.push('attachments')
540
+ // 一律给白名单:即使本次要的正好是清单全集,也把「哪些对象」写死在请求里,
541
+ // 免得将来清单里多出一个没人引用的孤儿时被整分区口径顺带带走。
542
+ includeItems.attachments = ids
543
+ partial = true
544
+ }
545
+ }
546
+ }
501
547
  return partial ? { only, includeItems } : { only }
502
548
  }
503
549
 
@@ -680,8 +726,17 @@ export type SessionWorkspaceCouplingFocus = 'sessions' | 'workspaces' | 'both'
680
726
  * 反向刻意不加(勾着工作区、会话清单没读):那种状态下会话单元根本不在选择器里,没有需要联动的会话。
681
727
  */
682
728
  export function couplingInventorySections(sections: readonly SectionId[]): SectionId[] {
683
- if (!sections.includes('sessions') || sections.includes('workspaces')) return [...sections]
684
- return [...sections, 'workspaces']
729
+ if (!sections.includes('sessions')) return [...sections]
730
+ const out = [...sections]
731
+ // 工作区:会话单元上的 sessionIds / projectKey 是「会话属于哪个工作区」的唯一数据源(见上)
732
+ if (!out.includes('workspaces')) out.push('workspaces')
733
+ /**
734
+ * 附件:会话行下面的附件子树(G5)只能由**附件分区的单元清单**渲染出来 —— 那份清单里的
735
+ * `parentUnitIds` 是宿主读会话日志算出的归属。不一起拉,界面上就只有光秃秃的会话行,
736
+ * 用户会以为「这些会话没有附件」(比看不见更糟的失败形态:确信的错误)。
737
+ */
738
+ if (!out.includes('attachments')) out.push('attachments')
739
+ return out
685
740
  }
686
741
 
687
742
  /** 两份选择是否等价(按集合;用于「清单到货后补一次联动」避免无谓写库 / 自激渲染)。 */
@@ -747,6 +802,199 @@ export function applySessionWorkspaceCoupling(
747
802
  return next
748
803
  }
749
804
 
805
+ /* ----------------------------------------------------------------------------------
806
+ 会话 → 附件子树(G5):附件挂在「用过它的那条会话」下面
807
+ ---------------------------------------------------------------------------------- */
808
+
809
+ /**
810
+ * 父单元 id → 挂在它下面的子单元(渲染与勾选联动共用同一份索引)。
811
+ *
812
+ * 子单元可能属于**别的分区**(附件单元属于 attachments、父是 sessions 单元):这是本仓库里
813
+ * 唯一的跨分区逐行嵌套,所以索引必须由调用方现算,而不是塞进分区的 `group`(那个只做同分区二级分组,
814
+ * 且不参与勾选契约)。
815
+ */
816
+ export function childUnitsOf(nodes: SelectionSection[]): Map<string, SelectionUnit[]> {
817
+ const out = new Map<string, SelectionUnit[]>()
818
+ for (const node of nodes) {
819
+ for (const unit of node.units) {
820
+ for (const parent of unit.parentUnitIds ?? []) {
821
+ const list = out.get(parent)
822
+ if (list === undefined) out.set(parent, [unit])
823
+ else list.push(unit)
824
+ }
825
+ }
826
+ }
827
+ return out
828
+ }
829
+
830
+ /**
831
+ * 会话「父对话 → 子代理会话」的挂载索引(A5):会话区里子代理不再平铺,而是缩进在父对话行下面。
832
+ *
833
+ * 只认**能在同一份清单里找到父行**的子会话:父对话被搜索过滤掉、或不在当前分区时,子会话留在顶层。
834
+ * 宁可平铺也不让它凭空消失 —— 看不见的单元就是勾不上的单元(勾选与包内容必须一一对应)。
835
+ */
836
+ export function sessionChildUnits(nodes: SelectionSection[]): Map<string, SelectionUnit[]> {
837
+ const out = new Map<string, SelectionUnit[]>()
838
+ const sessions = nodes.filter((n) => n.section === 'sessions').flatMap((n) => n.units)
839
+ if (sessions.length === 0) return out
840
+ const byBare = new Map<string, SelectionUnit>()
841
+ for (const unit of sessions) {
842
+ const bare = sessionIdOfUnit(unit.id)
843
+ if (bare !== undefined) byBare.set(sessionIdKey(bare), unit)
844
+ }
845
+ for (const unit of sessions) {
846
+ const parentBare = unit.parentSessionId
847
+ if (parentBare === undefined) continue
848
+ const parent = byBare.get(sessionIdKey(parentBare))
849
+ // 自指(父 == 自己)不挂:坏元数据不能把一行缩进到自己下面
850
+ if (parent === undefined || parent.id === unit.id) continue
851
+ const list = out.get(parent.id)
852
+ if (list === undefined) out.set(parent.id, [unit])
853
+ else list.push(unit)
854
+ }
855
+ return out
856
+ }
857
+
858
+ /**
859
+ * 已经挂在某父行下面的子单元 id(分区自己那一排不再重复列这些行,否则一个附件/一条子代理会话会出现两次)。
860
+ *
861
+ * 两类来源:跨分区的附件子行(parentUnitIds)与会话区内的子代理会话(parentSessionId)。
862
+ * 只收**真能找到父行**的那些 —— 与 sessionChildUnits 同一判据,否则单元会既不在顶层、也不在子行。
863
+ */
864
+ export function nestedChildUnitIds(nodes: SelectionSection[]): Set<string> {
865
+ const out = new Set<string>()
866
+ for (const node of nodes) {
867
+ for (const unit of node.units) {
868
+ if ((unit.parentUnitIds?.length ?? 0) > 0) out.add(unit.id)
869
+ }
870
+ }
871
+ for (const children of sessionChildUnits(nodes).values()) {
872
+ for (const child of children) out.add(child.id)
873
+ }
874
+ return out
875
+ }
876
+
877
+ /**
878
+ * 会话 ↔ 附件联动(G5):勾会话连带它用到的附件,取消会话连带取消,单个附件仍可单独取消。
879
+ *
880
+ * 三条设计要点:
881
+ * ① **按「实际发生变化的会话」逐条应用**,不只看用户点的那一个:父↔子会话联动会连带翻动别的会话
882
+ * (勾父自动勾上它的子代理会话)、勾子行又会连带勾上父对话(`applyChildUnitParentCoupling`),
883
+ * 那些会话的附件也必须跟着走,否则界面上「会话勾着、附件没勾」;
884
+ * ② 附件侧的每次改动都走 `toggleUnit()`:分区成员、稀疏排除、取消后「本分区已无选中」的反向收口
885
+ * 都由那一套语义决定,这里不另写一份(写两份必然分叉);
886
+ * ③ **批量动作也跑**(2026-11-21 起):组行有了自己的勾选框,勾「附件」组要连带父对话,
887
+ * 而父对话一被勾上就必须带上它**全部**附件 —— 否则界面(只勾了组里那几条)与包内容
888
+ * (导出请求按被勾对话推导全量附件白名单)不一致。代价可控:只对**状态真的翻动**的会话
889
+ * 逐条 `toggleUnit`,勾整个分区时 before === after ⇒ 循环里全部 `continue`,零额外写入。
890
+ */
891
+ export function applySessionAttachmentCoupling(
892
+ before: Selection,
893
+ after: Selection,
894
+ nodes: SelectionSection[],
895
+ ): Selection {
896
+ const children = childUnitsOf(nodes)
897
+ if (children.size === 0) return after
898
+ const sessionUnits = nodes.filter((n) => n.section === 'sessions').flatMap((n) => n.units)
899
+ if (sessionUnits.length === 0) return after
900
+ const sectionOf = new Map<string, SectionId>()
901
+ for (const node of nodes) for (const unit of node.units) sectionOf.set(unit.id, node.section)
902
+ /** 稀疏表示下「未排除」不等于「已选」(整个分区没勾时也是未排除),与其它联动函数同口径。
903
+ 用 Set 预建两份快照:万级排除集时逐条 `includes` 会让每次点击都慢几十毫秒。 */
904
+ const snapshot = (state: Selection): { sections: Set<SectionId>; excluded: Set<string> } => ({
905
+ sections: new Set(state.sections),
906
+ excluded: new Set(state.excluded),
907
+ })
908
+ const wasOn = snapshot(before)
909
+ const nowOn = snapshot(after)
910
+ const isOn = (set: { sections: Set<SectionId>; excluded: Set<string> }, unitId: string): boolean => {
911
+ const section = sectionOf.get(unitId)
912
+ return section !== undefined && set.sections.has(section) && !set.excluded.has(unitId)
913
+ }
914
+ let out = after
915
+ for (const unit of sessionUnits) {
916
+ const was = isOn(wasOn, unit.id)
917
+ const now = isOn(nowOn, unit.id)
918
+ if (was === now) continue
919
+ for (const child of children.get(unit.id) ?? []) out = toggleUnit(out, nodes, child.id, now)
920
+ }
921
+ return out
922
+ }
923
+
924
+ /**
925
+ * 子行 → 父行联动(A3,2026-11-21 用户要求):勾子代理会话或附件时,把它所属的父对话一起勾上。
926
+ *
927
+ * 为什么必须有这条:附件子行挂在会话行下面(`parentUnitIds`),而导出请求按「哪些对话被勾选」
928
+ * 推导附件白名单(`buildExportRequest`)—— 只勾附件、不勾父对话,等于点了没反应(包里不会带它)。
929
+ *
930
+ * 方向口径与 `applySessionParentCoupling` 一致,**只做正向**:
931
+ * - 勾选子行 → 沿 `parentUnitIds` 向上勾齐父链,并把父链上每一条的**全部子单元**一起勾上
932
+ * (父对话被勾上就等于带它的全部附件,与「勾会话带附件」同一口径,界面与包内容因此一致);
933
+ * - 取消子行 → 不动父(用户明确要求「取消子行不反向取消父对话」);取消父的整棵子树由
934
+ * `applySessionParentCoupling` 负责。
935
+ *
936
+ * `change` 缺省(分区/分组/全选等批量动作)只做正向闭包,绝不取消任何东西。
937
+ */
938
+ export function applyChildUnitParentCoupling(
939
+ sel: Selection,
940
+ nodes: SelectionSection[],
941
+ change?: SessionParentChange,
942
+ ): Selection {
943
+ const children = childUnitsOf(nodes)
944
+ if (children.size === 0) return sel
945
+ const byId = new Map<string, SelectionUnit>()
946
+ const sectionOf = new Map<string, SectionId>()
947
+ for (const node of nodes) {
948
+ for (const unit of node.units) {
949
+ byId.set(unit.id, unit)
950
+ sectionOf.set(unit.id, node.section)
951
+ }
952
+ }
953
+ /** 子单元 id → 父单元 id。父不在清单里(跨分区清单没读全)就整条忽略 —— 不猜归属。 */
954
+ const parentsOf = new Map<string, string[]>()
955
+ for (const unit of byId.values()) {
956
+ const parents = (unit.parentUnitIds ?? []).filter((id) => byId.has(id))
957
+ if (parents.length > 0) parentsOf.set(unit.id, parents)
958
+ }
959
+ if (parentsOf.size === 0) return sel
960
+ const picked = (state: Selection, unitId: string): boolean => {
961
+ const section = sectionOf.get(unitId)
962
+ return section !== undefined && state.sections.includes(section) && !state.excluded.includes(unitId)
963
+ }
964
+ /**
965
+ * 从 startId 向上补父链,父被勾上时连带它的全部子单元。
966
+ * `seen` 由调用方跨多次 lift 共享:批量模式下同一棵子树只走一遍
967
+ * (本机 1411 个附件 × 84 个兄弟,不共享会退化成 O(n²))。
968
+ */
969
+ const lift = (state: Selection, startId: string, seen: Set<string>): Selection => {
970
+ let out = state
971
+ const queue: string[] = [startId]
972
+ while (queue.length > 0) {
973
+ const id = queue.shift()
974
+ if (id === undefined || seen.has(id)) continue
975
+ seen.add(id)
976
+ for (const parentId of parentsOf.get(id) ?? []) {
977
+ if (!picked(out, parentId)) out = toggleUnit(out, nodes, parentId, true)
978
+ for (const sibling of children.get(parentId) ?? []) {
979
+ if (!picked(out, sibling.id)) out = toggleUnit(out, nodes, sibling.id, true)
980
+ }
981
+ queue.push(parentId)
982
+ }
983
+ }
984
+ return out
985
+ }
986
+ if (change === undefined) {
987
+ let out = sel
988
+ const seen = new Set<string>()
989
+ for (const id of parentsOf.keys()) {
990
+ if (!picked(out, id)) continue
991
+ out = lift(out, id, seen)
992
+ }
993
+ return out
994
+ }
995
+ return change.checked ? lift(sel, change.unitId, new Set<string>()) : sel
996
+ }
997
+
750
998
  export function filterSections(nodes: SelectionSection[], query: string): SelectionSection[] {
751
999
  const q = query.trim().toLowerCase()
752
1000
  if (q === '') return nodes
@@ -843,7 +1091,13 @@ export function sectionsFromPlan(plan: ImportPlan): SelectionSection[] {
843
1091
  id: unitId,
844
1092
  // 宿主给的展示名优先(sessions 的会话标题);缺省退回单元 id 剥前缀(会话目录名)
845
1093
  label: item.label ?? unitLabel(unitId, item.adapter),
1094
+ // 副标题(附件的短哈希):宿主在计划项里给了就透传,缺省不进模型(不能写 undefined 键)
1095
+ ...(item.detail !== undefined ? { detail: item.detail } : {}),
846
1096
  ...(item.group !== undefined ? { group: item.group } : {}),
1097
+ // 展示嵌套与勾选联动的两个归属字段:导入侧宿主(attachments.analyzeImport)与
1098
+ // sessions 的父会话关系都靠它们 —— 不透传就等于导入树里既没有子行、也没有联动。
1099
+ ...(item.parentUnitIds !== undefined ? { parentUnitIds: item.parentUnitIds } : {}),
1100
+ ...(item.parentSessionId !== undefined ? { parentSessionId: item.parentSessionId } : {}),
847
1101
  ...(item.sessionIds !== undefined ? { sessionIds: item.sessionIds } : {}),
848
1102
  ...(item.projectKey !== undefined ? { projectKey: item.projectKey } : {}),
849
1103
  ...(item.blank === true ? { blank: true } : {}),
@@ -0,0 +1,67 @@
1
+ /** P3 单测:UI 事实层(框架无关,node 可测)。 */
2
+ import assert from 'node:assert/strict';
3
+ import test from 'node:test';
4
+
5
+ import {
6
+ sessionCompareAttentionRows,
7
+ sessionCompareFactsFromAnalysis,
8
+ sessionCompareFactsFromPlan,
9
+ sessionCompareVerdictKey,
10
+ } from './session-compare-facts.ts';
11
+ import type { ImportAnalysis, PlanItem, SessionCompareRow } from '../core/types.ts';
12
+
13
+ function analysisWith(rows: SessionCompareRow[], extra: Partial<NonNullable<ImportAnalysis['sessionCompare']>> = {}): Pick<ImportAnalysis, 'sessionCompare'> {
14
+ return {
15
+ sessionCompare: { rows, skipped: 0, attachmentsReferenced: 0, attachmentsMissing: [], ...extra },
16
+ };
17
+ }
18
+
19
+ const ROWS: SessionCompareRow[] = [
20
+ { unitId: 'p/a', verdict: 'identical', packEvents: 3, localEvents: 3 },
21
+ { unitId: 'p/b', verdict: 'localAhead', packEvents: 3, localEvents: 9, localAheadBy: 6 },
22
+ { unitId: 'p/c', verdict: 'diverged', packEvents: 4, localEvents: 5, localAheadBy: 2, packAheadBy: 1 },
23
+ { unitId: 'p/d', verdict: 'new', packEvents: 2, localEvents: 0 },
24
+ ];
25
+
26
+ test('P3-UI-1 分析结果 → 五态计数与覆盖量(new 映射成 fresh)', () => {
27
+ const facts = sessionCompareFactsFromAnalysis(analysisWith(ROWS));
28
+ assert.ok(facts !== null);
29
+ assert.equal(facts.compared, 4);
30
+ assert.deepEqual(facts.counts, { identical: 1, packAhead: 0, localAhead: 1, diverged: 1, fresh: 1, unreadable: 0 });
31
+ assert.deepEqual(facts.overwrite, { units: 2, events: 8 });
32
+ assert.equal(facts.lossy, true);
33
+ });
34
+
35
+ test('P3-UI-2 缺省 ≠ 一致:没有比对结果返回 null,绝不返回全零事实', () => {
36
+ assert.equal(sessionCompareFactsFromAnalysis(null), null);
37
+ assert.equal(sessionCompareFactsFromAnalysis({}), null);
38
+ assert.equal(sessionCompareFactsFromAnalysis({ sessionCompare: undefined }), null);
39
+ });
40
+
41
+ test('P3-UI-3 只有一致项时 lossy=false;附件缺失单独也能让它为真', () => {
42
+ const clean = sessionCompareFactsFromAnalysis(analysisWith([ROWS[0] as SessionCompareRow]));
43
+ assert.equal(clean?.lossy, false);
44
+ const missing = sessionCompareFactsFromAnalysis(
45
+ analysisWith([ROWS[0] as SessionCompareRow], { attachmentsReferenced: 3, attachmentsMissing: ['sha256:aa'] }),
46
+ );
47
+ assert.equal(missing?.lossy, true);
48
+ assert.equal(missing?.attachmentsReferenced, 3);
49
+ assert.deepEqual(missing?.attachmentsMissing, ['sha256:aa']);
50
+ });
51
+
52
+ test('P3-UI-4 计划项 → 同一口径;没有 sessionVerdict 的项不算已比对', () => {
53
+ const items = [
54
+ { id: 'sessions:p/b', kind: 'Update', adapter: 'sessions', target: '', sessionVerdict: { verdict: 'localAhead', packEvents: 3, localEvents: 9, localAheadBy: 6 } },
55
+ { id: 'sessions:p/a', kind: 'Update', adapter: 'sessions', target: '' },
56
+ ] as unknown as PlanItem[];
57
+ const facts = sessionCompareFactsFromPlan(items);
58
+ assert.equal(facts?.compared, 1);
59
+ assert.deepEqual(facts?.overwrite, { units: 1, events: 6 });
60
+ assert.equal(sessionCompareFactsFromPlan([]), null);
61
+ });
62
+
63
+ test('P3-UI-5 关注行只列覆盖/分叉,按会被覆盖的条数降序', () => {
64
+ const rows = sessionCompareAttentionRows(analysisWith(ROWS));
65
+ assert.deepEqual(rows.map((r) => r.unitId), ['p/b', 'p/c']);
66
+ assert.equal(sessionCompareVerdictKey('fresh'), 'import.sessionCompare.verdict.fresh');
67
+ });