Files
plugins/packages/opendesign/index.test.mjs
T
Bernardxu123 6549b6335d opendesign 0.1.9: the plan's own credit multipliers, and V4.1 Flash Eco (#794)
A model's rate is now the Design Plan's own deduction multiplier from
open-design.ai/zh/model-credits/ (rates.mjs), not amr-link's catalog cost
word, which disagreed for seven models (Claude Haiku 5.5 2x, GPT-6 Luna 4x,
DeepSeek V4 Pro 1x, ...). A model the table doesn't name keeps its catalog
word. deepseek-v4.1-flash-eco joins the seed with V4.1 Flash's limits and
levels at 0.27x.

Reviewed at 0335afb86a9afb53a576813445c0b6cb4705cfeb:
- rates.mjs checked row by row against the vendor page, fetched 2026-11-06;
  the 0.25x row is the 10-20..10-27 promo, over.
- mote, HOME=$(mktemp -d), Bun 1.4.2: bun test packages/opendesign 27 pass;
  bun scripts/check.mjs opendesign ok; npm pack has rates.mjs and the packed
  plugin imports.
- Broken by hand: rateOf ignoring the table (2 red), config hook not
  re-declaring rate (1 red), eco seed line removed (3 red).
- magpie's host builds config models without rate and never writes a hook's
  result back, so the re-declared rate overrides nothing a user set.
- npm had 0.1.8; 0.1.9 is next.
Not tried: a real Open Design account; the live ids of hy4-preview and
minimax-m3.1-flash (not in the seed).
2026-11-06 20:18:20 +08:00

