dsh-memu-memory 1.4.2 → 1.4.3

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 (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +169 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
@@ -1,1728 +1,2008 @@
1
- // A settings pane that throws during render shows up as a blank panel with no
2
- // error anywhere — exactly what happened when an effect referenced a callback
3
- // declared further down (temporal dead zone). This harness runs the real client
4
- // component with a minimal hook runtime, so a render-time throw fails the build
5
- // instead of silently blanking the UI. Every page is rendered, because a block
6
- // only runs when its page is selected.
7
- import test from 'node:test'
8
- import assert from 'node:assert/strict'
9
- import fs from 'node:fs'
10
-
11
- const registrations = []
12
-
13
- function makeElement(type, props, ...children) {
14
- return { type, props: { ...(props || {}), children: children.length <= 1 ? children[0] : children } }
15
- }
16
-
17
- let hooks = []
18
- let cursor = 0
19
- let effects = []
20
- let dirty = false
21
- let forced = null
22
- let generation = 0
23
-
24
- const React = {
25
- createElement: makeElement,
26
- Fragment: Symbol('Fragment'),
27
- useState(initial) {
28
- const index = cursor++
29
- // A setter captured by a component from an earlier test must not write into
30
- // the hook array this test is using: async effects from a previous render can
31
- // resolve late, and without this the second test renders with the first one's
32
- // state.
33
- const generation_ = generation
34
- if (hooks[index] === undefined) hooks[index] = typeof initial === 'function' ? initial() : initial
35
- if (forced && forced.index === index) hooks[index] = forced.value
36
- return [hooks[index], (next) => {
37
- if (generation_ !== generation) return
38
- hooks[index] = typeof next === 'function' ? next(hooks[index]) : next
39
- dirty = true
40
- }]
41
- },
42
- memo: (component) => component,
43
- useCallback: (fn) => fn,
44
- useMemo: (fn) => fn(),
45
- useEffect(fn, deps) { effects.push({ fn, deps, index: cursor++ }) },
46
- useLayoutEffect() {},
47
- useRef: (value) => ({ current: value }),
48
- useSyncExternalStore: (_subscribe, getSnapshot) => getSnapshot(),
49
- }
50
-
51
- globalThis.window = {
52
- __ModuleLoader__: {
53
- load({ factory }) {
54
- globalThis.__dshMemuExports = factory((name) => {
55
- if (name === 'react') return React
56
- throw new Error(`unexpected require: ${name}`)
57
- })
58
- },
59
- },
60
- // The overlay listens for its close message and for Escape.
61
- addEventListener() {},
62
- removeEventListener() {},
63
- }
64
- // The WebUI button falls back to an in-app overlay when popups are blocked; the
65
- // stub records what got attached so the test can assert the current tab is never
66
- // navigated (that would unload the app and look like a forced refresh).
67
- const appendedNodes = []
68
- globalThis.document = {
69
- createElement: (tag) => {
70
- const node = {
71
- tag,
72
- style: {},
73
- attrs: {},
74
- children: [],
75
- href: '',
76
- textContent: '',
77
- setAttribute(name, value) { node.attrs[name] = value },
78
- addEventListener() {},
79
- appendChild(child) { node.children.push(child); return child },
80
- remove() { node.removed = true },
81
- click() { node.clicked = true },
82
- }
83
- return node
84
- },
85
- querySelector: () => null,
86
- addEventListener() {},
87
- removeEventListener() {},
88
- head: { appendChild() {} },
89
- body: { appendChild(node) { appendedNodes.push(node); return node } },
90
- }
91
-
92
- await import('../lib/client.js')
93
-
94
- const EMPTY_STATE = {
95
- engine: { status: 'ready', versions: [], currentVersion: '0.11.0b3', recommendedVersion: '0.11.0b3', installed: true, state: {} },
96
- settings: { autoInject: 'smart', mustRememberCap: 16, unpinBudgetPerSession: 2 },
97
- libraries: [],
98
- archivedLibraries: [],
99
- memuConfig: { provider: 'openai' },
100
- summaryConfig: {},
101
- binding: null,
102
- privateCount: 0,
103
- pinnedCount: 0,
104
- globalCount: 0,
105
- jobs: [],
106
- }
107
-
108
- const RPC_ANSWERS = {
109
- getState: EMPTY_STATE,
110
- getSettingsState: EMPTY_STATE,
111
- getPrompts: { prompts: [
112
- { key: 'system-guide', title: 'guide', description: '', variables: ['mustRememberCap'], source: 'default', text: 'a', scope: 'private', domain: null },
113
- { key: 'system-guide.rp', title: 'guide rp', description: '', variables: [], source: 'default', text: 'b', scope: 'private', domain: 'rp' },
114
- { key: 'global-curator', title: 'curator', description: '', variables: ['input'], source: 'default', text: 'c', scope: 'global', domain: null },
115
- ] },
116
- listVersions: { ok: true, versions: [] },
117
- listBackups: { backups: [] },
118
- listFolders: { folders: [] },
119
- listLibraries: { libraries: [] },
120
- listSessions: { sessions: [] },
121
- getSidebarState: {
122
- binding: { sessionId: 'probe-session', libraryId: 'lib-1', useLibrary: true, useGlobal: true, scopeKey: '/proj/demo', domain: 'coding' },
123
- domain: 'coding',
124
- folder: { scopeKey: '/proj/demo', useLibrary: true, useGlobal: true },
125
- effective: { useLibrary: true, useGlobal: true, enabled: true, folder: { scopeKey: '/proj/demo', useLibrary: true, useGlobal: true } },
126
- private: { items: [], active: 0, pinned: 0, total: 0 },
127
- global: { items: [], active: 0, total: 0 },
128
- domains: ['rp', 'coding'],
129
- },
130
- jobStatus: null,
131
- }
132
-
133
- function fakeCtx({ answers = {}, rpcCalls = [] } = {}) {
134
- return {
135
- effect: (fn) => { try { fn() } catch {} },
136
- locale: { register: () => () => {}, bind: () => (key) => key, get: () => 'zh' },
137
- connection: {
138
- rpc: {
139
- call: async (path, endpoint, payload) => {
140
- rpcCalls.push({ path, endpoint, payload })
141
- if (typeof answers[endpoint] === 'function') return answers[endpoint](payload)
142
- return { ok: true, value: answers[endpoint] ?? RPC_ANSWERS[endpoint] ?? {} }
143
- },
144
- },
145
- },
146
- sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: {}, ids: [] }) } },
147
- // The sidebar tab asks for the current conversation through one of these.
148
- get: (name) => (name === 'uiSession'
149
- ? { adapter: { current: { getSnapshot: () => ({ key: 'probe-session' }) } } }
150
- : undefined),
151
- slots: {
152
- inject: (_name, callback) => callback(scope),
153
- register: (spec, component) => { registrations.push({ slot: spec.name, id: spec.id, component }); return () => {} },
154
- },
155
- inject: (_deps, callback) => callback({
156
- // Run the effect body: that is where the tab body registers itself.
157
- effect: (fn) => { try { fn() } catch {} },
158
- sidebarRightTabs: { register: () => () => {} },
159
- get: () => undefined,
160
- }),
161
- }
162
- }
163
-
164
- const scope = {
165
- effect: (fn) => { try { fn() } catch {} },
166
- register: (spec, component) => { registrations.push({ slot: spec.name, id: spec.id, component }); return () => {} },
167
- inject: (_deps, callback) => callback(scope),
168
- }
169
-
170
- async function renderPage(component, props, pageValue, { remount = false } = {}) {
171
- if (remount) { hooks = []; generation++ }
172
- effects = []
173
- cursor = 0
174
- forced = pageValue === undefined ? null : { index: pageHookIndex, value: pageValue }
175
- const tree = component(props)
176
- assert.ok(tree, 'component rendered nothing')
177
- return { tree, effects }
178
- }
179
-
180
- let pageHookIndex = -1
181
-
182
- function collectPageHook() {
183
- // The page state is the only one initialised to the number 0.
184
- const zeroes = hooks.map((value, index) => (value === 0 ? index : -1)).filter((index) => index >= 0)
185
- assert.equal(zeroes.length, 1, 'expected exactly one numeric-zero state (the page index)')
186
- pageHookIndex = zeroes[0]
187
- }
188
-
189
- function treeText(node, depth = 0) {
190
- if (node === null || node === undefined || depth > 400) return ''
191
- if (typeof node === 'string' || typeof node === 'number') return String(node)
192
- if (Array.isArray(node)) return node.map((child) => treeText(child, depth + 1)).join(' ')
193
- // Function components are expanded so their bodies are exercised too — a throw
194
- // inside Section/Button counts the same as one inside the page.
195
- if (typeof node.type === 'function') return treeText(node.type(node.props), depth + 1)
196
- return `${node.props?.className || ''} ${treeText(node.props?.children, depth + 1)}`
197
- }
198
-
199
- test('the settings page renders every page instead of a blank panel', async () => {
200
- const ctx = fakeCtx()
201
- globalThis.__dshMemuExports.apply(ctx)
202
- const settings = registrations.find((r) => r.slot === 'settings.section')
203
- assert.ok(settings?.component, 'settings.section was not registered')
204
-
205
- // First render: state is still null, which is the loading branch.
206
- const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
207
- collectPageHook()
208
- assert.match(treeText(first.tree), /loading|dshm-settings/)
209
-
210
- // Let the mount effects fetch and settle, then render with data. Hooks survive
211
- // between renders, which is how the fetched state reaches the next pass.
212
- for (const effect of first.effects) effect.fn()
213
- await new Promise((resolve) => setTimeout(resolve, 0))
214
- await new Promise((resolve) => setTimeout(resolve, 0))
215
-
216
- // 14 页(含新增的关系图谱 graph:10 与诊断页 diagnostics:14);help 仍是最后一页,未纳入这轮巡检。
217
- for (let page = 0; page < 14; page++) {
218
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, page)
219
- const text = treeText(tree)
220
- assert.match(String(tree.props?.className), /dshm-root/, `page ${page} did not render the shell`)
221
- // The rail is the nav: every page label has to be there. Counting the shared
222
- // dshm-nav-item class instead would also pick up the in-page tab strips (memory
223
- // backend, prompt scope, browser view), which use the same widget on purpose.
224
- const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageGraph', 'pageLogs', 'pageLexicon', 'pageDiagnostics']
225
- assert.ok(NAV.every((key) => text.includes(key)), `page ${page} lost a nav entry`)
226
- assert.equal((text.match(/dshm-nav-ind/g) || []).length, 1, `page ${page} lost or duplicated its rail indicator`)
227
- assert.match(text, /dshm-page/, `page ${page} lost the content pane`)
228
- // Passing a labels map where an id was expected stringifies to this, which is
229
- // exactly how the sidebar domain picker broke.
230
- assert.ok(!text.includes('[object Object]'), `page ${page} rendered an object as text`)
231
- }
232
- })
233
-
234
- async function graphStudioHarness(call, libraries) {
235
- const ctx = fakeCtx()
236
- globalThis.__dshMemuExports.apply(ctx)
237
- const settings = registrations.filter(row => row.slot === 'settings.section').pop()
238
- const shell = await withHash('#/settings/graph', async () => {
239
- const props = { ctx, t: key => key, standalone: true }
240
- const first = await renderPage(settings.component, props, undefined, { remount: true })
241
- for (const effect of first.effects) effect.fn()
242
- await new Promise(resolve => setTimeout(resolve, 0))
243
- return (await renderPage(settings.component, props)).tree
244
- })
245
- let studio
246
- walkNodes(shell, node => { if (node.type?.name === 'GraphStudioPanel') { studio = node; return false } })
247
- assert.ok(studio, 'graph studio not found')
248
- const props = { ...studio.props, t: key => key, call, libraries }
249
- const previous = new Map()
250
- const pick = (tree, predicate) => {
251
- const found = []
252
- const visit = node => {
253
- if (!node || typeof node !== 'object') return
254
- if (Array.isArray(node)) { node.forEach(visit); return }
255
- if (predicate(node)) found.push(node)
256
- if (typeof node.type !== 'function') visit(node.props?.children)
257
- }
258
- visit(tree)
259
- return found
260
- }
261
- let first = true
262
- const render = async (flush = false) => {
263
- let view = await renderPage(studio.type, props, undefined, { remount: first })
264
- first = false
265
- if (flush) {
266
- for (const effect of view.effects) {
267
- const old = previous.get(effect.index)
268
- if (old && effect.deps?.length === old.deps?.length && effect.deps?.every((value, i) => Object.is(value, old.deps[i]))) continue
269
- old?.cleanup?.()
270
- previous.set(effect.index, { deps: effect.deps, cleanup: effect.fn() })
271
- }
272
- await new Promise(resolve => setTimeout(resolve, 0))
273
- view = await renderPage(studio.type, props)
274
- }
275
- return view.tree
276
- }
277
- return { render, pick, close: () => { for (const value of previous.values()) value.cleanup?.() } }
278
- }
279
-
280
- test('graph studio pages all libraries and filters custom domains without merging identities', async () => {
281
- const libraries = [{ id: 'lib-a', name: 'A' }, { id: 'lib-b', name: 'B' }], calls = []
282
- const call = async (endpoint, payload) => {
283
- calls.push({ endpoint, payload })
284
- if (endpoint === 'getMemory') return { entry: { title: 'B editable', content: 'B full body' } }
285
- if (endpoint !== 'getGraph') return { items: [] }
286
- const domain = payload.libraryId === 'lib-a' ? 'coding' : 'project:travel'
287
- const memories = Array.from({ length: payload.libraryId === 'lib-a' ? 201 : 1 }, (_, i) => ({
288
- id: i ? 'mem-' + i : 'mem-shared', title: payload.libraryId + '-memory-' + i, kind: 'memory', domain,
289
- }))
290
- const nodes = payload.domain && payload.domain !== domain ? [] : [...memories, { id: 'ent-shared', title: payload.libraryId + '-person', kind: 'person' }]
291
- const offset = payload.offset || 0, next = offset + 200
292
- return { nodes: nodes.slice(offset, next), edges: !offset && nodes.length ? [{ from: 'mem-shared', to: 'ent-shared', kind: 'person' }] : [],
293
- nextOffset: next < nodes.length ? next : null, domains: ['coding', 'project:travel'] }
294
- }
295
- const view = await graphStudioHarness(call, libraries)
296
- try {
297
- let tree = await view.render(true)
298
- view.pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
299
- tree = await view.render(true)
300
- const canvas = () => view.pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph
301
- assert.equal(canvas().nodes.length, 204)
302
- assert.equal(canvas().nodes.filter(node => node.kind === 'person').length, 2)
303
- assert.equal(new Set(canvas().nodes.map(node => node.id)).size, 204)
304
- assert.equal(canvas().edges.length, 2)
305
- for (const edge of canvas().edges) assert.equal(canvas().nodes.find(node => node.id === edge.from).libraryId, canvas().nodes.find(node => node.id === edge.to).libraryId)
306
- assert.ok(calls.some(row => row.payload.libraryId === 'lib-a' && row.payload.offset === 200))
307
- view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: ' PROJECT:travel ' } })
308
- tree = await view.render(true)
309
- assert.equal(canvas().nodes.length, 2)
310
- assert.ok(canvas().nodes.every(node => node.libraryId === 'lib-b'))
311
- assert.ok(calls.some(row => row.payload.domain === 'project:travel'))
312
- view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: 'project:travel' } })
313
- tree = await view.render(true)
314
- assert.equal(canvas().nodes.length, 2, 'equivalent domain input must not clear the graph')
315
- view.pick(tree, node => node.type === 'button' && node.props.children === 'gsManage')[0].props.onClick()
316
- tree = await view.render()
317
- const rows = view.pick(tree, node => String(node.props?.className || '').split(' ').includes('dshm-gs-mgr-row'))
318
- assert.equal(rows.length, 2, 'management uses the same domain filter')
319
- rows.find(row => treeText(row).includes('lib-b-memory-0')).props.onClick()
320
- tree = await view.render()
321
- view.pick(tree, node => node.type === 'button' && node.props['aria-label'] === 'gsEditNode')[0].props.onClick()
322
- await new Promise(resolve => setTimeout(resolve, 0))
323
- assert.deepEqual(calls.find(row => row.endpoint === 'getMemory').payload, { libraryId: 'lib-b', id: 'mem-shared' })
324
- tree = await view.render()
325
- view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: '' } })
326
- tree = await view.render(true)
327
- assert.equal(canvas().nodes.length, 204)
328
- } finally { view.close() }
329
- })
330
-
331
- test('the whole-workspace graph sends its domain filter to the global endpoint', async () => {
332
- const calls = []
333
- const call = async (endpoint, payload) => {
334
- calls.push({ endpoint, payload })
335
- if (endpoint !== 'getGraph') return { items: [] }
336
- const wanted = 'project:travel'
337
- const hit = !payload.domain || payload.domain === wanted
338
- return {
339
- scope: 'global',
340
- nodes: hit ? [{ id: 'mem-g-1', title: 'global memory', kind: 'global', domain: 'project:travel' }] : [],
341
- edges: [],
342
- domains: ['general', 'project:travel'],
343
- }
344
- }
345
- // 没有私有库时面板落在全局图:这条路径走的是 getGlobalGraph,不是逐库合并。
346
- const view = await graphStudioHarness(call, [])
347
- try {
348
- let tree = await view.render(true)
349
- view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0]
350
- .props.onChange({ target: { value: 'project:travel' } })
351
- tree = await view.render(true)
352
- const asked = calls.filter(row => row.endpoint === 'getGraph')
353
- const last = asked[asked.length - 1]
354
- assert.equal(last.payload.scope, 'global', 'the panel stayed on the global graph')
355
- assert.equal(last.payload.domain, 'project:travel', 'the global branch forwards the domain filter')
356
- const datalist = view.pick(tree, node => node.type === 'datalist' && node.props?.id === 'dshm-graph-domains')[0]
357
- const options = []
358
- const visit = (value) => {
359
- if (Array.isArray(value)) { value.forEach(visit); return }
360
- if (value && value.type === 'option') options.push(String(value.props?.value ?? ''))
361
- }
362
- if (datalist) visit([].concat(datalist.props?.children ?? []))
363
- assert.deepEqual(options, ['rp', 'coding', 'general', 'mixed', 'project:travel'].sort(),
364
- 'the datalist keeps every domain the server reported, not only the filtered one')
365
- } finally { view.close() }
366
- })
367
-
368
- test('graph studio surfaces failed libraries and retains successful results', async () => { const call = async (endpoint, payload) => {
369
- if (endpoint !== 'getGraph') return { items: [] }
370
- if (payload.libraryId === 'lib-denied') throw new Error('forbidden')
371
- return { nodes: [{ id: 'mem-ok', title: 'visible', kind: 'memory' }], edges: [], nextOffset: null }
372
- }
373
- const view = await graphStudioHarness(call, [{ id: 'lib-ok', name: 'OK' }, { id: 'lib-denied', name: 'Denied library' }])
374
- try {
375
- let tree = await view.render(true)
376
- view.pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
377
- tree = await view.render(true)
378
- assert.equal(view.pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.nodes.length, 1)
379
- assert.match(treeText(view.pick(tree, node => node.props?.role === 'alert')[0]), /gsLoadPartial.*Denied library/)
380
- } finally { view.close() }
381
- })
382
-
383
- test('the immersive graph shell stays with the standalone WebUI', async () => {
384
- // 点「关系图谱」把宿主页面的导航条掰成 158px 竖排,是 is-graph-wide 没分外壳造成的:
385
- // 那套样式是为独立 WebUI 的全屏画布写的,宿主设置页只需要普通横排导航 + 一个入口按钮。
386
- const ctx = fakeCtx()
387
- globalThis.__dshMemuExports.apply(ctx)
388
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
389
- assert.ok(settings?.component, 'settings.section was not registered')
390
- const GRAPH_PAGE = 10
391
-
392
- // The standalone shell resolves its page from the hash, so there is no
393
- // numeric-zero page state to force on; the host shell has one.
394
- const shell = async (props, { fromHash = false } = {}) => {
395
- const first = await renderPage(settings.component, props, undefined, { remount: true })
396
- if (!fromHash) collectPageHook()
397
- for (const effect of first.effects) effect.fn()
398
- await new Promise((resolve) => setTimeout(resolve, 0))
399
- return (await renderPage(settings.component, props, fromHash ? undefined : GRAPH_PAGE)).tree
400
- }
401
-
402
- const inHost = await shell({ ctx, t: (key) => key })
403
- assert.match(String(inHost.props?.className), /dshm-root/, 'the host graph page lost its shell')
404
- assert.ok(!/is-graph-wide/.test(String(inHost.props?.className)),
405
- `the host settings page must keep its horizontal rail, saw "${inHost.props?.className}"`)
406
- const buttons = []
407
- walkNodes(inHost, (node) => { if (node.type === 'button' && node.props?.children === 'openGraphStudio') buttons.push(node) })
408
- assert.equal(buttons.length, 1, 'the host graph page should offer exactly one entry into the studio')
409
- assert.equal(typeof buttons[0].props.onClick, 'function', 'the entry button has no handler')
410
-
411
- const inWebUi = await withHash('#/settings/graph', () => shell({ ctx, t: (key) => key, standalone: true }, { fromHash: true }))
412
- assert.match(String(inWebUi.props?.className), /is-graph-wide/, 'the standalone graph page lost its immersive shell')
413
- })
414
-
415
- test('the manual consolidation button rides the sidebar channel, not a new RPC', async () => {
416
- // 「立即整理」刻意不新增方法:它查 listSessions 的库绑定,再对每个绑定会话调用
417
- // 侧边栏同一个 generatePrivate。多一个只给 UI 用的整理方法,就等于多一条模型也能
418
- // 调用的写路径。
419
- const rpcCalls = []
420
- const ctx = fakeCtx({
421
- rpcCalls,
422
- answers: {
423
- getState: { ...RPC_ANSWERS.getState, libraries: [{ id: 'lib-1', name: 'L1', privateCount: 3, pinnedCount: 0, boundSessions: 2 }] },
424
- getSettingsState: { ...RPC_ANSWERS.getSettingsState, libraries: [{ id: 'lib-1', name: 'L1', privateCount: 3, pinnedCount: 0, boundSessions: 2 }] },
425
- listSessions: { sessions: [
426
- { id: 's1', libraryId: 'lib-1' }, { id: 's2', libraryId: 'lib-1' }, { id: 's3', libraryId: 'lib-2' },
427
- ] },
428
- generatePrivate: { ok: true },
429
- },
430
- })
431
- globalThis.__dshMemuExports.apply(ctx)
432
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
433
- const props = { ctx, t: (key) => key }
434
- const LIBRARIES_PAGE = 4
435
- const render = async (page, remount = false) => renderPage(settings.component, props, page, { remount })
436
- const first = await render(undefined, true)
437
- collectPageHook()
438
- for (const effect of first.effects) effect.fn()
439
- await new Promise((resolve) => setTimeout(resolve, 0))
440
- const second = await render(LIBRARIES_PAGE)
441
- for (const effect of second.effects) effect.fn()
442
- await new Promise((resolve) => setTimeout(resolve, 0))
443
- const tree = (await render(LIBRARIES_PAGE)).tree
444
-
445
- const buttons = []
446
- walkNodes(tree, (node) => { if (node.type === 'button' && node.props?.children === 'consolidateNow') buttons.push(node) })
447
- assert.equal(buttons.length, 1, 'the library row lost its 立即整理 button')
448
- rpcCalls.length = 0
449
- await buttons[0].props.onClick()
450
- assert.deepEqual(rpcCalls, [], 'the first click must only arm the confirmation')
451
- const armed = []
452
- walkNodes((await render(LIBRARIES_PAGE)).tree, (node) => { if (node.type === 'button' && node.props?.children === 'confirmAction') armed.push(node) })
453
- assert.equal(armed.length, 1, 'the arming state did not reach the button label')
454
- await armed[0].props.onClick()
455
- for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0))
456
- assert.deepEqual(rpcCalls.map((c) => [c.endpoint, c.payload]), [
457
- ['listSessions', { limit: 200 }],
458
- ['generatePrivate', { sessionId: 's1' }],
459
- ['generatePrivate', { sessionId: 's2' }],
460
- ], 'consolidation must hit only the sessions bound to that library')
461
- })
462
-
463
- // The standalone shell reads `window.location.hash` to pick its page and rewrites
464
- // it as the user navigates, which the host-side fixture never provides.
465
- async function withHash(hash, run) {
466
- const original = globalThis.window.location
467
- const originalHistory = globalThis.window.history
468
- globalThis.window.location = { ...original, hash }
469
- globalThis.window.history = { ...originalHistory, replaceState: () => {} }
470
- try { return await run() } finally {
471
- globalThis.window.location = original
472
- globalThis.window.history = originalHistory
473
- }
474
- }
475
-
476
- test('the sidebar tab renders with the two-layer header', async () => {
477
- const ctx = fakeCtx()
478
- const tab = registrations.find((r) => r.slot === 'sidebar.right.pane.tab')
479
- assert.ok(tab?.component, 'sidebar.right.pane.tab was not registered')
480
-
481
- // The registered body is a thin wrapper around MemoryTab; hooks only run in the
482
- // inner component, so unwrap it before rendering.
483
- const props = { ctx, t: (key) => key, sessionId: 'probe-session' }
484
- const wrapper = tab.component(props)
485
- const component = typeof wrapper.type === 'function' ? wrapper.type : tab.component
486
- const innerProps = typeof wrapper.type === 'function' ? wrapper.props : props
487
-
488
- hooks = []
489
- pageHookIndex = -1
490
- const first = await renderPage(component, innerProps, undefined, { remount: true })
491
- assert.ok(first.tree, 'sidebar tab rendered nothing')
492
-
493
- // Feed the fetched state back in, the same way the host would.
494
- for (const effect of first.effects) effect.fn()
495
- await new Promise((resolve) => setTimeout(resolve, 0))
496
- await new Promise((resolve) => setTimeout(resolve, 0))
497
-
498
- const { tree } = await renderPage(component, innerProps)
499
- const text = treeText(tree)
500
- assert.match(text, /layerFolder|layerConversation|noBinding|loading/, 'sidebar lost its two-layer header')
501
- assert.ok(!text.includes('[object Object]'), 'sidebar rendered an object as text')
502
- // The domain picker lists ids, translated through the label map.
503
- assert.match(text, /dmCoding/, 'domain picker did not render its options')
504
- })
505
-
506
- test('the sidebar context-scope card cannot be flex-shrunk and keeps a two-column field grid', () => {
507
- const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
508
- assert.match(src, /className: 'dshm-tab-body'/, 'the sidebar body needs its non-shrinking class')
509
- assert.match(src, /\.dshm-tab-body>\*\{flex-shrink:0\}/, 'sidebar sections must scroll instead of shrinking')
510
- assert.match(src, /\.dshm-scope\{width:100%;margin:0 0 10px;[^}]*flex-shrink:0/, 'the scope card must span the sidebar content width and not collapse')
511
- assert.match(src, /\.dshm-scope-form\{[^}]*grid-template-columns:repeat\(2,minmax\(0,1fr\)\)/, 'four scope fields must wrap into two readable columns')
512
- })
513
-
514
- test('consolidation alerts keep identity separate from actions when expanded', async () => {
515
- const ctx = fakeCtx()
516
- globalThis.__dshMemuExports.apply(ctx)
517
- const tab = registrations.filter((r) => r.slot === 'sidebar.right.pane.tab').pop()
518
- const wrapped = tab.component({ ctx, t: (key) => key, sessionId: 'probe-session' })
519
- const first = await renderPage(wrapped.type, wrapped.props, undefined, { remount: true })
520
- for (const effect of first.effects) effect.fn()
521
- await new Promise((resolve) => setTimeout(resolve, 0))
522
- const sidebar = (await renderPage(wrapped.type, wrapped.props)).tree
523
- let alerts
524
- walkNodes(sidebar, (node) => {
525
- if (node.type?.name === 'ConsolidationAlerts') { alerts = node.type; return false }
526
- })
527
- assert.ok(alerts)
528
- const failure = { id: 'failure', sessionId: 's1', sessionTitle: 'A long conversation title', message: 'An unbroken failure message'.repeat(12), at: '2026-11-17T16:59:33Z' }
529
- const success = { ...failure, id: 'success', message: 'done' }
530
- const jumps = []
531
- let cleared = 0
532
- const props = { feed: { failures: [failure], successes: [success] }, t: (key) => key, onJump: row => jumps.push(row.id), onClear: () => cleared++ }
533
- const nodes = (tree, className) => {
534
- const found = []
535
- walkNodes(tree, node => { if (node.props?.className === className) found.push(node) })
536
- return found
537
- }
538
- let tree = (await renderPage(alerts, props, undefined, { remount: true })).tree
539
- assert.equal(nodes(tree, 'dshm-consolidation-row').length, 1)
540
- nodes(tree, 'dshm-consolidation-head')[0].props.onClick()
541
- tree = (await renderPage(alerts, props)).tree
542
- assert.equal(nodes(tree, 'dshm-consolidation-column').length, 2)
543
- const rows = nodes(tree, 'dshm-consolidation-row')
544
- assert.equal(rows.length, 2)
545
- for (const row of rows) {
546
- assert.equal(row.props.children[0].props.className, 'dshm-consolidation-identity')
547
- assert.equal(row.props.children[1].props.className, 'dshm-consolidation-meta')
548
- assert.equal(nodes(row, 'dshm-consolidation-label')[0].props.title, failure.sessionTitle)
549
- assert.equal(nodes(row, 'dshm-consolidation-time').length, 1)
550
- }
551
- const buttons = []
552
- walkNodes(tree, node => { if (node.type === 'button') buttons.push(node) })
553
- buttons.find(node => node.props.title === 'consolidateJumpHint').props.onClick()
554
- buttons.find(node => node.props.title === 'consolidateClearHint').props.onClick()
555
- assert.deepEqual(jumps, ['failure'])
556
- assert.equal(cleared, 1)
557
- assert.ok(!treeText(tree).includes('consolidateStarted'))
558
- })
559
-
560
- test('consolidation alert columns wrap before their controls must be clipped', () => {
561
- const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
562
- assert.match(src, /\.dshm-consolidation-columns\{[^}]*grid-template-columns:repeat\(auto-fit,minmax\(min\(100%,240px\),1fr\)\)/)
563
- assert.match(src, /\.dshm-consolidation-meta\{[^}]*flex-wrap:wrap/)
564
- assert.match(src, /\.dshm-consolidation-column-head\{[^}]*flex-wrap:wrap/)
565
- assert.match(src, /\.dshm-consolidation-label\{[^}]*text-overflow:ellipsis/)
566
- assert.doesNotMatch(src, /\.dshm-consolidation-row\{[^}]*overflow:hidden/)
567
- })
568
-
569
- test('the memory UI renders the read-only arousal/dominance/emotionSource line', () => {
570
- const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
571
- for (const key of ['arousalLabel', 'dominanceLabel', 'emotionSourceLabel', 'emotionSourceModel', 'emotionSourceSession', 'emotionSourceContent', 'emotionSourceUnknown']) {
572
- assert.ok(src.includes(key), `missing ${key}`)
573
- }
574
- assert.match(src, /emotionMetaText\(f, t\)/, 'the card tag must expose affect metadata in its title')
575
- assert.match(src, /emotionMetaText\(shown, t\)/, 'the drawer must render the read-only affect line')
576
- })
577
-
578
- test('the sidebar run log keeps five rows and links its header to the WebUI logs page', () => {
579
- const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
580
- // 侧栏只显示正常流水(失败由「整理提醒」负责),列表仍是最近 5 条。
581
- assert.match(src, /runLog\.filter\(\(row\) => logRowState\(row\) !== 'failed'\)/, 'the sidebar run log must drop failed rows')
582
- assert.match(src, /sidebarRuns\.slice\(0, 5\)/, 'the sidebar shows the five newest runs, not an unbounded list')
583
- assert.match(src, /openWebUiPage\('logs'\)/, 'the run-log header must open the WebUI logs page')
584
- assert.match(src, /runLogOpen/, 'the jump needs a visible label')
585
- // 红色只属于 WebUI 的总日志页:侧栏整段不过 logRowClass(失败行已被过滤),
586
- // 判据仍集中在 logRowState 一处,改口径只改那一处。
587
- assert.equal((src.match(/className: logRowClass\(row\)/g) || []).length, 1, 'only the WebUI logs page marks row state')
588
- assert.ok(src.includes('const sidebarRuns = runLog.filter('), 'the sidebar must filter failed rows before rendering')
589
- assert.ok(!/tone: row\.level === 'error' \? 'warn'/.test(src), 'the old level-only predicate must not come back')
590
- })
591
-
592
- // The browser row is the only place a human can see that a memory is marked
593
- // "never say this out loud" or "secret" without opening the JSON. The badges are
594
- // driven by fields that used to be stored and ignored, so a regression here is
595
- // silent: the data stays correct and the warning disappears.
596
- function walkNodes(node, visit, depth = 0) {
597
- if (node === null || node === undefined || depth > 400) return
598
- if (Array.isArray(node)) {
599
- for (const child of node) walkNodes(child, visit, depth + 1)
600
- return
601
- }
602
- if (typeof node !== 'object') return
603
- if (visit(node, depth) === false) return
604
- if (typeof node.type === 'function') {
605
- walkNodes(node.type(node.props), visit, depth + 1)
606
- return
607
- }
608
- walkNodes(node.props?.children, visit, depth + 1)
609
- }
610
-
611
- test('the memory browser badges what a memory is allowed to say', async () => {
612
- const ctx = fakeCtx()
613
- const originalGetState = RPC_ANSWERS.getState
614
- const originalSettingsState = RPC_ANSWERS.getSettingsState
615
- const originalLibraries = RPC_ANSWERS.listLibraries
616
- const loaded = {
617
- ...EMPTY_STATE,
618
- libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 2 }],
619
- }
620
- // The pane reads the library list through both endpoints depending on the page.
621
- RPC_ANSWERS.getState = loaded
622
- RPC_ANSWERS.getSettingsState = loaded
623
- RPC_ANSWERS.browseLibrary = {
624
- source: 'engine',
625
- files: [
626
- {
627
- id: 'mem-quiet',
628
- title: 'the attic',
629
- content: 'he never told his brother',
630
- layer: 'short_term',
631
- status: 'active',
632
- decay: 0.5,
633
- disclosure: 'never_say',
634
- visibility: 'secret',
635
- owner: 'about_user',
636
- // 相对时间,不写死当天某一刻:短条目一旦过期就变成 inactive,行内编辑器不再渲染,
637
- // 这条测试就会在下午闪红(曾经 pin 在 2026-11-01T09:30Z)。它要断言的是「草稿看得到
638
- // 自己什么时候死」,所以留出 6 小时余量即可。
639
- expiresAt: new Date(Date.now() + 6 * 3600 * 1000).toISOString(),
640
- },
641
- { id: 'mem-loud', title: 'shared fact', content: 'anything', layer: 'long_term', status: 'active', decay: 0.9, disclosure: 'can_tell', visibility: 'shared', owner: 'me' },
642
- ],
643
- }
644
- try {
645
- globalThis.__dshMemuExports.apply(ctx)
646
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
647
- assert.ok(settings?.component, 'settings.section was not registered')
648
-
649
- const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
650
- collectPageHook()
651
- for (const effect of first.effects) effect.fn()
652
- await new Promise((resolve) => setTimeout(resolve, 0))
653
- await new Promise((resolve) => setTimeout(resolve, 0))
654
-
655
- // Open the library the way a click would: pick it, then press reload.
656
- let tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
657
- const picker = []
658
- walkNodes(tree, (node) => {
659
- // The layer picker of the new-memory form is also a <select>; only this one
660
- // lists libraries.
661
- const options = Array.isArray(node.props?.children) ? node.props.children : []
662
- if (node.type === 'select' && options.some((option) => option?.props?.value === 'lib-1')) picker.push(node)
663
- })
664
- assert.equal(picker.length, 1, 'the library picker did not render')
665
- picker[0].props.onChange({ target: { value: 'lib-1' } })
666
-
667
- tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
668
- const reload = []
669
- walkNodes(tree, (node) => {
670
- if (typeof node.type === 'function' && node.props?.children === 'reload') reload.push(node)
671
- })
672
- assert.equal(reload.length, 1, 'the reload button did not render')
673
- reload[0].props.onClick()
674
- await new Promise((resolve) => setTimeout(resolve, 0))
675
- await new Promise((resolve) => setTimeout(resolve, 0))
676
-
677
- tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
678
- const text = treeText(tree)
679
- // Every row carries three editor selects, so each enum label also appears in the
680
- // option lists: two rows = 2 occurrences. A badge is the third.
681
- const count = (needle) => text.split(needle).length - 1
682
- assert.match(text, /layerShortTerm/, 'a short-term entry renders its layer instead of an empty tag')
683
- assert.equal(count('discNeverSay'), 3, 'never_say is visible without opening the entry')
684
- assert.equal(count('discCanTell'), 2, 'the default say-ability stays quiet — options only')
685
- assert.equal(count('visSecret'), 3, 'a secret is flagged while scanning')
686
- assert.equal(count('visShared'), 2, 'and so does the default visibility')
687
- assert.equal(count('ownerAboutUser'), 3, 'whose fact it is shows up too')
688
- assert.equal(count('shortTermExpires'), 1, 'and a draft shows when it dies')
689
- assert.ok(!text.includes('[object Object]'), 'a badge rendered an object as text')
690
- } finally {
691
- RPC_ANSWERS.getState = originalGetState
692
- RPC_ANSWERS.getSettingsState = originalSettingsState
693
- RPC_ANSWERS.listLibraries = originalLibraries
694
- delete RPC_ANSWERS.browseLibrary
695
- }
696
- })
697
-
698
- test('the memory browser decides pending reviews in place', async () => {
699
- // 待复核条目在浏览页的复核池里就有接受/丢弃按钮,不必绕去全局页队列;
700
- // 点击走的是同一个 resolveReview RPC,带本库 libraryId。
701
- const rpcCalls = []
702
- const ctx = fakeCtx({ rpcCalls })
703
- const originalGetState = RPC_ANSWERS.getState
704
- const originalSettingsState = RPC_ANSWERS.getSettingsState
705
- const loaded = {
706
- ...EMPTY_STATE,
707
- libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 1 }],
708
- }
709
- RPC_ANSWERS.getState = loaded
710
- RPC_ANSWERS.getSettingsState = loaded
711
- RPC_ANSWERS.browseLibrary = {
712
- source: 'engine',
713
- files: [
714
- { id: 'mem-pending', title: 'pending fact', content: 'awaiting a human', layer: 'long_term', status: 'pending_review', decay: 0.5, disclosure: 'can_tell', visibility: 'shared' },
715
- { id: 'mem-active', title: 'settled fact', content: 'already true', layer: 'long_term', status: 'active', decay: 0.9, disclosure: 'can_tell', visibility: 'shared' },
716
- ],
717
- }
718
- RPC_ANSWERS.resolveReview = { id: 'mem-pending', status: 'active', resolution: 'replace' }
719
- RPC_ANSWERS.listReviews = { items: [] }
720
- try {
721
- globalThis.__dshMemuExports.apply(ctx)
722
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
723
- const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
724
- collectPageHook()
725
- for (const effect of first.effects) effect.fn()
726
- await new Promise((resolve) => setTimeout(resolve, 0))
727
- await new Promise((resolve) => setTimeout(resolve, 0))
728
-
729
- let tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
730
- const picker = []
731
- walkNodes(tree, (node) => {
732
- const options = Array.isArray(node.props?.children) ? node.props.children : []
733
- if (node.type === 'select' && options.some((option) => option?.props?.value === 'lib-1')) picker.push(node)
734
- })
735
- picker[0].props.onChange({ target: { value: 'lib-1' } })
736
- tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
737
- const reload = []
738
- walkNodes(tree, (node) => {
739
- if (typeof node.type === 'function' && node.props?.children === 'reload') reload.push(node)
740
- })
741
- reload[0].props.onClick()
742
- await new Promise((resolve) => setTimeout(resolve, 0))
743
- await new Promise((resolve) => setTimeout(resolve, 0))
744
-
745
- // 切到复核池:页签文案是 poolReview + 计数。
746
- tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
747
- const reviewTab = []
748
- walkNodes(tree, (node) => {
749
- if (node.type === 'button' && String(node.props?.children || '').startsWith('poolReview')) reviewTab.push(node)
750
- })
751
- assert.equal(reviewTab.length, 1, 'the review pool tab did not render')
752
- reviewTab[0].props.onClick()
753
- tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
754
- const buttons = []
755
- walkNodes(tree, (node) => {
756
- if (typeof node.type === 'function' && (node.props?.children === 'accept' || node.props?.children === 'reject')) buttons.push(node)
757
- })
758
- assert.equal(buttons.length, 2, 'the pending row offers exactly accept and reject')
759
- const accept = buttons.find((node) => node.props.children === 'accept')
760
- accept.props.onClick()
761
- await new Promise((resolve) => setTimeout(resolve, 0))
762
- await new Promise((resolve) => setTimeout(resolve, 0))
763
- const resolved = rpcCalls.filter((call) => call.endpoint === 'resolveReview')
764
- assert.equal(resolved.length, 1, 'accept fires exactly one resolveReview')
765
- assert.equal(resolved[0].payload.id, 'mem-pending')
766
- assert.equal(resolved[0].payload.libraryId, 'lib-1')
767
- assert.equal(resolved[0].payload.action, 'accept')
768
- } finally {
769
- RPC_ANSWERS.getState = originalGetState
770
- RPC_ANSWERS.getSettingsState = originalSettingsState
771
- delete RPC_ANSWERS.browseLibrary
772
- delete RPC_ANSWERS.resolveReview
773
- delete RPC_ANSWERS.listReviews
774
- }
775
- })
776
-
777
- test('the memory wall drawer decides pending reviews without leaving the wall', async () => {
778
- const rpcCalls = []
779
- const ctx = fakeCtx({ rpcCalls })
780
- const originalGetState = RPC_ANSWERS.getState
781
- const originalSettingsState = RPC_ANSWERS.getSettingsState
782
- const loaded = {
783
- ...EMPTY_STATE,
784
- libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 1 }],
785
- }
786
- RPC_ANSWERS.getState = loaded
787
- RPC_ANSWERS.getSettingsState = loaded
788
- RPC_ANSWERS.browseWall = {
789
- total: 1,
790
- items: [{ id: 'mem-pending', libraryId: 'lib-1', libraryName: 'demo', title: 'pending fact', preview: 'awaiting a human', layer: 'long_term', status: 'pending_review', source: 'inferred', decay: 0.5, tags: [] }],
791
- }
792
- RPC_ANSWERS.getMemory = { id: 'mem-pending', libraryId: 'lib-1', entry: { title: 'pending fact', content: 'awaiting a human', status: 'pending_review', layer: 'long_term', disclosure: 'can_tell' }, attachments: [] }
793
- RPC_ANSWERS.resolveReview = { id: 'mem-pending', status: 'active', resolution: 'replace' }
794
- try {
795
- globalThis.__dshMemuExports.apply(ctx)
796
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
797
- const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
798
- collectPageHook()
799
- for (const effect of first.effects) effect.fn()
800
- await new Promise((resolve) => setTimeout(resolve, 0))
801
- await new Promise((resolve) => setTimeout(resolve, 0))
802
-
803
- let tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
804
- // 墙的数据加载在 MemoryWallPanel 自己的 effect 里:展开子组件登记 effect 再执行。
805
- treeText(tree)
806
- for (const effect of effects) effect.fn()
807
- await new Promise((resolve) => setTimeout(resolve, 0))
808
- await new Promise((resolve) => setTimeout(resolve, 0))
809
- tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
810
- // 墙默认看活跃池;待复核条目在复核池,先切池再找卡片。
811
- const poolTab = []
812
- walkNodes(tree, (node) => {
813
- if (node.type === 'button' && String(node.props?.children || '').startsWith('poolReview')) poolTab.push(node)
814
- })
815
- assert.equal(poolTab.length, 1, 'the wall review pool tab did not render')
816
- poolTab[0].props.onClick()
817
- tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
818
- const cards = []
819
- walkNodes(tree, (node) => {
820
- if (node.type === 'button' && String(node.props?.className || '').includes('dshm-wall-item')) cards.push(node)
821
- })
822
- assert.equal(cards.length, 1, 'the pending card did not render on the wall')
823
- cards[0].props.onClick()
824
- await new Promise((resolve) => setTimeout(resolve, 0))
825
- await new Promise((resolve) => setTimeout(resolve, 0))
826
-
827
- tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
828
- const buttons = []
829
- walkNodes(tree, (node) => {
830
- if (typeof node.type === 'function' && (node.props?.children === 'accept' || node.props?.children === 'reject')) buttons.push(node)
831
- })
832
- assert.equal(buttons.length, 2, 'the drawer offers accept and reject for a pending review')
833
- buttons.find((node) => node.props.children === 'reject').props.onClick()
834
- await new Promise((resolve) => setTimeout(resolve, 0))
835
- await new Promise((resolve) => setTimeout(resolve, 0))
836
- const resolved = rpcCalls.filter((call) => call.endpoint === 'resolveReview')
837
- assert.equal(resolved.length, 1, 'reject fires exactly one resolveReview')
838
- assert.equal(resolved[0].payload.id, 'mem-pending')
839
- assert.equal(resolved[0].payload.libraryId, 'lib-1')
840
- assert.equal(resolved[0].payload.action, 'reject')
841
- } finally {
842
- RPC_ANSWERS.getState = originalGetState
843
- RPC_ANSWERS.getSettingsState = originalSettingsState
844
- delete RPC_ANSWERS.browseWall
845
- delete RPC_ANSWERS.getMemory
846
- delete RPC_ANSWERS.resolveReview
847
- }
848
- })
849
-
850
- test('the browse search box filters the loaded library in place', async () => {
851
- // 搜索是纯前端的:它只过滤已经拉回来的那一页,不新发 RPC。库一切换就清空,
852
- // 否则上一个库的关键词会把当前库筛成「空库」。
853
- const originalGetState = RPC_ANSWERS.getState
854
- const originalSettingsState = RPC_ANSWERS.getSettingsState
855
- const loaded = { ...EMPTY_STATE, libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 2 }] }
856
- RPC_ANSWERS.getState = loaded
857
- RPC_ANSWERS.getSettingsState = loaded
858
- RPC_ANSWERS.browseLibrary = {
859
- source: 'engine',
860
- files: [
861
- { id: 'mem-attic', title: 'the attic', content: 'he never told his brother', layer: 'long_term', status: 'active', decay: .5 },
862
- { id: 'mem-loud', title: 'shared fact', content: 'anything', layer: 'long_term', status: 'active', decay: .9 },
863
- ],
864
- }
865
- try {
866
- const rpcCalls = []
867
- const ctx = fakeCtx({ rpcCalls })
868
- globalThis.__dshMemuExports.apply(ctx)
869
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
870
- const props = { ctx, t: (key) => key }
871
- const render = (page, remount = false) => renderPage(settings.component, props, page, { remount })
872
- const first = await render(undefined, true)
873
- collectPageHook()
874
- for (const effect of first.effects) effect.fn()
875
- await new Promise((resolve) => setTimeout(resolve, 0))
876
- let tree = (await render(5)).tree
877
- const picker = []
878
- walkNodes(tree, (node) => {
879
- const options = Array.isArray(node.props?.children) ? node.props.children : []
880
- if (node.type === 'select' && options.some((option) => option?.props?.value === 'lib-1')) picker.push(node)
881
- })
882
- picker[0].props.onChange({ target: { value: 'lib-1' } })
883
- tree = (await render(5)).tree
884
- const reload = []
885
- walkNodes(tree, (node) => { if (node.type === 'button' && node.props?.children === 'reload') reload.push(node) })
886
- reload[0].props.onClick()
887
- for (let i = 0; i < 3; i++) await new Promise((resolve) => setTimeout(resolve, 0))
888
- tree = (await render(5)).tree
889
-
890
- // Rows carry their title in an editor input, so counting rendered values beats
891
- // grepping the flattened tree.
892
- const snapshot = (node) => {
893
- const titles = []
894
- let rows = 0
895
- walkNodes(node, (n) => {
896
- if (n.type === 'button' && n.props?.children === 'archive') rows++
897
- if (n.type === 'input' && (n.props?.value === 'the attic' || n.props?.value === 'shared fact')) titles.push(n.props.value)
898
- })
899
- return { rows, titles }
900
- }
901
-
902
- const before = snapshot(tree)
903
- assert.deepEqual(before, { rows: 2, titles: ['the attic', 'shared fact'] }, 'both rows render before filtering')
904
- rpcCalls.length = 0
905
- const box = []
906
- walkNodes(tree, (node) => { if (node.type === 'input' && node.props?.placeholder === 'browseSearchPlaceholder') box.push(node) })
907
- assert.equal(box.length, 1, 'no search box under 当前记忆库')
908
- box[0].props.onChange({ target: { value: 'attic' } })
909
- const filteredTree = (await render(5)).tree
910
- assert.deepEqual(snapshot(filteredTree), { rows: 1, titles: ['the attic'] }, 'the filter keeps only the matching row')
911
- assert.match(treeText(filteredTree), /1 \/ 2/, 'the counter says how much of the library the filter kept')
912
- assert.match(treeText(filteredTree), /browseActiveTab \(1\)/, 'the tab counts follow the filter, not the whole library')
913
- assert.deepEqual(rpcCalls, [], 'filtering an already loaded library must not re-fetch it')
914
- box[0].props.onChange({ target: { value: 'no-such-memory' } })
915
- assert.match(treeText((await render(5)).tree), /browseActiveTab \(0\)/, 'a query that matches nothing empties the tab counts')
916
- const clear = []
917
- walkNodes((await render(5)).tree, (node) => { if (node.type === 'button' && node.props?.children === 'browseSearchClear') clear.push(node) })
918
- assert.equal(clear.length, 1, 'no way to clear the query')
919
- clear[0].props.onClick()
920
- assert.deepEqual(snapshot((await render(5)).tree), before, 'clearing the query brings the library back')
921
- } finally {
922
- RPC_ANSWERS.getState = originalGetState
923
- RPC_ANSWERS.getSettingsState = originalSettingsState
924
- delete RPC_ANSWERS.browseLibrary
925
- }
926
- })
927
-
928
- test('the WebUI buttons open a new tab and never navigate this one', async () => {
929
- const opened = []
930
- const navigated = []
931
- const originalWindow = { open: globalThis.window.open, location: globalThis.window.location }
932
- globalThis.window.location = { href: 'http://host/app', assign: (url) => navigated.push(url) }
933
- try {
934
- const ctx = fakeCtx()
935
- globalThis.__dshMemuExports.apply(ctx)
936
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
937
- assert.ok(settings?.component, 'settings.section was not registered')
938
-
939
- const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
940
- collectPageHook()
941
- for (const effect of first.effects) effect.fn()
942
- await new Promise((resolve) => setTimeout(resolve, 0))
943
- await new Promise((resolve) => setTimeout(resolve, 0))
944
-
945
- const buttons = []
946
- walkNodes((await renderPage(settings.component, { ctx, t: (key) => key }, 0)).tree, (node) => {
947
- if (node.type === 'button' && node.props?.children === 'openMemu') buttons.push(node)
948
- })
949
- assert.equal(buttons.length, 1, 'the WebUI button did not render')
950
-
951
- globalThis.window.open = (url) => { opened.push(url); return { focus() {}, opener: null } }
952
- buttons[0].props.onClick()
953
- assert.equal(opened.length, 1, 'a popup was requested')
954
- assert.ok(opened[0].includes('/dsh-memu-memory/ui') && /[?&]theme=(light|dark)/.test(opened[0]) && opened[0].endsWith('#/settings/engine'), `unexpected url: ${opened[0]}`)
955
- assert.deepEqual(navigated, [], 'no fallback navigation while the popup works')
956
-
957
- // Blocked popups return null: fall back to an in-app overlay. Navigating this
958
- // tab would unload the app and look like a forced refresh on the way back.
959
- appendedNodes.length = 0
960
- globalThis.window.open = () => null
961
- buttons[0].props.onClick()
962
- assert.equal(appendedNodes.length, 1, 'blocked popups open an in-app overlay')
963
- const overlay = appendedNodes[0]
964
- assert.equal(overlay.attrs['data-dsh-memu-memory-webui'], '', 'the overlay is marked')
965
- const frame = overlay.children.find((child) => child.tag === 'iframe')
966
- assert.ok(frame, 'the overlay hosts an iframe')
967
- assert.ok(String(frame.src).includes('/dsh-memu-memory/ui') && /[?&]theme=(light|dark)/.test(String(frame.src)) && String(frame.src).endsWith('#/settings/engine'), `unexpected url: ${frame.src}`)
968
- assert.deepEqual(navigated, [], 'the current tab is never navigated')
969
- // The close control lives inside the page; the overlay only waits for its message.
970
- assert.equal(overlay.children.length, 1, 'no floating chrome outside the panel')
971
- } finally {
972
- globalThis.window.open = originalWindow.open
973
- globalThis.window.location = originalWindow.location
974
- }
975
- })
976
-
977
- test('the sidebar and the settings page hand out the same WebUI button', async () => {
978
- // Two spellings of one action is how the panes drift: the sidebar used to label
979
- // this button openSettingsShort while the settings page used openWebUi. Both
980
- // surfaces now render the same widget with the same label, hint and handler, and
981
- // the embedded settings page drops its own copy so the sidebar never shows two.
982
- async function renderSurface(component, props, page) {
983
- hooks = []
984
- pageHookIndex = -1
985
- const first = await renderPage(component, props, page, { remount: true })
986
- if (page !== undefined) collectPageHook()
987
- for (const effect of first.effects) effect.fn()
988
- await new Promise((resolve) => setTimeout(resolve, 0))
989
- await new Promise((resolve) => setTimeout(resolve, 0))
990
- const tree = (await renderPage(component, props, page)).tree
991
- const found = []
992
- walkNodes(tree, (node) => {
993
- if (node.type === 'button' && node.props?.children === 'openMemu') found.push(node)
994
- })
995
- return { tree, found }
996
- }
997
-
998
- const ctx = fakeCtx()
999
- globalThis.__dshMemuExports.apply(ctx)
1000
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1001
- const tab = registrations.filter((r) => r.slot === 'sidebar.right.pane.tab').pop()
1002
- assert.ok(settings?.component && tab?.component, 'both surfaces are registered')
1003
-
1004
- const inSettings = await renderSurface(settings.component, { ctx, t: (key) => key }, 0)
1005
- assert.equal(inSettings.found.length, 1, 'the settings page lost its WebUI button')
1006
-
1007
- const props = { ctx, t: (key) => key, sessionId: 'probe-session' }
1008
- const wrapper = tab.component(props)
1009
- const inner = typeof wrapper.type === 'function' ? wrapper.type : tab.component
1010
- const innerProps = typeof wrapper.type === 'function' ? wrapper.props : props
1011
- const inSidebar = await renderSurface(inner, innerProps, undefined)
1012
- assert.equal(inSidebar.found.length, 1, 'the sidebar lost its WebUI button')
1013
- assert.ok(!treeText(inSidebar.tree).includes('openSettings'), 'a second settings entry must not return')
1014
-
1015
- // The panel returns early while the conversation is still unknown, before its
1016
- // `pages` array is built. Effects scheduled by that render still run, and one of
1017
- // them reads `pages` — touching it then is a temporal-dead-zone error that the
1018
- // sidebar surfaces as "dsh-better-sidebar: Cannot access 'pages' before
1019
- // initialization". Rendering without a session must stay quiet.
1020
- for (const empty of [null, undefined]) {
1021
- const quiet = await renderSurface(inner, { ...innerProps, sessionId: empty }, undefined)
1022
- assert.ok(treeText(quiet.tree).includes('loading'), 'the unbound panel shows its loading state')
1023
- }
1024
-
1025
- for (const node of [...inSettings.found, ...inSidebar.found]) {
1026
- assert.equal(node.props.className, 'dshm-btn', 'the button bypasses the shared widget')
1027
- assert.equal(node.props.title, 'openWebUiHint', 'the button carries a different hint')
1028
- assert.equal(typeof node.props.onClick, 'function', 'the button has no handler')
1029
- }
1030
- // The old keys are gone rather than kept around as a second spelling.
1031
- const text = `${treeText(inSettings.tree)} ${treeText(inSidebar.tree)}`
1032
- assert.ok(!text.includes('openSettingsShort'), 'the second WebUI label came back')
1033
- })
1034
-
1035
- test('every pick-one-of-these control uses the same tab strip', async () => {
1036
- // The settings rail, the prompt scope, the browser's active/archived split and
1037
- // the memory backend are one widget (dshm-nav-item). They used to be three
1038
- // widgets with three different hover and focus states, which is what read as
1039
- // "the sidebar and the settings page do not match".
1040
- const ctx = fakeCtx()
1041
- globalThis.__dshMemuExports.apply(ctx)
1042
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1043
-
1044
- const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
1045
- collectPageHook()
1046
- for (const effect of first.effects) effect.fn()
1047
- await new Promise((resolve) => setTimeout(resolve, 0))
1048
- await new Promise((resolve) => setTimeout(resolve, 0))
1049
-
1050
- const orphans = []
1051
- for (let page = 0; page < 12; page++) {
1052
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, page)
1053
- walkNodes(tree, (node) => {
1054
- if (node.type !== 'button') return
1055
- const className = String(node.props?.className || '')
1056
- if (node.props?.role === 'tab' && !className.includes('dshm-nav-item')) {
1057
- orphans.push(`page ${page}: ${JSON.stringify(node.props?.children)}`)
1058
- }
1059
- if (className.includes('dshm-nav-item')) {
1060
- assert.equal(typeof node.props.onClick, 'function', `page ${page} lost a tab handler`)
1061
- }
1062
- })
1063
- }
1064
- assert.deepEqual(orphans, [], 'a tab strip sits outside the shared widget')
1065
- })
1066
-
1067
- // Task C: the statistics page is data-driven, so it only paints after two lazy
1068
- // loads (pick the first library, then read its stats). The charts are hand-written
1069
- // SVG — counting nodes is the honest check that thirty bars and one dot per memory
1070
- // actually reached the DOM, and that an empty day did not become NaN.
1071
- test('the statistics page draws the daily bars, the scatter and the shortlist', async () => {
1072
- const ctx = fakeCtx()
1073
- const originalState = RPC_ANSWERS.getSettingsState
1074
- RPC_ANSWERS.getSettingsState = {
1075
- ...EMPTY_STATE,
1076
- libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo' }],
1077
- }
1078
- RPC_ANSWERS.getStats = {
1079
- libraryId: 'lib-1',
1080
- available: true,
1081
- keptDays: 90,
1082
- windowDays: 30,
1083
- days: Array.from({ length: 30 }, (_, i) => ({
1084
- date: `2026-09-${String(i + 1).padStart(2, '0')}`,
1085
- written: i === 29 ? 2 : 0,
1086
- injected: i % 3,
1087
- recalled: 0,
1088
- archived: 0,
1089
- })),
1090
- totals: { written: 2, injected: 30, recalled: 4, archived: 1 },
1091
- ratio: { windowDays: 7, written: 2, injected: 9 },
1092
- health: { total: 2, active: 2, marginalized: 0, archived: 0, pendingReview: 0, avgStrength: 0.71 },
1093
- distribution: [
1094
- { id: 'mem-a', title: 'often recalled', layer: 'long_term', ageDays: 3, injectCount: 4, accessCount: 2 },
1095
- { id: 'mem-b', title: 'never recalled', layer: 'long_term', ageDays: 9, injectCount: 0, accessCount: 0 },
1096
- ],
1097
- distributionTotal: 2,
1098
- stale: [{ id: 'mem-b', title: 'never recalled', daysSinceTouch: 9 }],
1099
- }
1100
- const run = async (effectsToRun) => {
1101
- for (const effect of effectsToRun) effect.fn()
1102
- await new Promise((resolve) => setTimeout(resolve, 0))
1103
- await new Promise((resolve) => setTimeout(resolve, 0))
1104
- }
1105
- try {
1106
- globalThis.__dshMemuExports.apply(ctx)
1107
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1108
- const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
1109
- collectPageHook()
1110
- await run(first.effects)
1111
-
1112
- let pass = await renderPage(settings.component, { ctx, t: (key) => key }, 8)
1113
- await run(pass.effects)
1114
- pass = await renderPage(settings.component, { ctx, t: (key) => key }, 8)
1115
- await run(pass.effects)
1116
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 8)
1117
-
1118
- const counts = { rects: 0, circles: 0 }
1119
- walkNodes(tree, (node) => {
1120
- if (node.type === 'rect') counts.rects += 1
1121
- if (node.type === 'circle') counts.circles += 1
1122
- })
1123
- assert.equal(counts.rects, 30, 'thirty daily bars, including the quiet days')
1124
- assert.equal(counts.circles, 2, 'one scatter dot per memory')
1125
- const text = treeText(tree)
1126
- assert.match(text, /statsWritten/, 'the window totals render')
1127
- assert.match(text, /statsStaleDays/, 'the archive shortlist renders')
1128
- assert.ok(!text.includes('NaN'), 'an empty day must not paint NaN')
1129
- assert.ok(!text.includes('[object Object]'), 'the page rendered an object as text')
1130
- } finally {
1131
- RPC_ANSWERS.getSettingsState = originalState
1132
- delete RPC_ANSWERS.getStats
1133
- }
1134
- })
1135
-
1136
- test('the memory tab is registered exactly once, with or without better-sidebar', () => {
1137
- function appCtx(initialBetter) {
1138
- const seen = { native: [], better: [], pending: {} }
1139
- let better = initialBetter
1140
- const slotsScope = { effect: (fn) => { try { fn() } catch {} }, register: () => () => {}, inject: (_n, cb) => cb(slotsScope) }
1141
- const scope = {
1142
- effect: (fn) => { const dispose = fn(); return () => { try { dispose?.() } catch {} } },
1143
- get: (name) => (name === 'betterSidebar' ? better : undefined),
1144
- sidebarRightTabs: {
1145
- register: (spec) => {
1146
- seen.native.push(spec)
1147
- return () => { const at = seen.native.indexOf(spec); if (at >= 0) seen.native.splice(at, 1) }
1148
- },
1149
- },
1150
- slots: { inject: (_n, cb) => cb(slotsScope), register: () => () => {} },
1151
- }
1152
- const ctx = {
1153
- effect: () => {},
1154
- locale: { register: () => () => {}, bind: () => (key) => key, get: () => 'zh' },
1155
- connection: { rpc: { call: async () => ({ ok: true, value: {} }) } },
1156
- sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: {}, ids: [] }) } },
1157
- get: (name) => (name === 'betterSidebar' ? better : undefined),
1158
- slots: { inject: (_n, cb) => cb(scope), register: () => () => {} },
1159
- inject: (deps, callback) => {
1160
- const key = deps[0]
1161
- seen.pending[key] = callback
1162
- if (key === 'betterSidebar' && !better) return
1163
- callback(scope)
1164
- },
1165
- }
1166
- return {
1167
- ctx,
1168
- seen,
1169
- later(service) { better = service; seen.pending.betterSidebar(scope) },
1170
- }
1171
- }
1172
-
1173
- let betterCalls = 0
1174
- const betterService = () => ({ registerTab: () => { betterCalls += 1; return () => {} } })
1175
-
1176
- // No better-sidebar: the native tab is the only entry.
1177
- const a = appCtx(null)
1178
- globalThis.__dshMemuExports.apply(a.ctx)
1179
- assert.equal(a.seen.native.length, 1, 'native tab registered when better-sidebar is absent')
1180
- assert.equal(a.seen.better.length, 0)
1181
-
1182
- // Installed up front: only its tab, otherwise the start list shows two.
1183
- const b = appCtx(betterService())
1184
- globalThis.__dshMemuExports.apply(b.ctx)
1185
- assert.equal(b.seen.native.length, 0, 'native tab must not register when better-sidebar exists')
1186
- assert.equal(betterCalls, 1, 'its own tab is registered instead')
1187
-
1188
- // Installed after us: the native tab we already registered has to go.
1189
- const c = appCtx(null)
1190
- globalThis.__dshMemuExports.apply(c.ctx)
1191
- assert.equal(c.seen.native.length, 1)
1192
- let betterRegistrations = 0
1193
- c.later({ registerTab: () => { betterRegistrations += 1; return () => {} } })
1194
- assert.equal(c.seen.native.length, 0, 'late better-sidebar removes the native tab')
1195
- assert.equal(betterRegistrations, 1, 'and registers its own')
1196
- })
1197
-
1198
- // Exercise the actual settings component, not source-text matches: stale vector
1199
- // configuration must not escape the Agent gate, and rendering must never install.
1200
- async function renderVectorSettings(t, overrides = {}, answers = {}, pageValue = 1) {
1201
- const loaded = {
1202
- ...EMPTY_STATE,
1203
- ...overrides,
1204
- settings: { ...EMPTY_STATE.settings, ...overrides.settings },
1205
- memuConfig: { ...EMPTY_STATE.memuConfig, ...overrides.memuConfig },
1206
- }
1207
- const rpcCalls = []
1208
- const ctx = fakeCtx({ answers: { getSettingsState: loaded, ...answers }, rpcCalls })
1209
- globalThis.__dshMemuExports.apply(ctx)
1210
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1211
- assert.ok(settings?.component, 'settings.section was not registered')
1212
- const props = { ctx, t: (key) => key }
1213
- const first = await renderPage(settings.component, props, undefined, { remount: true })
1214
- collectPageHook()
1215
- const cleanups = []
1216
- t.after(() => { for (const cleanup of cleanups.reverse()) cleanup() })
1217
- for (const effect of first.effects) {
1218
- const cleanup = effect.fn()
1219
- if (typeof cleanup === 'function') cleanups.push(cleanup)
1220
- }
1221
- await new Promise((resolve) => setTimeout(resolve, 0))
1222
- await new Promise((resolve) => setTimeout(resolve, 0))
1223
- const tree = (await renderPage(settings.component, props, pageValue)).tree
1224
- const nodes = []
1225
- walkNodes(tree, (node) => { nodes.push(node) })
1226
- const rerender = async () => {
1227
- const { tree, effects } = await renderPage(settings.component, props, pageValue)
1228
- const nodes = []
1229
- walkNodes(tree, node => { nodes.push(node) })
1230
- return { tree, nodes, effects }
1231
- }
1232
- return { tree, nodes, rpcCalls, rerender }
1233
- }
1234
-
1235
- const VECTOR_CATALOG_FIXTURE = {
1236
- catalog: [
1237
- { id: 'fixture-download', displayName: 'Fixture Download Model', availability: 'available', dimension: 384, totalBytes: 100 },
1238
- { id: 'fixture-pending', displayName: 'Fixture Pending Model', availability: 'pending', pendingReasons: ['SHA-256 pending'], dimension: 384 },
1239
- { id: 'fixture-installed', displayName: 'Fixture Installed Model', availability: 'available', dimension: 384 },
1240
- ],
1241
- installations: { 'fixture-installed': { installed: true, fingerprintMatches: true, status: 'installed' } },
1242
- vector: {},
1243
- }
1244
-
1245
- test('the default Agent backend hides vector source, catalog and API configuration', async (t) => {
1246
- const { tree, nodes, rpcCalls } = await renderVectorSettings(t, {
1247
- memuConfig: { source: 'api', model: 'stale-api-model' },
1248
- localVector: VECTOR_CATALOG_FIXTURE,
1249
- })
1250
- const text = treeText(tree)
1251
- assert.match(text, /backendAgent/)
1252
- assert.ok(nodes.some((node) => node.type === 'button' && node.props.children === 'backendAgent' && node.props['aria-selected'] === true))
1253
- for (const hidden of ['vectorSource', 'managedVector', 'Fixture Download Model', 'summaryModel']) {
1254
- assert.ok(!text.includes(hidden), hidden + ' escaped the default Agent gate')
1255
- }
1256
- assert.ok(!nodes.some((node) => node.type === 'input' && node.props.value === 'stale-api-model'))
1257
- assert.ok(!rpcCalls.some((call) => /downloadLocalVector|setEmbeddingSource|switchLocalVector/.test(call.endpoint)))
1258
- })
1259
-
1260
- test('local vector settings render catalog controls and native download and migration progress', async (t) => {
1261
- const { tree, nodes, rpcCalls } = await renderVectorSettings(t, {
1262
- settings: { memoryBackend: 'api', vectorSource: 'local' },
1263
- localVector: {
1264
- ...VECTOR_CATALOG_FIXTURE,
1265
- installations: {
1266
- ...VECTOR_CATALOG_FIXTURE.installations,
1267
- 'fixture-download': { status: 'downloading', progress: { files: 2, done: 1, bytes: 25, totalBytes: 100, current: 'model.onnx' } },
1268
- },
1269
- vector: {
1270
- active: { catalogId: 'previous-model' },
1271
- requested: { catalogId: 'fixture-installed' },
1272
- pending: { report: { progress: { completed: 2, total: 8, generation: 3, stage: 'embedding', current: { itemId: 'memory-2' } } } },
1273
- },
1274
- },
1275
- })
1276
- const text = treeText(tree)
1277
- for (const visible of ['vectorSourceLocal', 'Fixture Download Model', 'Fixture Pending Model', 'SHA-256 pending', 'managedVectorDownload', 'managedVectorSelect', 'managedVectorSwitch', 'managedVectorRollback', 'model.onnx', 'memory-2']) {
1278
- assert.ok(text.includes(visible), visible + ' did not render')
1279
- }
1280
- const download = nodes.filter((node) => node.type === 'button' && node.props.children === 'managedVectorDownload')
1281
- assert.equal(download.length, 1, 'a pending manifest must not get a download button')
1282
- const progress = nodes.filter((node) => node.type === 'progress')
1283
- assert.equal(progress.length, 2)
1284
- assert.ok(progress.some((node) => node.props['aria-label'] === 'managedVectorProgress' && node.props.value === 25 && node.props.max === 100))
1285
- assert.ok(progress.some((node) => node.props['aria-label'] === 'managedVectorRebuilding' && node.props.value === 2 && node.props.max === 8))
1286
- assert.equal(nodes.filter((node) => node.props?.role === 'status' && node.props['aria-live'] === 'polite').length, 2)
1287
- assert.ok(!nodes.some((node) => node.type === 'input' && node.props.type === 'password'), 'API key fields leaked into local source')
1288
- assert.ok(!rpcCalls.some((call) => /downloadLocalVector|selectLocalVector|switchLocalVector/.test(call.endpoint)), 'rendering performed a model operation')
1289
- })
1290
-
1291
- test('runtime download shows MB/s, selectable sources and pause/stop controls', async (t) => {
1292
- const { tree, nodes, rpcCalls } = await renderVectorSettings(t, {
1293
- settings: { memoryBackend: 'api', vectorSource: 'local' },
1294
- localVector: {
1295
- ...VECTOR_CATALOG_FIXTURE,
1296
- runtime: {
1297
- status: 'downloading',
1298
- ready: false,
1299
- sources: [
1300
- { id: 'npmjs', label: 'npmjs' },
1301
- { id: 'npmmirror', label: 'npmmirror' },
1302
- ],
1303
- downloadSource: 'npmjs',
1304
- progress: {
1305
- bytes: 50 * 1048576,
1306
- totalBytes: 100 * 1048576,
1307
- speedBps: 2.5 * 1048576,
1308
- current: 'onnxruntime-node',
1309
- },
1310
- },
1311
- vector: {},
1312
- },
1313
- })
1314
- const text = treeText(tree)
1315
- for (const visible of ['managedVectorPause', 'managedVectorStop', 'managedVectorRuntimeSource', 'npmjs', 'npmmirror', '2.5 MB/s']) {
1316
- assert.ok(text.includes(visible), visible + ' did not render')
1317
- }
1318
- const progress = nodes.find((node) => node.type === 'progress' && node.props['aria-label'] === 'managedVectorProgress')
1319
- assert.ok(progress, 'runtime progress bar missing')
1320
- assert.equal(progress.props.value, 50 * 1048576)
1321
- assert.equal(progress.props.max, 100 * 1048576)
1322
- const pause = nodes.find((node) => node.type === 'button' && node.props.children === 'managedVectorPause')
1323
- const stop = nodes.find((node) => node.type === 'button' && node.props.children === 'managedVectorStop')
1324
- assert.ok(pause && stop, 'pause/stop buttons missing')
1325
- await pause.props.onClick()
1326
- await new Promise((resolve) => setTimeout(resolve, 0))
1327
- assert.ok(rpcCalls.some((call) => call.endpoint === 'installLocalVectorRuntime' && call.payload?.action === 'pause'))
1328
- })
1329
-
1330
- test('migration with unknown total renders indeterminate native progress', async (t) => {
1331
- const { tree, nodes } = await renderVectorSettings(t, {
1332
- settings: { memoryBackend: 'api', vectorSource: 'local' },
1333
- localVector: { catalog: [], installations: {}, vector: { pending: { report: { progress: { completed: 0, total: 0, generation: 4, stage: 'preparing' } } } } },
1334
- })
1335
- const progress = nodes.filter((node) => node.type === 'progress')
1336
- assert.equal(progress.length, 1)
1337
- assert.equal(progress[0].props.value, undefined, 'unknown work must not look complete')
1338
- assert.equal(progress[0].props.max, 1)
1339
- assert.match(treeText(tree), /managedVectorGeneration 4/)
1340
- assert.ok(!treeText(tree).includes('NaN'))
1341
- })
1342
-
1343
- test('switch waits for two clicks, reports in-flight work, and keeps a failed operation visible', async (t) => {
1344
- let finish
1345
- const response = new Promise(resolve => { finish = resolve })
1346
- const view = await renderVectorSettings(t, {
1347
- settings: { memoryBackend: 'api', vectorSource: 'local' },
1348
- localVector: {
1349
- ...VECTOR_CATALOG_FIXTURE,
1350
- runtime: { status: 'installed', ready: true, path: 'runtime' },
1351
- vector: { requested: { catalogId: 'fixture-installed' }, active: { catalogId: 'old-model' } },
1352
- },
1353
- }, { switchLocalVectorProfile: () => response })
1354
- const button = current => current.nodes.find(node => node.type === 'button' && node.props.title === 'managedVectorSwitch')
1355
- await button(view).props.onClick()
1356
- assert.equal(view.rpcCalls.filter(call => call.endpoint === 'switchLocalVectorProfile').length, 0)
1357
- const armed = await view.rerender()
1358
- assert.equal(button(armed).props.children, 'confirmAction')
1359
- const operation = button(armed).props.onClick()
1360
- const waiting = await view.rerender()
1361
- assert.equal(button(waiting).props.disabled, true)
1362
- assert.ok(waiting.nodes.some(node => node.props?.role === 'status' && treeText(node).includes('managedVectorStatus: managedVectorSwitch')))
1363
- assert.match(treeText(waiting.tree), /managedVectorPrerequisites/)
1364
- finish({ ok: false, error: { code: 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE', message: 'a verified managed runtime is required before switching local embeddings' } })
1365
- await operation
1366
- const failed = await view.rerender()
1367
- assert.equal(button(failed).props.disabled, false)
1368
- assert.ok(failed.nodes.some(node => node.props?.role === 'alert' && treeText(node).includes('verified managed runtime')))
1369
- assert.match(treeText(failed.tree), /old-model/)
1370
- assert.match(treeText(failed.tree), /managedVectorRequested/)
1371
- assert.equal(view.rpcCalls.filter(call => call.endpoint === 'switchLocalVectorProfile').length, 1)
1372
- })
1373
-
1374
- test('pending manifests show verification and size reasons; persisted migration failures remain visible', async (t) => {
1375
- const { tree, nodes } = await renderVectorSettings(t, {
1376
- settings: { memoryBackend: 'api', vectorSource: 'local' },
1377
- localVector: {
1378
- ...VECTOR_CATALOG_FIXTURE,
1379
- installations: { ...VECTOR_CATALOG_FIXTURE.installations, 'fixture-pending': { status: 'absent' } },
1380
- vector: { pending: { status: 'failed', error: {
1381
- code: 'VECTOR_SYNC_FAILED',
1382
- message: 'cannot list shadow database',
1383
- failedItems: [{ itemId: 'mem-failed-1', code: 'VECTOR_READBACK_FAILED', message: 'committed item is missing from shadow' }],
1384
- } } },
1385
- },
1386
- })
1387
- assert.match(treeText(tree), /managedVectorSizePending/)
1388
- assert.match(treeText(tree), /managedVectorPending/)
1389
- assert.match(treeText(tree), /SHA-256 pending/)
1390
- assert.ok(treeText(tree).includes('managedVectorSizePending'), 'pending artifacts must not display a guessed byte count')
1391
- assert.equal(nodes.filter(node => node.type === 'button' && node.props.title === 'managedVectorDownload').length, 1)
1392
- assert.ok(nodes.some(node => node.props?.role === 'alert' && treeText(node).includes('cannot list shadow database')))
1393
- // 重建失败必须说清是哪一条、为什么:只报"未覆盖全部记忆"根本没法修。
1394
- const failedText = treeText(tree)
1395
- assert.match(failedText, /mem-failed-1/)
1396
- assert.match(failedText, /VECTOR_READBACK_FAILED/)
1397
- assert.match(failedText, /committed item is missing from shadow/)
1398
- })
1399
-
1400
- test('a finished rebuild reads as switched, not as a running progress bar', async (t) => {
1401
- const { tree } = await renderVectorSettings(t, {
1402
- settings: { memoryBackend: 'api', vectorSource: 'local' },
1403
- localVector: {
1404
- ...VECTOR_CATALOG_FIXTURE,
1405
- runtime: { status: 'installed', ready: true, path: 'runtime' },
1406
- vector: {
1407
- active: { catalogId: 'fixture-installed', generation: 1, fingerprint: '47511436abcdef', lastMigration: { committed: 8, total: 8, generation: 1 } },
1408
- indexed: { global: ['a', 'b'], lib: ['c', 'd', 'e'] },
1409
- },
1410
- },
1411
- })
1412
- const text = treeText(tree)
1413
- assert.match(text, /vectorStageCommitted/)
1414
- assert.match(text, /vectorSwitchDoneHint/)
1415
- assert.doesNotMatch(text, /managedVectorRebuilding/, 'a committed generation must not keep the running label')
1416
- assert.match(text, /vectorRouteLocal/, 'the header must say which route recall uses')
1417
- assert.match(text, /vectorIndexedNow/, 'the card must show the live indexed count, not only the switch snapshot')
1418
- assert.match(text, /vectorIndexedNow 5 vectorIndexedUnit/, 'two global + three library ids')
1419
- })
1420
-
1421
- test('API vector settings render provider fields and hide the managed local catalog', async (t) => {
1422
- const { tree, nodes } = await renderVectorSettings(t, {
1423
- settings: { memoryBackend: 'api', vectorSource: 'api' },
1424
- memuConfig: { source: 'api', provider: 'jina', model: 'fixture-api-model', baseUrl: 'https://example.invalid/v1', hasKey: true },
1425
- summaryConfig: { model: 'fixture-summary-model' },
1426
- localVector: VECTOR_CATALOG_FIXTURE,
1427
- })
1428
- const text = treeText(tree)
1429
- for (const visible of ['vectorSourceApi', 'provider', 'model', 'baseUrl', 'apiKey', 'summaryModel']) {
1430
- assert.ok(text.includes(visible), visible + ' did not render')
1431
- }
1432
- assert.ok(nodes.some((node) => node.type === 'select' && node.props.value === 'jina'))
1433
- assert.ok(nodes.some((node) => node.type === 'input' && node.props.value === 'fixture-api-model'))
1434
- assert.ok(nodes.some((node) => node.type === 'input' && node.props.value === 'https://example.invalid/v1'))
1435
- assert.equal(nodes.filter((node) => node.type === 'input' && node.props.type === 'password').length, 2)
1436
- assert.ok(!text.includes('Fixture Download Model'))
1437
- assert.ok(!text.includes('managedVectorDownload'))
1438
- assert.ok(!nodes.some((node) => node.type === 'progress'))
1439
- })
1440
-
1441
- // 日志行的三档视觉状态。真实读数里整理超时记的是 level=warn + ok=false
1442
- //(lib/private.js 的超时路径),所以「只看 level==='error'」会把它显示成正常行——
1443
- // 用户看到的就是「失败长得好普通」。这条钉的是行为:哪一行该红、哪一行该橙、
1444
- // 哪一行什么都不该标。
1445
- test('failed and degraded activity rows are visually distinguished from normal rows', async () => {
1446
- const failed = {
1447
- id: 'act-failed', at: '2026-11-02T07:58:29.775Z', kind: 'consolidate', level: 'warn',
1448
- scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1', ok: false,
1449
- message: '整理超时 · 空闲 · fork f-7535be · timeout:consolidation timed out after 180s', detail: null, refs: [],
1450
- }
1451
- const degraded = {
1452
- id: 'act-degraded', at: '2026-11-02T07:59:00.000Z', kind: 'vector', level: 'warn',
1453
- scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
1454
- message: '向量未激活,写入已降级为索引+引擎', detail: { reason: 'no active vector generation' }, refs: [],
1455
- }
1456
- const normal = {
1457
- id: 'act-normal', at: '2026-11-02T08:02:40.988Z', kind: 'consolidate', level: 'info',
1458
- scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
1459
- message: '整理完成 · 空闲 · fork 1-2b16be · 索引 +1', detail: null, refs: [],
1460
- }
1461
- const ctx = fakeCtx({
1462
- answers: { getActivityLog: { events: [failed, degraded, normal], stats: { total: 3, capped: 2000, bytes: 1024 } } },
1463
- })
1464
- globalThis.__dshMemuExports.apply(ctx)
1465
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1466
- const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
1467
- collectPageHook()
1468
- for (const effect of first.effects) effect.fn()
1469
- await new Promise((resolve) => setTimeout(resolve, 0))
1470
- const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1471
- for (const effect of mid.effects) effect.fn()
1472
- await new Promise((resolve) => setTimeout(resolve, 0))
1473
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1474
- const rows = new Map()
1475
- const labels = []
1476
- walkNodes(tree, (node) => {
1477
- if (typeof node.props?.key === 'string' && node.props.key.startsWith('act-')) rows.set(node.props.key, node.props)
1478
- if (node.props?.children === 'logStateFailed' || node.props?.children === 'logDegraded') labels.push(node.props)
1479
- })
1480
- assert.equal(rows.size, 3, 'the log page rendered none of the fixture rows')
1481
- assert.match(String(rows.get('act-failed')?.className), /dshm-logrow is-failed/, 'the timeout row must carry the failed state class')
1482
- assert.match(String(rows.get('act-degraded')?.className), /dshm-logrow is-degraded/, 'a fallback-path row is degraded, not failed')
1483
- assert.equal(rows.get('act-normal')?.className, 'dshm-logrow', 'normal rows must not pick up any state class')
1484
- assert.ok(labels.some((props) => props.children === 'logStateFailed'), 'the failed row needs a 失败 label, not only colour')
1485
- assert.ok(labels.some((props) => props.children === 'logDegraded'), 'degraded rows need their own word')
1486
- assert.ok(labels.every((props) => typeof props.title === 'string' && props.title.length > 0), 'every state tag must explain itself on hover')
1487
- })
1488
-
1489
- test('clicking the API source tab sends the explicit setEmbeddingSource RPC only', async (t) => {
1490
- const { nodes, rpcCalls } = await renderVectorSettings(t, {
1491
- settings: { memoryBackend: 'api', vectorSource: 'local' },
1492
- localVector: VECTOR_CATALOG_FIXTURE,
1493
- })
1494
- const apiTab = nodes.filter((node) => node.type === 'button' && node.props.children === 'vectorSourceApi')
1495
- assert.equal(apiTab.length, 1)
1496
- assert.equal(apiTab[0].props['aria-selected'], false)
1497
- assert.equal(apiTab[0].props.disabled, false)
1498
- assert.equal(rpcCalls.filter((call) => call.endpoint === 'setEmbeddingSource').length, 0)
1499
- await apiTab[0].props.onClick()
1500
- assert.deepEqual(rpcCalls.filter((call) => call.endpoint === 'setEmbeddingSource'), [
1501
- { path: '/dsh-memu-memory', endpoint: 'setEmbeddingSource', payload: { source: 'api' } },
1502
- ])
1503
- assert.ok(!rpcCalls.some((call) => /downloadLocalVector|selectLocalVector|switchLocalVector/.test(call.endpoint)))
1504
- })
1505
-
1506
- test('the log page renders rows with copy, download and locate actions', async () => {
1507
- const event = {
1508
- id: 'act-fixture', at: '2026-10-30T03:00:00.000Z', kind: 'consolidate', level: 'warn',
1509
- scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
1510
- message: '整理超时:fork 已停止', detail: { timedOut: true, childId: 'memu-consolidate-x' }, refs: [], ok: false,
1511
- }
1512
- const check = {
1513
- id: 'act-check', at: '2026-10-30T03:05:00.000Z', kind: 'check', level: 'info',
1514
- scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
1515
- message: '主动检查跳过 · score 0.12 · large-transcript-thin · 空闲 40 分钟 · 会话 5913 事件',
1516
- detail: { reason: 'large-transcript-thin', score: 0.12, parts: { human: 0.33, content: 0.01, tool: 0 } }, refs: [], ok: false,
1517
- }
1518
- const ctx = fakeCtx({
1519
- answers: { getActivityLog: { events: [event, check], stats: { total: 2, capped: 2000, bytes: 1024 } } },
1520
- })
1521
- globalThis.__dshMemuExports.apply(ctx)
1522
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1523
- const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
1524
- collectPageHook()
1525
- for (const effect of first.effects) effect.fn()
1526
- await new Promise((resolve) => setTimeout(resolve, 0))
1527
- await new Promise((resolve) => setTimeout(resolve, 0))
1528
- // The log page's own effect only exists once that page renders, so it needs one
1529
- // more render + effect pass before the data is in the hook.
1530
- const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1531
- for (const effect of mid.effects) effect.fn()
1532
- await new Promise((resolve) => setTimeout(resolve, 0))
1533
- await new Promise((resolve) => setTimeout(resolve, 0))
1534
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1535
- const text = treeText(tree)
1536
- assert.match(text, /整理超时/)
1537
- assert.match(text, /logCopyAll/)
1538
- assert.match(text, /logDownload/)
1539
- assert.match(text, /logLocate/, 'a row with a library id offers the correction entry point')
1540
- assert.match(text, /pageLogs/)
1541
- assert.match(text, /logKindCheck/, 'the activity log labels wake-up checks')
1542
- assert.match(text, /large-transcript-thin/, 'the check row keeps its reason and score visible')
1543
- })
1544
-
1545
- test('the memory wall global block bulk-archives and the drawer deletes global entries two-step', async () => {
1546
- const rpcCalls = []
1547
- const ctx = fakeCtx({ rpcCalls })
1548
- const originalGetState = RPC_ANSWERS.getState
1549
- const originalSettingsState = RPC_ANSWERS.getSettingsState
1550
- const loaded = {
1551
- ...EMPTY_STATE,
1552
- libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 0 }],
1553
- }
1554
- RPC_ANSWERS.getState = loaded
1555
- RPC_ANSWERS.getSettingsState = loaded
1556
- RPC_ANSWERS.browseWall = {
1557
- total: 2,
1558
- items: [
1559
- { id: 'mem-g-active', libraryId: null, libraryName: 'global', title: 'global active', preview: 'active body', layer: 'long_term', status: 'active', source: 'inferred', decay: 0.5, tags: [] },
1560
- { id: 'mem-g-archived', libraryId: null, libraryName: 'global', title: 'global archived', preview: 'archived body', layer: 'long_term', status: 'archived', source: 'inferred', decay: 0.5, tags: [] },
1561
- ],
1562
- }
1563
- RPC_ANSWERS.listGlobal = {
1564
- files: [
1565
- { id: 'mem-g-active', title: 'global active', content: 'active body', status: 'active', domain: 'general' },
1566
- { id: 'mem-g-archived', title: 'global archived', content: 'archived body', status: 'archived', domain: 'general' },
1567
- ],
1568
- }
1569
- RPC_ANSWERS.archiveMemory = { id: 'mem-g-active', entry: { status: 'archived' } }
1570
- RPC_ANSWERS.deleteMemory = { id: 'mem-g-archived', libraryId: null, deleted: true }
1571
- const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
1572
- // harness 的 hook 游标是全局的:同一棵树只能展开一次,二次 walk 会把子组件
1573
- // 的 useState 重新初始化。所以每次 renderPage 后只 walk 一遍,收齐所有节点。
1574
- const collect = (tree) => {
1575
- const labels = new Map()
1576
- const cards = []
1577
- const tabs = []
1578
- walkNodes(tree, (node) => {
1579
- if (typeof node.type === 'function' && typeof node.props?.children === 'string' && !labels.has(node.props.children)) {
1580
- labels.set(node.props.children, node)
1581
- }
1582
- if (node.type === 'button' && String(node.props?.className || '').includes('dshm-wall-item')) cards.push(node)
1583
- if (node.type === 'button' && node.props?.role === 'tab') tabs.push(node)
1584
- })
1585
- return { labels, cards, tabs }
1586
- }
1587
- try {
1588
- globalThis.__dshMemuExports.apply(ctx)
1589
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1590
- const props = { ctx, t: (key) => key }
1591
- const first = await renderPage(settings.component, props, undefined, { remount: true })
1592
- collectPageHook()
1593
- for (const effect of first.effects) effect.fn()
1594
- await tick(); await tick()
1595
- let view = collect((await renderPage(settings.component, props, 9)).tree)
1596
- for (const effect of effects) effect.fn()
1597
- await tick(); await tick()
1598
- view = collect((await renderPage(settings.component, props, 9)).tree)
1599
-
1600
- // 切到全局块:多选开关必须存在(旧版全局块没有)。
1601
- const scopeTab = view.tabs.find((node) => String(node.props?.children || '').startsWith('wallScopeGlobal'))
1602
- assert.ok(scopeTab, 'the global scope tab did not render')
1603
- scopeTab.props.onClick()
1604
- view = collect((await renderPage(settings.component, props, 9)).tree)
1605
- assert.ok(view.labels.has('multiSelect'), 'the global block offers multi-select')
1606
- view.labels.get('multiSelect').props.onClick()
1607
- view = collect((await renderPage(settings.component, props, 9)).tree)
1608
- assert.equal(view.cards.length, 1, 'the active pool shows the active global card')
1609
- view.cards[0].props.onClick()
1610
- view = collect((await renderPage(settings.component, props, 9)).tree)
1611
- assert.ok(view.labels.has('archive (1)'), 'selecting one global card arms the bulk archive button')
1612
- view.labels.get('archive (1)').props.onClick()
1613
- await tick(); await tick()
1614
- const archived = rpcCalls.filter((call) => call.endpoint === 'archiveMemory')
1615
- assert.equal(archived.length, 1)
1616
- assert.equal(archived[0].payload.scope, 'global')
1617
- assert.equal(archived[0].payload.id, 'mem-g-active')
1618
- assert.equal(archived[0].payload.libraryId, undefined, 'global bulk writes never name a private library')
1619
-
1620
- // 已归档池开抽屉:恢复与两段删除都在,删除第一段只武装、第二段才发请求。
1621
- view = collect((await renderPage(settings.component, props, 9)).tree)
1622
- view.labels.get('wallMultiExit').props.onClick()
1623
- view = collect((await renderPage(settings.component, props, 9)).tree)
1624
- const archivedTab = view.tabs.find((node) => String(node.props?.children || '').startsWith('browseArchivedTab'))
1625
- archivedTab.props.onClick()
1626
- view = collect((await renderPage(settings.component, props, 9)).tree)
1627
- assert.equal(view.cards.length, 1)
1628
- view.cards[0].props.onClick()
1629
- await tick(); await tick()
1630
- view = collect((await renderPage(settings.component, props, 9)).tree)
1631
- assert.ok(view.labels.has('restore'), 'the archived global drawer offers restore')
1632
- assert.ok(view.labels.has('deleteForever'), 'the archived global drawer offers permanent delete')
1633
- assert.ok(!view.labels.has('save'), 'global content stays curator-written')
1634
- view.labels.get('deleteForever').props.onClick()
1635
- view = collect((await renderPage(settings.component, props, 9)).tree)
1636
- assert.equal(rpcCalls.filter((call) => call.endpoint === 'deleteMemory').length, 0, 'the first click only arms')
1637
- assert.ok(view.labels.has('confirmDelete'))
1638
- view.labels.get('confirmDelete').props.onClick()
1639
- await tick(); await tick()
1640
- const deleted = rpcCalls.filter((call) => call.endpoint === 'deleteMemory')
1641
- assert.equal(deleted.length, 1)
1642
- assert.equal(deleted[0].payload.scope, 'global')
1643
- assert.equal(deleted[0].payload.id, 'mem-g-archived')
1644
- assert.equal(deleted[0].payload.confirmed, true)
1645
- } finally {
1646
- RPC_ANSWERS.getState = originalGetState
1647
- RPC_ANSWERS.getSettingsState = originalSettingsState
1648
- delete RPC_ANSWERS.browseWall
1649
- delete RPC_ANSWERS.listGlobal
1650
- delete RPC_ANSWERS.archiveMemory
1651
- delete RPC_ANSWERS.deleteMemory
1652
- }
1653
- })
1654
-
1655
- test('the memory wall filters by domain and names every card domain', async () => {
1656
- const rpcCalls = []
1657
- const ctx = fakeCtx({ rpcCalls })
1658
- const originalGetState = RPC_ANSWERS.getState
1659
- const originalSettingsState = RPC_ANSWERS.getSettingsState
1660
- const loaded = {
1661
- ...EMPTY_STATE,
1662
- libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 2 }],
1663
- }
1664
- RPC_ANSWERS.getState = loaded
1665
- RPC_ANSWERS.getSettingsState = loaded
1666
- RPC_ANSWERS.browseWall = {
1667
- total: 2,
1668
- domains: ['coding', 'rp'],
1669
- items: [
1670
- { id: 'mem-rp', libraryId: 'lib-1', libraryName: 'demo', title: '约定的日子', preview: 'p', layer: 'long_term', status: 'active', source: 'user_said', decay: 0.5, tags: [], domain: 'rp' },
1671
- { id: 'mem-code', libraryId: 'lib-1', libraryName: 'demo', title: '部署窗口', preview: 'p', layer: 'long_term', status: 'active', source: 'inferred', decay: 0.4, tags: [], domain: 'coding' },
1672
- ],
1673
- }
1674
- const settle = async () => {
1675
- await new Promise((resolve) => setTimeout(resolve, 0))
1676
- await new Promise((resolve) => setTimeout(resolve, 0))
1677
- }
1678
- // harness 的 hook 游标是全局的:同一棵树只能展开一次,二次 walk 会把子组件的
1679
- // useState 重新初始化。所以每轮 render 只走一遍,把要的东西一次收齐。
1680
- const collect = (tree) => {
1681
- const found = { select: null, domainTags: [], cards: 0 }
1682
- walkNodes(tree, (node) => {
1683
- if (node.type === 'select' && node.props?.['aria-label'] === 'wallFilterDomain' && !found.select) found.select = node
1684
- if (node.type === 'span' && node.props?.title === 'wallDomainHint') found.domainTags.push(String(node.props?.children ?? ''))
1685
- if (node.type === 'button' && String(node.props?.className || '').includes('dshm-wall-item')) found.cards += 1
1686
- })
1687
- const values = []
1688
- const visit = (value) => {
1689
- if (Array.isArray(value)) { value.forEach(visit); return }
1690
- if (value && value.type === 'option') values.push(String(value.props?.value ?? ''))
1691
- }
1692
- if (found.select) visit([].concat(found.select.props?.children ?? []))
1693
- found.values = values
1694
- return found
1695
- }
1696
- try {
1697
- globalThis.__dshMemuExports.apply(ctx)
1698
- const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1699
- const props = { ctx, t: (key) => key }
1700
- const first = await renderPage(settings.component, props, undefined, { remount: true })
1701
- collectPageHook()
1702
- for (const effect of first.effects) effect.fn()
1703
- await settle()
1704
- let view = collect((await renderPage(settings.component, props, 9)).tree)
1705
- for (const effect of effects) effect.fn()
1706
- await settle()
1707
- view = collect((await renderPage(settings.component, props, 9)).tree)
1708
-
1709
- assert.ok(view.select, 'the wall renders a domain filter')
1710
- assert.equal(view.cards, 2, 'both wall cards rendered')
1711
- assert.deepEqual(view.values, ['', 'coding', 'rp'], 'the filter offers every domain the server reported')
1712
- assert.deepEqual(view.domainTags.sort(), ['dmCoding', 'dmRp'], 'each card names the domain it came from')
1713
-
1714
- view.select.props.onChange({ target: { value: 'rp' } })
1715
- view = collect((await renderPage(settings.component, props, 9)).tree)
1716
- for (const effect of effects) effect.fn()
1717
- await settle()
1718
- const asked = rpcCalls.filter((call) => call.endpoint === 'browseWall')
1719
- assert.equal(asked[asked.length - 1].payload.domain, 'rp', 'picking a domain asks the server instead of trimming the page in the browser')
1720
- view = collect((await renderPage(settings.component, props, 9)).tree)
1721
- assert.deepEqual(view.domainTags, [], 'once filtered, cards stop repeating the same domain')
1722
- assert.equal(view.select.props.value, 'rp', 'the filter keeps what the reader picked')
1723
- } finally {
1724
- RPC_ANSWERS.getState = originalGetState
1725
- RPC_ANSWERS.getSettingsState = originalSettingsState
1726
- delete RPC_ANSWERS.browseWall
1727
- }
1728
- })
1
+ // A settings pane that throws during render shows up as a blank panel with no
2
+ // error anywhere — exactly what happened when an effect referenced a callback
3
+ // declared further down (temporal dead zone). This harness runs the real client
4
+ // component with a minimal hook runtime, so a render-time throw fails the build
5
+ // instead of silently blanking the UI. Every page is rendered, because a block
6
+ // only runs when its page is selected.
7
+ import test from 'node:test'
8
+ import assert from 'node:assert/strict'
9
+ import fs from 'node:fs'
10
+
11
+ const registrations = []
12
+
13
+ function makeElement(type, props, ...children) {
14
+ return { type, props: { ...(props || {}), children: children.length <= 1 ? children[0] : children } }
15
+ }
16
+
17
+ let hooks = []
18
+ let cursor = 0
19
+ let effects = []
20
+ let dirty = false
21
+ let forced = null
22
+ let generation = 0
23
+
24
+ const React = {
25
+ createElement: makeElement,
26
+ Fragment: Symbol('Fragment'),
27
+ useState(initial) {
28
+ const index = cursor++
29
+ // A setter captured by a component from an earlier test must not write into
30
+ // the hook array this test is using: async effects from a previous render can
31
+ // resolve late, and without this the second test renders with the first one's
32
+ // state.
33
+ const generation_ = generation
34
+ if (hooks[index] === undefined) hooks[index] = typeof initial === 'function' ? initial() : initial
35
+ if (forced && forced.index === index) hooks[index] = forced.value
36
+ return [hooks[index], (next) => {
37
+ if (generation_ !== generation) return
38
+ hooks[index] = typeof next === 'function' ? next(hooks[index]) : next
39
+ dirty = true
40
+ }]
41
+ },
42
+ memo: (component) => component,
43
+ useCallback: (fn) => fn,
44
+ useMemo: (fn) => fn(),
45
+ useEffect(fn, deps) { effects.push({ fn, deps, index: cursor++ }) },
46
+ useLayoutEffect() {},
47
+ useRef: (value) => ({ current: value }),
48
+ useSyncExternalStore: (_subscribe, getSnapshot) => getSnapshot(),
49
+ }
50
+
51
+ globalThis.window = {
52
+ __ModuleLoader__: {
53
+ load({ factory }) {
54
+ globalThis.__dshMemuExports = factory((name) => {
55
+ if (name === 'react') return React
56
+ throw new Error(`unexpected require: ${name}`)
57
+ })
58
+ },
59
+ },
60
+ // The overlay listens for its close message and for Escape.
61
+ addEventListener() {},
62
+ removeEventListener() {},
63
+ }
64
+ // The WebUI button falls back to an in-app overlay when popups are blocked; the
65
+ // stub records what got attached so the test can assert the current tab is never
66
+ // navigated (that would unload the app and look like a forced refresh).
67
+ const appendedNodes = []
68
+ globalThis.document = {
69
+ createElement: (tag) => {
70
+ const node = {
71
+ tag,
72
+ style: {},
73
+ attrs: {},
74
+ children: [],
75
+ href: '',
76
+ textContent: '',
77
+ setAttribute(name, value) { node.attrs[name] = value },
78
+ addEventListener() {},
79
+ appendChild(child) { node.children.push(child); return child },
80
+ remove() { node.removed = true },
81
+ click() { node.clicked = true },
82
+ }
83
+ return node
84
+ },
85
+ querySelector: () => null,
86
+ addEventListener() {},
87
+ removeEventListener() {},
88
+ head: { appendChild() {} },
89
+ body: { appendChild(node) { appendedNodes.push(node); return node } },
90
+ }
91
+
92
+ await import('../lib/client.js')
93
+
94
+ const EMPTY_STATE = {
95
+ engine: { status: 'ready', versions: [], currentVersion: '0.11.0b3', recommendedVersion: '0.11.0b3', installed: true, state: {} },
96
+ settings: { autoInject: 'smart', mustRememberCap: 16, unpinBudgetPerSession: 2 },
97
+ libraries: [],
98
+ archivedLibraries: [],
99
+ memuConfig: { provider: 'openai' },
100
+ summaryConfig: {},
101
+ binding: null,
102
+ privateCount: 0,
103
+ pinnedCount: 0,
104
+ globalCount: 0,
105
+ jobs: [],
106
+ }
107
+
108
+ const RPC_ANSWERS = {
109
+ getState: EMPTY_STATE,
110
+ getSettingsState: EMPTY_STATE,
111
+ getPrompts: { prompts: [
112
+ { key: 'system-guide', title: 'guide', description: '', variables: ['mustRememberCap'], source: 'default', text: 'a', scope: 'private', domain: null },
113
+ { key: 'system-guide.rp', title: 'guide rp', description: '', variables: [], source: 'default', text: 'b', scope: 'private', domain: 'rp' },
114
+ { key: 'global-curator', title: 'curator', description: '', variables: ['input'], source: 'default', text: 'c', scope: 'global', domain: null },
115
+ ] },
116
+ listVersions: { ok: true, versions: [] },
117
+ listBackups: { backups: [] },
118
+ listFolders: { folders: [] },
119
+ listLibraries: { libraries: [] },
120
+ listSessions: { sessions: [] },
121
+ getSidebarState: {
122
+ binding: { sessionId: 'probe-session', libraryId: 'lib-1', useLibrary: true, useGlobal: true, scopeKey: '/proj/demo', domain: 'coding' },
123
+ domain: 'coding',
124
+ folder: { scopeKey: '/proj/demo', useLibrary: true, useGlobal: true },
125
+ effective: { useLibrary: true, useGlobal: true, enabled: true, folder: { scopeKey: '/proj/demo', useLibrary: true, useGlobal: true } },
126
+ private: { items: [], active: 0, pinned: 0, total: 0 },
127
+ global: { items: [], active: 0, total: 0 },
128
+ domains: ['rp', 'coding'],
129
+ },
130
+ jobStatus: null,
131
+ }
132
+
133
+ function fakeCtx({ answers = {}, rpcCalls = [] } = {}) {
134
+ return {
135
+ effect: (fn) => { try { fn() } catch {} },
136
+ locale: { register: () => () => {}, bind: () => (key) => key, get: () => 'zh' },
137
+ connection: {
138
+ rpc: {
139
+ call: async (path, endpoint, payload) => {
140
+ rpcCalls.push({ path, endpoint, payload })
141
+ if (typeof answers[endpoint] === 'function') return answers[endpoint](payload)
142
+ return { ok: true, value: answers[endpoint] ?? RPC_ANSWERS[endpoint] ?? {} }
143
+ },
144
+ },
145
+ },
146
+ sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: {}, ids: [] }) } },
147
+ // The sidebar tab asks for the current conversation through one of these.
148
+ get: (name) => (name === 'uiSession'
149
+ ? { adapter: { current: { getSnapshot: () => ({ key: 'probe-session' }) } } }
150
+ : undefined),
151
+ slots: {
152
+ inject: (_name, callback) => callback(scope),
153
+ register: (spec, component) => { registrations.push({ slot: spec.name, id: spec.id, component }); return () => {} },
154
+ },
155
+ inject: (_deps, callback) => callback({
156
+ // Run the effect body: that is where the tab body registers itself.
157
+ effect: (fn) => { try { fn() } catch {} },
158
+ sidebarRightTabs: { register: () => () => {} },
159
+ get: () => undefined,
160
+ }),
161
+ }
162
+ }
163
+
164
+ const scope = {
165
+ effect: (fn) => { try { fn() } catch {} },
166
+ register: (spec, component) => { registrations.push({ slot: spec.name, id: spec.id, component }); return () => {} },
167
+ inject: (_deps, callback) => callback(scope),
168
+ }
169
+
170
+ async function renderPage(component, props, pageValue, { remount = false } = {}) {
171
+ if (remount) { hooks = []; generation++ }
172
+ effects = []
173
+ cursor = 0
174
+ forced = pageValue === undefined ? null : { index: pageHookIndex, value: pageValue }
175
+ const tree = component(props)
176
+ assert.ok(tree, 'component rendered nothing')
177
+ return { tree, effects }
178
+ }
179
+
180
+ let pageHookIndex = -1
181
+
182
+ function collectPageHook() {
183
+ // The page state is the only one initialised to the number 0.
184
+ const zeroes = hooks.map((value, index) => (value === 0 ? index : -1)).filter((index) => index >= 0)
185
+ assert.equal(zeroes.length, 1, 'expected exactly one numeric-zero state (the page index)')
186
+ pageHookIndex = zeroes[0]
187
+ }
188
+
189
+ function treeText(node, depth = 0) {
190
+ if (node === null || node === undefined || depth > 400) return ''
191
+ if (typeof node === 'string' || typeof node === 'number') return String(node)
192
+ if (Array.isArray(node)) return node.map((child) => treeText(child, depth + 1)).join(' ')
193
+ // Function components are expanded so their bodies are exercised too — a throw
194
+ // inside Section/Button counts the same as one inside the page.
195
+ if (typeof node.type === 'function') return treeText(node.type(node.props), depth + 1)
196
+ return `${node.props?.className || ''} ${treeText(node.props?.children, depth + 1)}`
197
+ }
198
+
199
+ test('the settings page renders every page instead of a blank panel', async () => {
200
+ const ctx = fakeCtx()
201
+ globalThis.__dshMemuExports.apply(ctx)
202
+ const settings = registrations.find((r) => r.slot === 'settings.section')
203
+ assert.ok(settings?.component, 'settings.section was not registered')
204
+
205
+ // First render: state is still null, which is the loading branch.
206
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
207
+ collectPageHook()
208
+ assert.match(treeText(first.tree), /loading|dshm-settings/)
209
+
210
+ // Let the mount effects fetch and settle, then render with data. Hooks survive
211
+ // between renders, which is how the fetched state reaches the next pass.
212
+ for (const effect of first.effects) effect.fn()
213
+ await new Promise((resolve) => setTimeout(resolve, 0))
214
+ await new Promise((resolve) => setTimeout(resolve, 0))
215
+
216
+ // 遍历 14 个设置页;help 页由单独用例覆盖。
217
+ for (let page = 0; page < 14; page++) {
218
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, page)
219
+ const text = treeText(tree)
220
+ assert.match(String(tree.props?.className), /dshm-root/, `page ${page} did not render the shell`)
221
+ // The rail is the nav: every page label has to be there. Counting the shared
222
+ // dshm-nav-item class instead would also pick up the in-page tab strips (memory
223
+ // backend, prompt scope, browser view), which use the same widget on purpose.
224
+ const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageGraph', 'pageLogs', 'pageLexicon', 'pageDiagnostics']
225
+ assert.ok(NAV.every((key) => text.includes(key)), `page ${page} lost a nav entry`)
226
+ assert.equal((text.match(/dshm-nav-ind/g) || []).length, 1, `page ${page} lost or duplicated its rail indicator`)
227
+ assert.match(text, /dshm-page/, `page ${page} lost the content pane`)
228
+ // Passing a labels map where an id was expected stringifies to this, which is
229
+ // exactly how the sidebar domain picker broke.
230
+ assert.ok(!text.includes('[object Object]'), `page ${page} rendered an object as text`)
231
+ }
232
+ })
233
+
234
+ async function graphStudioHarness(call, libraries) {
235
+ const ctx = fakeCtx()
236
+ globalThis.__dshMemuExports.apply(ctx)
237
+ const settings = registrations.filter(row => row.slot === 'settings.section').pop()
238
+ const shell = await withHash('#/settings/graph', async () => {
239
+ const props = { ctx, t: key => key, standalone: true }
240
+ const first = await renderPage(settings.component, props, undefined, { remount: true })
241
+ for (const effect of first.effects) effect.fn()
242
+ await new Promise(resolve => setTimeout(resolve, 0))
243
+ return (await renderPage(settings.component, props)).tree
244
+ })
245
+ let studio
246
+ walkNodes(shell, node => { if (node.type?.name === 'GraphStudioPanel') { studio = node; return false } })
247
+ assert.ok(studio, 'graph studio not found')
248
+ const props = { ...studio.props, t: key => key, call, libraries }
249
+ const previous = new Map()
250
+ const pick = (tree, predicate) => {
251
+ const found = []
252
+ const visit = node => {
253
+ if (!node || typeof node !== 'object') return
254
+ if (Array.isArray(node)) { node.forEach(visit); return }
255
+ if (predicate(node)) found.push(node)
256
+ if (typeof node.type !== 'function') visit(node.props?.children)
257
+ }
258
+ visit(tree)
259
+ return found
260
+ }
261
+ let first = true
262
+ const render = async (flush = false) => {
263
+ let view = await renderPage(studio.type, props, undefined, { remount: first })
264
+ first = false
265
+ if (flush) {
266
+ for (const effect of view.effects) {
267
+ const old = previous.get(effect.index)
268
+ if (old && effect.deps?.length === old.deps?.length && effect.deps?.every((value, i) => Object.is(value, old.deps[i]))) continue
269
+ old?.cleanup?.()
270
+ previous.set(effect.index, { deps: effect.deps, cleanup: effect.fn() })
271
+ }
272
+ await new Promise(resolve => setTimeout(resolve, 0))
273
+ view = await renderPage(studio.type, props)
274
+ }
275
+ return view.tree
276
+ }
277
+ return { render, pick, close: () => { for (const value of previous.values()) value.cleanup?.() } }
278
+ }
279
+
280
+ test('graph studio pages all libraries and filters custom domains without merging identities', async () => {
281
+ const libraries = [{ id: 'lib-a', name: 'A' }, { id: 'lib-b', name: 'B' }], calls = []
282
+ const call = async (endpoint, payload) => {
283
+ calls.push({ endpoint, payload })
284
+ if (endpoint === 'getMemory') return { entry: { title: 'B editable', content: 'B full body' } }
285
+ if (endpoint !== 'getGraph') return { items: [] }
286
+ const domain = payload.libraryId === 'lib-a' ? 'coding' : 'project:travel'
287
+ const memories = Array.from({ length: payload.libraryId === 'lib-a' ? 201 : 1 }, (_, i) => ({
288
+ id: i ? 'mem-' + i : 'mem-shared', title: payload.libraryId + '-memory-' + i, kind: 'memory', domain,
289
+ }))
290
+ const nodes = payload.domain && payload.domain !== domain ? [] : [...memories, { id: 'ent-shared', title: payload.libraryId + '-person', kind: 'person' }]
291
+ const offset = payload.offset || 0, next = offset + 200
292
+ return { nodes: nodes.slice(offset, next), edges: !offset && nodes.length ? [{ from: 'mem-shared', to: 'ent-shared', kind: 'person' }] : [],
293
+ nextOffset: next < nodes.length ? next : null, domains: ['coding', 'project:travel'] }
294
+ }
295
+ const view = await graphStudioHarness(call, libraries)
296
+ try {
297
+ let tree = await view.render(true)
298
+ view.pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
299
+ tree = await view.render(true)
300
+ const canvas = () => view.pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph
301
+ assert.equal(canvas().nodes.length, 204)
302
+ assert.equal(canvas().nodes.filter(node => node.kind === 'person').length, 2)
303
+ assert.equal(new Set(canvas().nodes.map(node => node.id)).size, 204)
304
+ assert.equal(canvas().edges.length, 2)
305
+ for (const edge of canvas().edges) assert.equal(canvas().nodes.find(node => node.id === edge.from).libraryId, canvas().nodes.find(node => node.id === edge.to).libraryId)
306
+ assert.ok(calls.some(row => row.payload.libraryId === 'lib-a' && row.payload.offset === 200))
307
+ view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: ' PROJECT:travel ' } })
308
+ tree = await view.render(true)
309
+ assert.equal(canvas().nodes.length, 2)
310
+ assert.ok(canvas().nodes.every(node => node.libraryId === 'lib-b'))
311
+ assert.ok(calls.some(row => row.payload.domain === 'project:travel'))
312
+ view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: 'project:travel' } })
313
+ tree = await view.render(true)
314
+ assert.equal(canvas().nodes.length, 2, 'equivalent domain input must not clear the graph')
315
+ view.pick(tree, node => node.type === 'button' && node.props.children === 'gsManage')[0].props.onClick()
316
+ tree = await view.render()
317
+ const rows = view.pick(tree, node => String(node.props?.className || '').split(' ').includes('dshm-gs-mgr-row'))
318
+ assert.equal(rows.length, 2, 'management uses the same domain filter')
319
+ rows.find(row => treeText(row).includes('lib-b-memory-0')).props.onClick()
320
+ tree = await view.render()
321
+ view.pick(tree, node => node.type === 'button' && node.props['aria-label'] === 'gsEditNode')[0].props.onClick()
322
+ await new Promise(resolve => setTimeout(resolve, 0))
323
+ assert.deepEqual(calls.find(row => row.endpoint === 'getMemory').payload, { libraryId: 'lib-b', id: 'mem-shared' })
324
+ tree = await view.render()
325
+ view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0].props.onChange({ target: { value: '' } })
326
+ tree = await view.render(true)
327
+ assert.equal(canvas().nodes.length, 204)
328
+ } finally { view.close() }
329
+ })
330
+
331
+ test('the whole-workspace graph sends its domain filter to the global endpoint', async () => {
332
+ const calls = []
333
+ const call = async (endpoint, payload) => {
334
+ calls.push({ endpoint, payload })
335
+ if (endpoint !== 'getGraph') return { items: [] }
336
+ const wanted = 'project:travel'
337
+ const hit = !payload.domain || payload.domain === wanted
338
+ return {
339
+ scope: 'global',
340
+ nodes: hit ? [{ id: 'mem-g-1', title: 'global memory', kind: 'global', domain: 'project:travel' }] : [],
341
+ edges: [],
342
+ domains: ['general', 'project:travel'],
343
+ }
344
+ }
345
+ // 没有私有库时面板落在全局图:这条路径走的是 getGlobalGraph,不是逐库合并。
346
+ const view = await graphStudioHarness(call, [])
347
+ try {
348
+ let tree = await view.render(true)
349
+ view.pick(tree, node => node.type === 'input' && node.props['aria-label'] === 'gsDomain')[0]
350
+ .props.onChange({ target: { value: 'project:travel' } })
351
+ tree = await view.render(true)
352
+ const asked = calls.filter(row => row.endpoint === 'getGraph')
353
+ const last = asked[asked.length - 1]
354
+ assert.equal(last.payload.scope, 'global', 'the panel stayed on the global graph')
355
+ assert.equal(last.payload.domain, 'project:travel', 'the global branch forwards the domain filter')
356
+ const datalist = view.pick(tree, node => node.type === 'datalist' && node.props?.id === 'dshm-graph-domains')[0]
357
+ const options = []
358
+ const visit = (value) => {
359
+ if (Array.isArray(value)) { value.forEach(visit); return }
360
+ if (value && value.type === 'option') options.push(String(value.props?.value ?? ''))
361
+ }
362
+ if (datalist) visit([].concat(datalist.props?.children ?? []))
363
+ assert.deepEqual(options, ['rp', 'coding', 'general', 'mixed', 'project:travel'].sort(),
364
+ 'the datalist keeps every domain the server reported, not only the filtered one')
365
+ } finally { view.close() }
366
+ })
367
+
368
+ test('graph studio surfaces failed libraries and retains successful results', async () => { const call = async (endpoint, payload) => {
369
+ if (endpoint !== 'getGraph') return { items: [] }
370
+ if (payload.libraryId === 'lib-denied') throw new Error('forbidden')
371
+ return { nodes: [{ id: 'mem-ok', title: 'visible', kind: 'memory' }], edges: [], nextOffset: null }
372
+ }
373
+ const view = await graphStudioHarness(call, [{ id: 'lib-ok', name: 'OK' }, { id: 'lib-denied', name: 'Denied library' }])
374
+ try {
375
+ let tree = await view.render(true)
376
+ view.pick(tree, node => node.type === 'select' && node.props['aria-label'] === 'currentLibrary')[0].props.onChange({ target: { value: '__global__' } })
377
+ tree = await view.render(true)
378
+ assert.equal(view.pick(tree, node => node.type?.name === 'GraphCanvas')[0].props.graph.nodes.length, 1)
379
+ assert.match(treeText(view.pick(tree, node => node.props?.role === 'alert')[0]), /gsLoadPartial.*Denied library/)
380
+ } finally { view.close() }
381
+ })
382
+
383
+ test('the immersive graph shell stays with the standalone WebUI', async () => {
384
+ // 点「关系图谱」把宿主页面的导航条掰成 158px 竖排,是 is-graph-wide 没分外壳造成的:
385
+ // 那套样式是为独立 WebUI 的全屏画布写的,宿主设置页只需要普通横排导航 + 一个入口按钮。
386
+ const ctx = fakeCtx()
387
+ globalThis.__dshMemuExports.apply(ctx)
388
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
389
+ assert.ok(settings?.component, 'settings.section was not registered')
390
+ const GRAPH_PAGE = 10
391
+
392
+ // The standalone shell resolves its page from the hash, so there is no
393
+ // numeric-zero page state to force on; the host shell has one.
394
+ const shell = async (props, { fromHash = false } = {}) => {
395
+ const first = await renderPage(settings.component, props, undefined, { remount: true })
396
+ if (!fromHash) collectPageHook()
397
+ for (const effect of first.effects) effect.fn()
398
+ await new Promise((resolve) => setTimeout(resolve, 0))
399
+ return (await renderPage(settings.component, props, fromHash ? undefined : GRAPH_PAGE)).tree
400
+ }
401
+
402
+ const inHost = await shell({ ctx, t: (key) => key })
403
+ assert.match(String(inHost.props?.className), /dshm-root/, 'the host graph page lost its shell')
404
+ assert.ok(!/is-graph-wide/.test(String(inHost.props?.className)),
405
+ `the host settings page must keep its horizontal rail, saw "${inHost.props?.className}"`)
406
+ const buttons = []
407
+ walkNodes(inHost, (node) => { if (node.type === 'button' && node.props?.children === 'openGraphStudio') buttons.push(node) })
408
+ assert.equal(buttons.length, 1, 'the host graph page should offer exactly one entry into the studio')
409
+ assert.equal(typeof buttons[0].props.onClick, 'function', 'the entry button has no handler')
410
+
411
+ const inWebUi = await withHash('#/settings/graph', () => shell({ ctx, t: (key) => key, standalone: true }, { fromHash: true }))
412
+ assert.match(String(inWebUi.props?.className), /is-graph-wide/, 'the standalone graph page lost its immersive shell')
413
+ })
414
+
415
+ test('the manual consolidation button rides the sidebar channel, not a new RPC', async () => {
416
+ // 「立即整理」刻意不新增方法:它查 listSessions 的库绑定,再对每个绑定会话调用
417
+ // 侧边栏同一个 generatePrivate。多一个只给 UI 用的整理方法,就等于多一条模型也能
418
+ // 调用的写路径。
419
+ const rpcCalls = []
420
+ const ctx = fakeCtx({
421
+ rpcCalls,
422
+ answers: {
423
+ getState: { ...RPC_ANSWERS.getState, libraries: [{ id: 'lib-1', name: 'L1', privateCount: 3, pinnedCount: 0, boundSessions: 2 }] },
424
+ getSettingsState: { ...RPC_ANSWERS.getSettingsState, libraries: [{ id: 'lib-1', name: 'L1', privateCount: 3, pinnedCount: 0, boundSessions: 2 }] },
425
+ listSessions: { sessions: [
426
+ { id: 's1', libraryId: 'lib-1' }, { id: 's2', libraryId: 'lib-1' }, { id: 's3', libraryId: 'lib-2' },
427
+ ] },
428
+ generatePrivate: { ok: true },
429
+ },
430
+ })
431
+ globalThis.__dshMemuExports.apply(ctx)
432
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
433
+ const props = { ctx, t: (key) => key }
434
+ const LIBRARIES_PAGE = 4
435
+ const render = async (page, remount = false) => renderPage(settings.component, props, page, { remount })
436
+ const first = await render(undefined, true)
437
+ collectPageHook()
438
+ for (const effect of first.effects) effect.fn()
439
+ await new Promise((resolve) => setTimeout(resolve, 0))
440
+ const second = await render(LIBRARIES_PAGE)
441
+ for (const effect of second.effects) effect.fn()
442
+ await new Promise((resolve) => setTimeout(resolve, 0))
443
+ const tree = (await render(LIBRARIES_PAGE)).tree
444
+
445
+ const buttons = []
446
+ walkNodes(tree, (node) => { if (node.type === 'button' && node.props?.children === 'consolidateNow') buttons.push(node) })
447
+ assert.equal(buttons.length, 1, 'the library row lost its 立即整理 button')
448
+ rpcCalls.length = 0
449
+ await buttons[0].props.onClick()
450
+ assert.deepEqual(rpcCalls, [], 'the first click must only arm the confirmation')
451
+ const armed = []
452
+ walkNodes((await render(LIBRARIES_PAGE)).tree, (node) => { if (node.type === 'button' && node.props?.children === 'confirmAction') armed.push(node) })
453
+ assert.equal(armed.length, 1, 'the arming state did not reach the button label')
454
+ await armed[0].props.onClick()
455
+ for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0))
456
+ assert.deepEqual(rpcCalls.map((c) => [c.endpoint, c.payload]), [
457
+ ['listSessions', { limit: 200 }],
458
+ ['generatePrivate', { sessionId: 's1' }],
459
+ ['generatePrivate', { sessionId: 's2' }],
460
+ ], 'consolidation must hit only the sessions bound to that library')
461
+ })
462
+
463
+ // The standalone shell reads `window.location.hash` to pick its page and rewrites
464
+ // it as the user navigates, which the host-side fixture never provides.
465
+ async function withHash(hash, run) {
466
+ const original = globalThis.window.location
467
+ const originalHistory = globalThis.window.history
468
+ globalThis.window.location = { ...original, hash }
469
+ globalThis.window.history = { ...originalHistory, replaceState: () => {} }
470
+ try { return await run() } finally {
471
+ globalThis.window.location = original
472
+ globalThis.window.history = originalHistory
473
+ }
474
+ }
475
+
476
+ test('the sidebar tab renders with the two-layer header', async () => {
477
+ const ctx = fakeCtx()
478
+ const tab = registrations.find((r) => r.slot === 'sidebar.right.pane.tab')
479
+ assert.ok(tab?.component, 'sidebar.right.pane.tab was not registered')
480
+
481
+ // The registered body is a thin wrapper around MemoryTab; hooks only run in the
482
+ // inner component, so unwrap it before rendering.
483
+ const props = { ctx, t: (key) => key, sessionId: 'probe-session' }
484
+ const wrapper = tab.component(props)
485
+ const component = typeof wrapper.type === 'function' ? wrapper.type : tab.component
486
+ const innerProps = typeof wrapper.type === 'function' ? wrapper.props : props
487
+
488
+ hooks = []
489
+ pageHookIndex = -1
490
+ const first = await renderPage(component, innerProps, undefined, { remount: true })
491
+ assert.ok(first.tree, 'sidebar tab rendered nothing')
492
+
493
+ // Feed the fetched state back in, the same way the host would.
494
+ for (const effect of first.effects) effect.fn()
495
+ await new Promise((resolve) => setTimeout(resolve, 0))
496
+ await new Promise((resolve) => setTimeout(resolve, 0))
497
+
498
+ const { tree } = await renderPage(component, innerProps)
499
+ const text = treeText(tree)
500
+ assert.match(text, /layerFolder|layerConversation|noBinding|loading/, 'sidebar lost its two-layer header')
501
+ assert.ok(!text.includes('[object Object]'), 'sidebar rendered an object as text')
502
+ // The domain picker lists ids, translated through the label map.
503
+ assert.match(text, /dmCoding/, 'domain picker did not render its options')
504
+ })
505
+
506
+ test('the sidebar context-scope card cannot be flex-shrunk and keeps a two-column field grid', () => {
507
+ const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
508
+ assert.match(src, /className: 'dshm-tab-body'/, 'the sidebar body needs its non-shrinking class')
509
+ assert.match(src, /\.dshm-tab-body>\*\{flex-shrink:0\}/, 'sidebar sections must scroll instead of shrinking')
510
+ assert.match(src, /\.dshm-scope\{width:100%;margin:0 0 10px;[^}]*flex-shrink:0/, 'the scope card must span the sidebar content width and not collapse')
511
+ assert.match(src, /\.dshm-scope-form\{[^}]*grid-template-columns:repeat\(2,minmax\(0,1fr\)\)/, 'four scope fields must wrap into two readable columns')
512
+ })
513
+
514
+ test('consolidation alerts keep identity separate from actions when expanded', async () => {
515
+ const ctx = fakeCtx()
516
+ globalThis.__dshMemuExports.apply(ctx)
517
+ const tab = registrations.filter((r) => r.slot === 'sidebar.right.pane.tab').pop()
518
+ const wrapped = tab.component({ ctx, t: (key) => key, sessionId: 'probe-session' })
519
+ const first = await renderPage(wrapped.type, wrapped.props, undefined, { remount: true })
520
+ for (const effect of first.effects) effect.fn()
521
+ await new Promise((resolve) => setTimeout(resolve, 0))
522
+ const sidebar = (await renderPage(wrapped.type, wrapped.props)).tree
523
+ let alerts
524
+ walkNodes(sidebar, (node) => {
525
+ if (node.type?.name === 'ConsolidationAlerts') { alerts = node.type; return false }
526
+ })
527
+ assert.ok(alerts)
528
+ const failure = { id: 'failure', sessionId: 's1', sessionTitle: 'A long conversation title', message: 'An unbroken failure message'.repeat(12), at: '2026-11-17T16:59:33Z' }
529
+ const success = { ...failure, id: 'success', message: 'done' }
530
+ const jumps = []
531
+ let cleared = 0
532
+ const props = { feed: { failures: [failure], successes: [success] }, t: (key) => key, onJump: row => jumps.push(row.id), onClear: () => cleared++ }
533
+ const nodes = (tree, className) => {
534
+ const found = []
535
+ walkNodes(tree, node => { if (node.props?.className === className) found.push(node) })
536
+ return found
537
+ }
538
+ let tree = (await renderPage(alerts, props, undefined, { remount: true })).tree
539
+ assert.equal(nodes(tree, 'dshm-consolidation-row').length, 1)
540
+ nodes(tree, 'dshm-consolidation-head')[0].props.onClick()
541
+ tree = (await renderPage(alerts, props)).tree
542
+ assert.equal(nodes(tree, 'dshm-consolidation-column').length, 2)
543
+ const rows = nodes(tree, 'dshm-consolidation-row')
544
+ assert.equal(rows.length, 2)
545
+ for (const row of rows) {
546
+ assert.equal(row.props.children[0].props.className, 'dshm-consolidation-identity')
547
+ assert.equal(row.props.children[1].props.className, 'dshm-consolidation-meta')
548
+ assert.equal(nodes(row, 'dshm-consolidation-label')[0].props.title, failure.sessionTitle)
549
+ assert.equal(nodes(row, 'dshm-consolidation-time').length, 1)
550
+ }
551
+ const buttons = []
552
+ walkNodes(tree, node => { if (node.type === 'button') buttons.push(node) })
553
+ buttons.find(node => node.props.title === 'consolidateJumpHint').props.onClick()
554
+ buttons.find(node => node.props.title === 'consolidateClearHint').props.onClick()
555
+ assert.deepEqual(jumps, ['failure'])
556
+ assert.equal(cleared, 1)
557
+ assert.ok(!treeText(tree).includes('consolidateStarted'))
558
+ })
559
+
560
+ test('consolidation alert columns wrap before their controls must be clipped', () => {
561
+ const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
562
+ assert.match(src, /\.dshm-consolidation-columns\{[^}]*grid-template-columns:repeat\(auto-fit,minmax\(min\(100%,240px\),1fr\)\)/)
563
+ assert.match(src, /\.dshm-consolidation-meta\{[^}]*flex-wrap:wrap/)
564
+ assert.match(src, /\.dshm-consolidation-column-head\{[^}]*flex-wrap:wrap/)
565
+ assert.match(src, /\.dshm-consolidation-label\{[^}]*text-overflow:ellipsis/)
566
+ assert.doesNotMatch(src, /\.dshm-consolidation-row\{[^}]*overflow:hidden/)
567
+ })
568
+
569
+ test('the memory UI renders the read-only arousal/dominance/emotionSource line', () => {
570
+ const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
571
+ for (const key of ['arousalLabel', 'dominanceLabel', 'emotionSourceLabel', 'emotionSourceModel', 'emotionSourceSession', 'emotionSourceContent', 'emotionSourceUnknown']) {
572
+ assert.ok(src.includes(key), `missing ${key}`)
573
+ }
574
+ assert.match(src, /emotionMetaText\(f, t\)/, 'the card tag must expose affect metadata in its title')
575
+ assert.match(src, /emotionMetaText\(shown, t\)/, 'the drawer must render the read-only affect line')
576
+ })
577
+
578
+ test('the sidebar run log keeps five rows and links its header to the WebUI logs page', () => {
579
+ const src = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
580
+ // 侧栏只显示正常流水(失败由「整理提醒」负责),列表仍是最近 5 条。
581
+ assert.match(src, /runLog\.filter\(\(row\) => logRowState\(row\) !== 'failed'\)/, 'the sidebar run log must drop failed rows')
582
+ assert.match(src, /sidebarRuns\.slice\(0, 5\)/, 'the sidebar shows the five newest runs, not an unbounded list')
583
+ assert.match(src, /openWebUiPage\('logs'\)/, 'the run-log header must open the WebUI logs page')
584
+ assert.match(src, /runLogOpen/, 'the jump needs a visible label')
585
+ // 红色只属于 WebUI 的总日志页:侧栏整段不过 logRowClass(失败行已被过滤),
586
+ // 判据仍集中在 logRowState 一处,改口径只改那一处。
587
+ assert.equal((src.match(/className: logRowClass\(row\)/g) || []).length, 1, 'only the WebUI logs page marks row state')
588
+ assert.ok(src.includes('const sidebarRuns = runLog.filter('), 'the sidebar must filter failed rows before rendering')
589
+ assert.ok(!/tone: row\.level === 'error' \? 'warn'/.test(src), 'the old level-only predicate must not come back')
590
+ })
591
+
592
+ // The browser row is the only place a human can see that a memory is marked
593
+ // "never say this out loud" or "secret" without opening the JSON. The badges are
594
+ // driven by fields that used to be stored and ignored, so a regression here is
595
+ // silent: the data stays correct and the warning disappears.
596
+ function walkNodes(node, visit, depth = 0) {
597
+ if (node === null || node === undefined || depth > 400) return
598
+ if (Array.isArray(node)) {
599
+ for (const child of node) walkNodes(child, visit, depth + 1)
600
+ return
601
+ }
602
+ if (typeof node !== 'object') return
603
+ if (visit(node, depth) === false) return
604
+ if (typeof node.type === 'function') {
605
+ walkNodes(node.type(node.props), visit, depth + 1)
606
+ return
607
+ }
608
+ walkNodes(node.props?.children, visit, depth + 1)
609
+ }
610
+
611
+ test('the memory browser badges what a memory is allowed to say', async () => {
612
+ const ctx = fakeCtx()
613
+ const originalGetState = RPC_ANSWERS.getState
614
+ const originalSettingsState = RPC_ANSWERS.getSettingsState
615
+ const originalLibraries = RPC_ANSWERS.listLibraries
616
+ const loaded = {
617
+ ...EMPTY_STATE,
618
+ libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 2 }],
619
+ }
620
+ // The pane reads the library list through both endpoints depending on the page.
621
+ RPC_ANSWERS.getState = loaded
622
+ RPC_ANSWERS.getSettingsState = loaded
623
+ RPC_ANSWERS.browseLibrary = {
624
+ source: 'engine',
625
+ files: [
626
+ {
627
+ id: 'mem-quiet',
628
+ title: 'the attic',
629
+ content: 'he never told his brother',
630
+ layer: 'short_term',
631
+ status: 'active',
632
+ decay: 0.5,
633
+ disclosure: 'never_say',
634
+ visibility: 'secret',
635
+ owner: 'about_user',
636
+ // 相对时间,不写死当天某一刻:短条目一旦过期就变成 inactive,行内编辑器不再渲染,
637
+ // 测试断言草稿能看到自己的过期状态,因此留出 6 小时余量。
638
+ expiresAt: new Date(Date.now() + 6 * 3600 * 1000).toISOString(),
639
+ },
640
+ { id: 'mem-loud', title: 'shared fact', content: 'anything', layer: 'long_term', status: 'active', decay: 0.9, disclosure: 'can_tell', visibility: 'shared', owner: 'me' },
641
+ ],
642
+ }
643
+ try {
644
+ globalThis.__dshMemuExports.apply(ctx)
645
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
646
+ assert.ok(settings?.component, 'settings.section was not registered')
647
+
648
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
649
+ collectPageHook()
650
+ for (const effect of first.effects) effect.fn()
651
+ await new Promise((resolve) => setTimeout(resolve, 0))
652
+ await new Promise((resolve) => setTimeout(resolve, 0))
653
+
654
+ // Open the library the way a click would: pick it, then press reload.
655
+ let tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
656
+ const picker = []
657
+ walkNodes(tree, (node) => {
658
+ // The layer picker of the new-memory form is also a <select>; only this one
659
+ // lists libraries.
660
+ const options = Array.isArray(node.props?.children) ? node.props.children : []
661
+ if (node.type === 'select' && options.some((option) => option?.props?.value === 'lib-1')) picker.push(node)
662
+ })
663
+ assert.equal(picker.length, 1, 'the library picker did not render')
664
+ picker[0].props.onChange({ target: { value: 'lib-1' } })
665
+
666
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
667
+ const reload = []
668
+ walkNodes(tree, (node) => {
669
+ if (typeof node.type === 'function' && node.props?.children === 'reload') reload.push(node)
670
+ })
671
+ assert.equal(reload.length, 1, 'the reload button did not render')
672
+ reload[0].props.onClick()
673
+ await new Promise((resolve) => setTimeout(resolve, 0))
674
+ await new Promise((resolve) => setTimeout(resolve, 0))
675
+
676
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
677
+ const text = treeText(tree)
678
+ // Every row carries three editor selects, so each enum label also appears in the
679
+ // option lists: two rows = 2 occurrences. A badge is the third.
680
+ const count = (needle) => text.split(needle).length - 1
681
+ assert.match(text, /layerShortTerm/, 'a short-term entry renders its layer instead of an empty tag')
682
+ assert.equal(count('discNeverSay'), 3, 'never_say is visible without opening the entry')
683
+ assert.equal(count('discCanTell'), 2, 'the default say-ability stays quiet — options only')
684
+ assert.equal(count('visSecret'), 3, 'a secret is flagged while scanning')
685
+ assert.equal(count('visShared'), 2, 'and so does the default visibility')
686
+ assert.equal(count('ownerAboutUser'), 3, 'whose fact it is shows up too')
687
+ assert.equal(count('shortTermExpires'), 1, 'and a draft shows when it dies')
688
+ assert.ok(!text.includes('[object Object]'), 'a badge rendered an object as text')
689
+ } finally {
690
+ RPC_ANSWERS.getState = originalGetState
691
+ RPC_ANSWERS.getSettingsState = originalSettingsState
692
+ RPC_ANSWERS.listLibraries = originalLibraries
693
+ delete RPC_ANSWERS.browseLibrary
694
+ }
695
+ })
696
+
697
+ test('the memory browser decides pending reviews in place', async () => {
698
+ // 待复核条目在浏览页的复核池里就有接受/丢弃按钮,不必绕去全局页队列;
699
+ // 点击走的是同一个 resolveReview RPC,带本库 libraryId。
700
+ const rpcCalls = []
701
+ const ctx = fakeCtx({ rpcCalls })
702
+ const originalGetState = RPC_ANSWERS.getState
703
+ const originalSettingsState = RPC_ANSWERS.getSettingsState
704
+ const loaded = {
705
+ ...EMPTY_STATE,
706
+ libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 1 }],
707
+ }
708
+ RPC_ANSWERS.getState = loaded
709
+ RPC_ANSWERS.getSettingsState = loaded
710
+ RPC_ANSWERS.browseLibrary = {
711
+ source: 'engine',
712
+ files: [
713
+ { id: 'mem-pending', title: 'pending fact', content: 'awaiting a human', layer: 'long_term', status: 'pending_review', decay: 0.5, disclosure: 'can_tell', visibility: 'shared' },
714
+ { id: 'mem-active', title: 'settled fact', content: 'already true', layer: 'long_term', status: 'active', decay: 0.9, disclosure: 'can_tell', visibility: 'shared' },
715
+ ],
716
+ }
717
+ RPC_ANSWERS.resolveReview = { id: 'mem-pending', status: 'active', resolution: 'replace' }
718
+ RPC_ANSWERS.listReviews = { items: [] }
719
+ try {
720
+ globalThis.__dshMemuExports.apply(ctx)
721
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
722
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
723
+ collectPageHook()
724
+ for (const effect of first.effects) effect.fn()
725
+ await new Promise((resolve) => setTimeout(resolve, 0))
726
+ await new Promise((resolve) => setTimeout(resolve, 0))
727
+
728
+ let tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
729
+ const picker = []
730
+ walkNodes(tree, (node) => {
731
+ const options = Array.isArray(node.props?.children) ? node.props.children : []
732
+ if (node.type === 'select' && options.some((option) => option?.props?.value === 'lib-1')) picker.push(node)
733
+ })
734
+ picker[0].props.onChange({ target: { value: 'lib-1' } })
735
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
736
+ const reload = []
737
+ walkNodes(tree, (node) => {
738
+ if (typeof node.type === 'function' && node.props?.children === 'reload') reload.push(node)
739
+ })
740
+ reload[0].props.onClick()
741
+ await new Promise((resolve) => setTimeout(resolve, 0))
742
+ await new Promise((resolve) => setTimeout(resolve, 0))
743
+
744
+ // 切到复核池:页签文案是 poolReview + 计数。
745
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
746
+ const reviewTab = []
747
+ walkNodes(tree, (node) => {
748
+ if (node.type === 'button' && String(node.props?.children || '').startsWith('poolReview')) reviewTab.push(node)
749
+ })
750
+ assert.equal(reviewTab.length, 1, 'the review pool tab did not render')
751
+ reviewTab[0].props.onClick()
752
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 5)).tree
753
+ const buttons = []
754
+ walkNodes(tree, (node) => {
755
+ if (typeof node.type === 'function' && (node.props?.children === 'accept' || node.props?.children === 'reject')) buttons.push(node)
756
+ })
757
+ assert.equal(buttons.length, 2, 'the pending row offers exactly accept and reject')
758
+ const accept = buttons.find((node) => node.props.children === 'accept')
759
+ accept.props.onClick()
760
+ await new Promise((resolve) => setTimeout(resolve, 0))
761
+ await new Promise((resolve) => setTimeout(resolve, 0))
762
+ const resolved = rpcCalls.filter((call) => call.endpoint === 'resolveReview')
763
+ assert.equal(resolved.length, 1, 'accept fires exactly one resolveReview')
764
+ assert.equal(resolved[0].payload.id, 'mem-pending')
765
+ assert.equal(resolved[0].payload.libraryId, 'lib-1')
766
+ assert.equal(resolved[0].payload.action, 'accept')
767
+ } finally {
768
+ RPC_ANSWERS.getState = originalGetState
769
+ RPC_ANSWERS.getSettingsState = originalSettingsState
770
+ delete RPC_ANSWERS.browseLibrary
771
+ delete RPC_ANSWERS.resolveReview
772
+ delete RPC_ANSWERS.listReviews
773
+ }
774
+ })
775
+
776
+ test('the memory wall drawer decides pending reviews without leaving the wall', async () => {
777
+ const rpcCalls = []
778
+ const ctx = fakeCtx({ rpcCalls })
779
+ const originalGetState = RPC_ANSWERS.getState
780
+ const originalSettingsState = RPC_ANSWERS.getSettingsState
781
+ const loaded = {
782
+ ...EMPTY_STATE,
783
+ libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 1 }],
784
+ }
785
+ RPC_ANSWERS.getState = loaded
786
+ RPC_ANSWERS.getSettingsState = loaded
787
+ RPC_ANSWERS.browseWall = {
788
+ total: 1,
789
+ items: [{ id: 'mem-pending', libraryId: 'lib-1', libraryName: 'demo', title: 'pending fact', preview: 'awaiting a human', layer: 'long_term', status: 'pending_review', source: 'inferred', decay: 0.5, tags: [] }],
790
+ }
791
+ RPC_ANSWERS.getMemory = { id: 'mem-pending', libraryId: 'lib-1', entry: { title: 'pending fact', content: 'awaiting a human', status: 'pending_review', layer: 'long_term', disclosure: 'can_tell' }, attachments: [] }
792
+ RPC_ANSWERS.resolveReview = { id: 'mem-pending', status: 'active', resolution: 'replace' }
793
+ try {
794
+ globalThis.__dshMemuExports.apply(ctx)
795
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
796
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
797
+ collectPageHook()
798
+ for (const effect of first.effects) effect.fn()
799
+ await new Promise((resolve) => setTimeout(resolve, 0))
800
+ await new Promise((resolve) => setTimeout(resolve, 0))
801
+
802
+ let tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
803
+ // 墙的数据加载在 MemoryWallPanel 自己的 effect 里:展开子组件登记 effect 再执行。
804
+ treeText(tree)
805
+ for (const effect of effects) effect.fn()
806
+ await new Promise((resolve) => setTimeout(resolve, 0))
807
+ await new Promise((resolve) => setTimeout(resolve, 0))
808
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
809
+ // 墙默认看活跃池;待复核条目在复核池,先切池再找卡片。
810
+ const poolTab = []
811
+ walkNodes(tree, (node) => {
812
+ if (node.type === 'button' && String(node.props?.children || '').startsWith('poolReview')) poolTab.push(node)
813
+ })
814
+ assert.equal(poolTab.length, 1, 'the wall review pool tab did not render')
815
+ poolTab[0].props.onClick()
816
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
817
+ const cards = []
818
+ walkNodes(tree, (node) => {
819
+ if (node.type === 'button' && String(node.props?.className || '').includes('dshm-wall-item')) cards.push(node)
820
+ })
821
+ assert.equal(cards.length, 1, 'the pending card did not render on the wall')
822
+ cards[0].props.onClick()
823
+ await new Promise((resolve) => setTimeout(resolve, 0))
824
+ await new Promise((resolve) => setTimeout(resolve, 0))
825
+
826
+ tree = (await renderPage(settings.component, { ctx, t: (key) => key }, 9)).tree
827
+ const buttons = []
828
+ walkNodes(tree, (node) => {
829
+ if (typeof node.type === 'function' && (node.props?.children === 'accept' || node.props?.children === 'reject')) buttons.push(node)
830
+ })
831
+ assert.equal(buttons.length, 2, 'the drawer offers accept and reject for a pending review')
832
+ buttons.find((node) => node.props.children === 'reject').props.onClick()
833
+ await new Promise((resolve) => setTimeout(resolve, 0))
834
+ await new Promise((resolve) => setTimeout(resolve, 0))
835
+ const resolved = rpcCalls.filter((call) => call.endpoint === 'resolveReview')
836
+ assert.equal(resolved.length, 1, 'reject fires exactly one resolveReview')
837
+ assert.equal(resolved[0].payload.id, 'mem-pending')
838
+ assert.equal(resolved[0].payload.libraryId, 'lib-1')
839
+ assert.equal(resolved[0].payload.action, 'reject')
840
+ } finally {
841
+ RPC_ANSWERS.getState = originalGetState
842
+ RPC_ANSWERS.getSettingsState = originalSettingsState
843
+ delete RPC_ANSWERS.browseWall
844
+ delete RPC_ANSWERS.getMemory
845
+ delete RPC_ANSWERS.resolveReview
846
+ }
847
+ })
848
+
849
+ test('the browse search box filters the loaded library in place', async () => {
850
+ // 搜索是纯前端的:它只过滤已经拉回来的那一页,不新发 RPC。库一切换就清空,
851
+ // 否则上一个库的关键词会把当前库筛成「空库」。
852
+ const originalGetState = RPC_ANSWERS.getState
853
+ const originalSettingsState = RPC_ANSWERS.getSettingsState
854
+ const loaded = { ...EMPTY_STATE, libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 2 }] }
855
+ RPC_ANSWERS.getState = loaded
856
+ RPC_ANSWERS.getSettingsState = loaded
857
+ RPC_ANSWERS.browseLibrary = {
858
+ source: 'engine',
859
+ files: [
860
+ { id: 'mem-attic', title: 'the attic', content: 'he never told his brother', layer: 'long_term', status: 'active', decay: .5 },
861
+ { id: 'mem-loud', title: 'shared fact', content: 'anything', layer: 'long_term', status: 'active', decay: .9 },
862
+ ],
863
+ }
864
+ try {
865
+ const rpcCalls = []
866
+ const ctx = fakeCtx({ rpcCalls })
867
+ globalThis.__dshMemuExports.apply(ctx)
868
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
869
+ const props = { ctx, t: (key) => key }
870
+ const render = (page, remount = false) => renderPage(settings.component, props, page, { remount })
871
+ const first = await render(undefined, true)
872
+ collectPageHook()
873
+ for (const effect of first.effects) effect.fn()
874
+ await new Promise((resolve) => setTimeout(resolve, 0))
875
+ let tree = (await render(5)).tree
876
+ const picker = []
877
+ walkNodes(tree, (node) => {
878
+ const options = Array.isArray(node.props?.children) ? node.props.children : []
879
+ if (node.type === 'select' && options.some((option) => option?.props?.value === 'lib-1')) picker.push(node)
880
+ })
881
+ picker[0].props.onChange({ target: { value: 'lib-1' } })
882
+ tree = (await render(5)).tree
883
+ const reload = []
884
+ walkNodes(tree, (node) => { if (node.type === 'button' && node.props?.children === 'reload') reload.push(node) })
885
+ reload[0].props.onClick()
886
+ for (let i = 0; i < 3; i++) await new Promise((resolve) => setTimeout(resolve, 0))
887
+ tree = (await render(5)).tree
888
+
889
+ // Rows carry their title in an editor input, so counting rendered values beats
890
+ // grepping the flattened tree.
891
+ const snapshot = (node) => {
892
+ const titles = []
893
+ let rows = 0
894
+ walkNodes(node, (n) => {
895
+ if (n.type === 'button' && n.props?.children === 'archive') rows++
896
+ if (n.type === 'input' && (n.props?.value === 'the attic' || n.props?.value === 'shared fact')) titles.push(n.props.value)
897
+ })
898
+ return { rows, titles }
899
+ }
900
+
901
+ const before = snapshot(tree)
902
+ assert.deepEqual(before, { rows: 2, titles: ['the attic', 'shared fact'] }, 'both rows render before filtering')
903
+ rpcCalls.length = 0
904
+ const box = []
905
+ walkNodes(tree, (node) => { if (node.type === 'input' && node.props?.placeholder === 'browseSearchPlaceholder') box.push(node) })
906
+ assert.equal(box.length, 1, 'no search box under 当前记忆库')
907
+ box[0].props.onChange({ target: { value: 'attic' } })
908
+ const filteredTree = (await render(5)).tree
909
+ assert.deepEqual(snapshot(filteredTree), { rows: 1, titles: ['the attic'] }, 'the filter keeps only the matching row')
910
+ assert.match(treeText(filteredTree), /1 \/ 2/, 'the counter says how much of the library the filter kept')
911
+ assert.match(treeText(filteredTree), /browseActiveTab \(1\)/, 'the tab counts follow the filter, not the whole library')
912
+ assert.deepEqual(rpcCalls, [], 'filtering an already loaded library must not re-fetch it')
913
+ box[0].props.onChange({ target: { value: 'no-such-memory' } })
914
+ assert.match(treeText((await render(5)).tree), /browseActiveTab \(0\)/, 'a query that matches nothing empties the tab counts')
915
+ const clear = []
916
+ walkNodes((await render(5)).tree, (node) => { if (node.type === 'button' && node.props?.children === 'browseSearchClear') clear.push(node) })
917
+ assert.equal(clear.length, 1, 'no way to clear the query')
918
+ clear[0].props.onClick()
919
+ assert.deepEqual(snapshot((await render(5)).tree), before, 'clearing the query brings the library back')
920
+ } finally {
921
+ RPC_ANSWERS.getState = originalGetState
922
+ RPC_ANSWERS.getSettingsState = originalSettingsState
923
+ delete RPC_ANSWERS.browseLibrary
924
+ }
925
+ })
926
+
927
+ test('the WebUI buttons open a new tab and never navigate this one', async () => {
928
+ const opened = []
929
+ const navigated = []
930
+ const originalWindow = { open: globalThis.window.open, location: globalThis.window.location }
931
+ globalThis.window.location = { href: 'http://host/app', assign: (url) => navigated.push(url) }
932
+ try {
933
+ const ctx = fakeCtx()
934
+ globalThis.__dshMemuExports.apply(ctx)
935
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
936
+ assert.ok(settings?.component, 'settings.section was not registered')
937
+
938
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
939
+ collectPageHook()
940
+ for (const effect of first.effects) effect.fn()
941
+ await new Promise((resolve) => setTimeout(resolve, 0))
942
+ await new Promise((resolve) => setTimeout(resolve, 0))
943
+
944
+ const buttons = []
945
+ walkNodes((await renderPage(settings.component, { ctx, t: (key) => key }, 0)).tree, (node) => {
946
+ if (node.type === 'button' && node.props?.children === 'openMemu') buttons.push(node)
947
+ })
948
+ assert.equal(buttons.length, 1, 'the WebUI button did not render')
949
+
950
+ globalThis.window.open = (url) => { opened.push(url); return { focus() {}, opener: null } }
951
+ buttons[0].props.onClick()
952
+ assert.equal(opened.length, 1, 'a popup was requested')
953
+ assert.ok(opened[0].includes('/dsh-memu-memory/ui') && /[?&]theme=(light|dark)/.test(opened[0]) && opened[0].endsWith('#/settings/engine'), `unexpected url: ${opened[0]}`)
954
+ assert.deepEqual(navigated, [], 'no fallback navigation while the popup works')
955
+
956
+ // Blocked popups return null: fall back to an in-app overlay. Navigating this
957
+ // tab would unload the app and look like a forced refresh on the way back.
958
+ appendedNodes.length = 0
959
+ globalThis.window.open = () => null
960
+ buttons[0].props.onClick()
961
+ assert.equal(appendedNodes.length, 1, 'blocked popups open an in-app overlay')
962
+ const overlay = appendedNodes[0]
963
+ assert.equal(overlay.attrs['data-dsh-memu-memory-webui'], '', 'the overlay is marked')
964
+ const frame = overlay.children.find((child) => child.tag === 'iframe')
965
+ assert.ok(frame, 'the overlay hosts an iframe')
966
+ assert.ok(String(frame.src).includes('/dsh-memu-memory/ui') && /[?&]theme=(light|dark)/.test(String(frame.src)) && String(frame.src).endsWith('#/settings/engine'), `unexpected url: ${frame.src}`)
967
+ assert.deepEqual(navigated, [], 'the current tab is never navigated')
968
+ // The close control lives inside the page; the overlay only waits for its message.
969
+ assert.equal(overlay.children.length, 1, 'no floating chrome outside the panel')
970
+ } finally {
971
+ globalThis.window.open = originalWindow.open
972
+ globalThis.window.location = originalWindow.location
973
+ }
974
+ })
975
+
976
+ test('the sidebar and the settings page hand out the same WebUI button', async () => {
977
+ // Two spellings of one action is how the panes drift: the sidebar used to label
978
+ // this button openSettingsShort while the settings page used openWebUi. Both
979
+ // surfaces now render the same widget with the same label, hint and handler, and
980
+ // the embedded settings page drops its own copy so the sidebar never shows two.
981
+ async function renderSurface(component, props, page) {
982
+ hooks = []
983
+ pageHookIndex = -1
984
+ const first = await renderPage(component, props, page, { remount: true })
985
+ if (page !== undefined) collectPageHook()
986
+ for (const effect of first.effects) effect.fn()
987
+ await new Promise((resolve) => setTimeout(resolve, 0))
988
+ await new Promise((resolve) => setTimeout(resolve, 0))
989
+ const tree = (await renderPage(component, props, page)).tree
990
+ const found = []
991
+ walkNodes(tree, (node) => {
992
+ if (node.type === 'button' && node.props?.children === 'openMemu') found.push(node)
993
+ })
994
+ return { tree, found }
995
+ }
996
+
997
+ const ctx = fakeCtx()
998
+ globalThis.__dshMemuExports.apply(ctx)
999
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1000
+ const tab = registrations.filter((r) => r.slot === 'sidebar.right.pane.tab').pop()
1001
+ assert.ok(settings?.component && tab?.component, 'both surfaces are registered')
1002
+
1003
+ const inSettings = await renderSurface(settings.component, { ctx, t: (key) => key }, 0)
1004
+ assert.equal(inSettings.found.length, 1, 'the settings page lost its WebUI button')
1005
+
1006
+ const props = { ctx, t: (key) => key, sessionId: 'probe-session' }
1007
+ const wrapper = tab.component(props)
1008
+ const inner = typeof wrapper.type === 'function' ? wrapper.type : tab.component
1009
+ const innerProps = typeof wrapper.type === 'function' ? wrapper.props : props
1010
+ const inSidebar = await renderSurface(inner, innerProps, undefined)
1011
+ assert.equal(inSidebar.found.length, 1, 'the sidebar lost its WebUI button')
1012
+ assert.ok(!treeText(inSidebar.tree).includes('openSettings'), 'a second settings entry must not return')
1013
+
1014
+ // The panel returns early while the conversation is still unknown, before its
1015
+ // `pages` array is built. Effects scheduled by that render still run, and one of
1016
+ // them reads `pages` — touching it then is a temporal-dead-zone error that the
1017
+ // sidebar surfaces as "dsh-better-sidebar: Cannot access 'pages' before
1018
+ // initialization". Rendering without a session must stay quiet.
1019
+ for (const empty of [null, undefined]) {
1020
+ const quiet = await renderSurface(inner, { ...innerProps, sessionId: empty }, undefined)
1021
+ assert.ok(treeText(quiet.tree).includes('loading'), 'the unbound panel shows its loading state')
1022
+ }
1023
+
1024
+ for (const node of [...inSettings.found, ...inSidebar.found]) {
1025
+ assert.equal(node.props.className, 'dshm-btn', 'the button bypasses the shared widget')
1026
+ assert.equal(node.props.title, 'openWebUiHint', 'the button carries a different hint')
1027
+ assert.equal(typeof node.props.onClick, 'function', 'the button has no handler')
1028
+ }
1029
+ // The old keys are gone rather than kept around as a second spelling.
1030
+ const text = `${treeText(inSettings.tree)} ${treeText(inSidebar.tree)}`
1031
+ assert.ok(!text.includes('openSettingsShort'), 'the second WebUI label came back')
1032
+ })
1033
+
1034
+ test('every pick-one-of-these control uses the same tab strip', async () => {
1035
+ // The settings rail, the prompt scope, the browser's active/archived split and
1036
+ // the memory backend are one widget (dshm-nav-item). They used to be three
1037
+ // widgets with three different hover and focus states, which is what read as
1038
+ // "the sidebar and the settings page do not match".
1039
+ const ctx = fakeCtx()
1040
+ globalThis.__dshMemuExports.apply(ctx)
1041
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1042
+
1043
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
1044
+ collectPageHook()
1045
+ for (const effect of first.effects) effect.fn()
1046
+ await new Promise((resolve) => setTimeout(resolve, 0))
1047
+ await new Promise((resolve) => setTimeout(resolve, 0))
1048
+
1049
+ const orphans = []
1050
+ for (let page = 0; page < 12; page++) {
1051
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, page)
1052
+ walkNodes(tree, (node) => {
1053
+ if (node.type !== 'button') return
1054
+ const className = String(node.props?.className || '')
1055
+ if (node.props?.role === 'tab' && !className.includes('dshm-nav-item')) {
1056
+ orphans.push(`page ${page}: ${JSON.stringify(node.props?.children)}`)
1057
+ }
1058
+ if (className.includes('dshm-nav-item')) {
1059
+ assert.equal(typeof node.props.onClick, 'function', `page ${page} lost a tab handler`)
1060
+ }
1061
+ })
1062
+ }
1063
+ assert.deepEqual(orphans, [], 'a tab strip sits outside the shared widget')
1064
+ })
1065
+
1066
+ // Task C: the statistics page is data-driven, so it only paints after two lazy
1067
+ // loads (pick the first library, then read its stats). The charts are hand-written
1068
+ // SVG — counting nodes is the honest check that thirty bars and one dot per memory
1069
+ // actually reached the DOM, and that an empty day did not become NaN.
1070
+ test('the statistics page draws the daily bars, the scatter and the shortlist', async () => {
1071
+ const ctx = fakeCtx()
1072
+ const originalState = RPC_ANSWERS.getSettingsState
1073
+ RPC_ANSWERS.getSettingsState = {
1074
+ ...EMPTY_STATE,
1075
+ libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo' }],
1076
+ }
1077
+ RPC_ANSWERS.getStats = {
1078
+ libraryId: 'lib-1',
1079
+ available: true,
1080
+ keptDays: 90,
1081
+ windowDays: 30,
1082
+ days: Array.from({ length: 30 }, (_, i) => ({
1083
+ date: `2026-09-${String(i + 1).padStart(2, '0')}`,
1084
+ written: i === 29 ? 2 : 0,
1085
+ injected: i % 3,
1086
+ recalled: 0,
1087
+ archived: 0,
1088
+ })),
1089
+ totals: { written: 2, injected: 30, recalled: 4, archived: 1 },
1090
+ ratio: { windowDays: 7, written: 2, injected: 9 },
1091
+ health: { total: 2, active: 2, marginalized: 0, archived: 0, pendingReview: 0, avgStrength: 0.71 },
1092
+ distribution: [
1093
+ { id: 'mem-a', title: 'often recalled', layer: 'long_term', ageDays: 3, injectCount: 4, accessCount: 2 },
1094
+ { id: 'mem-b', title: 'never recalled', layer: 'long_term', ageDays: 9, injectCount: 0, accessCount: 0 },
1095
+ ],
1096
+ distributionTotal: 2,
1097
+ stale: [{ id: 'mem-b', title: 'never recalled', daysSinceTouch: 9 }],
1098
+ }
1099
+ const run = async (effectsToRun) => {
1100
+ for (const effect of effectsToRun) effect.fn()
1101
+ await new Promise((resolve) => setTimeout(resolve, 0))
1102
+ await new Promise((resolve) => setTimeout(resolve, 0))
1103
+ }
1104
+ try {
1105
+ globalThis.__dshMemuExports.apply(ctx)
1106
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1107
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
1108
+ collectPageHook()
1109
+ await run(first.effects)
1110
+
1111
+ let pass = await renderPage(settings.component, { ctx, t: (key) => key }, 8)
1112
+ await run(pass.effects)
1113
+ pass = await renderPage(settings.component, { ctx, t: (key) => key }, 8)
1114
+ await run(pass.effects)
1115
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 8)
1116
+
1117
+ const counts = { rects: 0, circles: 0 }
1118
+ walkNodes(tree, (node) => {
1119
+ if (node.type === 'rect') counts.rects += 1
1120
+ if (node.type === 'circle') counts.circles += 1
1121
+ })
1122
+ assert.equal(counts.rects, 30, 'thirty daily bars, including the quiet days')
1123
+ assert.equal(counts.circles, 2, 'one scatter dot per memory')
1124
+ const text = treeText(tree)
1125
+ assert.match(text, /statsWritten/, 'the window totals render')
1126
+ assert.match(text, /statsStaleDays/, 'the archive shortlist renders')
1127
+ assert.ok(!text.includes('NaN'), 'an empty day must not paint NaN')
1128
+ assert.ok(!text.includes('[object Object]'), 'the page rendered an object as text')
1129
+ } finally {
1130
+ RPC_ANSWERS.getSettingsState = originalState
1131
+ delete RPC_ANSWERS.getStats
1132
+ }
1133
+ })
1134
+
1135
+ test('the memory tab is registered exactly once, with or without better-sidebar', () => {
1136
+ function appCtx(initialBetter) {
1137
+ const seen = { native: [], better: [], pending: {} }
1138
+ let better = initialBetter
1139
+ const slotsScope = { effect: (fn) => { try { fn() } catch {} }, register: () => () => {}, inject: (_n, cb) => cb(slotsScope) }
1140
+ const scope = {
1141
+ effect: (fn) => { const dispose = fn(); return () => { try { dispose?.() } catch {} } },
1142
+ get: (name) => (name === 'betterSidebar' ? better : undefined),
1143
+ sidebarRightTabs: {
1144
+ register: (spec) => {
1145
+ seen.native.push(spec)
1146
+ return () => { const at = seen.native.indexOf(spec); if (at >= 0) seen.native.splice(at, 1) }
1147
+ },
1148
+ },
1149
+ slots: { inject: (_n, cb) => cb(slotsScope), register: () => () => {} },
1150
+ }
1151
+ const ctx = {
1152
+ effect: () => {},
1153
+ locale: { register: () => () => {}, bind: () => (key) => key, get: () => 'zh' },
1154
+ connection: { rpc: { call: async () => ({ ok: true, value: {} }) } },
1155
+ sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: {}, ids: [] }) } },
1156
+ get: (name) => (name === 'betterSidebar' ? better : undefined),
1157
+ slots: { inject: (_n, cb) => cb(scope), register: () => () => {} },
1158
+ inject: (deps, callback) => {
1159
+ const key = deps[0]
1160
+ seen.pending[key] = callback
1161
+ if (key === 'betterSidebar' && !better) return
1162
+ callback(scope)
1163
+ },
1164
+ }
1165
+ return {
1166
+ ctx,
1167
+ seen,
1168
+ later(service) { better = service; seen.pending.betterSidebar(scope) },
1169
+ }
1170
+ }
1171
+
1172
+ let betterCalls = 0
1173
+ const betterService = () => ({ registerTab: () => { betterCalls += 1; return () => {} } })
1174
+
1175
+ // No better-sidebar: the native tab is the only entry.
1176
+ const a = appCtx(null)
1177
+ globalThis.__dshMemuExports.apply(a.ctx)
1178
+ assert.equal(a.seen.native.length, 1, 'native tab registered when better-sidebar is absent')
1179
+ assert.equal(a.seen.better.length, 0)
1180
+
1181
+ // Installed up front: only its tab, otherwise the start list shows two.
1182
+ const b = appCtx(betterService())
1183
+ globalThis.__dshMemuExports.apply(b.ctx)
1184
+ assert.equal(b.seen.native.length, 0, 'native tab must not register when better-sidebar exists')
1185
+ assert.equal(betterCalls, 1, 'its own tab is registered instead')
1186
+
1187
+ // Installed after us: the native tab we already registered has to go.
1188
+ const c = appCtx(null)
1189
+ globalThis.__dshMemuExports.apply(c.ctx)
1190
+ assert.equal(c.seen.native.length, 1)
1191
+ let betterRegistrations = 0
1192
+ c.later({ registerTab: () => { betterRegistrations += 1; return () => {} } })
1193
+ assert.equal(c.seen.native.length, 0, 'late better-sidebar removes the native tab')
1194
+ assert.equal(betterRegistrations, 1, 'and registers its own')
1195
+ })
1196
+
1197
+ // Exercise the actual settings component, not source-text matches: stale vector
1198
+ // configuration must not escape the Agent gate, and rendering must never install.
1199
+ async function renderVectorSettings(t, overrides = {}, answers = {}, pageValue = 1) {
1200
+ const loaded = {
1201
+ ...EMPTY_STATE,
1202
+ ...overrides,
1203
+ settings: { ...EMPTY_STATE.settings, ...overrides.settings },
1204
+ memuConfig: { ...EMPTY_STATE.memuConfig, ...overrides.memuConfig },
1205
+ }
1206
+ const rpcCalls = []
1207
+ const ctx = fakeCtx({ answers: { getSettingsState: loaded, ...answers }, rpcCalls })
1208
+ globalThis.__dshMemuExports.apply(ctx)
1209
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1210
+ assert.ok(settings?.component, 'settings.section was not registered')
1211
+ const props = { ctx, t: (key) => key }
1212
+ const first = await renderPage(settings.component, props, undefined, { remount: true })
1213
+ collectPageHook()
1214
+ const cleanups = []
1215
+ t.after(() => { for (const cleanup of cleanups.reverse()) cleanup() })
1216
+ for (const effect of first.effects) {
1217
+ const cleanup = effect.fn()
1218
+ if (typeof cleanup === 'function') cleanups.push(cleanup)
1219
+ }
1220
+ await new Promise((resolve) => setTimeout(resolve, 0))
1221
+ await new Promise((resolve) => setTimeout(resolve, 0))
1222
+ const tree = (await renderPage(settings.component, props, pageValue)).tree
1223
+ const nodes = []
1224
+ walkNodes(tree, (node) => { nodes.push(node) })
1225
+ const rerender = async () => {
1226
+ const { tree, effects } = await renderPage(settings.component, props, pageValue)
1227
+ const nodes = []
1228
+ walkNodes(tree, node => { nodes.push(node) })
1229
+ return { tree, nodes, effects }
1230
+ }
1231
+ return { tree, nodes, rpcCalls, rerender }
1232
+ }
1233
+
1234
+ const VECTOR_CATALOG_FIXTURE = {
1235
+ catalog: [
1236
+ { id: 'fixture-download', displayName: 'Fixture Download Model', availability: 'available', dimension: 384, totalBytes: 100 },
1237
+ { id: 'fixture-pending', displayName: 'Fixture Pending Model', availability: 'pending', pendingReasons: ['SHA-256 pending'], dimension: 384 },
1238
+ { id: 'fixture-installed', displayName: 'Fixture Installed Model', availability: 'available', dimension: 384 },
1239
+ ],
1240
+ installations: { 'fixture-installed': { installed: true, fingerprintMatches: true, status: 'installed' } },
1241
+ vector: {},
1242
+ }
1243
+
1244
+ test('the default Agent backend hides vector source, catalog and API configuration', async (t) => {
1245
+ const { tree, nodes, rpcCalls } = await renderVectorSettings(t, {
1246
+ memuConfig: { source: 'api', model: 'stale-api-model' },
1247
+ localVector: VECTOR_CATALOG_FIXTURE,
1248
+ })
1249
+ const text = treeText(tree)
1250
+ assert.match(text, /backendAgent/)
1251
+ assert.ok(nodes.some((node) => node.type === 'button' && node.props.children === 'backendAgent' && node.props['aria-selected'] === true))
1252
+ for (const hidden of ['vectorSource', 'managedVector', 'Fixture Download Model', 'summaryModel']) {
1253
+ assert.ok(!text.includes(hidden), hidden + ' escaped the default Agent gate')
1254
+ }
1255
+ assert.ok(!nodes.some((node) => node.type === 'input' && node.props.value === 'stale-api-model'))
1256
+ assert.ok(!rpcCalls.some((call) => /downloadLocalVector|setEmbeddingSource|switchLocalVector/.test(call.endpoint)))
1257
+ })
1258
+
1259
+ test('local vector settings render catalog controls and native download and migration progress', async (t) => {
1260
+ const { tree, nodes, rpcCalls } = await renderVectorSettings(t, {
1261
+ settings: { memoryBackend: 'api', vectorSource: 'local' },
1262
+ localVector: {
1263
+ ...VECTOR_CATALOG_FIXTURE,
1264
+ installations: {
1265
+ ...VECTOR_CATALOG_FIXTURE.installations,
1266
+ 'fixture-download': { status: 'downloading', progress: { files: 2, done: 1, bytes: 25, totalBytes: 100, current: 'model.onnx' } },
1267
+ },
1268
+ vector: {
1269
+ active: { catalogId: 'previous-model' },
1270
+ requested: { catalogId: 'fixture-installed' },
1271
+ pending: { report: { progress: { completed: 2, total: 8, generation: 3, stage: 'embedding', current: { itemId: 'memory-2' } } } },
1272
+ },
1273
+ },
1274
+ })
1275
+ const text = treeText(tree)
1276
+ for (const visible of ['vectorSourceLocal', 'Fixture Download Model', 'Fixture Pending Model', 'SHA-256 pending', 'managedVectorDownload', 'managedVectorSelect', 'managedVectorSwitch', 'managedVectorRollback', 'model.onnx', 'memory-2']) {
1277
+ assert.ok(text.includes(visible), visible + ' did not render')
1278
+ }
1279
+ const download = nodes.filter((node) => node.type === 'button' && node.props.children === 'managedVectorDownload')
1280
+ assert.equal(download.length, 1, 'a pending manifest must not get a download button')
1281
+ const progress = nodes.filter((node) => node.type === 'progress')
1282
+ assert.equal(progress.length, 2)
1283
+ assert.ok(progress.some((node) => node.props['aria-label'] === 'managedVectorProgress' && node.props.value === 25 && node.props.max === 100))
1284
+ assert.ok(progress.some((node) => node.props['aria-label'] === 'managedVectorRebuilding' && node.props.value === 2 && node.props.max === 8))
1285
+ assert.equal(nodes.filter((node) => node.props?.role === 'status' && node.props['aria-live'] === 'polite').length, 2)
1286
+ assert.ok(!nodes.some((node) => node.type === 'input' && node.props.type === 'password'), 'API key fields leaked into local source')
1287
+ assert.ok(!rpcCalls.some((call) => /downloadLocalVector|selectLocalVector|switchLocalVector/.test(call.endpoint)), 'rendering performed a model operation')
1288
+ })
1289
+
1290
+ test('runtime download shows MB/s, selectable sources and pause/stop controls', async (t) => {
1291
+ const { tree, nodes, rpcCalls } = await renderVectorSettings(t, {
1292
+ settings: { memoryBackend: 'api', vectorSource: 'local' },
1293
+ localVector: {
1294
+ ...VECTOR_CATALOG_FIXTURE,
1295
+ runtime: {
1296
+ status: 'downloading',
1297
+ ready: false,
1298
+ sources: [
1299
+ { id: 'npmjs', label: 'npmjs' },
1300
+ { id: 'npmmirror', label: 'npmmirror' },
1301
+ ],
1302
+ downloadSource: 'npmjs',
1303
+ progress: {
1304
+ bytes: 50 * 1048576,
1305
+ totalBytes: 100 * 1048576,
1306
+ speedBps: 2.5 * 1048576,
1307
+ current: 'onnxruntime-node',
1308
+ },
1309
+ },
1310
+ vector: {},
1311
+ },
1312
+ })
1313
+ const text = treeText(tree)
1314
+ for (const visible of ['managedVectorPause', 'managedVectorStop', 'managedVectorRuntimeSource', 'npmjs', 'npmmirror', '2.5 MB/s']) {
1315
+ assert.ok(text.includes(visible), visible + ' did not render')
1316
+ }
1317
+ const progress = nodes.find((node) => node.type === 'progress' && node.props['aria-label'] === 'managedVectorProgress')
1318
+ assert.ok(progress, 'runtime progress bar missing')
1319
+ assert.equal(progress.props.value, 50 * 1048576)
1320
+ assert.equal(progress.props.max, 100 * 1048576)
1321
+ const pause = nodes.find((node) => node.type === 'button' && node.props.children === 'managedVectorPause')
1322
+ const stop = nodes.find((node) => node.type === 'button' && node.props.children === 'managedVectorStop')
1323
+ assert.ok(pause && stop, 'pause/stop buttons missing')
1324
+ await pause.props.onClick()
1325
+ await new Promise((resolve) => setTimeout(resolve, 0))
1326
+ assert.ok(rpcCalls.some((call) => call.endpoint === 'installLocalVectorRuntime' && call.payload?.action === 'pause'))
1327
+ })
1328
+
1329
+ test('migration with unknown total renders indeterminate native progress', async (t) => {
1330
+ const { tree, nodes } = await renderVectorSettings(t, {
1331
+ settings: { memoryBackend: 'api', vectorSource: 'local' },
1332
+ localVector: { catalog: [], installations: {}, vector: { pending: { report: { progress: { completed: 0, total: 0, generation: 4, stage: 'preparing' } } } } },
1333
+ })
1334
+ const progress = nodes.filter((node) => node.type === 'progress')
1335
+ assert.equal(progress.length, 1)
1336
+ assert.equal(progress[0].props.value, undefined, 'unknown work must not look complete')
1337
+ assert.equal(progress[0].props.max, 1)
1338
+ assert.match(treeText(tree), /managedVectorGeneration 4/)
1339
+ assert.ok(!treeText(tree).includes('NaN'))
1340
+ })
1341
+
1342
+ test('switch waits for two clicks, reports in-flight work, and keeps a failed operation visible', async (t) => {
1343
+ let finish
1344
+ const response = new Promise(resolve => { finish = resolve })
1345
+ const view = await renderVectorSettings(t, {
1346
+ settings: { memoryBackend: 'api', vectorSource: 'local' },
1347
+ localVector: {
1348
+ ...VECTOR_CATALOG_FIXTURE,
1349
+ runtime: { status: 'installed', ready: true, path: 'runtime' },
1350
+ vector: { requested: { catalogId: 'fixture-installed' }, active: { catalogId: 'old-model' } },
1351
+ },
1352
+ }, { switchLocalVectorProfile: () => response })
1353
+ const button = current => current.nodes.find(node => node.type === 'button' && node.props.title === 'managedVectorSwitch')
1354
+ await button(view).props.onClick()
1355
+ assert.equal(view.rpcCalls.filter(call => call.endpoint === 'switchLocalVectorProfile').length, 0)
1356
+ const armed = await view.rerender()
1357
+ assert.equal(button(armed).props.children, 'confirmAction')
1358
+ const operation = button(armed).props.onClick()
1359
+ const waiting = await view.rerender()
1360
+ assert.equal(button(waiting).props.disabled, true)
1361
+ assert.ok(waiting.nodes.some(node => node.props?.role === 'status' && treeText(node).includes('managedVectorStatus: managedVectorSwitch')))
1362
+ assert.match(treeText(waiting.tree), /managedVectorPrerequisites/)
1363
+ finish({ ok: false, error: { code: 'LOCAL_VECTOR_RUNTIME_UNAVAILABLE', message: 'a verified managed runtime is required before switching local embeddings' } })
1364
+ await operation
1365
+ const failed = await view.rerender()
1366
+ assert.equal(button(failed).props.disabled, false)
1367
+ assert.ok(failed.nodes.some(node => node.props?.role === 'alert' && treeText(node).includes('verified managed runtime')))
1368
+ assert.match(treeText(failed.tree), /old-model/)
1369
+ assert.match(treeText(failed.tree), /managedVectorRequested/)
1370
+ assert.equal(view.rpcCalls.filter(call => call.endpoint === 'switchLocalVectorProfile').length, 1)
1371
+ })
1372
+
1373
+ test('pending manifests show verification and size reasons; persisted migration failures remain visible', async (t) => {
1374
+ const { tree, nodes } = await renderVectorSettings(t, {
1375
+ settings: { memoryBackend: 'api', vectorSource: 'local' },
1376
+ localVector: {
1377
+ ...VECTOR_CATALOG_FIXTURE,
1378
+ installations: { ...VECTOR_CATALOG_FIXTURE.installations, 'fixture-pending': { status: 'absent' } },
1379
+ vector: { pending: { status: 'failed', error: {
1380
+ code: 'VECTOR_SYNC_FAILED',
1381
+ message: 'cannot list shadow database',
1382
+ failedItems: [{ itemId: 'mem-failed-1', code: 'VECTOR_READBACK_FAILED', message: 'committed item is missing from shadow' }],
1383
+ } } },
1384
+ },
1385
+ })
1386
+ assert.match(treeText(tree), /managedVectorSizePending/)
1387
+ assert.match(treeText(tree), /managedVectorPending/)
1388
+ assert.match(treeText(tree), /SHA-256 pending/)
1389
+ assert.ok(treeText(tree).includes('managedVectorSizePending'), 'pending artifacts must not display a guessed byte count')
1390
+ assert.equal(nodes.filter(node => node.type === 'button' && node.props.title === 'managedVectorDownload').length, 1)
1391
+ assert.ok(nodes.some(node => node.props?.role === 'alert' && treeText(node).includes('cannot list shadow database')))
1392
+ // 重建失败必须说清是哪一条、为什么:只报"未覆盖全部记忆"根本没法修。
1393
+ const failedText = treeText(tree)
1394
+ assert.match(failedText, /mem-failed-1/)
1395
+ assert.match(failedText, /VECTOR_READBACK_FAILED/)
1396
+ assert.match(failedText, /committed item is missing from shadow/)
1397
+ })
1398
+
1399
+ test('a finished rebuild reads as switched, not as a running progress bar', async (t) => {
1400
+ const { tree } = await renderVectorSettings(t, {
1401
+ settings: { memoryBackend: 'api', vectorSource: 'local' },
1402
+ localVector: {
1403
+ ...VECTOR_CATALOG_FIXTURE,
1404
+ runtime: { status: 'installed', ready: true, path: 'runtime' },
1405
+ vector: {
1406
+ active: { catalogId: 'fixture-installed', generation: 1, fingerprint: '47511436abcdef', lastMigration: { committed: 8, total: 8, generation: 1 } },
1407
+ indexed: { global: ['a', 'b'], lib: ['c', 'd', 'e'] },
1408
+ },
1409
+ },
1410
+ })
1411
+ const text = treeText(tree)
1412
+ assert.match(text, /vectorStageCommitted/)
1413
+ assert.match(text, /vectorSwitchDoneHint/)
1414
+ assert.doesNotMatch(text, /managedVectorRebuilding/, 'a committed generation must not keep the running label')
1415
+ assert.match(text, /vectorRouteLocal/, 'the header must say which route recall uses')
1416
+ assert.match(text, /vectorIndexedNow/, 'the card must show the live indexed count, not only the switch snapshot')
1417
+ assert.match(text, /vectorIndexedNow 5 vectorIndexedUnit/, 'two global + three library ids')
1418
+ })
1419
+
1420
+ test('API vector settings render provider fields and hide the managed local catalog', async (t) => {
1421
+ const { tree, nodes } = await renderVectorSettings(t, {
1422
+ settings: { memoryBackend: 'api', vectorSource: 'api' },
1423
+ memuConfig: { source: 'api', provider: 'jina', model: 'fixture-api-model', baseUrl: 'https://example.invalid/v1', hasKey: true },
1424
+ summaryConfig: { model: 'fixture-summary-model' },
1425
+ localVector: VECTOR_CATALOG_FIXTURE,
1426
+ })
1427
+ const text = treeText(tree)
1428
+ for (const visible of ['vectorSourceApi', 'provider', 'model', 'baseUrl', 'apiKey', 'summaryModel']) {
1429
+ assert.ok(text.includes(visible), visible + ' did not render')
1430
+ }
1431
+ assert.ok(nodes.some((node) => node.type === 'select' && node.props.value === 'jina'))
1432
+ assert.ok(nodes.some((node) => node.type === 'input' && node.props.value === 'fixture-api-model'))
1433
+ assert.ok(nodes.some((node) => node.type === 'input' && node.props.value === 'https://example.invalid/v1'))
1434
+ assert.equal(nodes.filter((node) => node.type === 'input' && node.props.type === 'password').length, 2)
1435
+ assert.ok(!text.includes('Fixture Download Model'))
1436
+ assert.ok(!text.includes('managedVectorDownload'))
1437
+ assert.ok(!nodes.some((node) => node.type === 'progress'))
1438
+ })
1439
+
1440
+ // 日志行的三档视觉状态。真实读数里整理超时记的是 level=warn + ok=false
1441
+ //(lib/private.js 的超时路径),所以「只看 level==='error'」会把它显示成正常行——
1442
+ // 用户看到的就是「失败长得好普通」。这条钉的是行为:哪一行该红、哪一行该橙、
1443
+ // 哪一行什么都不该标。
1444
+ test('failed and degraded activity rows are visually distinguished from normal rows', async () => {
1445
+ const failed = {
1446
+ id: 'act-failed', at: '2026-11-02T07:58:29.775Z', kind: 'consolidate', level: 'warn',
1447
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1', ok: false,
1448
+ message: '整理超时 · 空闲 · fork f-7535be · timeout:consolidation timed out after 180s', detail: null, refs: [],
1449
+ }
1450
+ const degraded = {
1451
+ id: 'act-degraded', at: '2026-11-02T07:59:00.000Z', kind: 'vector', level: 'warn',
1452
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
1453
+ message: '向量未激活,写入已降级为索引+引擎', detail: { reason: 'no active vector generation' }, refs: [],
1454
+ }
1455
+ const normal = {
1456
+ id: 'act-normal', at: '2026-11-02T08:02:40.988Z', kind: 'consolidate', level: 'info',
1457
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
1458
+ message: '整理完成 · 空闲 · fork 1-2b16be · 索引 +1', detail: null, refs: [],
1459
+ }
1460
+ const ctx = fakeCtx({
1461
+ answers: { getActivityLog: { events: [failed, degraded, normal], stats: { total: 3, capped: 2000, bytes: 1024 } } },
1462
+ })
1463
+ globalThis.__dshMemuExports.apply(ctx)
1464
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1465
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
1466
+ collectPageHook()
1467
+ for (const effect of first.effects) effect.fn()
1468
+ await new Promise((resolve) => setTimeout(resolve, 0))
1469
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1470
+ for (const effect of mid.effects) effect.fn()
1471
+ await new Promise((resolve) => setTimeout(resolve, 0))
1472
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1473
+ const rows = new Map()
1474
+ const labels = []
1475
+ walkNodes(tree, (node) => {
1476
+ if (typeof node.props?.key === 'string' && node.props.key.startsWith('act-')) rows.set(node.props.key, node.props)
1477
+ if (node.props?.children === 'logStateFailed' || node.props?.children === 'logDegraded') labels.push(node.props)
1478
+ })
1479
+ assert.equal(rows.size, 3, 'the log page rendered none of the fixture rows')
1480
+ assert.match(String(rows.get('act-failed')?.className), /dshm-logrow is-failed/, 'the timeout row must carry the failed state class')
1481
+ assert.match(String(rows.get('act-degraded')?.className), /dshm-logrow is-degraded/, 'a fallback-path row is degraded, not failed')
1482
+ assert.equal(rows.get('act-normal')?.className, 'dshm-logrow', 'normal rows must not pick up any state class')
1483
+ assert.ok(labels.some((props) => props.children === 'logStateFailed'), 'the failed row needs a 失败 label, not only colour')
1484
+ assert.ok(labels.some((props) => props.children === 'logDegraded'), 'degraded rows need their own word')
1485
+ assert.ok(labels.every((props) => typeof props.title === 'string' && props.title.length > 0), 'every state tag must explain itself on hover')
1486
+ })
1487
+
1488
+ test('clicking the API source tab sends the explicit setEmbeddingSource RPC only', async (t) => {
1489
+ const { nodes, rpcCalls } = await renderVectorSettings(t, {
1490
+ settings: { memoryBackend: 'api', vectorSource: 'local' },
1491
+ localVector: VECTOR_CATALOG_FIXTURE,
1492
+ })
1493
+ const apiTab = nodes.filter((node) => node.type === 'button' && node.props.children === 'vectorSourceApi')
1494
+ assert.equal(apiTab.length, 1)
1495
+ assert.equal(apiTab[0].props['aria-selected'], false)
1496
+ assert.equal(apiTab[0].props.disabled, false)
1497
+ assert.equal(rpcCalls.filter((call) => call.endpoint === 'setEmbeddingSource').length, 0)
1498
+ await apiTab[0].props.onClick()
1499
+ assert.deepEqual(rpcCalls.filter((call) => call.endpoint === 'setEmbeddingSource'), [
1500
+ { path: '/dsh-memu-memory', endpoint: 'setEmbeddingSource', payload: { source: 'api' } },
1501
+ ])
1502
+ assert.ok(!rpcCalls.some((call) => /downloadLocalVector|selectLocalVector|switchLocalVector/.test(call.endpoint)))
1503
+ })
1504
+
1505
+ test('the log page renders rows with copy, download and locate actions', async () => {
1506
+ const event = {
1507
+ id: 'act-fixture', at: '2026-10-30T03:00:00.000Z', kind: 'consolidate', level: 'warn',
1508
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
1509
+ message: '整理超时:fork 已停止', detail: { timedOut: true, childId: 'memu-consolidate-x' }, refs: [], ok: false,
1510
+ }
1511
+ const check = {
1512
+ id: 'act-check', at: '2026-10-30T03:05:00.000Z', kind: 'check', level: 'info',
1513
+ scope: 'private', sessionId: 'session-abcdef', libraryId: 'lib-1',
1514
+ message: '主动检查跳过 · score 0.12 · large-transcript-thin · 空闲 40 分钟 · 会话 5913 事件',
1515
+ detail: { reason: 'large-transcript-thin', score: 0.12, parts: { human: 0.33, content: 0.01, tool: 0 } }, refs: [], ok: false,
1516
+ }
1517
+ const ctx = fakeCtx({
1518
+ answers: { getActivityLog: { events: [event, check], stats: { total: 2, capped: 2000, bytes: 1024 } } },
1519
+ })
1520
+ globalThis.__dshMemuExports.apply(ctx)
1521
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1522
+ const first = await renderPage(settings.component, { ctx, t: (key) => key }, undefined, { remount: true })
1523
+ collectPageHook()
1524
+ for (const effect of first.effects) effect.fn()
1525
+ await new Promise((resolve) => setTimeout(resolve, 0))
1526
+ await new Promise((resolve) => setTimeout(resolve, 0))
1527
+ // The log page's own effect only exists once that page renders, so it needs one
1528
+ // more render + effect pass before the data is in the hook.
1529
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1530
+ for (const effect of mid.effects) effect.fn()
1531
+ await new Promise((resolve) => setTimeout(resolve, 0))
1532
+ await new Promise((resolve) => setTimeout(resolve, 0))
1533
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1534
+ const text = treeText(tree)
1535
+ assert.match(text, /整理超时/)
1536
+ assert.match(text, /logCopyAll/)
1537
+ assert.match(text, /logDownload/)
1538
+ assert.match(text, /logLocate/, 'a row with a library id offers the correction entry point')
1539
+ assert.match(text, /pageLogs/)
1540
+ assert.match(text, /logKindCheck/, 'the activity log labels wake-up checks')
1541
+ assert.match(text, /large-transcript-thin/, 'the check row keeps its reason and score visible')
1542
+ })
1543
+
1544
+ test('the memory wall global block bulk-archives and the drawer deletes global entries two-step', async () => {
1545
+ const rpcCalls = []
1546
+ const ctx = fakeCtx({ rpcCalls })
1547
+ const originalGetState = RPC_ANSWERS.getState
1548
+ const originalSettingsState = RPC_ANSWERS.getSettingsState
1549
+ const loaded = {
1550
+ ...EMPTY_STATE,
1551
+ libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 0 }],
1552
+ }
1553
+ RPC_ANSWERS.getState = loaded
1554
+ RPC_ANSWERS.getSettingsState = loaded
1555
+ RPC_ANSWERS.browseWall = {
1556
+ total: 2,
1557
+ items: [
1558
+ { id: 'mem-g-active', libraryId: null, libraryName: 'global', title: 'global active', preview: 'active body', layer: 'long_term', status: 'active', source: 'inferred', decay: 0.5, tags: [] },
1559
+ { id: 'mem-g-archived', libraryId: null, libraryName: 'global', title: 'global archived', preview: 'archived body', layer: 'long_term', status: 'archived', source: 'inferred', decay: 0.5, tags: [] },
1560
+ ],
1561
+ }
1562
+ RPC_ANSWERS.listGlobal = {
1563
+ files: [
1564
+ { id: 'mem-g-active', title: 'global active', content: 'active body', status: 'active', domain: 'general' },
1565
+ { id: 'mem-g-archived', title: 'global archived', content: 'archived body', status: 'archived', domain: 'general' },
1566
+ ],
1567
+ }
1568
+ RPC_ANSWERS.archiveMemory = { id: 'mem-g-active', entry: { status: 'archived' } }
1569
+ RPC_ANSWERS.deleteMemory = { id: 'mem-g-archived', libraryId: null, deleted: true }
1570
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
1571
+ // harness 的 hook 游标是全局的:同一棵树只能展开一次,二次 walk 会把子组件
1572
+ // 的 useState 重新初始化。所以每次 renderPage 后只 walk 一遍,收齐所有节点。
1573
+ const collect = (tree) => {
1574
+ const labels = new Map()
1575
+ const cards = []
1576
+ const tabs = []
1577
+ walkNodes(tree, (node) => {
1578
+ if (typeof node.type === 'function' && typeof node.props?.children === 'string' && !labels.has(node.props.children)) {
1579
+ labels.set(node.props.children, node)
1580
+ }
1581
+ if (node.type === 'button' && String(node.props?.className || '').includes('dshm-wall-item')) cards.push(node)
1582
+ if (node.type === 'button' && node.props?.role === 'tab') tabs.push(node)
1583
+ })
1584
+ return { labels, cards, tabs }
1585
+ }
1586
+ try {
1587
+ globalThis.__dshMemuExports.apply(ctx)
1588
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1589
+ const props = { ctx, t: (key) => key }
1590
+ const first = await renderPage(settings.component, props, undefined, { remount: true })
1591
+ collectPageHook()
1592
+ for (const effect of first.effects) effect.fn()
1593
+ await tick(); await tick()
1594
+ let view = collect((await renderPage(settings.component, props, 9)).tree)
1595
+ for (const effect of effects) effect.fn()
1596
+ await tick(); await tick()
1597
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1598
+
1599
+ // 切到全局块:多选开关必须存在(旧版全局块没有)。
1600
+ const scopeTab = view.tabs.find((node) => String(node.props?.children || '').startsWith('wallScopeGlobal'))
1601
+ assert.ok(scopeTab, 'the global scope tab did not render')
1602
+ scopeTab.props.onClick()
1603
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1604
+ assert.ok(view.labels.has('multiSelect'), 'the global block offers multi-select')
1605
+ view.labels.get('multiSelect').props.onClick()
1606
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1607
+ assert.equal(view.cards.length, 1, 'the active pool shows the active global card')
1608
+ view.cards[0].props.onClick()
1609
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1610
+ assert.ok(view.labels.has('archive (1)'), 'selecting one global card arms the bulk archive button')
1611
+ view.labels.get('archive (1)').props.onClick()
1612
+ await tick(); await tick()
1613
+ const archived = rpcCalls.filter((call) => call.endpoint === 'archiveMemory')
1614
+ assert.equal(archived.length, 1)
1615
+ assert.equal(archived[0].payload.scope, 'global')
1616
+ assert.equal(archived[0].payload.id, 'mem-g-active')
1617
+ assert.equal(archived[0].payload.libraryId, undefined, 'global bulk writes never name a private library')
1618
+
1619
+ // 已归档池开抽屉:恢复与两段删除都在,删除第一段只武装、第二段才发请求。
1620
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1621
+ view.labels.get('wallMultiExit').props.onClick()
1622
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1623
+ const archivedTab = view.tabs.find((node) => String(node.props?.children || '').startsWith('browseArchivedTab'))
1624
+ archivedTab.props.onClick()
1625
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1626
+ assert.equal(view.cards.length, 1)
1627
+ view.cards[0].props.onClick()
1628
+ await tick(); await tick()
1629
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1630
+ assert.ok(view.labels.has('restore'), 'the archived global drawer offers restore')
1631
+ assert.ok(view.labels.has('deleteForever'), 'the archived global drawer offers permanent delete')
1632
+ assert.ok(!view.labels.has('save'), 'global content stays curator-written')
1633
+ view.labels.get('deleteForever').props.onClick()
1634
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1635
+ assert.equal(rpcCalls.filter((call) => call.endpoint === 'deleteMemory').length, 0, 'the first click only arms')
1636
+ assert.ok(view.labels.has('confirmDelete'))
1637
+ view.labels.get('confirmDelete').props.onClick()
1638
+ await tick(); await tick()
1639
+ const deleted = rpcCalls.filter((call) => call.endpoint === 'deleteMemory')
1640
+ assert.equal(deleted.length, 1)
1641
+ assert.equal(deleted[0].payload.scope, 'global')
1642
+ assert.equal(deleted[0].payload.id, 'mem-g-archived')
1643
+ assert.equal(deleted[0].payload.confirmed, true)
1644
+ } finally {
1645
+ RPC_ANSWERS.getState = originalGetState
1646
+ RPC_ANSWERS.getSettingsState = originalSettingsState
1647
+ delete RPC_ANSWERS.browseWall
1648
+ delete RPC_ANSWERS.listGlobal
1649
+ delete RPC_ANSWERS.archiveMemory
1650
+ delete RPC_ANSWERS.deleteMemory
1651
+ }
1652
+ })
1653
+
1654
+ test('the memory wall filters by domain and names every card domain', async () => {
1655
+ const rpcCalls = []
1656
+ const ctx = fakeCtx({ rpcCalls })
1657
+ const originalGetState = RPC_ANSWERS.getState
1658
+ const originalSettingsState = RPC_ANSWERS.getSettingsState
1659
+ const loaded = {
1660
+ ...EMPTY_STATE,
1661
+ libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 2 }],
1662
+ }
1663
+ RPC_ANSWERS.getState = loaded
1664
+ RPC_ANSWERS.getSettingsState = loaded
1665
+ RPC_ANSWERS.browseWall = {
1666
+ total: 2,
1667
+ domains: ['coding', 'rp'],
1668
+ items: [
1669
+ { id: 'mem-rp', libraryId: 'lib-1', libraryName: 'demo', title: '约定的日子', preview: 'p', layer: 'long_term', status: 'active', source: 'user_said', decay: 0.5, tags: [], domain: 'rp' },
1670
+ { id: 'mem-code', libraryId: 'lib-1', libraryName: 'demo', title: '部署窗口', preview: 'p', layer: 'long_term', status: 'active', source: 'inferred', decay: 0.4, tags: [], domain: 'coding' },
1671
+ ],
1672
+ }
1673
+ const settle = async () => {
1674
+ await new Promise((resolve) => setTimeout(resolve, 0))
1675
+ await new Promise((resolve) => setTimeout(resolve, 0))
1676
+ }
1677
+ // harness 的 hook 游标是全局的:同一棵树只能展开一次,二次 walk 会把子组件的
1678
+ // useState 重新初始化。所以每轮 render 只走一遍,把要的东西一次收齐。
1679
+ const collect = (tree) => {
1680
+ const found = { select: null, domainTags: [], cards: 0 }
1681
+ walkNodes(tree, (node) => {
1682
+ if (node.type === 'select' && node.props?.['aria-label'] === 'wallFilterDomain' && !found.select) found.select = node
1683
+ if (node.type === 'span' && node.props?.title === 'wallDomainHint') found.domainTags.push(String(node.props?.children ?? ''))
1684
+ if (node.type === 'button' && String(node.props?.className || '').includes('dshm-wall-item')) found.cards += 1
1685
+ })
1686
+ const values = []
1687
+ const visit = (value) => {
1688
+ if (Array.isArray(value)) { value.forEach(visit); return }
1689
+ if (value && value.type === 'option') values.push(String(value.props?.value ?? ''))
1690
+ }
1691
+ if (found.select) visit([].concat(found.select.props?.children ?? []))
1692
+ found.values = values
1693
+ return found
1694
+ }
1695
+ try {
1696
+ globalThis.__dshMemuExports.apply(ctx)
1697
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
1698
+ const props = { ctx, t: (key) => key }
1699
+ const first = await renderPage(settings.component, props, undefined, { remount: true })
1700
+ collectPageHook()
1701
+ for (const effect of first.effects) effect.fn()
1702
+ await settle()
1703
+ let view = collect((await renderPage(settings.component, props, 9)).tree)
1704
+ for (const effect of effects) effect.fn()
1705
+ await settle()
1706
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1707
+
1708
+ assert.ok(view.select, 'the wall renders a domain filter')
1709
+ assert.equal(view.cards, 2, 'both wall cards rendered')
1710
+ assert.deepEqual(view.values, ['', 'coding', 'rp'], 'the filter offers every domain the server reported')
1711
+ assert.deepEqual(view.domainTags.sort(), ['dmCoding', 'dmRp'], 'each card names the domain it came from')
1712
+
1713
+ view.select.props.onChange({ target: { value: 'rp' } })
1714
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1715
+ for (const effect of effects) effect.fn()
1716
+ await settle()
1717
+ const asked = rpcCalls.filter((call) => call.endpoint === 'browseWall')
1718
+ assert.equal(asked[asked.length - 1].payload.domain, 'rp', 'picking a domain asks the server instead of trimming the page in the browser')
1719
+ view = collect((await renderPage(settings.component, props, 9)).tree)
1720
+ assert.deepEqual(view.domainTags, [], 'once filtered, cards stop repeating the same domain')
1721
+ assert.equal(view.select.props.value, 'rp', 'the filter keeps what the reader picked')
1722
+ } finally {
1723
+ RPC_ANSWERS.getState = originalGetState
1724
+ RPC_ANSWERS.getSettingsState = originalSettingsState
1725
+ delete RPC_ANSWERS.browseWall
1726
+ }
1727
+ })
1728
+
1729
+ // better-sidebar keeps one panel per conversation and stays mounted while the
1730
+ // reader switches between them, so "the conversation on screen" is not the
1731
+ // conversation a panel belongs to. Deriving the session from that live store let
1732
+ // a panel paint one conversation's switches while writing another's: the reader
1733
+ // turned private memory off, the panel answered "on" after the next refresh, and
1734
+ // the conversation they were actually chatting in kept injecting memory. The tab
1735
+ // body has to follow the scope better-sidebar hands it.
1736
+ test('the better-sidebar memory tab writes to the conversation its tab belongs to', async () => {
1737
+ const rpcCalls = []
1738
+ let tabComponent = null
1739
+ const better = {
1740
+ registerTab: (descriptor) => {
1741
+ if (descriptor?.id?.endsWith(':memory-better')) tabComponent = descriptor.component
1742
+ return () => {}
1743
+ },
1744
+ }
1745
+ const sidebarRight = {
1746
+ mounted: { subscribe: () => () => {}, getSnapshot: () => 'session-on-screen' },
1747
+ }
1748
+ const ctx = {
1749
+ effect: (fn) => { try { fn() } catch {} },
1750
+ locale: { register: () => () => {}, bind: () => (key) => key, get: () => 'zh' },
1751
+ connection: {
1752
+ rpc: {
1753
+ call: async (path, endpoint, payload) => {
1754
+ rpcCalls.push({ path, endpoint, payload })
1755
+ return { ok: true, value: RPC_ANSWERS[endpoint] ?? {} }
1756
+ },
1757
+ },
1758
+ },
1759
+ sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: {}, ids: [] }) } },
1760
+ get: (name) => {
1761
+ if (name === 'betterSidebar') return better
1762
+ if (name === 'sidebarRight') return sidebarRight
1763
+ return undefined
1764
+ },
1765
+ slots: {
1766
+ inject: (_name, callback) => callback(pluginScope),
1767
+ register: () => () => {},
1768
+ },
1769
+ inject: (deps, callback) => {
1770
+ if (Array.isArray(deps) && deps.includes('betterSidebar')) callback(pluginScope)
1771
+ },
1772
+ }
1773
+ // The tab registers through the injected plugin scope, not through ctx itself.
1774
+ const pluginScope = {
1775
+ effect: (fn) => { try { return fn() } catch { return undefined } },
1776
+ register: () => () => {},
1777
+ inject: (_name, callback) => callback(pluginScope),
1778
+ get: (name) => ctx.get(name),
1779
+ }
1780
+
1781
+ globalThis.__dshMemuExports.apply(ctx)
1782
+ assert.ok(tabComponent, 'the better-sidebar tab was not registered')
1783
+
1784
+ // better-sidebar calls the registered component with its own props; follow the
1785
+ // returned element one level so the panel body's hooks actually run.
1786
+ const hostProps = {
1787
+ ctx,
1788
+ t: (key) => key,
1789
+ scope: { sessionId: 'session-of-this-tab', cwd: '/proj/demo' },
1790
+ tab: { id: 'tab-1', type: 'dsh-memu-memory:memory-better' },
1791
+ visible: true,
1792
+ }
1793
+ const element = tabComponent(hostProps)
1794
+ assert.equal(typeof element?.type, 'function', 'the tab body must be a component')
1795
+ assert.equal(element.props?.scope?.sessionId, 'session-of-this-tab', 'the tab scope must reach the panel body')
1796
+ const body = element.type(element.props)
1797
+ assert.equal(typeof body?.type, 'function', 'the tab body must render the memory panel')
1798
+ const rendered = await renderPage(body.type, body.props, undefined, { remount: true })
1799
+ for (const effect of rendered.effects) effect.fn()
1800
+ await new Promise((resolve) => setTimeout(resolve, 0))
1801
+ await new Promise((resolve) => setTimeout(resolve, 0))
1802
+
1803
+ const asked = rpcCalls.filter((call) => call.endpoint === 'getSidebarState').map((call) => call.payload?.sessionId)
1804
+ assert.ok(asked.includes('session-of-this-tab'), 'the panel must read the conversation its tab belongs to')
1805
+ assert.ok(!asked.includes('session-on-screen'), 'the on-screen conversation must not override the tab scope')
1806
+ })
1807
+
1808
+ // 首帧不许断言:数据还没回来时,`binding` 为 null 既可能是「真的没绑定」也可能是
1809
+ // 「还没查」。旧代码在这时画「初始化记忆」卡,读者看到的就是「进去先显示没有记忆,
1810
+ // 过一会儿才加载出来」。这条钉住:未加载就只画加载中;数据到了才画真实开关。
1811
+ test('the sidebar paints loading before it may claim the conversation has no memory', async () => {
1812
+ const rpcCalls = []
1813
+ let paneComponent = null
1814
+ const pluginScope = {
1815
+ effect: (fn) => { try { return fn() } catch { return undefined } },
1816
+ inject: (_name, callback) => callback(pluginScope),
1817
+ get: () => undefined,
1818
+ sidebarRightTabs: { register: () => () => {} },
1819
+ }
1820
+ const ctx = {
1821
+ effect: (fn) => { try { fn() } catch {} },
1822
+ locale: { register: () => () => {}, bind: () => (key) => key, get: () => 'zh' },
1823
+ connection: {
1824
+ rpc: {
1825
+ call: async (path, endpoint, payload) => {
1826
+ rpcCalls.push({ path, endpoint, payload })
1827
+ return { ok: true, value: RPC_ANSWERS[endpoint] ?? {} }
1828
+ },
1829
+ },
1830
+ },
1831
+ sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: {}, ids: [] }) } },
1832
+ get: () => undefined,
1833
+ slots: {
1834
+ inject: (_name, callback) => callback(pluginScope),
1835
+ register: (spec, component) => {
1836
+ if (spec?.name === 'sidebar.right.pane.tab') paneComponent = component
1837
+ return () => {}
1838
+ },
1839
+ },
1840
+ inject: (deps, callback) => {
1841
+ if (Array.isArray(deps) && deps.includes('sidebarRightTabs')) callback(pluginScope)
1842
+ },
1843
+ }
1844
+ globalThis.__dshMemuExports.apply(ctx)
1845
+ assert.ok(paneComponent, 'the native sidebar tab body was not registered')
1846
+
1847
+ const props = { ctx, t: (key) => key, sessionId: 'probe-session' }
1848
+ const hostElement = paneComponent(props)
1849
+ const first = await renderPage(hostElement.type, hostElement.props, undefined, { remount: true })
1850
+ const firstText = treeText(first.tree)
1851
+ assert.match(firstText, /loading/, 'the first frame says it is loading')
1852
+ assert.ok(!firstText.includes('initMemory'), 'and it does not offer to initialise a library it has not looked for yet')
1853
+ assert.ok(!firstText.includes('noPrivate'), 'nor claim the conversation has no memories')
1854
+
1855
+ for (const effect of first.effects) effect.fn()
1856
+ await new Promise((resolve) => setTimeout(resolve, 0))
1857
+ await new Promise((resolve) => setTimeout(resolve, 0))
1858
+ const second = await renderPage(hostElement.type, hostElement.props)
1859
+ const secondText = treeText(second.tree)
1860
+ assert.ok(secondText.includes('usePrivate'), 'once the data lands the real switches are painted')
1861
+ assert.ok(!secondText.includes('initMemory'), 'a bound conversation never shows the init card')
1862
+ })
1863
+
1864
+ // 首查失败时不能停在骨架屏:骨架屏唯一的定时通道(useMemoryBeat)在首查成功前不轮询,
1865
+ // 失败之后就再没人叫醒它。面板必须落成一张带「重试」的错误卡。
1866
+ test('a failed first fetch turns into a retry card, not an endless skeleton', async () => {
1867
+ let paneComponent = null
1868
+ const pluginScope = {
1869
+ effect: (fn) => { try { return fn() } catch { return undefined } },
1870
+ inject: (_name, callback) => callback(pluginScope),
1871
+ get: () => undefined,
1872
+ sidebarRightTabs: { register: () => () => {} },
1873
+ }
1874
+ const ctx = {
1875
+ effect: (fn) => { try { fn() } catch {} },
1876
+ locale: { register: () => () => {}, bind: () => (key) => key, get: () => 'zh' },
1877
+ connection: {
1878
+ rpc: {
1879
+ call: async (_path, endpoint) => {
1880
+ if (endpoint === 'getSidebarState') throw new Error('boom: state unavailable')
1881
+ return { ok: true, value: RPC_ANSWERS[endpoint] ?? {} }
1882
+ },
1883
+ },
1884
+ },
1885
+ sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: {}, ids: [] }) } },
1886
+ get: () => undefined,
1887
+ slots: {
1888
+ inject: (_name, callback) => callback(pluginScope),
1889
+ register: (spec, component) => {
1890
+ if (spec?.name === 'sidebar.right.pane.tab') paneComponent = component
1891
+ return () => {}
1892
+ },
1893
+ },
1894
+ inject: (deps, callback) => {
1895
+ if (Array.isArray(deps) && deps.includes('sidebarRightTabs')) callback(pluginScope)
1896
+ },
1897
+ }
1898
+ globalThis.__dshMemuExports.apply(ctx)
1899
+ assert.ok(paneComponent, 'the native sidebar tab body was not registered')
1900
+
1901
+ const props = { ctx, t: (key) => key, sessionId: 'probe-session' }
1902
+ const hostElement = paneComponent(props)
1903
+ const first = await renderPage(hostElement.type, hostElement.props, undefined, { remount: true })
1904
+ for (const effect of first.effects) effect.fn()
1905
+ await new Promise((resolve) => setTimeout(resolve, 0))
1906
+ await new Promise((resolve) => setTimeout(resolve, 0))
1907
+
1908
+ const text = treeText((await renderPage(hostElement.type, hostElement.props)).tree)
1909
+ assert.ok(text.includes('boom: state unavailable'), 'the failure is named on the panel')
1910
+ assert.ok(text.includes('settingsRetry'), 'and there is a retry control, so it cannot be stuck')
1911
+ assert.ok(!text.includes('initMemory'), 'a failed read must not be reported as "no memory library"')
1912
+ })
1913
+
1914
+ // offset 分页按 updatedAt 排序:两批之间有人写入/归档时,后一批会重复上一批已经出现
1915
+ // 过的条目。首批 60 之后必然要拉第二批,所以去重是必需的不是优化。
1916
+
1917
+ // Exercise the real async closures with controlled replies, without mounting unrelated hooks.
1918
+ function reviewClientClosure(start, end, dependencies, callback = false) {
1919
+ const source = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
1920
+ const from = source.lastIndexOf(start)
1921
+ assert.ok(from >= 0, start)
1922
+ const to = source.indexOf(end, from + start.length)
1923
+ assert.ok(to > from, end)
1924
+ return new Function(...Object.keys(dependencies), 'return ' + source.slice(from + start.length, to).trim().replace(/;$/, '') + (callback ? '\n}' : ''))(...Object.values(dependencies))
1925
+ }
1926
+
1927
+ test('wall pagination consumes raw rows and continues past a fully duplicate page', async () => {
1928
+ const rows = Array.from({ length: 300 }, (_, n) => ({ id: 'review-' + n, libraryId: 'lib-1' }))
1929
+ const tail = { id: 'review-tail', libraryId: 'lib-1' }
1930
+ const calls = [], snapshots = []
1931
+ const pages = new Map([[0, rows.slice(0, 60)], [60, rows], [360, rows], [660, [tail]]])
1932
+ const stream = reviewClientClosure('const stream = ', ' const load = async', {
1933
+ call: async (_method, args) => { calls.push(args); return { total: 661, items: pages.get(args.offset) || [] } },
1934
+ current: () => true, setData: value => snapshots.push(value), setError: () => {}, wallDomain: '',
1935
+ })
1936
+ await stream('lib-1')
1937
+ assert.deepEqual(calls.map(row => row.offset), [0, 60, 360, 660])
1938
+ assert.deepEqual(calls.map(row => row.limit), [60, 300, 300, 300])
1939
+ assert.equal(snapshots.at(-1).items.length, 301)
1940
+ assert.ok(snapshots.at(-1).items.some(row => row.id === tail.id), 'tail after duplicate page must be present')
1941
+ assert.equal(new Set(snapshots.at(-1).items.map(row => row.libraryId + ':' + row.id)).size, 301)
1942
+ })
1943
+
1944
+ function reviewRefresh(sessionId, overrides = {}) {
1945
+ return reviewClientClosure('const refresh = React.useCallback(', ' }, [call, sessionId])', {
1946
+ sessionId, currentSession: { current: sessionId }, refreshRequest: { current: 0 },
1947
+ call: async () => ({ private: { crossLibrary: true, items: [] } }),
1948
+ setState: () => {}, setPrivateFiles: () => {}, setGlobalFiles: () => {},
1949
+ markerRef: { current: null }, sidebarMarker: () => 'marker', setError: () => {},
1950
+ setLoadFailed: () => {}, setLoadedFor: () => {}, ...overrides,
1951
+ }, true)
1952
+ }
1953
+
1954
+ test('a late sidebar response cannot publish under a different current conversation', async () => {
1955
+ let release
1956
+ const reply = new Promise(resolve => { release = resolve })
1957
+ const currentSession = { current: 'old' }, refreshRequest = { current: 0 }, writes = []
1958
+ const deps = { currentSession, refreshRequest, setState: value => writes.push(value), setLoadedFor: value => writes.push(value) }
1959
+ const pending = reviewRefresh('old', { ...deps, call: () => reply })()
1960
+ currentSession.current = 'new'
1961
+ await reviewRefresh('new', deps)()
1962
+ const before = writes.slice()
1963
+ release({ private: { crossLibrary: true, items: [] } })
1964
+ await pending
1965
+ assert.deepEqual(writes, before, 'old data and loadedFor must both be ignored')
1966
+ await reviewRefresh('old', { ...deps, call: () => { throw new Error('stale refresh started') } })()
1967
+ assert.deepEqual(writes, before)
1968
+ })
1969
+
1970
+ function reviewSetScope(overrides = {}) {
1971
+ return reviewClientClosure('const setScope = ', ' const setDomain = ', {
1972
+ sessionId: 'old', currentSession: { current: 'old' }, setBusy: () => {},
1973
+ call: async () => ({ effective: { useLibrary: true } }), refresh: async () => {},
1974
+ setError: () => {}, setNotice: () => {}, t: key => key, ...overrides,
1975
+ })
1976
+ }
1977
+
1978
+ test('scope read-back mismatch survives the successful refresh and is logged', async () => {
1979
+ let error = '', logged = 0
1980
+ const setScope = reviewSetScope({
1981
+ call: async method => { if (method === 'logClientEvent') { logged++; return {} } return { effective: { useLibrary: true } } },
1982
+ refresh: async () => { error = '' }, setError: value => { error = value },
1983
+ })
1984
+ await setScope('useLibrary', false)
1985
+ assert.match(error, /scopeNotApplied/)
1986
+ assert.equal(logged, 1)
1987
+ })
1988
+
1989
+ test('a scope write completed after a session switch cannot start an old refresh', async () => {
1990
+ let release, refreshed = 0
1991
+ const reply = new Promise(resolve => { release = resolve })
1992
+ const currentSession = { current: 'old' }
1993
+ const pending = reviewSetScope({ currentSession, call: () => reply, refresh: async () => { refreshed++ } })('useLibrary', false)
1994
+ currentSession.current = 'new'
1995
+ release({ effective: { useLibrary: true } })
1996
+ await pending
1997
+ assert.equal(refreshed, 0)
1998
+ })
1999
+
2000
+ test('a failed read-back after a scope write keeps the actual read error', async () => {
2001
+ let error = ''
2002
+ const setScope = reviewSetScope({
2003
+ refresh: async () => { error = 'read-back unavailable'; return false },
2004
+ setError: value => { error = value },
2005
+ })
2006
+ await setScope('useLibrary', true)
2007
+ assert.equal(error, 'read-back unavailable')
2008
+ })