dsh-soul 0.7.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,7 +26,7 @@ import { assertCount } from './lib/skip-report.mjs'
26
26
 
27
27
  // 基线运行应跑出的断言数。本脚本没有环境相关跳过(客户端源码与 Node 都在),
28
28
  // 所以链里的 `--strict` 对它无额外语义;数字由下面的 assertCount 守住。
29
- const EXPECTED_ASSERTIONS = 23
29
+ const EXPECTED_ASSERTIONS = 52
30
30
 
31
31
  const source = readFileSync(new URL('../client/index.mjs', import.meta.url), 'utf8')
32
32
 
@@ -140,16 +140,32 @@ function createRuntime() {
140
140
  unmount() {
141
141
  for (const fn of cleanups.values()) if (typeof fn === 'function') fn()
142
142
  cleanups.clear()
143
+ // ⚠️ 必须**同时清掉 frames**:它是按渲染路径缓存的 hook 状态(useState 的当前值、
144
+ // 已跑过的 deps)。只跑 cleanup 而不清 frames,下一次 render 会复用旧的
145
+ // values/deps —— 于是「重新挂载」实际是「接着上次的状态继续」,effect 因为
146
+ // deps 未变而不再执行。判断力对照实测:不清 frames 时,换掉路由后重进页面
147
+ // 仍然显示上一次成功的数据,看起来像"组件没重新加载"。
148
+ frames.clear()
149
+ frameStack = []
143
150
  dirty = false
144
151
  queue = []
145
152
  },
146
- /** 渲染 + 跑本轮 effect,直到状态不再变化(含 effect / handler 里已 resolve 的 promise)。 */
153
+ /**
154
+ * 渲染 + 跑 effect,直到**状态与异步副作用都稳定**,并返回稳定后的那棵树。
155
+ *
156
+ * 踩过的坑:上一版在 `if (!dirty) return tree` 时返回的是**倒数第二轮**渲染的树 ——
157
+ * 而「最后一轮」什么都没做(dirty 仍为 false,是上一轮的 false 摆在那)。于是
158
+ * 由 `await` 触发的 setState(例如点「绑定」后 handleBind 里 resolve 的那次)
159
+ * 虽然被记进了 frame,却**永远没有出现在返回的树里**:断言看到的是旧画面。
160
+ */
147
161
  async settle(root) {
162
+ let tree = null
148
163
  for (let pass = 0; pass < 40; pass++) {
149
164
  dirty = false
150
165
  queue = []
151
- const tree = render(root, 'root')
152
- for (const { frame, slot, fn } of queue) {
166
+ tree = render(root, 'root')
167
+ const effects = queue
168
+ for (const { frame, slot, fn } of effects) {
153
169
  const key = `${frame.key}#${slot}`
154
170
  const previous = cleanups.get(key)
155
171
  if (typeof previous === 'function') previous()
@@ -157,7 +173,12 @@ function createRuntime() {
157
173
  cleanups.set(key, typeof returned === 'function' ? returned : null)
158
174
  }
159
175
  await drain()
160
- if (!dirty) return tree
176
+ if (!dirty) {
177
+ // 本帧的 effect 都已执行完。若这一帧**一个 effect 都没跑**,它就是最终画面
178
+ // (上一轮的 tree 与它等价);否则这一帧仍是「状态刚被 effect 改写、尚未重画」
179
+ // 的中间态,必须再渲一轮才把新状态画出来。
180
+ return effects.length === 0 ? tree : render(root, 'root')
181
+ }
161
182
  }
162
183
  throw new Error('渲染未收敛(40 轮仍在变化)—— hook 依赖或 effect 里可能有自激循环')
163
184
  }
@@ -245,7 +266,7 @@ const interpolate = (text, params) =>
245
266
  String(text).replace(/\{(\w+)\}/g, (all, key) => (params && key in params ? String(params[key]) : all))
246
267
 
247
268
  /** 载入真实客户端 bundle 并装配插件(返回真实 controller 与设置页组件)。 */
248
- function loadClient(routes) {
269
+ function loadClient(routes, options = {}) {
249
270
  let factory = null
250
271
  const domNode = () => ({
251
272
  style: { setProperty() {}, removeProperty() {} },
@@ -307,7 +328,31 @@ function loadClient(routes) {
307
328
  // ui.Button / ui.Toast 单独换成宿主元素标记:这样它们连同 onClick / text /
308
329
  // tone / holdMs / onDone 原样留在渲染树里,断言就能像用户一样
309
330
  // 「找到那个按钮并点它」、「读出提示条的文案与色调」,而不是去猜某个闭包。
310
- return { Button: 'ui-button', Toast: 'ui-toast' }
331
+ // IconAgentPresetOutlineRegular:宿主 primitives 里的「智能体预设」图标,
332
+ // header 人设标签用它(与邻居「创造模式」标签同一套图标语言)。
333
+ // 桩里给一个可识别的元素标记,断言就能验证「图标确实渲染了」。
334
+ return {
335
+ Button: 'ui-button',
336
+ Toast: 'ui-toast',
337
+ // 气泡:行尾徽标用宿主 Tooltip(与「置顶/归档」同一套黑色气泡),
338
+ // 断言要能读到它的 label / side / delayMs。
339
+ Tooltip: 'ui-tooltip',
340
+ IconAgentPresetOutlineRegular: 'ui-icon-persona'
341
+ }
342
+ // 白名单校验:访问未声明的名字一律返回 undefined(与真实宿主一致),
343
+ // 并大声报错 —— 让「用了宿主没有的图标名」在测试期就暴露,
344
+ // 而不是等它在浏览器里把整个区块崩掉。
345
+ return new Proxy(shimmed, {
346
+ get(target, prop) {
347
+ if (typeof prop !== 'string') return target[prop]
348
+ if (prop in target) return target[prop]
349
+ if (ICON_WHITELIST.has(prop)) return 'ui-' + prop
350
+ throw new Error(
351
+ 'ui.' + prop + ' 不在宿主模块表里(真实运行时会拿到 undefined ⇒ React error #130)。' +
352
+ '可用图标见 ICON_WHITELIST 或宿主 bundle 的 TU 定义。'
353
+ )
354
+ }
355
+ })
311
356
  }
312
357
  throw new Error(`未预料的 require:${spec}`)
313
358
  }
@@ -319,9 +364,31 @@ function loadClient(routes) {
319
364
  // **装配层**」—— 此前它们全在 SoulSettings 组件内,设置页没挂载时全部失效
320
365
  // (底栏人设名因此不刷新)。stub 原本是空实现,这里让它可观测。
321
366
  const captured = { provide: {}, sections: [], dicts: null, runtime, events: { window: [], document: [] } }
367
+ // 目录点选服务桩:默认可用,用例可换成 `{ throw: '...' }` 走降级路径。
368
+ // 宿主 UiWorkspaceService.pickDirectory() 返回 string | null,失败时抛普通 Error
369
+ // (capability 被包在 cause 里、客户端读不到)—— 桩必须同形,见 DESIGN §7.5。
370
+ captured.uiWorkspace = {
371
+ pickDirectory: async () => null
372
+ }
373
+ // inject 的语义要跟宿主一致:**同步回调**、回调里的 ctx 就是新 scope。
374
+ // 返回的是一个可 unload 的 fiber;这里只记录已触发次数与卸载函数。
375
+ captured.injected = []
376
+ captured.uiWorkspaceAbsent = options.uiWorkspace === null
322
377
  const ctx = {
323
378
  provide: (name, value) => { captured.provide[name] = value },
324
379
  effect: (fn) => { const dispose = fn(); if (typeof dispose === 'function') captured.sections.push({ dispose }) },
380
+ // 动态 inject:只有 uiWorkspace 一个依赖。**不调用**回调 = 服务缺席,
381
+ // 正好用来断言「缺席时插件照常装配、只是点选按钮降级」。
382
+ inject: (deps, cb) => {
383
+ captured.injected.push({ deps, cb })
384
+ const requested = Array.isArray(deps) ? deps : Object.keys(deps || {})
385
+ if (!requested.includes('uiWorkspace')) return
386
+ if (captured.uiWorkspaceAbsent) return
387
+ cb({
388
+ uiWorkspace: captured.uiWorkspace,
389
+ effect: (fn) => { const dispose = fn(); if (typeof dispose === 'function') captured.sections.push({ dispose }) }
390
+ })
391
+ },
325
392
  locale: {
326
393
  register: (_ns, dicts) => { captured.dicts = dicts },
327
394
  bind: () => (key, params) => interpolate((captured.dicts?.zh || {})[key] ?? key, params)
@@ -362,7 +429,7 @@ function loadClient(routes) {
362
429
  * **从未被执行过**:把它改成真实形状,整套 C 系列依然全绿(实测)。这正是「测试替身
363
430
  * 与真实协议漂移」的典型:桩喂了一个真实环境不可达的输入,测试永远看不到真问题。
364
431
  */
365
- async function boot(configPayload = {}, personaPayload = null) {
432
+ async function boot(configPayload = {}, personaPayload = null, options = {}) {
366
433
  fetchCalls = []
367
434
  timerQueue = []
368
435
  const routes = {
@@ -373,12 +440,12 @@ async function boot(configPayload = {}, personaPayload = null) {
373
440
  // 默认形状贴近宿主:对象 map + activeName(不是数组、不是 activePersona)
374
441
  '/api/soul/personas': () => (personaPayload || {
375
442
  ok: true,
376
- personas: { 苏格拉底式提问者: { style: 'professional', builtin: true } },
443
+ personas: { 苏格拉底式提问者: { style: 'professional', builtin: true }, 极简主义者: { style: 'efficient' } },
377
444
  activeName: null
378
445
  }),
379
446
  '/api/soul/prompt': () => ({ ok: true, prompt: 'P', enabled: true })
380
447
  }
381
- const world = loadClient(routes)
448
+ const world = loadClient(routes, options)
382
449
  for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
383
450
  return world
384
451
  }
@@ -400,8 +467,22 @@ function rootElement(world) {
400
467
 
401
468
  const renderSettings = (world) => world.runtime.settle(rootElement(world))
402
469
 
470
+ /**
471
+ * 渲染设置页并**等异步副作用落地**(点击后的请求、effect 里的 setState)。
472
+ *
473
+ * `settle` 只保证「状态收敛」,而一个 handler 里的 `await fetch` 要等下一轮
474
+ * microtask 才把结果写回 store。断言「点完之后界面上有什么」时必须用它,
475
+ * 否则读到的是点击前那一帧(本文件踩过:绿字已进 store 却读不出来)。
476
+ */
477
+ async function renderSettingsSettled(world) {
478
+ for (let i = 0; i < 6; i++) await new Promise((r) => drainTick(r))
479
+ return world.runtime.settle(rootElement(world))
480
+ }
481
+
403
482
  /** 输入框左侧的快捷开关(conversation.input.left 槽位),渲染方式与设置页同源。 */
404
483
  function quickToggleElement(world) {
484
+ // 快捷开关留在 **conversation.input.left**(输入框左侧只留「开/关」这个动作)。
485
+ // 人设名与层级标注在 0.9.0-h 挪到了 conversation.session.header.actions。
405
486
  const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.input.left')
406
487
  assert.ok(slot, '未注册 conversation.input.left 槽位')
407
488
  const props = slot.options.inject()
@@ -414,6 +495,25 @@ function quickToggleElement(world) {
414
495
  return { type: slot.component, props: { ...props, useSoulController } }
415
496
  }
416
497
 
498
+ /**
499
+ * 渲染会话 header 的人设标签(0.9.0-h 起从输入框左侧挪到这里)。
500
+ *
501
+ * 槽位是 conversation.session.header.actions(kind:'list' / scope:'session'),
502
+ * inject 收到**位置参数** [sessionId]。
503
+ */
504
+ function personaLabelElement(world, sessionId = 'session-abc') {
505
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.session.header.actions')
506
+ assert.ok(slot, '未注册 conversation.session.header.actions 槽位')
507
+ const props = slot.options.inject(sessionId)
508
+ const store = props.hooks.soulController
509
+ const useSoulController = (selector) => {
510
+ const [, force] = world.runtime.React.useState(0)
511
+ world.runtime.React.useEffect(() => store.subscribe(() => force((n) => n + 1)), [])
512
+ return selector(store.getSnapshot())
513
+ }
514
+ return { type: slot.component, props: { ...props, useSoulController } }
515
+ }
516
+
417
517
  /** 像用户一样点快捷开关,返回之后的按钮节点(可读 props 上的反馈)。 */
418
518
  async function clickQuickToggle(world) {
419
519
  const before = await world.runtime.settle(quickToggleElement(world))
@@ -614,6 +714,644 @@ try {
614
714
  assert.equal(good.props['data-failed'], 'false', '成功时不应残留失败标记')
615
715
  })
616
716
 
717
+ await check('C44 会话人设 tab:没有生效人设时右栏仍须有「用这个」按钮(兜底不得缺席)', async () => {
718
+ // 症状:全局配置不匹配任何预设(手改过特质)⇒ 服务端 activePersona 为 null
719
+ // ⇒ 若选中态没有兜底,右栏渲染成「点左侧任意一张卡」的空提示,
720
+ // **一个按钮都没有** —— 用户看到的是「点了没反应」(其实按钮都没画出来)。
721
+ const world = await boot()
722
+ const zh = world.dicts.zh
723
+ world.routes['/api/soul/personas'] = () => ({
724
+ ok: true,
725
+ personas: {
726
+ 苏格拉底式提问者: { style: 'professional', builtin: true },
727
+ 幽默风趣: { style: 'humorous', builtin: true }
728
+ },
729
+ activeName: null
730
+ })
731
+ await world.controller.loadPersonas()
732
+ world.routes['/api/soul/session-scope'] = (call) => {
733
+ if (call.method === 'GET') {
734
+ return {
735
+ ok: true,
736
+ sessionId: 'session-abc',
737
+ workspaceId: null,
738
+ override: null,
739
+ source: 'global',
740
+ activePersona: null // ← 不匹配任何预设
741
+ }
742
+ }
743
+ return { ok: true, sessionId: 'session-abc', override: null, source: 'global', activePersona: null }
744
+ }
745
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.view')
746
+ const props = slot.options.inject('session-abc')
747
+ const useSoulController = (selector) => selector(world.controller.store.getSnapshot())
748
+ const t2 = (k, p2) => {
749
+ const raw = zh[k] ?? k
750
+ return p2 ? raw.replace(/\{(\w+)\}/g, (m, n) => (p2[n] === undefined ? m : String(p2[n]))) : raw
751
+ }
752
+ await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t: t2 } })
753
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
754
+ const tree = await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t: t2 } })
755
+
756
+ // ① 右栏必须有详情(不能是空提示)
757
+ const detail = findAllByClass(tree, 'soul-session-detail')[0]
758
+ assert.ok(detail, '应有右栏详情面板')
759
+ assert.equal(
760
+ textOf(detail).includes(zh['session.pickHint']),
761
+ false,
762
+ '右栏不得停在「点左侧任意一张卡」的空提示 —— 那样一个按钮都没有,用户看到的是「点了没反应」'
763
+ )
764
+ // ② 必须有可点的「用这个」
765
+ const btns = findAllByClass(detail, 'soul-persona-action')
766
+ assert.equal(btns.length, 1, `右栏应恰好一个操作按钮,实际 ${btns.length}`)
767
+ assert.equal(textOf(btns[0]), zh['session.useCard'], '应显示「用这个」')
768
+ // ③ 预设数少于 3 时不得重复渲染同一张(重复 React key + 中心卡判据失真)
769
+ const cards = findAllByClass(tree, 'soul-session-card')
770
+ const names = cards.map((c) => textOf(findAllByClass(c, 'soul-persona-label')[0] || c))
771
+ assert.equal(new Set(names).size, names.length, `卡片不得重复渲染同一张:${JSON.stringify(names)}`)
772
+ })
773
+
774
+ await check('C43 会话人设 tab:view 到达后中心卡 = 生效的那张(兜底不得抢先)', async () => {
775
+ // 这个 bug 的形态:选中态的兜底在 view 加载完成前就跑了,抢先选中第一个预设;
776
+ // 等 view 到达,「selectedPersona !== null」的守卫又把正确选择挡回去 ——
777
+ // 结果是「生效的那张被甩到侧边、中心卡是别的预设」。
778
+ // 判据:中心卡的名字必须等于服务端回的 activePersona。
779
+ const world = await boot()
780
+ const zh = world.dicts.zh
781
+ world.routes['/api/soul/personas'] = () => ({
782
+ ok: true,
783
+ personas: {
784
+ 苏格拉底式提问者: { style: 'professional', builtin: true },
785
+ 幽默风趣: { style: 'humorous', builtin: true }
786
+ },
787
+ activeName: null
788
+ })
789
+ await world.controller.loadPersonas()
790
+ world.routes['/api/soul/session-scope'] = (call) => {
791
+ if (call.method === 'GET') {
792
+ return {
793
+ ok: true,
794
+ sessionId: 'session-abc',
795
+ workspaceId: null,
796
+ override: { style: 'humorous' },
797
+ source: 'session',
798
+ activePersona: '幽默风趣'
799
+ }
800
+ }
801
+ return { ok: true, sessionId: 'session-abc', override: null, source: 'global', activePersona: '苏格拉底式提问者' }
802
+ }
803
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.view')
804
+ const props = slot.options.inject('session-abc')
805
+ const useSoulController = (selector) => selector(world.controller.store.getSnapshot())
806
+ const t2 = (k, p2) => {
807
+ const raw = zh[k] ?? k
808
+ return p2 ? raw.replace(/\{(\w+)\}/g, (m, n) => (p2[n] === undefined ? m : String(p2[n]))) : raw
809
+ }
810
+ await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t: t2 } })
811
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
812
+ const tree = await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t: t2 } })
813
+
814
+ const cards = findAllByClass(tree, 'soul-session-card')
815
+ const center = cards.find((c) => c.props['data-current'] === 'true')
816
+ assert.ok(center, '应有一张中心卡')
817
+ // 卡面已无可见文字(0.9.0-l)⇒ 用 aria-label 识别预设名。
818
+ // 同时这条断言顺带守住了「纯图形元素必须有可访问名」这条无障碍要求。
819
+ const centerName = String(center.props['aria-label'] || '')
820
+ assert.ok(
821
+ centerName.includes('幽默风趣'),
822
+ `中心卡应是生效的「幽默风趣」,实际「${centerName}」(兜底抢先选中了第一张)`
823
+ )
824
+ // 右栏详情也必须与中心卡一致
825
+ const detailName = textOf(findAllByClass(findAllByClass(tree, 'soul-session-detail')[0], 'soul-session-detail-name')[0] || {})
826
+ assert.ok(detailName.includes('幽默风趣'), `右栏详情应是「幽默风趣」,实际「${detailName}」`)
827
+ })
828
+
829
+ await check('C40 header 人设标签:显示会话实际人设 + 来源层级,不退回全局值', async () => {
830
+ // 背景:三级隔离下「全局匹配结果」与「会话实际生效值」可以不同 ——
831
+ // 用户在设置页选了 A(全局)、在会话里选了 B(会话覆盖),模型实际用 B。
832
+ // 标签若显示全局的 A,就会出现「界面说 A、模型用 B」的割裂。
833
+ const world = await boot()
834
+ // 全局是「游戏开发与策划专家」,会话实际是「资深架构师」
835
+ world.routes['/api/soul/config'] = (call) => (call.method === 'GET'
836
+ ? { ok: true, config: { ...CONFIG, style: 'roast' } }
837
+ : { ok: true, config: { ...CONFIG } })
838
+ world.routes['/api/soul/session-scope/current'] = (call) => ({
839
+ ok: true,
840
+ sessionId: 'sess-1',
841
+ workspaceId: 'ws_1',
842
+ override: { style: 'professional' },
843
+ source: 'session',
844
+ activePersona: '资深架构师',
845
+ globalPersona: '游戏开发与策划专家',
846
+ workspaceTitle: 'dsh-plugin'
847
+ })
848
+
849
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.session.header.actions')
850
+ assert.ok(slot, '前置条件:conversation.input.left 已注册')
851
+ // scope:'session' 槽位的标准 props 带 sessionId —— 宿主 ui-session 的
852
+ // BUILTIN_SOURCE 声明了 props: ["sessionId"]。没有它就查不到会话作用域。
853
+ const injected = slot.options.inject('sess-1')
854
+ assert.equal(injected.sessionId, 'sess-1', 'inject 必须把 sessionId 传给组件')
855
+
856
+ const props = injected
857
+ const useSoulController = (selector) => selector(world.controller.store.getSnapshot())
858
+ const t = (k, p) => {
859
+ const raw = world.dicts.zh[k] ?? k
860
+ return p ? raw.replace(/\{(\w+)\}/g, (m, n) => (p[n] === undefined ? m : String(p[n]))) : raw
861
+ }
862
+ await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t } })
863
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
864
+ const tree = await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t } })
865
+ const text = textOf(tree)
866
+
867
+ // ① 显示的是**会话实际**的人设,不是全局那个
868
+ assert.ok(text.includes('资深架构师'), `标签应显示会话实际人设,实际「${text}」`)
869
+ // ③ 必须有图标(人设概念的视觉标识)
870
+ // 断言的是「渲染出了图标元素」,不是「用了哪个图标」——
871
+ // 图标来源换实现时这条不该失配。
872
+ const icons = findAllByClass(tree, 'soul-session-persona-label-icon')
873
+ assert.equal(icons.length, 1, '人设标签应渲染一个图标')
874
+ // 尺寸必须与邻居(header 上的「创造模式」标签)一致,否则同一行里两个图标大小不齐。
875
+ // 0.9.0-w 起换成自绘面具 SVG:尺寸属性从宿主图标的 size 变成 SVG 的 width/height。
876
+ // 判断力对照实测:不写尺寸时这条必须拦住。
877
+ assert.equal(
878
+ icons[0].props.width,
879
+ 14,
880
+ `图标宽度应为 14(与邻居 AgentPresetLabel 视觉一致),实际 ${String(icons[0].props.width)}`
881
+ )
882
+ assert.equal(
883
+ icons[0].props.height,
884
+ 14,
885
+ `图标高度应为 14,实际 ${String(icons[0].props.height)}`
886
+ )
887
+ // header 标签只显示人设与层级,不重复「个性化已启用」(那是输入框左侧开关的事)
888
+ assert.equal(text.includes('个性化已启用'), false, 'header 标签不应重复开关文案')
889
+ assert.equal(text.includes('游戏开发与策划专家'), false, '标签不得显示全局人设(那与模型实际用的不符)')
890
+ // ② 带来源层级标注
891
+ assert.ok(text.includes(world.dicts.zh['quick.scopeSession']), '应标注来源是「本会话覆盖」')
892
+ assert.equal(findAllByClass(tree, 'soul-session-persona-label-scope').length, 1, '应有且仅有一个来源层级标注')
893
+ })
894
+
895
+ await check('C46 header/input.left 的 inject 按**位置参数**收 sessionId(不是 props 对象)', async () => {
896
+ // 宿主契约 FactoryInjectParams:
897
+ // scope 'session' → [sessionId: SessionId]
898
+ // scope 'session-maybe'→ [sessionId: SessionId | undefined]
899
+ // scope 'root' → []
900
+ //
901
+ // 这里曾写成 `inject: (props) => ({ sessionId: props?.sessionId })` ——
902
+ // props 实际是 sessionId **字符串**,props.sessionId 是 undefined,
903
+ // 于是 sessionId 恒为 null,标签拿不到当前会话、层级标注整块不显示。
904
+ //
905
+ // 判据:inject 传字符串能拿到 sessionId;传对象拿不到(对象不是契约里的形态)。
906
+ const world = await boot()
907
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.session.header.actions')
908
+ assert.ok(slot, '前置条件:conversation.input.left 已注册')
909
+
910
+ const injected = slot.options.inject('sess-real')
911
+ assert.equal(injected.sessionId, 'sess-real', 'inject 传 sessionId 字符串时必须原样透传')
912
+
913
+ // 反向:传对象不得被误当成 props
914
+ const wrong = slot.options.inject({ sessionId: 'sess-object' })
915
+ assert.equal(
916
+ wrong.sessionId,
917
+ null,
918
+ 'inject 传对象时不得从中取 sessionId —— 契约里那是位置参数,不是 props'
919
+ )
920
+ })
921
+
922
+ await check('C45 header 人设标签:每种作用域来源都要有层级标注(含「全局配置」)', async () => {
923
+ // ⚠️ global 分支曾**缺失**:source 为 'global' 时 scopeTag 返回 null,
924
+ // 标签整块不渲染 ⇒ 用户看到「· 人设名」却**没有任何层级标注**。
925
+ // 而全局恰恰是最该标出来的一层:它意味着「改这里会影响所有会话」。
926
+ const world = await boot()
927
+ const zh = world.dicts.zh
928
+ world.routes['/api/soul/personas'] = () => ({
929
+ ok: true,
930
+ personas: { 幽默风趣: { style: 'humorous', builtin: true } },
931
+ activeName: '幽默风趣'
932
+ })
933
+ await world.controller.loadPersonas()
934
+
935
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.session.header.actions')
936
+ assert.ok(slot, '前置条件:conversation.input.left 已注册')
937
+ const props = slot.options.inject('sess-1')
938
+ const useSoulController = (selector) => selector(world.controller.store.getSnapshot())
939
+ const t2 = (k, p2) => {
940
+ const raw = zh[k] ?? k
941
+ return p2 ? raw.replace(/\{(\w+)\}/g, (m, n) => (p2[n] === undefined ? m : String(p2[n]))) : raw
942
+ }
943
+
944
+ // 逐个 source 验一遍:每一种都必须有对应的层级标注
945
+ const cases = [
946
+ ['session', zh['quick.scopeSession']],
947
+ ['workspace', zh['quick.scopeWorkspace']],
948
+ ['directory', zh['quick.scopeDirectory']],
949
+ ['global', zh['quick.scopeGlobal']]
950
+ ]
951
+ for (const [source, expected] of cases) {
952
+ // ⚠️ 必须换 sessionId 而不是复用同一棵树:scopeView 是 useState,
953
+ // 改路由桩不会让已有实例自动重取数 —— 复用就会读到上一次的 source。
954
+ // 换 sessionId 会触发 effect 的依赖变化(effect 依赖 [sessionId]),
955
+ // 重新取数 —— 这也更接近真实场景(用户在两个会话间切换)。
956
+ const sid = 'sess-' + source
957
+ world.routes['/api/soul/session-scope/current'] = () => ({
958
+ ok: true,
959
+ sessionId: sid,
960
+ workspaceId: source === 'workspace' ? 'ws_1' : null,
961
+ override: source === 'session' ? { style: 'humorous' } : null,
962
+ source,
963
+ activePersona: '幽默风趣',
964
+ globalPersona: '幽默风趣',
965
+ workspaceTitle: source === 'workspace' ? 'dsh-plugin' : null
966
+ })
967
+ const p2 = { ...props, useSoulController, t: t2, sessionId: sid }
968
+ await world.runtime.settle({ type: slot.component, props: p2 })
969
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
970
+ const tree = await world.runtime.settle({ type: slot.component, props: p2 })
971
+ const tags = findAllByClass(tree, 'soul-session-persona-label-scope')
972
+ assert.equal(tags.length, 1, `source=${source} 应有且仅有一个层级标注,实际 ${tags.length}`)
973
+ // 期望值里的 {name} 要按本 case 的 workspaceTitle 填上 —— 词典键里是模板,
974
+ // 直接拿原始字符串去比会永远不相等。
975
+ const expectedText = expected.replace(/\{name\}/g, source === 'workspace' ? 'dsh-plugin' : '')
976
+ assert.ok(
977
+ textOf(tags[0]).includes(expectedText),
978
+ `source=${source} 的标注应为「${expectedText}」,实际「${textOf(tags[0])}」`
979
+ )
980
+ }
981
+
982
+ // 未知 source:明说「未知」而不是静默不标(服务端新增层级时客户端要跟得上)
983
+ world.routes['/api/soul/session-scope/current'] = () => ({
984
+ ok: true, sessionId: 'sess-brand-new', override: null,
985
+ source: 'brand-new-layer', activePersona: '幽默风趣', globalPersona: '幽默风趣'
986
+ })
987
+ const p3 = { ...props, useSoulController, t: t2, sessionId: 'sess-brand-new' }
988
+ await world.runtime.settle({ type: slot.component, props: p3 })
989
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
990
+ const tree = await world.runtime.settle({ type: slot.component, props: p3 })
991
+ const tags = findAllByClass(tree, 'soul-session-persona-label-scope')
992
+ assert.equal(tags.length, 1, '未知 source 也必须有标注(明说「未知」,不能静默不标)')
993
+ assert.ok(textOf(tags[0]).includes(zh['quick.scopeUnknown']), '未知 source 应标为「会话状态未知」')
994
+ })
995
+
996
+ await check('C48 会话作用域写 store 必须换引用(原地改不会触发重渲染)', async () => {
997
+ // store 的 update 做的是**浅比较**:只有被改字段的引用变了才会通知订阅者。
998
+ // 原地改 s.sessionScopes[x] = scope 时,sessionScopes 引用没变 ⇒ 不通知 ⇒
999
+ // 真实浏览器里标签不会重渲染(但 getSnapshot() 仍能读到新值 —— 所以
1000
+ // 「重新读快照」型断言会漏网)。
1001
+ const world = await boot()
1002
+ world.routes['/api/soul/session-scope'] = (call) => (call.method === 'GET'
1003
+ ? { ok: true, sessionId: 's1', override: null, source: 'global', activePersona: null }
1004
+ : { ok: true, sessionId: 's1', override: { style: 'humorous' }, source: 'session', activePersona: 'X' })
1005
+ const before = world.controller.store.getSnapshot().sessionScopes
1006
+ await world.controller.saveSessionScope('s1', { style: 'humorous' }, 'X')
1007
+ const after = world.controller.store.getSnapshot().sessionScopes
1008
+ assert.notEqual(
1009
+ after,
1010
+ before,
1011
+ '写会话作用域必须**换新对象** —— 原地改不会触发 store 的浅比较,订阅者不会重渲染'
1012
+ )
1013
+ assert.equal(after.s1.activePersona, 'X', '新对象里应带上解析结果')
1014
+ })
1015
+
1016
+ await check('C51 更新到预设:保存后表单也回退到当前配置(dirty 消失)', async () => {
1017
+ // 用户要求:更新到预设之后,表单内容也要回到**当前人设**(当前配置)的内容。
1018
+ //
1019
+ // 理由与「存为预设(不勾选立即应用)」一致:更新的是**另一个对象**(某个已有预设),
1020
+ // 当前配置没有变。若不回退,底部会同时显示「已更新预设「X」」与
1021
+ // 「有未保存的更改」—— 同一类矛盾提示。
1022
+ const world = await boot()
1023
+ const zh = world.dicts.zh
1024
+ world.routes['/api/soul/personas'] = () => ({
1025
+ ok: true,
1026
+ personas: {
1027
+ 苏格拉底式提问者: { style: 'professional', builtin: true },
1028
+ 我的预设: { style: 'casual', builtin: false }
1029
+ },
1030
+ activeName: '苏格拉底式提问者'
1031
+ })
1032
+ await world.controller.loadPersonas()
1033
+ world.routes['/api/soul/personas/save'] = (call) => ({
1034
+ ok: true,
1035
+ personas: { 苏格拉底式提问者: { style: 'professional', builtin: true }, 我的预设: { style: 'casual', builtin: false } },
1036
+ activeName: '苏格拉底式提问者'
1037
+ })
1038
+
1039
+ // ① 先改表单制造 dirty
1040
+ const tree0 = await renderSettings(world)
1041
+ const nickInput = findAll(tree0, (n) => n.type === 'input' && n.props && n.props.id === 'soul-nickname')[0]
1042
+ assert.ok(nickInput, '应能看到昵称输入框')
1043
+ await nickInput.props.onChange({ target: { value: '临时昵称' } })
1044
+ const dirtyTree = await renderSettings(world)
1045
+ assert.equal(
1046
+ findAllByClass(dirtyTree, 'soul-dirty').length,
1047
+ 1,
1048
+ '前置条件:改了表单后应显示「有未保存的更改」'
1049
+ )
1050
+
1051
+ // ② 打开「更新到预设」弹层,选「我的预设」
1052
+ const openBtn = findAll(dirtyTree, (n) => textOf(n) === zh['personas.updateTo'])[0]
1053
+ assert.ok(openBtn, '应有「更新到预设」按钮')
1054
+ await openBtn.props.onClick()
1055
+ const withModal = await renderSettings(world)
1056
+ const item = findAllByClass(withModal, 'soul-update-item')
1057
+ .find((n) => textOf(n).includes('我的预设'))
1058
+ assert.ok(item, '弹层里应能选到「我的预设」')
1059
+ await item.props.onClick()
1060
+ await new Promise((r) => drainTick(r))
1061
+
1062
+ // ③ 更新后 dirty 必须消失,且表单回到**当前配置**的值
1063
+ const finalTree = await renderSettings(world)
1064
+ assert.equal(
1065
+ findAllByClass(finalTree, 'soul-dirty').length,
1066
+ 0,
1067
+ '更新预设后不应再有「有未保存的更改」(表单应回退到当前配置)'
1068
+ )
1069
+ // 昵称回到 CONFIG 里的值(不是临时昵称)
1070
+ const nickAfter = findAll(finalTree, (n) => n.type === 'input' && n.props && n.props.id === 'soul-nickname')[0]
1071
+ assert.ok(nickAfter, '应仍能看到昵称输入框')
1072
+ assert.equal(
1073
+ nickAfter.props.value,
1074
+ CONFIG.nickname || '',
1075
+ `昵称应回退到当前配置的值,实际「${String(nickAfter.props.value)}」`
1076
+ )
1077
+ })
1078
+
1079
+ await check('C49 存为预设:勾选「立即应用」则切换;不勾选则表单回退、dirty 消失', async () => {
1080
+ // 用户实测的困惑:改完表单直接「存为预设」后,底部同时显示
1081
+ // 「已保存预设「X」」和「有未保存的更改」—— 读起来像"到底存没存"。
1082
+ //
1083
+ // 修法:弹层里给一个「保存后立即应用」复选框。
1084
+ // 勾选 ⇒ savePersona + usePersona(dirty 消失,★ 指向新预设)
1085
+ // 不勾选 ⇒ savePersona + 表单回退到已保存配置(dirty 消失)
1086
+ // 两条分支都必须**消掉 dirty**,否则矛盾提示还在。
1087
+ const world = await boot()
1088
+ const zh = world.dicts.zh
1089
+ const posts = []
1090
+ world.routes['/api/soul/personas'] = () => ({
1091
+ ok: true,
1092
+ personas: {
1093
+ 苏格拉底式提问者: { style: 'professional', builtin: true },
1094
+ 新预设: { style: 'roast', builtin: false }
1095
+ },
1096
+ activeName: null
1097
+ })
1098
+ await world.controller.loadPersonas()
1099
+ world.routes['/api/soul/personas/save'] = (call) => {
1100
+ posts.push({ kind: 'save', body: call.body })
1101
+ return { ok: true, personas: { 苏格拉底式提问者: { style: 'professional', builtin: true }, 新预设: { style: 'roast', builtin: false } }, activeName: null }
1102
+ }
1103
+ world.routes['/api/soul/personas/use'] = (call) => {
1104
+ posts.push({ kind: 'use', body: call.body })
1105
+ return { ok: true, config: { ...CONFIG, style: 'roast' }, invalid: [], changed: ['style'], unchanged: false }
1106
+ }
1107
+
1108
+ // ① 先**真的改一个字段**,让表单 dirty —— 否则「回退后 dirty 消失」是空断言。
1109
+ // (判断力对照实测:不改就存时 dirty 初始为 false,把整段回退逻辑删掉仍然全绿。)
1110
+ const tree0 = await renderSettings(world)
1111
+ // 默认展开的是「关于你」分组 ⇒ 昵称输入框可见。用它制造 dirty ——
1112
+ // 风格控件在「特质」分组里,默认折叠时不渲染。
1113
+ const nickInput = findAll(tree0, (n) => n.type === 'input' && n.props && n.props.id === 'soul-nickname')[0]
1114
+ assert.ok(nickInput, '应能看到昵称输入框(关于你分组默认展开)')
1115
+ await nickInput.props.onChange({ target: { value: '临时昵称' } })
1116
+ const dirtyTree = await renderSettings(world)
1117
+ assert.equal(
1118
+ findAllByClass(dirtyTree, 'soul-dirty').length,
1119
+ 1,
1120
+ '前置条件:改了表单后应显示「有未保存的更改」'
1121
+ )
1122
+
1123
+ // ② 不勾选:只 save,不 use
1124
+ const tree = await renderSettings(world)
1125
+ // 找到「存为预设」按钮
1126
+ const openBtn = findAll(tree, (n) => textOf(n) === zh['personas.saveAs'])[0]
1127
+ assert.ok(openBtn, '应有「存为预设」按钮')
1128
+ await openBtn.props.onClick()
1129
+ const withModal = await renderSettings(world)
1130
+ // 输入名字
1131
+ const input = findAll(withModal, (n) => n.type === 'input' && n.props && n.props.id === 'soul-new-persona-name')[0]
1132
+ assert.ok(input, '弹层应有名称输入框')
1133
+ await input.props.onChange({ target: { value: '新预设' } })
1134
+ const withName = await renderSettings(world)
1135
+ // 默认不勾选
1136
+ // ⚠️ 必须限定在**弹层内**找:设置页本身还有一个复选框(soul-enabled 启用开关),
1137
+ // 在整棵树里取第一个 type=checkbox 会抓到它(判断力对照实测踩过)。
1138
+ const modal = findAll(withName, (n) => n.props && n.props.className === 'soul-modal')[0]
1139
+ assert.ok(modal, '应能找到弹层容器')
1140
+ const checkbox = findAll(modal, (n) => n.type === 'input' && n.props && n.props.type === 'checkbox')[0]
1141
+ assert.ok(checkbox, '弹层应有「保存后立即应用」复选框')
1142
+ // 垫片不做受控属性归一化:初始值可能是 undefined 而非 false ⇒ 判「非真」
1143
+ assert.ok(!checkbox.props.checked, '默认不勾选(不该替用户静默改配置)')
1144
+ // 点确认
1145
+ const confirm = findAll(withName, (n) => textOf(n) === zh['personas.saveConfirm'])[0]
1146
+ assert.ok(confirm, '应有确认按钮')
1147
+ await confirm.props.onClick()
1148
+ await new Promise((r) => drainTick(r))
1149
+ const afterUnchecked = posts.map((x) => x.kind)
1150
+ assert.deepEqual(afterUnchecked, ['save'], `不勾选时只能有 save,实际 ${JSON.stringify(afterUnchecked)}`)
1151
+ // 保存必须带草稿
1152
+ assert.ok(posts[0].body.draft, '保存必须带草稿(0.9.0-r)')
1153
+
1154
+ // ⚠️ 关键:不勾选时表单必须**回退到已保存配置**,「有未保存的更改」要消失。
1155
+ // 这是用户报的矛盾的根源(「已保存预设 X」+「有未保存的更改」并存)。
1156
+ // 判断力对照实测:不写这条断言时,把回退逻辑删掉(lastSyncRef.current = null
1157
+ // 改成 void 0)仍然全绿 —— 漏网。
1158
+ const finalTree = await renderSettings(world)
1159
+ const dirtyEls = findAllByClass(finalTree, 'soul-dirty')
1160
+ assert.equal(
1161
+ dirtyEls.length,
1162
+ 0,
1163
+ `不勾选保存预设后不应再有「有未保存的更改」(表单应回退到已保存配置),实际 ${dirtyEls.length} 个`
1164
+ )
1165
+ })
1166
+
1167
+ await check('C50 勾选「立即应用」时,保存后必须调用 usePersona 并切换', async () => {
1168
+ const world = await boot()
1169
+ const zh = world.dicts.zh
1170
+ const posts = []
1171
+ world.routes['/api/soul/personas'] = () => ({
1172
+ ok: true,
1173
+ personas: { 苏格拉底式提问者: { style: 'professional', builtin: true } },
1174
+ activeName: null
1175
+ })
1176
+ await world.controller.loadPersonas()
1177
+ world.routes['/api/soul/personas/save'] = (call) => {
1178
+ posts.push({ kind: 'save', name: call.body.name })
1179
+ return { ok: true, personas: { 苏格拉底式提问者: { style: 'professional', builtin: true }, 新预设: { style: 'roast', builtin: false } }, activeName: null }
1180
+ }
1181
+ world.routes['/api/soul/personas/use'] = (call) => {
1182
+ posts.push({ kind: 'use', name: call.body.name })
1183
+ return { ok: true, config: { ...CONFIG, style: 'roast' }, invalid: [], changed: ['style'], unchanged: false }
1184
+ }
1185
+
1186
+ const tree = await renderSettings(world)
1187
+ const openBtn = findAll(tree, (n) => textOf(n) === zh['personas.saveAs'])[0]
1188
+ await openBtn.props.onClick()
1189
+ const withModal = await renderSettings(world)
1190
+ const input = findAll(withModal, (n) => n.type === 'input' && n.props && n.props.id === 'soul-new-persona-name')[0]
1191
+ await input.props.onChange({ target: { value: '新预设' } })
1192
+ const withName = await renderSettings(world)
1193
+ const modal = findAll(withName, (n) => n.props && n.props.className === 'soul-modal')[0]
1194
+ assert.ok(modal, '应能找到弹层容器')
1195
+ const checkbox = findAll(modal, (n) => n.type === 'input' && n.props && n.props.type === 'checkbox')[0]
1196
+ await checkbox.props.onChange({ target: { checked: true } })
1197
+ const checkedTree = await renderSettings(world)
1198
+ const confirm = findAll(checkedTree, (n) => textOf(n) === zh['personas.saveConfirm'])[0]
1199
+ await confirm.props.onClick()
1200
+ await new Promise((r) => drainTick(r))
1201
+ const kinds = posts.map((x) => x.kind)
1202
+ assert.deepEqual(kinds, ['save', 'use'], `勾选时应先 save 再 use,实际 ${JSON.stringify(kinds)}`)
1203
+ assert.equal(posts[1].name, '新预设', 'use 的目标应是刚保存的预设名')
1204
+ })
1205
+
1206
+ await check('C47 切换人设后,header 标签必须跟着更新(单一数据源)', async () => {
1207
+ // 症状:人设 tab 里切换了人设,**会话标题旁的标签仍显示旧人设**。
1208
+ //
1209
+ // 根因:header 标签自己 fetch,且 effect 依赖只有 [sessionId] ——
1210
+ // 切换人设不改变 sessionId ⇒ effect 不重跑 ⇒ 标签永远停在初始值。
1211
+ //
1212
+ // 修法:会话作用域进**全局 store**(sessionScopes[sessionId]),
1213
+ // saveSessionScope 成功后写入 ⇒ 标签与 tab 读同一份,一起刷新。
1214
+ const world = await boot()
1215
+ const zh = world.dicts.zh
1216
+ world.routes['/api/soul/personas'] = () => ({
1217
+ ok: true,
1218
+ personas: {
1219
+ 苏格拉底式提问者: { style: 'professional', builtin: true },
1220
+ 幽默风趣: { style: 'humorous', builtin: true }
1221
+ },
1222
+ activeName: null
1223
+ })
1224
+ await world.controller.loadPersonas()
1225
+
1226
+ let current = { style: 'professional' }
1227
+ // header 标签的兜底 fetch 走的是 /api/soul/session-scope/current
1228
+ // (输入框左侧那个开关才走 /api/soul/session-scope)。
1229
+ world.routes['/api/soul/session-scope/current'] = () => ({
1230
+ ok: true, sessionId: 'session-abc', workspaceId: null,
1231
+ override: null, source: 'global', activePersona: '苏格拉底式提问者'
1232
+ })
1233
+ world.routes['/api/soul/session-scope'] = (call) => {
1234
+ if (call.method === 'GET') {
1235
+ return {
1236
+ ok: true, sessionId: 'session-abc', workspaceId: null,
1237
+ override: null, source: 'global', activePersona: '苏格拉底式提问者'
1238
+ }
1239
+ }
1240
+ // POST:应用预设 ⇒ 返回新的解析结果
1241
+ const name = call.body.personaName || '苏格拉底式提问者'
1242
+ current = { style: name === '幽默风趣' ? 'humorous' : 'professional' }
1243
+ return {
1244
+ ok: true, sessionId: 'session-abc', workspaceId: null,
1245
+ override: current, source: 'session', activePersona: name
1246
+ }
1247
+ }
1248
+
1249
+ const labelSlot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.session.header.actions')
1250
+ const viewSlot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.view')
1251
+ assert.ok(labelSlot, '前置条件:header 标签槽位已注册')
1252
+ assert.ok(viewSlot, '前置条件:会话人设 tab 槽位已注册')
1253
+
1254
+ const store = world.controller.store
1255
+ // 必须**订阅** store(真实浏览器里 useSoulController 是订阅式 hook):
1256
+ // 用快照读取的话,store 变了也不会重渲染,测不到「切换后标签更新」。
1257
+ const useSoulController = (selector) => {
1258
+ const [, force] = world.runtime.React.useState(0)
1259
+ world.runtime.React.useEffect(() => store.subscribe(() => force((n) => n + 1)), [])
1260
+ return selector(store.getSnapshot())
1261
+ }
1262
+ const t2 = (k, p2) => {
1263
+ const raw = zh[k] ?? k
1264
+ return p2 ? raw.replace(/\{(\w+)\}/g, (m, n) => (p2[n] === undefined ? m : String(p2[n]))) : raw
1265
+ }
1266
+
1267
+ // 渲染 header 标签
1268
+ const labelProps = labelSlot.options.inject('session-abc')
1269
+ await world.runtime.settle({ type: labelSlot.component, props: { ...labelProps, useSoulController, t: t2 } })
1270
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
1271
+ let labelTree = await world.runtime.settle({ type: labelSlot.component, props: { ...labelProps, useSoulController, t: t2 } })
1272
+ const labelText = () => textOf(findAllByClass(labelTree, 'soul-session-persona-label')[0] || {})
1273
+ assert.ok(labelText().includes('苏格拉底式提问者'), `初始应显示「苏格拉底式提问者」,实际「${labelText()}」`)
1274
+
1275
+ // 在会话 tab 里点「用这个」切到「幽默风趣」
1276
+ const viewProps = viewSlot.options.inject('session-abc')
1277
+ await world.runtime.settle({ type: viewSlot.component, props: { ...viewProps, useSoulController, t: t2 } })
1278
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
1279
+ let viewTree = await world.runtime.settle({ type: viewSlot.component, props: { ...viewProps, useSoulController, t: t2 } })
1280
+ // 切换靠**轮播导航**(0.9.0-m 起卡不可点):点「下一个」按钮。
1281
+ // 桩里的预设顺序是 [苏格拉底式提问者, 幽默风趣] ⇒ 下一个就是「幽默风趣」。
1282
+ const nextBtn = findAllByClass(viewTree, 'soul-persona-navbtn')
1283
+ .find((b) => b.props['data-dir'] === 'next')
1284
+ assert.ok(nextBtn, '应有轮播的「下一个」按钮')
1285
+ await nextBtn.props.onClick()
1286
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
1287
+ viewTree = await world.runtime.settle({ type: viewSlot.component, props: { ...viewProps, useSoulController, t: t2 } })
1288
+ const detail = findAllByClass(viewTree, 'soul-session-detail')[0]
1289
+ assert.ok(detail, '会话 tab 应有右栏详情')
1290
+ assert.ok(
1291
+ textOf(findAllByClass(detail, 'soul-session-detail-name')[0] || {}).includes('幽默风趣'),
1292
+ '点「下一个」后,右栏应切换到「幽默风趣」'
1293
+ )
1294
+ const btn = findAllByClass(detail, 'soul-persona-action')[0]
1295
+ assert.ok(btn, '右栏应有操作按钮')
1296
+ await btn.props.onClick()
1297
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
1298
+
1299
+ // 重新渲染 header 标签 —— 它必须已经是新的人设
1300
+ await world.runtime.settle({ type: labelSlot.component, props: { ...labelProps, useSoulController, t: t2 } })
1301
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
1302
+ labelTree = await world.runtime.settle({ type: labelSlot.component, props: { ...labelProps, useSoulController, t: t2 } })
1303
+ const after = labelText()
1304
+ assert.ok(
1305
+ after.includes('幽默风趣'),
1306
+ `切换后 header 标签应显示「幽默风趣」,实际「${after}」`
1307
+ )
1308
+ assert.equal(
1309
+ after.includes('苏格拉底式提问者'),
1310
+ false,
1311
+ '切换后 header 标签不得还显示旧人设'
1312
+ )
1313
+ })
1314
+
1315
+ await check('C42 header 人设标签:会话状态读取失败时显示「未知」,不得退回全局值', async () => {
1316
+ // 失败路径同样不能骗人:若失败时静默退回全局值,用户看到的仍是
1317
+ // 「界面说 A、模型用 B」—— 正是这个标签最初要修的问题,失败路径不能把它带回来。
1318
+ const world = await boot()
1319
+ const zh = world.dicts.zh
1320
+ world.routes['/api/soul/session-scope/current'] = () => false
1321
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.session.header.actions')
1322
+ assert.ok(slot, '前置条件:conversation.input.left 已注册')
1323
+ const props = slot.options.inject('sess-1')
1324
+ const useSoulController = (selector) => selector(world.controller.store.getSnapshot())
1325
+ const t = (k) => zh[k] ?? k
1326
+ await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t } })
1327
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
1328
+ const tree = await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t } })
1329
+ const text = textOf(tree)
1330
+ assert.ok(
1331
+ text.includes(zh['quick.scopeUnknown']),
1332
+ `读取失败时应显示「${zh['quick.scopeUnknown']}」,实际「${text}」`
1333
+ )
1334
+ })
1335
+
1336
+ await check('C41 设置页人设预设行标注「全局」(它的「使用」写的是全局配置)', async () => {
1337
+ // 设置页的 settings.section 槽位拿不到 sessionId(宿主槽位契约决定的),
1338
+ // 所以这里的「使用」必然写**全局**配置。三级隔离下用户可能以为「在这里点了使用
1339
+ // = 只影响这个项目」—— 那是会话/工作区层的事。标出来避免误解。
1340
+ const world = await boot()
1341
+ const zh = world.dicts.zh
1342
+ // 人设分组默认折叠,body 不渲染 ⇒ 必须像用户一样展开才能看到卡
1343
+ const closed = await renderSettings(world)
1344
+ const trigger = findAll(closed, (n) => n.type === 'button' && textOf(n).includes(zh['group.personas']))[0]
1345
+ assert.ok(trigger, '前置条件:应存在「人设预设」分组')
1346
+ await trigger.props.onClick()
1347
+ const tree = await renderSettingsSettled(world)
1348
+ const tags = findAllByClass(tree, 'soul-persona-scope-tag')
1349
+ assert.ok(tags.length > 0, '设置页人设卡上应有作用域标注')
1350
+ for (const tag of tags) {
1351
+ assert.equal(textOf(tag), zh['personas.scopeGlobal'], `作用域标注应为「${zh['personas.scopeGlobal']}」,实际「${textOf(tag)}」`)
1352
+ }
1353
+ })
1354
+
617
1355
  await check('C14 预设列表拉取失败时显示失败原因,不得永远停在「加载中...」', async () => {
618
1356
  const world = await boot()
619
1357
  world.routes['/api/soul/personas'] = () => false
@@ -1033,8 +1771,8 @@ await check('C23 全局轮询注册在装配层(底栏不依赖设置页是否
1033
1771
  )
1034
1772
  })
