Files
plugins/packages/inkstone/usage.test.mjs
T
我是一条没有名字的区 e7004d9354 inkstone 0.1.0: Intern InkStone (书生·端砚) Token Plan, browser sign-in, credit card and ink-* key chat (#775)
New package @magpie-community/opencode-inkstone-auth 0.1.0 for Intern
InkStone (书生·端砚, Shanghai AI Lab) Token Plan, provider id
`intern-inkstone`. Community package by yunwang2442-creator.

What it does:
- Browser sign-in (Edge/Chrome, its own profile under
  $XDG_CONFIG_HOME or ~/.config/magpie/inkstone-browser, or
  %LOCALAPPDATA%\magpie\inkstone-browser). The login window has no
  debugging port. A headless CDP read takes the uaa-token cookie, and the
  same read renews it silently later.
- Usage card: ink-credit balance, 5-hour and 7-day windows, credit packs.
- Chat: a pasted ink-* API key, or one the sign-in creates, named
  ink-<host4>-<acct4>-<rand4> (18 of the console's 20 characters). An
  idempotency clash (-15109) retries with a fresh name, up to three times.
  Pruning is on by default. It only touches this machine's and account's
  prefix, keeps the newest two and the key this sign-in created, and never
  deletes manual keys or keys of unknown age.
- Closing on Unix: SIGTERM, then SIGKILL only after a 15s grace. Leftover
  browsers are matched by --user-data-dir=<escaped profile>, and Windows
  uses .Contains().
- The login wait comes from an injected waitForLogin in tests. No env
  hook is left in production code.
- Hosts: discovery.intern-ai.org.cn, discovery-api.intern-ai.org.cn,
  127.0.0.1 (CDP).

Outside the package: scripts/opencode2.mjs lets a prompt with
`required: false` stay optional (`p.required !== false`). Every package's
copy is synced byte for byte, so all 39 copies in the merged tree are blob
afe074cb. No other package sets `required: false` on a prompt, so this
changes nothing for them. Also a root README row and a registry entry.

Review at 36412a15, on mote, HOME=$(mktemp -d), Bun 1.4.2:
- bun test packages/inkstone: 68 pass, 0 fail in Asia/Shanghai, UTC,
  America/Los_Angeles and Pacific/Kiritimati.
- bun scripts/check.mjs inkstone and bun scripts/check.mjs: ok.
- bun test (repo), on 36412a15 merged with origin/main e7cb9dc5:
  6743 pass, 20 skip, 0 fail. main has since moved by cline 0.1.14 and
  zcode 0.1.55 only, and none of the adapter copies changed.
- Broken by hand, each red: no protectName protection; prune_keys default
  off; no post-sign-in prune; no SIGTERM on close; the -15109 retry keeping
  its name.

Not tried: a real InkStone account sign-in on macOS, Linux or Windows (no
account here); a live chat request; magpie end to end with the plugin.
2026-11-07 15:07:06 +08:00

215 lines
9.3 KiB
JavaScript

// The credit card: the console's balance, windows and credit packs as magpie's
// usage card. Everything runs against the local fake; a read that fails must
// say so rather than show a fake zero. Per-model token spend belongs to the
// usage page, not this card.
import "./nonet.mjs"
import { afterEach, expect, test } from "bun:test"
import { InkStoneAuthPlugin } from "./index.mjs"
import { fakeInkStone, ok, poolUsageFixture, packagesFixture } from "./fake.mjs"
let f
afterEach(() => f?.close())
const auth = { type: "oauth", access: "sk-test", apiKey: "sk-test", uaaToken: "uaa-token" }
async function plugin(options = {}) {
return InkStoneAuthPlugin({ client: { auth: { set: async () => {} } } }, options)
}
function serve({ free = ok({ has_received: true }), validate = ok({ name: "张三", phone: "12345678901" }) } = {}) {
f.route("GET /api/tokenplan/v1/credits/balance", () => ok(poolUsageFixture()))
f.route("GET /api/tokenplan/v1/credits/packages", () => ok(packagesFixture()))
f.route("GET /api/tokenplan/v1/users/validate", () => validate)
f.route("POST /api/tokenplan/v1/users/free-grant", () => free)
}
test("balance, 5h/7d windows and the credit packs become the card", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
const u = await p.auth.usage(async () => auth)
expect(u.plan).toBe("墨点计划 (Token Plan)")
expect(u.user).toBe("123****8901")
expect(u.balance).toBe("10 墨点 · 2 个可用包")
expect(u.signIn).toBe("kept")
const five = u.windows.find((w) => w.name === "5 hours")
expect(five.used).toBeCloseTo(35, 1)
expect(five.display).toBe("3.5 / 10")
expect(five.resetsAt).toBe("2026-11-05T08:00:00.000Z")
const seven = u.windows.find((w) => w.name === "7 days")
expect(seven.used).toBeCloseTo(17.6, 1)
expect(seven.display).toBe("8.8 / 50")
const names = u.windows.map((w) => w.name)
expect(names).toContain("每月免费基础包")
expect(names).toContain("扩容包")
expect(names).toContain("限速")
expect(names).not.toContain("最近到期")
// the expiry day is the viewer's calendar day: derive the expected string
// from the same local parse instead of a fixed UTC date (a fixed date fails
// in far-east zones, where 2026-11-28T12:00Z is already the 29th)
const endDay = (() => {
const d = new Date("2026-11-28T12:00:00Z")
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`
})()
expect(u.windows.find((w) => w.name === "每月免费基础包").display).toBe(`剩 6.5 / 10 · ${endDay} 到期`)
// amount is the used share (10 - 6.5), not the remainder
expect(u.windows.find((w) => w.name === "每月免费基础包").used).toBe(35)
expect(u.windows.find((w) => w.name === "每月免费基础包").amount).toBe(3.5)
expect(u.windows.find((w) => w.name === "每月免费基础包").limit).toBe(10)
expect(u.windows.find((w) => w.name === "每月免费基础包").runsOutAt).toBe("2026-11-28T12:00:00.000Z")
expect(u.windows.find((w) => w.name === "每月免费基础包").runsOut).toBe(6.5)
expect(u.windows.find((w) => w.name === "限速").display).toBe("50 RPM · 2,000,000 TPM")
expect(u.windows.find((w) => w.name === "本月免费额度")).toBeUndefined()
// the card carries no per-model rows: token spend is the usage page's job
expect(names.some((n) => n.startsWith("模型 "))).toBe(false)
expect(names).not.toContain("本月已用")
expect(names).not.toContain("今日 tokens")
// the pack rows never become meters
expect(u.windows.find((w) => w.name === "每月免费基础包").aside).toBe(true)
})
test("a usage read asks only the three credit APIs — no per-model calls", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
await p.auth.usage(async () => auth)
const paths = f.seen.map((r) => r.path)
expect(paths.some((p) => p.endsWith("/models/called"))).toBe(false)
expect(paths.some((p) => p.endsWith("/usage/summary"))).toBe(false)
expect(paths.some((p) => p.endsWith("/credits/transactions"))).toBe(false)
expect(paths.some((p) => p.endsWith("/credits/balance"))).toBe(true)
expect(paths.some((p) => p.endsWith("/credits/packages"))).toBe(true)
})
test("the card is cached briefly: a second read in the same minute asks nothing new", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
await p.auth.usage(async () => auth)
const balanceCalls = f.seen.filter((r) => r.path.endsWith("/credits/balance")).length
await p.auth.usage(async () => auth)
expect(f.seen.filter((r) => r.path.endsWith("/credits/balance")).length).toBe(balanceCalls)
})
test("reading usage never claims free credits; magpie decides with auth.checkin", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
const u = await p.auth.usage(async () => auth)
expect(f.seen.some((r) => r.method === "POST" && r.path.endsWith("/users/free-grant"))).toBe(false)
expect(u.windows.some((w) => w.name === "本月免费额度")).toBe(false)
})
test("auth.checkin claims the monthly grant through magpie's hook", async () => {
f = fakeInkStone()
serve()
const p = await plugin()
const r = await p.auth.checkin(async () => auth)
expect(r).toEqual({ outcome: "done" })
expect(f.seen.filter((r) => r.method === "POST" && r.path.endsWith("/users/free-grant")).length).toBe(1)
})
test("auth.checkin says the account can't take part when the phone is missing", async () => {
f = fakeInkStone()
serve({
free: new Response(JSON.stringify({ code: -15900, msg: "PhoneRequired", data: null }), {
status: 200,
headers: { "content-type": "application/json" },
}),
})
const p = await plugin()
const r = await p.auth.checkin(async () => auth)
expect(r.outcome).toBe("ineligible")
})
test("a console 401 for auth.checkin is a plain failure: the host's checkin path reads no signIn", async () => {
f = fakeInkStone()
// keep_sign_in off: the 401 path must not launch a browser in the test
const p = await plugin({ keep_sign_in: false })
f.route("POST /api/tokenplan/v1/users/free-grant", () => new Response("", { status: 401 }))
const r = await p.auth.checkin(async () => auth)
expect(r).toEqual({ outcome: "failed", message: expect.stringContaining("401") })
})
test("no console token: the card says how to get one, and models stay usable", async () => {
f = fakeInkStone()
const p = await plugin()
const u = await p.auth.usage(async () => ({ type: "api", key: "sk-test" }))
expect(u.error).toContain("ink credits")
expect(u.windows).toEqual([])
expect(u.signIn).toBe("kept")
})
test("a console 401 is an error, not an empty balance, and does not sign the account out", async () => {
f = fakeInkStone()
f.route("GET /api/tokenplan/v1/credits/balance", () => new Response("", { status: 401 }))
// keep_sign_in off: the 401 path must not launch a browser in the test
const p = await plugin({ keep_sign_in: false })
const u = await p.auth.usage(async () => auth)
expect(u.error).toContain("console session expired")
expect(u.signIn).toBe("kept")
})
test("a console 403 is reported as a disabled account, not as a broken balance", async () => {
f = fakeInkStone()
f.route("GET /api/tokenplan/v1/credits/balance", () => new Response("", { status: 403 }))
const p = await plugin({ keep_sign_in: false })
const u = await p.auth.usage(async () => auth)
expect(u.error).toBe("TokenPlan account disabled in the console")
expect(u.signIn).toBe("kept")
expect(u.balance).toBeUndefined()
})
test("a balance read that fails for another reason keeps the reason and no fake zero", async () => {
f = fakeInkStone()
f.route("GET /api/tokenplan/v1/credits/balance", () => new Response("", { status: 503 }))
const p = await plugin()
const u = await p.auth.usage(async () => auth)
expect(u.error).toContain("credit balance")
expect(u.balance).toBeUndefined()
expect(u.signIn).toBe("kept")
})
test("a zero balance is shown as 0 credits, never hidden or treated as a read failure", async () => {
f = fakeInkStone()
serve()
f.route("GET /api/tokenplan/v1/credits/balance", () =>
ok({
available_credits: 0,
active_package_count: 0,
usage_windows: {
"5h": { enabled: true, limit_credits: 10, remaining_credits: 0 },
},
}),
)
f.route("GET /api/tokenplan/v1/credits/packages", () => ok({ total: 0, packages: [] }))
const p = await plugin()
const u = await p.auth.usage(async () => auth)
expect(u.balance).toBe("0 墨点")
expect(u.error).toBeUndefined()
})
test("a phone number missing before free credits is reported by auth.checkin", async () => {
f = fakeInkStone()
serve({ validate: ok({ name: "张三", phone: "" }) })
f.route("POST /api/tokenplan/v1/users/free-grant", () =>
new Response(JSON.stringify({ code: -15900, msg: "PhoneRequired", data: null }), {
status: 200,
headers: { "content-type": "application/json" },
}),
)
const p = await plugin()
const u = await p.auth.usage(async () => auth)
// 插件不再自动 claim,也不会因手机号缺失污染卡片;该状态由宿主的 checkin 处理。
expect(u.error).toBeUndefined()
expect(u.windows.some((w) => w.name === "本月免费额度")).toBe(false)
const r = await p.auth.checkin(async () => auth)
expect(r).toEqual({
outcome: "ineligible",
message: "Bind a phone number in the InkStone console to claim free credits.",
})
})