From 486a68a54f7300e230023322bb1deb7d952fc310 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 2 Nov 2026 09:28:24 +0800 Subject: [PATCH] workbuddy 0.2.11: the plan's credits and the gifted ones are two windows, the plan's with its own cycle (akic404) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit akic404 on Discord: "workbuddy 积分总量可否分离套餐内的总量和赠送的总量?… 现在这样那个匀速用量线实际没意义的,因为算上那些已用过的赠送积分,每月第一天就 看起来用了一大半了". usageOf summed CycleTotalCapacity/CycleUsedCapacity over every package of the resource summary into one "Credits" window, so gifted and activity packages' credits used long ago counted against the plan's month; the real China-site free account in usage.test.mjs (CN_FREE_SUMMARY, 2026-10-26) read 282 / 3400 with its 500 plan credits untouched. What tells them apart is the package code. WorkBuddy's client (5.9.x, app.asar, its COMMODITY_CODES and the onlyRefreshCodes / onlyExpireCodes lists its usage panel uses) refreshes proMon, proMonPlus, proYear, youth, advanced, flagship, bonus28, freeMonIntl, proTrialMon, proTrialYear, bonusIntl, and freeMon on the China build only; gift (006), activity (007, 赠送积分), bonus29/30 and the credit packs only lapse. The summary carries PackageCode and SubscriptionPackageCode (no CapacityType or name), so the split is by code: PLAN_CODES, plus the subscription the summary names. - "Credits" is the plan's packages, with cycleOf's reset and span as before, so its pace line is the plan's cycle. "Extra credits" is the rest, used / total. A summary with only one kind (or codes the client names nothing for, as the older fixtures) keeps the one summed "Credits" window, as before. The prepaid balance window is unchanged. - Only one window stops the account, as WorkBuddy serves it while any credits are left: "Extra credits" is aside, until the plan's are spent with extra ones left, then "Credits" is aside. Both spent: the plan's stops it at 100%, as the summed window did. - runsOutOf over every package stays on the window that stops the account (routing reads none set aside, cdredfox's spend-first); the aside window gets runsOutOf over its own packages. So the plan window can say a gifted package's soonest lapse while it is the one routing reads. - Enterprise accounts (no packages, enterprise meter) are unchanged. WorkBuddy AI goes through the same code with site.ai: freeMon (008) is extra there, as its client says. Run on mote at this tree: HOME=$(mktemp -d) bun test (whole repo): 4730 tests, 0 fail, 12 skip; bun scripts/check.mjs: registry.json and workbuddy ok. packages/workbuddy alone: 305 pass. Broken by hand: usage.test.mjs against origin/main's index.mjs: 3 fail (the new two, "282 / 3400" for "0 / 500", and the unreadable-lists test that now expects the split). The gating rule replaced by "extra is always aside": the akic404 test fails. Not tried: a real account. No account here has gifted and plan packages at once with credits used, and akic404's own summary wasn't seen; the split follows the client's code lists, not their bytes. magpie's GUI has no translation for "Extra credits" (it shows in English, as "Prepaid credits" does). --- packages/workbuddy/README.md | 11 +++++ packages/workbuddy/index.mjs | 81 +++++++++++++++++++++++++++---- packages/workbuddy/package.json | 2 +- packages/workbuddy/usage.test.mjs | 67 ++++++++++++++++++++++++- 4 files changed, 149 insertions(+), 12 deletions(-) diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index 8151822..3018764 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -344,6 +344,17 @@ client reads. The daily Free Plan slice isn't counted: it ends at the same midnight on every account. magpie's smart routing spends the account whose credits run out first. +The plan's own credits and the rest are two windows. "Credits" is the +packages whose credits come back each cycle, as WorkBuddy's client lists +them (Pro monthly or yearly, youth, advanced, flagship, the plan's bonus, +the free plan's monthly base, the Pro trials, or the subscription the +summary names), with the plan's cycle, so its pace line is the month's. +"Extra credits" is the packages that only lapse: gifted and activity +credits (赠送积分) and bought credit packs. Only one of the two stops the +account, since WorkBuddy serves it while any credits are left: the extra +window is set aside until the plan's credits are spent. A summary with +only one kind keeps the one "Credits" window (akic404 on Discord). + An enterprise (team) account's resource summary lists no packages. Its credits are read from the enterprise meter (`/billing/meter/get-enterprise-user-usage`), the one WorkBuddy's own usage diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 6e0a459..9f1e30b 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -2776,20 +2776,49 @@ function pinned(rows, account) { // CycleRemainCapacity at all leaves the window out. TotalCredits is not a // fallback: an account with no packages at all keeps its unknown allowance, // as before, so its free models are not skipped. -function usageOf(sum, plan) { +// +// The plan's own credits and the rest are two windows (akic404 on +// Discord): summed, the gifted and activity packages' credits used long +// ago put the card at most of its allowance on the first day of the +// month, and the plan's pace line said nothing. "Credits" is the packages +// whose credits come back each cycle — WorkBuddy's client's own +// onlyRefreshCodes (PLAN_CODES), or the subscription the summary names — +// and "Extra credits" the ones that only lapse (gift, activity, bought +// credit packs, any code the client doesn't list). A summary with only +// one kind keeps the one "Credits" window, as before. +// +// Only one of the two stops the account at a time: WorkBuddy serves it +// while any credits are left, so the one set aside is the one whose +// running out doesn't stop it — "Extra credits", until the plan's are +// spent and extra ones are left. +function usageOf(sum, plan, site) { const out = { plan: plan || (sum?.IsPaidUser ? "Pro" : "Free plan"), windows: [] } - let total = 0, used = 0, left = 0, bags = 0 + const ofPlan = planCodes(sum, site) + const kinds = { plan: { total: 0, used: 0 }, extra: { total: 0, used: 0 } } + let left = 0, bags = 0 for (const p of sum?.Packages ?? []) { const hasTotal = p?.CycleTotalCapacity != null && p.CycleTotalCapacity !== "" if (hasTotal) { - total += capacity(p.CycleTotalCapacity) - used += capacity(p?.CycleUsedCapacity) + const k = kinds[ofPlan(p?.PackageCode) ? "plan" : "extra"] + k.total += capacity(p.CycleTotalCapacity) + k.used += capacity(p?.CycleUsedCapacity) } else if (p?.CycleRemainCapacity != null && p.CycleRemainCapacity !== "") { left += capacity(p.CycleRemainCapacity) bags++ } } - if (total > 0) out.windows.push({ name: "Credits", used: (100 * used) / total, display: `${compact(used)} / ${compact(total)}`, amount: used, limit: total, unit: "credits" }) + 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 })) + } + 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 } @@ -2845,6 +2874,26 @@ const FREE_CODES = [DAILY_CODE, CODE("008", "cfWoLwvjU4"), CODE("035", "ArVxJcGD // lost at the same midnight on every account, so they tell none apart const SLICE = "4" +// PLAN_CODES are the packages whose credits come back each cycle, as +// WorkBuddy's client (5.9.x) lists them (onlyRefreshCodes): Pro monthly, +// Pro monthly plus, Pro yearly, youth, advanced, flagship, the plan's +// bonus (bonus28; bonusIntl, "Plan Bonus Quota"), the international free +// plan (freeMonIntl), the Pro trials, and on the China build alone the +// free plan's monthly base (freeMon, 套餐基础积分). Every other code only +// lapses: gift (006, "Bonus Pack" / Pro trial), activity (007, 赠送积分), +// bonus29/30, and the credit packs (009, 036, 038). +const PLAN_CODES = [CODE("002", "AkiJS3ZHF5"), CODE("005", "maRGyrHhw1"), CODE("003", "FAnt7lcmRT"), CODE("023", "4xbGhMrE6q"), + CODE("026", "BaESVICNoi"), CODE("027", "0FCGVA6vSa"), CODE("028", "NtpWi0jzXs"), CODE("035", "ArVxJcGDsm"), + CODE("039", "KRcQj7wUat"), CODE("040", "mi9rCYg46x"), CODE("037", "WxOD3MpI2o")] +const FREE_MON = CODE("008", "cfWoLwvjU4") + +// 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) { + const sub = sum?.SubscriptionPackageCode + return (code) => !!code && (code === sub || PLAN_CODES.includes(code) || (!site?.ai && code === FREE_MON)) +} + // beijing is WorkBuddy's own time ("2026-10-13 00:39:27" is UTC+8, as its // DeductionEndTime for the same package says). const beijing = (ms) => new Date(ms + 8 * 3600_000).toISOString().slice(0, 19).replace("T", " ") @@ -2887,11 +2936,12 @@ function endOf(p) { // packages are lost, and how many (cdredfox on X): smart routing spends // the account whose credits expire first. Only packages the summary // counts, with credits left, and not the daily slice; null when none. -function runsOutOf(sum, packages, now = Date.now()) { +// only narrows it to the packages of one window (the split's, usageOf). +function runsOutOf(sum, packages, now = Date.now(), only = () => true) { const counted = new Set((sum?.Packages ?? []).map((p) => p?.PackageCode)) let at = 0, amount = 0 for (const p of packages ?? []) { - if (!counted.has(p?.PackageCode) || p?.PackageCode === DAILY_CODE || String(p?.CapacityType) === SLICE) continue + if (!counted.has(p?.PackageCode) || !only(p?.PackageCode) || p?.PackageCode === DAILY_CODE || String(p?.CapacityType) === SLICE) continue const left = capacity(p?.CycleCapacityRemainPrecise ?? p?.CycleCapacityRemain) const end = endOf(p) if (!(left > 0) || end <= now) continue @@ -3626,7 +3676,7 @@ function makePlugin(site) { } said = "renewed" } - const out = usageOf(sum, auth.plan) + const out = usageOf(sum, auth.plan, site) // an enterprise account's summary has no packages: its credits // are the enterprise meter's (#1904). A personal account's // refusal of it (10001 "uid or enterpriseID is empty") leaves @@ -3641,11 +3691,22 @@ function makePlugin(site) { // when the plan's credits start again (cycleOf), and when the credits // left run out, for routing to spend them first (runsOutOf); // a list that can't be read leaves it unknown, the card stands + // + // Split (usageOf), the plan's cycle is the plan window's alone; + // the soonest credits to lapse, of any package, stay on the window + // that stops the account, as routing reads none set aside, and + // the window set aside says its own. const credits = out.windows.find((w) => w.name === "Credits") + const extra = out.windows.find((w) => w.name === "Extra credits") if (credits) { try { const packages = await packagesOf(site, a) - Object.assign(credits, cycleOf(sum, packages) ?? {}, runsOutOf(sum, packages) ?? {}) + Object.assign(credits, cycleOf(sum, packages) ?? {}) + const ofPlan = planCodes(sum, site) + const stops = extra && !extra.aside ? extra : credits + 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)) ?? {}) } catch {} } await spareFree(site, a, out.windows) @@ -3801,4 +3862,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, 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, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } +export const _internal = { planCodes, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, 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, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index c4149c2..eb4ac1e 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.2.10", + "version": "0.2.11", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs", diff --git a/packages/workbuddy/usage.test.mjs b/packages/workbuddy/usage.test.mjs index 1d97411..3fbd88a 100644 --- a/packages/workbuddy/usage.test.mjs +++ b/packages/workbuddy/usage.test.mjs @@ -428,7 +428,72 @@ test("a detail list that can't be read leaves the card as it was", async () => { }) const u = await usageOf(WorkBuddyAIAuthPlugin, { type: "oauth", access: "a", refresh: "r", expires: later(), uid: "u" }) expect(u.error).toBeUndefined() - expect(u.windows[0]).toEqual({ name: "Credits", used: 100 * 17.6 / 2250, display: "17.6 / 2250", amount: 17.6, limit: 2250, unit: "credits" }) + // the plan's (Pro, Plan Bonus) and the Bonus Pack apart, as usageOf says them + expect(u.windows.slice(0, 2)).toEqual([ + { name: "Credits", used: 0, display: "0 / 2000", amount: 0, limit: 2000, unit: "credits" }, + { name: "Extra credits", used: 100 * 17.6 / 250, display: "17.6 / 250", amount: 17.6, limit: 250, unit: "credits", aside: true }, + ]) +}) + +// akic404 on Discord: "workbuddy 积分总量可否分离套餐内的总量和赠送的总量?… +// 算上那些已用过的赠送积分,每月第一天就看起来用了一大半了". The plan's own +// credits are the packages WorkBuddy's client refreshes each cycle (its +// onlyRefreshCodes), the rest only lapse; summed, CN_FREE_SUMMARY read +// 281.99 / 3400 on a month whose plan credits were untouched. +test("the plan's credits and the gifted ones are two windows, the plan's with its own cycle (akic404 on Discord)", () => { + const { SITES } = _internal + // the China build: the activity package (007, 赠送积分) apart from the + // month's plan base (008, 套餐基础积分) + expect(_internal.usageOf(CN_FREE_SUMMARY, "", SITES.workbuddy).windows).toEqual([ + { name: "Credits", used: 0, display: "0 / 500", amount: 0, limit: 500, unit: "credits" }, + { name: "Extra credits", used: (100 * 281.9999965) / 2900, display: "282 / 2900", amount: 281.9999965, limit: 2900, unit: "credits", aside: true }, + ]) + // WorkBuddy AI: Pro and its Plan Bonus are the plan's, the Bonus Pack (006) is not + expect(_internal.usageOf(AI_SUMMARY, "", SITES["workbuddy-ai"]).windows.map((w) => [w.name, w.display, !!w.aside])) + .toEqual([["Credits", "0 / 2000", false], ["Extra credits", "17.6 / 250", true]]) + // a summary of the plan's packages alone keeps the one window, as before + expect(_internal.usageOf(LIVE_SUMMARY, "", SITES["workbuddy-ai"]).windows.map((w) => w.name)).toEqual(["Credits"]) + // and one of packages the client names nothing for (or none at all) too + expect(_internal.usageOf(PAID, "", SITES.workbuddy).windows.map((w) => [w.name, w.display])).toEqual([["Credits", "2500 / 10000"]]) + // the plan's spent with extra ones left: those keep the account going, so + // it is the plan's window that is set aside, not the extra one + const spent = { ...CN_FREE_SUMMARY, Packages: [CN_FREE_SUMMARY.Packages[0], { ...CN_FREE_SUMMARY.Packages[1], CycleRemainCapacity: "0", CycleUsedCapacity: "500" }] } + expect(_internal.usageOf(spent, "", SITES.workbuddy).windows.map((w) => [w.name, !!w.aside])).toEqual([["Credits", true], ["Extra credits", false]]) + // both spent: the plan's stops it, as the summed window did at 100% + const all = { ...spent, Packages: [{ ...spent.Packages[0], CycleUsedCapacity: "2900" }, spent.Packages[1]] } + expect(_internal.usageOf(all, "", SITES.workbuddy).windows.map((w) => [w.name, w.used, !!w.aside])).toEqual([["Credits", 100, false], ["Extra credits", 100, true]]) + // the free plan's monthly base (008) is the plan's on the China build only; + // WorkBuddy AI's client lists it among the packages that only lapse + expect(_internal.planCodes(CN_FREE_SUMMARY, SITES.workbuddy)("TCACA_code_008_cfWoLwvjU4")).toBe(true) + expect(_internal.planCodes(CN_FREE_SUMMARY, SITES["workbuddy-ai"])("TCACA_code_008_cfWoLwvjU4")).toBe(false) + // the subscription the summary names is the plan's, whatever its code + expect(_internal.planCodes({ SubscriptionPackageCode: "NEW_PLAN" }, SITES.workbuddy)("NEW_PLAN")).toBe(true) + expect(_internal.planCodes({ SubscriptionPackageCode: "" }, SITES.workbuddy)("")).toBe(false) +}) + +test("split, the plan's window keeps its cycle and each says what lapses", async () => { + // CN_FREE's lists a year on, so the cycle is still to come + const on = (d) => ({ ...d, Accounts: d.Accounts.map((p) => ({ ...p, DeductionEndTime: p.DeductionEndTime + Date.UTC(2036, 9, 1) - Date.UTC(2026, 9, 1), + CycleStartTime: "2036" + p.CycleStartTime.slice(4), CycleEndTime: "2036" + p.CycleEndTime.slice(4) })) }) + serve({ + "/billing/meter/get-user-resource-summary": () => ok(CN_FREE_SUMMARY), + "/billing/meter/get-user-resource-paid-packages": () => ok({ TotalCount: 0, Accounts: [] }), + "/billing/meter/get-user-resource-free-packages": () => ok(on(CN_FREE)), + }) + const u = await usageOf(WorkBuddyAuthPlugin, { type: "oauth", access: "a", refresh: "r", expires: later(), uid: "u" }) + const [credits, extra] = u.windows + expect(credits.name).toBe("Credits") + expect(credits.display).toBe("0 / 500") + // the plan base's month, so the pace line is the month's + expect(credits.resetsAt).toBe("2036-10-31T15:59:59.000Z") + expect(credits.span).toBe(31 * 86400 - 1) + expect(extra).toMatchObject({ name: "Extra credits", display: "282 / 2900", aside: true, runsOut: 18.4400035 }) + expect(extra.resetsAt).toBeUndefined() + expect(extra.span).toBeUndefined() + // the window that stops the account carries the account's soonest lapse, + // as routing reads no window set aside (cdredfox on X) + expect(credits.runsOut).toBe(18.4400035) + expect(credits.runsOutAt).toBe(extra.runsOutAt) }) // magpie #1904 (CnsMaple): an enterprise account's resource summary has no