1035
1773
 
1036
- await check('C21 底栏展示当前人设,未匹配时显示「自定义」', async () => {
1037
- // 需求:底栏「个性化已启用」后必须回答「现在用的是哪套人设」。
1774
+ await check('C21 header 人设标签展示当前人设,未匹配时显示「自定义」', async () => {
1775
+ // 需求:会话 header 必须回答「现在用的是哪套人设」(0.9.0-h 起该标签在 header)。
1038
1776
  // 此前只有匹配到预设才缀名字,手改过特质后留空 —— 等于没回答。
1039
1777
  // 现在:匹配到预设显示预设名,否则显示「自定义」。
1040
1778
  const personaLib = (activeName) => ({
@@ -1051,12 +1789,18 @@ await check('C21 底栏展示当前人设,未匹配时显示「自定义」',
1051
1789
 
1052
1790
  // ① 匹配到预设 ⇒ 缀预设名
1053
1791
  const w1 = await boot({}, personaLib('苏格拉底式提问者'))
1792
+ // 会话作用域端点:没有会话覆盖 ⇒ source 'global',人设名取全局匹配结果。
1793
+ // 不 mock 的话请求失败 ⇒ 标签显示「会话状态未知」,把断言冲掉。
1794
+ w1.routes['/api/soul/session-scope/current'] = () => ({
1795
+ ok: true, sessionId: 'session-abc', workspaceId: null, override: null,
1796
+ source: 'global', activePersona: '苏格拉底式提问者', globalPersona: '苏格拉底式提问者'
1797
+ })
1054
1798
  // 人设列表由**设置页组件挂载后的 refresh** 拉取(apply 阶段只拉 config)。
1055
1799
  // 快捷开关单独渲染不会触发它 —— 先渲染一次设置页把人设灌进 store,
1056
1800
  // 否则下面读到的 activePersona 恒为 null(此前踩过:断言读到「自定义」)。
1057
1801
  await renderSettings(w1)
1058
- const btn1 = await w1.runtime.settle(quickToggleElement(w1))
1059
- const name1 = findAll(btn1, (n) => typeof n.props?.className === 'string' && String(n.props.className).includes('soul-quick-toggle-name'))
1802
+ const btn1 = await w1.runtime.settle(personaLabelElement(w1))
1803
+ const name1 = findAll(btn1, (n) => typeof n.props?.className === 'string' && String(n.props.className).includes('soul-session-persona-label-name'))
1060
1804
  assert.equal(name1.length, 1, `启用时应有一个人设名节点,实际 ${name1.length}`)
1061
1805
  assert.ok(
1062
1806
  textOf(name1[0]).includes('苏格拉底式提问者'),
@@ -1065,9 +1809,13 @@ await check('C21 底栏展示当前人设,未匹配时显示「自定义」',
1065
1809
 
1066
1810
  // ② 未匹配(手改过特质)⇒ 显示「自定义」,不能留空
1067
1811
  const w2 = await boot({}, personaLib(null))
1812
+ w2.routes['/api/soul/session-scope/current'] = () => ({
1813
+ ok: true, sessionId: 'session-abc', workspaceId: null, override: null,
1814
+ source: 'global', activePersona: null, globalPersona: null
1815
+ })
1068
1816
  await renderSettings(w2)
1069
- const btn2 = await w2.runtime.settle(quickToggleElement(w2))
1070
- const name2 = findAll(btn2, (n) => typeof n.props?.className === 'string' && String(n.props.className).includes('soul-quick-toggle-name'))
1817
+ const btn2 = await w2.runtime.settle(personaLabelElement(w2))
1818
+ const name2 = findAll(btn2, (n) => typeof n.props?.className === 'string' && String(n.props.className).includes('soul-session-persona-label-name'))
1071
1819
  assert.equal(name2.length, 1, '未匹配时也应有人设名节点(回退为「自定义」)')
1072
1820
  assert.ok(
1073
1821
  textOf(name2[0]).includes(w2.dicts.zh['quick.custom']),
@@ -1310,10 +2058,1455 @@ await check('C20 点叠层侧边卡只翻页、不翻面(整面点击必须限
1310
2058
  await world.controller.usePersona('任意')
1311
2059
  assert.equal(world.controller.store.getSnapshot().error, null, '应用预设成功后不得残留上一轮的失败提示')
1312
2060
  })
2061
+
2062
+ // ==================== 插件详情页「变更记录」区块(0.8.1 双入口)====================
2063
+ //
2064
+ // 0.8.1 起变更记录的主入口是宿主插件详情页(plugins.detail.section 槽位),
2065
+ // 设置页只留一行指引。渲染组件是 SoulHistorySection,判据是
2066
+ // subject.kind === 'bundle' && subject.pkg.name === 'dsh-soul'——
2067
+ // 所以这里的渲染语境是「详情页」:挂载即拉取(不再有「展开才拉」),
2068
+ // subject 不是 dsh-soul 时必须渲染 null(槽位契约原话)。
2069
+
2070
+ /** 详情页槽位(plugins.detail.section)与它的渲染辅助。 */
2071
+ function detailSectionOf(world) {
2072
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'plugins.detail.section')
2073
+ assert.ok(slot, '未注册 plugins.detail.section 槽位')
2074
+ assert.equal(slot.options.id, 'soul-detail-history', '详情页区块的 id 必须是 soul-detail-history')
2075
+ return slot
2076
+ }
2077
+ /** 渲染详情页区块。subject 模拟宿主 PackageDetail 的 bundle 形态(packageRef);
2078
+ * subject 缺省才补默认值 —— 显式传 null 必须原样传入(判据要吃得到)。 */
2079
+ async function renderDetail(world, subject) {
2080
+ const slot = detailSectionOf(world)
2081
+ const props = slot.options.inject()
2082
+ const store = props.hooks.soulController
2083
+ const useSoulController = (selector) => {
2084
+ const [, force] = world.runtime.React.useState(0)
2085
+ world.runtime.React.useEffect(() => store.subscribe(() => force((n) => n + 1)), [])
2086
+ return selector(store.getSnapshot())
2087
+ }
2088
+ const pkg = subject === undefined
2089
+ ? { kind: 'bundle', pkg: { name: 'dsh-soul', installed: true, enabled: true, rows: [] } }
2090
+ : subject
2091
+ return world.runtime.settle({
2092
+ type: slot.component,
2093
+ props: { ...props, useSoulController, t: (key, params) => interpolate((world.dicts?.zh || {})[key] ?? key, params), subject: pkg }
2094
+ })
2095
+ }
2096
+ /** 渲染 + 排空异步(挂载拉取与随后的 setState 都要跑完)。 */
2097
+ async function renderDetailSettled(world, subject) {
2098
+ await renderDetail(world, subject)
2099
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
2100
+ return await renderDetail(world, subject)
2101
+ }
2102
+
2103
+ /** 造一条服务端形状的变更记录(before/after 只装变化字段,personas 恒三段)。 */
2104
+ function historyEntry(over) {
2105
+ return {
2106
+ v: 1,
2107
+ id: 'e-0',
2108
+ at: new Date().toISOString(),
2109
+ source: 'web',
2110
+ action: 'save',
2111
+ configHash: 'h',
2112
+ before: {},
2113
+ after: {},
2114
+ personas: { added: [], updated: [], removed: [] },
2115
+ ...over
2116
+ }
2117
+ }
2118
+ /** 唯一的成功绿字(`.soul-saved-notice`)的文案。 */
2119
+ function savedNoticeOf(tree) {
2120
+ const hits = findAllByClass(tree, 'soul-saved-notice')
2121
+ assert.equal(hits.length, 1, `期望恰好一条成功提示,实际 ${hits.length} 条`)
2122
+ return textOf(hits[0])
2123
+ }
2124
+
2125
+ await check('C24 变更记录详情页:subject 判据、挂载即拉取、按记录渲染时间/来源/字段', async () => {
2126
+ const entries = [
2127
+ historyEntry({
2128
+ id: 'aaa-1',
2129
+ at: new Date(Date.now() - 90 * 1000).toISOString(),
2130
+ before: { bio: '旧介绍', style: 'professional' },
2131
+ after: { bio: '', style: 'humorous' }
2132
+ }),
2133
+ historyEntry({
2134
+ id: 'bbb-2',
2135
+ at: new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString(),
2136
+ source: 'command',
2137
+ action: 'set',
2138
+ personas: { added: ['头脑风暴伙伴'], updated: [], removed: [{ name: '极简主义者', entry: { style: 'efficient' } }] }
2139
+ }),
2140
+ // 刻意给一条「未来」的记录:服务端时钟略快或本机时钟回拨时真的会出现。
2141
+ // 时间差算出来是负数,显示「-1 分钟前」会让人以为记录坏了。
2142
+ historyEntry({
2143
+ id: 'ccc-3',
2144
+ at: new Date(Date.now() + 30 * 1000).toISOString(),
2145
+ source: 'persona',
2146
+ action: 'use',
2147
+ label: '苏格拉底式提问者',
2148
+ before: { style: 'professional' },
2149
+ after: { style: 'casual' }
2150
+ })
2151
+ ]
2152
+ const world = await boot()
2153
+ const calls = []
2154
+ world.routes['/api/soul/history'] = (call) => {
2155
+ calls.push(call)
2156
+ // 上限刻意不取 200:写死数字的实现在这条断言下会立刻露馅。
2157
+ // (「最多保留 200 条」是一句会被人当真的承诺,客户端只能转述服务端说的话。)
2158
+ return { ok: true, entries, max: 50, warning: null }
2159
+ }
2160
+ const zh = world.dicts.zh
2161
+
2162
+ // ① subject 判据:别的插件详情页 / 非 bundle 形态必须渲染 null(槽位契约)
2163
+ for (const bad of [
2164
+ null,
2165
+ { kind: 'item', pkg: { name: 'dsh-soul' } },
2166
+ { kind: 'row', pkg: { name: 'dsh-soul' } },
2167
+ { kind: 'bundle', pkg: { name: 'dsh-other-plugin' } }
2168
+ ]) {
2169
+ const tree = await renderDetail(world, bad)
2170
+ assert.equal(findAllByClass(tree, 'soul-detail-history').length, 0,
2171
+ `subject=${JSON.stringify(bad)} 不得渲染变更记录区块`)
2172
+ }
2173
+ assert.equal(calls.length, 0, '未渲染自己详情页时不得请求 /api/soul/history')
2174
+
2175
+ // ② 挂载 ⇒ 立即以 GET 拉取(详情页本来就是「专门来看记录」才打开的页面)
2176
+ const tree = await renderDetailSettled(world)
2177
+ assert.equal(calls.length, 1, '挂载详情页区块应恰好拉取一次')
2178
+ assert.equal(calls[0].method, 'GET', '拉取变更记录必须用 GET')
2179
+ assert.equal(calls[0].path, '/api/soul/history', '拉取路径必须是 /api/soul/history')
2180
+
2181
+ // ③ 顶部计数:上限由服务端带回,客户端不写死
2182
+ assert.equal(textOf(findAllByClass(tree, 'soul-detail-history-count')[0]),
2183
+ zh['history.summary'].replace('{count}', '3').replace('{max}', '50'),
2184
+ '计数行必须用服务端带回的条数与条数上限')
2185
+
2186
+ // ④ 每条行摘要:相对时间 · 来源 · 涉及字段(字段名复用设置页既有文案)
2187
+ const items = findAllByClass(tree, 'soul-history-item')
2188
+ assert.equal(items.length, 3, `应渲染 3 条记录,实际 ${items.length}`)
2189
+ assert.equal(textOf(findAllByClass(items[0], 'soul-history-time')[0]), '1 分钟前')
2190
+ assert.equal(textOf(findAllByClass(items[0], 'soul-history-source')[0]), zh['history.source.web'])
2191
+ assert.equal(textOf(findAllByClass(items[0], 'soul-history-fields')[0]),
2192
+ zh['history.fields'].replace('{fields}', `${zh['field.bio']}、${zh['field.style']}`))
2193
+ assert.equal(items[0].props['data-source'], 'web', '行上带来源标识,供按来源取样式')
2194
+ assert.equal(textOf(findAllByClass(items[1], 'soul-history-time')[0]), '3 小时前')
2195
+ assert.equal(textOf(findAllByClass(items[1], 'soul-history-fields')[0]),
2196
+ zh['history.fields'].replace('{fields}',
2197
+ `${zh['history.personasAdded'].replace('{names}', '头脑风暴伙伴')}、${zh['history.personasRemoved'].replace('{names}', '极简主义者')}`),
2198
+ '只有预设事件的记录也得有一句「涉及 …」,否则末尾悬着一个空壳')
2199
+ assert.equal(textOf(findAllByClass(items[2], 'soul-history-time')[0]), zh['history.timeJustNow'],
2200
+ '时间差为负(时钟回拨/服务端稍快)必须归入「刚刚」,不能显示「-1 分钟前」')
2201
+ // ④b label(预设名)必须出现在折叠摘要里 —— 不然「应用预设 · 风格」答不了「应用的是什么」;
2202
+ // 且拼在字段列表**之前**(先说什么预设,再说动了哪些字段,阅读顺序和提问顺序一致)。
2203
+ assert.equal(textOf(findAllByClass(items[2], 'soul-history-fields')[0]),
2204
+ zh['history.fields'].replace('{fields}',
2205
+ `${zh['history.labelSuffix'].replace('{label}', '苏格拉底式提问者')}、${zh['field.style']}`),
2206
+ '应用预设的记录必须在摘要里带预设名')
2207
+
2208
+ // ⑤ 拉取失败必须留下痕迹:否则永远停在「加载中」,与「真的没有记录」无从区分
2209
+ const bad = await boot()
2210
+ bad.routes['/api/soul/history'] = () => false
2211
+ const badTree = await renderDetailSettled(bad)
2212
+ const badErrors = findAllByClass(badTree, 'soul-error').map(textOf)
2213
+ assert.equal(badErrors.length, 1, `拉取失败应在这个区块里显示一条错误,实际 ${badErrors.length} 条`)
2214
+ assert.equal(badErrors[0], bad.dicts.zh['history.loadFailed'].replace('{reason}', 'boom'))
2215
+ // 计数行也得交代状态:失败时不能还挂着「最近 N 条」装作一切正常
2216
+ assert.equal(textOf(findAllByClass(badTree, 'soul-detail-history-count')[0]),
2217
+ bad.dicts.zh['accordion.loadFailed'], '失败时计数行必须显示「加载失败」')
2218
+ })
2219
+
2220
+ await check('C25 变更记录展开:原值→新值、空值占位、预设事件与恢复入口', async () => {
2221
+ const entries = [
2222
+ historyEntry({
2223
+ id: 'ct-1',
2224
+ at: new Date(Date.now() - 30 * 1000).toISOString(),
2225
+ // 刻意凑齐五种取值形态:枚举(要查词典)、被清空的文本(要显示「(空)」)、
2226
+ // 布尔(要显示「已开启/未开启」而不是 true/false)、**只出现在 before 里的键**
2227
+ //(「字段被删掉」的唯一表达方式,只遍历 after 的实现会把它整行漏掉 ——
2228
+ // 而漏掉的那一行恰是「谁把我的职业删了」),以及**枚举外的取值**。
2229
+ // 最后这种:配置文件被手工改坏时真的会出现(`trailSpeed: 'turbo'`),
2230
+ // 必须原样显示 —— 若不加 HISTORY_ENUM_VALUES 白名单就直接查词典,
2231
+ // `t('trail.speed.turbo')` 会渲染成裸键名,比显示原始值更难懂。
2232
+ before: { bio: '旧介绍', style: 'professional', requireToolConfirmation: false, occupation: '工程师', trailSpeed: 'slow' },
2233
+ after: { bio: '', style: 'humorous', requireToolConfirmation: true, trailSpeed: 'turbo' }
2234
+ }),
2235
+ historyEntry({
2236
+ id: 'ct-2',
2237
+ at: new Date(Date.now() - 30 * 1000).toISOString(),
2238
+ source: 'command',
2239
+ action: 'deletePreset',
2240
+ personas: { added: [], updated: [], removed: [{ name: '极简主义者', entry: { style: 'efficient' } }] }
2241
+ })
2242
+ ]
2243
+ const world = await boot()
2244
+ world.routes['/api/soul/history'] = () => ({ ok: true, entries, max: 200, warning: null })
2245
+ const zh = world.dicts.zh
2246
+ let tree = await renderDetailSettled(world)
2247
+
2248
+ // ① 默认不收开任何一行:20 条全铺开会比详情页还长
2249
+ assert.equal(findAllByClass(tree, 'soul-history-detail').length, 0, '默认不得展开任何一条记录')
2250
+ // ② 「恢复此预设」只给删过预设的那条 —— 别的记录点它无事可做
2251
+ const restoreButtons = findAllByClass(tree, 'soul-history-action')
2252
+ .filter((n) => textOf(n) === zh['history.restorePreset'])
2253
+ assert.equal(restoreButtons.length, 1, `「恢复此预设」应只出现在删过预设的记录上,实际 ${restoreButtons.length} 个`)
2254
+
2255
+ // ③ 展开第一条 ⇒ 逐字段「原值 → 新值」
2256
+ const mainOf = (index) => {
2257
+ const items = findAllByClass(tree, 'soul-history-item')
2258
+ const hit = findAllByClass(items[index], 'soul-history-item-main')
2259
+ assert.equal(hit.length, 1, '每条记录应恰好一个可展开主体')
2260
+ return hit[0]
2261
+ }
2262
+ await mainOf(0).props.onClick()
2263
+ tree = await renderDetail(world)
2264
+ const rows = findAllByClass(tree, 'soul-history-diff-row')
2265
+ assert.equal(rows.length, 5, `第一条应展开出 5 个字段,实际 ${rows.length}`)
2266
+ const rowOf = (label) => {
2267
+ const hit = rows.filter((r) => textOf(findAllByClass(r, 'soul-history-diff-field')[0]) === label)
2268
+ assert.equal(hit.length, 1, `应恰好一行「${label}」`)
2269
+ return hit[0]
2270
+ }
2271
+ const styleRow = rowOf(zh['field.style'])
2272
+ // 「展开即全文」:值放在 .soul-history-diff-value 里,块前有 .soul-history-diff-tag 标「原值/新值」
2273
+ const cellOf = (row, side) => {
2274
+ const cells = findAllByClass(row, 'soul-history-diff-cell')
2275
+ assert.equal(cells.length, side === 'from' ? 2 : 2, `展开行应有两块(原值/新值),实际 ${cells.length}`)
2276
+ const index = side === 'from' ? 0 : 1
2277
+ assert.equal(textOf(findAllByClass(cells[index], 'soul-history-diff-tag')[0]),
2278
+ zh[side === 'from' ? 'history.field.from' : 'history.field.to'],
2279
+ `值块前必须有「${side === 'from' ? '原值' : '新值'}」标签 —— 光靠位置分不清哪边是原值`)
2280
+ return findAllByClass(cells[index], 'soul-history-diff-value')[0]
2281
+ }
2282
+ assert.equal(textOf(cellOf(styleRow, 'from')), zh['style.professional'])
2283
+ assert.equal(textOf(cellOf(styleRow, 'to')), zh['style.humorous'])
2284
+ const bioRow = rowOf(zh['field.bio'])
2285
+ assert.equal(textOf(cellOf(bioRow, 'from')), '旧介绍')
2286
+ assert.equal(textOf(cellOf(bioRow, 'to')), zh['history.valueEmpty'],
2287
+ '被清空的字段必须显示「(空)」而不是留白 —— 留白会被读成渲染坏了')
2288
+ // ④ 布尔字段画的是「已开启/未开启」,不是 true/false
2289
+ const toolRow = rowOf(zh['field.toolConfirm'])
2290
+ assert.equal(textOf(cellOf(toolRow, 'from')), zh['accordion.off'])
2291
+ assert.equal(textOf(cellOf(toolRow, 'to')), zh['accordion.on'])
2292
+ // ⑤ 只出现在 before 里的键(字段被删掉)也必须占一行,新值那侧显示「(空)」
2293
+ const occRow = rowOf(zh['field.occupation'])
2294
+ assert.equal(textOf(cellOf(occRow, 'from')), '工程师')
2295
+ assert.equal(textOf(cellOf(occRow, 'to')), zh['history.valueEmpty'],
2296
+ '只在 before 里出现的字段必须照常占一行 —— 否则「谁把我这一项删了」就永远查不到')
2297
+ // ⑦ 枚举外的取值原样显示(查词典前必须先过取值白名单)
2298
+ const speedRow = rowOf(zh['trail.speed'])
2299
+ assert.equal(textOf(cellOf(speedRow, 'from')), zh['trail.speed.slow'])
2300
+ assert.equal(textOf(cellOf(speedRow, 'to')), 'turbo',
2301
+ '枚举外的取值必须原样显示 —— 直接查词典会渲染成裸键名 `trail.speed.turbo`')
2302
+
2303
+ // ⑧ 展开第二条:预设事件单独成行,并**取代**第一条的展开(同时只展开一行)
2304
+ await mainOf(1).props.onClick()
2305
+ tree = await renderDetail(world)
2306
+ const personaLines = findAllByClass(tree, 'soul-history-diff-persona').map(textOf)
2307
+ assert.ok(personaLines.includes(zh['history.personasRemoved'].replace('{names}', '极简主义者')),
2308
+ `应有一行「删除预设 极简主义者」,实际 ${JSON.stringify(personaLines)}`)
2309
+ assert.equal(findAllByClass(tree, 'soul-history-diff-row').length, 0,
2310
+ '展开第二条时第一条必须收起 —— 同时摊开多行会让区块长度不可控')
2311
+ // ⑨ 再点一次收起
2312
+ await mainOf(1).props.onClick()
2313
+ tree = await renderDetail(world)
2314
+ assert.equal(findAllByClass(tree, 'soul-history-detail').length, 0, '点第二次应收起')
2315
+ })
2316
+
2317
+ await check('C26 变更记录:撤销与清空都要过内联二次确认(不用原生 confirm)', async () => {
2318
+ const entries = [historyEntry({
2319
+ id: 'u-1',
2320
+ at: new Date().toISOString(),
2321
+ before: { style: 'professional' },
2322
+ after: { style: 'casual' }
2323
+ })]
2324
+ const world = await boot()
2325
+ const rollbacks = []
2326
+ const clears = []
2327
+ world.routes['/api/soul/history'] = () => ({ ok: true, entries, max: 200, warning: null })
2328
+ world.routes['/api/soul/history/rollback'] = (call) => {
2329
+ rollbacks.push(call.body)
2330
+ return {
2331
+ ok: true,
2332
+ config: { ...CONFIG },
2333
+ changed: ['style'],
2334
+ skipped: [],
2335
+ reversed: ['u-1'],
2336
+ unchanged: false,
2337
+ entry: null,
2338
+ deliveryWarning: null
2339
+ }
2340
+ }
2341
+ world.routes['/api/soul/history/clear'] = () => { clears.push(true); return { ok: true, removed: 1 } }
2342
+ const zh = world.dicts.zh
2343
+ let tree = await renderDetailSettled(world)
2344
+
2345
+ // ① 撤销:第一次点只进入待确认,一个请求都不发
2346
+ const undoBtn = () => findAllByClass(tree, 'soul-history-action')[0]
2347
+ assert.equal(textOf(undoBtn()), zh['history.restore'])
2348
+ await undoBtn().props.onClick()
2349
+ tree = await renderDetail(world)
2350
+ assert.equal(textOf(undoBtn()), zh['history.restoreArmed'], '第一次点后按钮应变成「撤销?」')
2351
+ assert.equal(rollbacks.length, 0, '第一次点「撤销这一次」不得直接发请求')
2352
+ // ② 第二次点才真的撤销
2353
+ await undoBtn().props.onClick()
2354
+ tree = await renderDetailSettled(world)
2355
+ assert.equal(rollbacks.length, 1, '第二次点「撤销?」才发请求')
2356
+ assert.equal(rollbacks[0].id, 'u-1', '撤销必须带上这一条的 id')
2357
+ assert.equal(savedNoticeOf(tree), zh['history.restoreDone'].replace('{count}', '1'))
2358
+
2359
+ // ③ 清空:同样的两步。它是这个区块唯一的危险色按钮(不可逆)
2360
+ const clearBtn = () => findAllByClass(tree, 'soul-history-clear')[0]
2361
+ assert.equal(textOf(clearBtn()), zh['history.clear'])
2362
+ await clearBtn().props.onClick()
2363
+ tree = await renderDetail(world)
2364
+ assert.equal(textOf(clearBtn()), zh['history.clearArmed'], '第一次点后按钮应变成「确认清空?」')
2365
+ assert.equal(clears.length, 0, '第一次点「清空记录」不得直接发请求')
2366
+ await clearBtn().props.onClick()
2367
+ tree = await renderDetailSettled(world)
2368
+ assert.equal(clears.length, 1, '第二次点「确认清空?」才发请求')
2369
+ assert.equal(savedNoticeOf(tree), zh['history.clearDone'].replace('{count}', '1'))
2370
+ })
2371
+
2372
+ await check('C27 变更记录:超过 20 条改为分页,warning 不得被当成失败', async () => {
2373
+ const many = Array.from({ length: 22 }, (_, i) => historyEntry({
2374
+ id: `m-${String(i).padStart(2, '0')}`,
2375
+ at: new Date(Date.now() - (i + 1) * 60 * 1000).toISOString(),
2376
+ before: { style: 'professional' },
2377
+ after: { style: 'humorous' }
2378
+ }))
2379
+ const world = await boot()
2380
+ world.routes['/api/soul/history'] = () => ({
2381
+ ok: true,
2382
+ entries: many,
2383
+ max: 200,
2384
+ warning: '记录文件较大,只读取了最近的部分。'
2385
+ })
2386
+ const zh = world.dicts.zh
2387
+ let tree = await renderDetailSettled(world)
2388
+
2389
+ // ① 一页 20 条:一条一条铺开会让这个区块比详情页还长
2390
+ assert.equal(findAllByClass(tree, 'soul-history-item').length, 20, '第一页只渲染 20 条')
2391
+ // ② 多于一页时必须给出分页器(而不是「还有 N 条 → 全部摊开」)
2392
+ const pagerOf = (root) => {
2393
+ const boxes = findAllByClass(root, 'soul-history-pager')
2394
+ assert.equal(boxes.length, 1, '多于一页时应出现分页器')
2395
+ return findAll(boxes[0], (n) => n.type === 'ui-button')
2396
+ }
2397
+ let pageButtons = pagerOf(tree)
2398
+ assert.equal(pageButtons.length, 2, '分页器应有「上一页」「下一页」两个按钮')
2399
+ assert.equal(pageButtons[0].props.disabled, true, '第一页时「上一页」必须禁用')
2400
+ assert.equal(pageButtons[1].props.disabled, false, '第一页时「下一页」可点')
2401
+ const pageInfo = findAllByClass(tree, 'soul-history-pageinfo')[0]
2402
+ assert.equal(
2403
+ textOf(pageInfo),
2404
+ zh['history.pageInfo'].replace('{page}', '1').replace('{total}', '2').replace('{count}', '22'),
2405
+ '页码文案应写清「第 1 / 2 页 · 共 22 条」'
2406
+ )
2407
+
2408
+ // ③ 翻到第二页:只剩 2 条,「下一页」禁用
2409
+ await pageButtons[1].props.onClick()
2410
+ tree = await renderDetail(world)
2411
+ assert.equal(findAllByClass(tree, 'soul-history-item').length, 2, '第二页应只剩 2 条')
2412
+ pageButtons = pagerOf(tree)
2413
+ assert.equal(pageButtons[0].props.disabled, false, '第二页时「上一页」可点')
2414
+ assert.equal(pageButtons[1].props.disabled, true, '最后一页时「下一页」必须禁用')
2415
+
2416
+ // ④ 回到第一页:恢复 20 条
2417
+ await pageButtons[0].props.onClick()
2418
+ tree = await renderDetail(world)
2419
+ assert.equal(findAllByClass(tree, 'soul-history-item').length, 20, '回到第一页应恢复 20 条')
2420
+
2421
+ // ③ warning 是「看到的不是全部」,不是失败:留在区块内、且不能染红
2422
+ const warn = findAllByClass(tree, 'soul-history-warning')
2423
+ assert.equal(warn.length, 1, 'warning 应留在这个区块内提示')
2424
+ assert.equal(textOf(warn[0]), zh['history.warning'].replace('{reason}', '记录文件较大,只读取了最近的部分。'))
2425
+ assert.ok(String(warn[0].props.className).includes('soul-status'), 'warning 用普通提示样式,不是 .soul-error')
2426
+ assert.equal(findAllByClass(tree, 'soul-error').length, 0, 'warning 不得被当成错误')
2427
+ })
2428
+
2429
+ await check('C28 设置页指引:一条轻提示 + 问号里的全文,不再铺两行正文', async () => { const world = await boot()
2430
+ world.routes['/api/soul/history'] = () => ({ ok: true, entries: [historyEntry({ id: 'a' })], max: 200, warning: null })
2431
+ const zh = world.dicts.zh
2432
+
2433
+ // ① 折叠态:变更记录不该在设置页有独立分组,也不该出现在折叠标题旁。
2434
+ const closed = await renderSettings(world)
2435
+ // 判据用 accordion **标题 span** 而不是整个 accordion 文本:指引文案里就有
2436
+ //「变更记录」四个字,整树文本匹配会被自己误伤(首轮假红就是这么来的)。
2437
+ const closedTitles = findAllByClass(closed, 'soul-accordion-title')
2438
+ assert.equal(closedTitles.some((n) => textOf(n) === zh['group.history']), false,
2439
+ '设置页不得再保留「变更记录」手风琴分组')
2440
+ assert.equal(findAllByClass(closed, 'soul-history-entry').length, 0, '设置页不得再保留独立指引行(.soul-history-entry)')
2441
+ assert.equal(findAllByClass(closed, 'soul-accordion-head').length, 0,
2442
+ '折叠标题旁的 head 层应已删除(说明改放展开区内)')
2443
+ assert.equal(textOf(closed).includes(zh['history.entryHint']), false,
2444
+ '折叠态不该出现变更记录指引 —— 它解释的是展开后的东西')
2445
+
2446
+ // ② 展开「人设预设」:两条说明各自一行,正文只有一句话,细节在问号里。
2447
+ const triggers = findAll(closed, (n) => n.type === 'button' && textOf(n).includes(zh['group.personas']))
2448
+ assert.ok(triggers.length > 0, '应存在「人设预设」分组标题(前置条件)')
2449
+ await triggers[0].props.onClick()
2450
+ const tree = await renderSettings(world)
2451
+
2452
+ const notes = findAllByClass(tree, 'soul-note-inline')
2453
+ assert.equal(notes.length, 2, `应有两行轻提示(预设范围 + 变更记录去向),实际 ${notes.length}`)
2454
+ // 每行都是「一句话 + 一个问号」,正文走 .soul-note-text
2455
+ const texts = notes.map((n) => textOf(findAllByClass(n, 'soul-note-text')[0]))
2456
+ assert.deepEqual(texts, [zh['personas.hint'], zh['history.entryHint']],
2457
+ `两行正文应分别是两条短文案,实际 ${JSON.stringify(texts)}`)
2458
+
2459
+ // ③ 关键:正文**不得**再穷举清单 —— 那些名词在卡片和按钮上本来就看得到。
2460
+ // 细节只能出现在问号的 tooltip 里(.soul-hint-tip),不能混进正文。
2461
+ for (const key of ['personas.hint', 'history.entryHint']) {
2462
+ assert.ok(zh[key].length <= 40, `${key} 应是短句(≤40 字),实际 ${zh[key].length} 字:${zh[key]}`)
2463
+ }
2464
+ const tips = findAllByClass(tree, 'soul-hint-tip').map((n) => textOf(n))
2465
+ assert.ok(tips.includes(zh['personas.hintDetail']), '预设的完整说明应在问号 tooltip 里')
2466
+ assert.ok(tips.includes(zh['history.entryHintMore']), '变更记录的去向全文应在问号 tooltip 里')
2467
+ // 反向:tooltip 的细节文字绝不能漏进正文(那等于没瘦身)
2468
+ const bodyText = texts.join('')
2469
+ for (const detailKey of ['personas.hintDetail', 'history.entryHintMore']) {
2470
+ assert.equal(bodyText.includes(zh[detailKey]), false, `正文不得混入 ${detailKey} 的全文`)
2471
+ }
2472
+ // ④ 说明是正文,不是按钮内容:绝不能嵌进 trigger(button 内不允许嵌可聚焦元素)
2473
+ const openTriggers = findAllByClass(tree, 'soul-accordion-trigger')
2474
+ assert.equal(openTriggers.some((n) => textOf(n).includes(zh['history.entryHint'])), false,
2475
+ '指引不得嵌进 trigger 按钮')
2476
+ // ⑤ 其余分组的展开区不得误挂说明(说明块是 personas 专属)
2477
+ const bodies = findAllByClass(tree, 'soul-accordion-body')
2478
+ const others = bodies.filter((n) => textOf(n) !== textOf(notes[0].parent) && !(n.children || []).includes(notes[0]))
2479
+ assert.equal(others.some((n) => findAllByClass(n, 'soul-note').length > 0), false,
2480
+ '只有人设预设分组挂说明块,其他分组不得误挂')
2481
+ })
2482
+
2483
+ await check('C35 0.8.0 起设置页不得再出现「工作区绑定」分组(逻辑层保留,UI 撤下)', async () => {
2484
+ const world = await boot()
2485
+ // 绑定接口给它一条数据:如果分组被误加回来,展开后一定能看到这条 ——
2486
+ // 用空数据测不出问题(空态与「分组不存在」在文本上都可能什么都不显示)。
2487
+ world.routes['/api/soul/bindings'] = () => ({
2488
+ ok: true,
2489
+ bindings: { 'D:\\项目A': '苏格拉底式提问者' },
2490
+ invalid: [], dropped: 0, warning: null, max: 50, maxPathLength: 260, sessions: []
2491
+ })
2492
+ const zh = world.dicts.zh
2493
+
2494
+ // ① 逐个分组展开,任何一组里都不得出现这个手风琴(连同它的标题与主体)
2495
+ let tree = await renderSettings(world)
2496
+ for (const groupKey of ['about', 'traits', 'personas', 'tool']) {
2497
+ const titleKey = { about: 'group.aboutYou', traits: 'group.traits', personas: 'group.personas', tool: 'group.tool' }[groupKey]
2498
+ const btn = findAll(tree, (n) => n.type === 'button' && textOf(n).includes(zh[titleKey]))[0]
2499
+ assert.ok(btn, `前置条件:应存在「${zh[titleKey]}」分组`)
2500
+ await btn.props.onClick()
2501
+ tree = await renderSettingsSettled(world)
2502
+ // 判据一:折叠标题里不得有这一项
2503
+ assert.equal(
2504
+ findAllByClass(tree, 'soul-accordion-title').some((n) => textOf(n) === zh['group.bindings']),
2505
+ false,
2506
+ `展开「${zh[titleKey]}」后不得出现「工作区绑定」分组标题`
2507
+ )
2508
+ // 判据二:主体(那个会渲染绑定表的组件)不得被挂载
2509
+ assert.equal(findAllByClass(tree, 'soul-bindings').length, 0,
2510
+ `展开「${zh[titleKey]}」后不得渲染绑定主体(.soul-bindings)`)
2511
+ }
2512
+ // ② 折叠态整树文本里也不该出现它的说明文案
2513
+ assert.equal(textOf(tree).includes(zh['bindings.hint']), false,
2514
+ '设置页不得出现工作区绑定的说明文案')
2515
+ })
2516
+
2517
+ await check('C36 会话「人设」tab:常驻注册、拿到 sessionId、按来源显示生效人设', async () => {
2518
+ const world = await boot()
2519
+ const zh = world.dicts.zh
2520
+
2521
+ // ① 槽位:注册到 conversation.view(列表槽位),且 inject 必须把 sessionId 传下去。
2522
+ // 这是插件拿到「当前会话 id」的唯一正规入口 —— 设置页的 slotInject 是空串。
2523
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.view')
2524
+ assert.ok(slot, '必须注册到 conversation.view 槽位(否则会话里没有「人设」tab)')
2525
+ assert.equal(slot.options.id, 'soul-persona')
2526
+ assert.equal(typeof slot.options.label, 'function', 'label 必须是函数(语言切换时需重新解析)')
2527
+ const injected = slot.options.inject('session-abc')
2528
+ assert.equal(injected.sessionId, 'session-abc', 'inject 必须把 sessionId 原样传给组件')
2529
+ assert.ok(injected.controller, 'inject 必须传 controller')
2530
+ // 宿主不传 sessionId 时(空白会话)必须是 null,而不是 undefined —— 组件靠它判"能不能改"
2531
+ assert.equal(slot.options.inject(undefined).sessionId, null)
2532
+
2533
+ // ② 渲染:有覆盖时显示「有覆盖」标记、当前人设与来源
2534
+ // 预设库必须真的提供 activePersona 指向的那一项 ——
2535
+ // 否则选中态找不到对应项,兜底也无处可去(personaNames 为空 ⇒ 右栏空 ⇒ 无按钮)。
2536
+ world.routes['/api/soul/personas'] = () => ({
2537
+ ok: true,
2538
+ personas: {
2539
+ 苏格拉底式提问者: { style: 'professional', headingLists: 'less', emoji: 'default', tables: 'default', replyLength: 'normal', builtin: true },
2540
+ 幽默风趣: { style: 'humorous', headingLists: 'default', emoji: 'default', tables: 'default', replyLength: 'normal', builtin: true },
2541
+ 极简主义者: { style: 'efficient', headingLists: 'less', emoji: 'less', tables: 'less', replyLength: 'concise', builtin: true }
2542
+ },
2543
+ activeName: null
2544
+ })
2545
+ await world.controller.loadPersonas()
2546
+ world.routes['/api/soul/session-scope'] = (call) => {
2547
+ if (call.method === 'GET') {
2548
+ return {
2549
+ ok: true,
2550
+ sessionId: 'session-abc',
2551
+ workspaceId: 'ws_1',
2552
+ override: { style: 'humorous' },
2553
+ source: 'session',
2554
+ activePersona: '幽默风趣',
2555
+ workspaceTitle: 'dsh-plugin'
2556
+ }
2557
+ }
2558
+ return { ok: true, sessionId: 'session-abc', override: null, source: 'workspace', activePersona: '极简主义者', workspaceTitle: 'dsh-plugin' }
2559
+ }
2560
+
2561
+ const renderTab = async () => {
2562
+ const props = slot.options.inject('session-abc')
2563
+ const useSoulController = (selector) => selector(world.controller.store.getSnapshot())
2564
+ const tree = await world.runtime.settle({
2565
+ type: slot.component,
2566
+ props: { ...props, useSoulController, t: (k, p) => {
2567
+ const raw = zh[k] ?? k
2568
+ return p ? raw.replace(/\{(\w+)\}/g, (m, name) => (p[name] === undefined ? m : String(p[name]))) : raw
2569
+ } }
2570
+ })
2571
+ for (let i = 0; i < 6; i++) await new Promise((r) => drainTick(r))
2572
+ return world.runtime.settle({
2573
+ type: slot.component,
2574
+ props: { ...props, useSoulController, t: (k, p) => {
2575
+ const raw = zh[k] ?? k
2576
+ return p ? raw.replace(/\{(\w+)\}/g, (m, name) => (p[name] === undefined ? m : String(p[name]))) : raw
2577
+ } }
2578
+ })
2579
+ }
2580
+
2581
+ // 先让预设加载完(组件靠 state.personas 生成胶囊)
2582
+ world.routes['/api/soul/personas'] = () => ({
2583
+ ok: true,
2584
+ personas: { 苏格拉底式提问者: { style: 'professional', builtin: true }, 幽默风趣: { style: 'humorous' } },
2585
+ activeName: null
2586
+ })
2587
+ await world.controller.loadPersonas()
2588
+
2589
+ const tree = await renderTab()
2590
+ const text = textOf(tree)
2591
+ assert.ok(text.includes(zh['session.title']), '应显示标题')
2592
+ assert.ok(text.includes('幽默风趣'), `应显示当前生效人设,实际「${text}」`)
2593
+ assert.ok(text.includes(zh['session.source.session']), '来源应标明是「本会话临时覆盖」')
2594
+ // 「有覆盖」标记会出现**两处**:顶部状态行 + 右栏详情头。
2595
+ // 改成左右分栏后两处都要显示 —— 用户点开别的卡时,详情头显示"使用中"而顶部
2596
+ // 仍是"有覆盖",读起来才是同一套状态。
2597
+ assert.ok(
2598
+ findAllByClass(tree, 'soul-session-badge').length >= 1,
2599
+ '有覆盖时应显示「有覆盖」标记'
2600
+ )
2601
+ // 卡牌:每个预设一张(与设置页同一套卡牌语言)。
2602
+ // 0.9.0-d 改版前这里是胶囊(.soul-session-chip);改成卡牌后断言对象随之更换。
2603
+ const cards = findAllByClass(tree, 'soul-session-card')
2604
+ // 桩里有 2 个预设,叠层最多渲染 3 张 —— 2 个时只渲染 2 张(中心 + 左侧)
2605
+ assert.ok(cards.length <= 3 && cards.length >= 1, `叠层应渲染 1–3 张,实际 ${cards.length}`)
2606
+ // 卡面:插画 + 角标(0.9.0-l 起移除了遮罩与压图标题)
2607
+ assert.equal(findAllByClass(cards[0], 'soul-persona-art').length, 1, '卡面应有插画区(与设置页同款)')
2608
+ assert.equal(findAllByClass(cards[0], 'soul-persona-art-title').length, 0, '卡面不应有压图标题(0.9.0-l 已移除)')
2609
+ assert.equal(findAllByClass(cards[0], 'soul-persona-art-veil').length, 0, '卡面不应有渐变遮罩(0.9.0-l 已移除)')
2610
+ // 纯图形元素必须有可访问名
2611
+ assert.ok(
2612
+ String(cards[0].props['aria-label'] || '').length > 0,
2613
+ '纯图形的卡必须有 aria-label(读屏用户与断言都靠它识别是哪张卡)'
2614
+ )
2615
+ // 0.9.0-j:卡面**不再**有下方效果栏 —— 右栏详情已完整展示,
2616
+ // 卡上重复是冗余,还会把插画挤成半张。「完全展示卡牌」= 插画铺满。
2617
+ assert.equal(
2618
+ findAllByClass(cards[0], 'soul-persona-eff').length,
2619
+ 0,
2620
+ '卡面不应有效果栏(右栏详情已展示)'
2621
+ )
2622
+ // 0.9.0-l:遮罩与压图标题**都移除了** —— 右侧详情已完整展示,
2623
+ // 卡上再叠一层渐变遮罩 + 文字只是重复,还会让插画失掉饱和度。
2624
+ assert.equal(findAllByClass(cards[0], 'soul-persona-art-title').length, 0, '卡面不应有压图标题')
2625
+ assert.equal(findAllByClass(cards[0], 'soul-persona-art-veil').length, 0, '卡面不应有渐变遮罩')
2626
+ // 但必须有**可访问名**(纯图形元素的可访问名是必需品,不是可选项)
2627
+ assert.ok(
2628
+ String(cards[0].props['aria-label'] || '').length > 0,
2629
+ '纯图形的卡必须有 aria-label(读屏用户与断言都靠它识别是哪张卡)'
2630
+ )
2631
+ // 左卡牌 + 右详情:两块都必须存在
2632
+ assert.equal(findAllByClass(tree, 'soul-session-split').length, 1, '应是左右分栏布局')
2633
+ assert.equal(findAllByClass(tree, 'soul-session-detail').length, 1, '应有右栏详情面板')
2634
+ // 右栏要显示与设置页卡背**同款**的六个维度 + 自定义指令全文块
2635
+ // ⚠️ 不能只断言容器存在:容器在但里面一个维度都没有时,界面看起来"有一块空白",
2636
+ // 而容器断言仍然通过(判断力对照实测:把维度列表换成空数组时漏网)。
2637
+ assert.equal(
2638
+ findAllByClass(tree, 'soul-persona-dim').length,
2639
+ 6,
2640
+ `详情栏应列出六个维度(与设置页卡背同款),实际 ${findAllByClass(tree, 'soul-persona-dim').length}`
2641
+ )
2642
+ assert.ok(findAllByClass(tree, 'soul-persona-fulltext').length >= 1, '详情栏应有自定义指令全文块')
2643
+ // ⚠️ 叠层映射:选中卡必须落在**中心**(data-current)而非左侧。
2644
+ // 初版错写成 `stackOrder[offset + 1]`,把选中卡渲染到左侧、中心显示下一个 ——
2645
+ // 表现是「无论点哪个都显示同一张」。这里用中心卡 vs 详情栏名称交叉验证。
2646
+ {
2647
+ const centers = cards.filter((c) => c.props['data-current'] === 'true')
2648
+ assert.equal(centers.length, 1, `应恰好一张中心卡(data-current),实际 ${centers.length}`)
2649
+ const detail = findAllByClass(tree, 'soul-session-detail')[0]
2650
+ assert.ok(detail, '应有右栏详情面板')
2651
+ const detailName = findAllByClass(detail, 'soul-session-detail-name')[0]
2652
+ assert.ok(detailName, '详情栏应有名称')
2653
+ // 用 aria-label 交叉验证(卡面已无可见文字,0.9.0-l)
2654
+ assert.ok(
2655
+ String(centers[0].props['aria-label'] || '').includes(textOf(detailName)),
2656
+ `中心卡应是详情栏展示的那张(中心=「${String(centers[0].props['aria-label'] || '')}」,详情=「${textOf(detailName)}」)`
2657
+ )
2658
+ }
2659
+ // 自定义字段必须用中英文标签,不是裸键名
2660
+ {
2661
+ const fieldEls = findAllByClass(tree, 'soul-session-field')
2662
+ if (fieldEls.length > 0) {
2663
+ const bare = fieldEls.filter((f) => /^[a-z][A-Za-z]*$/.test(textOf(f)))
2664
+ assert.equal(
2665
+ bare.length, 0,
2666
+ `自定义字段应显示中英文标签,不应露出裸键名:${bare.map(textOf).join(', ')}`
2667
+ )
2668
+ }
2669
+ }
2670
+ // 宽度必须与宿主输入框同宽(读 --dsh-chat-content-width),不是硬编码
2671
+ {
2672
+ const source = readFileSync(new URL('../client/index.mjs', import.meta.url), 'utf8')
2673
+ const cssBlock = source.match(/const css = \[([\s\S]*?)\]\.join/)?.[1] ?? ''
2674
+ assert.match(
2675
+ cssBlock,
2676
+ /max-width:var\(--dsh-chat-content-width/,
2677
+ '会话 tab 宽度应读 --dsh-chat-content-width(与宿主输入框同宽)而非硬编码'
2678
+ )
2679
+ }
2680
+ // 左侧是**叠层轮转**:只渲染 3 张(中心 + 两侧露边),不是全部平铺。
2681
+ // 0.9.0-d 起是叠层,所以"每个预设一张"不再成立 —— 判据改为「最多 3 张且恰好一张中心」。
2682
+ {
2683
+ const styled = cards.filter((c) => c.props.style && typeof c.props.style.transform === 'string')
2684
+ assert.equal(styled.length, cards.length, '每张卡都应有叠层 transform(不是平铺)')
2685
+ // 判据不能只是「是字符串」:transform: '' 也是字符串。
2686
+ // 必须真的含 translateX,否则把叠层写成平铺、再留个空 transform 也能过。
2687
+ for (const c of styled) {
2688
+ assert.ok(
2689
+ c.props.style.transform.includes('translateX'),
2690
+ `叠层 transform 必须含 translateX,实际「${c.props.style.transform}」`
2691
+ )
2692
+ }
2693
+ assert.ok(cards.length <= 3, `叠层最多渲染 3 张(中心 + 两侧),实际 ${cards.length}`)
2694
+ const centers = cards.filter((c) => c.props['data-current'] === 'true')
2695
+ assert.equal(centers.length, 1, `应恰好一张中心卡(data-current),实际 ${centers.length}`)
2696
+ }
2697
+ // 生效中的那张卡要标出来,否则用户看不出哪个在用
2698
+ const effectiveCards = cards.filter((c) => c.props['data-effective'] === 'true')
2699
+ assert.equal(effectiveCards.length, 1, `应恰好一张卡标为生效中,实际 ${effectiveCards.length}`)
2700
+ assert.ok(
2701
+ String(effectiveCards[0].props['aria-label'] || '').includes('幽默风趣'),
2702
+ '生效中的应是当前覆盖的那个预设'
2703
+ )
2704
+ assert.equal(
2705
+ findAllByClass(tree, 'soul-session-chip').filter((c) => textOf(c) === zh['session.clear']).length,
2706
+ 1,
2707
+ '有覆盖时必须给出「取消本会话的临时人设」'
2708
+ )
2709
+ })
2710
+
2711
+ await check('C37 会话「人设」tab:轮播切卡看详情(不改配置)、右栏「用这个」才改、清除即恢复', async () => {
2712
+ const world = await boot()
2713
+ const zh = world.dicts.zh
2714
+ const posts = []
2715
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.view')
2716
+ assert.ok(slot, '前置条件:conversation.view 已注册')
2717
+
2718
+ let current = {
2719
+ ok: true,
2720
+ sessionId: 'session-abc',
2721
+ workspaceId: 'ws_1',
2722
+ override: null,
2723
+ source: 'workspace',
2724
+ activePersona: '苏格拉底式提问者',
2725
+ workspaceTitle: 'dsh-plugin'
2726
+ }
2727
+ world.routes['/api/soul/personas'] = () => ({
2728
+ ok: true,
2729
+ // 桩必须带上**真实预设会有的元数据**(updatedAt / builtin)与「关于你」字段:
2730
+ // 否则「客户端是否筛掉非覆盖字段」这件事根本测不出来 —— 判断力对照实测:
2731
+ // 把筛选循环换成 Object.assign 时,不带元数据的桩让断言全部放行。
2732
+ personas: {
2733
+ 苏格拉底式提问者: { style: 'professional', builtin: true, updatedAt: '2026-01-01T00:00:00Z' },
2734
+ 幽默风趣: {
2735
+ style: 'humorous',
2736
+ replyLength: 'concise',
2737
+ nickname: '不该被提交的昵称',
2738
+ occupation: '不该被提交的职业',
2739
+ updatedAt: '2026-01-01T00:00:00Z'
2740
+ }
2741
+ },
2742
+ activeName: null
2743
+ })
2744
+ world.routes['/api/soul/session-scope'] = (call) => {
2745
+ if (call.method === 'GET') return current
2746
+ posts.push(call.body)
2747
+ if (call.body && call.body.clear === true) {
2748
+ current = { ...current, override: null, source: 'workspace', activePersona: '苏格拉底式提问者' }
2749
+ } else {
2750
+ current = { ...current, override: call.body.overrides, source: 'session', activePersona: '幽默风趣' }
2751
+ }
2752
+ return current
2753
+ }
2754
+ await world.controller.loadPersonas()
2755
+
2756
+ const renderTab = async () => {
2757
+ const props = slot.options.inject('session-abc')
2758
+ const useSoulController = (selector) => selector(world.controller.store.getSnapshot())
2759
+ const t = (k, p) => {
2760
+ const raw = zh[k] ?? k
2761
+ return p ? raw.replace(/\{(\w+)\}/g, (m, name) => (p[name] === undefined ? m : String(p[name]))) : raw
2762
+ }
2763
+ for (let i = 0; i < 6; i++) await new Promise((r) => drainTick(r))
2764
+ return world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t } })
2765
+ }
2766
+
2767
+ let tree = await renderTab()
2768
+ // ① 点卡片选中 → 右栏详情出现「用这个」→ 点它才改配置
2769
+ //
2770
+ // 0.9.0-d 改成左右分栏后,卡面**不再**放操作按钮:点卡 = 换右栏详情(纯浏览),
2771
+ // 改配置的动作收敛到右栏。这两步必须分开验证 —— 否则「点卡直接改配置」这种
2772
+ // 退化(浏览即生效)测不出来。
2773
+ // 用 aria-label 识别卡(卡面已无可见文字,0.9.0-l)
2774
+ const cardFor = (n) => findAllByClass(tree, 'soul-session-card')
2775
+ .find((c) => String(c.props['aria-label'] || '').includes(n))
2776
+ const humorousCard = cardFor('幽默风趣')
2777
+ assert.ok(humorousCard, '应有「幽默风趣」的卡牌')
2778
+ // 卡面上不应有操作按钮(改配置只在右栏)
2779
+ assert.equal(
2780
+ findAllByClass(humorousCard, 'soul-persona-action').length,
2781
+ 0,
2782
+ '卡面上不应有操作按钮 —— 点卡只换详情,不该顺带改配置'
2783
+ )
2784
+ // 选中靠轮播的**圆点**(0.9.0-m 起卡不可点,只作信息展示)
2785
+ const dot = findAllByClass(tree, 'soul-persona-dot')
2786
+ .find((d) => String(d.props['aria-label'] || '').includes('幽默风趣'))
2787
+ assert.ok(dot, '轮播圆点里应有「幽默风趣」')
2788
+ await dot.props.onClick()
2789
+ tree = await renderTab()
2790
+ // 选中后右栏显示这张卡的详情,且「用这个」在右栏
2791
+ const detail = findAllByClass(tree, 'soul-session-detail')[0]
2792
+ assert.ok(detail, '应有右栏详情面板')
2793
+ assert.ok(textOf(detail).includes('幽默风趣'), `右栏应显示被选中的那张卡,实际「${textOf(detail).slice(0, 80)}」`)
2794
+ const useBtn = findAllByClass(detail, 'soul-persona-action')[0]
2795
+ assert.ok(useBtn, '右栏应有「用这个」按钮')
2796
+ assert.equal(textOf(useBtn), zh['session.useCard'], '未生效的人设应显示「用这个」')
2797
+ assert.equal(posts.length, 0, '仅仅选中一张卡**不得**改配置(浏览与生效是两件事)')
2798
+ await useBtn.props.onClick()
2799
+ tree = await renderTab()
2800
+ assert.equal(posts.length, 1, `点一次应只发一次请求,实际 ${posts.length}`)
2801
+ assert.deepEqual(posts[0], {
2802
+ sessionId: 'session-abc',
2803
+ overrides: { style: 'humorous', replyLength: 'concise' },
2804
+ // 必须带上用户实际点的预设名:服务端靠它显示「当前生效的是哪个预设」。
2805
+ // 只传字段的话,服务端只能反查,而反查在两个预设字段相同时不确定
2806
+ // (实测:自建「游戏策划与开发专家」与内置「自驱型协作者」字段一致时,
2807
+ // 名称排序让自建的那个抢先命中,用户点了后者却显示前者)。
2808
+ personaName: '幽默风趣'
2809
+ }, `应只带预设声明过的字段与预设名,实际 ${JSON.stringify(posts[0])}`)
2810
+ // ⚠️ 反向断言:预设条目的元数据与非人设字段**绝不能**被提交。
2811
+ // 只断言"带了正确的两个字段"会漏掉「整份预设照发」的形态 —— 判断力对照实测:
2812
+ // 把筛选循环换成 `Object.assign(overrides, entry)` 时,原版本全部放行。
2813
+ const submitted = posts[0].overrides || {}
2814
+ for (const forbidden of ['updatedAt', 'builtin', 'name', 'nickname', 'enabled']) {
2815
+ assert.equal(
2816
+ Object.prototype.hasOwnProperty.call(submitted, forbidden),
2817
+ false,
2818
+ `提交的覆盖里不得含 ${forbidden} —— 服务端会丢弃它,客户端本来就不该发`
2819
+ )
2820
+ }
2821
+ assert.ok(findAllByClass(tree, 'soul-session-badge').length >= 1, '改完应出现「有覆盖」标记')
2822
+ // 生效中的卡:卡片带 data-effective(配置事实),而**按钮在右栏**且变「使用中」
2823
+ {
2824
+ const effective = findAllByClass(tree, 'soul-session-card').filter((c) => c.props['data-effective'] === 'true')
2825
+ assert.equal(effective.length, 1, `应恰好一张卡标为生效中,实际 ${effective.length}`)
2826
+ // 卡面上没有按钮(浏览与生效分离),所以 active 样式落在右栏那个按钮上
2827
+ const detail = findAllByClass(tree, 'soul-session-detail')[0]
2828
+ const activeBtn = findAllByClass(detail, 'soul-persona-action')[0]
2829
+ assert.ok(activeBtn, '右栏应有操作按钮')
2830
+ assert.equal(textOf(activeBtn), zh['session.chipInUse'], '生效中的人设,右栏按钮应显示「使用中」')
2831
+ assert.ok(String(activeBtn.props.className).includes('soul-persona-active'), '生效中时按钮应带 active 样式')
2832
+ }
2833
+
2834
+ // ② 点「取消本会话的临时人设」→ clear:true,且覆盖消失
2835
+ const clearChip = findAllByClass(tree, 'soul-session-chip').find((c) => textOf(c) === zh['session.clear'])
2836
+ assert.ok(clearChip, '应有「取消本会话的临时人设」按钮')
2837
+ await clearChip.props.onClick()
2838
+ tree = await renderTab()
2839
+ assert.equal(posts.length, 2, '清除应再发一次请求')
2840
+ assert.deepEqual(posts[1], { sessionId: 'session-abc', clear: true })
2841
+ assert.equal(findAllByClass(tree, 'soul-session-badge').length, 0, '清除后不该再有「有覆盖」标记')
2842
+ })
2843
+
2844
+
2845
+ await check('C38 工作区人设:平铺卡片(未绑定排前)、内联选人设、解绑过二次确认', async () => {
2846
+ const world = await boot()
2847
+ const zh = world.dicts.zh
2848
+ const posts = []
2849
+ let view = {
2850
+ ok: true,
2851
+ indexProblem: null,
2852
+ max: 200,
2853
+ boundCount: 1,
2854
+ workspaces: [
2855
+ { workspaceId: 'ws_a', title: 'dsh-plugin', path: 'D:\\p\\dsh-plugin', sessionCount: 2, bound: true, invalidPersona: false },
2856
+ { workspaceId: 'ws_b', title: 'dsh-soul', path: 'D:\\p\\dsh-soul', sessionCount: 1, bound: false, invalidPersona: false },
2857
+ { workspaceId: 'ws_c', title: 'aaa-newest', path: 'D:\\p\\aaa', sessionCount: 0, bound: false, invalidPersona: false }
2858
+ ]
2859
+ }
2860
+ world.routes['/api/soul/personas'] = () => ({
2861
+ ok: true,
2862
+ personas: { 苏格拉底式提问者: { style: 'professional', builtin: true }, 极简主义者: { style: 'efficient' } },
2863
+ activeName: null
2864
+ })
2865
+ world.routes['/api/soul/workspaces'] = (call) => {
2866
+ if (call.method === 'GET') return view
2867
+ posts.push({ path: '/api/soul/workspaces', body: call.body })
2868
+ view = {
2869
+ ...view,
2870
+ workspaces: view.workspaces.map((w) => (w.workspaceId === call.body.workspaceId ? { ...w, bound: true } : w))
2871
+ }
2872
+ return view
2873
+ }
2874
+ world.routes['/api/soul/workspaces/delete'] = (call) => {
2875
+ posts.push({ path: '/api/soul/workspaces/delete', body: call.body })
2876
+ view = {
2877
+ ...view,
2878
+ workspaces: view.workspaces.map((w) => (w.workspaceId === call.body.workspaceId ? { ...w, bound: false } : w))
2879
+ }
2880
+ return view
2881
+ }
2882
+ await world.controller.loadPersonas()
2883
+
2884
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'plugins.detail.section' && s.options.id === 'soul-detail-workspaces')
2885
+ assert.ok(slot, '必须注册到 plugins.detail.section 槽位')
2886
+
2887
+ // ⚠️ `subject` 由**宿主**在渲染详情页时注入,不在注册时的 inject 里。
2888
+ // 组件靠它判断"这个详情页是不是自己的",所以测试必须自己补上 ——
2889
+ // 漏补的话组件一律 return null,看起来像"组件坏了"(本用例初版就读到 0 张卡片)。
2890
+ const OWN_SUBJECT = { kind: 'bundle', pkg: { name: 'dsh-soul' } }
2891
+
2892
+ const render = async () => {
2893
+ const props = { ...slot.options.inject(), subject: OWN_SUBJECT }
2894
+ const useSoulController = (selector) => selector(world.controller.store.getSnapshot())
2895
+ const t = (k, p) => {
2896
+ const raw = zh[k] ?? k
2897
+ return p ? raw.replace(/\{(\w+)\}/g, (m, name) => (p[name] === undefined ? m : String(p[name]))) : raw
2898
+ }
2899
+ // ⚠️ 顺序必须是「先渲染 → 再等 → 再渲染」:组件在**首次渲染**时才挂载、
2900
+ // effect 才排上异步加载。先等再渲染的话,等的是"还没发出去的请求",
2901
+ // 于是永远停在加载态(本用例初版就是这么读到 0 张卡片的)。
2902
+ await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t } })
2903
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
2904
+ return world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t } })
2905
+ }
2906
+
2907
+ // `reload` 的 effect 依赖是 `[]` —— 组件只在**挂载那一次**拉数据。
2908
+ // 测试里换掉路由后再调 render() 并不会重跑 effect(依赖没变),
2909
+ // 所以「换路由 → 重进页面」必须显式重建:先 unmount 再 render。
2910
+ const remount = async () => {
2911
+ world.runtime.unmount()
2912
+ return await render()
2913
+ }
2914
+
2915
+ // ① 只服务自己的详情页
2916
+ let tree = await render()
2917
+ const props0 = { ...slot.options.inject(), subject: OWN_SUBJECT }
2918
+ // settle 返回的是渲染树节点(组件返回 null 时外层仍有一层),所以判据是**没有内容**,
2919
+ // 而不是 strictEqual(null)。
2920
+ const otherTree = await world.runtime.settle({
2921
+ type: slot.component,
2922
+ props: { ...props0, subject: { kind: 'bundle', pkg: { name: 'other-plugin' } }, useSoulController: (s) => s(world.controller.store.getSnapshot()), t: (k) => zh[k] ?? k }
2923
+ })
2924
+ assert.equal(textOf(otherTree || {}).trim(), '', '其他插件的详情页必须不渲染任何内容')
2925
+ assert.equal(findAllByClass(otherTree || {}, 'soul-ws-card').length, 0, '其他插件的详情页不得出现工作区卡片')
2926
+
2927
+ // ② 平铺卡片,且**未绑定的排在前面**(那正是用户来这一页要处理的)
2928
+ const cards = findAllByClass(tree, 'soul-ws-card')
2929
+ assert.equal(cards.length, 3, `应渲染三张工作区卡片,实际 ${cards.length}`)
2930
+ const titles = cards.map((c) => textOf(findAllByClass(c, 'soul-ws-title')[0]))
2931
+ assert.deepEqual(titles, ['aaa-newest', 'dsh-soul', 'dsh-plugin'],
2932
+ `未绑定的应排前面并按标题排序,实际 ${JSON.stringify(titles)}`)
2933
+ assert.equal(cards[0].props['data-bound'], 'false')
2934
+ assert.equal(cards[2].props['data-bound'], 'true')
2935
+
2936
+ // ②b 「加载中」「加载失败」「确实没有工作区」是三件不同的事。
2937
+ // 这一组曾经在 0.8.0 的 C14 上被真实抓到过(懒加载分组把失败显示成"加载中"),
2938
+ // 所以这里逐个验证三态各自的文案,而不是只测成功路径。
2939
+ {
2940
+ const saved = world.routes['/api/soul/workspaces']
2941
+ // 失败:必须显示原因,不能停在「加载中」。
2942
+ // 桩用 `ok:false` 而不是抛错 —— postJSON 只把 `payload.error` 翻进异常消息,
2943
+ // 抛错会变成 "HTTP 500",测不到"原因被展示"这件事。
2944
+ world.routes['/api/soul/workspaces'] = () => ({ ok: false, error: 'boom' })
2945
+ const failTree = await remount()
2946
+ assert.equal(
2947
+ textOf(failTree).includes(zh['workspaces.loading']),
2948
+ false,
2949
+ '读取失败时不得停在「加载中」—— 那与"确实没有工作区"长得一样'
2950
+ )
2951
+ assert.ok(textOf(failTree).includes('boom'), `失败时应把原因显示出来,实际「${textOf(failTree)}」`)
2952
+
2953
+ // 空列表:显示空态文案,而不是加载中
2954
+ world.routes['/api/soul/workspaces'] = () => ({ ok: true, indexProblem: null, max: 200, boundCount: 0, workspaces: [] })
2955
+ const emptyTree = await remount()
2956
+ assert.ok(textOf(emptyTree).includes(zh['workspaces.empty']), '没有工作区时应显示空态文案')
2957
+ assert.equal(textOf(emptyTree).includes(zh['workspaces.loading']), false, '空态不得显示成加载中')
2958
+
2959
+ // 服务不可用(indexProblem):如实说明,且**不**显示空态
2960
+ world.routes['/api/soul/workspaces'] = () => ({ ok: true, indexProblem: 'registry 不可用', max: 200, boundCount: 0, workspaces: [] })
2961
+ const problemTree = await remount()
2962
+ assert.ok(textOf(problemTree).includes('registry 不可用'), '服务不可用时应如实说明原因')
2963
+ assert.equal(
2964
+ textOf(problemTree).includes(zh['workspaces.empty']),
2965
+ false,
2966
+ '服务不可用时不得显示成"还没有工作区"—— 那会让用户以为自己的数据没了'
2967
+ )
2968
+ world.routes['/api/soul/workspaces'] = saved
2969
+ }
2970
+
2971
+ // ③ 点「绑定人设」→ 内联展开人设胶囊(不弹层)
2972
+ tree = await remount()
2973
+ const freshCards = findAllByClass(tree, 'soul-ws-card')
2974
+ // 「绑定人设」已改用宿主 ui.Button(0.9.0-am),不再是 .soul-ws-action ——
2975
+ // 按「可点 + 文案」找,而不是按 class 找,这样组件实现换了断言依然成立。
2976
+ const bindBtn = findAll(
2977
+ freshCards[0],
2978
+ (b) => (b.type === 'button' || b.type === 'ui-button') &&
2979
+ typeof b.props?.onClick === 'function' &&
2980
+ textOf(b) === zh['workspaces.bind']
2981
+ )[0]
2982
+ assert.ok(bindBtn, '未绑定的卡片应有「绑定人设」')
2983
+ await bindBtn.props.onClick()
2984
+ tree = await render()
2985
+ const chips = findAllByClass(tree, 'soul-session-chip')
2986
+ assert.ok(chips.length >= 2, `应展开人设胶囊,实际 ${chips.length}`)
2987
+ assert.equal(findAllByClass(tree, 'soul-ws-picker').length, 1, '只展开一个选择器')
2988
+
2989
+ // ④ 点一个人设 → 发一次绑定请求
2990
+ const pick = chips.find((c) => textOf(c) === '极简主义者')
2991
+ assert.ok(pick, '应有「极简主义者」胶囊')
2992
+ await pick.props.onClick()
2993
+ tree = await render()
2994
+ assert.equal(posts.length, 1, `应发一次绑定请求,实际 ${posts.length}`)
2995
+ assert.deepEqual(posts[0], { path: '/api/soul/workspaces', body: { workspaceId: 'ws_c', persona: '极简主义者' } })
2996
+ assert.equal(findAllByClass(tree, 'soul-ws-picker').length, 0, '绑定后应收起选择器')
2997
+
2998
+ // ⑤ 解绑:第一次点只 arm,第二次才发请求
2999
+ tree = await render()
3000
+ const boundCard = findAllByClass(tree, 'soul-ws-card')[2]
3001
+ // 解绑是**文字按钮**(0.9.0-ao,照抄宿主设置-模型页的「删除」= dangerButton):
3002
+ // 文案在按钮文字上,按文案找。
3003
+ const unbindBtn = () => findAllByClass(tree, 'soul-ws-btn-danger')
3004
+ .find((b) => textOf(b) === zh['workspaces.unbind'])
3005
+ assert.ok(unbindBtn(), '已绑定的卡片应有「解除绑定」按钮')
3006
+ await unbindBtn().props.onClick()
3007
+ tree = await render()
3008
+ assert.equal(posts.length, 1, '第一次点解绑不得发请求')
3009
+ // armed 态:同一按钮多一个 armed 类,文字换成「确认解绑…」
3010
+ const armed = findAllByClass(tree, 'soul-ws-btn-armed')
3011
+ assert.equal(armed.length, 1, '第一次点后应进入 armed 态')
3012
+ assert.equal(armed[0].props['data-armed'], 'true', 'armed 态应有 data-armed 标记')
3013
+ assert.equal(textOf(armed[0]), zh['workspaces.unbindArmed'], 'armed 态文案应换成确认文案')
3014
+ await armed[0].props.onClick()
3015
+ tree = await render()
3016
+ assert.equal(posts.length, 2, '第二次点才发解绑请求')
3017
+ assert.equal(posts[1].path, '/api/soul/workspaces/delete')
3018
+ })
3019
+
3020
+ // verify-e2e-prompt 的 W1–W15 与 R1–R13 守着。0.9.0 用工作区平铺卡片重写 UI 时,
3021
+ // 会在这里补新的行为用例。
3022
+
3023
+ await check('C34 保留条数在变更记录区块里就地改并即时落盘,设置页不得再有它', async () => {
3024
+ const entries = [historyEntry({ id: 'r-1', at: new Date().toISOString(), before: { style: 'professional' }, after: { style: 'casual' } })]
3025
+ const world = await boot()
3026
+ const posts = []
3027
+ world.routes['/api/soul/history'] = () => ({ ok: true, entries, max: 200, warning: null })
3028
+ world.routes['/api/soul/config'] = (call) => {
3029
+ if (call.method === 'GET') return { ok: true, config: { ...CONFIG }, configError: null, deliveryWarning: null }
3030
+ posts.push(call.body)
3031
+ // 服务端把 POST 体当 patch 合并,并把(夹取后的)值回传
3032
+ return { ok: true, config: { ...CONFIG, ...call.body }, changed: ['historyMaxEntries'], deliveryWarning: null }
3033
+ }
3034
+ const zh = world.dicts.zh
3035
+
3036
+ // ① 设置页的每个分组里都不得再有这个控件(逐个展开查,避免只看了默认展开的那组)
3037
+ let tree = await renderSettings(world)
3038
+ for (const groupKey of ['group.traits', 'group.personas', 'group.bindings', 'group.tool']) {
3039
+ const btn = findAll(tree, (n) => n.type === 'button' && textOf(n).includes(zh[groupKey]))[0]
3040
+ if (!btn) continue
3041
+ await btn.props.onClick()
3042
+ tree = await renderSettingsSettled(world)
3043
+ assert.equal(findAll(tree, (n) => n.props && n.props.id === 'soul-historyMaxEntries').length, 0,
3044
+ `设置页「${zh[groupKey]}」分组里不得再出现保留条数下拉(0.8.1 已迁到详情页)`)
3045
+ }
3046
+
3047
+ // ② 详情页的变更记录区块里必须有它
3048
+ let detail = await renderDetailSettled(world)
3049
+ const selects = findAll(detail, (n) => n.type === 'select' && n.props.id === 'soul-historyMaxEntries')
3050
+ assert.equal(selects.length, 1, `详情页应恰好一个保留条数下拉,实际 ${selects.length}`)
3051
+ assert.equal(selects[0].props.value, '200', '初始值应来自配置(默认 200)')
3052
+ // 档位完整(50 / 100 / 200 / 500),否则用户没法把窗口调大
3053
+ const options = findAll(selects[0], (n) => n.type === 'option').map((n) => n.props.value)
3054
+ assert.deepEqual(options, ['50', '100', '200', '500'], `档位应为四档,实际 ${JSON.stringify(options)}`)
3055
+
3056
+ // ③ 改一次就落盘,不用等设置页那个保存按钮
3057
+ await selects[0].props.onChange({ target: { value: '500' } })
3058
+ detail = await renderDetailSettled(world)
3059
+ assert.equal(posts.length, 1, `改一次应恰好发一次保存请求,实际 ${posts.length}`)
3060
+ // 只发这一个字段:整份配置回传会覆盖掉别的标签页刚改的东西
3061
+ assert.deepEqual(posts[0], { historyMaxEntries: 500 }, `请求体只该带这一个字段,实际 ${JSON.stringify(posts[0])}`)
3062
+ const after = findAll(detail, (n) => n.type === 'select' && n.props.id === 'soul-historyMaxEntries')[0]
3063
+ assert.equal(after.props.value, '500', '成功后下拉应停在新值上')
3064
+ const okText = findAllByClass(detail, 'soul-saved-notice')
3065
+ assert.equal(okText.length, 1, '成功后应有一行绿字')
3066
+ assert.equal(textOf(okText[0]), zh['history.maxEntriesSaved'].replace('{count}', '500'))
3067
+ })
3068
+
3069
+ await check('C39 会话覆盖清理:默认只预览、确认才删、扫描不完整时不给清理按钮', async () => {
3070
+ const world = await boot()
3071
+ const zh = world.dicts.zh
3072
+ const posts = []
3073
+ let plan = {
3074
+ ok: true,
3075
+ dryRun: true,
3076
+ scanComplete: true,
3077
+ persistenceProblem: null,
3078
+ total: 3,
3079
+ markable: [{ sessionId: 's-watching' }],
3080
+ collectable: [{ sessionId: 's-old', file: 'a.json', reason: '缺席超过 30 天' }],
3081
+ quarantine: [{ sessionId: 's-bad', file: 'b.json', reason: '内容损坏' }],
3082
+ entries: []
3083
+ }
3084
+ world.routes['/api/soul/session-scope/gc'] = (call) => {
3085
+ posts.push(call.body || {})
3086
+ if (call.body && call.body.apply === true) {
3087
+ plan = { ...plan, dryRun: false, collectable: [], removed: ['s-old'] }
3088
+ }
3089
+ return plan
3090
+ }
3091
+
3092
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'plugins.detail.section' && s.options.id === 'soul-detail-sessions')
3093
+ assert.ok(slot, '必须注册到 plugins.detail.section 槽位(id=soul-detail-sessions)')
3094
+ const OWN = { kind: 'bundle', pkg: { name: 'dsh-soul' } }
3095
+
3096
+ const render = async () => {
3097
+ const props = { ...slot.options.inject(), subject: OWN }
3098
+ const useSoulController = (selector) => selector(world.controller.store.getSnapshot())
3099
+ const t = (k, p) => {
3100
+ const raw = zh[k] ?? k
3101
+ return p ? raw.replace(/\{(\w+)\}/g, (m, name) => (p[name] === undefined ? m : String(p[name]))) : raw
3102
+ }
3103
+ await world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t } })
3104
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
3105
+ return world.runtime.settle({ type: slot.component, props: { ...props, useSoulController, t } })
3106
+ }
3107
+
3108
+ // ① 打开页面**不自动扫描**:清理是运维动作,不该在打开详情页时悄悄跑一遍
3109
+ let tree = await render()
3110
+ assert.equal(posts.length, 0, '打开详情页不得自动发起清理扫描')
3111
+ assert.ok(textOf(tree).includes(zh['sessions.previewHint']), '未预览时应给出「预览不会删」的说明')
3112
+ assert.equal(findAllByClass(tree, 'soul-ws-action-armed').length, 0, '未预览时不得出现确认按钮')
3113
+
3114
+ // ② 点「清理可回收项」→ 只发一次 dry-run(body 里**没有** apply:true)
3115
+ const firstBtn = () => findAll(findAllByClass(tree, 'soul-sessions-actions')[0], (n) => n.type === 'button')[0]
3116
+ await firstBtn().props.onClick()
3117
+ tree = await render()
3118
+ assert.equal(posts.length, 1, '点一次应只发一次扫描请求')
3119
+ assert.equal(posts[0].apply, undefined, '第一次点击**不得**带 apply:true —— 默认必须站在「不删」一侧')
3120
+ const armed = findAllByClass(tree, 'soul-ws-action-armed')
3121
+ assert.equal(armed.length, 1, '预览出可回收项后应出现确认按钮')
3122
+ assert.equal(textOf(armed[0]), zh['sessions.collectArmed'].replace('{count}', '1'))
3123
+
3124
+ // ③ 点确认 → 才发 apply:true
3125
+ await armed[0].props.onClick()
3126
+ tree = await render()
3127
+ assert.equal(posts.length, 2, '确认应再发一次请求')
3128
+ assert.equal(posts[1].apply, true, '确认时**必须**带 apply:true')
3129
+ assert.ok(textOf(tree).includes(zh['sessions.collected'].replace('{count}', '1')), '应报告清理结果')
3130
+
3131
+ // ④ 扫描不完整 → 明确说明「没做判定」,且**不给清理按钮**
3132
+ world.runtime.unmount()
3133
+ posts.length = 0
3134
+ // ⚠️ 桩必须让 collectable **非空**:扫描不完整时状态机对所有条目返回 keep,
3135
+ // 所以真实数据下 collectable 必然是空的 —— 但如果桩也给它空,
3136
+ // 「界面上是否显示清理按钮只取决于 collectable」这个缺陷就永远测不出来。
3137
+ // 这里刻意构造"不完整 + 有可回收项"这个真实世界不该出现、但代码可能误判的形态。
3138
+ plan = {
3139
+ ok: true,
3140
+ dryRun: true,
3141
+ scanComplete: false,
3142
+ persistenceProblem: 'sessionPersistence 不可用',
3143
+ total: 3,
3144
+ markable: [],
3145
+ collectable: [{ sessionId: 's-should-not-show', file: 'c.json', reason: '不应出现' }],
3146
+ quarantine: [],
3147
+ entries: []
3148
+ }
3149
+ tree = await render()
3150
+ await firstBtn().props.onClick()
3151
+ tree = await render()
3152
+ assert.ok(textOf(tree).includes(zh['sessions.scanIncomplete']), '扫描不完整时必须说清没做判定')
3153
+ assert.equal(findAllByClass(tree, 'soul-ws-action-armed').length, 0, '扫描不完整时不得给出确认删除的入口')
3154
+ })
1313
3155
  } finally {
1314
3156
  restoreTimers()
1315
3157
  }
