qoder 0.2.37: a QwenWork personal account's usage shows what is left, with each pool, instead of "no credits" (#385)

Cause: the public cloud's account-context answers a personal account's
quota with total and used null and only remaining (the reporter's
{"total": null, "used": null, "remaining": 2098.6336, "exceeded": false}).
parseAccountContext made a window only from total > 0, so every such
account read as "QwenWork: the account reports no credits". The usage
hook already read the account-context on site.usagePath, not Qoder's
/sash/api/v2/me/usage (that is the qoder path); the comment naming a
fetchSiteUsage that doesn't exist is corrected.

What QwenWork's own client reads, from QwenWorkCN.app 1.2.1's
app.asar out/main/main.js: fetchQuotaUsage reads
/api/v1/adapter/user/account-context?include=user,plan,quota,page,data_sharing
(unwrapAdapterResponse: the data object, else the envelope), and for a
personal account fetchUserWallets reads /api/v1/adapter/user/wallets,
taking daily_credits, monthly_credits and longterm_credits'
total_balance (mergeWalletsIntoCreditBreakdown).

Now: remaining is the card's balance, "2098.63 credits (daily 98.6 ·
long-term 2000)", with no used share made up; an account with a total
keeps its used / total window; remaining 0 or exceeded is a spent
window. The wallets are asked on the public cloud only, never for a biz
account or the enterprise flagship (the client doesn't either), and a
failed wallets read leaves the balance without pools. The envelope is
read wrapped in data or bare.

Not changed: an enterprise account on the public cloud, which the
client reads from /api/v2/quota/usage, still reads the account-context.

Run (bun 1.4.2): bun test in packages/qoder, 238 pass, 0 fail; bun
scripts/check.mjs, rc 0. The 5 new tests in qwenwork.test.mjs (built
from the reporter's bytes) fail on the old index.mjs, 14 pass 5 fail.
Probed gateway.qwenwork.cn with a bad token: wallets and
account-context answer 401, /sash/api/v2/me/usage 404.
Not tried: a real QwenWork account (none on this machine).
This commit is contained in:
yetone
2026-10-25 17:33:27 +08:00
parent 1fbe22b3ad
commit 60b9abf2bc
4 changed files with 148 additions and 18 deletions
+6
View File
@@ -271,6 +271,12 @@ on this same protocol, with the desktop client's client id, an RSA key the
Qoder one's equal, its own `qwork` scene, and the device token as the chat
token. The public cloud's sign-in is the desktop app's device flow, with
`redirect_uri=qwenwork-cn://`; usage reads the sign-in's account-context.
A personal account's quota there has `total` and `used` null, only
`remaining`, so the card shows what is left as its balance, with each pool
(daily, monthly, long-term) from `/api/v1/adapter/user/wallets`, as
QwenWork's own client reads them; no share used is made up. An account
with a total keeps its used / total window, and a biz account (or the
enterprise flagship) never asks for the wallets.
There is no PAT and no daily check-in on it: the `pat: false` and
`checkin: false` site fields turn both off, so Qoder's device identity is
never sent there.
+59 -16
View File
@@ -1787,7 +1787,7 @@ class UsageStatus extends Error {
// fetchUsage is the usage envelope, {displayMode, qoderUsage}; a site with
// its own usage path (QwenWork's account-context) is read by
// fetchSiteUsage below instead.
// the usage hook's site.usagePath branch instead (parseAccountContext).
async function fetchUsage(site, deviceToken) {
if (!String(deviceToken ?? "").trim()) throw new Error("qoder usage: missing device token")
let res
@@ -2083,28 +2083,59 @@ XcW+ML9FoCI6AOvOzwIDAQAB
-----END PUBLIC KEY-----`
// parseAccountContext reads the account-context QwenWork's sign-in already
// reads: plan {name, next_refresh / next_due} and quota {total, used,
// remaining} in the plan's credit unit. One window is one pool of credits.
// remaining, exceeded} in the plan's credit unit, and the wallets
// (/api/v1/adapter/user/wallets) where the public cloud has them: each
// pool's total_balance (daily_credits, monthly_credits, longterm_credits).
// That is what QwenWork's own client reads (QwenWorkCN.app 1.2.1,
// out/main/main.js: fetchQuotaUsage, fetchUserWallets,
// mergeWalletsIntoCreditBreakdown). A personal account's quota has total
// and used null, so only what is left is known: that is the balance, with
// each pool, and no share used is made up. An account with a total keeps
// its window of used / total.
const num = (v) => {
const n = Number(v)
if (!Number.isFinite(n)) return "0"
return String(Math.round(n * 100) / 100)
}
const parseAccountContext = (ctx) => {
const data = ctx?.data ?? {}
const q = data.quota
// the client's unwrapAdapterResponse: the envelope's data object, else the
// envelope itself
const unwrap = (v) => (v?.data && typeof v.data === "object" && !Array.isArray(v.data) ? v.data : (v && typeof v === "object" ? v : {}))
const finite = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined)
const POOLS = [["daily_credits", "daily"], ["monthly_credits", "monthly"], ["longterm_credits", "long-term"]]
const walletPools = (w) => {
const d = unwrap(w)
const out = []
for (const [key, name] of POOLS) {
const p = d[key]
const b = p && typeof p === "object" ? finite(p.total_balance ?? p.totalBalance) : undefined
if (b !== undefined && b > 0) out.push(`${name} ${num(b)}`)
}
return out
}
const parseAccountContext = (ctx, wallets) => {
const data = unwrap(ctx)
const q = data.quota && typeof data.quota === "object" && !Array.isArray(data.quota) ? data.quota : null
const out = {}
if (data.plan?.name) out.plan = String(data.plan.name)
const refresh = data.plan?.next_refresh_date ?? data.plan?.next_due_date
if (refresh) out.until = new Date(refresh).toISOString()
if (q && typeof q === "object") {
const total = Number(q.total)
const remaining = Number(q.remaining)
const used = Number.isFinite(Number(q.used)) ? Number(q.used) : total - remaining
if (Number.isFinite(total) && total > 0 && Number.isFinite(used) && used >= 0) {
if (q) {
const total = finite(q.total)
const remaining = finite(q.remaining)
const used = finite(q.used) ?? (total !== undefined && remaining !== undefined ? total - remaining : undefined)
if (total !== undefined && total > 0 && used !== undefined && used >= 0) {
out.windows = [{ name: "Credits", used: Math.min(100, (100 * used) / total), display: `${num(used)} / ${num(total)} credits` }]
}
if (remaining !== undefined) {
const pools = wallets ? walletPools(wallets) : []
out.balance = `${num(remaining)} credits${pools.length ? ` (${pools.join(" · ")})` : ""}`
// nothing left stops the account: say so as a spent window, since
// there is no total to show a share of
const exceeded = q.exceeded === true || q.is_quota_exceeded === true || q.isQuotaExceeded === true || remaining <= 0
if (!out.windows && exceeded) out.windows = [{ name: "Credits", used: 100, display: "no credits left" }]
}
}
if (!out.windows) out.error = "QwenWork: the account reports no credits"
if (!out.windows && out.balance === undefined) out.error = "QwenWork: the account reports no credits"
return out
}
@@ -2162,6 +2193,9 @@ const SITES = {
...QWENWORK_COMMON,
id: "qwenwork",
name: "QwenWork",
// the public cloud's personal accounts have wallets; the client asks
// for them beside the account-context, and not for an enterprise one
walletsPath: "/api/v1/adapter/user/wallets",
web: "https://gateway.qwenwork.cn",
openapi: "https://gateway.qwenwork.cn",
api: "https://gateway.qwenwork.cn",
@@ -2338,9 +2372,9 @@ const makePlugin = (site) => async ({ client }) => {
// like any other call and answered with its own envelope) is read
// there; a 401 rotates the device token once, as the qoder path does
if (site.usagePath) {
const read = async (token) => {
const read = async (token, path = site.usagePath) => {
const s = siteOf(site, cred)
const res = await fetch(`${s.openapi}${site.usagePath}`, {
const res = await fetch(`${s.openapi}${path}`, {
headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(20_000),
})
@@ -2348,14 +2382,23 @@ const makePlugin = (site) => async ({ client }) => {
return res.json()
}
let env
let token = cred.deviceToken ?? cred.access
try {
env = await read(cred.deviceToken ?? cred.access)
env = await read(token)
} catch (e) {
if (!(e instanceof UsageStatus) || (e.status !== 401 && e.status !== 403)) throw e
if (!cred.deviceToken) throw e
env = await read(await deviceToken(getAuth, cred.deviceToken))
token = await deviceToken(getAuth, cred.deviceToken)
env = await read(token)
}
return { ...(site.parseUsage ? site.parseUsage(env) : { windows: [] }), signIn }
// the pools behind the balance, as the client asks for a personal
// account's; a failed read leaves the balance without them
let wallets
const ctxUser = (env?.data ?? env)?.user
if (site.walletsPath && ctxUser?.is_biz !== true && ctxUser?.isBiz !== true) {
try { wallets = await read(token, site.walletsPath) } catch {}
}
return { ...(site.parseUsage ? site.parseUsage(env, wallets) : { windows: [] }), signIn }
}
// A PAT account has no device token: the usage endpoint takes the job
// token the exchange gave — a live PAT account answered 200 with a
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-qoder-auth",
"version": "0.2.36",
"version": "0.2.37",
"description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)",
"type": "module",
"main": "./index.mjs",
+82 -1
View File
@@ -330,4 +330,85 @@ test("a queued chat's status request is signed for the site", async () => {
} finally {
restore()
}
})
})
// #385: a public-cloud personal account's account-context has quota total
// and used null, only remaining; the pools are in /api/v1/adapter/user/wallets.
// These are the reporter's bytes.
const pubCred = () => ({ type: "oauth", uid: "u1", email: "bob@example.com", name: "Bob", machineId: "m1", access: "a", refresh: "r", expires: Date.now() + 3_600_000, deviceChat: true, deviceToken: "dt", deviceRefresh: "dtr" })
const WALLETS = { active_wallets: { wallets: [{ balance: 98.6035, valid_to: "2026-10-26T00:00:00+08:00" }, { balance: 2000, valid_to: "2026-12-18T19:50:23.14+08:00" }] }, daily_credits: { total_balance: 98.6035 }, longterm_credits: { total_balance: 2000 }, monthly_credits: { total_balance: 0 } }
const PERSONAL_QUOTA = { total: null, used: null, remaining: 2098.6336, exceeded: false }
for (const [shape, wrap] of [["wrapped in data", (v) => ({ data: v })], ["bare", (v) => v]]) {
test(`a personal account with only what is left shows it as the balance, with each pool (${shape}, #385)`, async () => {
const { pub } = await load()
const restore = mock()
answer = async (url) => {
if (url.startsWith("https://gateway.qwenwork.cn/api/v1/adapter/user/account-context")) return new Response(JSON.stringify(wrap({ user: { id: "u1" }, plan: { name: "Free" }, quota: PERSONAL_QUOTA })), { status: 200 })
if (url === "https://gateway.qwenwork.cn/api/v1/adapter/user/wallets") return new Response(JSON.stringify(wrap(WALLETS)), { status: 200 })
return new Response("{}", { status: 404 })
}
try {
const usage = await pub.auth.usage(async () => pubCred())
expect(usage.error).toBeUndefined()
expect(usage.plan).toBe("Free")
expect(usage.balance).toBe("2098.63 credits (daily 98.6 · long-term 2000)")
expect(usage.windows).toBeUndefined()
const w = seen.find((r) => r.url.endsWith("/api/v1/adapter/user/wallets"))
expect(w?.headers.Authorization).toBe("Bearer dt")
expect(seen.some((r) => r.url.includes("/sash/"))).toBe(false)
} finally {
restore()
}
})
}
test("a personal account's wallets that can't be read leave the balance without pools (#385)", async () => {
const { pub } = await load()
const restore = mock()
answer = async (url) => {
if (url.includes("/account-context")) return new Response(JSON.stringify({ data: { quota: PERSONAL_QUOTA } }), { status: 200 })
return new Response("oops", { status: 500 })
}
try {
const usage = await pub.auth.usage(async () => pubCred())
expect(usage.error).toBeUndefined()
expect(usage.balance).toBe("2098.63 credits")
} finally {
restore()
}
})
test("a personal account with nothing left is a spent window, not a share made up (#385)", async () => {
const { pub } = await load()
const restore = mock()
answer = async (url) => {
if (url.includes("/account-context")) return new Response(JSON.stringify({ data: { quota: { total: null, used: null, remaining: 0, exceeded: true } } }), { status: 200 })
if (url.endsWith("/wallets")) return new Response(JSON.stringify({ data: { daily_credits: { total_balance: 0 }, longterm_credits: { total_balance: 0 } } }), { status: 200 })
return new Response("{}", { status: 404 })
}
try {
const usage = await pub.auth.usage(async () => pubCred())
expect(usage.balance).toBe("0 credits")
expect(usage.windows).toEqual([{ name: "Credits", used: 100, display: "no credits left" }])
} finally {
restore()
}
})
test("the enterprise flagship and a biz account never read the wallets (#385)", async () => {
const { ent, pub } = await load()
const restore = mock()
answer = async (url) => {
if (url.includes("/account-context")) return new Response(JSON.stringify({ data: { user: { id: "u1", is_biz: true }, quota: { total: 100, remaining: 60 } } }), { status: 200 })
return new Response("{}", { status: 404 })
}
try {
await ent.auth.usage(async () => entCred())
const biz = await pub.auth.usage(async () => pubCred())
expect(biz.windows[0].display).toBe("40 / 100 credits")
expect(biz.balance).toBe("60 credits")
expect(seen.some((r) => r.url.includes("/wallets"))).toBe(false)
} finally {
restore()
}
})