453 lines
20 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { test, expect, mock, afterEach } from "bun:test"
import {
_internal as I,
OpenDesignAuthPlugin,
} from "./index.mjs"
import { MODELS } from "./models.mjs"
import { RATES } from "./rates.mjs"
// bun test runs every package's files in one process: a fetch left
// stubbed here answers every test file after this one
const realFetch = globalThis.fetch
afterEach(() => {
mock.restore()
globalThis.fetch = realFetch
})
// ---- the sign-in it keeps ----------------------------------------------------
test("authOf keeps both keys and the account they belong to", () => {
expect(I.authOf({ id: "u1", email: "ada@example.com" }, { controlKey: "vela_ctrl_a", runtimeKey: "sk-amr-b" }))
.toEqual({ type: "success", refresh: "", expires: 0, access: "sk-amr-b", control: "vela_ctrl_a", accountId: "ada@example.com", email: "ada@example.com", uid: "u1" })
})
test("authOf is nothing without both keys", () => {
expect(I.authOf({}, { runtimeKey: "sk-amr-b" })).toBe(null)
expect(I.authOf({}, { controlKey: "vela_ctrl_a" })).toBe(null)
expect(I.authOf(null, {})).toBe(null)
})
test("a control key is not taken as a runtime key", () => {
expect(I.runtimeKeyOf({ key: "vela_ctrl_a" })).toBe("")
expect(I.runtimeKeyOf({ access: "sk-amr-b" })).toBe("sk-amr-b")
expect(I.controlKeyOf({ key: "vela_ctrl_a" })).toBe("vela_ctrl_a")
expect(I.controlKeyOf({ metadata: { control: "vela_ctrl_c" } })).toBe("vela_ctrl_c")
expect(I.controlKeyOf({ access: "sk-amr-b" })).toBe("")
})
test("the poll takes the approval's keys, and says so when the code runs out", async () => {
const calls = []
globalThis.fetch = async (url, init) => {
calls.push(String(url))
const n = calls.length
const body = n < 2
? { status: "pending", controlKey: null, runtimeKey: null, user: null }
: { status: "approved", controlKey: "vela_ctrl_a", runtimeKey: "sk-amr-b", user: { id: "u1", email: "ada@example.com" } }
return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } })
}
const got = await I.waitForDevice({ deviceId: "d1", deviceSecret: "s1", interval: 0, until: Date.now() + 5000 }, { sleep: async () => {} })
expect(got).toMatchObject({ access: "sk-amr-b", control: "vela_ctrl_a", accountId: "ada@example.com", uid: "u1" })
expect(calls[0]).toBe("https://amr-api.open-design.ai/api/v1/cli/device-authorizations/d1/token")
globalThis.fetch = async () => new Response(JSON.stringify({ status: "expired" }), { status: 200 })
await expect(I.waitForDevice({ deviceId: "d2", deviceSecret: "s2", interval: 0, until: Date.now() + 5000 }, { sleep: async () => {} }))
.rejects.toThrow(/expired/)
globalThis.fetch = async () => new Response(JSON.stringify({ error: "invalid_device_secret" }), { status: 401 })
await expect(I.waitForDevice({ deviceId: "d3", deviceSecret: "s3", interval: 0, until: Date.now() + 5000 }, { sleep: async () => {} }))
.rejects.toThrow(/no longer valid/)
})
// ---- what the dashboard shows ------------------------------------------------
// one reading of /workspaces/{id}/billing/preflight, as the control plane
// answers it
const PREFLIGHT = {
balanceUsd: "1.5000",
funding: "wallet",
codingPlan: {
eligible: true,
tier: "go",
// out of order on purpose: the plugin's own sort is what puts the 5-hour
// window first, as the vendor's card shows them
windows: [
{ durationSeconds: 604800, usedCredits: "16251", limitCredits: "150000", resetsAt: "2026-10-18T06:36:14.000Z" },
{ durationSeconds: 18000, usedCredits: "16251", limitCredits: "50000", resetsAt: "2026-10-11T11:36:14.000Z" },
],
},
}
test("the plan's windows become magpie's, shortest first", () => {
expect(I.allowances(PREFLIGHT.codingPlan)).toEqual([
{ name: "5 hours", used: 32.5, span: 18000, resetsAt: "2026-10-11T11:36:14.000Z", display: "16.3k / 50k credits" },
{ name: "7 days", used: 10.8, span: 604800, resetsAt: "2026-10-18T06:36:14.000Z", display: "16.3k / 150k credits" },
])
})
test("a window with nothing to divide is left out", () => {
expect(I.allowances({ windows: [{ durationSeconds: 18000, usedCredits: "3", limitCredits: "0" }] })).toEqual([])
expect(I.allowances(null)).toEqual([])
})
test("window names follow the vendor's own card", () => {
expect(I.windowName(18000)).toBe("5 hours")
expect(I.windowName(604800)).toBe("7 days")
expect(I.windowName(3600)).toBe("1 hour")
expect(I.windowName(86400)).toBe("1 day")
expect(I.windowName(900)).toBe("15 minutes")
expect(I.windowName(0)).toBe("Allowance")
})
test("credits are shown short", () => {
expect(I.credits("16251")).toBe("16.3k")
expect(I.credits("9999")).toBe("9999")
expect(I.credits("477")).toBe("477")
expect(I.credits("150000")).toBe("150k")
expect(I.credits("2340000")).toBe("2.3M")
expect(I.credits(undefined)).toBe("")
})
test("the plan reads as the dashboard names it", () => {
expect(I.thePlan({ membershipTier: "go" }, "")).toBe("Design Plan Go")
expect(I.thePlan(null, "pro")).toBe("Design Plan Pro")
expect(I.thePlan(null, "")).toBe("Open Design")
})
test("the wallet shows as dollars", () => {
expect(I.money("1.5000")).toBe("$1.50")
expect(I.money(undefined)).toBe("")
})
// ---- the account's models ----------------------------------------------------
// one reading of amr-link's /v1/models
const CATALOG = {
data: [
{
id: "gpt-6-luna",
architecture: { input_modalities: ["text", "image", "file"], output_modalities: ["text"] },
metadata: { cost: "low", capability: "standard", context_limit: 1050000, context_budget: 304000 },
},
{
id: "deepseek-v4-pro",
architecture: { input_modalities: ["text"], output_modalities: ["text"] },
metadata: { cost: "high", capability: "advanced", context_limit: 1048000, context_budget: 232000 },
},
{ id: "brand-new-9", architecture: { input_modalities: ["text", "image"] }, metadata: { cost: "medium", capability: "advanced" } },
],
}
// what magpie's plugin host reads off a model provider.models gives back
// (internal/plugin/host.js, providers()): its thinking from
// capabilities.reasoning, its levels from the variants' names
const asMagpieReads = (m) => ({
reasoning: !!m.capabilities?.reasoning,
variants: Object.keys(m.variants ?? {}),
image: !!m.capabilities?.input?.image,
})
test("the account's list is the vendor's own, live", () => {
const models = I.modelsOf(CATALOG)
expect(Object.keys(models)).toEqual(["gpt-6-luna", "deepseek-v4-pro", "brand-new-9"])
expect(models["gpt-6-luna"]).toEqual({
id: "gpt-6-luna",
name: "GPT-6 Luna",
api: { id: "gpt-6-luna", url: "https://amr-link.open-design.ai/v1", npm: "@ai-sdk/openai-compatible" },
status: "active",
headers: {},
options: {},
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
limit: { context: 1050000, output: 304000 },
capabilities: {
temperature: true,
reasoning: false,
attachment: true,
toolcall: true,
input: { text: true, image: true, audio: false, video: false, pdf: false },
output: { text: true, image: false, audio: false, video: false, pdf: false },
interleaved: false,
},
release_date: "",
variants: {},
rate: "x4",
})
expect(models["deepseek-v4-pro"]).toMatchObject({ rate: "x1", limit: { context: 1048000, output: 232000 } })
// a model the seed doesn't know is named by its id, and a catalog entry
// without limits still gets a workable entry
expect(models["brand-new-9"]).toMatchObject({
id: "brand-new-9",
name: "brand-new-9",
rate: "x1",
limit: { context: 200000, output: 32000 },
})
})
// #137 (sryimnoob123): amr-link took reasoning_effort low and high (max too,
// plugins#141) on all 11
// models, and every one but GPT-6 Luna thought at it, "standard" or not
test("a signed-in account's models reason at the levels amr-link took (#137)", () => {
const models = I.modelsOf(CATALOG)
expect(asMagpieReads(models["deepseek-v4-pro"])).toEqual({ reasoning: true, variants: ["low", "high", "max"], image: false })
expect(models["deepseek-v4-pro"].variants).toEqual({ low: { reasoningEffort: "low" }, high: { reasoningEffort: "high" }, max: { reasoningEffort: "max" } })
// took the level and never thought at it
expect(asMagpieReads(models["gpt-6-luna"])).toEqual({ reasoning: false, variants: [], image: true })
// "advanced" but never measured: it reasons, at no level said for it
expect(asMagpieReads(models["brand-new-9"])).toEqual({ reasoning: true, variants: [], image: true })
// the catalog calls these "standard"; they thought at both levels
const standard = I.modelsOf({
data: ["claude-haiku-5.5", "deepseek-v4-flash", "deepseek-v4-flash-vision-exp", "mimo-v2.6-flash"].map((id) => ({ id, metadata: { capability: "standard" } })),
})
for (const m of Object.values(standard)) expect(asMagpieReads(m)).toMatchObject({ reasoning: true, variants: ["low", "high", "max"] })
})
test("the seed's models carry the measured levels as the config's variants", async () => {
const hooks = await OpenDesignAuthPlugin({})
const cfg = {}
await hooks.config(cfg)
const models = cfg.provider.opendesign.models
const levels = Object.fromEntries(Object.entries(models).map(([id, m]) => [id, m.reasoning ? Object.keys(m.variants ?? {}) : null]))
expect(levels).toEqual({
"claude-haiku-5.5": ["low", "high", "max"],
"deepseek-v4-flash": ["low", "high", "max"],
"deepseek-v4-flash-vision-exp": ["low", "high", "max"],
"deepseek-v4-pro": ["low", "high", "max"],
"deepseek-v4.1-flash": ["low", "high", "max"],
"deepseek-v4.1-flash-eco": ["low", "high", "max"],
"glm-5.3-flash": ["low", "high", "max"],
"glm-5.3-flashx": ["low", "high", "max"],
"gpt-6-luna": null,
"kimi-k2.7-code": ["low", "high", "max"],
"mimo-v2.6-flash": ["low", "high", "max"],
"mimo-v2.6-pro": ["low", "high", "max"],
})
expect(models["claude-haiku-5.5"].variants.high).toEqual({ reasoningEffort: "high" })
})
test("the seed gives the eco schedule the model V4.1 Flash is", () => {
const { "deepseek-v4.1-flash": flash, "deepseek-v4.1-flash-eco": eco } = MODELS
expect(eco).toEqual({ ...flash, name: "DeepSeek V4.1 Flash Eco" })
expect(Object.keys(MODELS)).toContain("deepseek-v4.1-flash-eco")
})
// the plan's deduction multipliers, "额度扣除倍率", published at
// https://open-design.ai/zh/model-credits/ (read 2026-11-06)
test("the plan's multipliers are the vendor's own table, not the catalog's cost words", () => {
expect(RATES).toEqual({
"claude-haiku-5.5": 2,
"deepseek-v4-flash": 1,
"deepseek-v4-flash-vision-exp": 1,
"deepseek-v4-pro": 1,
"deepseek-v4.1-flash": 0.5,
"deepseek-v4.1-flash-eco": 0.27,
"glm-5.3-flash": 1,
"glm-5.3-flashx": 2,
"gpt-6-luna": 4,
"hy4-preview": 1,
"kimi-k2.7-code": 1,
"mimo-v2.6-flash": 1,
"mimo-v2.6-pro": 1,
"minimax-m3.1-flash": 1,
})
// each seed model is rated by the table; a model it doesn't name keeps the
// catalog's word (brand-new-9 below, and any model the vendor adds later)
const WORD = {
"claude-haiku-5.5": ["low", "x2"],
"gpt-6-luna": ["low", "x4"],
"glm-5.3-flash": ["low", "x1"],
"glm-5.3-flashx": ["medium", "x2"],
"deepseek-v4-pro": ["high", "x1"],
"deepseek-v4.1-flash": ["low", "x0.5"],
"deepseek-v4.1-flash-eco": ["low", "x0.27"],
"brand-new-9": ["high", "x2"],
}
const models = I.modelsOf({ data: Object.entries(WORD).map(([id, [cost]]) => ({ id, metadata: { cost } })) })
for (const [id, [, rate]] of Object.entries(WORD)) expect([id, models[id].rate]).toEqual([id, rate])
})
test("a kept model's rate is re-declared, so a charge an earlier version wrote can't linger", async () => {
const kept = {
provider: {
opendesign: {
models: {
"gpt-6-luna": { id: "gpt-6-luna", name: "GPT-6 Luna", rate: "x0.5" },
"brand-new-9": { id: "brand-new-9", name: "brand-new-9", rate: "x1" },
},
},
},
}
await (await OpenDesignAuthPlugin({})).config(kept)
const models = kept.provider.opendesign.models
expect(models["gpt-6-luna"].rate).toBe("x4")
// a kept name is still kept
expect(models["gpt-6-luna"].name).toBe("GPT-6 Luna")
// a model the table doesn't name keeps the rate it had
expect(models["brand-new-9"].rate).toBe("x1")
})
test("an empty catalog is no models", () => {
expect(I.modelsOf({ data: [] })).toEqual({})
expect(I.modelsOf(null)).toEqual({})
})
test("each model is asked on the API amr-link thinks on (plugins#141)", async () => {
expect(I.modelsOf(CATALOG)["deepseek-v4-pro"].api.npm).toBe("@ai-sdk/openai")
expect(I.modelsOf(CATALOG)["gpt-6-luna"].api.npm).toBe("@ai-sdk/openai-compatible")
// a model kept from 0.1.5, which put every model on the Responses API,
// is moved to its own wire
const kept = { "glm-5.3-flash": { id: "glm-5.3-flash", name: "GLM", provider: { npm: "@ai-sdk/openai" }, api: { npm: "@ai-sdk/openai" } } }
const cfg = { provider: { opendesign: { npm: "@ai-sdk/openai", models: kept } } }
await (await OpenDesignAuthPlugin({})).config(cfg)
const p = cfg.provider.opendesign
expect(p.npm).toBe("@ai-sdk/openai-compatible")
expect(p.models["glm-5.3-flash"].provider.npm).toBe("@ai-sdk/anthropic")
expect(p.models["glm-5.3-flash"].api.npm).toBe("@ai-sdk/anthropic")
expect(p.models["glm-5.3-flash"].name).toBe("GLM")
expect(p.models["claude-haiku-5.5"].provider.npm).toBe("@ai-sdk/openai")
expect(p.models["kimi-k2.7-code"].provider.npm).toBe("@ai-sdk/openai-compatible")
})
// ---- what magpie is given ----------------------------------------------------
test("the plugin declares the provider and answers its methods", async () => {
const hooks = await OpenDesignAuthPlugin({})
const cfg = {}
await hooks.config(cfg)
expect(cfg.provider.opendesign).toMatchObject({
name: "Open Design",
npm: "@ai-sdk/openai-compatible",
api: "https://amr-link.open-design.ai/v1",
})
// the seed models.mjs carries, which a signed-in account's list replaces
expect(Object.keys(cfg.provider.opendesign.models)).toHaveLength(12)
expect(cfg.provider.opendesign.models["deepseek-v4.1-flash"]).toEqual({
id: "deepseek-v4.1-flash",
name: "DeepSeek V4.1 Flash",
api: { npm: "@ai-sdk/openai-compatible" },
provider: { npm: "@ai-sdk/openai-compatible" },
attachment: true,
tool_call: true,
reasoning: true,
variants: { low: { reasoningEffort: "low" }, high: { reasoningEffort: "high" }, max: { reasoningEffort: "max" } },
rate: "x0.5",
limit: { context: 1048000, output: 232000 },
modalities: { input: ["text", "image"], output: ["text"] },
})
// the eco schedule is the same model: same limits, same levels, its own 0.27×
expect(cfg.provider.opendesign.models["deepseek-v4.1-flash-eco"]).toEqual({
...cfg.provider.opendesign.models["deepseek-v4.1-flash"],
id: "deepseek-v4.1-flash-eco",
name: "DeepSeek V4.1 Flash Eco",
rate: "x0.27",
})
expect(hooks.auth.provider).toBe("opendesign")
expect(hooks.auth.methods.map((m) => m.type)).toEqual(["oauth", "api"])
expect(hooks.provider.id).toBe("opendesign")
})
test("the loader hands the runtime key to the model plane", async () => {
const hooks = await OpenDesignAuthPlugin({})
expect(await hooks.auth.loader(async () => ({ access: "sk-amr-b", control: "vela_ctrl_a" })))
.toEqual({ baseURL: "https://amr-link.open-design.ai/v1", apiKey: "sk-amr-b" })
expect(await hooks.auth.loader(async () => null)).toEqual({})
})
test("the account's models are read at its own key", async () => {
const hooks = await OpenDesignAuthPlugin({})
const seen = []
globalThis.fetch = async (url, init) => {
seen.push([String(url), new Headers(init.headers).get("authorization")])
return new Response(JSON.stringify(CATALOG), { status: 200, headers: { "content-type": "application/json" } })
}
const given = { models: {} }
const models = await hooks.provider.models(given, { auth: { access: "sk-amr-b", control: "vela_ctrl_a" } })
expect(seen).toEqual([["https://amr-link.open-design.ai/v1/models", "Bearer sk-amr-b"]])
expect(Object.keys(models)).toEqual(["gpt-6-luna", "deepseek-v4-pro", "brand-new-9"])
// a vendor that refuses the key marks the account
globalThis.fetch = async () => new Response(JSON.stringify({ error: { message: "invalid_api_key" } }), { status: 401 })
await expect(hooks.provider.models(given, { auth: { access: "sk-amr-b" } })).rejects.toThrow(/invalid_api_key/)
// a vendor hiccup keeps the list magpie had
globalThis.fetch = async () => new Response("{}", { status: 500 })
expect(await hooks.provider.models(given, { auth: { access: "sk-amr-b" } })).toBe(given.models)
// nothing signed in: the list it was given
expect(await hooks.provider.models(given, { auth: null })).toBe(given.models)
})
test("usage reads the plan, the wallet and the windows at the control key", async () => {
const hooks = await OpenDesignAuthPlugin({})
const seen = []
globalThis.fetch = async (url, init) => {
const u = String(url)
seen.push([u, new Headers(init.headers).get("authorization")])
if (u.endsWith("/api/v1/workspaces/current")) return new Response(JSON.stringify({ activeWorkspaceId: "ws1", personalMembershipTier: "go" }), { status: 200 })
if (u.includes("/billing/preflight")) return new Response(JSON.stringify(PREFLIGHT), { status: 200 })
if (u.includes("/billing/summary")) {
return new Response(JSON.stringify({
membershipTier: "go",
subscriptionStatus: "active",
subscriptionCancelAtPeriodEnd: false,
subscriptionCurrentPeriodEnd: "2026-11-11T06:36:14.000Z",
balanceUsd: "1.5000",
}), { status: 200 })
}
return new Response("{}", { status: 404 })
}
const auth = { access: "sk-amr-b", control: "vela_ctrl_a", email: "ada@example.com" }
expect(await hooks.auth.usage(async () => auth)).toEqual({
plan: "Design Plan Go",
user: "ada@example.com",
balance: "$1.50",
until: "2026-11-11T06:36:14.000Z",
renew: "auto",
windows: [
{ name: "5 hours", used: 32.5, span: 18000, resetsAt: "2026-10-11T11:36:14.000Z", display: "16.3k / 50k credits" },
{ name: "7 days", used: 10.8, span: 604800, resetsAt: "2026-10-18T06:36:14.000Z", display: "16.3k / 150k credits" },
],
signIn: "kept",
})
expect(seen.every(([, key]) => key === "Bearer vela_ctrl_a")).toBe(true)
})
test("usage says a refused sign-in marks the account, and that an API key has none", async () => {
const hooks = await OpenDesignAuthPlugin({})
globalThis.fetch = async (url) => (String(url).endsWith("/workspaces/current")
? new Response(JSON.stringify({ activeWorkspaceId: "ws1" }), { status: 200 })
: new Response(JSON.stringify({ error: "unauthenticated" }), { status: 401 }))
expect(await hooks.auth.usage(async () => ({ access: "sk-amr-b", control: "vela_ctrl_a" })))
.toMatchObject({ signIn: "expired", windows: [] })
expect(await hooks.auth.usage(async () => ({ access: "sk-amr-b" })))
.toMatchObject({ signIn: "kept", windows: [], error: expect.stringMatching(/API key/) })
})
test("the API key method takes the key as it is", async () => {
const hooks = await OpenDesignAuthPlugin({})
const m = hooks.auth.methods.find((x) => x.type === "api")
expect(m.type).toBe("api")
// magpie's own prompt saves what the user pasted; the plugin adds nothing
expect(m.authorize).toBeUndefined()
})
test("everything the manifest ships is on disk", async () => {
// `files` naming a file that isn't there ships a package missing it, which
// is how 0.1.2 went out without refresh-models.mjs. The manifest is found
// by walking up, so this file works in `test/` and at a package root alike.
const { existsSync } = await import("node:fs")
const { dirname, join } = await import("node:path")
const { fileURLToPath } = await import("node:url")
let root = dirname(fileURLToPath(import.meta.url))
while (!existsSync(join(root, "package.json"))) {
const up = dirname(root)
if (up === root) throw new Error("no package.json above this test")
root = up
}
const pkg = await Bun.file(join(root, "package.json")).json()
for (const f of pkg.files) expect(existsSync(join(root, f))).toBe(true)
// the plugin's own imports are among them (npm ships package.json itself,
// whatever `files` says)
const src = await Bun.file(join(root, pkg.main ?? "index.mjs")).text()
const imports = [...src.matchAll(/from "\.\/([^"]+)"/g)].map((m) => m[1]).filter((f) => f !== "package.json")
expect(imports.length).toBeGreaterThan(0)
for (const spec of imports) expect(pkg.files).toContain(spec)
})