workbuddy 0.1.2: usage shows as magpie's built-in did — plan, period, windows and what they count, balanceworkbuddy

This commit is contained in:
yetone
2026-09-30 23:03:10 +08:00
parent 4dd783a2c0
commit 8c419105c0
3 changed files with 201 additions and 1 deletions
+74
View File
@@ -342,6 +342,65 @@ async function current(site, client, auth) {
return a
}
// ---- allowance ----------------------------------------------------------------
// STATUS_TEXT is Go's http.StatusText for the answers WorkBuddy gives.
const STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed",
408: "Request Timeout", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable",
504: "Gateway Timeout" }
// meter asks the billing API as magpie's built-in did, its errors said
// the same: WorkBuddy's message, else its code, else the HTTP status.
async function meter(site, a, path) {
const res = await fetch(site.endpoint + path, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "WorkBuddy/" + UA_VERSION,
Authorization: "Bearer " + a.access, "X-User-Id": a.uid ?? "", "X-Domain": domainOf(site, a), "X-Product": "SaaS",
"X-IDE-Type": "WorkBuddy" },
body: "{}",
signal: AbortSignal.timeout(20000),
})
let env = {}
try {
env = JSON.parse(await res.text()) ?? {}
} catch {}
const code = Number.parseInt(env.code, 10) || 0
if (!res.ok) {
if (code) throw new Error(env.msg || `error ${code}`)
if (env.msg) throw new Error(env.msg)
throw new Error(STATUS_TEXT[res.status] ?? "")
}
if (code) throw new Error(env.msg || `error ${code}`)
return env.data ?? null
}
// capacity is a capacity the billing API sends, as a string ("438.88")
// or now and then a number; empty is 0.
function capacity(v) {
if (v == null || v === "") return 0
if (typeof v === "number") return v
const s = String(v)
const n = Number(s)
if (s.trim() !== s || Number.isNaN(n)) throw new Error(`strconv.ParseFloat: parsing ${JSON.stringify(s)}: invalid syntax`)
return n
}
// compact is a count as magpie says one: whole, else to two places.
const compact = (n) => (Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/0+$/, "").replace(/\.$/, ""))
// usageOf is the account's credits, from its resource summary: the plan's
// credits used against what the cycle grants, as magpie's built-in said.
function usageOf(sum, plan) {
const out = { plan: plan || (sum?.IsPaidUser ? "Pro" : "Free"), windows: [] }
let total = 0, used = 0
for (const p of sum?.Packages ?? []) {
total += capacity(p?.CycleTotalCapacity)
used += capacity(p?.CycleUsedCapacity)
}
if (total > 0) out.windows.push({ name: "Credits", used: (100 * used) / total, display: `${compact(used)} / ${compact(total)}` })
return out
}
// ---- models -----------------------------------------------------------------
// variants are the reasoning levels as OpenCode gives them to the AI SDK.
@@ -484,6 +543,18 @@ function makePlugin(site) {
},
}
},
// the account's credits, as magpie's built-in showed them
async usage(getAuth) {
const auth = await getAuth()
if (auth?.type !== "oauth" || !(auth.access || auth.source)) return { error: "not signed in" }
try {
const a = await current(site, client, auth)
// the meter has no /v2 prefix, on either site
return usageOf(await meter(site, a, "/billing/meter/get-user-resource-summary"), auth.plan)
} catch (e) {
return { error: e?.message ?? String(e) }
}
},
methods: [
{
type: "oauth",
@@ -502,3 +573,6 @@ function makePlugin(site) {
export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
// for tests
export const _internal = { usageOf, desktopHeld }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-workbuddy-auth",
"version": "0.1.1",
"version": "0.1.2",
"description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
"type": "module",
"main": "./index.mjs",
+126
View File
@@ -0,0 +1,126 @@
// auth.usage tells what magpie's built-in WorkBuddy usage told for the same
// answers (internal/provider/workbuddy_test.go, workbuddy_ai_test.go).
import { test, expect, beforeAll, afterEach } from "bun:test"
import { mkdirSync, writeFileSync, readFileSync } from "node:fs"
import { homedir, tmpdir } from "node:os"
import { realpathSync } from "node:fs"
import { join } from "node:path"
let WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal, home
beforeAll(async () => {
// Bun reads HOME once, at start: run as HOME=$(mktemp -d) bun test, so
// no real sign-in is ever read
if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test")
home = homedir()
;({ WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } = await import("./index.mjs"))
})
// nothing leaves the machine
const offline = async () => { throw new Error("no network in tests") }
globalThis.fetch = offline
afterEach(() => {
globalThis.fetch = offline
_internal.desktopHeld.clear()
})
const later = () => Date.now() + 3600_000
const ok = (data) => new Response(JSON.stringify({ code: 0, msg: "ok", data }))
// the summary as the live API sends it: capacities as strings, some fractional
const PAID = { IsPaidUser: true, Packages: [
{ PackageCode: "coding", CycleTotalCapacity: "9500", CycleRemainCapacity: "7500", CycleUsedCapacity: "2000" },
{ PackageCode: "vibe", CycleTotalCapacity: "500", CycleRemainCapacity: "0", CycleUsedCapacity: "500.00000000" },
] }
function serve(routes) {
const calls = []
globalThis.fetch = async (url, init) => {
const u = new URL(String(url))
calls.push({ url: u, init, headers: new Headers(init?.headers) })
const r = routes[u.pathname]
return r ? r(init) : new Response("", { status: 404 })
}
return calls
}
const usageOf = async (plugin, auth, client = {}) => (await plugin({ client })).auth.usage(async () => auth)
test("a paid WorkBuddy account's credits", async () => {
const calls = serve({ "/billing/meter/get-user-resource-summary": () => ok(PAID) })
const auth = { type: "oauth", access: "two-access", refresh: "r", expires: later(), uid: "u2", domain: "" }
expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ plan: "Pro", windows: [{ name: "Credits", used: 25, display: "2500 / 10000" }] })
const c = calls[0]
expect(c.url.origin).toBe("https://copilot.tencent.com")
expect(c.init.method).toBe("POST")
expect(c.init.body).toBe("{}")
expect(Object.fromEntries(["authorization", "x-user-id", "x-domain", "x-product", "x-ide-type", "user-agent"].map((h) => [h, c.headers.get(h)])))
.toEqual({ authorization: "Bearer two-access", "x-user-id": "u2", "x-domain": "copilot.tencent.com", "x-product": "SaaS",
"x-ide-type": "WorkBuddy", "user-agent": "WorkBuddy/5.5.6" })
})
test("a free WorkBuddy AI account, at its own site and domain", async () => {
const calls = serve({ "/billing/meter/get-user-resource-summary": () =>
ok({ IsPaidUser: false, Packages: [{ CycleTotalCapacity: "1000", CycleUsedCapacity: "100" }] }) })
const auth = { type: "oauth", access: "ai-access", expires: later(), uid: "ai2", domain: "www.codebuddy.ai" }
expect(await usageOf(WorkBuddyAIAuthPlugin, auth)).toEqual({ plan: "Free", windows: [{ name: "Credits", used: 10, display: "100 / 1000" }] })
expect(calls[0].url.origin).toBe("https://www.workbuddy.ai")
expect(calls[0].headers.get("x-domain")).toBe("www.codebuddy.ai")
})
test("counts and plans as Go says them", () => {
expect(_internal.usageOf({ IsPaidUser: true, Packages: [{ CycleTotalCapacity: 3300, CycleUsedCapacity: "438.88000002" }, {}] }, "Team"))
.toEqual({ plan: "Team", windows: [{ name: "Credits", used: (100 * 438.88000002) / 3300, display: "438.88 / 3300" }] })
// no capacity, no window
expect(_internal.usageOf({ IsPaidUser: false, Packages: [{ CycleTotalCapacity: "", CycleUsedCapacity: null }] }, ""))
.toEqual({ plan: "Free", windows: [] })
expect(() => _internal.usageOf({ Packages: [{ CycleTotalCapacity: "lots" }] })).toThrow('strconv.ParseFloat: parsing "lots": invalid syntax')
})
test("WorkBuddy's refusals are the card's error", async () => {
const auth = { type: "oauth", access: "a", expires: later(), uid: "u" }
serve({ "/billing/meter/get-user-resource-summary": () => new Response("", { status: 401 }) })
expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ error: "Unauthorized" })
serve({ "/billing/meter/get-user-resource-summary": () => new Response(JSON.stringify({ code: 10085, msg: "" }), { status: 403 }) })
expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ error: "error 10085" })
serve({ "/billing/meter/get-user-resource-summary": () => new Response(JSON.stringify({ code: 11001, msg: "token expired" })) })
expect(await usageOf(WorkBuddyAuthPlugin, auth)).toEqual({ error: "token expired" })
expect(await usageOf(WorkBuddyAuthPlugin, null)).toEqual({ error: "not signed in" })
})
test("a token near its end is renewed and saved, as the loader does", async () => {
const sets = []
const calls = serve({
"/v2/plugin/auth/token/refresh": () => ok({ accessToken: "new-access", refreshToken: "new-refresh", expiresIn: 3600 }),
"/billing/meter/get-user-resource-summary": () => ok(PAID),
})
const auth = { type: "oauth", access: "old-access", refresh: "old-refresh", expires: Date.now() + 1000, uid: "u2" }
const out = await usageOf(WorkBuddyAuthPlugin, auth, { auth: { set: async (x) => sets.push(x) } })
expect(out.windows[0].used).toBe(25)
expect(calls[0].headers.get("x-refresh-token")).toBe("old-refresh")
expect(calls[1].headers.get("authorization")).toBe("Bearer new-access")
expect(sets.length).toBe(1)
expect(sets[0].path).toEqual({ id: "workbuddy" })
expect(sets[0].body).toMatchObject({ access: "new-access", refresh: "new-refresh", uid: "u2" })
})
test("the desktop's sign-in is renewed in memory only", async () => {
const dir = process.platform === "darwin" ? join(home, "Library", "Application Support", "CodeBuddyExtension")
: process.platform === "win32" ? join(home, "AppData", "Local", "CodeBuddyExtension") : join(home, ".local", "share", "CodeBuddyExtension")
mkdirSync(join(dir, "Data", "Public", "auth"), { recursive: true })
const file = join(dir, "Data", "Public", "auth", "workbuddy-desktop.info")
const info = JSON.stringify({ auth: { accessToken: "desk-old", refreshToken: "desk-refresh", expiresAt: Date.now() + 1000, domain: "www.codebuddy.cn" },
account: { uid: "u1", nickname: "旅行者" } })
writeFileSync(file, info)
const sets = []
const calls = serve({
"/v2/plugin/auth/token/refresh": () => ok({ accessToken: "desk-new", expiresIn: 3600 }),
"/billing/meter/get-user-resource-summary": () => ok(PAID),
})
const auth = { type: "oauth", access: "", refresh: "", expires: 0, source: "desktop", uid: "u1" }
const client = { auth: { set: async (x) => sets.push(x) } }
expect(await usageOf(WorkBuddyAuthPlugin, auth, client)).toEqual({ plan: "Pro", windows: [{ name: "Credits", used: 25, display: "2500 / 10000" }] })
expect(calls[1].headers.get("authorization")).toBe("Bearer desk-new")
expect(calls[1].headers.get("x-domain")).toBe("www.codebuddy.cn")
expect(sets).toEqual([]) // never saved,
expect(readFileSync(file, "utf8")).toBe(info) // nor written where the app keeps it
// and held: the next ask doesn't renew again
await usageOf(WorkBuddyAuthPlugin, auth, client)
expect(calls.filter((c) => c.url.pathname.endsWith("/refresh")).length).toBe(1)
})