dsh-zcode-startplan 0.4.5 → 0.5.2

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,293 @@
1
+ /**
2
+ * 赠送额度领取(/claimable + /claim)的**路由级**测试。
3
+ *
4
+ * 上游 HTTP 全部换成假 fetch,但走真实的 `lib/upstream-api.js` 解析与
5
+ * `lib/manage-routes.js` 的路由装配 —— 断言的是「面板点一次按钮,宿主到底
6
+ * 发了什么、怎么处理 captcha」。
7
+ *
8
+ * 三条不可动摇的约定(来自上游实测):
9
+ * 1. captcha **一次性**:每个 plan 必须重新 mint,复用必 3007;
10
+ * 2. `1003` = 已领过,是**幂等成功**,不能报红;
11
+ * 3. captcha 产出失败时**立刻停**,不要连环重试烧设备信誉。
12
+ */
13
+
14
+ import test from 'node:test'
15
+ import assert from 'node:assert/strict'
16
+
17
+ import { makeManageRoutes } from '../lib/manage-routes.js'
18
+
19
+ /** 极简 req/res 桩:够 readJsonBody / writeJson 用。 */
20
+ function makeReqRes({ method = 'GET', url = '/', body } = {}) {
21
+ const chunks = body === undefined ? [] : [Buffer.from(JSON.stringify(body))]
22
+ const req = {
23
+ method,
24
+ url,
25
+ socket: { remoteAddress: '127.0.0.1' },
26
+ headers: { host: '127.0.0.1:58962', 'content-type': 'application/json' },
27
+ on(event, handler) {
28
+ if (event === 'data') chunks.forEach((chunk) => handler(chunk))
29
+ if (event === 'end') handler()
30
+ return req
31
+ },
32
+ destroy() {},
33
+ }
34
+ let captured
35
+ let status = 200
36
+ const res = {
37
+ writableEnded: false,
38
+ destroyed: false,
39
+ writeHead(code) {
40
+ status = code
41
+ },
42
+ end(text) {
43
+ res.writableEnded = true
44
+ captured = text
45
+ },
46
+ get body() {
47
+ return captured === undefined ? undefined : JSON.parse(captured)
48
+ },
49
+ get status() {
50
+ return status
51
+ },
52
+ }
53
+ return { req, res }
54
+ }
55
+
56
+ /** 账号池桩:一条账号、带凭据。 */
57
+ const pool = {
58
+ list: ({ withCredentials } = {}) => [
59
+ {
60
+ id: 'acc-1',
61
+ nickname: 'TARGET_ACCOUNT',
62
+ enabled: true,
63
+ user_id: 'user-1',
64
+ added_at: 1,
65
+ model_rate_limits: {},
66
+ last_error: null,
67
+ ...(withCredentials === true
68
+ ? { credential: { zcode_jwt: 'ZCODE_JWT', device_mid: 'DEVICE_MID', app_version: '3.14.3' } }
69
+ : {}),
70
+ },
71
+ ],
72
+ get: (id) => undefined,
73
+ }
74
+
75
+ /** 找到某条路由并调用。 */
76
+ async function call(routes, path, options) {
77
+ const route = routes.find((item) => item.path === path)
78
+ assert.ok(route !== undefined, `没有注册 ${path}`)
79
+ const { req, res } = makeReqRes(options)
80
+ await route.handler(req, res)
81
+ return res
82
+ }
83
+
84
+ /** 可领取的活动(priority 降序由 fetchClaimablePlans 排)。 */
85
+ const CLAIMABLE_PLANS = [
86
+ { plan_id: 'plan-low', name: 'LOW', priority: 10 },
87
+ { plan_id: 'plan-high', name: 'HIGH', priority: 90 },
88
+ ]
89
+
90
+ /** 假上游:按 URL 分发,并记录 captcha 头,供断言「每个 plan 都重新 mint」。 */
91
+ function makeUpstream({ claimCodes = [0, 0], captchaFails = false } = {}) {
92
+ const calls = { claim: [], captchaHeaders: [], preview: 0, report: 0 }
93
+ let claimIndex = 0
94
+ const fetchImpl = async (url, init = {}) => {
95
+ const target = String(url)
96
+ if (target.includes('/event/report')) {
97
+ calls.report += 1
98
+ return new Response(JSON.stringify({ code: 0 }), { status: 200, headers: { 'content-type': 'application/json' } })
99
+ }
100
+ if (target.includes('/billing/preview')) {
101
+ calls.preview += 1
102
+ return new Response(JSON.stringify({ code: 0, data: { plans: CLAIMABLE_PLANS } }), {
103
+ status: 200,
104
+ headers: { 'content-type': 'application/json' },
105
+ })
106
+ }
107
+ if (target.includes('/billing/claim')) {
108
+ const payload = JSON.parse(init.body)
109
+ calls.claim.push(payload.plan_id)
110
+ calls.captchaHeaders.push(init.headers['x-aliyun-captcha-verify-param'])
111
+ const code = claimCodes[claimIndex++] ?? 0
112
+ return new Response(JSON.stringify({ code, msg: code === 0 ? '' : 'x' }), {
113
+ status: 200,
114
+ headers: { 'content-type': 'application/json' },
115
+ })
116
+ }
117
+ throw new Error(`未预期的上游请求:${target}`)
118
+ }
119
+ /** captcha minter 桩:每次给一个新 param(一次性)。 */
120
+ let seq = 0
121
+ const client = {
122
+ async mintCaptcha() {
123
+ if (captchaFails) throw new Error('连不上宿主调试端口')
124
+ seq += 1
125
+ return { param: `param-${seq}`, region: 'cn' }
126
+ },
127
+ }
128
+ return { fetchImpl, client, calls }
129
+ }
130
+
131
+ /**
132
+ * ⚠ `lib/upstream-api.js` 用**模块级** `globalThis.fetch` 默认值。
133
+ * 这里临时替换全局 fetch(测试单进程串行跑,用完立刻还原)。
134
+ */
135
+ async function withGlobalFetch(fetchImpl, fn) {
136
+ const original = globalThis.fetch
137
+ globalThis.fetch = fetchImpl
138
+ try {
139
+ return await fn()
140
+ } finally {
141
+ globalThis.fetch = original
142
+ }
143
+ }
144
+
145
+ function buildRoutes(client) {
146
+ return makeManageRoutes({
147
+ pool,
148
+ client,
149
+ fetchBalance: async () => undefined,
150
+ settings: {},
151
+ log: () => {},
152
+ })
153
+ }
154
+
155
+ test('/claimable: 先补活跃上报再查 preview,返回可领列表', async () => {
156
+ const { fetchImpl, client, calls } = makeUpstream()
157
+ const routes = buildRoutes(client)
158
+ const res = await withGlobalFetch(fetchImpl, () => call(routes, '/api/zcode-start-plan/claimable', { url: '/api/zcode-start-plan/claimable?id=acc-1' }))
159
+
160
+ assert.equal(res.status, 200)
161
+ assert.equal(res.body.ok, true)
162
+ assert.equal(calls.report, 2, 'reportActivation 会发两个事件(launch + daily_active)')
163
+ assert.deepEqual(
164
+ res.body.plans.map((plan) => plan.planId),
165
+ ['plan-high', 'plan-low'],
166
+ 'priority 降序',
167
+ )
168
+ })
169
+
170
+ test('/claim: 每个 plan 重新 mint captcha(param 不同),全部成功', async () => {
171
+ const { fetchImpl, client, calls } = makeUpstream({ claimCodes: [0, 0] })
172
+ const routes = buildRoutes(client)
173
+ const res = await withGlobalFetch(fetchImpl, () => call(routes, '/api/zcode-start-plan/claim', { method: 'POST', body: { id: 'acc-1' } }))
174
+
175
+ assert.equal(res.status, 200)
176
+ assert.equal(res.body.ok, true)
177
+ assert.deepEqual(calls.claim, ['plan-high', 'plan-low'])
178
+ assert.deepEqual(calls.captchaHeaders, ['param-1', 'param-2'], '两次领取必须用不同的 captcha param')
179
+ assert.equal(res.body.results.length, 2)
180
+ assert.ok(res.body.results.every((item) => item.ok === true))
181
+ })
182
+
183
+ test('/claim: 1003(已领过)算幂等成功,不报错', async () => {
184
+ const { fetchImpl, client } = makeUpstream({ claimCodes: [1003] })
185
+ const routes = buildRoutes(client)
186
+ const res = await withGlobalFetch(fetchImpl, () =>
187
+ call(routes, '/api/zcode-start-plan/claim', { method: 'POST', body: { id: 'acc-1', planId: 'plan-high' } }),
188
+ )
189
+
190
+ assert.equal(res.body.ok, true, '已领过不能算失败')
191
+ assert.equal(res.body.results[0].ok, true)
192
+ assert.equal(res.body.results[0].alreadyClaimed, true)
193
+ })
194
+
195
+ test('/claim: 指定 planId 只领那一个', async () => {
196
+ const { fetchImpl, client, calls } = makeUpstream()
197
+ const routes = buildRoutes(client)
198
+ await withGlobalFetch(fetchImpl, () =>
199
+ call(routes, '/api/zcode-start-plan/claim', { method: 'POST', body: { id: 'acc-1', planId: 'plan-low' } }),
200
+ )
201
+ assert.deepEqual(calls.claim, ['plan-low'])
202
+ })
203
+
204
+ test('/claim: captcha 产出失败即停,不连环重试', async () => {
205
+ const { fetchImpl, client, calls } = makeUpstream({ captchaFails: true })
206
+ const routes = buildRoutes(client)
207
+ const res = await withGlobalFetch(fetchImpl, () =>
208
+ call(routes, '/api/zcode-start-plan/claim', { method: 'POST', body: { id: 'acc-1' } }),
209
+ )
210
+
211
+ assert.equal(res.body.ok, false)
212
+ assert.match(res.body.results[0].error, /captcha 产出失败/)
213
+ assert.equal(calls.claim.length, 0, 'captcha 没拿到就绝不能打 claim(烧设备信誉)')
214
+ assert.equal(res.body.results.length, 1, '失败后不再尝试第二个 plan')
215
+ })
216
+
217
+ test('/claimable: 账号不存在给 404;未知路径不会误配', async () => {
218
+ const { fetchImpl, client } = makeUpstream()
219
+ const routes = buildRoutes(client)
220
+ const res = await withGlobalFetch(fetchImpl, () =>
221
+ call(routes, '/api/zcode-start-plan/claimable', { url: '/api/zcode-start-plan/claimable?id=nope' }),
222
+ )
223
+ assert.equal(res.status, 404)
224
+ assert.equal(res.body.ok, false)
225
+ })
226
+
227
+ test('/claim: 缺 id 给 400', async () => {
228
+ const { fetchImpl, client } = makeUpstream()
229
+ const routes = buildRoutes(client)
230
+ const res = await withGlobalFetch(fetchImpl, () =>
231
+ call(routes, '/api/zcode-start-plan/claim', { method: 'POST', body: {} }),
232
+ )
233
+ assert.equal(res.status, 400)
234
+ })
235
+
236
+ test('/restart-cdp: 把 debugPort 与等待时长交给重启实现,不阻塞响应', async () => {
237
+ const calls = []
238
+ const routes = makeManageRoutes({
239
+ pool,
240
+ client: {},
241
+ fetchBalance: async () => undefined,
242
+ settings: {},
243
+ log: () => {},
244
+ requestRestart: async (options) => {
245
+ calls.push(options)
246
+ },
247
+ })
248
+ const res = await call(routes, '/api/zcode-start-plan/restart-cdp', {
249
+ method: 'POST',
250
+ body: { debugPort: 9333, waitSeconds: 5 },
251
+ })
252
+ assert.equal(res.status, 200)
253
+ assert.equal(res.body.ok, true)
254
+ assert.equal(res.body.debugPort, 9333)
255
+ assert.deepEqual(calls, [{ debugPort: 9333, waitSeconds: 5 }])
256
+ assert.equal(typeof res.body.estimatedReadyMs, 'number')
257
+ })
258
+
259
+ test('/restart-cdp: 非法端口给 400,且不触发重启', async () => {
260
+ const calls = []
261
+ const routes = makeManageRoutes({
262
+ pool,
263
+ client: {},
264
+ settings: {},
265
+ log: () => {},
266
+ requestRestart: async (options) => calls.push(options),
267
+ })
268
+ const res = await call(routes, '/api/zcode-start-plan/restart-cdp', { method: 'POST', body: { debugPort: 99999 } })
269
+ assert.equal(res.status, 400)
270
+ assert.equal(calls.length, 0, '参数不合法时绝不能真的去重启宿主')
271
+ })
272
+
273
+ test('/restart-cdp: 宿主没提供重启实现时给 501(而不是假装成功)', async () => {
274
+ const routes = makeManageRoutes({ pool, client: {}, settings: {}, log: () => {} })
275
+ const res = await call(routes, '/api/zcode-start-plan/restart-cdp', { method: 'POST', body: {} })
276
+ assert.equal(res.status, 501)
277
+ assert.match(res.body.error, /不支持自动重启/)
278
+ })
279
+
280
+ test('/restart-cdp: 重启实现抛错时把原因透出来', async () => {
281
+ const routes = makeManageRoutes({
282
+ pool,
283
+ client: {},
284
+ settings: {},
285
+ log: () => {},
286
+ requestRestart: async () => {
287
+ throw new Error('找不到 DeepSeek Harness.exe')
288
+ },
289
+ })
290
+ const res = await call(routes, '/api/zcode-start-plan/restart-cdp', { method: 'POST', body: {} })
291
+ assert.equal(res.status, 500)
292
+ assert.match(res.body.error, /找不到/)
293
+ })
@@ -0,0 +1,356 @@
1
+ /**
2
+ * client.js 面板的**结构级**测试。
3
+ *
4
+ * client.js 是宿主注入 `React` 的浏览器 bundle(不 import react),
5
+ * 所以这里塞一个**最小 createElement 实现**,把渲染结果摊成可断言的树:
6
+ * 只关心「有没有那条进度条 / 条纹标记对不对 / 底部那句时间在不在」。
7
+ *
8
+ * 覆盖 0.4.7 的需求:未生效额度与已生效额度**同形状一条进度条**,
9
+ * 区别只在 `data-pending` 与底部「X 起可用」。
10
+ */
11
+
12
+ import test from 'node:test'
13
+ import assert from 'node:assert/strict'
14
+ import { readFileSync } from 'node:fs'
15
+
16
+ /**
17
+ * 极简 h():只认 type / props / children,够断言用。
18
+ *
19
+ * ⚠ hooks 是**带计数**的桩:同一组件在两次渲染里调用的 hook 数不一致时抛错
20
+ * (复刻 React 的「Rendered fewer hooks than expected」)。0.5.0 的
21
+ * ClaimSection 把 useCallback 放在早退之后,账号非空时多调一个 → 整个面板白屏。
22
+ */
23
+ function makeReact() {
24
+ const h = (type, props, ...children) => ({
25
+ type,
26
+ props: props ?? {},
27
+ children: children.flat().filter((child) => child !== null && child !== undefined && child !== false),
28
+ })
29
+ /** 当前组件的 hook 计数(渲染前由 render() 重置)。 */
30
+ let hookCount = 0
31
+ let expectedHookCount
32
+ const tick = () => {
33
+ hookCount += 1
34
+ }
35
+ return {
36
+ createElement: h,
37
+ Fragment: Symbol('Fragment'),
38
+ useState: (initial) => {
39
+ tick()
40
+ return [typeof initial === 'function' ? initial() : initial, () => {}]
41
+ },
42
+ useEffect: () => tick(),
43
+ useRef: (initial) => {
44
+ tick()
45
+ return { current: initial }
46
+ },
47
+ useCallback: (fn) => {
48
+ tick()
49
+ return fn
50
+ },
51
+ __hooks: {
52
+ begin: (expected) => {
53
+ expectedHookCount = expected
54
+ hookCount = 0
55
+ },
56
+ end: () => {
57
+ if (expectedHookCount !== undefined && hookCount !== expectedHookCount) {
58
+ throw new Error(`渲染之间 hook 数量变化:${expectedHookCount} → ${hookCount}(React 会抛 Rendered fewer hooks than expected)`)
59
+ }
60
+ expectedHookCount = hookCount
61
+ return hookCount
62
+ },
63
+ },
64
+ }
65
+ }
66
+
67
+ /**
68
+ * 把 client.js 当作工厂函数求值。它导出 `(ctx) => …`,内部用闭包里的
69
+ * `React`;这里用一个假的 React 与环境把面板组件取出来。
70
+ */
71
+ const SOURCE = readFileSync(new URL('../client.js', import.meta.url), 'utf8')
72
+
73
+ /** 全局共享的假 React(buildPanel 与 resolve 用同一份 Fragment 符号)。 */
74
+ const FakeReact = makeReact()
75
+
76
+ /**
77
+ * 从源码里抠出一个函数定义(按名 + 括号配平)。
78
+ *
79
+ * 不能用 `function NAME(props)` 定位:辅助函数签名各异
80
+ * (`formatReset(resetAt)` / `QuotaMeter(props)`),统一按名字找。
81
+ */
82
+ function extractFunction(name) {
83
+ const pattern = new RegExp(`function ${name}\\s*\\(`)
84
+ const match = pattern.exec(SOURCE)
85
+ assert.notEqual(match, null, `client.js 里找不到 function ${name}`)
86
+ const start = match.index
87
+ let depth = 0
88
+ let i = SOURCE.indexOf('{', start)
89
+ for (; i < SOURCE.length; i += 1) {
90
+ if (SOURCE[i] === '{') depth += 1
91
+ else if (SOURCE[i] === '}') {
92
+ depth -= 1
93
+ if (depth === 0) break
94
+ }
95
+ }
96
+ return SOURCE.slice(start, i + 1)
97
+ }
98
+
99
+ /** 把抽出来的组件 + 依赖函数拼成一个可执行模块。 */
100
+ function buildPanel() {
101
+ const helpers = ['formatReset', 'formatEffective', 'formatPendingUnits', 'formatRemaining', 'channelLabel'].map(extractFunction).join('\n')
102
+ const quota = extractFunction('QuotaMeter')
103
+ const card = extractFunction('AccountCard')
104
+ const claimSection = extractFunction('ClaimSection')
105
+ /**
106
+ * 桩件:NicknameEdit / Toggle / api 用最简实现替代(它们的渲染不是本测试的主题),
107
+ * `h`/`Fragment` 从 fake React 取。
108
+ */
109
+ const code = `
110
+ const h = React.createElement
111
+ const Fragment = React.Fragment
112
+ const { useState, useCallback } = React
113
+ const api = async () => ({ ok: true, plans: [] })
114
+ function NicknameEdit(props) { return h('span', null, props.nickname) }
115
+ function Toggle() { return h('input', { type: 'checkbox' }) }
116
+ ${helpers}
117
+ ${quota}
118
+ ${card}
119
+ ${claimSection}
120
+ return { AccountCard, QuotaMeter, ClaimSection, formatEffective, formatPendingUnits, formatRemaining }
121
+ `
122
+ // eslint-disable-next-line no-new-func
123
+ const mod = new Function('React', code)(FakeReact)
124
+ return { ...mod, React: FakeReact, render: (node) => resolve(node, FakeReact) }
125
+ }
126
+
127
+ /** 在渲染树里找所有 className 含 needle 的节点。 */
128
+ function findAll(node, predicate, out = []) {
129
+ if (node === null || typeof node !== 'object') return out
130
+ if (predicate(node)) out.push(node)
131
+ for (const child of node.children ?? []) findAll(child, predicate, out)
132
+ return out
133
+ }
134
+
135
+ /**
136
+ * 展开树里的函数组件(`h(QuotaMeter, props)` 的 type 是函数)。
137
+ * 不做 memo / hooks 状态,但**校验 hook 数量**:同一个组件先后渲染时
138
+ * hook 数必须一致,否则就是 React 层面的白屏 bug。
139
+ */
140
+ function resolve(node, React, seen = new Map()) {
141
+ if (node === null || typeof node !== 'object') return node
142
+ if (typeof node.type === 'function') {
143
+ const name = node.type.name || 'anonymous'
144
+ React.__hooks.begin(seen.has(name) ? seen.get(name) : undefined)
145
+ let rendered
146
+ try {
147
+ rendered = node.type(node.props)
148
+ } finally {
149
+ seen.set(name, React.__hooks.end())
150
+ }
151
+ return resolve(rendered, React, seen)
152
+ }
153
+ return { ...node, children: node.children.map((child) => resolve(child, React, seen)) }
154
+ }
155
+
156
+ const textOf = (node) =>
157
+ node === null || node === undefined
158
+ ? ''
159
+ : typeof node === 'string' || typeof node === 'number'
160
+ ? String(node)
161
+ : (node.children ?? []).map(textOf).join('')
162
+
163
+ const baseAccount = {
164
+ id: 'acc-1',
165
+ index: 1,
166
+ nickname: 'ACC_B',
167
+ enabled: true,
168
+ channel: 'zai',
169
+ modelRateLimits: {},
170
+ }
171
+
172
+ test('AccountCard: 已生效额度只有一条实色进度条', () => {
173
+ const panel = buildPanel()
174
+ const tree = panel.render(panel.AccountCard({
175
+ account: baseAccount,
176
+ balance: { ok: true, enterprise: false, remaining: 7_876_044, total: 8_000_000, planName: 'GLM-5.3' },
177
+ modelListVisible: true,
178
+ }))
179
+ const bars = findAll(tree, (node) => node.props?.className === 'zsp-bar')
180
+ assert.equal(bars.length, 1, '已生效时应有一条进度条')
181
+ assert.notEqual(bars[0].props['data-pending'], true, '已生效的条不能打 pending 标记')
182
+ const text = textOf(tree)
183
+ assert.match(text, /剩余 7876044\/8000000/)
184
+ assert.match(text, /GLM-5\.3/)
185
+ })
186
+
187
+ test('AccountCard: 未生效额度与已生效额度同形状,底部标启用时间', () => {
188
+ const panel = buildPanel()
189
+ const effectiveAt = Date.now() + 2 * 60 * 60 * 1000
190
+ const tree = panel.render(panel.AccountCard({
191
+ account: baseAccount,
192
+ balance: {
193
+ ok: true,
194
+ enterprise: false,
195
+ remaining: 0,
196
+ total: 0,
197
+ planName: null,
198
+ pending: [{ planId: 'zcode-v3-start-plan-nt-1026', showName: 'GLM-5.3-Flash', grantUnits: 300_000_000, effectiveAt }],
199
+ },
200
+ modelListVisible: true,
201
+ }))
202
+ const bars = findAll(tree, (node) => node.props?.className === 'zsp-bar')
203
+ assert.equal(bars.length, 2, '已生效 1 条 + 未生效 1 条')
204
+ assert.notEqual(bars[0].props['data-pending'], true, '第一条是已生效的')
205
+ assert.equal(bars[1].props['data-pending'], true, '第二条是未生效的(条纹)')
206
+ /** 未生效那条必须是满格:还没开始消耗。 */
207
+ const fill = bars[1].children[0]
208
+ assert.equal(fill.props.style.width, '100%')
209
+
210
+ const text = textOf(tree)
211
+ assert.match(text, /起可用/, '进度条底部要写启用时间')
212
+ assert.match(text, /GLM-5\.3-Flash 3亿 tokens/, '要标出是哪一份额度')
213
+ /** 时间文案应出现在条下方的 caption 里,而不是标题行。 */
214
+ const captions = findAll(tree, (node) => node.props?.className?.includes('zsp-meter-caption'))
215
+ assert.equal(captions.length, 2, '每条进度条各一句 caption')
216
+ assert.match(textOf(captions[1]), /起可用/)
217
+ })
218
+
219
+ test('AccountCard: 多个未生效额度各一条进度条(按到点时间顺序)', () => {
220
+ const panel = buildPanel()
221
+ const now = Date.now()
222
+ const tree = panel.render(panel.AccountCard({
223
+ account: baseAccount,
224
+ balance: {
225
+ ok: true,
226
+ enterprise: false,
227
+ remaining: 0,
228
+ total: 0,
229
+ planName: null,
230
+ pending: [
231
+ { planId: 'a', showName: 'GLM-5.3-Flash', grantUnits: 100_000_000, effectiveAt: now + 3_600_000 },
232
+ { planId: 'b', showName: 'GLM-5.3', grantUnits: 50_000_000, effectiveAt: now + 7_200_000 },
233
+ ],
234
+ },
235
+ modelListVisible: true,
236
+ }))
237
+ const pendingBars = findAll(tree, (node) => node.props?.className === 'zsp-bar' && node.props['data-pending'] === true)
238
+ assert.equal(pendingBars.length, 2)
239
+ })
240
+
241
+ test('QuotaMeter: 缺 total 的额度按 0% 画(不是满格),未生效固定 100%', () => {
242
+ const panel = buildPanel()
243
+ const unknown = panel.QuotaMeter({ remaining: undefined, total: undefined })
244
+ assert.equal(unknown.children[0].children[0].props.style.width, '0%')
245
+ const pending = panel.QuotaMeter({ pending: true, effectiveAt: Date.now() + 1000 })
246
+ assert.equal(pending.children[0].children[0].props.style.width, '100%')
247
+ })
248
+
249
+ test('AccountCard: 企业版与错误态不画进度条', () => {
250
+ const panel = buildPanel()
251
+ const enterprise = panel.render(panel.AccountCard({ account: baseAccount, balance: { ok: true, enterprise: true }, modelListVisible: true }))
252
+ assert.equal(findAll(enterprise, (n) => n.props?.className === 'zsp-bar').length, 0)
253
+ const failed = panel.render(panel.AccountCard({ account: baseAccount, balance: { ok: false, error: '余额不可用' }, modelListVisible: true }))
254
+ assert.equal(findAll(failed, (n) => n.props?.className === 'zsp-bar').length, 0)
255
+ assert.match(textOf(failed), /余额不可用/)
256
+ })
257
+
258
+ test('formatEffective: 今天只给时刻,跨天带日期', () => {
259
+ const panel = buildPanel()
260
+ const { formatEffective } = panel
261
+ const today = new Date()
262
+ const laterToday = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 0).getTime()
263
+ assert.equal(formatEffective(laterToday), '23:00')
264
+ const nextWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7, 9, 30).getTime()
265
+ assert.match(formatEffective(nextWeek), /\d+\/\d+/)
266
+ })
267
+
268
+ test('formatRemaining: 分钟 / 小时 / 天 / 已过期 四档', () => {
269
+ const panel = buildPanel()
270
+ const { formatRemaining } = panel
271
+ const now = Date.now()
272
+ assert.equal(formatRemaining(now + 12 * 60_000, now), '12 分钟后')
273
+ assert.equal(formatRemaining(now + 3 * 3_600_000, now), '3 小时后')
274
+ assert.equal(formatRemaining(now + 90 * 60_000, now), '1 小时 30 分后')
275
+ assert.equal(formatRemaining(now + 2 * 86_400_000, now), '2 天后')
276
+ assert.equal(formatRemaining(now + 30_000, now), '不到 1 分钟')
277
+ assert.equal(formatRemaining(now - 1000, now), '已过期')
278
+ assert.equal(formatRemaining(0, now), '', '没有到期时间时返回空串,不能出现 1970')
279
+ assert.equal(formatRemaining(undefined, now), '')
280
+ })
281
+
282
+ test('QuotaMeter: caption 同时给出剩余、计划名与到期时间', () => {
283
+ const panel = buildPanel()
284
+ const expiresAt = Date.now() + 3 * 3_600_000 // 3 小时后
285
+ const tree = panel.QuotaMeter({ remaining: 7_876_044, total: 8_000_000, planName: 'GLM-5.3', expiresAt })
286
+ const text = textOf(tree.children[1])
287
+ assert.match(text, /剩余 7876044\/8000000/)
288
+ assert.match(text, /GLM-5\.3/)
289
+ assert.match(text, /到期/)
290
+ assert.match(text, /3 小时后/)
291
+ })
292
+
293
+ test('QuotaMeter: 未生效额度同时给"何时起可用"与"何时到期"', () => {
294
+ const panel = buildPanel()
295
+ const effectiveAt = Date.now() + 60 * 60_000
296
+ const expiresAt = Date.now() + 2 * 86_400_000
297
+ const tree = panel.QuotaMeter({ pending: true, effectiveAt, expiresAt, planName: 'GLM-5.3-Flash' })
298
+ const text = textOf(tree.children[1])
299
+ assert.match(text, /起可用/)
300
+ assert.match(text, /到期/)
301
+ })
302
+
303
+ test('QuotaMeter: 没有 gives 到期信息时不留下 undefined', () => {
304
+ const panel = buildPanel()
305
+ const tree = panel.QuotaMeter({ remaining: 10, total: 10, planName: 'X' })
306
+ const text = textOf(tree.children[1])
307
+ assert.doesNotMatch(text, /undefined/)
308
+ assert.doesNotMatch(text, /NaN/)
309
+ assert.doesNotMatch(text, /1970/)
310
+ })
311
+
312
+ /**
313
+ * ⚠ 白屏回归闸(0.5.0 实际事故)。
314
+ *
315
+ * ClaimSection 曾把 `useCallback` 放在 `return null` 早退之后:
316
+ * 账号为空走早退 → 少调一个 hook;非空 → 多调一个。React 抛
317
+ * 「Rendered fewer hooks than expected」,**整个插件面板白屏**。
318
+ *
319
+ * 本用例用**带计数的 hooks 桩**渲染 ClaimSection 两次(空账号池 / 有账号),
320
+ * 两次 hook 数不一致就抛错。
321
+ */
322
+ test('ClaimSection: 空账号池与有账号两次渲染,hook 数量必须一致', () => {
323
+ const panel = buildPanel()
324
+ /** 先渲染空池(走早退)。 */
325
+ const empty = panel.render(panel.ClaimSection({ accounts: [], busy: false, captcha: { reachable: false } }))
326
+ assert.equal(empty, null, '空池时不渲染任何内容')
327
+
328
+ /** 再渲染有账号(不应因 hooks 数量变化而抛错)。 */
329
+ const filled = panel.render(
330
+ panel.ClaimSection({
331
+ accounts: [{ id: 'a1', index: 1, nickname: 'ACC', enabled: true }],
332
+ busy: false,
333
+ captcha: { reachable: false, debugPort: 9229, reason: '连不上调试端口' },
334
+ }),
335
+ )
336
+ assert.notEqual(filled, null)
337
+ const text = textOf(filled)
338
+ assert.match(text, /赠送额度/)
339
+ /** captcha 不可用 → 必须给出「以调试模式重启」按钮,而不是让人手抄 param。 */
340
+ const buttons = findAll(filled, (node) => node.type === 'button').map(textOf)
341
+ assert.ok(buttons.includes('以调试模式重启'), `应出现重启按钮,实际:${buttons.join(' / ')}`)
342
+ })
343
+
344
+ test('ClaimSection: captcha 可用时不显示重启按钮', () => {
345
+ const panel = buildPanel()
346
+ const tree = panel.render(
347
+ panel.ClaimSection({
348
+ accounts: [{ id: 'a1', index: 1, nickname: 'ACC', enabled: true }],
349
+ busy: false,
350
+ captcha: { reachable: true, debugPort: 9229 },
351
+ }),
352
+ )
353
+ const buttons = findAll(tree, (node) => node.type === 'button').map(textOf)
354
+ assert.ok(!buttons.includes('以调试模式重启'), '载体已就绪就不该再提示重启')
355
+ assert.match(textOf(tree), /captcha 载体已就绪/)
356
+ })