dsh-codearts-dock 1.0.0 → 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.
@@ -1,4 +1,4 @@
1
- /** All five features against real local storage and fake gateway/host boundaries. */
1
+ /** Account health, model presets and encrypted migration against isolated local storage. */
2
2
  import assert from 'node:assert/strict'
3
3
  import { mkdtemp, readFile, stat, rm } from 'node:fs/promises'
4
4
  import { tmpdir } from 'node:os'
@@ -13,35 +13,35 @@ delete process.env.CODEARTS_SK
13
13
  delete process.env.CODEARTS_SECURITY_TOKEN
14
14
  const { FEATURE_DEFAULTS, validatePreferences, persistPreferences, readPreferences, portablePreferences } = await import('../src/preferences.js')
15
15
  const { encodeBackup, decodeBackup } = await import('../src/backup.js')
16
- const { createUsageStore, USAGE_LIMIT } = await import('../src/usage.js')
17
- const { accountHealth, isLowBalance } = await import('../src/health.js')
16
+ const { accountHealth } = await import('../src/health.js')
18
17
  const { readCredit } = await import('../src/account.js')
19
18
  const accounts = await import('../src/accounts.js')
20
- const { createCodeArtsAdapter } = await import('../src/adapter.js')
21
- const { Catalog } = await import('../src/catalog.js')
22
19
  const results = []
23
20
  const check = async (name, fn) => {
24
21
  try { await fn(); results.push(`✓ ${name}`) } catch (error) { results.push(`✗ ${name}\n${error.stack}`); process.exitCode = 1 }
25
22
  }
26
- const settings = { ...FEATURE_DEFAULTS, enabledModelIds: null, modelOverrides: {}, autoCheckin: false, composerChip: true, refreshIntervalMs: 300000 }
23
+ const settings = { ...FEATURE_DEFAULTS, enabledModelIds: null, modelOverrides: {}, composerChip: true, refreshIntervalMs: 300000 }
27
24
  const preferences = portablePreferences(settings)
28
25
  const secretAccount = { ak: 'TEST_BACKUP_AK_123456789', sk: 'TEST_BACKUP_SK_987654321', label: 'Example' }
29
26
 
