dsh-soul 0.6.2 → 0.7.1

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.
@@ -0,0 +1,700 @@
1
+ // scripts/verify-client.mjs — 设置页客户端行为回归(离线,无浏览器)
2
+ //
3
+ // 为什么需要它:`verify-trail` / `verify-nav-icon` 覆盖的是**渲染层**(DOM 里的 SVG),
4
+ // 而设置页的**交互行为**一直只有「源文本契约」——即断言客户端源码里出现了某段写法。
5
+ // 那种断言证明不了「运行时真的走了那条分支」:把 `if (!payload)` 改成常量、或让
6
+ // `resetConfig` 永不返回 undefined,源码看起来依然正确。
7
+ //
8
+ // 这里把**真实的 `client/index.mjs`** 原样载入(不复制、不裁剪),在纯 Node 里:
9
+ // 1. 用一小撮 React 垫片实现 hooks(useState / useEffect / useRef)与 jsx-runtime;
10
+ // 2. 用假 window / document / fetch / 定时器接管外部世界;
11
+ // 3. 跑真实的 `apply(ctx)`,拿到真实的 `soulController` 与设置页组件;
12
+ // 4. 像用户一样**点按钮**,断言**用户实际会看到的提示文案**。
13
+ //
14
+ // 覆盖的行为全部是 0.7.1 修过、而此前没有任何行为回归守着的那几处:
15
+ // - 两类问题分开上报:`configError`(配置读不出来)/ `deliveryWarning`(送不到会话)
16
+ // - 重置失败**不得**被报成成功(配置损坏时那唯一一条自救路径)
17
+ // - 重置成功且丢弃过损坏文件时要告知「已备份」
18
+ // - 保存失败**不得**误报成「配置无变化」
19
+ //
20
+ // 零依赖,直接 `node scripts/verify-client.mjs` 运行。
21
+
22
+ import assert from 'node:assert/strict'
23
+ import { readFileSync } from 'node:fs'
24
+ import { setImmediate as drainTick } from 'node:timers'
25
+ import { assertCount } from './lib/skip-report.mjs'
26
+
27
+ // 基线运行应跑出的断言数。本脚本没有环境相关跳过(客户端源码与 Node 都在),
28
+ // 所以链里的 `--strict` 对它无额外语义;数字由下面的 assertCount 守住。
29
+ const EXPECTED_ASSERTIONS = 17
30
+
31
+ const source = readFileSync(new URL('../client/index.mjs', import.meta.url), 'utf8')
32
+
33
+ // ==================== 一、React 垫片 ====================
34
+ //
35
+ // 只实现客户端真正用到的那几个 hook(`React.useState` × 25 / `useEffect` × 9 /
36
+ // `useRef` × 6,无 useCallback / useMemo / useSyncExternalStore)。hook 按「组件在
37
+ // 渲染树里的路径」分帧、按调用顺序取槽 —— 与 React 的规则一致。渲染是同步的:状态
38
+ // 变化只置脏标记,由 settle() 收敛。
39
+
40
+ const Fragment = Symbol('Fragment')
41
+
42
+ function createRuntime() {
43
+ const frames = new Map() // 路径 -> { key, values: [], deps: [], cursor }
44
+ const cleanups = new Map() // `${frame.key}#${slot}` -> 清理函数
45
+ let frameStack = []
46
+ let queue = []
47
+ let dirty = false
48
+
49
+ const frameOf = () => {
50
+ const frame = frameStack[frameStack.length - 1]
51
+ if (!frame) throw new Error('hook 在组件外被调用')
52
+ return frame
53
+ }
54
+
55
+ const React = {
56
+ Fragment,
57
+ useState(initial) {
58
+ const frame = frameOf()
59
+ const slot = frame.cursor++
60
+ if (!(slot in frame.values)) {
61
+ frame.values[slot] = typeof initial === 'function' ? initial() : initial
62
+ }
63
+ const set = (next) => {
64
+ const current = frame.values[slot]
65
+ const value = typeof next === 'function' ? next(current) : next
66
+ if (Object.is(value, current)) return
67
+ frame.values[slot] = value
68
+ dirty = true
69
+ }
70
+ return [frame.values[slot], set]
71
+ },
72
+ useEffect(fn, deps) {
73
+ const frame = frameOf()
74
+ const slot = frame.cursor++
75
+ const prev = frame.deps[slot]
76
+ const same = prev !== undefined && deps !== undefined &&
77
+ prev.length === deps.length && deps.every((d, i) => Object.is(d, prev[i]))
78
+ if (same) return
79
+ frame.deps[slot] = deps
80
+ queue.push({ frame, slot, fn })
81
+ },
82
+ useRef(initial) {
83
+ const frame = frameOf()
84
+ const slot = frame.cursor++
85
+ if (!(slot in frame.values)) frame.values[slot] = { current: initial }
86
+ return frame.values[slot]
87
+ }
88
+ }
89
+
90
+ const jsx = (type, props, key) => ({ type, props: props || {}, key })
91
+
92
+ function renderChildren(children, path) {
93
+ if (children === undefined || children === null || typeof children === 'boolean') return []
94
+ if (Array.isArray(children)) return children.flatMap((c, i) => renderChildren(c, `${path},${i}`))
95
+ if (typeof children === 'string' || typeof children === 'number') {
96
+ return [{ type: '#text', text: String(children) }]
97
+ }
98
+ const node = render(children, path)
99
+ return node ? [node] : []
100
+ }
101
+
102
+ function render(node, path) {
103
+ if (typeof node === 'string' || typeof node === 'number') return { type: '#text', text: String(node) }
104
+ if (!node || typeof node !== 'object') return null
105
+ const { type, props } = node
106
+ if (type === Fragment) return { type: '#fragment', children: renderChildren(props.children, `${path}#`) }
107
+ if (typeof type === 'function') {
108
+ const frame = frames.get(path) || { key: path, values: [], deps: [], cursor: 0 }
109
+ frames.set(path, frame)
110
+ frame.cursor = 0
111
+ frameStack.push(frame)
112
+ let out
113
+ try {
114
+ out = type(props)
115
+ } finally {
116
+ frameStack.pop()
117
+ }
118
+ return render(out, `${path}/`)
119
+ }
120
+ // 宿主元素(原生标签,或 ui 垫片里的标记类型):props 原样保留 —— 断言要读它们
121
+ return { type, props, children: renderChildren(props.children, `${path}>`) }
122
+ }
123
+
124
+ const drain = async () => {
125
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
126
+ }
127
+
128
+ return {
129
+ React,
130
+ jsx,
131
+ Fragment,
132
+ /** 渲染 + 跑本轮 effect,直到状态不再变化(含 effect / handler 里已 resolve 的 promise)。 */
133
+ async settle(root) {
134
+ for (let pass = 0; pass < 40; pass++) {
135
+ dirty = false
136
+ queue = []
137
+ const tree = render(root, 'root')
138
+ for (const { frame, slot, fn } of queue) {
139
+ const key = `${frame.key}#${slot}`
140
+ const previous = cleanups.get(key)
141
+ if (typeof previous === 'function') previous()
142
+ const returned = fn()
143
+ cleanups.set(key, typeof returned === 'function' ? returned : null)
144
+ }
145
+ await drain()
146
+ if (!dirty) return tree
147
+ }
148
+ throw new Error('渲染未收敛(40 轮仍在变化)—— hook 依赖或 effect 里可能有自激循环')
149
+ }
150
+ }
151
+ }
152
+
153
+ // ==================== 二、遍历渲染树 ====================
154
+
155
+ function walk(node, visit) {
156
+ if (!node) return
157
+ visit(node)
158
+ for (const child of node.children || []) walk(child, visit)
159
+ }
160
+
161
+ function textOf(node) {
162
+ if (!node) return ''
163
+ if (node.type === '#text') return node.text
164
+ return (node.children || []).map(textOf).join('')
165
+ }
166
+
167
+ function findAll(tree, predicate) {
168
+ const hits = []
169
+ walk(tree, (node) => {
170
+ if (predicate(node)) hits.push(node)
171
+ })
172
+ return hits
173
+ }
174
+
175
+ // ==================== 三、沙箱:假 window / document / 定时器 / fetch ====================
176
+
177
+ const realTimers = {
178
+ setTimeout: globalThis.setTimeout,
179
+ clearTimeout: globalThis.clearTimeout,
180
+ setInterval: globalThis.setInterval,
181
+ clearInterval: globalThis.clearInterval
182
+ }
183
+ let timerQueue = []
184
+ let fetchCalls = []
185
+
186
+ const installFakeTimers = () => {
187
+ // 客户端有三处定时器,全部与断言直接相关,必须接管:
188
+ // - toast 的 2s 自动消失(绝不能在断言之前触发);
189
+ // - 「关于你」分组的 2s 轮询刷新(真实 setInterval 会让事件循环永不空 —— 脚本
190
+ // 跑完最后一行却不退出,看起来像挂住);
191
+ // - 提示词预览的 400ms 防抖。
192
+ // 接管后由用例决定何时推进,测试才是确定性的、也才跑得完。
193
+ globalThis.setTimeout = (fn, delay) => {
194
+ const handle = { fn, delay: delay || 0, repeat: false }
195
+ timerQueue.push(handle)
196
+ return handle
197
+ }
198
+ globalThis.setInterval = (fn, delay) => {
199
+ const handle = { fn, delay: delay || 0, repeat: true }
200
+ timerQueue.push(handle)
201
+ return handle
202
+ }
203
+ const drop = (handle) => {
204
+ if (handle) timerQueue = timerQueue.filter((t) => t !== handle)
205
+ }
206
+ globalThis.clearTimeout = drop
207
+ globalThis.clearInterval = drop
208
+ }
209
+ const restoreTimers = () => {
210
+ globalThis.setTimeout = realTimers.setTimeout
211
+ globalThis.clearTimeout = realTimers.clearTimeout
212
+ globalThis.setInterval = realTimers.setInterval
213
+ globalThis.clearInterval = realTimers.clearInterval
214
+ }
215
+
216
+ const interpolate = (text, params) =>
217
+ String(text).replace(/\{(\w+)\}/g, (all, key) => (params && key in params ? String(params[key]) : all))
218
+
219
+ /** 载入真实客户端 bundle 并装配插件(返回真实 controller 与设置页组件)。 */
220
+ function loadClient(routes) {
221
+ let factory = null
222
+ const domNode = () => ({
223
+ style: { setProperty() {}, removeProperty() {} },
224
+ classList: { add() {}, remove() {} },
225
+ dataset: {},
226
+ setAttribute() {},
227
+ removeAttribute() {},
228
+ appendChild() {},
229
+ remove() {},
230
+ addEventListener() {},
231
+ removeEventListener() {},
232
+ children: []
233
+ })
234
+ const windowStub = {
235
+ __ModuleLoader__: { load: (m) => { factory = m.factory } },
236
+ addEventListener() {},
237
+ removeEventListener() {},
238
+ location: { origin: 'http://dsh.test' }
239
+ }
240
+ const documentStub = {
241
+ visibilityState: 'visible',
242
+ body: domNode(),
243
+ head: domNode(),
244
+ addEventListener() {},
245
+ removeEventListener() {},
246
+ // 插件在装配时会把样式表插到 head(用 querySelector 判重),导航图标那一层还会
247
+ // 挂 MutationObserver —— 这里只需让这些调用成立;本脚本断言的是行为,不是 DOM。
248
+ querySelector: () => null,
249
+ querySelectorAll: () => [],
250
+ createElement: () => domNode(),
251
+ createElementNS: () => domNode()
252
+ }
253
+
254
+ globalThis.window = windowStub
255
+ globalThis.document = documentStub
256
+ globalThis.MutationObserver = class { observe() {} disconnect() {} takeRecords() { return [] } }
257
+ globalThis.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} }
258
+ globalThis.requestAnimationFrame = (fn) => drainTick(() => fn(0))
259
+ globalThis.cancelAnimationFrame = () => {}
260
+ globalThis.getComputedStyle = () => ({ position: 'absolute', getPropertyValue: () => '' })
261
+ globalThis.fetch = async (input, init = {}) => {
262
+ const url = new URL(String(input))
263
+ const method = (init.method || 'GET').toUpperCase()
264
+ const call = { path: url.pathname, method, body: init.body ? JSON.parse(init.body) : null }
265
+ fetchCalls.push(call)
266
+ const handler = routes[url.pathname]
267
+ const body = handler ? handler(call) : { ok: false, error: `no route: ${url.pathname}` }
268
+ if (body === false) return { ok: false, status: 500, json: async () => ({ ok: false, error: 'boom' }) }
269
+ return { ok: true, status: 200, json: async () => body }
270
+ }
271
+
272
+ installFakeTimers()
273
+
274
+ const runtime = createRuntime()
275
+ const requireStub = (spec) => {
276
+ if (spec === 'react') return runtime.React
277
+ if (spec === 'react/jsx-runtime') return { jsx: runtime.jsx, jsxs: runtime.jsx, Fragment }
278
+ if (spec === '@deepseek-ai/dsh-client-ui-primitives') {
279
+ // ui.Button 单独换成宿主元素标记:这样它连同 onClick / children 原样留在渲染树里,
280
+ // 断言就能像用户一样「找到那个按钮并点它」,而不是去猜某个闭包。
281
+ return { Button: 'ui-button' }
282
+ }
283
+ throw new Error(`未预料的 require:${spec}`)
284
+ }
285
+ // eslint-disable-next-line no-new-func -- 客户端是宿主加载的 bundle(无 ESM 导入),只能在受控作用域里求值
286
+ new Function('window', source)(windowStub)
287
+ const module = factory(requireStub)
288
+
289
+ const captured = { provide: {}, sections: [], dicts: null, runtime }
290
+ const ctx = {
291
+ provide: (name, value) => { captured.provide[name] = value },
292
+ effect: (fn) => { const dispose = fn(); if (typeof dispose === 'function') captured.sections.push({ dispose }) },
293
+ locale: {
294
+ register: (_ns, dicts) => { captured.dicts = dicts },
295
+ bind: () => (key, params) => interpolate((captured.dicts?.zh || {})[key] ?? key, params)
296
+ },
297
+ slots: {
298
+ inject: (_name, cb) => cb(),
299
+ register: (options, component) => { captured.sections.push({ options, component }) }
300
+ }
301
+ }
302
+ module.apply(ctx)
303
+
304
+ const section = captured.sections.find((s) => s.options && s.options.name === 'settings.section')
305
+ const controller = captured.provide.soulController
306
+ const world = {
307
+ runtime,
308
+ captured,
309
+ section,
310
+ controller,
311
+ routes,
312
+ dicts: captured.dicts,
313
+ apply: module.apply,
314
+ module
315
+ }
316
+ return world
317
+ }
318
+
319
+ // ==================== 四、驱动器 ====================
320
+
321
+ /**
322
+ * 装配一个干净的客户端实例(含真实的初始 loadConfig)。
323
+ *
324
+ * **桩必须与宿主真实协议同形**:`GET /api/soul/personas` 返回的是
325
+ * `{ personas: <对象 map>, activeName: <名字|null> }`(见 index.mjs:835 personaLibrary),
326
+ * 其中 personas 由 mergePersonas 生成、**恒含 7 个内置人设**(已实测:mergePersonas(null)
327
+ * 也有 7 个键),所以真实环境里「空列表」分支不可达。
328
+ * 此前这个桩写的是 `{ personas: [], activePersona: null }` —— 字段名错(activePersona
329
+ * 而非 activeName)、类型也错(数组而非对象 map),于是人设行与 ★ 标记的渲染在行为层
330
+ * **从未被执行过**:把它改成真实形状,整套 C 系列依然全绿(实测)。这正是「测试替身
331
+ * 与真实协议漂移」的典型:桩喂了一个真实环境不可达的输入,测试永远看不到真问题。
332
+ */
333
+ async function boot(configPayload = {}, personaPayload = null) {
334
+ fetchCalls = []
335
+ timerQueue = []
336
+ const routes = {
337
+ '/api/soul/config': (call) => (call.method === 'GET'
338
+ ? { ok: true, config: { ...CONFIG }, ...configPayload }
339
+ : { ok: true, config: { ...CONFIG }, changed: [] }),
340
+ '/api/soul/config/reset': () => ({ ok: true, config: { ...CONFIG }, changed: [], backupPath: null }),
341
+ // 默认形状贴近宿主:对象 map + activeName(不是数组、不是 activePersona)
342
+ '/api/soul/personas': () => (personaPayload || {
343
+ ok: true,
344
+ personas: { 苏格拉底式提问者: { style: 'professional', builtin: true } },
345
+ activeName: null
346
+ }),
347
+ '/api/soul/prompt': () => ({ ok: true, prompt: 'P', enabled: true })
348
+ }
349
+ const world = loadClient(routes)
350
+ for (let i = 0; i < 8; i++) await new Promise((r) => drainTick(r))
351
+ return world
352
+ }
353
+
354
+ /**
355
+ * 渲染设置页。`useSoulController` 由宿主把槽位声明的 `hooks.soulController`
356
+ * (一个 subscribe / getSnapshot store)包成 hook 注入 —— 这里用垫片复刻同一语义。
357
+ */
358
+ function rootElement(world) {
359
+ const props = world.section.options.inject()
360
+ const store = props.hooks.soulController
361
+ const useSoulController = (selector) => {
362
+ const [, force] = world.runtime.React.useState(0)
363
+ world.runtime.React.useEffect(() => store.subscribe(() => force((n) => n + 1)), [])
364
+ return selector(store.getSnapshot())
365
+ }
366
+ return { type: world.section.component, props: { ...props, useSoulController } }
367
+ }
368
+
369
+ const renderSettings = (world) => world.runtime.settle(rootElement(world))
370
+
371
+ /** 输入框左侧的快捷开关(conversation.input.left 槽位),渲染方式与设置页同源。 */
372
+ function quickToggleElement(world) {
373
+ const slot = world.captured.sections.find((s) => s.options && s.options.name === 'conversation.input.left')
374
+ assert.ok(slot, '未注册 conversation.input.left 槽位')
375
+ const props = slot.options.inject()
376
+ const store = props.hooks.soulController
377
+ const useSoulController = (selector) => {
378
+ const [, force] = world.runtime.React.useState(0)
379
+ world.runtime.React.useEffect(() => store.subscribe(() => force((n) => n + 1)), [])
380
+ return selector(store.getSnapshot())
381
+ }
382
+ return { type: slot.component, props: { ...props, useSoulController } }
383
+ }
384
+
385
+ /** 像用户一样点快捷开关,返回之后的按钮节点(可读 props 上的反馈)。 */
386
+ async function clickQuickToggle(world) {
387
+ const before = await world.runtime.settle(quickToggleElement(world))
388
+ const buttons = findAll(before, (n) => n.type === 'button' && typeof n.props?.onClick === 'function')
389
+ assert.equal(buttons.length, 1, `快捷开关应恰好一个可点按钮,实际 ${buttons.length}`)
390
+ await buttons[0].props.onClick()
391
+ for (let i = 0; i < 6; i++) await new Promise((r) => drainTick(r))
392
+ const after = await world.runtime.settle(quickToggleElement(world))
393
+ return findAll(after, (n) => n.type === 'button')[0]
394
+ }
395
+
396
+ /** 像用户一样点下指定文案的按钮,返回之后的 toast({ text, kind })。 */
397
+ async function clickButton(world, labelKey) {
398
+ const tree = await renderSettings(world)
399
+ const label = world.dicts.zh[labelKey]
400
+ const buttons = findAll(tree, (n) => n.type === 'ui-button' && textOf(n) === label)
401
+ assert.equal(buttons.length, 1, `期望恰好一个「${label}」按钮,实际 ${buttons.length} 个`)
402
+ await buttons[0].props.onClick()
403
+ const after = await renderSettings(world)
404
+ const toasts = findAll(after, (n) => typeof n.props?.className === 'string' && n.props.className.includes('soul-toast'))
405
+ assert.equal(toasts.length, 1, `期望恰好一个 toast,实际 ${toasts.length} 个`)
406
+ return {
407
+ text: textOf(toasts[0]),
408
+ kind: toasts[0].props.className.includes('soul-toast-error') ? 'error' : 'success'
409
+ }
410
+ }
411
+
412
+ // ==================== 五、用例 ====================
413
+
414
+ const CONFIG = {
415
+ enabled: true,
416
+ nickname: '',
417
+ occupation: '',
418
+ bio: '',
419
+ style: 'professional',
420
+ headingLists: 'default',
421
+ emoji: 'default',
422
+ tables: 'default',
423
+ replyLength: 'normal',
424
+ language: 'zh',
425
+ customInstructions: '',
426
+ requireToolConfirmation: false,
427
+ trailEnabled: true,
428
+ trailColor: '#679EFE',
429
+ trailSpeed: 'slow',
430
+ trailWidth: 'thin'
431
+ }
432
+
433
+ let passed = 0
434
+ async function check(name, fn) {
435
+ try {
436
+ await fn()
437
+ } catch (error) {
438
+ // 失败时把用例名带进消息:否则只有一行 AssertionError,无法一眼看出是哪个用例塌了。
439
+ // 注意 `stack` 也要改 —— 未捕获错误打印的是 stack,它的首行在 AssertionError 构造时
440
+ // 就已经写死,只改 `message` 在终端上根本看不见(判断力对照实测过)。
441
+ error.message = `【${name}】${error.message}`
442
+ error.stack = `【${name}】${error.stack}`
443
+ throw error
444
+ }
445
+ passed++
446
+ console.log(` ✓ ${name}`)
447
+ }
448
+
449
+ try {
450
+ await check('C1 真实 client/index.mjs 可在纯 Node 里装配,并通过 settings.section 注册设置栏目', async () => {
451
+ const world = await boot()
452
+ assert.ok(world.section, '未注册 settings.section')
453
+ assert.equal(world.section.options.id, 'soul-settings')
454
+ assert.equal(typeof world.section.options.label, 'function', 'label 必须是函数(语言切换时实时解析)')
455
+ assert.ok(world.controller, '未 provide soulController')
456
+ assert.ok(world.dicts?.zh && world.dicts?.en, '双语文案表未注册')
457
+ })
458
+
459
+ await check('C2 装配后立即以 GET 拉取配置(而不是等用户打开设置页)', async () => {
460
+ await boot()
461
+ const got = fetchCalls.filter((c) => c.path === '/api/soul/config' && c.method === 'GET')
462
+ assert.equal(got.length, 1, `期望恰好一次 GET /api/soul/config,实际 ${got.length}`)
463
+ })
464
+
465
+ await check('C3 磁盘配置损坏时,configError 要显示在设置页上', async () => {
466
+ const world = await boot({ configError: 'soul-config.json 解析失败' })
467
+ const tree = await renderSettings(world)
468
+ assert.match(textOf(tree), /soul-config\.json 解析失败/, '设置页未显示 configError')
469
+ })
470
+
471
+ await check('C4 只有送达警告时,deliveryWarning 同样要显示出来', async () => {
472
+ const world = await boot({ deliveryWarning: '未送达任何活动会话' })
473
+ const tree = await renderSettings(world)
474
+ assert.match(textOf(tree), /未送达任何活动会话/, '设置页未显示 deliveryWarning')
475
+ })
476
+
477
+ await check('C5 两者同时存在时以 configError 为准(读不出来的问题更靠前)', async () => {
478
+ const world = await boot({ configError: '读不出来', deliveryWarning: '送不到' })
479
+ assert.equal(world.controller.store.getSnapshot().error, '读不出来')
480
+ })
481
+
482
+ await check('C6 保存成功但配置送不到会话时,回传的 deliveryWarning 要落到提示条上', async () => {
483
+ const world = await boot()
484
+ world.routes['/api/soul/config'] = (call) => (call.method === 'GET'
485
+ ? { ok: true, config: { ...CONFIG } }
486
+ : { ok: true, config: { ...CONFIG }, changed: ['style'], deliveryWarning: '注入失败' })
487
+ const payload = await world.controller.saveConfig({ style: 'casual' })
488
+ assert.ok(payload, '保存成功应返回 payload')
489
+ assert.equal(world.controller.store.getSnapshot().error, '注入失败')
490
+ })
491
+
492
+ await check('C7 保存失败时 saveConfig 返回 falsy(调用方据此给失败提示,而不是误报「无变化」)', async () => {
493
+ const world = await boot()
494
+ world.routes['/api/soul/config'] = (call) => (call.method === 'GET'
495
+ ? { ok: true, config: { ...CONFIG } }
496
+ : { ok: false, error: '写入被拒绝' })
497
+ const payload = await world.controller.saveConfig({ style: 'casual' })
498
+ assert.equal(payload, undefined, '保存失败不得返回 payload')
499
+ assert.match(String(world.controller.store.getSnapshot().error), /写入被拒绝/)
500
+ })
501
+
502
+ await check('C8 重置失败时弹「重置失败」,不得报成成功(0.7.1 修的就是这里)', async () => {
503
+ const world = await boot()
504
+ world.routes['/api/soul/config/reset'] = () => false // 失败响应
505
+ const toast = await clickButton(world, 'button.reset')
506
+ assert.equal(toast.kind, 'error', `重置失败的提示应为错误样式,实际 ${toast.kind}`)
507
+ assert.equal(toast.text, world.dicts.zh['toast.resetFailed'])
508
+ assert.notEqual(toast.text, world.dicts.zh['toast.reset'])
509
+ })
510
+
511
+ await check('C9 重置成功且丢弃过损坏文件时,提示「已备份」(而不是普通的「已重置」)', async () => {
512
+ const world = await boot()
513
+ world.routes['/api/soul/config/reset'] = () => ({
514
+ ok: true, config: { ...CONFIG }, changed: [], backupPath: '/x/soul-config.json.corrupt'
515
+ })
516
+ const toast = await clickButton(world, 'button.reset')
517
+ assert.equal(toast.kind, 'success')
518
+ assert.equal(toast.text, world.dicts.zh['toast.resetRecovered'])
519
+ })
520
+
521
+ await check('C10 普通重置只提示「已重置」,且不留残余的送达警告', async () => {
522
+ const world = await boot({ deliveryWarning: '旧的送达警告' })
523
+ world.routes['/api/soul/config/reset'] = () => ({ ok: true, config: { ...CONFIG }, changed: [], backupPath: null })
524
+ const toast = await clickButton(world, 'button.reset')
525
+ assert.equal(toast.text, world.dicts.zh['toast.reset'])
526
+ assert.equal(world.controller.store.getSnapshot().error, null, '重置后不应残留上一轮的送达警告')
527
+ })
528
+
529
+ await check('C11 保存失败弹「保存失败」,不得误报「配置无变化」', async () => {
530
+ const world = await boot()
531
+ world.routes['/api/soul/config'] = (call) => (call.method === 'GET'
532
+ ? { ok: true, config: { ...CONFIG } }
533
+ : { ok: false, error: '非法颜色' })
534
+ const toast = await clickButton(world, 'button.save')
535
+ assert.equal(toast.kind, 'error')
536
+ assert.equal(toast.text, world.dicts.zh['toast.saveFailed'])
537
+ assert.notEqual(toast.text, world.dicts.zh['toast.noChanges'])
538
+ })
539
+
540
+ await check('C12 设置页真的渲染出可点的保存 / 重置按钮(断言不是对着空树跑)', async () => {
541
+ const world = await boot()
542
+ const tree = await renderSettings(world)
543
+ const buttons = findAll(tree, (n) => n.type === 'ui-button')
544
+ assert.ok(buttons.length >= 2, `应至少有保存与重置两个按钮,实际 ${buttons.length}`)
545
+ const labels = buttons.map(textOf)
546
+ assert.ok(labels.includes(world.dicts.zh['button.save']), `未找到保存按钮:${labels.join(' / ')}`)
547
+ assert.ok(labels.includes(world.dicts.zh['button.reset']), `未找到重置按钮:${labels.join(' / ')}`)
548
+ assert.ok(buttons.every((b) => typeof b.props.onClick === 'function'), '按钮缺少 onClick')
549
+ // 反「空树也通过」:不仅要有按钮,还要真的渲染出了栏目与字段
550
+ const text = textOf(tree)
551
+ for (const key of ['settings.title', 'field.nickname', 'button.save', 'button.reset']) {
552
+ assert.ok(
553
+ text.includes(world.dicts.zh[key]),
554
+ `设置页缺少「${key}」对应的文案(${world.dicts.zh[key]}):${text}`
555
+ )
556
+ }
557
+ })
558
+
559
+ await check('C13 快捷开关保存失败时必须给出反馈(此前静默:按钮外观与文案都不变)', async () => {
560
+ const world = await boot()
561
+ world.routes['/api/soul/config'] = (call) => (call.method === 'GET'
562
+ ? { ok: true, config: { ...CONFIG } }
563
+ : false)
564
+ const button = await clickQuickToggle(world)
565
+ assert.equal(button.props['data-failed'], 'true', '失败后 data-failed 必须为 true')
566
+ assert.ok(
567
+ String(button.props.title || '').includes('boom'),
568
+ `失败原因要出现在 title 上,实际:${button.props.title}`
569
+ )
570
+ assert.equal(
571
+ button.props['aria-label'],
572
+ button.props.title,
573
+ 'aria-label 需与 title 一致(读屏用户同样要拿到失败原因)'
574
+ )
575
+ // 防空过:成功时该标记必须是 false,否则上面的断言等于写死
576
+ const ok = await boot()
577
+ const good = await clickQuickToggle(ok)
578
+ assert.equal(good.props['data-failed'], 'false', '成功时不应残留失败标记')
579
+ })
580
+
581
+ await check('C14 预设列表拉取失败时显示失败原因,不得永远停在「加载中...」', async () => {
582
+ const world = await boot()
583
+ world.routes['/api/soul/personas'] = () => false
584
+ // 人设分组默认折叠(Accordion 折叠时不渲染子节点),先像用户一样展开它
585
+ const closed = await renderSettings(world)
586
+ const triggers = findAll(closed, (n) => n.type === 'button' && textOf(n).includes(world.dicts.zh['group.personas']))
587
+ assert.equal(triggers.length, 1, `应恰好一个「人设预设」折叠标题,实际 ${triggers.length}`)
588
+ await triggers[0].props.onClick()
589
+ const text = textOf(await renderSettings(world))
590
+ const failedLabel = world.dicts.zh['personas.loadFailed'].split('{')[0]
591
+ assert.ok(text.includes(failedLabel), `应显示加载失败提示,实际渲染:${text.slice(0, 240)}`)
592
+ assert.ok(text.includes('boom'), '失败原因要一并显示')
593
+ assert.ok(
594
+ !text.includes(world.dicts.zh['status.loading']),
595
+ '失败后不得继续显示「加载中...」(此前是空 catch,personas 永为 null)'
596
+ )
597
+ // 防空过:正常加载时不应误报失败
598
+ const ok = await boot()
599
+ const okClosed = await renderSettings(ok)
600
+ const okTrigger = findAll(okClosed, (n) => n.type === 'button' && textOf(n).includes(world.dicts.zh['group.personas']))[0]
601
+ await okTrigger.props.onClick()
602
+ const okText = textOf(await renderSettings(ok))
603
+ assert.ok(!okText.includes(failedLabel), '正常加载不应误报失败')
604
+ })
605
+
606
+ await check('C15 只改首尾空格不算「未保存的更改」(与服务端 trim 判据一致)', async () => {
607
+ // 服务端对字符串字段一律 trim 后再落盘,客户端若按原始串比较 dirty,就会出现
608
+ // 「敲了个空格 → 保存按钮亮起 → 保存成功却提示『配置无变化』」这种自相矛盾的状态。
609
+ const world = await boot()
610
+ world.routes['/api/soul/config'] = (call) => (call.method === 'GET'
611
+ ? { ok: true, config: { ...CONFIG, nickname: 'NickLi6' } }
612
+ : { ok: true, config: { ...CONFIG, nickname: 'NickLi6' }, changed: [] })
613
+ await world.controller.loadConfig()
614
+ for (let i = 0; i < 6; i++) await new Promise((r) => drainTick(r))
615
+
616
+ const find = async () => findAll(await renderSettings(world), (n) => n.type === 'input' && n.props?.id === 'soul-nickname')
617
+ const inputs = await find()
618
+ assert.equal(inputs.length, 1, `应有一个昵称输入框,实际 ${inputs.length}`)
619
+ inputs[0].props.onChange({ target: { value: ' NickLi6 ' } })
620
+ for (let i = 0; i < 4; i++) await new Promise((r) => drainTick(r))
621
+ assert.ok(
622
+ !textOf(await renderSettings(world)).includes(world.dicts.zh['status.unsaved']),
623
+ '只加首尾空格不应被判成「未保存的更改」'
624
+ )
625
+ // 防空过:真有改动时必须提示,否则上面那条等于恒真
626
+ const inputs2 = await find()
627
+ inputs2[0].props.onChange({ target: { value: 'NickLi6-改过' } })
628
+ for (let i = 0; i < 4; i++) await new Promise((r) => drainTick(r))
629
+ assert.ok(
630
+ textOf(await renderSettings(world)).includes(world.dicts.zh['status.unsaved']),
631
+ '真有改动时必须提示「有未保存的更改」'
632
+ )
633
+ })
634
+
635
+ await check('C16 人设行真的按宿主协议渲染,且「当前生效」预设带 ★ 标记', async () => {
636
+ // 这条补的是一个**覆盖空洞**:此前桩返回 `{ personas: [], activePersona: null }`
637
+ // (字段名与类型都与宿主不符),于是人设行渲染与 ★ 标记从未被执行过 —— 把桩改成
638
+ // 真实形状后,整套 C 系列仍全绿(实测),说明没有任何断言吃过这份数据。
639
+ // 宿主真实协议:personas 是由 mergePersonas 生成的**对象 map**(恒含 7 个内置),
640
+ // activeName 是「与当前配置匹配」的预设名(client:1235 读的就是它)。
641
+ const world = await boot({}, {
642
+ ok: true,
643
+ personas: {
644
+ 苏格拉底式提问者: { style: 'professional', builtin: true },
645
+ 我的自建: { style: 'roast', emoji: 'more' }
646
+ },
647
+ activeName: '我的自建'
648
+ })
649
+ const closed = await renderSettings(world)
650
+ const triggers = findAll(closed, (n) => n.type === 'button' && textOf(n).includes(world.dicts.zh['group.personas']))
651
+ assert.equal(triggers.length, 1, '应有一个「人设预设」分组标题')
652
+ await triggers[0].props.onClick()
653
+ const tree = await renderSettings(world)
654
+
655
+ // ① activeName → store.activePersona 这条链路必须真的通(字段名写错就全灭)
656
+ assert.equal(
657
+ world.controller.store.getSnapshot().activePersona,
658
+ '我的自建',
659
+ 'activeName 未被写进 store.activePersona —— 字段名与宿主协议不符'
660
+ )
661
+
662
+ // ② 两行都渲染出来,且 line 文本各自完整
663
+ const rows = findAll(tree, (n) => typeof n.props?.className === 'string' && n.props.className.includes('soul-persona-row'))
664
+ assert.equal(rows.length, 2, `应渲染两行预设,实际 ${rows.length}`)
665
+ const rowText = rows.map(textOf)
666
+
667
+ // ③ 生效预设带 ★,非生效的不带(防空过:两个方向都要断言,否则「恒加★」也会过)
668
+ const activeRow = rowText.find((t) => t.includes('我的自建'))
669
+ const idleRow = rowText.find((t) => t.includes('苏格拉底式提问者'))
670
+ assert.ok(activeRow, `未渲染「我的自建」行:${rowText.join(' | ')}`)
671
+ assert.ok(idleRow, `未渲染「苏格拉底式提问者」行:${rowText.join(' | ')}`)
672
+ assert.ok(activeRow.includes('★'), `生效预设应带 ★:${activeRow}`)
673
+ assert.ok(!idleRow.includes('★'), `非生效预设不应带 ★:${idleRow}`)
674
+
675
+ // ④ 内置行带「内置」标记、且不渲染删除按钮;自建行相反
676
+ assert.ok(idleRow.includes(world.dicts.zh['personas.builtin']), `内置行应带「内置」标记:${idleRow}`)
677
+ assert.ok(!activeRow.includes(world.dicts.zh['personas.builtin']), `自建行不应带「内置」标记:${activeRow}`)
678
+ const deleteButtons = findAll(tree, (n) => n.type === 'button' && textOf(n) === world.dicts.zh['personas.delete'])
679
+ assert.equal(deleteButtons.length, 1, `只应有一个删除按钮(内置行不得有),实际 ${deleteButtons.length}`)
680
+ })
681
+
682
+ await check('C17 应用预设成功后清掉上一轮的失败提示', async () => {
683
+ // 该端点不返回 deliveryWarning;此前不清 error ⇒ 上一轮保存失败过的红色提示
684
+ // 会一直挂在设置页上,即使随后切预设成功。
685
+ const world = await boot()
686
+ world.routes['/api/soul/config'] = (call) => (call.method === 'GET' ? { ok: true, config: { ...CONFIG } } : false)
687
+ const failed = await world.controller.saveConfig({ style: 'casual' })
688
+ assert.equal(failed, undefined, '前置条件:保存失败应返回 undefined')
689
+ assert.equal(world.controller.store.getSnapshot().error, 'boom', '前置条件:失败原因应写进 store')
690
+ world.routes['/api/soul/personas/use'] = () => ({ ok: true, config: { ...CONFIG }, changed: ['style'], invalid: [] })
691
+ await world.controller.usePersona('任意')
692
+ assert.equal(world.controller.store.getSnapshot().error, null, '应用预设成功后不得残留上一轮的失败提示')
693
+ })
694
+ } finally {
695
+ restoreTimers()
696
+ }
697
+
698
+ if (!assertCount('verify-client', passed, EXPECTED_ASSERTIONS)) process.exit(1)
699
+
700
+ console.log(`\n全部通过:${passed} 项检查`)