workbuddy 0.2.17: extra credits only the detail lists have are their own window

jiabubu on Discord (magpie 0.1.2774, workbuddy 0.2.16, a China-site free
account): magpie's card read "Free plan · 0 / 500" and nothing else, with no
Extra credits row. 0.2.16 splits the credits only by the resource summary
(CreditGroups, else its Packages). WorkBuddy's own usage panel (5.5.6,
buildCreditGroups) groups the packages of the paid and free detail lists, so
extra credits only those lists carry were nowhere in magpie.

The usage hook now adds, when the summary has the plan's credits alone, an
"Extra credits" window from the detail lists' packages that:
- are an extra kind as the client's resolveCreditGroup has it (bonus 028/037,
  top-ups 009/038/036, rewards 007/029/030; on WorkBuddy AI also 008 and 006;
  the China build puts gift 006 in no group);
- the summary doesn't list (never counted twice);
- haven't ended, and have a total (a slice package counts the day's slice).
It is set aside, and says the soonest-lapsing credits (runsOutAt/runsOut).
The plan's window still stops the account. Lists that can't be read, or a
summary that already splits, keep the card as it was.

Run at this head on mote: `HOME=$(mktemp -d) bun test` 4892 pass, 14 skip,
0 fail; `bun scripts/check.mjs` ok. Broken by hand: not adding the window
turns the new test red (1 fail).

