dsh-codearts-dock 0.0.0-stage → 1.0.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.
Files changed (49) hide show
  1. package/DISCLAIMER.md +47 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/SECURITY.md +45 -0
  5. package/THIRD_PARTY_NOTICES.md +64 -0
  6. package/client.js +3491 -0
  7. package/cordis.patch.yml +10 -0
  8. package/docs/DETAIL.md +24 -0
  9. package/docs/DETAIL.zh.md +24 -0
  10. package/docs/PUBLISHING.md +43 -0
  11. package/docs/preview.svg +78 -0
  12. package/icons/dsh-connect-codearts-128.png +0 -0
  13. package/icons/dsh-connect-codearts-256.png +0 -0
  14. package/locale/en.json +7 -0
  15. package/locale/zh.json +7 -0
  16. package/package.json +88 -4
  17. package/scripts/build-market-index.mjs +24 -0
  18. package/scripts/check-legal.sh +33 -0
  19. package/scripts/check-release.mjs +29 -0
  20. package/scripts/test.mjs +11 -0
  21. package/src/account.js +217 -0
  22. package/src/accounts.js +481 -0
  23. package/src/adapter.js +715 -0
  24. package/src/backup.js +89 -0
  25. package/src/catalog.js +269 -0
  26. package/src/checkin.js +271 -0
  27. package/src/credentials.js +435 -0
  28. package/src/features.js +79 -0
  29. package/src/gateway.js +521 -0
  30. package/src/health.js +15 -0
  31. package/src/index.js +1029 -0
  32. package/src/models.js +147 -0
  33. package/src/paths.js +36 -0
  34. package/src/preferences.js +87 -0
  35. package/src/protocol/crypto.js +160 -0
  36. package/src/protocol/sign.js +176 -0
  37. package/src/protocol/sm4.js +264 -0
  38. package/src/protocol/sse.js +134 -0
  39. package/src/sts.js +118 -0
  40. package/test/accounts.test.mjs +344 -0
  41. package/test/adapter.test.mjs +234 -0
  42. package/test/assembler.test.mjs +86 -0
  43. package/test/features.test.mjs +240 -0
  44. package/test/live-probe.mjs +55 -0
  45. package/test/protocol.test.mjs +167 -0
  46. package/test/registration.test.mjs +303 -0
  47. package/test/sm4.test.mjs +64 -0
  48. package/test/ui.test.mjs +732 -0
  49. package/test/visual.test.mjs +420 -0
