Files
plugins/packages/qoder/credits-off.test.mjs
T
yetone e2d15ba653 qoder 0.2.64: a model off for credits used up is a 429 quota (#880); qodercli 1.21.2's single-file runtime on Windows (#879)
#880: on an international personal_professional_trial account whose 800
credits were used up, Qoder's listing had dfmodel off, and ask() answered
its own 400 `unknown or disabled model "dfmodel"`, which magpie reads as
the request's fault: a routing group neither failed over nor rested the
account (yetone/magpie#5726).

- models() records the keys the live listing names and has off (l.off).
- ask(): a known model the listing has off, on an account whose usage
  (/sash/api/v2/me/usage, device token rotated once as usage reads it; a
  PAT account's on its job token) says the pools spent in turn have no
  credits left, is answered 429 "usage limit reached: the account's
  credits are used up (800 / 800 credits), and Qoder lists "dfmodel" off
  for it until they refresh", before any job-token renewal. magpie's
  failure() reads that as failQuota (429 + usage limit, no brokeWords).
- Kept as before: a model off while credits are left, or when the usage
  can't be read (unknown, not quota), goes to the #484 renewal and the
  400; an id Qoder never served is the 400 at once with no usage read.
- usage() reads the envelope through the same usageEnv helper.

#879: qodercli 1.21.2 on Windows caches the helper as
.qoder\.bin\runtime-info-win32-x64-<hash>.exe beside sgsdk.dll, and
campaignRuntime took only the 1.1.66 folder umid-win32-<arch>-<hash>\.
Both are now taken, the newest by mtime; another arch's file and a
non-.exe (a .tmp) are passed over.

Run (mote, load ~900): packages/qoder bun test 424 pass 0 fail; bun
scripts/check.mjs qoder ok.
Broken by hand: the new tests against the old index.mjs: 5 red
(#879's single file found the umid folder instead; #880's 429 was 400;
spentOf missing).
Fixtures: #879 uses the reporter's file names
(runtime-info-win32-x64-faa59bbe39db0bd1.exe, sgsdk.dll). #880's issue
gives the plan, 800 credits used 100% and dfmodel off, but not the
listing's or usage's bytes; their shape is the other qoder tests'.
Not tried: a real out-of-credit Qoder account; Windows itself (the
runtime test forces platform win32 on mote); where Qoder desktop 1.21.2
keeps its helper now that resources\umid is gone (the reporter's second
point; QODER_RUNTIME_INFO still covers it); the repo-wide bun test (mote
at load ~900; only packages/qoder changed).

Reported-by: zane668 (#880)
Reported-by: ArmedHelicopter (#879)
2026-11-09 09:52:58 +08:00

161 lines
8.1 KiB
JavaScript

// plugins#880 (zane668): on an international personal_professional_trial
// account, once the 800 credits were used up the account's listing had
// dfmodel off, and the plugin answered every chat for it with its own
// `400 unknown or disabled model "dfmodel"`, which magpie reads as the
// request's fault: a routing group neither failed over nor rested the
// account (yetone/magpie#5726). Qoder had said `429 usage limit reached`
// at 16:11, the 400 followed from 17:14, and dfmodel answered 200 again
// once the daily credits came back.
//
// A model the live listing names and has off, on an account whose usage
// says no credits are left, is now that account's quota: 429 usage limit
// reached. A model off while credits are left, an id Qoder never served,
// and a usage that can't be read keep the 400.
//
// The issue gives the plan, the 800 credits, used 100%, and dfmodel off; it
// doesn't give the listing's or the usage's bytes, so their shape is the
// one the other tests here use (listing-renew, spare-free). Every fetch is
// a fake; nothing reaches the network.
import { afterEach, beforeEach, expect, test } from "bun:test"
import { constants, createDecipheriv, generateKeyPairSync, privateDecrypt } from "node:crypto"
import { QoderAuthPlugin, _internal } from "./index.mjs"
const real = globalThis.fetch
const site = _internal.SITES.qoder
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 })
beforeEach(() => (site.rsaKey = publicKey.export({ type: "spki", format: "pem" })))
afterEach(() => {
globalThis.fetch = real
delete site.rsaKey
})
const HOUR = 3_600_000
const CHAT = "https://api3.qoder.sh/v1/chat/completions"
const MODELS = ["dfmodel", "qfmodel", "efficient"]
const TRIAL = (used) => ({ displayMode: "qoder", qoderUsage: { userType: "personal_professional_trial", userQuota: { total: 800, used, remaining: 800 - used, unit: "credits" } } })
const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } })
const line = (body) => `data:${JSON.stringify({ headers: {}, body: JSON.stringify(body), statusCodeValue: 200 })}\n\n`
const answered = () =>
new Response(line({ choices: [{ delta: { content: "hello" } }] }) + line({ choices: [{ delta: {}, finish_reason: "stop" }] }) + `data:${JSON.stringify({ headers: {}, body: "[DONE]", statusCodeValue: 200 })}\n\n`, {
headers: { "Content-Type": "text/event-stream" },
})
const chat = (model) => ({ method: "POST", body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }] }) })
function tokenOf(headers) {
const block = privateDecrypt({ key: privateKey, padding: constants.RSA_NO_PADDING }, Buffer.from(headers["Cosy-Key"], "base64"))
const key = block.subarray(block.indexOf(0, 2) + 1)
const [payload] = headers.Authorization.slice("Bearer COSY.".length).split(".")
const { info } = JSON.parse(Buffer.from(payload, "base64").toString())
const d = createDecipheriv("aes-128-cbc", key, key)
return JSON.parse(Buffer.concat([d.update(Buffer.from(info, "base64")), d.final()]).toString()).security_oauth_token
}
// qoder is the fake: state.off is the models the listing has off,
// state.usage the usage reply (a function, or the envelope)
function qoder(state) {
const pairs = new Map([["jrt-1", "jt-1"]])
const honoured = new Set(["jt-1"])
const calls = { refresh: [], usage: 0, chats: [] }
let n = 1
globalThis.fetch = async (url, init = {}) => {
const u = new URL(String(url))
if (u.pathname === "/sash/api/v2/me/usage") {
calls.usage++
return typeof state.usage === "function" ? state.usage() : json(state.usage)
}
if (u.pathname === "/api/v1/jobToken/refresh") {
const rt = JSON.parse(init.body).refresh_token
calls.refresh.push(rt)
if (!pairs.has(rt)) return json({ message: "invalid refresh token" }, 401)
pairs.delete(rt)
n++
honoured.add(`jt-${n}`)
pairs.set(`jrt-${n}`, `jt-${n}`)
return json({ token: `jt-${n}`, refresh_token: `jrt-${n}`, expires_in: 24 * HOUR })
}
const t = tokenOf(init.headers)
if (u.pathname.endsWith("/model/list")) {
return json({ app: MODELS.map((key) => ({ key, display_name: key, enable: !state.off.includes(key) })), byok_teams: [], byok_enterprise: [] })
}
calls.chats.push(t)
return answered()
}
return calls
}
async function account() {
const box = {
stored: { type: "oauth", access: "jt-1", refresh: "jrt-1", expires: Date.now() + 24 * HOUR, accountId: "trial@example.com", uid: "u-trial", email: "trial@example.com", machineId: "m1", deviceToken: "dt-1", deviceRefresh: "drt-1" },
}
const hooks = await QoderAuthPlugin({ client: { auth: { set: async ({ body }) => (box.stored = { ...body }) } } })
const l = await hooks.auth.loader(async () => box.stored)
return { fetch: l.fetch, box }
}
test("plugins#880: dfmodel off with the 800 credits used up is the account's quota, a 429 usage limit, with no token spent", async () => {
const calls = qoder({ off: ["dfmodel"], usage: TRIAL(800) })
const a = await account()
const res = await a.fetch(CHAT, chat("dfmodel"))
expect(res.status).toBe(429)
const message = (await res.json()).error.message
expect(message).toStartWith("usage limit reached: ")
expect(message).toContain("800 / 800 credits")
expect(message).toContain('"dfmodel"')
expect(message).not.toContain("unknown or disabled")
expect(res.headers.get("X-Magpie-Sign-In")).toBeNull()
expect(calls.refresh).toEqual([])
expect(calls.chats).toEqual([])
// the models still on are served
expect((await a.fetch(CHAT, chat("qfmodel"))).status).toBe(200)
})
test("plugins#880: once the daily credits are back and the listing has dfmodel on again, it is served", async () => {
const state = { off: ["dfmodel"], usage: TRIAL(800) }
qoder(state)
const a = await account()
expect((await a.fetch(CHAT, chat("dfmodel"))).status).toBe(429)
state.off = []
state.usage = TRIAL(0)
expect((await a.fetch(CHAT, chat("dfmodel"))).status).toBe(200)
})
test("a model off while credits are left is still said disabled", async () => {
const calls = qoder({ off: ["dfmodel"], usage: TRIAL(200) })
const a = await account()
const res = await a.fetch(CHAT, chat("dfmodel"))
expect(res.status).toBe(400)
expect((await res.json()).error.message).toContain('unknown or disabled model "dfmodel"')
expect(calls.usage).toBe(1)
})
test("an id Qoder never served is said unknown with the credits used up, its usage not read", async () => {
const calls = qoder({ off: ["dfmodel"], usage: TRIAL(800) })
const a = await account()
const res = await a.fetch(CHAT, chat("no-such-model"))
expect(res.status).toBe(400)
expect((await res.json()).error.message).toContain('unknown or disabled model "no-such-model"')
expect(calls.usage).toBe(0)
expect(calls.refresh).toEqual([])
})
test("a usage that can't be read says nothing of the credits: the model off is said disabled", async () => {
qoder({ off: ["dfmodel"], usage: () => new Response("boom", { status: 500 }) })
const a = await account()
const res = await a.fetch(CHAT, chat("dfmodel"))
expect(res.status).toBe(400)
expect((await res.json()).error.message).toContain('unknown or disabled model "dfmodel"')
})
test("spentOf: none left in every pool spent in turn, a free account's pools of 0 too; a pool with some left, or no pool, is not spent", () => {
const { spentOf } = _internal
expect(spentOf(TRIAL(800))).toBe("800 / 800 credits")
expect(spentOf(TRIAL(799))).toBe("")
expect(spentOf({ displayMode: "qoder", qoderUsage: { userQuota: { total: 300, used: 300 }, addOnQuota: { total: 100, used: 40 } } })).toBe("")
expect(spentOf({ displayMode: "qoder", qoderUsage: { userQuota: { total: 300, used: 300 }, add_on_quota: { total: 100, remaining: 0 } } })).toBe("400 / 400 credits")
expect(spentOf({ displayMode: "qoder", qoderUsage: { userType: "personal_standard", userQuota: { total: 0, used: 0, remaining: 0 } } })).toBe("0 / 0 credits")
expect(spentOf({ displayMode: "qoder", qoderUsage: { userType: "personal" } })).toBe("")
expect(spentOf({ displayMode: "enterprise" })).toBe("")
expect(spentOf({ displayMode: "qoder", qoderUsage: { userQuota: { total: 800 } } })).toBe("")
})