Not tried: a real account with extra credits; the China meter answered 401
for the account I could read. The fixtures are CN_FREE's shapes with a
total, not jiabubu's own bytes (not seen).
This commit is contained in:
yetone
2026-11-03 11:02:26 +08:00
parent e08e420581
commit da94c2768a
3 changed files with 136 additions and 19 deletions
+82 -18
View File
@@ -2884,9 +2884,30 @@ function pinning() {
// spent and extra ones are left.
function usageOf(sum, plan, site) {
const out = { plan: plan || (sum?.IsPaidUser ? "Pro" : "Free plan"), windows: [] }
const { plan: mine, extra, left, bags } = kindsOf(sum, site)
if (mine.total > 0 && extra.total > 0) {
const credits = creditWindow("Credits", mine), more = creditWindow("Extra credits", extra)
if (mine.used >= mine.total && extra.used < extra.total) credits.aside = true
else more.aside = true
out.windows.push(credits, more)
} else {
const total = mine.total + extra.total, used = mine.used + extra.used
if (total > 0) out.windows.push(creditWindow("Credits", { used, total }))
}
const total = mine.total + extra.total
if (bags > 0 && (total === 0 || left > 0)) out.windows.push({ name: "Prepaid credits", balance: left, display: `${compact(left)} credits`, unit: "credits" })
return out
}
// creditWindow is a window of credits used of a total.
const creditWindow = (name, { used, total }) => ({ name, used: (100 * used) / total, display: `${compact(used)} / ${compact(total)}`, amount: used, limit: total, unit: "credits" })
// kindsOf is the summary's credits, the plan's and the extra ones (see
// usageOf), and what is left in its packages with no total (a prepaid
// balance).
function kindsOf(sum, site) {
const ofPlan = planCodes(sum, site)
const kinds = { plan: { total: 0, used: 0 }, extra: { total: 0, used: 0 } }
let left = 0, bags = 0
const kinds = { plan: { total: 0, used: 0 }, extra: { total: 0, used: 0 }, left: 0, bags: 0 }
const hasTotal = (p) => p?.CycleTotalCapacity != null && p.CycleTotalCapacity !== ""
const add = (k, p) => ((k.total += capacity(p.CycleTotalCapacity)), (k.used += capacity(p?.CycleUsedCapacity)))
const groups = (Array.isArray(sum?.CreditGroups) ? sum.CreditGroups : []).filter(hasTotal)
@@ -2895,24 +2916,45 @@ function usageOf(sum, plan, site) {
if (hasTotal(p)) {
if (!groups.length) add(kinds[ofPlan(p?.PackageCode) ? "plan" : "extra"], p)
} else if (p?.CycleRemainCapacity != null && p.CycleRemainCapacity !== "") {
left += capacity(p.CycleRemainCapacity)
bags++
kinds.left += capacity(p.CycleRemainCapacity)
kinds.bags++
}
}
const window = (name, { used, total }) => ({ name, used: (100 * used) / total, display: `${compact(used)} / ${compact(total)}`, amount: used, limit: total, unit: "credits" })
const { plan: mine, extra } = kinds
if (mine.total > 0 && extra.total > 0) {
const credits = window("Credits", mine), more = window("Extra credits", extra)
if (mine.used >= mine.total && extra.used < extra.total) credits.aside = true
else more.aside = true
out.windows.push(credits, more)
} else {
const total = mine.total + extra.total, used = mine.used + extra.used
if (total > 0) out.windows.push(window("Credits", { used, total }))
return kinds
}
// listedExtra is the extra credits of the detail lists (packagesOf) that
// the summary doesn't list at all, as WorkBuddy's own usage panel counts
// them (jiabubu on Discord, magpie 0.1.2774, a China-site free account:
// magpie's card read "0 / 500" alone, while the panel shows the extra
// kinds beside the plan's). The panel's groups come from the detail
// lists, not the summary (buildCreditGroups over fetchUserResources' paid
// and free lists), and leave out a package past its end; a slice package
// (CapacityType 4) counts the day's slice, as resolveResourceCapacity
// does. null when there are none with credits.
function listedExtra(sum, packages, site, now = Date.now()) {
const summed = new Set((sum?.Packages ?? []).map((p) => p?.PackageCode))
const codes = site?.ai ? [...EXTRA_CODES, ...EXTRA_AI] : EXTRA_CODES
let total = 0, left = 0, at = 0, lapsing = 0
for (const p of packages ?? []) {
const code = p?.PackageCode
if (!codes.includes(code) || summed.has(code)) continue
const end = endOf(p)
if (end > 0 && end <= now) continue
const slice = String(p?.CapacityType) === SLICE ? p?.SlicePeriodUsageDetails?.[0] : null
const of = (v) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0 }
const t = of(slice ? slice.SlicePeriodCapacitySizePrecise : p?.CycleCapacitySizePrecise)
const l = Math.min(t, of(slice ? slice.SlicePeriodCapacityRemainPrecise : p?.CycleCapacityRemainPrecise))
if (!(t > 0)) continue
total += t
left += l
if (l > 0 && end > 0 && !slice) {
if (!at || end < at) at = end, lapsing = l
else if (end === at) lapsing += l
}
}
const total = mine.total + extra.total
if (bags > 0 && (total === 0 || left > 0)) out.windows.push({ name: "Prepaid credits", balance: left, display: `${compact(left)} credits`, unit: "credits" })
return out
if (!(total > 0)) return null
return { total, used: total - left, ...(at ? { runsOutAt: new Date(at).toISOString(), runsOut: lapsing } : {}) }
}
// enterpriseUsageOf is an enterprise (team) account's credits, from
@@ -2980,6 +3022,16 @@ const PLAN_CODES = [CODE("002", "AkiJS3ZHF5"), CODE("005", "maRGyrHhw1"), CODE("
CODE("039", "KRcQj7wUat"), CODE("040", "mi9rCYg46x")]
const FREE_MON = CODE("008", "cfWoLwvjU4")
// EXTRA_CODES are the kinds of extra credits WorkBuddy's own usage panel
// shows beside the plan's base (WorkBuddy 5.5.6, the China build's
// resolveCreditGroup): the plan's bonus (bonus28, bonusIntl), top-ups
// (extra 009, extra38 038, extraIntl 036) and platform rewards (activity
// 007, bonus29, bonus30), and on WorkBuddy AI the free month (008) and
// gift (006) too. The China build puts gift in no group, so it shows none.
const EXTRA_CODES = [CODE("028", "NtpWi0jzXs"), CODE("037", "WxOD3MpI2o"), CODE("009", "0XmEQc2xOf"), CODE("038", "OhvqZtiPKr"),
CODE("036", "lupO5WgNdG"), CODE("007", "nzdH5h4Nl0"), CODE("029", "6wCGEWquYy"), CODE("030", "BjSt89qTvr")]
const EXTRA_AI = [FREE_MON, CODE("006", "DbXS0lrypC")]
// planCodes says whether a package of the summary is the plan's own: one
// of PLAN_CODES on that site, or the subscription the summary names.
function planCodes(sum, site) {
@@ -3816,6 +3868,18 @@ function makePlugin(site) {
Object.assign(stops, runsOutOf(sum, packages) ?? {})
const aside = extra ? (stops === credits ? extra : credits) : null
if (aside) Object.assign(aside, runsOutOf(sum, packages, Date.now(), (code) => ofPlan(code) === (aside === credits)) ?? {})
// the summary of the plan's credits alone: the extra ones
// only the detail lists have (listedExtra) are their window,
// always set aside. Whether WorkBuddy spends them once the
// plan's are gone isn't seen, so the plan's window stops the
// account as it did before.
const kinds = !extra && kindsOf(sum, site)
const more = kinds && kinds.plan.total > 0 && kinds.extra.total === 0 ? listedExtra(sum, packages, site) : null
if (more) {
const { runsOutAt, runsOut, ...counts } = more
const w = { ...creditWindow("Extra credits", counts), aside: true, ...(runsOutAt ? { runsOutAt, runsOut } : {}) }
out.windows.splice(out.windows.indexOf(credits) + 1, 0, w)
}
} catch {}
}
await spareFree(site, a, out.windows)
@@ -3973,4 +4037,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
// for tests
export const _internal = { planCodes, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, SMALL_BUDGET, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, readLedgerTail, pinned, pinning, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_CN, FREE_WINDOW_AI, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM }
export const _internal = { planCodes, listedExtra, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, SMALL_BUDGET, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, readLedgerTail, pinned, pinning, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_CN, FREE_WINDOW_AI, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-workbuddy-auth",
"version": "0.2.16",
"version": "0.2.17",
"description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
"type": "module",
"main": "./index.mjs",
+53
View File
@@ -542,6 +542,59 @@ test("split, the plan's window keeps its cycle and each says what lapses", async
expect(credits.runsOutAt).toBe(extra.runsOutAt)
})
// jiabubu on Discord (magpie 0.1.2774, workbuddy 0.2.16, a China-site free
// account): the card read "Free plan · 0 / 500" and nothing else. WorkBuddy's
// own usage panel (WorkBuddy 5.5.6, buildCreditGroups) groups the packages
// of the detail lists, not the summary's, so extra credits only those lists
// have show there and were nowhere in magpie. The summary below is the plan's
// base alone (CN_FREE_SUMMARY's 008); the lists' packages are CN_FREE's
// shapes with a total, not the reporter's bytes (not seen).
test("extra credits only the detail lists have are a window of their own, set aside (jiabubu on Discord)", async () => {
const { SITES } = _internal
const year = Date.UTC(2036, 9, 1) - Date.UTC(2026, 9, 1)
const on = (p) => ({ ...p, DeductionEndTime: p.DeductionEndTime + year, CycleStartTime: "2036" + p.CycleStartTime.slice(4), CycleEndTime: "2036" + p.CycleEndTime.slice(4) })
const base = { ...CN_FREE.Accounts[1], CycleCapacitySizePrecise: "500", CycleCapacityRemainPrecise: "500", SlicePeriodUsageDetails: [{ SlicePeriodCapacitySizePrecise: "500", SlicePeriodCapacityRemainPrecise: "500" }] }
const gift = { ...CN_FREE.Accounts[0], CycleCapacitySizePrecise: "300", CycleCapacityRemainPrecise: "280" }
const topup = { PackageCode: "TCACA_code_009_0XmEQc2xOf", PackageName: "加量包", CapacityType: 1, CycleCapacitySizePrecise: "1000", CycleCapacityRemainPrecise: "1000",
CycleStartTime: "2026-10-02 10:00:00", CycleEndTime: "2027-10-02 09:59:59", DeductionEndTime: Date.parse("2027-10-02T01:59:59Z"), ExpiredTime: "", Status: 0 }
const summary = { ...CN_FREE_SUMMARY, Packages: [CN_FREE_SUMMARY.Packages[1]] }
serve({
"/billing/meter/get-user-resource-summary": () => ok(summary),
"/billing/meter/get-user-resource-paid-packages": () => ok({ TotalCount: 1, Accounts: [on(topup)] }),
"/billing/meter/get-user-resource-free-packages": () => ok({ TotalCount: 2, Accounts: [on(gift), on(base)] }),
})
const u = await usageOf(WorkBuddyAuthPlugin, { type: "oauth", access: "a", refresh: "r", expires: later(), uid: "u" })
expect(u.windows.slice(0, 2).map((w) => [w.name, w.display, !!w.aside])).toEqual([["Credits", "0 / 500", false], ["Extra credits", "20 / 1300", true]])
// the soonest to lapse is the activity's, on the window that says them
expect(u.windows[1]).toMatchObject({ amount: 20, limit: 1300, runsOut: 280, runsOutAt: new Date(on(gift).DeductionEndTime).toISOString() })
// the plan's window keeps its cycle
expect(u.windows[0].resetsAt).toBe("2036-10-31T15:59:59.000Z")
const now = Date.parse("2026-11-03T00:00:00Z")
// past its end, a package is not counted, as the panel leaves it out
expect(_internal.listedExtra(summary, [gift, topup], SITES.workbuddy, now)).toEqual({ total: 1000, used: 0, runsOutAt: "2027-10-02T01:59:59.000Z", runsOut: 1000 })
// one the summary lists is the summary's, never counted twice
expect(_internal.listedExtra(CN_FREE_SUMMARY, [on(gift)], SITES.workbuddy, now)).toBeNull()
// the plan's base is never extra; nor, on the China build, a gift (006)
const giftPack = { ...topup, PackageCode: "TCACA_code_006_DbXS0lrypC" }
expect(_internal.listedExtra(summary, [base, giftPack], SITES.workbuddy, now)).toBeNull()
// WorkBuddy AI's panel counts gift and the free month among the rewards
expect(_internal.listedExtra(GROUPS_SUMMARY, [giftPack, { ...topup, PackageCode: "TCACA_code_008_cfWoLwvjU4" }], SITES["workbuddy-ai"], now)?.total).toBe(2000)
// a package with no total adds nothing
expect(_internal.listedExtra(summary, [{ ...topup, CycleCapacitySizePrecise: "" }], SITES.workbuddy, now)).toBeNull()
})
test("a summary that already splits the credits, or lists with no extra ones, keep the card as it was", async () => {
const empty = () => ok({ TotalCount: 0, Accounts: [] })
serve({
"/billing/meter/get-user-resource-summary": () => ok(GROUPS_SUMMARY),
"/billing/meter/get-user-resource-paid-packages": empty,
"/billing/meter/get-user-resource-free-packages": empty,
})
const u = await usageOf(WorkBuddyAIAuthPlugin, { type: "oauth", access: "a", refresh: "r", expires: later(), uid: "u" })
expect(u.windows.map((w) => [w.name, w.display])).toEqual([["Credits", "0.19 / 100"]])
})
// magpie #1904 (CnsMaple): an enterprise account's resource summary has no
// packages, and its credits are the enterprise meter's, which WorkBuddy's
// own usage page reads. The two answers below are the reporter's, byte for