@@ -0,0 +1,732 @@
1
+ /** Offline interactions for the actual client components; no browser, network, or credentials. */
2
+ import assert from 'node:assert/strict'
3
+ import { readFileSync } from 'node:fs'
4
+ import vm from 'node:vm'
5
+
6
+ const source = readFileSync(new URL('../client.js', import.meta.url), 'utf8')
7
+ const initialModels = {
8
+ ok: true, source: 'cache', enabledIds: null, refreshedAt: 1,
9
+ models: [
10
+ { id: 'reasoner', name: 'Reasoner', strengths: ['high', 'max'], defaultStrength: 'max', allowOff: false, supportsImages: true, overrides: { images: true, allowOff: false, defaultStrength: 'max' }, ratio: '0.7x' },
11
+ { id: 'coder', name: 'Coder', strengths: [], supportsImages: false, overrides: null, ratio: '1x' },
12
+ ],
13
+ }
14
+
15
+ function harness(surface = 'settings', rootProps = {}) {
16
+ const postResponses = new Map()
17
+ const confirmations = []
18
+ const controls = { confirmAnswer: true, now: Date.now() }
19
+ let active
20
+ let cursor = 0
21
+ let SettingsPage
22
+ let ComposerChip
23
+ let currentTree
24
+ const instances = new Map()
25
+ const effects = []
26
+ const intervals = []
27
+ const pending = []
28
+ const writes = []
29
+ const copied = []
30
+ const downloads = []
31
+ const blobs = new Map()
32
+ const state = () => {
33
+ const index = cursor++
34
+ return [active, index]
35
+ }
36
+ const React = {
37
+ Fragment: Symbol('Fragment'),
38
+ createElement: (type, props, ...children) => ({ type, props: { ...props, children: children.flat(Infinity) } }),
39
+ useState: (initial) => {
40
+ const [instance, index] = state()
41
+ if (!(index in instance.hooks)) instance.hooks[index] = typeof initial === 'function' ? initial() : initial
42
+ return [instance.hooks[index], (value) => { instance.hooks[index] = typeof value === 'function' ? value(instance.hooks[index]) : value }]
43
+ },
44
+ useRef: (initial) => {
45
+ const [instance, index] = state()
46
+ return instance.hooks[index] ??= { current: initial }
47
+ },
48
+ useCallback: (fn, deps) => {
49
+ const [instance, index] = state()
50
+ const previous = instance.hooks[index]
51
+ if (!previous || deps.some((dep, i) => dep !== previous.deps[i])) {
52
+ instance.hooks[index] = { value: fn, deps }
53
+ }
54
+ return instance.hooks[index].value
55
+ },
56
+ useId: () => {
57
+ const [instance, index] = state()
58
+ return instance.hooks[index] ??= `test-${instances.size}-${index}`
59
+ },
60
+ useEffect: (fn, deps) => {
61
+ const [instance, index] = state()
62
+ const previous = instance.hooks[index]
63
+ if (!previous || !deps || deps.some((dep, i) => dep !== previous.deps[i])) {
64
+ instance.hooks[index] = { deps, cleanup: previous?.cleanup }
65
+ effects.push(() => {
66
+ previous?.cleanup?.()
67
+ instance.hooks[index].cleanup = fn()
68
+ })
69
+ }
70
+ },
71
+ }
72
+ const context = vm.createContext({
73
+ console, AbortController,
74
+ Date: class extends Date { static now() { return controls.now } },
75
+ Blob,
76
+ URL: {
77
+ createObjectURL: (blob) => { const url = `blob:offline-${blobs.size}`; blobs.set(url, blob); return url },
78
+ revokeObjectURL: (url) => blobs.delete(url),
79
+ },
80
+ document: {
81
+ documentElement: { lang: 'zh-CN' }, body: { appendChild() {} },
82
+ addEventListener() {}, removeEventListener() {},
83
+ createElement: (tag) => {
84
+ assert.equal(tag, 'a')
85
+ return { click() { downloads.push({ name: this.download, blob: blobs.get(this.href) }) }, remove() {} }
86
+ },
87
+ },
88
+ navigator: { language: 'zh-CN', clipboard: { writeText: async (text) => copied.push(text) } },
89
+ setInterval: (fn) => { intervals.push(fn); return intervals.length }, clearInterval() {},
90
+ fetch: async (url, options = {}) => {
91
+ const path = url.replace('/plugins/dsh-connect-codearts', '')
92
+ if (options.method === 'POST') {
93
+ const body = JSON.parse(options.body)
94
+ writes.push({ path, body })
95
+ const reply = postResponses.get(path)
96
+ const result = await (typeof reply === 'function' ? reply(body) : reply ?? { ok: true, enabled: 1 })
97
+ return { ok: true, text: async () => JSON.stringify(result) }
98
+ }
99
+ return new Promise((resolve, reject) => {
100
+ pending.push({ path, options, resolve: (body) => resolve({ ok: true, text: async () => JSON.stringify(body) }), reject })
101
+ })
102
+ },
103
+ window: { setTimeout: (fn) => fn(), confirm: (text) => { confirmations.push(text); return controls.confirmAnswer }, __ModuleLoader__: { load: (definition) => {
104
+ const module = definition.factory(() => React)
105
+ module.apply({ effect() {}, slots: {
106
+ inject: (_, fn) => fn(),
107
+ register: (seat, component) => {
108
+ if (seat.name === 'settings.section') SettingsPage = component
109
+ if (seat.name === 'conversation.input.right') ComposerChip = component
110
+ return () => {}
111
+ },
112
+ } })
113
+ } } },
114
+ })
115
+ vm.runInContext(source, context)
116
+
117
+ function render() {
118
+ const live = new Set()
119
+ function resolve(element, path) {
120
+ if (element === undefined || element === null || typeof element === 'boolean') return null
121
+ if (typeof element !== 'object') return element
122
+ if (typeof element.type === 'function') {
123
+ live.add(path)
124
+ let instance = instances.get(path)
125
+ if (!instance || instance.type !== element.type) {
126
+ instance = { type: element.type, hooks: [] }
127
+ instances.set(path, instance)
128
+ }
129
+ active = instance
130
+ cursor = 0
131
+ return resolve(element.type(element.props), `${path}/output`)
132
+ }
133
+ const result = { ...element, props: { ...element.props, children: element.props.children.map((child, i) => resolve(child, `${path}/${child?.props?.key ?? i}`)) } }
134
+ return result
135
+ }
136
+ currentTree = resolve(React.createElement(surface === 'settings' ? SettingsPage : ComposerChip, rootProps), 'root')
137
+ for (const [key, instance] of instances) {
138
+ if (!live.has(key)) {
139
+ instance.hooks.forEach((hook) => hook?.cleanup?.())
140
+ instances.delete(key)
141
+ }
142
+ }
143
+ effects.splice(0).forEach((run) => run())
144
+ return currentTree
145
+ }
146
+ function findAll(predicate, node = currentTree) {
147
+ if (!node || typeof node !== 'object') return []
148
+ return [...(predicate(node) ? [node] : []), ...node.props.children.flatMap((child) => findAll(predicate, child))]
149
+ }
150
+ function one(predicate) {
151
+ const matches = findAll(predicate)
152
+ assert.equal(matches.length, 1, `Expected one node, got ${matches.length}`)
153
+ return matches[0]
154
+ }
155
+ const text = (node) => typeof node === 'object' && node ? node.props.children.map(text).join('') : node ?? ''
156
+ async function settle(path, body) {
157
+ const index = pending.findIndex((request) => request.path === path)
158
+ assert.notEqual(index, -1, `Missing request ${path}`)
159
+ pending.splice(index, 1)[0].resolve(body)
160
+ await new Promise(setImmediate)
161
+ render()
162
+ }
163
+ async function fail(path) {
164
+ const index = pending.findIndex((request) => request.path === path)
165
+ assert.notEqual(index, -1, `Missing request ${path}`)
166
+ pending.splice(index, 1)[0].reject(new Error('Offline refresh failure'))
167
+ await new Promise(setImmediate)
168
+ render()
169
+ }
170
+ render()
171
+ return { render, findAll, one, text, settle, fail, pending, writes, intervals, copied, postResponses, confirmations, controls, downloads }
172
+ }
173
+
174
+ const app = harness()
175
+ assert.deepEqual(app.pending.map((request) => request.path).sort(), ['/account', '/accounts', '/models', '/status'])
176
+ const tab = (id) => app.one((node) => node.props.role === 'tab' && node.props.id.endsWith(`-tab-${id}`))
177
+ const panel = (id) => app.one((node) => node.props.role === 'tabpanel' && node.props.id.endsWith(`-panel-${id}`))
178
+ const button = (label) => app.one((node) => node.type === 'button' && app.text(node) === label)
179
+
180
+ await app.settle('/models', initialModels)
181
+ assert.match(app.text(panel('account')), /加载中/)
182
+ assert.doesNotMatch(app.text(panel('account')), /还没有账号/)
183
+ tab('models').props.onClick()
184
+ app.render()
185
+ assert.equal(panel('models').props.hidden, false)
186
+ assert.match(app.text(panel('models')), /本地缓存/)
187
+ let focused = false
188
+ tab('diagnostics').props.ref({ focus: () => { focused = true } })
189
+ tab('models').props.onKeyDown({ key: 'ArrowRight', preventDefault() {} })
190
+ app.render()
191
+ assert.equal(focused, true)
192
+ assert.equal(panel('diagnostics').props.hidden, false)
193
+ assert.match(app.text(panel('diagnostics')), /加载中/)
194
+ console.log('✓ fast model reads render before account probes; tab arrows move focus')
195
+
196
+ const reasoner = () => app.one((node) => node.type === 'input' && node.props['aria-label'] === 'Reasoner')
197
+ reasoner().props.onChange({ target: { checked: false } })
198
+ app.render()
199
+ tab('account').props.onClick()
200
+ app.render()
201
+ tab('models').props.onClick()
202
+ app.render()
203
+ assert.equal(reasoner().props.checked, false)
204
+ assert.match(app.text(panel('models')), /未保存/)
205
+ console.log('✓ switching panels preserves the model draft')
206
+
207
+ const savePromise = button('保存模型配置').props.onClick()
208
+ await new Promise(setImmediate)
209
+ assert.equal(app.writes[0].path, '/models/select')
210
+ assert.deepEqual(app.writes[0].body.enabledIds, ['coder'])
211
+ assert.deepEqual(app.writes[0].body.overrides.reasoner, { images: true, allowOff: false, defaultStrength: 'max' })
212
+ assert.equal(app.pending.filter((entry) => entry.path === '/models').length, 1)
213
+ assert.equal(app.pending.filter((entry) => entry.path === '/account').length, 1)
214
+ await app.settle('/models', { ...initialModels, enabledIds: ['coder'] })
215
+ await savePromise
216
+ app.render()
217
+ assert.equal(button('保存模型配置').props.disabled, true)
218
+ assert.match(app.text(panel('models')), /已保存/)
219
+ console.log('✓ save preserves existing overrides and completes without waiting for account probes')
220
+
221
+ const status = { ok: true, provider: 'codearts', catalog: { source: 'cache', models: 2, error: 'SECRET_ERROR', refreshedAt: 1 }, credential: { configured: true, source: 'file', savedAk: 'SECRET_AK', savedSk: 'SECRET_SK', sourceLabel: 'SECRET_LABEL', path: '/SECRET_PATH', candidates: [{ label: 'SECRET_CANDIDATE' }] }, registration: { configSchema: true, settingsNs: 'SECRET_NAMESPACE' }, settings: { gateway: 'https://SECRET_HOST' } }
222
+ await app.settle('/status', status)
223
+ await app.settle('/account', { ok: true, account: 'SECRET_ACCOUNT', userId: 'SECRET_USER', roles: ['SECRET_ROLE'], credit: { total: 1000, remain: 99 } })
224
+ await button('复制脱敏诊断信息').props.onClick()
225
+ const report = JSON.parse(app.copied[0])
226
+ assert.equal(report.catalog.hasError, true)
227
+ assert.equal(report.credential.savedAkSet, true)
228
+ assert.equal(report.credential.savedSkSet, true)
229
+ assert.ok(!app.copied[0].includes('SECRET'))
230
+ assert.equal(report.catalog.source, 'cache')
231
+ console.log('✓ copied diagnostics omit account identities, paths, gateway, credentials, and error text')
232
+
233
+ // Background polling must not interrupt a foreground model refresh.
234
+ const refreshButton = button('重读模型目录')
235
+ const refreshPromise = refreshButton.props.onClick()
236
+ await new Promise(setImmediate)
237
+ // The refresh route is deliberately a normal pending read in this harness.
238
+ await app.settle('/refresh', { ok: true })
239
+ const oldRequest = app.pending.find((request) => request.path === '/models')
240
+ app.intervals[0]()
241
+ await new Promise(setImmediate)
242
+ assert.equal(app.pending.filter((request) => request.path === '/models').length, 1, 'background polling does not abort a foreground refresh')
243
+ await app.settle('/models', { ...initialModels, source: 'gateway', enabledIds: ['coder'] })
244
+ await refreshPromise
245
+ assert.equal(oldRequest.options.signal.aborted, false)
246
+ console.log('✓ background polling leaves a foreground model refresh in progress')
247
+
248
+
249
+
250
+ // Exercise the new forms through SettingsPage with controlled HTTP responses.
251
+ const features = harness()
252
+ const fixtures = {
253
+ '/models': { ...initialModels, models: [
254
+ ...initialModels.models,
255
+ { id: 'expensive', name: 'Expensive', ratio: '9x', strengths: [], supportsImages: false },
256
+ { id: 'free', name: 'Free', ratio: '0x', strengths: [], supportsImages: false },
257
+ ] },
258
+ '/status': status,
259
+ '/account': { ok: true, credit: { total: 1000, remain: 99 } },
260
+ '/accounts': { ok: true, activeId: 'account-1', accounts: [{ id: 'account-1', label: 'Example', ak: 'TEST…MASK', isActive: true, health: { state: 'credentials', checkedAt: features.controls.now - 300000 }, error: 'RAW_GATEWAY_ERROR_FOR_DETAILS', credit: null, checkin: null }] },
261
+ }
262
+ const ft = (id) => features.one((node) => node.props.role === 'tab' && node.props.id.endsWith(`-tab-${id}`))
263
+ const fp = (id) => features.one((node) => node.props.role === 'tabpanel' && node.props.id.endsWith(`-panel-${id}`))
264
+ const fb = (label) => features.one((node) => node.type === 'button' && features.text(node) === label)
265
+ const labelled = (label, type = 'input') => {
266
+ const wrapper = features.one((node) => node.type === 'label' && features.text(node).startsWith(label))
267
+ const matches = features.findAll((node) => node.type === type, wrapper)
268
+ assert.equal(matches.length, 1)
269
+ return matches[0]
270
+ }
271
+ async function drain() {
272
+ await new Promise(setImmediate)
273
+ let turns = 0
274
+ while (features.pending.length && turns++ < 30) {
275
+ const path = features.pending[0].path
276
+ assert.ok(path in fixtures, `Unexpected offline request ${path}`)
277
+ await features.settle(path, fixtures[path])
278
+ }
279
+ assert.equal(features.pending.length, 0)
280
+ features.render()
281
+ }
282
+ async function act(fn) {
283
+ const promise = fn()
284
+ await drain()
285
+ await promise
286
+ features.render()
287
+ }
288
+ await drain()
289
+
290
+ assert.equal(features.findAll((node) => node.props.role === 'tab').length, 3)
291
+ assert.doesNotMatch(features.text(fp('account')), /余额提醒|自动签到/)
292
+ assert.ok(!features.pending.some((request) => ['/usage', '/preferences'].includes(request.path)))
293
+ console.log('✓ settings retain three tabs and never request retired alert or history data')
294
+ const checkTime = () => features.one((node) => node.type === 'time')
295
+ assert.equal(features.text(checkTime()), '5 分钟前')
296
+ assert.match(checkTime().props.title, /最近检查/)
297
+ assert.equal(checkTime().props.dateTime, new Date(features.controls.now - 300000).toISOString())
298
+ features.controls.now += 60000
299
+ features.intervals[1]()
300
+ features.render()
301
+ assert.equal(features.text(checkTime()), '6 分钟前')
302
+ const accountError = features.one((node) => node.type === 'details' && node.props.className === 'dca-details dca-account-error')
303
+ assert.notEqual(accountError.props.open, true)
304
+ assert.match(features.text(accountError), /RAW_GATEWAY_ERROR_FOR_DETAILS/)
305
+ console.log('✓ account check times advance without fetching; raw errors stay in collapsed details')
306
+
307
+
308
+ fb('更新凭证').props.onClick()
309
+ features.render(); features.render()
310
+ assert.match(features.text(fp('account')), /填写同一个 AK 和新的 SK/)
311
+ features.postResponses.set('/accounts/check', { ok: true, account: { label: 'Example', health: { state: 'available' } } })
312
+ await act(() => fb('重新检查').props.onClick())
313
+ assert.ok(features.writes.some((entry) => entry.path === '/accounts/check' && entry.body.id === 'account-1'))
314
+ console.log('✓ unhealthy accounts expose credential repair and account-specific rechecks')
315
+ assert.ok(!features.writes.some((entry) => entry.path.startsWith('/checkin')), 'loading and rechecking accounts never claims benefits')
316
+ features.postResponses.set('/checkin/claim-all', { ok: true, summary: { claimed: 1, failures: [] } })
317
+ await act(() => fb('一键签到').props.onClick())
318
+ const manualClaims = features.writes.filter((entry) => entry.path.startsWith('/checkin'))
319
+ assert.equal(manualClaims.length, 1)
320
+ assert.deepEqual(manualClaims[0], { path: '/checkin/claim-all', body: {} })
321
+ console.log('✓ check-in only runs on an explicit click and never sends automation preferences')
322
+
323
+
324
+ ft('models').props.onClick(); features.render()
325
+ const capability = (label, value) => { labelled(label).props.onChange({ target: { checked: value } }); features.render() }
326
+ capability('支持图片', true)
327
+ assert.equal(features.findAll((node) => node.type === 'input' && node.props['aria-label'] === 'Coder').length, 0)
328
+ assert.equal(features.findAll((node) => node.type === 'input' && node.props['aria-label'] === 'Reasoner').length, 1)
329
+ capability('支持图片', false)
330
+ capability('支持推理', true)
331
+ assert.equal(features.findAll((node) => node.type === 'input' && node.props['aria-label'] === 'Free').length, 0)
332
+ capability('支持推理', false)
333
+ assert.equal(features.findAll((node) => node.type === 'input' && node.props.maxLength === 48).length, 0)
334
+ const presetSelect = () => features.one((node) => node.type === 'select' && node.props['aria-label'] === '模型配置预设')
335
+ presetSelect().props.onChange({ target: { value: 'builtin:daily' } }); features.render()
336
+ const writesBeforePreview = features.writes.length
337
+ const previewList = features.one((node) => node.type === 'ul' && node.props.className === 'dca-preset-preview')
338
+ assert.match(features.text(previewList), /Free/)
339
+ assert.doesNotMatch(features.text(previewList), /Expensive/)
340
+ assert.equal(features.writes.length, writesBeforePreview)
341
+ fb('应用到草稿').props.onClick(); features.render()
342
+ assert.equal(features.writes.length, writesBeforePreview)
343
+ assert.equal(features.one((node) => node.type === 'input' && node.props['aria-label'] === 'Expensive').props.checked, false)
344
+ assert.match(features.text(fp('models')), /未保存/)
345
+ fb('保存为预设').props.onClick(); features.render()
346
+ const presetName = features.one((node) => node.type === 'input' && node.props.maxLength === 48)
347
+ presetName.props.onChange({ target: { value: 'My draft' } }); features.render()
348
+ features.postResponses.set('/presets', (body) => ({ ok: true, presets: [{ ...body, id: 'custom-1' }] }))
349
+ await act(() => features.one((node) => node.type === 'form' && features.findAll((child) => child.type === 'input' && child.props.maxLength === 48, node).length === 1).props.onSubmit({ preventDefault() {} }))
350
+ assert.equal(features.writes.at(-1).path, '/presets')
351
+ assert.equal(features.writes.at(-1).body.modelOverrides.reasoner.allowOff, false)
352
+ assert.ok(!features.writes.slice(writesBeforePreview).some((entry) => entry.path === '/models/select'))
353
+ console.log('✓ capability filters and presets preserve drafts, include zero-cost models, and never auto-save the live selection')
354
+
355
+ ft('account').props.onClick(); features.render()
356
+ const backupRoot = () => features.one((node) => node.type === 'details' && node.props.className === 'dca-card dca-details' && features.findAll((child) => child.type === 'summary' && features.text(child) === '配置备份与迁移', node).length === 1)
357
+ assert.equal(features.findAll((node) => node.type === 'input' && node.props.type === 'password' && node.props.autoComplete === 'new-password').length, 0)
358
+ assert.equal(features.findAll((node) => node.type === 'textarea' && node.props.rows === 4).length, 0, 'restore controls are absent in export mode')
359
+ assert.equal(fb('下载备份').props.disabled, false, 'config-only export needs no password by default')
360
+ labelled('加密备份').props.onChange({ target: { checked: true } }); features.render()
361
+ assert.equal(fb('下载备份').props.disabled, true)
362
+ labelled('加密密码').props.onChange({ target: { value: 'password-123' } })
363
+ labelled('确认加密密码').props.onChange({ target: { value: 'different' } }); features.render()
364
+ assert.equal(fb('下载备份').props.disabled, true)
365
+ labelled('确认加密密码').props.onChange({ target: { value: 'password-123' } }); features.render()
366
+ labelled('加密备份').props.onChange({ target: { checked: false } }); features.render()
367
+ assert.equal(features.findAll((node) => node.type === 'input' && node.props.autoComplete === 'new-password').length, 0)
368
+ labelled('包含账号凭证(AK/SK)').props.onChange({ target: { checked: true } }); features.render()
369
+ assert.equal(fb('下载备份').props.disabled, true)
370
+ assert.equal(labelled('加密密码').props.value, '', 'turning off encryption clears its password')
371
+ labelled('加密密码').props.onChange({ target: { value: 'password-123' } })
372
+ labelled('确认加密密码').props.onChange({ target: { value: 'password-123' } }); features.render()
373
+ assert.equal(fb('下载备份').props.disabled, false)
374
+ const backupForm = () => features.one((node) => node.type === 'form' && features.findAll((child) => child.type === 'button' && features.text(child) === '下载备份', node).length === 1)
375
+ const exportedEnvelope = { format: 'dsh-connect-codearts-encrypted', version: 1, data: 'fake-test-ciphertext' }
376
+ features.postResponses.set('/backup/export', { ok: true, backup: exportedEnvelope })
377
+ await act(() => backupForm().props.onSubmit({ preventDefault() {} }))
378
+ assert.equal(features.writes.at(-1).body.includeCredentials, true)
379
+ assert.equal(features.writes.at(-1).body.password, 'password-123')
380
+ assert.equal(features.downloads.length, 1)
381
+ assert.match(features.downloads[0].name, /^codearts-backup-\d{4}-\d{2}-\d{2}\.json$/)
382
+ assert.deepEqual(JSON.parse(await features.downloads[0].blob.text()), exportedEnvelope)
383
+ assert.equal(labelled('加密密码').props.value, '')
384
+ assert.equal(labelled('确认加密密码').props.value, '')
385
+ fb('恢复配置').props.onClick(); features.render()
386
+ assert.equal(features.findAll((node) => node.type === 'button' && features.text(node) === '下载备份').length, 0)
387
+ assert.equal(features.findAll((node) => node.type === 'input' && node.props.autoComplete === 'off' && node.props.type === 'password', backupRoot()).length, 0)
388
+ const advancedPaste = features.one((node) => node.type === 'details' && features.findAll((child) => child.type === 'summary' && features.text(child) === '粘贴 JSON(高级)', node).length === 1 && features.findAll((child) => child.type === 'textarea', node).length === 1 && node.props.className === 'dca-details')
389
+ assert.notEqual(advancedPaste.props.open, true)
390
+ const backupText = JSON.stringify(exportedEnvelope)
391
+ const inputFile = () => features.one((node) => node.type === 'input' && node.props.type === 'file' && node.props.accept === '.json,application/json')
392
+ await act(() => inputFile().props.onChange({ target: { value: 'file.json', files: [{ name: 'my-backup.json', size: backupText.length, text: async () => backupText }] } }))
393
+ assert.match(features.text(fp('account')), /已选择:my-backup.json/)
394
+ assert.equal(fb('读取并预览').props.disabled, true, 'encrypted files require a password')
395
+ labelled('解密密码').props.onChange({ target: { value: 'password-123' } }); features.render()
396
+ features.postResponses.set('/backup/preview', { ok: true, changes: ['composerChip'], preferences: { composerChip: false }, accounts: { added: 1, updated: 0 } })
397
+ await act(() => fb('读取并预览').props.onClick())
398
+ assert.equal(features.writes.at(-1).path, '/backup/preview')
399
+ assert.ok(!features.writes.some((entry) => entry.path === '/backup/restore'))
400
+ labelled('解密密码').props.onChange({ target: { value: 'new-password' } }); features.render()
401
+ assert.equal(features.findAll((node) => node.type === 'button' && features.text(node) === '确认恢复').length, 0)
402
+ await act(() => fb('读取并预览').props.onClick())
403
+ features.postResponses.set('/backup/restore', { ok: true, added: 1, updated: 0 })
404
+ await act(() => fb('确认恢复').props.onClick())
405
+ assert.equal(features.writes.at(-1).path, '/backup/restore')
406
+ assert.equal(features.writes.at(-1).body.text, backupText)
407
+ assert.equal(features.writes.at(-1).body.password, 'new-password')
408
+ assert.equal(labelled('备份内容(也可粘贴 JSON)', 'textarea').props.value, '')
409
+ assert.equal(features.findAll((node) => node.type === 'input' && node.props.autoComplete === 'off' && node.props.type === 'password', backupRoot()).length, 0)
410
+ console.log('✓ backup modes reveal only relevant forms; encryption, file selection, restore preview and input clearing work')
411
+
412
+ // Failed reads preserve input; selecting an invalid replacement never leaves a stale backup ready to restore.
413
+ labelled('备份内容(也可粘贴 JSON)', 'textarea').props.onChange({ target: { value: backupText } }); features.render()
414
+ labelled('解密密码').props.onChange({ target: { value: 'wrong-password' } }); features.render()
415
+ features.postResponses.set('/backup/preview', { ok: false, error: '密码错误,或备份文件已损坏' })
416
+ const restoreCount = features.writes.filter((entry) => entry.path === '/backup/restore').length
417
+ await act(() => fb('读取并预览').props.onClick())
418
+ assert.match(features.text(fp('account')), /密码错误/)
419
+ assert.equal(labelled('备份内容(也可粘贴 JSON)', 'textarea').props.value, backupText)
420
+ assert.equal(labelled('解密密码').props.value, 'wrong-password')
421
+ assert.equal(features.findAll((node) => node.type === 'button' && features.text(node) === '确认恢复').length, 0)
422
+ assert.equal(features.writes.filter((entry) => entry.path === '/backup/restore').length, restoreCount)
423
+ await act(() => inputFile().props.onChange({ target: { value: 'too-big.json', files: [{ name: 'too-big.json', size: 800000 }] } }))
424
+ assert.match(features.text(fp('account')), /备份文件过大/)
425
+ assert.equal(labelled('备份内容(也可粘贴 JSON)', 'textarea').props.value, '')
426
+ assert.equal(fb('读取并预览').props.disabled, true)
427
+ const plainBackup = '{"format":"dsh-connect-codearts-backup","version":1,"preferences":{}}'
428
+ labelled('备份内容(也可粘贴 JSON)', 'textarea').props.onChange({ target: { value: plainBackup } }); features.render()
429
+ assert.equal(features.findAll((node) => node.type === 'input' && node.props.autoComplete === 'off' && node.props.type === 'password', backupRoot()).length, 0)
430
+ features.postResponses.set('/backup/preview', { ok: true, changes: [], preferences: {}, accounts: { added: 0, updated: 0 } })
431
+ await act(() => fb('读取并预览').props.onClick())
432
+ assert.equal(features.writes.at(-1).body.password, '')
433
+ fb('导出配置').props.onClick(); features.render()
434
+ fb('恢复配置').props.onClick(); features.render()
435
+ assert.equal(features.findAll((node) => node.type === 'button' && features.text(node) === '确认恢复').length, 0, 'changing modes invalidates the preview')
436
+ console.log('✓ malformed replacements cannot restore stale contents; plain backups skip password inputs; mode changes invalidate previews')
437
+
438
+ // The composer is a compact account picker, not a second diagnostics page.
439
+ let openedSettings = 0
440
+ const chip = harness('composer', {
441
+ useProjection: () => ({ next: { provider: 'codearts' } }),
442
+ openSettings: () => { openedSettings += 1 },
443
+ })
444
+ const chipPool = { ok: true, accounts: [
445
+ { id: 'primary', label: 'Primary', active: true, credit: { remain: 42 }, health: { state: 'available' } },
446
+ { id: 'backup', label: 'Backup', credit: { remain: 13.25 }, health: { state: 'available' } },
447
+ { id: 'network', label: 'Network', error: 'RAW_NETWORK_ERROR', health: { state: 'network' } },
448
+ ] }
449
+ await chip.settle('/account', { ok: true, credit: { remain: 42 } })
450
+ await chip.settle('/accounts', chipPool)
451
+ chip.one((node) => node.props['aria-haspopup'] === 'dialog').props.onClick()
452
+ chip.render()
453
+ const dialog = () => chip.one((node) => node.props.role === 'dialog')
454
+ const chipRow = (name) => chip.one((node) => node.props['aria-label'] === `切换到 ${name}`)
455
+ assert.equal(chipRow('Primary').props.disabled, true)
456
+ assert.equal(chip.text(chipRow('Primary')), 'Primary当前选用')
457
+ assert.equal(chip.text(chipRow('Backup')), 'Backup')
458
+ assert.equal(chip.text(chipRow('Network')), 'Network网络异常')
459
+ assert.equal(chip.findAll((node) => node.props.title === 'RAW_NETWORK_ERROR', dialog()).length, 1)
460
+ assert.doesNotMatch(chip.text(dialog()), /RAW_NETWORK_ERROR/)
461
+ chipRow('Backup').props.onClick()
462
+ await new Promise(setImmediate)
463
+ assert.deepEqual(chip.writes.at(-1), { path: '/accounts/activate', body: { id: 'backup' } })
464
+ chip.render()
465
+ assert.match(chip.text(chipRow('Backup')), /正在切换/)
466
+ assert.doesNotMatch(chip.text(chipRow('Primary')), /正在切换/)
467
+ assert.equal(chipRow('Backup').props['aria-busy'], true)
468
+ assert.equal(chipRow('Network').props.disabled, true)
469
+ assert.equal(chip.findAll((node) => node.type === 'svg' && node.props.className?.includes('dca-pop-refresh-icon-spin')).length, 0, 'switching must not look like a refresh')
470
+ await chip.settle('/account', { ok: true, credit: { remain: 13.25 } })
471
+ await chip.settle('/accounts', { ok: true, accounts: chipPool.accounts.map((account) => ({ ...account, active: account.id === 'backup' })) })
472
+ assert.equal(chip.text(chipRow('Backup')), 'Backup当前选用')
473
+ assert.equal(chipRow('Backup').props['aria-busy'], false)
474
+ assert.match(chip.text(dialog()), /已切换到「Backup」/)
475
+ chip.postResponses.set('/accounts/activate', { ok: false, error: 'Switch refused' })
476
+ chipRow('Primary').props.onClick()
477
+ await new Promise(setImmediate); chip.render()
478
+ assert.equal(chipRow('Primary').props.disabled, false, 'failed account switches can be retried')
479
+ assert.equal(chip.text(chipRow('Backup')), 'Backup当前选用', 'failed switches keep the current account')
480
+ assert.match(chip.text(dialog()), /切换到「Primary」失败:Switch refused/)
481
+ assert.doesNotMatch(chip.text(dialog()), /已切换到「Backup」/)
482
+ chip.one((node) => node.props.className === 'dca-pop-settings').props.onClick()
483
+ chip.render()
484
+ assert.equal(openedSettings, 1)
485
+ assert.equal(chip.findAll((node) => node.props.role === 'dialog').length, 0)
486
+ const otherProvider = harness('composer', { useProjection: () => ({ next: { provider: 'another' } }) })
487
+ assert.equal(otherProvider.render(), null)
488
+ assert.equal(otherProvider.pending.length, 0)
489
+ console.log('✓ composer shows concise health states, keeps raw errors out of row text, and supports account switching')
490
+
491
+ // Pinned ordering is a preference independent of the unsaved model draft.
492
+ async function flushSettings(instance, responses) {
493
+ await new Promise(setImmediate)
494
+ let turns = 0
495
+ while (instance.pending.length && turns++ < 20) {
496
+ const path = instance.pending[0].path
497
+ assert.ok(path in responses, `Unexpected request ${path}`)
498
+ await instance.settle(path, responses[path])
499
+ }
500
+ assert.equal(instance.pending.length, 0)
501
+ instance.render()
502
+ }
503
+ const pins = harness()
504
+ const pinResponses = { ...fixtures, '/models': { ...fixtures['/models'], favoriteModelIds: ['coder'] } }
505
+ await flushSettings(pins, pinResponses)
506
+ pins.one((node) => node.props.role === 'tab' && node.props.id.endsWith('-tab-models')).props.onClick(); pins.render()
507
+ const modelOrder = () => pins.findAll((node) => node.type === 'div' && /^dca-model(?: |$)/.test(node.props.className ?? '')).map((node) => node.props.key)
508
+ const star = (label) => pins.one((node) => node.type === 'button' && node.props['aria-label'] === label)
509
+ assert.equal(modelOrder()[0], 'coder')
510
+ pins.one((node) => node.type === 'input' && node.props['aria-label'] === 'Reasoner').props.onChange({ target: { checked: false } }); pins.render()
511
+ pins.postResponses.set('/preferences/save', (body) => {
512
+ pinResponses['/models'] = { ...pinResponses['/models'], favoriteModelIds: body.favoriteModelIds }
513
+ return { ok: true, preferences: { favoriteModelIds: body.favoriteModelIds } }
514
+ })
515
+ star('置顶 Expensive').props.onClick()
516
+ await flushSettings(pins, pinResponses)
517
+ assert.deepEqual(pins.writes.at(-1), { path: '/preferences/save', body: { favoriteModelIds: ['coder', 'expensive'] } })
518
+ assert.deepEqual(modelOrder(), ['coder', 'expensive', 'reasoner', 'free'])
519
+ assert.equal(pins.one((node) => node.type === 'input' && node.props['aria-label'] === 'Reasoner').props.checked, false)
520
+ assert.ok(!pins.writes.some((entry) => entry.path === '/models/select'), 'pinning must not save the live selection')
521
+ const modelSaveStatus = () => pins.one((node) => node.props.className === 'dca-save-status')
522
+ assert.equal(pins.text(modelSaveStatus()), '有未保存的模型配置', 'pin success must not hide the unsaved settings status')
523
+ assert.match(pins.text(pins.render()), /常用置顶已保存/)
524
+ assert.match(pins.text(pins.render()), /置顶即时保存/)
525
+ assert.equal(pins.one((node) => node.type === 'button' && pins.text(node) === '保存模型配置').props.disabled, false)
526
+ pins.one((node) => node.type === 'select' && node.props['aria-label'] === '模型排序').props.onChange({ target: { value: 'ratio' } }); pins.render()
527
+ assert.deepEqual(modelOrder(), ['coder', 'expensive', 'free', 'reasoner'])
528
+ pins.one((node) => node.type === 'input' && node.props.type === 'search').props.onChange({ target: { value: 'Reasoner' } }); pins.render()
529
+ assert.deepEqual(modelOrder(), ['reasoner'], 'pinned models still obey search filters')
530
+ pins.one((node) => node.type === 'input' && node.props.type === 'search').props.onChange({ target: { value: '' } }); pins.render()
531
+ star('取消置顶 Coder').props.onClick()
532
+ await flushSettings(pins, pinResponses)
533
+ assert.deepEqual(modelOrder(), ['expensive', 'free', 'reasoner', 'coder'])
534
+ pins.postResponses.set('/preferences/save', { ok: false, error: 'Cannot save pinned models' })
535
+ star('置顶 Free').props.onClick()
536
+ await flushSettings(pins, pinResponses)
537
+ assert.equal(star('置顶 Free').props['aria-pressed'], false, 'failed writes must not appear persisted')
538
+ assert.match(pins.text(pins.render()), /Cannot save pinned models/)
539
+ assert.equal(pins.text(modelSaveStatus()), '有未保存的模型配置', 'pin errors must remain separate from the model draft status')
540
+ pins.one((node) => node.type === 'input' && node.props['aria-label'] === 'Coder').props.onChange({ target: { checked: false } })
541
+ pins.one((node) => node.type === 'input' && node.props['aria-label'] === 'Expensive').props.onChange({ target: { checked: false } })
542
+ pins.one((node) => node.type === 'input' && node.props['aria-label'] === 'Free').props.onChange({ target: { checked: false } })
543
+ pins.render()
544
+ star('置顶 Free').props.onClick()
545
+ await flushSettings(pins, pinResponses)
546
+ assert.equal(pins.text(modelSaveStatus()), '请至少启用一个模型后保存', 'favorite errors must not hide the empty-selection guidance')
547
+ assert.equal(pins.one((node) => node.type === 'button' && pins.text(node) === '保存模型配置').props.disabled, true)
548
+ console.log('✓ pinned models lead each sort, obey filters, persist separately, and preserve unsaved drafts on success and failure')
549
+
550
+ // Deferred writes expose progress before acknowledgement and before the subsequent reload.
551
+ const switching = harness()
552
+ const switchResponses = { ...fixtures, '/accounts': { ok: true, accounts: [
553
+ { id: 'personal', label: '个人', active: true, health: { state: 'available' } },
554
+ { id: 'work', label: '工作', active: false, health: { state: 'available' } },
555
+ ] } }
556
+ await flushSettings(switching, switchResponses)
557
+ const accountRow = (id) => switching.one((node) => node.type === 'div' && node.props.key === id && node.props.className?.startsWith('dca-pool-row'))
558
+ const accountButton = (id, label) => {
559
+ const matches = switching.findAll((node) => node.type === 'button' && switching.text(node) === label, accountRow(id))
560
+ assert.equal(matches.length, 1)
561
+ return matches[0]
562
+ }
563
+ let finishSwitch
564
+ switching.postResponses.set('/accounts/activate', () => new Promise((resolve) => { finishSwitch = resolve }))
565
+ const pendingSwitch = accountButton('work', '切换').props.onClick()
566
+ switching.render()
567
+ assert.equal(accountButton('work', '正在切换…').props.disabled, true)
568
+ assert.equal(accountButton('work', '正在切换…').props['aria-busy'], true)
569
+ assert.equal(accountButton('work', '重新检查').props.disabled, true)
570
+ assert.equal(accountButton('personal', '重新检查').props.disabled, true)
571
+ assert.doesNotMatch(switching.text(accountRow('personal')), /正在切换/)
572
+ assert.equal(switching.findAll((node) => node.type === 'button' && switching.text(node) === '加载中…').length, 0)
573
+ assert.equal(switching.pending.length, 0, 'reload waits for activation acknowledgement')
574
+ finishSwitch({ ok: true })
575
+ await new Promise(setImmediate); switching.render()
576
+ assert.match(switching.text(accountRow('work')), /正在切换/)
577
+ switchResponses['/accounts'] = { ok: true, accounts: switchResponses['/accounts'].accounts.map((account) => ({ ...account, active: account.id === 'work' })) }
578
+ await flushSettings(switching, switchResponses)
579
+ await pendingSwitch; switching.render()
580
+ assert.match(switching.text(accountRow('work')), /已切换到「工作」/)
581
+ assert.doesNotMatch(switching.text(accountRow('personal')), /已切换到/)
582
+ assert.equal(accountRow('work').props['aria-busy'], false)
583
+ assert.equal(accountButton('personal', '切换').props.disabled, false)
584
+ switching.postResponses.set('/accounts/activate', { ok: false, error: 'Switch refused' })
585
+ await accountButton('personal', '切换').props.onClick(); switching.render()
586
+ assert.match(switching.text(accountRow('personal')), /切换到「个人」失败:Switch refused/)
587
+ assert.equal(switching.findAll((node) => node.props.role === 'alert', accountRow('personal')).length, 1)
588
+ assert.equal(accountButton('personal', '切换').props.disabled, false)
589
+ assert.match(accountRow('work').props.className, /dca-pool-row-current/)
590
+ assert.doesNotMatch(switching.text(accountRow('work')), /Switch refused|已切换到/)
591
+ switching.postResponses.set('/accounts/activate', () => { throw new Error('Offline switch') })
592
+ await accountButton('personal', '切换').props.onClick(); switching.render()
593
+ assert.match(switching.text(accountRow('personal')), /切换到「个人」失败:Offline switch/)
594
+ assert.equal(accountButton('personal', '切换').props.disabled, false)
595
+ console.log('✓ account switches show progress and outcomes on the target row, preserve current state on failure, and allow retry')
596
+
597
+ // Account import is a read-only preview of the entire confirmed batch.
598
+ const imports = harness()
599
+ await flushSettings(imports, fixtures)
600
+ const importFile = () => imports.one((node) => node.type === 'input' && node.props.type === 'file' && node.props.accept.includes('.csv'))
601
+ const importDialog = () => imports.one((node) => node.props.role === 'dialog' && node.props.className === 'dca-transfer-dialog')
602
+ const importButton = (label) => {
603
+ const matches = imports.findAll((node) => node.type === 'button' && imports.text(node) === label, importDialog())
604
+ assert.equal(matches.length, 1)
605
+ return matches[0]
606
+ }
607
+ const importText = 'OFFLINE_AK_1,OFFLINE_SK_1\nOFFLINE_AK_2,OFFLINE_SK_2'
608
+ imports.postResponses.set('/accounts/preview', { ok: true, total: 2, accounts: [
609
+ { index: 0, label: '个人', akMasked: 'OFF…ONE' },
610
+ { index: 1, akMasked: 'OFF…TWO' },
611
+ ] })
612
+ const chooseImport = async () => {
613
+ importFile().props.onChange({ target: { value: 'credentials.csv', files: [{ text: async () => importText }] } })
614
+ await flushSettings(imports, fixtures)
615
+ }
616
+ await chooseImport()
617
+ assert.match(imports.text(importDialog()), /将导入以下 2 个账号/)
618
+ assert.equal(imports.findAll((node) => node.type === 'li', importDialog()).length, 2)
619
+ assert.equal(imports.findAll((node) => node.type === 'input' || node.type === 'label', importDialog()).length, 0, 'the preview must not imply per-account selection')
620
+ assert.match(imports.text(importDialog()), /个人OFF…TWO/)
621
+ assert.doesNotMatch(imports.text(importDialog()), /OFFLINE_SK|OFFLINE_AK/)
622
+ assert.ok(!imports.writes.some((write) => write.path === '/accounts/import'))
623
+ importButton('取消').props.onClick(); imports.render()
624
+ assert.equal(imports.findAll((node) => node.props.className === 'dca-transfer-dialog').length, 0)
625
+ assert.ok(!imports.writes.some((write) => write.path === '/accounts/import'), 'cancel does not write any accounts')
626
+ await chooseImport()
627
+ imports.postResponses.set('/accounts/import', { ok: true, added: 2, updated: 0, skipped: 0 })
628
+ const importing = importButton('导入 2 个').props.onClick()
629
+ await flushSettings(imports, fixtures)
630
+ await importing; imports.render()
631
+ assert.deepEqual(imports.writes.at(-1), { path: '/accounts/import', body: { text: importText } })
632
+ assert.equal(imports.findAll((node) => node.props.className === 'dca-transfer-dialog').length, 0)
633
+ console.log('✓ account import previews a plain list with the confirmed batch count and only writes after confirmation')
634
+
635
+ const balances = harness()
636
+ const checkedAt = balances.controls.now - 300000
637
+ const balanceResponses = { ...fixtures,
638
+ '/account': { ok: true, accountId: 'primary', creditIdentity: 'primary-key', credit: { remain: 20 }, creditCheckedAt: checkedAt },
639
+ '/accounts': { ok: true, accounts: [
640
+ { id: 'primary', creditIdentity: 'primary-key', label: 'Primary', credit: { remain: 20 }, creditCheckedAt: checkedAt },
641
+ { id: 'backup', creditIdentity: 'backup-key', label: 'Backup', credit: { remain: 0 }, creditCheckedAt: checkedAt },
642
+ ] },
643
+ }
644
+ await flushSettings(balances, balanceResponses)
645
+ const balanceCell = (name) => {
646
+ const row = balances.one((node) => node.type === 'div' && /^dca-pool-row(?: dca-pool-row-current)?$/.test(node.props.className ?? '') && balances.text(node).includes(name))
647
+ return balances.findAll((node) => node.props.className === 'dca-pool-credits-row', row)[0]
648
+ }
649
+ balanceResponses['/accounts'] = { ok: true, accounts: balanceResponses['/accounts'].accounts.map((account) => ({ ...account, credit: null, creditCheckedAt: null, health: { state: 'network' } })) }
650
+ balances.intervals[0]()
651
+ await flushSettings(balances, balanceResponses)
652
+ assert.match(balances.text(balanceCell('Primary')), /20.*上次结果.*5 分钟前/)
653
+ assert.match(balances.text(balanceCell('Backup')), /0.*上次结果.*5 分钟前/, 'zero is a successful balance too')
654
+ balances.controls.now += 120000
655
+ balances.intervals[1]()
656
+ balances.intervals[0]()
657
+ await balances.fail('/accounts')
658
+ await flushSettings(balances, balanceResponses)
659
+ assert.match(balances.text(balanceCell('Primary')), /20.*上次结果.*7 分钟前/, 'failed reads must not move the success timestamp')
660
+ balanceResponses['/accounts'] = { ok: true, accounts: [{ id: 'primary', creditIdentity: 'primary-key', label: 'Primary', credit: { remain: 0 }, creditCheckedAt: balances.controls.now }] }
661
+ balances.intervals[0]()
662
+ await flushSettings(balances, balanceResponses)
663
+ assert.equal(balances.text(balanceCell('Primary')), '0')
664
+ balanceResponses['/accounts'] = { ok: true, accounts: [{ id: 'primary', creditIdentity: 'replaced-key', label: 'Primary', credit: null }] }
665
+ balances.intervals[0]()
666
+ await flushSettings(balances, balanceResponses)
667
+ assert.equal(balances.text(balanceCell('Primary')), '—', 'new credentials must not inherit an old credential snapshot')
668
+ console.log('✓ settings retain successful balances and timestamps on gateway and route failures, recover zero balances, and isolate credential identities')
669
+
670
+ const staleChip = harness('composer', { useProjection: () => ({ next: { provider: 'codearts' } }) })
671
+ const chipCheckedAt = staleChip.controls.now - 300000
672
+ const currentAccount = { ok: true, accountId: 'primary', creditIdentity: 'primary-key', credit: { remain: 20 }, creditCheckedAt: chipCheckedAt }
673
+ const currentPool = { ok: true, accounts: [
674
+ { id: 'primary', creditIdentity: 'primary-key', active: true, label: 'Primary', credit: { remain: 20 }, creditCheckedAt: chipCheckedAt },
675
+ { id: 'backup', creditIdentity: 'backup-key', active: false, label: 'Backup', credit: { remain: 0 }, creditCheckedAt: chipCheckedAt },
676
+ ] }
677
+ await staleChip.settle('/account', currentAccount)
678
+ await staleChip.settle('/accounts', currentPool)
679
+ const chipTrigger = () => staleChip.one((node) => node.props['aria-haspopup'] === 'dialog')
680
+ const chipRefresh = () => staleChip.one((node) => node.props.className === 'dca-pop-refresh')
681
+ chipTrigger().props.onClick(); staleChip.render()
682
+ const failedRefresh = chipRefresh().props.onClick()
683
+ await staleChip.fail('/account')
684
+ await staleChip.fail('/accounts')
685
+ await failedRefresh; staleChip.render()
686
+ assert.equal(staleChip.text(chipTrigger()), '◈上次积分 20')
687
+ assert.match(staleChip.text(staleChip.render()), /积分刷新失败,显示上次结果/)
688
+ assert.match(staleChip.text(staleChip.render()), /5 分钟前/)
689
+ assert.equal(staleChip.text(chipRefresh()).includes('重试'), true)
690
+ const nullRefresh = chipRefresh().props.onClick()
691
+ await staleChip.settle('/account', { ...currentAccount, credit: null, creditCheckedAt: null })
692
+ await staleChip.settle('/accounts', { ok: true, accounts: currentPool.accounts.map((account) => ({ ...account, credit: null, creditCheckedAt: null })) })
693
+ await nullRefresh; staleChip.render()
694
+ assert.equal(staleChip.text(chipTrigger()), '◈上次积分 20', 'an HTTP success without credit data is still a failed credit read')
695
+ const gatewayError = chipRefresh().props.onClick()
696
+ await staleChip.settle('/account', { ok: false, stage: 'gateway', error: 'offline gateway error' })
697
+ await staleChip.settle('/accounts', { ok: false, error: 'offline gateway error' })
698
+ await gatewayError; staleChip.render()
699
+ assert.equal(staleChip.text(chipTrigger()), '◈上次积分 20', 'HTTP-200 error payloads must retain last successful values too')
700
+ const recovery = chipRefresh().props.onClick()
701
+ await staleChip.settle('/account', { ...currentAccount, credit: { remain: 7 }, creditCheckedAt: staleChip.controls.now })
702
+ await staleChip.settle('/accounts', { ok: true, accounts: currentPool.accounts.map((account) => ({ ...account, credit: { remain: account.id === 'primary' ? 7 : 0 } })) })
703
+ await recovery; staleChip.render()
704
+ assert.equal(staleChip.text(chipTrigger()), '◈积分 7')
705
+ assert.equal(staleChip.findAll((node) => node.props.className === 'dca-credit-status').length, 0)
706
+ // An older background response must not overwrite a newer manual refresh.
707
+ staleChip.intervals[0]()
708
+ const olderReads = staleChip.pending.splice(0)
709
+ const newestRefresh = chipRefresh().props.onClick()
710
+ await staleChip.settle('/account', { ...currentAccount, credit: { remain: 9 }, creditCheckedAt: staleChip.controls.now })
711
+ await staleChip.settle('/accounts', currentPool)
712
+ await newestRefresh
713
+ for (const request of olderReads) request.resolve(request.path === '/account' ? { ...currentAccount, credit: { remain: 999 } } : currentPool)
714
+ await new Promise(setImmediate); staleChip.render()
715
+ assert.equal(staleChip.text(chipTrigger()), '◈积分 9', 'late background responses cannot restore an older value')
716
+ staleChip.one((node) => node.props['aria-label'] === '切换到 Backup').props.onClick()
717
+ await new Promise(setImmediate); staleChip.render()
718
+ assert.doesNotMatch(staleChip.text(chipTrigger()), /9/, 'switching clears the previous account headline immediately')
719
+ await staleChip.settle('/account', { ok: true, accountId: 'backup', creditIdentity: 'backup-key', credit: null })
720
+ await staleChip.settle('/accounts', { ok: true, accounts: currentPool.accounts.map((account) => ({ ...account, active: account.id === 'backup' })) })
721
+ assert.doesNotMatch(staleChip.text(chipTrigger()), /9/, 'failed reads for the new account cannot reuse the previous account balance')
722
+ console.log('✓ composer retains last values on refresh failures, exposes retry and timestamps, clears stale markers on recovery, and isolates account switches')
723
+
724
+ const unreadChip = harness('composer', { useProjection: () => ({ next: { provider: 'codearts' } }) })
725
+ await unreadChip.fail('/account')
726
+ await unreadChip.fail('/accounts')
727
+ unreadChip.one((node) => node.props['aria-haspopup'] === 'dialog').props.onClick(); unreadChip.render()
728
+ assert.match(unreadChip.text(unreadChip.render()), /积分暂时无法读取,请重试/)
729
+ assert.doesNotMatch(unreadChip.text(unreadChip.render()), /上次积分|积分 0/)
730
+ console.log('✓ first-time credit failures show an actionable state without inventing a cached balance')
731
+
732
+ console.log('\nui: all checks passed')