Files
plugins/packages/workbuddy/freeonly.test.mjs
T
yetone 18268848d3 workbuddy 0.1.38: a "Free models only" switch that never spends credits (#430)
kongbai01203 asked for a hard stop on WorkBuddy credits: use only the free
models, and never let a paid one through by mistake.

Each site (workbuddy, workbuddy-ai) now declares a magpie plugin option,
free_only, "Free models only", off by default. With it on:
- models() lists only the models priced free now (priceOf: a model free only
  at night, or one with no price, is paid). A list that can't be read, or an
  API key WorkBuddy lists no prices for, is a failure, not the built-in list.
- fetch reads the model from the body and, unless /v3/config lists it as
  free, answers 404 model_not_found itself and sends nothing. The message
  has no quota words, so magpie's gateway rests that model only and falls
  through, not the account. A price list that can't be read answers 503 and
  sends nothing. The list is kept a minute per account for requests.
Off, nothing changes: the config isn't read on a request.

Run:
- HOME=$(mktemp -d) bun test packages/workbuddy: 179 pass (freeonly.test.mjs
  new, both sites); bun scripts/check.mjs: ok.
- Real accounts, sandbox magpie (HOME under the scratchpad, magpie
  wb-free-only branch, this package added by path): with the switch on for
  workbuddy-ai the list went 26 -> 2 (hy3, deepseek-v4.1-flash) within 2s,
  workbuddy (own switch) stayed at 19; gpt-5.4 got the 404 with nothing
  sent, hy3 and deepseek-v4.1-flash answered. Off: 26 again, gpt-6-luna and
  gpt-5.4 answered (no rest left on gpt-5.4).
Broken by hand: without the fetch check 4 tests fail; with onlyFree
returning every model 2 fail.
Not tried: the GUI switch itself (set through /api/settings/plugin-option);
the workbuddy (China) site's switch with a real request; Responses or
Anthropic bodies against the real API (the model is read the same way).
2026-10-27 17:26:51 +08:00

130 lines
6.3 KiB
JavaScript

// plugins#430 (kongbai01203): "Free models only" is a hard stop on credits.
// With it on, the list holds only the models WorkBuddy serves at no cost,
// and a request for any other is answered here and never reaches WorkBuddy;
// so is one whose price can't be read. Every fetch here is a fake; nothing
// reaches the network.
import { afterEach, expect, test } from "bun:test"
import { WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } from "./index.mjs"
const real = globalThis.fetch
afterEach(() => (globalThis.fetch = real))
const KEY = "ck_test0000000000abcdefgh"
const CONFIG = {
code: 0,
data: {
agents: [{ name: "cli", models: ["hy3", "glm-5.3", "hy4-preview", "auto", "claude-sonnet-5"] }],
models: [
{ id: "hy3", credits: "x0.00" },
{ id: "glm-5.3", credits: "x0.79" },
// free only at night: paid here (#121)
{ id: "hy4-preview", credits: "x0.29" },
// no price said: not free
{ id: "auto" },
{ id: "claude-sonnet-5", credits: "x1.00" },
],
modelPromotions: [
{ discount: { discountedCredits: "0.00x", factor: 0 }, enabled: true, kind: "discount", modelIds: ["hy4-preview"], schedule: { daily: [{ start: "23:00", end: "23:59" }] } },
],
},
}
// serve answers /v3/config with config (or fails it) and a chat with OK,
// and keeps every URL asked
function serve(config = () => Response.json(CONFIG)) {
const sent = []
globalThis.fetch = async (url, init) => {
const u = String(url)
sent.push({ url: u, body: init?.body })
if (u.endsWith("/v3/config")) return config()
return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } })
}
return sent
}
const chat = (opts, url, model) =>
opts.fetch(url, { method: "POST", body: JSON.stringify({ model, stream: true, messages: [{ role: "user", content: "hi" }] }) })
const magpieWith = (on) => ({ option: (provider, key) => on[provider]?.[key] === true })
for (const [plugin, site, url] of [
[WorkBuddyAuthPlugin, "workbuddy", "https://copilot.tencent.com/v2/chat/completions"],
[WorkBuddyAIAuthPlugin, "workbuddy-ai", "https://www.workbuddy.ai/v2/chat/completions"],
]) {
test(`${site}: declares the switch, off by default`, async () => {
const h = await plugin({ client: {} })
const o = h.auth.options.find((x) => x.key === _internal.FREE_ONLY)
expect(o.label).toBe("Free models only")
expect(o.default).toBeUndefined()
})
test(`${site}: on, the list holds only the free models; off, all of them`, async () => {
serve()
const auth = { type: "api", key: KEY }
const on = await plugin({ client: {}, magpie: magpieWith({ [site]: { free_only: true } }) })
const cfg = { provider: {} }
await on.config(cfg)
expect(Object.keys(await on.provider.models(cfg.provider[site], { auth }))).toEqual(["hy3"])
const off = await plugin({ client: {}, magpie: magpieWith({}) })
expect(Object.keys(await off.provider.models(cfg.provider[site], { auth }))).toEqual(["hy3", "glm-5.3", "hy4-preview", "auto", "claude-sonnet-5"])
// the other site's switch is its own
const other = site === "workbuddy" ? "workbuddy-ai" : "workbuddy"
const theirs = await plugin({ client: {}, magpie: magpieWith({ [other]: { free_only: true } }) })
expect(Object.keys(await theirs.provider.models(cfg.provider[site], { auth }))).toHaveLength(5)
})
test(`${site}: on, a list that can't be read is a failure, not the built-in list`, async () => {
serve(() => new Response("down", { status: 502 }))
const h = await plugin({ client: {}, magpie: magpieWith({ [site]: { free_only: true } }) })
const cfg = { provider: {} }
await h.config(cfg)
await expect(h.provider.models(cfg.provider[site], { auth: { type: "api", key: KEY } })).rejects.toThrow()
// a key WorkBuddy lists no prices for, too
await expect(h.provider.models(cfg.provider[site], { auth: { type: "api", key: "sk-other" } })).rejects.toThrow(/Free models only/)
// off, the built-in list as before
const off = await plugin({ client: {} })
expect(Object.keys(await off.provider.models(cfg.provider[site], { auth: { type: "api", key: KEY } })).length).toBeGreaterThan(0)
})
test(`${site}: on, a paid or unpriced model's request never reaches WorkBuddy`, async () => {
const sent = serve()
const h = await plugin({ client: {}, magpie: magpieWith({ [site]: { free_only: true } }) })
const opts = await h.auth.loader(async () => ({ type: "api", key: KEY }))
for (const model of ["glm-5.3", "hy4-preview", "auto", "claude-sonnet-5", "not-listed", undefined]) {
const res = await chat(opts, url, model)
expect(res.status).toBe(404)
const e = (await res.json()).error
expect(e.code).toBe("model_not_found")
expect(e.message).toContain("Free models only")
// magpie's gateway rests the model, not the account, for these words
expect(e.message).toMatch(/model.{0,80}not available/i)
expect(e.message).not.toMatch(/quota|insufficient|balance|credit|billing|exceeded|limit/i)
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
}
expect(sent.filter((s) => !s.url.endsWith("/v3/config"))).toHaveLength(0)
// the free one goes, and the list was read once for all of them
const res = await chat(opts, url, "hy3")
expect(res.status).toBe(200)
expect(sent.filter((s) => s.url === url)).toHaveLength(1)
expect(sent.filter((s) => s.url.endsWith("/v3/config"))).toHaveLength(1)
})
test(`${site}: on, a price that can't be read sends nothing`, async () => {
const sent = serve(() => new Response("down", { status: 502 }))
const h = await plugin({ client: {}, magpie: magpieWith({ [site]: { free_only: true } }) })
const opts = await h.auth.loader(async () => ({ type: "api", key: KEY }))
const res = await chat(opts, url, "hy3")
expect(res.status).toBe(503)
expect((await res.json()).error.message).toContain("is unknown")
expect(sent.filter((s) => s.url === url)).toHaveLength(0)
})
test(`${site}: off, a paid model's request goes as before, the list not read`, async () => {
const sent = serve()
const h = await plugin({ client: {}, magpie: magpieWith({}) })
const opts = await h.auth.loader(async () => ({ type: "api", key: KEY }))
expect((await chat(opts, url, "glm-5.3")).status).toBe(200)
expect(sent.map((s) => s.url)).toEqual([url])
})
}