From f6fdf8fee14dd375eb97b6d088df4da70614e318 Mon Sep 17 00:00:00 2001 From: kassama <31820658+kasisama@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:42:45 +0800 Subject: [PATCH] joycode 0.2.4: plan expiry, and one retry when gray access is denied (#701) joycode 0.2.4 (kasisama): - usage: the plan's expiry from the IDE's expireText (end of that day, China time) as `until`, with each pool's runsOutAt/runsOut; the package row decides, otherwise the earliest pool. - a gray-access denial is retried once with the identity read again. - gateway failures are read from a clone of the reply (64KB at most); a JSON reply over 8MB answers 502 response_too_large. - an empty catalogue keeps the built-in models, which are text-only. The first head (f16034b2) turned the repo suite red: usage.test.mjs called t.mock.method(globalThis, 'fetch') several times in one test, Bun 1.4 restored the wrong function, and the next file (joycode/login.test) and ~450 tests after it kept hitting the mock. b1f06b75 installs the mock once per test; nothing outside usage.test.mjs changed. Run at the reviewed head b1f06b7501bddb4f035eee069bf44d89f02e5349 (mote): - whole repo `bun test`: 5374 pass, 19 skip, 0 fail (401 files). - at f16034b2: the same run had its first red in joycode/login.test.mjs right after usage.test.mjs, an AssertionError from usage.test.mjs's mock (the leak above). - CI run 41772835368 on b1f06b75: success. Not tried: a real JoyCode account (none here); the gray-denial retry and expiry phrases are checked against the tests' fixtures only. --- packages/joycode/CHANGELOG.md | 8 ++ packages/joycode/README.md | 2 +- packages/joycode/chat.test.mjs | 96 +++++++++++++++- packages/joycode/index.mjs | 182 +++++++++++++++++++++++-------- packages/joycode/models.test.mjs | 16 +++ packages/joycode/package.json | 2 +- packages/joycode/usage.test.mjs | 64 ++++++++++- 7 files changed, 317 insertions(+), 53 deletions(-) diff --git a/packages/joycode/CHANGELOG.md b/packages/joycode/CHANGELOG.md index 3c325b9..8dbda71 100644 --- a/packages/joycode/CHANGELOG.md +++ b/packages/joycode/CHANGELOG.md @@ -1,5 +1,13 @@ # 更新记录 +## 0.2.4 + +- 从额度接口的有效期文字解析套餐到期时间。账号卡片悬停用量时显示「N 积分 将于 … 过期」(中国时区当天 23:59:59),并写入 magpie 的 `until`。套餐行优先,否则取最早的一份。不写成「重置于」,也不当成额度窗口的重置时间。 +- 网关返回 `AI_GRAY_ACCESS_DENIED` 时丢弃缓存的账号身份,重新拉取一次并重发该请求。第二次仍被拒绝则返回 403,不把账号标成登录失效。其它 403 不重试。 +- 模型目录成功但为空时保留内置模型。内置模型不再声明未验收的图片输入。非流式 JSON 读到结束再解析,超过 8MB 返回 `response_too_large`。 + +这次没有抓到新的网关原文。灰度重试只由 mock 覆盖,没有对 JoyCode 再做一次真实请求。 + ## 0.2.2 - 根据真实网关支持值修复 Codex 压缩的推理强度:GPT-6 Astra、GPT-6.1 Sol 的 `none` / `minimal` 转为 `low`;GPT-6 Sol、GPT-5.6 Sol 的 `minimal` 转为 `low`,保留这两个模型支持的 `none`。其他模型、协议、有效强度和未指定强度不变。 diff --git a/packages/joycode/README.md b/packages/joycode/README.md index 66103f6..7ac2a70 100644 --- a/packages/joycode/README.md +++ b/packages/joycode/README.md @@ -65,7 +65,7 @@ flatten 模式会把 Chat Completions 消息压平成 `system + 单条 user prom ## 已知限制 -- **额度展示**:通过 IDE 同款 `get_newpoint_ide` 接口读取套餐、已用/总积分、剩余积分和有效期文字,可在账号及用量页面刷新。有效期文字不等同于额度重置时间,因此不推算重置倒计时。多个积分池分别显示,不相加;额度窗口仅作展示,由上游判定具体模型能否继续使用。 +- **额度展示**:通过 IDE 同款 `get_newpoint_ide` 接口读取套餐、已用/总积分、剩余积分和有效期文字,可在账号及用量页面刷新。套餐行上的「有效期至」会解析成中国时区当天 23:59:59:账号卡片上悬停用量会显示「N 积分 将于 … 过期」,同时写入套餐到期时间。没有套餐行时,套餐到期时间取各积分池里最早的一份,每条用量仍显示自己的过期时间。这不是额度重置,所以不会出现「重置于」,也不推算重置倒计时。无法解析的文字仍只留在用量说明里。多个积分池分别显示,不相加;额度窗口仅作展示,由上游判定具体模型能否继续使用。 - **ptKey 失效**:表现为账号被标记「需要重新登录」,重新 `magpie plugin login joycode` 即可。 - **签名 key 轮换**:签名 key 是内嵌在每份 JoyCode IDE 里的公开协议常量,不是密钥。若 JoyCode 轮换它,从新版 `extension.js` 重新提取后,可通过环境变量 `JOYCODE_SIGN_KEY` 覆盖,无需改代码。 - 登录方式默认 `loginType: PIN_JD_CLOUD`;如果你的账号是京东云企业域登录且请求被拒,改 `index.mjs` 顶部的 `LOGIN_TYPE` 常量。 diff --git a/packages/joycode/chat.test.mjs b/packages/joycode/chat.test.mjs index 8af32d2..14eb0c0 100644 --- a/packages/joycode/chat.test.mjs +++ b/packages/joycode/chat.test.mjs @@ -28,7 +28,8 @@ function chunks(parts) { return new ReadableStream({ start(c) { for (const p of parts) c.enqueue(new TextEncoder().encode(p)); c.close() } }) } test('HTTP 200 raw gateway denial becomes actionable error, not empty SSE', async t => { - const r = await request(t, new Response(chunks([' {"error":', '{"code":"AI_GRAY_ACCESS_DENIED","message":"访问受限,请联系管理员开通"}}']), { headers: { 'content-type': 'text/event-stream' } })) + const denial = () => new Response(chunks([' {"error":', '{"code":"AI_GRAY_ACCESS_DENIED","message":"访问受限,请联系管理员开通"}}']), { headers: { 'content-type': 'text/event-stream' } }) + const r = await request(t, denial) assert.equal(r.status, 403) assert.equal(r.headers.get('x-magpie-sign-in'), 'kept') assert.equal((await r.json()).error.code, 'AI_GRAY_ACCESS_DENIED') @@ -495,7 +496,98 @@ test('flatten applies only to Chat Completions, never Responses', async t => { }) test('HTTP 403 permission denial is not marked as expired credentials', async t => { - const r = await request(t, Response.json({ error: { code: 'AI_GRAY_ACCESS_DENIED', message: 'denied' } }, { status: 403 })) + const r = await request(t, () => Response.json({ error: { code: 'AI_GRAY_ACCESS_DENIED', message: 'denied' } }, { status: 403 })) assert.equal(r.status, 403) assert.equal(r.headers.get('x-magpie-sign-in'), 'kept') }) + +test('AI_GRAY_ACCESS_DENIED refreshes identity once and retries with the new account', async t => { + let infoCalls = 0 + let chats = 0 + t.mock.method(globalThis, 'fetch', async (url, init) => { + if (new URL(url).searchParams.get('functionId') === 'joycode_userInfo') { + infoCalls++ + return Response.json({ + code: 0, + data: infoCalls === 1 + ? { userId: 'test-user', tenant: '', orgFullName: '' } + : { userId: 'test-user', tenant: 'refreshed-tenant', orgFullName: 'refreshed-org' }, + }) + } + chats++ + const sent = JSON.parse(init.body) + if (chats === 1) { + assert.equal(sent.orgFullName, '') + assert.equal(sent.tenant, '') + return Response.json({ code: 'AI_GRAY_ACCESS_DENIED', msg: '访问受限,请联系管理员开通' }) + } + assert.equal(sent.orgFullName, 'refreshed-org') + assert.equal(sent.tenant, 'refreshed-tenant') + assert.equal(init.headers.get('tenant'), 'refreshed-tenant') + return new Response('data: [DONE]\n\n', { headers: { 'content-type': 'text/event-stream' } }) + }) + const hooks = await plugin.server({}) + const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' })) + const r = await loader.fetch('https://api-ai.jd.com/v1/chat/completions', { + method: 'POST', + body: JSON.stringify({ model: 'JoyAI-Code-1.6', messages: [{ role: 'user', content: 'OK' }], stream: true }), + }) + assert.equal(r.status, 200) + assert.equal(await r.text(), 'data: [DONE]\n\n') + assert.equal(infoCalls, 2) + assert.equal(chats, 2) +}) + +test('a second AI_GRAY_ACCESS_DENIED stays 403 and does not fetch identity again', async t => { + let infoCalls = 0 + let chats = 0 + t.mock.method(globalThis, 'fetch', async (url) => { + if (new URL(url).searchParams.get('functionId') === 'joycode_userInfo') { + infoCalls++ + return Response.json({ code: 0, data: { userId: 'test-user', tenant: 't', orgFullName: 'o' } }) + } + chats++ + return Response.json({ code: 'AI_GRAY_ACCESS_DENIED', msg: '访问受限,请联系管理员开通' }) + }) + const hooks = await plugin.server({}) + const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' })) + const r = await loader.fetch('https://api-ai.jd.com/v1/chat/completions', { + method: 'POST', + body: JSON.stringify({ model: 'JoyAI-Code-1.6', messages: [{ role: 'user', content: 'OK' }] }), + }) + assert.equal(r.status, 403) + assert.equal(r.headers.get('x-magpie-sign-in'), 'kept') + assert.equal((await r.json()).error.message, '访问受限,请联系管理员开通') + assert.equal(infoCalls, 2) + assert.equal(chats, 2) +}) + +test('plain HTTP 403 is not retried', async t => { + let infoCalls = 0 + let chats = 0 + t.mock.method(globalThis, 'fetch', async (url) => { + if (new URL(url).searchParams.get('functionId') === 'joycode_userInfo') { + infoCalls++ + return Response.json({ code: 0, data: { userId: 'test-user', tenant: 't', orgFullName: 'o' } }) + } + chats++ + return new Response('nope', { status: 403 }) + }) + const hooks = await plugin.server({}) + const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' })) + const r = await loader.fetch('https://api-ai.jd.com/v1/chat/completions', { + method: 'POST', + body: JSON.stringify({ model: 'JoyAI-Code-1.6', messages: [{ role: 'user', content: 'OK' }] }), + }) + assert.equal(r.status, 403) + assert.equal(r.headers.get('x-magpie-sign-in'), 'kept') + assert.equal(infoCalls, 1) + assert.equal(chats, 1) +}) + +test('non-streaming chat JSON larger than 1MB is returned intact', async t => { + const content = 'x'.repeat(1_200_000) + const r = await request(t, Response.json({ choices: [{ message: { content } }] })) + assert.equal(r.status, 200) + assert.equal((await r.json()).choices[0].message.content, content) +}) diff --git a/packages/joycode/index.mjs b/packages/joycode/index.mjs index 76f5cbf..c1282ee 100644 --- a/packages/joycode/index.mjs +++ b/packages/joycode/index.mjs @@ -80,21 +80,21 @@ const MODELS = { limit: { context: 200000, output: 64000 }, reasoning: true, tool_call: true, - modalities: { input: ['text', 'image'] }, + modalities: { input: ['text'] }, }, 'MiniMax-M3-agent': { name: 'MiniMax M3', limit: { context: 200000, output: 64000 }, reasoning: true, tool_call: true, - modalities: { input: ['text', 'image'] }, + modalities: { input: ['text'] }, }, 'Doubao-Seed-2.0-pro-agent': { name: 'Doubao Seed 2.0 Pro', limit: { context: 200000, output: 64000 }, reasoning: true, tool_call: true, - modalities: { input: ['text', 'image'] }, + modalities: { input: ['text'] }, }, } @@ -377,6 +377,9 @@ async function browserLogin() { // ---------------------------------------------------------------- chat responses +const JSON_BODY_LIMIT = 8 * 1024 * 1024 +const GRAY_ACCESS_DENIED = 'AI_GRAY_ACCESS_DENIED' + function chatError(status, code, message) { return Response.json({ error: { type: 'upstream_error', code, message } }, { status, @@ -384,6 +387,41 @@ function chatError(status, code, message) { }) } +/** + * Business code from a JSON body, read off a clone so the original response + * can still be normalized. Non-JSON (SSE) returns nothing. cancel() is not + * awaited: the clone's tee waits until the original body is read. + */ +async function gatewayFailure(response) { + if (!response?.body) return {} + let clone + try { clone = response.clone() } catch { return {} } + const reader = clone.body.getReader() + const decoder = new TextDecoder() + let prefix = '' + let bytes = 0 + try { + while (bytes <= 65536) { + const next = await reader.read() + if (next.done) break + bytes += next.value.byteLength + prefix += decoder.decode(next.value, { stream: true }) + if (prefix.trim() && !prefix.trimStart().startsWith('{')) break + } + prefix += decoder.decode() + } catch { + return {} + } finally { + reader.cancel().catch(() => {}) + } + if (!prefix.trimStart().startsWith('{')) return {} + let json + try { json = JSON.parse(prefix) } catch { return {} } + const code = json?.error?.code ?? json?.code + const message = json?.error?.message ?? json?.message ?? json?.msg + return { code, message: typeof message === 'string' ? message : undefined } +} + function isSuccessfulJson(json, protocol) { if (!json || typeof json !== 'object') return false if (protocol === 'chat') return Boolean(json.choices) @@ -526,10 +564,18 @@ async function normalizeResponse(response, protocol = 'chat') { return chatError(502, 'empty_response', 'JoyCode 返回空响应') } if (prefix.trimStart().startsWith('{')) { - while (bytes <= 1024 * 1024) { + if (bytes > JSON_BODY_LIMIT) { + await reader.cancel() + return chatError(502, 'response_too_large', 'JoyCode 响应超过 8MB') + } + while (true) { const next = await reader.read() if (next.done) break bytes += next.value.byteLength + if (bytes > JSON_BODY_LIMIT) { + await reader.cancel() + return chatError(502, 'response_too_large', 'JoyCode 响应超过 8MB') + } prefix += decoder.decode(next.value, { stream: true }) } await reader.cancel() @@ -538,7 +584,7 @@ async function normalizeResponse(response, protocol = 'chat') { try { json = JSON.parse(prefix) } catch {} if (json?.error || (json?.code !== undefined && Number(json.code) !== 0)) { const code = json.error?.code ?? json.code - const status = code === 'AI_GRAY_ACCESS_DENIED' ? 403 : Number(code) === 401 ? 401 : 502 + const status = code === GRAY_ACCESS_DENIED ? 403 : Number(code) === 401 ? 401 : 502 const message = json.error?.message ?? json.message ?? json.msg return chatError(status, code, typeof message === 'string' ? message.slice(0, 500) : 'JoyCode 请求被拒绝') } @@ -602,6 +648,26 @@ async function fetchAccountData(auth, functionId, body = {}) { return json.data ?? json } +/** + * JoyCode sends a calendar phrase such as "有效期至 2026年11月11日", not an + * instant. 23:59:59 that China calendar day is the last moment the IDE still + * calls valid, and it is what magpie prints on the account-card tooltip. + * This is plan expiry, not a quota-window reset, so callers must not copy it + * onto resetsAt — that tooltip line would say the credits reset. + */ +function expiryUntil(text) { + if (typeof text !== 'string' || !text) return undefined + const match = text.match(/(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日/) + ?? text.match(/(\d{4})[-/](\d{1,2})[-/](\d{1,2})/) + if (!match) return undefined + const year = Number(match[1]) + const month = Number(match[2]) + const day = Number(match[3]) + if (!Number.isInteger(year) || year < 2000 || month < 1 || month > 12 || day < 1) return undefined + if (day > new Date(Date.UTC(year, month, 0)).getUTCDate()) return undefined + return new Date(Date.UTC(year, month - 1, day, 15, 59, 59)).toISOString() +} + function quotaFromData(data) { const items = data?.usageItems if (!Array.isArray(items) || !items.length) throw new Error('JoyCode 暂未返回额度数据') @@ -611,21 +677,35 @@ function quotaFromData(data) { } const format = value => new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(value) const plans = [...new Set(items.map(item => item.badge).filter(value => typeof value === 'string' && value))] + const dated = items.flatMap(item => { + const until = expiryUntil(item.expireText) + return until ? [{ until, plan: typeof item.badge === 'string' && item.badge }] : [] + }) + const expiries = dated.filter(item => item.plan).map(item => item.until) + const until = (expiries.length ? expiries : dated.map(item => item.until)).sort()[0] return { ...(plans.length ? { plan: plans.join(' / ') } : {}), + ...(until ? { until } : {}), // Different buckets may overlap; do not manufacture a summed balance. ...(items.length === 1 ? { balance: `${format(items[0].remain)} ${items[0].unit || '积分'}` } : {}), - windows: items.map(item => ({ - name: item.title, - used: item.usedPercent, - amount: item.used, - limit: item.total, - unit: item.unit || '积分', - display: `${format(item.used)} / ${format(item.total)} · 剩余 ${format(item.remain)}${item.expireText ? ` · ${item.expireText}` : ''}`, - // Bucket applicability is unspecified, and free models can remain usable. - // Show the balance without blocking the entire account at 100%. - aside: true, - })), + windows: items.map(item => { + const expires = expiryUntil(item.expireText) + return { + name: item.title, + used: item.usedPercent, + amount: item.used, + limit: item.total, + unit: item.unit || '积分', + display: `${format(item.used)} / ${format(item.total)} · 剩余 ${format(item.remain)}${item.expireText ? ` · ${item.expireText}` : ''}`, + // The card composes its own "used / limit" line and ignores display. + // runsOutAt is the hover line "N 积分 将于 … 过期". resetsAt would + // be mislabeled "重置于". + ...(expires ? { runsOutAt: expires, runsOut: item.remain } : {}), + // Bucket applicability is unspecified, and free models can remain usable. + // Show the balance without blocking the entire account at 100%. + aside: true, + } + }), } } @@ -654,7 +734,8 @@ async function accountModels(provider, { auth } = {}) { for (const result of [catalogue, pricing]) { if (result.status === 'rejected' && result.reason?.signIn === 'expired') throw result.reason } - if (catalogue.status !== 'fulfilled' || !Array.isArray(catalogue.value)) return provider.models + // An empty catalogue is a glitch, not "this account has no models". + if (catalogue.status !== 'fulfilled' || !Array.isArray(catalogue.value) || catalogue.value.length === 0) return provider.models const scene = pricing.status === 'fulfilled' ? billingScene(pricing.value) : undefined const tenant = auth.metadata?.tenant?.trim() const excluded = (scene?.excludeTenants ?? []).some(value => typeof value === 'string' && value.trim() === tenant) @@ -772,7 +853,8 @@ export const JoyCodeAuthPlugin = async (_input, options) => { } // Preserve chat structure; the IDE also adds authenticated metadata. - const account = await identity() + // The host payload is parsed once. A gray denial refreshes identity + // and resends that same payload; effort rewrites must not run twice. const request = input instanceof Request ? input : undefined let source = init?.body if (source === undefined && request) source = await request.clone().text() @@ -787,36 +869,46 @@ export const JoyCodeAuthPlugin = async (_input, options) => { payload.reasoning = { ...payload.reasoning, effort: 'low' } } const forwarded = protocol === 'responses' ? withoutUnstoredReasoningIds(payload) : payload - const body = JSON.stringify({ - ...(flatten && protocol === 'chat' ? flattenBody(payload) : forwarded), - ...account, - language: 'UNKNOWN', - }) + const functionId = FUNCTION_IDS[protocol] - // 2) URL: fresh signature per request, on the model's wire protocol. - const url = buildGatewayUrl(FUNCTION_IDS[protocol]) - - // 3) Headers: keep what magpie synthesized (content-type, …), - // add the gateway credentials, drop the OpenAI-style bearer - // JoyCode does not understand. - const headers = new Headers(init?.headers ?? request?.headers) - for (const [k, v] of Object.entries(buildGatewayHeaders(ptKey, account.tenant, loginType))) { - headers.set(k, v) + const send = async () => { + const account = await identity() + const body = JSON.stringify({ + ...(flatten && protocol === 'chat' ? flattenBody(payload) : forwarded), + ...account, + language: 'UNKNOWN', + }) + const url = buildGatewayUrl(functionId) + // Rebuild headers per attempt so an empty tenant cannot stick. + const headers = new Headers(init?.headers ?? request?.headers) + headers.delete('tenant') + for (const [k, v] of Object.entries(buildGatewayHeaders(ptKey, account.tenant, loginType))) { + headers.set(k, v) + } + headers.delete('authorization') + headers.delete('x-api-key') + headers.delete('content-length') + headers.delete('host') + const resp = await fetch(url, { + ...init, + method: init?.method ?? request?.method, + headers, + body, + signal: init?.signal ?? request?.signal, + }) + return { resp, account } } - headers.delete('authorization') - headers.delete('x-api-key') - headers.delete('content-length') - headers.delete('host') - - // 4) Forward (...init carries the abort signal). - const resp = await fetch(url, { - ...init, - method: init?.method ?? request?.method, - headers, - body, - signal: init?.signal ?? request?.signal, - }) + let { resp } = await send() + const failure = await gatewayFailure(resp) + // Missing account fields are cached with the first userInfo. One + // refresh can recover; a second denial is the gateway's answer. + // Other 403s (a bad signature, a clock) are not retried. + if (failure.code === GRAY_ACCESS_DENIED) { + await resp.body?.cancel?.().catch(() => {}) + identityPromise = undefined + ;({ resp } = await send()) + } return normalizeResponse(resp, protocol) }, } diff --git a/packages/joycode/models.test.mjs b/packages/joycode/models.test.mjs index 6d843a3..1510e04 100644 --- a/packages/joycode/models.test.mjs +++ b/packages/joycode/models.test.mjs @@ -68,3 +68,19 @@ test('catalogue fetch failure returns original fallback model list', async t => const { models, provider } = await load(t, { failList: true }) assert.equal(models, provider.models) }) +test('empty catalogue keeps the fallback model list', async t => { + const { models, provider } = await load(t, { list: [] }) + assert.equal(models, provider.models) +}) +test('a catalogue of only hidden models does not fall back', async t => { + const { models } = await load(t, { list: [{ chatApiModel: 'JoyAI-Code-1.6', hidden: true }] }) + assert.deepEqual(models, {}) +}) +test('static fallback models do not advertise image input', async t => { + const hooks = await plugin.server({}) + const cfg = {} + await hooks.config(cfg) + for (const id of ['Kimi-K2.6-agent', 'MiniMax-M3-agent', 'Doubao-Seed-2.0-pro-agent']) { + assert.deepEqual(cfg.provider.joycode.models[id].modalities.input, ['text']) + } +}) diff --git a/packages/joycode/package.json b/packages/joycode/package.json index cc6c728..af363b8 100644 --- a/packages/joycode/package.json +++ b/packages/joycode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-joycode-auth", - "version": "0.2.3", + "version": "0.2.4", "description": "OpenCode provider plugin: JoyCode (JD Cloud JoyCoder IDE credits)", "type": "module", "main": "./opencode.mjs", diff --git a/packages/joycode/usage.test.mjs b/packages/joycode/usage.test.mjs index 3a16fd3..05b690b 100644 --- a/packages/joycode/usage.test.mjs +++ b/packages/joycode/usage.test.mjs @@ -5,7 +5,11 @@ import plugin from './index.mjs' const auth = { type: 'api', key: 'fake-ticket', metadata: { tenant: '测试租户', loginType: 'PIN_JD_CLOUD' } } const item = { type: 'seatPackage', title: '套餐积分', badge: '团队版(限免)', used: 0, total: 10000, remain: 10000, usedPercent: 0, expireText: '有效期至 2026年11月11日' } -async function query(t, response, account = auth) { +// Install fetch once per test. Calling mock.method again in the same test +// makes Bun 1.4 restore the wrong function, and packages that captured +// global fetch at import (the nonet guards) keep calling this mock. +function mockQuota(t, account = auth) { + let response = () => { throw new Error('no quota response') } t.mock.method(globalThis, 'fetch', async (url, init) => { assert.equal(new URL(url).origin, 'https://api-ai.jd.com') assert.equal(new URL(url).searchParams.get('functionId'), 'get_newpoint_ide') @@ -17,9 +21,16 @@ async function query(t, response, account = auth) { assert.ok(init.signal) return response() }) - const hooks = await plugin.server({}) - assert.equal(typeof hooks.auth.usage, 'function') - return hooks.auth.usage(async () => account) + return async next => { + response = next + const hooks = await plugin.server({}) + assert.equal(typeof hooks.auth.usage, 'function') + return hooks.auth.usage(async () => account) + } +} + +async function query(t, response, account = auth) { + return mockQuota(t, account)(response) } test('maps actual IDE quota schema including zero usage and expiry text', async (t) => { @@ -32,6 +43,50 @@ test('maps actual IDE quota schema including zero usage and expiry text', async assert.match(result.windows[0].display, /剩余 10,000/) assert.match(result.windows[0].display, /2026年11月11日/) assert.equal(result.windows[0].resetsAt, undefined) + // 23:59:59 on 2026-11-11 in China, shown as "将于 … 过期", not a reset. + assert.equal(result.until, '2026-11-11T15:59:59.000Z') + assert.equal(result.windows[0].runsOutAt, '2026-11-11T15:59:59.000Z') + assert.equal(result.windows[0].runsOut, 10000) +}) + +test('plan expiry accepts the IDE date phrases and ignores text that is not a date', async (t) => { + const run = mockQuota(t) + for (const [expireText, until] of [ + ['有效期至2026年11月11日', '2026-11-11T15:59:59.000Z'], + ['2026-11-11', '2026-11-11T15:59:59.000Z'], + ['2026/11/11', '2026-11-11T15:59:59.000Z'], + ['2024年2月29日', '2024-02-29T15:59:59.000Z'], + ['长期有效', undefined], + ['有效期至 2026年2月31日', undefined], + ['有效期至 1999年11月11日', undefined], + ]) { + const result = await run(() => Response.json({ code: 0, data: { usageItems: [{ ...item, expireText }] } })) + assert.equal(result.until, until, expireText) + assert.equal(result.windows[0].runsOutAt, until, expireText) + assert.equal(result.windows[0].runsOut, until ? 10000 : undefined, expireText) + assert.equal(result.windows[0].resetsAt, undefined) + assert.match(result.windows[0].display, new RegExp(expireText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))) + } +}) + +test('plan expiry follows the package row, and otherwise the earliest pool', async (t) => { + const run = mockQuota(t) + const packaged = await run(() => Response.json({ code: 0, data: { usageItems: [ + { ...item, expireText: '有效期至 2026年12月1日' }, + { title: '加油包', used: 0, total: 100, remain: 100, usedPercent: 0, expireText: '2026-11-01' }, + ] } })) + assert.equal(packaged.until, '2026-12-01T15:59:59.000Z') + assert.equal(packaged.windows[0].runsOutAt, '2026-12-01T15:59:59.000Z') + assert.equal(packaged.windows[0].runsOut, 10000) + assert.equal(packaged.windows[1].runsOutAt, '2026-11-01T15:59:59.000Z') + assert.equal(packaged.windows[1].runsOut, 100) + assert.ok(packaged.windows.every(window => window.resetsAt === undefined)) + + const pools = await run(() => Response.json({ code: 0, data: { usageItems: [ + { title: '套餐积分', used: 0, total: 100, remain: 100, usedPercent: 0, expireText: '2026-12-01' }, + { title: '加油包', used: 0, total: 100, remain: 100, usedPercent: 0, expireText: '2026-11-01' }, + ] } })) + assert.equal(pools.until, '2026-11-01T15:59:59.000Z') }) test('multiple pools preserve balances without one exhausted pool blocking the account', async (t) => { @@ -40,6 +95,7 @@ test('multiple pools preserve balances without one exhausted pool blocking the a { title: '加油包', used: 250, total: 1000, remain: 750, usedPercent: 25 }, ] } })) assert.equal(result.balance, undefined) + assert.equal(result.until, '2026-11-11T15:59:59.000Z') assert.deepEqual(result.windows.map(w => w.used), [100, 25]) assert.ok(result.windows.every(w => w.aside === true)) })