1316
3158
 
3159
+ await check('C52 工作区绑定按钮用宿主 ui.Button —— 自绘 <button> 会在 hover 变全黑', async () => {
3160
+ // 背景(用户实测):自定义 <button> 会继承宿主的基础按钮样式(实心主色底 + 白字),
3161
+ // 而插件又用 `.soul-bindings-bind{color:var(--dsw-alias-brand-primary)}` 覆盖了文字色
3162
+ // (深色)。hover 时宿主把底色压深、插件把文字压深 ⇒ 深底深字,整个按钮全黑。
3163
+ //
3164
+ // 契约:这四个按钮必须走宿主组件 ui.Button —— 底色/文字/悬停由宿主成套给出,
3165
+ // 插件不得再覆盖 background / color(.soul-bindings-* 里出现这两条即为回归)。
3166
+ const start = source.indexOf('function SoulBindings')
3167
+ assert.ok(start > 0, '应能定位到 SoulBindings 组件')
3168
+ // 边界 = 下一个顶层函数声明(组件之间的分隔),取不到则退化为 13400 字符
3169
+ const nextFn = source.indexOf('\n function ', start + 10)
3170
+ const region = source.slice(start, nextFn > start ? nextFn : start + 13400)
3171
+ assert.ok(region.length > 5000, `SoulBindings 区域应完整(实际 ${region.length} 字符)`)
3172
+ const btnCount = (region.match(/e\(ui\.Button,/g) || []).length
3173
+ assert.ok(
3174
+ btnCount >= 4,
3175
+ `SoulBindings 里的按钮应全部改用 ui.Button(选择目录/绑定/解绑/改为),实际只有 ${btnCount} 处`
3176
+ )
3177
+ assert.equal(
3178
+ region.includes('soul-bindings-pick'),
3179
+ false,
3180
+ '不得再自绘「选择目录…」按钮(.soul-bindings-pick 已废弃)'
3181
+ )
3182
+ assert.equal(
3183
+ region.includes('soul-bindings-bind'),
3184
+ false,
3185
+ '不得再自绘「绑定人设」按钮(.soul-bindings-bind 已废弃)'
3186
+ )
3187
+ // variant 必须是 outline:primary 是实心主色底(浅色主题下 ≈ 黑),
3188
+ // hover 再压一层就更黑 —— 用户两次反馈「hover 全黑」的根因就是它。
3189
+ const outlineCount = (region.match(/variant: 'outline'/g) || []).length
3190
+ assert.equal(outlineCount, 2, `绑定/选择目录两个按钮都应为 outline,实际 ${outlineCount} 个`)
3191
+ assert.equal(
3192
+ /variant: 'primary'/.test(region),
3193
+ false,
3194
+ '工作区绑定区不得用 primary —— 实心主色底 + 深色文字会让按钮看起来「全黑」'
3195
+ )
3196
+ // 插件 CSS 不得再给这些按钮定底色或文字色 —— 那正是全黑的成因。
3197
+ for (const selector of ['.soul-bindings-pick', '.soul-bindings-bind', '.soul-bindings-action']) {
3198
+ const rulePattern = new RegExp(
3199
+ selector.replace(/\./g, '\\.') + '\\{[^}]*\\}',
3200
+ 'g'
3201
+ )
3202
+ const rules = source.match(rulePattern) || []
3203
+ for (const rule of rules) {
3204
+ assert.equal(
3205
+ /background\s*:/.test(rule),
3206
+ false,
3207
+ `${selector} 不得覆盖 background(会让宿主悬停底色与文字撞色):${rule.slice(0, 80)}`
3208
+ )
3209
+ assert.equal(
3210
+ /[^-]color\s*:/.test(rule),
3211
+ false,
3212
+ `${selector} 不得覆盖 color(全黑的直接成因):${rule.slice(0, 80)}`
3213
+ )
3214
+ }
3215
+ }
3216
+ })
3217
+
3218
+ await check('C53 侧栏会话行面具徽标:自己按需拉绑定视图(不再依赖插件详情页)', async () => {
3219
+ // 背景(用户实测「看不到」):徽标的数据源 store.bindingsSessions 原先**只有**
3220
+ // 插件详情页的 SoulBindings 挂载时才会被填充(那里调 loadBindings)。
3221
+ // 侧栏往往先于详情页挂载 ⇒ bindingsSessions 恒为空 ⇒ 徽标永远渲染 null,
3222
+ // 用户 hover 会话行什么也看不到。
3223
+ //
3224
+ // 契约:徽标首次挂载时自行补一次拉取(bindings === null 才拉),
3225
+ // 拿到「会话 → 生效人设」的解析结果后渲染;已拉过就不再重复请求。
3226
+ const world = await boot()
3227
+ const zh = world.dicts.zh
3228
+ let bindingCalls = 0
3229
+ world.routes['/api/soul/bindings'] = () => {
3230
+ bindingCalls += 1
3231
+ return {
3232
+ ok: true,
3233
+ bindings: {},
3234
+ sessions: [
3235
+ { id: 'session-abc', cwd: 'D:\\proj', persona: '自驱型协作者', binding: null, shadowed: [] },
3236
+ { id: 'session-xyz', cwd: null, persona: '极简主义者', binding: null, shadowed: [] }
3237
+ ],
3238
+ max: 64,
3239
+ maxPathLength: 260
3240
+ }
3241
+ }
3242
+ await world.controller.loadConfig()
3243
+
3244
+ const slot = world.captured.sections.find(
3245
+ (s) => s.options && s.options.name === 'sidebar.workspaces.session.row.action'
3246
+ )
3247
+ assert.ok(slot, '未注册 sidebar.workspaces.session.row.action 槽位')
3248
+ const tFn = (k, q) => {
3249
+ const raw = zh[k] ?? k
3250
+ return q ? raw.replace(/\{(\w+)\}/g, (m, name) => (q[name] === undefined ? m : String(q[name]))) : raw
3251
+ }
3252
+ const renderBadge = async (sessionId) => {
3253
+ const injected = slot.options.inject()
3254
+ const store = injected.hooks.soulController
3255
+ const useSoulController = (selector) => selector(store.getSnapshot())
3256
+ const element = {
3257
+ type: slot.component,
3258
+ props: { ...injected, sessionId, useSoulController, t: tFn }
3259
+ }
3260
+ await world.runtime.settle(element)
3261
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
3262
+ return world.runtime.settle(element)
3263
+ }
3264
+
3265
+ // ① store 从没拉过绑定视图(bindings === null)——正是侧栏先挂载时的真实状态
3266
+ assert.equal(
3267
+ world.controller.store.getSnapshot().bindings,
3268
+ null,
3269
+ '前置:本用例必须从「没拉过绑定视图」开始,否则测不到按需拉取'
3270
+ )
3271
+
3272
+ // ② 挂载徽标 → 必须自己触发一次拉取
3273
+ let tree = await renderBadge('session-abc')
3274
+ assert.equal(bindingCalls, 1, `徽标挂载应补拉一次绑定视图,实际 ${bindingCalls} 次`)
3275
+
3276
+ // ③ 拉回后按 sessionId 命中对应会话的人设,渲染面具徽标 + tooltip
3277
+ const badges = findAllByClass(tree, 'soul-sidebar-persona-badge')
3278
+ assert.equal(badges.length, 1, '有生效人设的会话行应渲染一个面具徽标')
3279
+ const expectTip = zh['sidebar.personaTip'].replace('{name}', '自驱型协作者')
3280
+ assert.equal(badges[0].props['aria-label'], expectTip, '无障碍标签应写明该会话的人设')
3281
+ // 不得再挂 title 气泡:人设已进宿主 hover 信息卡,两个气泡会同时冒出来
3282
+ assert.equal(
3283
+ badges[0].props.title,
3284
+ undefined,
3285
+ '徽标不应再挂 title —— 人设显示在宿主那张卡里,避免两个弹窗'
3286
+ )
3287
+ // 只读:不得绑点击(避免误触打开会话)
3288
+ assert.equal(typeof badges[0].props.onClick, 'undefined', '徽标是只读标识,不应有点击行为')
3289
+
3290
+ // 气泡必须是**宿主 Tooltip**:原生 title 会画浅色系统气泡,与旁边「置顶/归档」
3291
+ // 的黑色气泡并排时两种样式(用户实测指出)。
3292
+ const tips = findAll(tree, (x) => x.type === 'ui-tooltip')
3293
+ assert.equal(tips.length, 1, '徽标应被宿主 Tooltip 包裹,而不是靠原生 title')
3294
+ assert.equal(tips[0].props.label, expectTip, 'Tooltip 文案应为「人设:X」')
3295
+ assert.equal(tips[0].props.delayMs, 500, '延迟应与宿主的行尾按钮一致(500ms)')
3296
+ assert.equal(tips[0].props.portal, true, '应 portal 渲染 —— 与宿主行尾按钮一致')
3297
+ assert.equal(
3298
+ badges[0].props.title,
3299
+ undefined,
3300
+ '不得再用原生 title(会与宿主 Tooltip 抢着弹)'
3301
+ )
3302
+
3303
+ // ④ 已拉过就不再重复请求(每次重渲染都发一次请求会打出请求风暴)
3304
+ tree = await renderBadge('session-abc')
3305
+ assert.equal(bindingCalls, 1, '数据已就绪后不得重复拉取')
3306
+ assert.equal(findAllByClass(tree, 'soul-sidebar-persona-badge').length, 1, '重渲染后徽标仍在')
3307
+
3308
+ // ⑤ 不存在的会话 id:渲染 null(不占 hover 位),也不额外请求
3309
+ tree = await renderBadge('session-not-in-list')
3310
+ assert.equal(
3311
+ findAllByClass(tree, 'soul-sidebar-persona-badge').length,
3312
+ 0,
3313
+ '解析不到人设的会话行不应出现徽标'
3314
+ )
3315
+ assert.equal(bindingCalls, 1, '不应为未知会话再发请求')
3316
+ })
3317
+
3318
+ await check('C54 面具图标只有一份几何 —— 三处不得各抄一套(下巴改圆只改到 header 的旧伤)', async () => {
3319
+ // 背景(用户实测):这个面具出现在会话 header 标签、侧栏会话行徽标、侧栏面板图标
3320
+ // 三处。此前每处各抄一份 path,「下巴改圆」只改了 header,另两处仍用尖下巴 ——
3321
+ // 同一副面具在界面上长出两种轮廓。
3322
+ //
3323
+ // 契约:轮廓只允许出现一次(SOUL_MASK_PATHS),三处都调用 soulMask()。
3324
+ const outlineCount = (source.match(/M2\.2 3\.0 C4\.2 1\.8/g) || []).length
3325
+ assert.equal(outlineCount, 1, `面具轮廓应只有一份定义,实际 ${outlineCount} 份`)
3326
+ const callCount = (source.match(/soulMask\(\{/g) || []).length
3327
+ assert.ok(callCount >= 3, `三处图标都应调用 soulMask(),实际 ${callCount} 处`)
3328
+ // 旧尖下巴轮廓不得残留(它是「分叉」的具体证据)
3329
+ assert.equal(
3330
+ source.includes('C14.4 6.6 12.4 11.6 8.0 13.8'),
3331
+ false,
3332
+ '不得残留旧版尖下巴轮廓'
3333
+ )
3334
+ // 圆下巴的弧必须是正文里那一份(防止有人把数组里那份改回尖的)
3335
+ assert.ok(
3336
+ source.includes('C14.4 6.4 13.0 11.4 11.4 12.4'),
3337
+ '共用几何应为圆下巴版本'
3338
+ )
3339
+ })
3340
+
3341
+ await check('C55 宿主 hover 信息卡里显示当前会话人设(复用宿主那张卡,不自绘 tooltip)', async () => {
3342
+ // 用户诉求:hover 会话行时宿主会弹信息卡(标题 / 运行状态 / 几分钟前),
3343
+ // 希望人设也显示在里面,而不是另冒一个自己的 tooltip。
3344
+ //
3345
+ // 槽位:sidebar.session.row.hover —— 宿主文档写明它是
3346
+ // "Section of the Session row's hover card ... Mounted only while that card is open."
3347
+ const world = await boot()
3348
+ const zh = world.dicts.zh
3349
+ world.routes['/api/soul/bindings'] = () => ({
3350
+ ok: true,
3351
+ bindings: {},
3352
+ sessions: [{ id: 'session-abc', cwd: 'D:\\proj', persona: '自驱型协作者', binding: null, shadowed: [] }],
3353
+ max: 64,
3354
+ maxPathLength: 260
3355
+ })
3356
+ await world.controller.loadConfig()
3357
+
3358
+ const slot = world.captured.sections.find(
3359
+ (s) => s.options && s.options.name === 'sidebar.session.row.hover'
3360
+ )
3361
+ assert.ok(slot, '未注册 sidebar.session.row.hover 槽位')
3362
+ assert.equal(slot.options.id, 'soul-persona', '槽位 id 应为 soul-persona')
3363
+
3364
+ const tFn = (k, q) => {
3365
+ const raw = zh[k] ?? k
3366
+ return q ? raw.replace(/\{(\w+)\}/g, (m, name) => (q[name] === undefined ? m : String(q[name]))) : raw
3367
+ }
3368
+ const renderHover = async (sessionId) => {
3369
+ const injected = slot.options.inject()
3370
+ const store = injected.hooks.soulController
3371
+ const useSoulController = (selector) => selector(store.getSnapshot())
3372
+ const element = {
3373
+ type: slot.component,
3374
+ props: { ...injected, sessionId, useSoulController, t: tFn }
3375
+ }
3376
+ await world.runtime.settle(element)
3377
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
3378
+ return world.runtime.settle(element)
3379
+ }
3380
+
3381
+ // ① 命中该会话 → 卡里出现「人设 · 名字」
3382
+ let tree = await renderHover('session-abc')
3383
+ const rows = findAllByClass(tree, 'soul-hover-persona')
3384
+ assert.equal(rows.length, 1, '有生效人设的会话应在 hover 卡里渲染一行')
3385
+ const text = textOf(rows[0])
3386
+ assert.ok(text.includes(zh['sidebar.personaRow']), `应带「人设」标签,实际「${text}」`)
3387
+ assert.ok(text.includes('自驱型协作者'), `应显示人设名,实际「${text}」`)
3388
+ // 图标与 header 共用同一份几何(同一个 soulMask 产物)
3389
+ assert.equal(findAllByClass(rows[0], 'soul-hover-persona-icon').length, 1, '应带面具图标')
3390
+
3391
+ // ② 解析不到人设 → 渲染 null(宿主卡里不多一行空壳)
3392
+ tree = await renderHover('session-not-in-list')
3393
+ assert.equal(
3394
+ findAllByClass(tree, 'soul-hover-persona').length,
3395
+ 0,
3396
+ '解析不到人设时不应占用宿主卡片的一行'
3397
+ )
3398
+
3399
+ // ③ 与行尾徽标共用同一套取数(不得各写一份,否则会出现「徽标有、卡里没有」)
3400
+ const region = source.slice(
3401
+ source.indexOf('function SoulSessionPersonaHover'),
3402
+ source.indexOf('function SoulQuickToggle')
3403
+ )
3404
+ assert.ok(
3405
+ region.includes('useSessionRowPersona('),
3406
+ 'hover 卡必须复用 useSessionRowPersona —— 与行尾徽标同一份数据/降级规则'
3407
+ )
3408
+
3409
+ // ④ 文字规格必须与宿主卡片一致(宿主同槽位住户 ui-schedule 的 SessionScheduleHover):
3410
+ // .task{gap:8px;align-items:flex-start} / .taskIcon{color:#cfd3d6;height:16px}
3411
+ // .taskName{color:#fff;font-size:12px;line-height:16px}
3412
+ // .taskTiming{color:#cfd3d6;font-size:12px;line-height:16px}
3413
+ // 并且**不得用主题 token**:宿主卡片恒为深色,token 在浅色主题下是深色值,
3414
+ // 照搬会变成深字压深底(看不见)。
3415
+ const ruleOf = (cls) => {
3416
+ const m = source.match(new RegExp('\\.' + cls + '\\{[^}]*\\}'))
3417
+ assert.ok(m, '缺少样式规则 .' + cls)
3418
+ return m[0]
3419
+ }
3420
+ const row = ruleOf('soul-hover-persona')
3421
+ assert.ok(row.includes('gap:8px'), '行间距应与宿主 .task 一致(8px)')
3422
+ assert.ok(row.includes('align-items:flex-start'), '对齐方式应与宿主 .task 一致')
3423
+ const icon = ruleOf('soul-hover-persona-icon')
3424
+ assert.ok(icon.includes('height:16px'), '图标容器高度应与宿主 .taskIcon 一致(16px)')
3425
+ assert.ok(icon.includes('--dsw-static-neutral-bluish-300'), '图标色应取宿主同值的静态色(#cfd3d6 = bluish-300)')
3426
+ const label = ruleOf('soul-hover-persona-label')
3427
+ assert.ok(label.includes('--dsw-static-neutral-bluish-300'), '「人设」标签色应与宿主次要文字同值(bluish-300)')
3428
+ assert.ok(label.includes('font-size:12px') && label.includes('line-height:16px'), '标签字号/行高应为 12/16')
3429
+ const name = ruleOf('soul-hover-persona-name')
3430
+ assert.ok(name.includes('--dsw-static-neutral-bluish-00'), '人设名应与宿主主体文字同值(#fff = bluish-00)')
3431
+ assert.ok(name.includes('font-size:12px') && name.includes('line-height:16px'), '人设名字号/行高应为 12/16')
3432
+ for (const cls of ['soul-hover-persona', 'soul-hover-persona-icon', 'soul-hover-persona-label', 'soul-hover-persona-name']) {
3433
+ assert.equal(
3434
+ ruleOf(cls).includes('--dsw-alias'),
3435
+ false,
3436
+ '.` + cls + ` 不得使用主题 token —— 宿主卡片恒为深色,token 会随主题变成深字压深底'
3437
+ )
3438
+ }
3439
+ })
3440
+
3441
+ await check('C56 工作区人设按钮:hover 不得改文字色(深底白字会被压成黑底黑字)', async () => {
3442
+ // 用户两次反馈「hover 全黑」。真因不在 SoulBindings,而在工作区人设卡片:
3443
+ // .soul-ws-action-primary{background:brand-primary;color:label-primary-foreground}
3444
+ // .soul-ws-action:hover{... color:brand-primary} ← 优先级更高(class+伪类)
3445
+ // 于是深色底 + 被染成近黑色的文字 = 整块全黑;同一条规则也压掉了
3446
+ // .soul-ws-action-armed 的红色「确认解绑」提示。
3447
+ //
3448
+ // 契约:hover 只允许改边框,不得改文字色;「绑定人设」改用宿主 ui.Button。
3449
+ const hover = source.match(/\.soul-ws-action:hover\{([^}]*)\}/)
3450
+ assert.ok(hover, '找不到 .soul-ws-action:hover 规则')
3451
+ assert.equal(
3452
+ /[^-]color\s*:/.test(hover[1]),
3453
+ false,
3454
+ `hover 不得改文字色(会让深底按钮变成黑底黑字):${hover[1]}`
3455
+ )
3456
+ // 自绘的主色按钮样式必须彻底移除(现在用 ui.Button 的 outline 变体)
3457
+ assert.equal(
3458
+ /'\.soul-ws-action-primary\{/.test(source),
3459
+ false,
3460
+ '不得再自绘主色按钮样式(.soul-ws-action-primary 已废弃)'
3461
+ )
3462
+ assert.ok(
3463
+ /variant: 'outline',\s*size: 'sm',[\s\S]{0,200}?workspaces\.bind/.test(source),
3464
+ '「绑定人设」必须走宿主 ui.Button 的 outline 变体'
3465
+ )
3466
+ })
3467
+
3468
+ await check('C57 改绑/解绑是文字按钮:规格照抄宿主设置-模型页的编辑(secondaryButton)/删除(dangerButton)', async () => {
3469
+ // 用户指出:宿主设置-模型页的「编辑 / 删除」是**文字按钮**,不是图标按钮。
3470
+ // 我上一版误抄了同页面的 .iconButton(那是别处的图标形态),已纠正。
3471
+ //
3472
+ // 宿主真实实现(ui-settings-models 的 CSS 模块):
3473
+ // 编辑 → .secondaryButton
3474
+ // {border:.5px solid border-l3; color:label-primary; background:0 0}
3475
+ // {border-radius:sm; height:28px; padding:0 10px; font-size:12px; line-height:18px}
3476
+ // :hover{background:interactive-bg-hover-solid}
3477
+ // :disabled{opacity:.4;cursor:default}
3478
+ // 删除 → .dangerButton(紧凑尺寸同上)
3479
+ // {color:state-error-primary; background:0 0; border:none} ← 无描边、红字
3480
+ // :hover{background:interactive-bg-hover-danger}
3481
+ const rule = (cls) => {
3482
+ const m = source.match(new RegExp('\\.' + cls + '\\{[^}]*\\}'))
3483
+ assert.ok(m, '缺少样式规则 .' + cls)
3484
+ return m[0]
3485
+ }
3486
+ const base = rule('soul-ws-btn')
3487
+ assert.ok(/border:\.5px solid var\(--dsw-alias-border-l3\)/.test(base), '描边应为 .5px border-l3(宿主 secondaryButton 同款)')
3488
+ assert.ok(/height:28px/.test(base), '高度应为 28px(宿主紧凑尺寸)')
3489
+ assert.ok(/padding:0 10px/.test(base), '左右内边距应为 10px(宿主紧凑尺寸)')
3490
+ assert.ok(/font-size:12px/.test(base) && /line-height:18px/.test(base), '字号/行高应为 12/18(宿主紧凑尺寸)')
3491
+ assert.ok(/color:var\(--dsw-alias-label-primary\)/.test(base), '文字色应为 label-primary(宿主编辑按钮同款)')
3492
+ const hover = rule('soul-ws-btn:hover:not\\(:disabled\\)')
3493
+ assert.ok(/interactive-bg-hover-solid/.test(hover), '悬停底色应为 interactive-bg-hover-solid(宿主 secondaryButton 同款)')
3494
+ // 删除:无描边 + 红字 + 浅红悬停
3495
+ const danger = rule('soul-ws-btn-danger')
3496
+ assert.ok(/border:none/.test(danger), '删除按钮不应有描边(宿主 dangerButton 是 border:none)')
3497
+ assert.ok(/state-error-primary/.test(danger), '删除按钮应为红字(宿主 dangerButton 同款)')
3498
+ const dangerHover = rule('soul-ws-btn-danger:hover:not\\(:disabled\\)')
3499
+ assert.ok(/interactive-bg-hover-danger/.test(dangerHover), '删除悬停应为 danger 浅红底(宿主同款)')
3500
+ // 必须是文字按钮:不得再引用任何图标组件
3501
+ assert.equal(
3502
+ /ui\.Icon\w+/.test(source),
3503
+ false,
3504
+ '工作区按钮应为文字按钮 —— 不得引用 ui.Icon*(图标名还在宿主模块表里踩过 #130)'
3505
+ )
3506
+ // 文案必须还在(文字按钮的核心:靠文字表达动作)
3507
+ assert.ok(/workspaces\.rebind/.test(source) && /workspaces\.unbindArmed/.test(source), '按钮文案应保留')
3508
+ })
3509
+
1317
3510
  if (!assertCount('verify-client', passed, EXPECTED_ASSERTIONS)) process.exit(1)
1318
3511
 
1319
3512
  console.log(`\n全部通过:${passed} 项检查`)