30
- await check('alert thresholds reject invalid data and distinguish unknown from zero balance', async () => {
31
- assert.equal(isLowBalance({ remain: 10 }, { ...settings, lowBalanceThreshold: 20 }), true)
32
- assert.equal(isLowBalance({ remain: 20 }, { ...settings, lowBalanceThreshold: 20 }), false)
33
- assert.equal(isLowBalance({ remain: 0 }, settings), true)
34
- assert.equal(isLowBalance(null, settings), false)
35
- assert.equal(isLowBalance({ remain: 10 }, { ...settings, lowBalanceEnabled: false }), false)
36
- for (const invalid of [-1, NaN, Infinity, '500', 1e10]) assert.throws(() => validatePreferences({ lowBalanceThreshold: invalid }))
27
+ await check('preferences validate retained settings and ignore retired alert and history fields', async () => {
28
+ for (const invalid of [-1, 0, '60000', 86400001]) assert.throws(() => validatePreferences({ refreshIntervalMs: invalid }))
29
+ assert.throws(() => validatePreferences({ composerChip: 'true' }))
30
+ for (const favoriteModelIds of [null, 'model', [5], ['__proto__'], Array(501).fill('model')]) assert.throws(() => validatePreferences({ favoriteModelIds }))
31
+ assert.deepEqual(validatePreferences({ favoriteModelIds: ['b', 'a', 'b'] }), { favoriteModelIds: ['b', 'a'] })
37
32
  assert.throws(() => validatePreferences({ enabledModelIds: [], modelOverrides: {} }))
38
33
  assert.throws(() => validatePreferences(JSON.parse('{"modelOverrides":{"__proto__":{"images":true}}}')))
39
34
  assert.throws(() => validatePreferences({ modelPresets: Array(21).fill({}) }))
35
+ assert.deepEqual(validatePreferences({ lowBalanceEnabled: true, lowBalanceThreshold: 500, usageEnabled: true, autoCheckin: true, composerChip: true }), { composerChip: true })
36
+ const portable = portablePreferences({ ...settings, lowBalanceEnabled: true, usageEnabled: true, autoCheckin: true })
37
+ assert.ok(!('lowBalanceEnabled' in portable))
38
+ assert.ok(!('usageEnabled' in portable))
39
+ assert.ok(!('autoCheckin' in portable))
40
40
  })
41
41
  await check('concurrent preference writes are atomic, private, and do not lose other keys', async () => {
42
- await Promise.all([persistPreferences({ lowBalanceThreshold: 250 }), persistPreferences({ usageEnabled: false }), persistPreferences({ autoCheckin: false })])
43
- assert.equal(readPreferences().lowBalanceThreshold, 250)
44
- assert.equal(readPreferences().usageEnabled, false)
42
+ await Promise.all([persistPreferences({ refreshIntervalMs: 120000 }), persistPreferences({ composerChip: false }), persistPreferences({ modelPresets: [] })])
43
+ assert.equal(readPreferences().refreshIntervalMs, 120000)
44
+ assert.equal(readPreferences().composerChip, false)
45
45
  const mode = (await stat(join(scratch, 'dsh-connect-codearts', 'preferences.json'))).mode & 0o777
46
46
  assert.equal(mode, 0o600)
47
47
  })
@@ -61,6 +61,8 @@ await check('plain backups contain only preferences, encrypted backups round-tri
61
61
  assert.equal(plain.accounts, undefined)
62
62
  assert.ok(!JSON.stringify(plain).includes(secretAccount.ak))
63
63
  assert.deepEqual((await decodeBackup(JSON.stringify(plain))).preferences, preferences)
64
+ const legacy = { ...plain, preferences: { ...plain.preferences, lowBalanceEnabled: true, lowBalanceThreshold: 500, usageEnabled: true, autoCheckin: true } }
65
+ assert.deepEqual((await decodeBackup(JSON.stringify(legacy))).preferences, preferences)
64
66
  await assert.rejects(encodeBackup({ preferences, accounts: [secretAccount], includeCredentials: true, password: '' }))
65
67
  await assert.rejects(encodeBackup({ preferences, accounts: [secretAccount, { ...secretAccount, ak: ` ${secretAccount.ak} ` }], includeCredentials: true, password: 'test-password-123' }), /重复账号/)
66
68
  const encrypted = await encodeBackup({ preferences, accounts: [secretAccount], activeAccountId: accounts.accountIdOf(secretAccount.ak), includeCredentials: true, password: 'test-password-123' })
@@ -74,52 +76,6 @@ await check('plain backups contain only preferences, encrypted backups round-tri
74
76
  await assert.rejects(decodeBackup(JSON.stringify({ ...plain, accounts: [secretAccount] })), /必须为加密/)
75
77
  await assert.rejects(decodeBackup(JSON.stringify({ ...plain, version: 99 })))
76
78
  })
77
- await check('usage is bounded and stores only metadata, with disable and in-flight clear guards', async () => {
78
- let enabled = true
79
- const usage = createUsageStore({ directory: join(scratch, 'usage-tests'), enabled: () => enabled })
80
- const epoch = usage.generation()
81
- await usage.record({ at: Date.now(), model: 'test-model', status: 'success', durationMs: 50, inputTokens: 10, outputTokens: 2, prompt: 'PRIVATE_PROMPT', account: 'PRIVATE_ACCOUNT', sk: 'PRIVATE_SK' }, epoch)
82
- const saved = await readFile(join(scratch, 'usage-tests', 'usage.json'), 'utf8')
83
- assert.ok(!saved.includes('PRIVATE'))
84
- assert.equal((await stat(join(scratch, 'usage-tests', 'usage.json'))).mode & 0o777, 0o600)
85
- enabled = false
86
- const disabledEpoch = usage.generation()
87
- await usage.record({ model: 'not-recorded' }, epoch)
88
- assert.equal(usage.list().records.length, 1)
89
- enabled = true
90
- await usage.record({ model: 'started-while-disabled' }, disabledEpoch)
91
- assert.equal(usage.list().records.length, 1)
92
- await usage.clear()
93
- await usage.record({ model: 'stale-in-flight' }, epoch)
94
- assert.equal(usage.list().records.length, 0)
95
- // Queue several writes together to exercise disk ordering without a gateway.
96
- await Promise.all(Array.from({ length: USAGE_LIMIT + 3 }, (_, i) => usage.record({ model: `model-${i}`, status: 'success' })))
97
- assert.equal(usage.list().records.length, USAGE_LIMIT)
98
- assert.equal(usage.list().records[0].model, `model-${USAGE_LIMIT + 2}`)
99
- assert.equal(createUsageStore({ directory: join(scratch, 'usage-tests') }).list().records.length, USAGE_LIMIT)
100
- })
101
- await check('real adapter records success, upstream failure, credential failure and cancellation without contents', async () => {
102
- const catalog = new Catalog(); catalog.current = [{ id: 'm', name: 'Model', strengths: [] }]
103
- async function run(chunks, failCredentials = false, cancel = false) {
104
- const recorded = []
105
- const adapter = createCodeArtsAdapter({
106
- catalog, credentials: { resolve: async () => { if (failCredentials) throw new Error('PRIVATE_CREDENTIAL'); return { key: { ak: 'TEST', sk: 'TEST' } } } },
107
- createClient: () => ({ heartbeat: async () => {}, streamChat: async function* () { for (const chunk of chunks) { if (chunk instanceof Error) throw chunk; yield chunk } } }),
108
- usage: { generation: () => 0, record: async (row) => recorded.push(row) },
109
- })
110
- try {
111
- for await (const chunk of adapter.stream({ model: 'm', provider: 'codearts', messages: [{ role: 'user', content: [{ type: 'text', text: 'PRIVATE_PROMPT' }] }] })) { if (cancel) break }
112
- } catch {}
113
- return recorded
114
- }
115
- const success = await run([{ text: 'PRIVATE_OUTPUT' }, { usage: { inputTokens: 8, outputTokens: 2 } }, { finish: 'stop' }])
116
- assert.equal(success[0].status, 'success')
117
- assert.equal(success[0].inputTokens, 8)
118
- assert.ok(!JSON.stringify(success).includes('PRIVATE'))
119
- assert.equal((await run([new Error('PRIVATE_UPSTREAM')]))[0].status, 'error')
120
- assert.equal((await run([], true))[0].status, 'error')
121
- assert.equal((await run([{ text: 'x' }], false, true))[0].status, 'aborted')
122
- })
123
79
  await check('concurrent account imports and name discovery cannot overwrite other accounts', async () => {
124
80
  const [one] = await Promise.all([accounts.addAccount(secretAccount), accounts.addAccount({ ak: 'SECOND_TEST_AK', sk: 'SECOND_TEST_SK' })])
125
81
  await Promise.all([accounts.rememberAccountName(one.account.id, 'Example name'), accounts.addAccount({ ak: 'THIRD_TEST_AK', sk: 'THIRD_TEST_SK' })])
@@ -134,6 +90,7 @@ let creditReads = 0
134
90
  let creditGate = null
135
91
  let creditRemain = 50
136
92
  let iamReads = 0
93
+ let benefitReads = 0
137
94
  const jsonResponse = (value, status = 200) => new Response(JSON.stringify(value), { status })
138
95
  globalThis.fetch = async (input) => {
139
96
  const url = String(input)
@@ -149,14 +106,15 @@ globalThis.fetch = async (input) => {
149
106
  return jsonResponse({ metrics: [{ name: 'usageTotalPackageCredit', package_credit_amount: 1000, package_credit_used: 950, package_credit_remain: remain }] })
150
107
  }
151
108
  if (url.includes('/v1/model/builtin') || url.includes('/v1/model/thinking-variants')) return jsonResponse([])
152
- if (url.includes('/v1/ops/delivery')) return jsonResponse([])
109
+ if (url.includes('/v1/ops/delivery')) { benefitReads += 1; return jsonResponse([]) }
153
110
  if (url.includes('/member/roles')) return jsonResponse([])
154
111
  throw new Error('Offline test blocked an unexpected gateway request')
155
112
  }
156
113
  const routes = new Map()
157
114
  const plugin = await import('../src/index.js')
158
115
  const effect = (fn) => { const dispose = fn(); if (typeof dispose === 'function') disposers.push(dispose); return dispose }
159
- plugin.apply({ effect, get: () => undefined, emit() {}, inject: (_, callback) => callback({ effect, webServer: { register: (route) => { routes.set(route.path, route.handler); return () => {} } } }) }, { registerProvider: false })
116
+ plugin.apply({ effect, get: () => undefined, emit() {}, inject: (_, callback) => callback({ effect, webServer: { register: (route) => { routes.set(route.path, route.handler); return () => {} } } }) }, { registerProvider: false, autoCheckin: true })
117
+ for (const path of ['/usage', '/usage/clear', '/checkin/auto']) assert.ok(!routes.has(`/plugins/dsh-connect-codearts${path}`), `Retired route registered: ${path}`)
160
118
  const request = (path, body, method = body === undefined ? 'GET' : 'POST', options = {}) => new Promise((resolve, reject) => {
161
119
  const handler = routes.get(`/plugins/dsh-connect-codearts${path}`)
162
120
  if (!handler) return reject(new Error(`Unknown route ${path}`))
@@ -165,11 +123,19 @@ const request = (path, body, method = body === undefined ? 'GET' : 'POST', optio
165
123
  let status
166
124
  handler(req, { setHeader() {}, writeHead: (value) => { status = value }, end: (text) => resolve({ status, body: JSON.parse(text) }) })
167
125
  })
126
+ await check('legacy automatic check-in settings cause no background benefit requests', async () => {
127
+ await new Promise(setImmediate)
128
+ assert.equal(benefitReads, 0, 'legacy autoCheckin=true must not run a claim sweep on startup')
129
+ const result = await request('/preferences')
130
+ assert.ok(!('autoCheckin' in result.body.preferences))
131
+ assert.equal((await request('/checkin/claim-all', {})).status, 200, 'manual batch route remains available')
132
+ assert.ok(benefitReads > 0, 'the manual request checks upstream eligibility')
133
+ })
168
134
  await check('feature routes enforce POST, validate preferences, and persist presets without changing the live selection', async () => {
169
- for (const path of ['/preferences/save', '/usage/clear', '/presets', '/backup/export', '/backup/preview', '/backup/restore', '/accounts/check']) assert.equal((await request(path)).status, 405)
170
- assert.equal((await request('/preferences/save', { lowBalanceThreshold: -1 })).status, 400)
171
- const preferenceSave = await request('/preferences/save', { lowBalanceThreshold: 75, usageEnabled: true })
172
- assert.equal(preferenceSave.body.preferences.lowBalanceThreshold, 75)
135
+ for (const path of ['/preferences/save', '/presets', '/backup/export', '/backup/preview', '/backup/restore', '/accounts/check', '/checkin/claim-all']) assert.equal((await request(path)).status, 405)
136
+ assert.equal((await request('/preferences/save', { refreshIntervalMs: -1 })).status, 400)
137
+ const preferenceSave = await request('/preferences/save', { refreshIntervalMs: 75000, composerChip: true })
138
+ assert.equal(preferenceSave.body.preferences.refreshIntervalMs, 75000)
173
139
  const preset = await request('/presets', { action: 'save', name: 'Daily', enabledModelIds: ['test-model'], modelOverrides: { 'test-model': { images: true, defaultStrength: 'high' } } })
174
140
  assert.equal(preset.status, 200)
175
141
  assert.equal(preset.body.presets.length, 1)
@@ -177,9 +143,23 @@ await check('feature routes enforce POST, validate preferences, and persist pres
177
143
  const id = preset.body.presets[0].id
178
144
  assert.equal((await request('/presets', { action: 'delete', id })).body.presets.length, 0)
179
145
  })
146
+ await check('pinned models persist without changing model selection and travel with backups', async () => {
147
+ const before = (await request('/models')).body.enabledIds
148
+ const saved = await request('/preferences/save', { favoriteModelIds: ['test-model', 'temporarily-unavailable'] })
149
+ assert.deepEqual(saved.body.preferences.favoriteModelIds, ['test-model', 'temporarily-unavailable'])
150
+ assert.deepEqual(readPreferences().favoriteModelIds, ['test-model', 'temporarily-unavailable'])
151
+ assert.deepEqual((await request('/models')).body.favoriteModelIds, ['test-model', 'temporarily-unavailable'])
152
+ assert.deepEqual((await request('/models')).body.enabledIds, before)
153
+ const exported = await request('/backup/export', {})
154
+ assert.deepEqual(exported.body.backup.preferences.favoriteModelIds, ['test-model', 'temporarily-unavailable'])
155
+ await request('/preferences/save', { favoriteModelIds: [] })
156
+ const restored = await request('/backup/restore', { text: JSON.stringify(exported.body.backup) })
157
+ assert.equal(restored.status, 200)
158
+ assert.deepEqual((await request('/models')).body.favoriteModelIds, ['test-model', 'temporarily-unavailable'])
159
+ })
180
160
  await check('malformed, non-object, oversized and remote feature requests are rejected without mutations', async () => {
181
161
  const before = JSON.stringify((await request('/preferences')).body)
182
- for (const path of ['/preferences/save', '/presets', '/backup/export', '/backup/preview', '/backup/restore', '/accounts/check']) {
162
+ for (const path of ['/preferences/save', '/presets', '/backup/export', '/backup/preview', '/backup/restore', '/accounts/check', '/checkin/claim-all']) {
183
163
  for (const body of [null, [], 42, 'invalid']) {
184
164
  assert.equal((await request(path, body)).status, 400, `${path} must reject ${JSON.stringify(body)}`)
185
165
  }
@@ -187,24 +167,27 @@ await check('malformed, non-object, oversized and remote feature requests are re
187
167
  }
188
168
  assert.equal((await request('/preferences/save', { ignored: 'x'.repeat(65536) })).status, 413)
189
169
  assert.equal((await request('/backup/preview', { text: 'x'.repeat(1024 * 1024) })).status, 413)
190
- assert.equal((await request('/preferences/save', { lowBalanceThreshold: 123 }, 'POST', { remoteAddress: '192.0.2.1' })).status, 403)
170
+ assert.equal((await request('/preferences/save', { refreshIntervalMs: 123000 }, 'POST', { remoteAddress: '192.0.2.1' })).status, 403)
191
171
  assert.equal(JSON.stringify((await request('/preferences')).body), before)
192
172
  })
193
- await check('account checks use one probe for concurrent clicks, expose actionable status, and report low balances', async () => {
173
+ await check('account checks use one probe for concurrent clicks, expose actionable status, and keep the credit overview', async () => {
194
174
  const id = accounts.readStore().accounts[0].id
195
175
  await new Promise(setImmediate)
196
176
  const creditsBefore = creditReads, iamBefore = iamReads
197
177
  const [a, b] = await Promise.all([request('/accounts/check', { id }), request('/accounts/check', { id })])
198
178
  assert.equal(a.body.account.health.state, 'available')
199
- assert.equal(b.body.account.lowBalance, true)
179
+ assert.equal(b.body.account.credit.remain, 50)
180
+ assert.ok(b.body.account.creditCheckedAt > 0)
181
+ assert.equal(typeof b.body.account.creditIdentity, 'string')
182
+ assert.ok(!('lowBalance' in b.body.account))
200
183
  assert.equal(creditReads - creditsBefore, 1)
201
184
  assert.equal(iamReads - iamBefore, 1)
202
185
  creditStatus = 429
203
186
  assert.equal((await request('/accounts/check', { id })).body.account.health.state, 'rate_limited')
204
187
  creditStatus = 200
205
188
  const active = (await request('/account')).body
206
- assert.equal(active.lowBalance, true)
207
- assert.equal(active.lowBalanceThreshold, 75)
189
+ assert.equal(active.credit.remain, 50)
190
+ assert.ok(!('lowBalanceThreshold' in active))
208
191
  })
209
192
  await check('an invalidated in-flight health probe cannot repopulate stale account state', async () => {
210
193
  const account = accounts.readStore().accounts[0]
@@ -232,13 +215,13 @@ await check('backup preview writes nothing; restore merges accounts, preferences
232
215
  assert.equal(preview.body.accounts.updated, 3)
233
216
  assert.equal(JSON.stringify(accounts.readStore()), before)
234
217
  assert.ok(!JSON.stringify(preview.body).includes(secretAccount.sk))
235
- await request('/preferences/save', { lowBalanceThreshold: 999 })
218
+ await request('/preferences/save', { refreshIntervalMs: 999000 })
236
219
  const preservedId = accounts.readStore().accounts.at(-1).id
237
220
  await accounts.setActiveAccount(preservedId)
238
221
  const restore = await request('/backup/restore', { text, password: 'test-password-123' })
239
222
  assert.equal(restore.status, 200)
240
223
  assert.equal(restore.body.updated, 3)
241
- assert.equal((await request('/preferences')).body.preferences.lowBalanceThreshold, 75)
224
+ assert.equal((await request('/preferences')).body.preferences.refreshIntervalMs, 75000)
242
225
  assert.equal(accounts.readStore().accounts.length, 3)
243
226
  assert.equal(accounts.readStore().activeId, preservedId)
244
227
 
@@ -234,8 +234,10 @@ await check('Config satisfies the two gates Settings → Models applies', async
234
234
  const json = schema.toJSON()
235
235
  assert.equal(typeof json, 'object', 'gate 1: toJSON must produce a schema document')
236
236
  // Gate 2 needs the schema to resolve the values the card reads.
237
+ assert.ok(!('autoCheckin' in plugin.DEFAULTS), 'removed automatic preference has no default')
237
238
  const values = schema({})
238
- for (const field of ['enabled', 'composerChip', 'registerProvider', 'autoCheckin']) {
239
+ assert.ok(!('autoCheckin' in values), 'removed automatic preference is not offered by settings')
240
+ for (const field of ['enabled', 'composerChip', 'registerProvider']) {
239
241
  assert.ok(field in values, `gate 2: ${field} must resolve from the schema`)
240
242
  }
241
243
  })